lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
apache-2.0
70bab7592051da1bb6d7fb6f0b9a48d0eeb0411a
0
FHannes/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,caot/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,signed/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,caot/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,semonte/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,holmes/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,ernestp/consulo,alphafoobar/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,izonder/intellij-community,consulo/consulo,Distrotech/intellij-community,jexp/idea2,retomerz/intellij-community,izonder/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,kool79/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,ernestp/consulo,mglukhikh/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,xfournet/intellij-community,caot/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,signed/intellij-community,hurricup/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,kool79/intellij-community,FHannes/intellij-community,semonte/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,samthor/intellij-community,suncycheng/intellij-community,da1z/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,semonte/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,samthor/intellij-community,signed/intellij-community,jagguli/intellij-community,signed/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,samthor/intellij-community,kdwink/intellij-community,semonte/intellij-community,gnuhub/intellij-community,joewalnes/idea-community,robovm/robovm-studio,muntasirsyed/intellij-community,semonte/intellij-community,allotria/intellij-community,wreckJ/intellij-community,slisson/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,ryano144/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,joewalnes/idea-community,ibinti/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,fnouama/intellij-community,holmes/intellij-community,kdwink/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,da1z/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,ernestp/consulo,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,da1z/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,xfournet/intellij-community,ernestp/consulo,ivan-fedorov/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,xfournet/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,vladmm/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,fitermay/intellij-community,fitermay/intellij-community,supersven/intellij-community,nicolargo/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,amith01994/intellij-community,retomerz/intellij-community,consulo/consulo,mglukhikh/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,jexp/idea2,robovm/robovm-studio,jexp/idea2,muntasirsyed/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,dslomov/intellij-community,retomerz/intellij-community,allotria/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,samthor/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,clumsy/intellij-community,da1z/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,joewalnes/idea-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,allotria/intellij-community,adedayo/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,kool79/intellij-community,ryano144/intellij-community,blademainer/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,consulo/consulo,hurricup/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,signed/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,clumsy/intellij-community,asedunov/intellij-community,fnouama/intellij-community,ryano144/intellij-community,slisson/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,da1z/intellij-community,tmpgit/intellij-community,xfournet/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,slisson/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,allotria/intellij-community,holmes/intellij-community,fitermay/intellij-community,kdwink/intellij-community,izonder/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,supersven/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,izonder/intellij-community,consulo/consulo,semonte/intellij-community,caot/intellij-community,blademainer/intellij-community,vladmm/intellij-community,ryano144/intellij-community,ibinti/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,blademainer/intellij-community,blademainer/intellij-community,semonte/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,signed/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,signed/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,semonte/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,vladmm/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,slisson/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,semonte/intellij-community,izonder/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,dslomov/intellij-community,amith01994/intellij-community,supersven/intellij-community,joewalnes/idea-community,allotria/intellij-community,ahb0327/intellij-community,kool79/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,xfournet/intellij-community,adedayo/intellij-community,asedunov/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,FHannes/intellij-community,amith01994/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,fnouama/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,fnouama/intellij-community,fnouama/intellij-community,asedunov/intellij-community,jexp/idea2,diorcety/intellij-community,clumsy/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,jexp/idea2,supersven/intellij-community,Distrotech/intellij-community,semonte/intellij-community,jexp/idea2,kool79/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,allotria/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,joewalnes/idea-community,allotria/intellij-community,petteyg/intellij-community,retomerz/intellij-community,asedunov/intellij-community,joewalnes/idea-community,ftomassetti/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,SerCeMan/intellij-community,caot/intellij-community,blademainer/intellij-community,FHannes/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,robovm/robovm-studio,ibinti/intellij-community,holmes/intellij-community,jexp/idea2,hurricup/intellij-community,asedunov/intellij-community,slisson/intellij-community,Lekanich/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,supersven/intellij-community,fitermay/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,ol-loginov/intellij-community,vladmm/intellij-community,caot/intellij-community,ernestp/consulo,fnouama/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,da1z/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,retomerz/intellij-community,caot/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,diorcety/intellij-community,amith01994/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,consulo/consulo,ivan-fedorov/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,ernestp/consulo,caot/intellij-community,fitermay/intellij-community,hurricup/intellij-community,joewalnes/idea-community,joewalnes/idea-community,SerCeMan/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,ibinti/intellij-community,clumsy/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,fitermay/intellij-community,kdwink/intellij-community,da1z/intellij-community,supersven/intellij-community,vvv1559/intellij-community,jexp/idea2,salguarnieri/intellij-community,ibinti/intellij-community,kdwink/intellij-community,retomerz/intellij-community,semonte/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,izonder/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,caot/intellij-community,supersven/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,clumsy/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,FHannes/intellij-community,fitermay/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,retomerz/intellij-community,signed/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,signed/intellij-community,kool79/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,adedayo/intellij-community,dslomov/intellij-community,da1z/intellij-community,hurricup/intellij-community,joewalnes/idea-community,idea4bsd/idea4bsd,tmpgit/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,consulo/consulo,fitermay/intellij-community,retomerz/intellij-community,adedayo/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,da1z/intellij-community,tmpgit/intellij-community,signed/intellij-community,petteyg/intellij-community,jagguli/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,ibinti/intellij-community,caot/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,petteyg/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,izonder/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,blademainer/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,robovm/robovm-studio,apixandru/intellij-community,samthor/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,allotria/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,ryano144/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,holmes/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,izonder/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community
/* * Copyright (c) 2005 Your Corporation. All Rights Reserved. */ package com.intellij.util.xml.ui; import com.intellij.util.xml.DomElement; import javax.swing.*; /** * @author peter * * @see DomUIFactory */ public interface DomUIControl extends CommittablePanel { DomElement getDomElement(); void bind(JComponent component); void addCommitListener(CommitListener listener); void removeCommitListener(CommitListener listener); boolean canNavigate(DomElement element); void navigate(DomElement element); }
openapi/src/com/intellij/util/xml/ui/DomUIControl.java
/* * Copyright (c) 2005 Your Corporation. All Rights Reserved. */ package com.intellij.util.xml.ui; import com.intellij.util.xml.DomElement; import javax.swing.*; /** * @author peter */ public interface DomUIControl extends CommittablePanel { DomElement getDomElement(); void bind(JComponent component); void addCommitListener(CommitListener listener); void removeCommitListener(CommitListener listener); boolean canNavigate(DomElement element); void navigate(DomElement element); }
property table & struts model changes
openapi/src/com/intellij/util/xml/ui/DomUIControl.java
property table & struts model changes
<ide><path>penapi/src/com/intellij/util/xml/ui/DomUIControl.java <ide> <ide> /** <ide> * @author peter <add> * <add> * @see DomUIFactory <ide> */ <ide> public interface DomUIControl extends CommittablePanel { <ide>
Java
mit
c52156c04aedfdc846c9e42660e570a359a7813a
0
baumato/lines-of-code,baumato/lines-of-code
package de.baumato.loc; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.Collection; import java.util.stream.Stream; import de.baumato.loc.configuration.Configuration; import de.baumato.loc.messages.Messages; import de.baumato.loc.printer.ConsolePrinter; public class LineCounter { private final Configuration conf; private final ConsolePrinter printer; public LineCounter(Configuration conf, ConsolePrinter printer) { this.conf = conf; this.printer = printer; } public long count() { printer.step(Messages.FILE.get() + ";" + Messages.COUNT.get()); long sum = countLinesInDir(conf.getDirectory(), conf.getExcludeDirs()); printer.step(Messages.SUM.get() + ";" + sum); return sum; } private long countLinesInDir(Path dir, Collection<String> excludeDirs) { try (Stream<Path> paths = Files.walk(dir)) { long sum = paths.filter(p -> p.getFileName().toString().endsWith(".java")) .filter(p -> !pathContainsOneOfDirs(p, excludeDirs)) .mapToLong(p -> countLinesInFile(p)) .sum(); return sum; } catch (IOException e) { throw new UncheckedIOException(e); } } private static boolean pathContainsOneOfDirs(Path p, Collection<String> excludeDirs) { for (int i = 0; i < p.getNameCount(); i++) { if (excludeDirs.contains(p.getName(i).toString())) { return true; } } return false; } private long countLinesInFile(Path p) { long count = countLinesInFile0(p); printer.step(p.toString() + ";" + count); return count; } private static long countLinesInFile0(Path p) { /* * We cannot use Files.lines because that uses BufferedReader with the default charset and this results * to java.nio.charset.MalformedInputException when a file has not the default charset. We can use new * Scanner(p) but the scanner is slower than using BufferedReader like below. */ try (BufferedReader reader = new BufferedReader( new InputStreamReader(Files.newInputStream(p, StandardOpenOption.READ)))) { int count = 0; while (reader.readLine() != null) { count++; } return count; } catch (IOException e) { throw new UncheckedIOException(e); } } }
src/main/java/de/baumato/loc/LineCounter.java
package de.baumato.loc; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.Collection; import java.util.stream.Stream; import de.baumato.loc.configuration.Configuration; import de.baumato.loc.messages.Messages; import de.baumato.loc.printer.ConsolePrinter; public class LineCounter { private final Configuration conf; private final ConsolePrinter printer; public LineCounter(Configuration conf, ConsolePrinter printer) { this.conf = conf; this.printer = printer; } public long count() { printer.step(Messages.FILE.get() + ";" + Messages.COUNT.get()); long sum = countLinesInDir(conf.getDirectory(), conf.getExcludeDirs()); printer.step(Messages.SUM.get() + ";" + sum); return sum; } private long countLinesInDir(Path dir, Collection<String> excludeDirs) { try (Stream<Path> paths = Files.walk(dir)) { long sum = paths.filter(p -> p.getFileName().toString().endsWith(".java")) .filter(p -> !pathContainsOneOfDirs(p, excludeDirs)) .mapToLong(p -> countLinesInFile(p)) .sum(); return sum; } catch (IOException e) { throw new UncheckedIOException(e); } } private static boolean pathContainsOneOfDirs(Path p, Collection<String> excludeDirs) { for (int i = 0; i < p.getNameCount(); i++) { if (excludeDirs.contains(p.getName(i).toString())) { return true; } } return false; } private long countLinesInFile(Path p) { long count = countLinesInFile3(p); printer.step(p.toString() + ";" + count); return count; } private static long countLinesInFile3(Path p) { /* * We cannot use Files.lines because that uses BufferedReader with the default charset and this results * to java.nio.charset.MalformedInputException when a file has not the default charset. We can use new * Scanner(p) but the scanner is slower than using BufferedReader like below. */ try (BufferedReader reader = new BufferedReader( new InputStreamReader(Files.newInputStream(p, StandardOpenOption.READ)))) { int count = 0; while (reader.readLine() != null) { count++; } return count; } catch (IOException e) { throw new UncheckedIOException(e); } } }
rename method
src/main/java/de/baumato/loc/LineCounter.java
rename method
<ide><path>rc/main/java/de/baumato/loc/LineCounter.java <ide> } <ide> <ide> private long countLinesInFile(Path p) { <del> long count = countLinesInFile3(p); <add> long count = countLinesInFile0(p); <ide> printer.step(p.toString() + ";" + count); <ide> return count; <ide> } <ide> <del> private static long countLinesInFile3(Path p) { <add> private static long countLinesInFile0(Path p) { <ide> /* <ide> * We cannot use Files.lines because that uses BufferedReader with the default charset and this results <ide> * to java.nio.charset.MalformedInputException when a file has not the default charset. We can use new
Java
mit
13700ecb2b64590870df6473d3a934bd0733aeb4
0
MCTCP/TerrainControl,whichonespink44/TerrainControl,PG85/OpenTerrainGenerator,Ezoteric/TerrainControl,LinkBR/TerrainControl
package com.khorn.terraincontrol.configuration; import com.khorn.terraincontrol.DefaultBiome; import com.khorn.terraincontrol.LocalBiome; import com.khorn.terraincontrol.LocalWorld; import com.khorn.terraincontrol.TerrainControl; import java.io.DataInputStream; import java.io.File; import java.io.IOException; import java.util.*; import java.util.Map.Entry; import java.util.logging.Level; /** * */ public final class BiomeConfigManager { /* * */ private final File worldBiomesDir; /* * */ private final File globalBiomesDir; /* * */ private final File worldDefaultBiomesDir; /* * */ private byte[] ReplaceMatrixBiomes = new byte[256]; /* * */ private LocalWorld world; /* * */ private WorldConfig worldConfig; /* * */ private boolean checkOnly; /* * A running list of biomes that have been processed during the loading */ private String LoadedBiomeNames = ""; /* * Must be simple array for fast access. Beware! Some ids may contain null * values; */ private BiomeConfig[] biomeConfigs; /* * Overall biome count in this world. */ private int biomesCount; /** * * @param settingsDir * @param world * @param wConfig * @param customBiomes * @param checkOnly */ public BiomeConfigManager(File settingsDir, LocalWorld world, WorldConfig wConfig, Map<String, Integer> customBiomes, boolean checkOnly) { this.world = world; this.worldConfig = wConfig; this.checkOnly = checkOnly; // Check biome ids, These are the names from the worldConfig file //>> Corrects any instances of incorrect biome id. for (String biomeName : customBiomes.keySet()) if (customBiomes.get(biomeName) == -1) customBiomes.put(biomeName, world.getFreeBiomeId()); //>> TerrainControl/GlobalBiomes this.globalBiomesDir = new File(TerrainControl.getEngine().getTCDataFolder(), TCDefaultValues.GlobalBiomeConfigDirectoryName.stringValue()); //>> TerrainControl/worlds/<WorldName>/WorldBiomes this.worldBiomesDir = new File(settingsDir, correctOldBiomeConfigFolder(settingsDir)); //>> TerrainControl/worlds/<WorldName>/BiomeConfigs/Defaults this.worldDefaultBiomesDir = new File(this.worldBiomesDir, TCDefaultValues.WorldDefaultBiomeConfigDirectoryName.stringValue()); //>> If there was an error in folder establishment if (!makeBiomeFolders()) return; // Build biome replace matrix for (int i = 0; i < this.ReplaceMatrixBiomes.length; i++) this.ReplaceMatrixBiomes[i] = (byte) i; //>> Init the biomeConfigs Array biomeConfigs = new BiomeConfig[world.getMaxBiomesCount()]; //>> Set variable for biomeCount, MIGHT NOT NEED biomesCount = 0; //>> This arrayList now contains all biomes listed in `DefaultBiome` populateDefaultBiomeConfigs(new ArrayList<LocalBiome>(world.getDefaultBiomes())); ArrayList<LocalBiome> localBiomes = new ArrayList<LocalBiome>(customBiomes.size()); //>> This adds all custombiomes that have been listed in WorldConfig to the arrayList for (Iterator<Entry<String, Integer>> it = customBiomes.entrySet().iterator(); it.hasNext();) { Entry<String, Integer> entry = it.next(); if (checkOnly) localBiomes.add(world.getNullBiome(entry.getKey())); else localBiomes.add(world.AddBiome(entry.getKey(), entry.getValue())); } populateCustomBiomeConfigs(localBiomes, worldBiomesDir); for (int i = 0; i < biomeConfigs.length; i++) { BiomeConfig bc = biomeConfigs[i]; if (bc != null) { TerrainControl.log(Level.INFO, "Loaded ({0}:{1}) biome", new Object[] { bc.name, i }); } } processBiomeConfigs(); TerrainControl.log(Level.INFO, "Loaded {0} biomes", new Object[] { biomesCount }); TerrainControl.logIfLevel(Level.ALL, Level.CONFIG, LoadedBiomeNames); } private boolean makeBiomeFolders() { boolean allFoldersExist = true; //>> Create the folders if not present if (!globalBiomesDir.exists()) if (!globalBiomesDir.mkdir()) { TerrainControl.log(Level.WARNING, "Error creating Global directory."); allFoldersExist = false; } if (!worldBiomesDir.exists()) if (!worldBiomesDir.mkdir()) { TerrainControl.log(Level.WARNING, "Error creating World Biome configs directory."); allFoldersExist = false; } if (!worldDefaultBiomesDir.exists()) if (!worldDefaultBiomesDir.mkdir()) { TerrainControl.log(Level.WARNING, "Error creating World Default Biome configs directory."); allFoldersExist = false; } if (!allFoldersExist) { TerrainControl.log(Level.WARNING, "Potentially working with defaults."); } return allFoldersExist; } private String correctOldBiomeConfigFolder(File settingsDir) { //>> Rename the old folder String biomeFolderName = TCDefaultValues.WorldBiomeConfigDirectoryName.stringValue(); File oldBiomeConfigs = new File(settingsDir, "BiomeConfigs"); if (oldBiomeConfigs.exists()) { if (!oldBiomeConfigs.renameTo(new File(settingsDir, biomeFolderName))) { TerrainControl.log(Level.WARNING, "========================"); TerrainControl.log(Level.WARNING, "Fould old `BiomeConfigs` folder, but it could not be renamed to `", biomeFolderName, "`!"); TerrainControl.log(Level.WARNING, "Please rename the folder manually."); TerrainControl.log(Level.WARNING, "========================"); biomeFolderName = "BiomeConfigs"; } } return biomeFolderName; } private void populateDefaultBiomeConfigs(ArrayList<LocalBiome> biomesToLoad) { for (LocalBiome localBiome : biomesToLoad) { //>> Upon loading a biome, check the worldDefault location first. BiomeConfig config = new BiomeConfig(worldDefaultBiomesDir, localBiome, this.worldConfig); if (!config.readSuccess) { //>> If a config doesnt exist at that location try the usual BiomeConfigs folder config = new BiomeConfig(worldBiomesDir, localBiome, this.worldConfig); } if (!config.readSuccess) { //>> and if all else fails look in the globalBiomes folder //>> if the biome does not exist here, one will be created config = new BiomeConfig(globalBiomesDir, localBiome, this.worldConfig); } TerrainControl.log(Level.FINER, config.file.getAbsolutePath()); pushBiomeConfig(localBiome, config); } } private void populateCustomBiomeConfigs(ArrayList<LocalBiome> biomesToLoad, File biomeFolder) { for (LocalBiome localBiome : biomesToLoad) { BiomeConfig config = new BiomeConfig(biomeFolder, localBiome, this.worldConfig); pushBiomeConfig(localBiome, config); } } private void pushBiomeConfig(LocalBiome localBiome, BiomeConfig config) { if (biomesCount != 0) LoadedBiomeNames += ", "; LoadedBiomeNames += localBiome.getName(); // Add biome to the biome array if (biomeConfigs[localBiome.getId()] == null) { // Only if it won't overwrite another biome in the array biomesCount++; } else { TerrainControl.log(Level.WARNING, "Duplicate biome id {0} ({1} and {2})!", new Object[] { localBiome.getId(), biomeConfigs[localBiome.getId()].name, config.name }); } biomeConfigs[localBiome.getId()] = config; } private void processBiomeConfigs() { /** ********************* * Proposed Algorithm *********************** * - Grab the settingsCache value for BiomeExtends check * - Get the id of the biome to be extended and find it in * biomeConfigs check * - determine if need to extend what we found check * ---- decend until we find a non-extending biome check * - merge the two biomeConfig's needs fix * ---- special treatment for resources * - save results by overwritting approp. config check * - make sure we dont process already processed configs check * - ascend until no more extending can be done check * - Rinse / Repeat until done extending all biome configs check */ int xbiome = 0; autosarcophagousBiomes = ""; TerrainControl.log(Level.INFO, "=============== Biome Processing START ==============="); for (BiomeConfig config : biomeConfigs) { if (config == null) { xbiome++; continue; } TerrainControl.log(Level.CONFIG, "Biome attempting to load: " + config.name + ":" + xbiome++); if (!config.BiomeExtendsProcessed) { TerrainControl.log(Level.CONFIG, "======== Inheritance Starting ========"); populateInhertianceStack(config); BiomeConfig parent = biomeLoadingStack.pop(); while (!biomeLoadingStack.isEmpty()) { BiomeConfig child = biomeLoadingStack.pop(); TerrainControl.log(Level.CONFIG, "Merging Biomes (" + parent.name + ":" + child.name + ");"); biomeConfigs[this.worldConfig.CustomBiomeIds.get(child.name)] = merge(parent, child); } TerrainControl.log(Level.CONFIG, "========= Inheritance Ending ========="); } //t>> Process needs a special way of handling resource entries to avoid //t>> having both parent and child resources get saved. Need to figure //t>> out how resource loading works. Comment that function in ConfigFile. //>> //t>> Also, another possbility: //t>> Look into using readConfigSettings() instead of the low level //t>> readSettingsFile() method, then write a merge method in BiomeConfigs //t>> that individually copies over all variables. This will be more fine //t>> tuned but less maintainable. If we can isolate the resource loading //t>> and give it special treatment, that is far more desirable from what //t>> I can see from the code.... config.process(); if (this.checkOnly) continue; if (!config.ReplaceBiomeName.equals("")) { this.worldConfig.HaveBiomeReplace = true; this.ReplaceMatrixBiomes[config.Biome.getId()] = (byte) world.getBiomeIdByName(config.ReplaceBiomeName); } if (this.worldConfig.NormalBiomes.contains(config.name)) this.worldConfig.normalBiomesRarity += config.BiomeRarity; if (this.worldConfig.IceBiomes.contains(config.name)) this.worldConfig.iceBiomesRarity += config.BiomeRarity; if (!this.worldConfig.BiomeConfigsHaveReplacement) this.worldConfig.BiomeConfigsHaveReplacement = config.ReplaceCount > 0; if (this.worldConfig.maxSmoothRadius < config.SmoothRadius) this.worldConfig.maxSmoothRadius = config.SmoothRadius; //>> OLD LOCATION OF SETTINGS CACHE POPULATION & BIOME COUNT INCREMENT if (this.worldConfig.biomeMode == TerrainControl.getBiomeModeManager().FROM_IMAGE) { if (this.worldConfig.biomeColorMap == null) this.worldConfig.biomeColorMap = new HashMap<Integer, Integer>(); try { int color = Integer.decode(config.BiomeColor); if (color <= 0xFFFFFF) this.worldConfig.biomeColorMap.put(color, config.Biome.getId()); } catch (NumberFormatException ex) { TerrainControl.log(Level.WARNING, "Wrong color in " + config.Biome.getName()); } } } if (!autosarcophagousBiomes.isEmpty()) { TerrainControl.log(Level.WARNING, "A Biome can NOT extend itself, please fix the following biomes: {0}", new Object[] { autosarcophagousBiomes }); } } private String autosarcophagousBiomes; private LinkedList<BiomeConfig> biomeLoadingStack = new LinkedList<BiomeConfig>(); private void populateInhertianceStack(BiomeConfig config) { biomeLoadingStack.push(config); if (!config.BiomeExtendsProcessed && config.settingsCache.containsKey(TCDefaultValues.BiomeExtends.name().toLowerCase())) { String biomeToExtend_Name = config.settingsCache.get(TCDefaultValues.BiomeExtends.name().toLowerCase()); if (!biomeToExtend_Name.isEmpty()) { TerrainControl.log(Level.SEVERE, "Biome(" + biomeToExtend_Name + ") Processing!"); //>> anti-self-inheritance if (biomeToExtend_Name.equals(config.name)) { if (!autosarcophagousBiomes.isEmpty()) { autosarcophagousBiomes += ", "; } autosarcophagousBiomes += biomeToExtend_Name; TerrainControl.log(Level.CONFIG, "Biome(" + biomeToExtend_Name + ":null) being Autosarcophagous!"); } else { Integer biomeToExtend_Id = this.worldConfig.CustomBiomeIds.get(biomeToExtend_Name); if (biomeToExtend_Id == null) //>> If not found as custom biome, look at the defaults biomeToExtend_Id = DefaultBiome.getId(biomeToExtend_Name); if (biomeToExtend_Id == null) { TerrainControl.log(Level.WARNING, "Biome2Extend(" + biomeToExtend_Name + ":null) not found. If you think this is in error, check your configs!"); } else { TerrainControl.log(Level.WARNING, "Biome2Extend( " + biomeToExtend_Name + ":" + biomeToExtend_Id + ") was found!"); populateInhertianceStack(biomeConfigs[biomeToExtend_Id]); } } } } else { biomeLoadingStack.peek().BiomeExtendsProcessed = true; } } /** * * @param baseBiome * @param extendingBiome * @return */ public static BiomeConfig merge(BiomeConfig baseBiome, BiomeConfig extendingBiome) { TerrainControl.log(Level.SEVERE, "Starting Merge!"); for (String key : baseBiome.settingsCache.keySet()) { if (!extendingBiome.settingsCache.containsKey(key)) { extendingBiome.settingsCache.put(key, baseBiome.settingsCache.get(key)); TerrainControl.log(Level.SEVERE, "Setting({0},{1})", new Object[] { key, baseBiome.settingsCache.get(key) }); } } extendingBiome.BiomeExtendsProcessed = true; return extendingBiome; } /** * * @return */ public BiomeConfig[] getBiomeConfigs() { return biomeConfigs; } /** * * @param biomeConfigs */ public void setBiomeConfigs(BiomeConfig[] biomeConfigs) { this.biomeConfigs = biomeConfigs; } /** * * @param index * @param biomeConfig */ public void addBiomeConfig(int index, BiomeConfig biomeConfig) { this.biomeConfigs[index] = biomeConfig; } /** * * @return */ public int getBiomesCount() { return biomesCount; } /** * * @param biomesCount */ public void setBiomesCount(int biomesCount) { this.biomesCount = biomesCount; } }
common/src/com/khorn/terraincontrol/configuration/BiomeConfigManager.java
package com.khorn.terraincontrol.configuration; import com.khorn.terraincontrol.DefaultBiome; import com.khorn.terraincontrol.LocalBiome; import com.khorn.terraincontrol.LocalWorld; import com.khorn.terraincontrol.TerrainControl; import java.io.DataInputStream; import java.io.File; import java.io.IOException; import java.util.*; import java.util.Map.Entry; import java.util.logging.Level; /** * */ public final class BiomeConfigManager { /* * */ private final File worldBiomesDir; /* * */ private final File globalBiomesDir; /* * */ private final File worldDefaultBiomesDir; /* * */ private byte[] ReplaceMatrixBiomes = new byte[256]; /* * */ private LocalWorld world; /* * */ private WorldConfig worldConfig; /* * */ private boolean checkOnly; /* * A running list of biomes that have been processed during the loading */ private String LoadedBiomeNames = ""; /* * Must be simple array for fast access. Beware! Some ids may contain null * values; */ private BiomeConfig[] biomeConfigs; /* * Overall biome count in this world. */ private int biomesCount; /** * * @param settingsDir * @param world * @param wConfig * @param customBiomes * @param checkOnly */ public BiomeConfigManager(File settingsDir, LocalWorld world, WorldConfig wConfig, Map<String, Integer> customBiomes, boolean checkOnly) { this.world = world; this.worldConfig = wConfig; this.checkOnly = checkOnly; // Check biome ids, These are the names from the worldConfig file //>> Corrects any instances of incorrect biome id. for (String biomeName : customBiomes.keySet()) if (customBiomes.get(biomeName) == -1) customBiomes.put(biomeName, world.getFreeBiomeId()); //>> TerrainControl/GlobalBiomes this.globalBiomesDir = new File(TerrainControl.getEngine().getTCDataFolder(), TCDefaultValues.GlobalBiomeConfigDirectoryName.stringValue()); //>> TerrainControl/worlds/<WorldName>/WorldBiomes this.worldBiomesDir = new File(settingsDir, correctOldBiomeConfigFolder(settingsDir)); //>> TerrainControl/worlds/<WorldName>/BiomeConfigs/Defaults this.worldDefaultBiomesDir = new File(this.worldBiomesDir, TCDefaultValues.WorldDefaultBiomeConfigDirectoryName.stringValue()); //>> If there was an error in folder establishment if (!makeBiomeFolders()) return; // Build biome replace matrix for (int i = 0; i < this.ReplaceMatrixBiomes.length; i++) this.ReplaceMatrixBiomes[i] = (byte) i; //>> Init the biomeConfigs Array biomeConfigs = new BiomeConfig[world.getMaxBiomesCount()]; //>> Set variable for biomeCount, MIGHT NOT NEED biomesCount = 0; //>> This arrayList now contains all biomes listed in `DefaultBiome` populateDefaultBiomeConfigs(new ArrayList<LocalBiome>(world.getDefaultBiomes())); ArrayList<LocalBiome> localBiomes = new ArrayList<LocalBiome>(customBiomes.size()); //>> This adds all custombiomes that have been listed in WorldConfig to the arrayList for (Iterator<Entry<String, Integer>> it = customBiomes.entrySet().iterator(); it.hasNext();) { Entry<String, Integer> entry = it.next(); if (checkOnly) localBiomes.add(world.getNullBiome(entry.getKey())); else localBiomes.add(world.AddBiome(entry.getKey(), entry.getValue())); } populateCustomBiomeConfigs(localBiomes, worldBiomesDir); for (int i = 0; i < biomeConfigs.length; i++) { BiomeConfig bc = biomeConfigs[i]; if (bc != null) { TerrainControl.log(Level.INFO, "Loaded ({0}:{1}) biome", new Object[] { bc.name, i }); } } processBiomeConfigs(); TerrainControl.log(Level.INFO, "Loaded {0} biomes", new Object[] { biomesCount }); TerrainControl.logIfLevel(Level.ALL, Level.CONFIG, LoadedBiomeNames); } private boolean makeBiomeFolders() { boolean allFoldersExist = true; //>> Create the folders if not present if (!globalBiomesDir.exists()) if (!globalBiomesDir.mkdir()) { TerrainControl.log(Level.WARNING, "Error creating Global directory."); allFoldersExist = false; } if (!worldBiomesDir.exists()) if (!worldBiomesDir.mkdir()) { TerrainControl.log(Level.WARNING, "Error creating World Biome configs directory."); allFoldersExist = false; } if (!worldDefaultBiomesDir.exists()) if (!worldDefaultBiomesDir.mkdir()) { TerrainControl.log(Level.WARNING, "Error creating World Default Biome configs directory."); allFoldersExist = false; } if (!allFoldersExist) { TerrainControl.log(Level.WARNING, "Potentially working with defaults."); } return allFoldersExist; } private String correctOldBiomeConfigFolder(File settingsDir) { //>> Rename the old folder String biomeFolderName = TCDefaultValues.WorldBiomeConfigDirectoryName.stringValue(); File oldBiomeConfigs = new File(settingsDir, "BiomeConfigs"); if (oldBiomeConfigs.exists()) { if (!oldBiomeConfigs.renameTo(new File(settingsDir, biomeFolderName))) { TerrainControl.log(Level.WARNING, "========================"); TerrainControl.log(Level.WARNING, "Fould old `BiomeConfigs` folder, but it could not be renamed to `", biomeFolderName, "`!"); TerrainControl.log(Level.WARNING, "Please rename the folder manually."); TerrainControl.log(Level.WARNING, "========================"); biomeFolderName = "BiomeConfigs"; } } return biomeFolderName; } private void populateDefaultBiomeConfigs(ArrayList<LocalBiome> biomesToLoad) { for (LocalBiome localBiome : biomesToLoad) { //>> Upon loading a biome, check the worldDefault location first. BiomeConfig config = new BiomeConfig(worldDefaultBiomesDir, localBiome, this.worldConfig); if (!config.readSuccess) { //>> If a config doesnt exist at that location try the usual BiomeConfigs folder config = new BiomeConfig(worldBiomesDir, localBiome, this.worldConfig); } if (!config.readSuccess) { //>> and if all else fails look in the globalBiomes folder //>> if the biome does not exist here, one will be created config = new BiomeConfig(globalBiomesDir, localBiome, this.worldConfig); } TerrainControl.log(Level.FINER, config.file.getAbsolutePath()); pushBiomeConfig(localBiome, config); } } private void populateCustomBiomeConfigs(ArrayList<LocalBiome> biomesToLoad, File biomeFolder) { for (LocalBiome localBiome : biomesToLoad) { BiomeConfig config = new BiomeConfig(biomeFolder, localBiome, this.worldConfig); pushBiomeConfig(localBiome, config); } } private void pushBiomeConfig(LocalBiome localBiome, BiomeConfig config) { if (biomesCount != 0) LoadedBiomeNames += ", "; LoadedBiomeNames += localBiome.getName(); // Add biome to the biome array if (biomeConfigs[localBiome.getId()] == null) { // Only if it won't overwrite another biome in the array biomesCount++; } else { TerrainControl.log(Level.WARNING, "Duplicate biome id {0} ({1} and {2})!", new Object[] { localBiome.getId(), biomeConfigs[localBiome.getId()].name, config.name }); } biomeConfigs[localBiome.getId()] = config; } private void processBiomeConfigs() { /** ********************* * Proposed Algorithm *********************** * - Grab the settingsCache value for BiomeExtends * - Get the id of the biome to be extended and find it in * biomeConfigs * - determine if need to extend what we found * ---- decend until we find a non-extending biome * - merge the two biomeConfig's * ---- special treatment for resources * - save results by overwritting approp. config * - unset entend var to prevent multi-extending * - ascend until no more extending can be done * - Rinse / Repeat until done extending all biome configs */ int xbiome = 0; autosarcophagousBiomes = ""; TerrainControl.log(Level.INFO, "=============== Biome Processing START ==============="); for (BiomeConfig config : biomeConfigs) { if (config == null) { xbiome++; continue; } //>> //>> //>> // if (config.name.contains("Beach")) // { // String xtemp = ""; // for (Entry<String, String> string : config.settingsCache.entrySet()) // { // if (!xtemp.isEmpty()) // xtemp += ", "; // xtemp += string.getKey() + ":" + string.getValue(); // } // TerrainControl.log(Level.CONFIG, "Settings BEFORE: " + xtemp + "\n for " + config.name + " ::: " + TCDefaultValues.BiomeExtends.name()); // } //>> //>> //>> TerrainControl.log(Level.CONFIG, "Biome attempting to load: " + config.name + ":" + xbiome++); if (!config.BiomeExtendsProcessed) { TerrainControl.log(Level.CONFIG, "======== Inheritance Starting ========"); populateInhertianceStack(config); BiomeConfig parent = biomeLoadingStack.pop(); while (!biomeLoadingStack.isEmpty()) { BiomeConfig child = biomeLoadingStack.pop(); TerrainControl.log(Level.CONFIG, "Merging Biomes (" + parent.name + ":" + child.name + ");"); biomeConfigs[this.worldConfig.CustomBiomeIds.get(child.name)] = merge(parent, child); } TerrainControl.log(Level.CONFIG, "========= Inheritance Ending ========="); } //t>> Process needs a special way of handling resource entries to avoid //t>> having both parent and child resources get saved. Need to figure //t>> out how resource loading works. Comment that function in ConfigFile. //>> //t>> Also, another possbility: //t>> Look into using readConfigSettings() instead of the low level //t>> readSettingsFile() method, then write a merge method in BiomeConfigs //t>> that individually copies over all variables. This will be more fine //t>> tuned but less maintainable. If we can isolate the resource loading //t>> and give it special treatment, that is far more desirable from what //t>> I can see from the code.... config.process(); if (this.checkOnly) continue; if (!config.ReplaceBiomeName.equals("")) { this.worldConfig.HaveBiomeReplace = true; this.ReplaceMatrixBiomes[config.Biome.getId()] = (byte) world.getBiomeIdByName(config.ReplaceBiomeName); } if (this.worldConfig.NormalBiomes.contains(config.name)) this.worldConfig.normalBiomesRarity += config.BiomeRarity; if (this.worldConfig.IceBiomes.contains(config.name)) this.worldConfig.iceBiomesRarity += config.BiomeRarity; if (!this.worldConfig.BiomeConfigsHaveReplacement) this.worldConfig.BiomeConfigsHaveReplacement = config.ReplaceCount > 0; if (this.worldConfig.maxSmoothRadius < config.SmoothRadius) this.worldConfig.maxSmoothRadius = config.SmoothRadius; //>> OLD LOCATION OF SETTINGS CACHE POPULATION & BIOME COUNT INCREMENT if (this.worldConfig.biomeMode == TerrainControl.getBiomeModeManager().FROM_IMAGE) { if (this.worldConfig.biomeColorMap == null) this.worldConfig.biomeColorMap = new HashMap<Integer, Integer>(); try { int color = Integer.decode(config.BiomeColor); if (color <= 0xFFFFFF) this.worldConfig.biomeColorMap.put(color, config.Biome.getId()); } catch (NumberFormatException ex) { TerrainControl.log(Level.WARNING, "Wrong color in " + config.Biome.getName()); } } } if (!autosarcophagousBiomes.isEmpty()) { TerrainControl.log(Level.WARNING, "A Biome can NOT extend itself, please fix the following biomes: {0}", new Object[] { autosarcophagousBiomes }); } } private String autosarcophagousBiomes; private LinkedList<BiomeConfig> biomeLoadingStack = new LinkedList<BiomeConfig>(); private void populateInhertianceStack(BiomeConfig config) { biomeLoadingStack.push(config); if (!config.BiomeExtendsProcessed && config.settingsCache.containsKey(TCDefaultValues.BiomeExtends.name().toLowerCase())) { String biomeToExtend_Name = config.settingsCache.get(TCDefaultValues.BiomeExtends.name().toLowerCase()); if (!biomeToExtend_Name.isEmpty()) { TerrainControl.log(Level.SEVERE, "Biome(" + biomeToExtend_Name + ") Processing!"); //>> anti-self-inheritance if (biomeToExtend_Name.equals(config.name)) { if (!autosarcophagousBiomes.isEmpty()) { autosarcophagousBiomes += ", "; } autosarcophagousBiomes += biomeToExtend_Name; TerrainControl.log(Level.CONFIG, "Biome(" + biomeToExtend_Name + ":null) being Autosarcophagous!"); } else { Integer biomeToExtend_Id = this.worldConfig.CustomBiomeIds.get(biomeToExtend_Name); if (biomeToExtend_Id == null) //>> If not found as custom biome, look at the defaults biomeToExtend_Id = DefaultBiome.getId(biomeToExtend_Name); if (biomeToExtend_Id == null) { TerrainControl.log(Level.WARNING, "Biome2Extend(" + biomeToExtend_Name + ":null) not found. If you think this is in error, check your configs!"); } else { TerrainControl.log(Level.WARNING, "Biome2Extend( " + biomeToExtend_Name + ":" + biomeToExtend_Id + ") was found!"); populateInhertianceStack(biomeConfigs[biomeToExtend_Id]); } } } } else { biomeLoadingStack.peek().BiomeExtendsProcessed = true; } } /** * * @param baseBiome * @param extendingBiome * @return */ public static BiomeConfig merge(BiomeConfig baseBiome, BiomeConfig extendingBiome) { TerrainControl.log(Level.SEVERE, "Starting Merge!"); for (String key : baseBiome.settingsCache.keySet()) { if (!extendingBiome.settingsCache.containsKey(key)) { extendingBiome.settingsCache.put(key, baseBiome.settingsCache.get(key)); TerrainControl.log(Level.SEVERE, "Setting({0},{1})", new Object[] { key, baseBiome.settingsCache.get(key) }); } } extendingBiome.BiomeExtendsProcessed = true; return extendingBiome; } /** * * @return */ public BiomeConfig[] getBiomeConfigs() { return biomeConfigs; } /** * * @param biomeConfigs */ public void setBiomeConfigs(BiomeConfig[] biomeConfigs) { this.biomeConfigs = biomeConfigs; } /** * * @param index * @param biomeConfig */ public void addBiomeConfig(int index, BiomeConfig biomeConfig) { this.biomeConfigs[index] = biomeConfig; } /** * * @return */ public int getBiomesCount() { return biomesCount; } /** * * @param biomesCount */ public void setBiomesCount(int biomesCount) { this.biomesCount = biomesCount; } }
Removed some debug logging and comments
common/src/com/khorn/terraincontrol/configuration/BiomeConfigManager.java
Removed some debug logging and comments
<ide><path>ommon/src/com/khorn/terraincontrol/configuration/BiomeConfigManager.java <ide> /** ********************* <ide> * Proposed Algorithm <ide> *********************** <del> * - Grab the settingsCache value for BiomeExtends <add> * - Grab the settingsCache value for BiomeExtends check <ide> * - Get the id of the biome to be extended and find it in <del> * biomeConfigs <del> * - determine if need to extend what we found <del> * ---- decend until we find a non-extending biome <del> * - merge the two biomeConfig's <add> * biomeConfigs check <add> * - determine if need to extend what we found check <add> * ---- decend until we find a non-extending biome check <add> * - merge the two biomeConfig's needs fix <ide> * ---- special treatment for resources <del> * - save results by overwritting approp. config <del> * - unset entend var to prevent multi-extending <del> * - ascend until no more extending can be done <del> * - Rinse / Repeat until done extending all biome configs <add> * - save results by overwritting approp. config check <add> * - make sure we dont process already processed configs check <add> * - ascend until no more extending can be done check <add> * - Rinse / Repeat until done extending all biome configs check <ide> */ <ide> int xbiome = 0; <ide> autosarcophagousBiomes = ""; <ide> xbiome++; <ide> continue; <ide> } <del> <del> //>> <del> //>> <del> //>> <del> <del>// if (config.name.contains("Beach")) <del>// { <del>// String xtemp = ""; <del>// for (Entry<String, String> string : config.settingsCache.entrySet()) <del>// { <del>// if (!xtemp.isEmpty()) <del>// xtemp += ", "; <del>// xtemp += string.getKey() + ":" + string.getValue(); <del>// } <del>// TerrainControl.log(Level.CONFIG, "Settings BEFORE: " + xtemp + "\n for " + config.name + " ::: " + TCDefaultValues.BiomeExtends.name()); <del>// } <del> <del> //>> <del> //>> <del> //>> <ide> <ide> TerrainControl.log(Level.CONFIG, "Biome attempting to load: " + config.name + ":" + xbiome++); <ide> if (!config.BiomeExtendsProcessed)
Java
bsd-3-clause
4b0dfd6d981c35b1aa07ed42570b91e50a1895f2
0
krishagni/openspecimen,asamgir/openspecimen,asamgir/openspecimen,NCIP/catissue-core,asamgir/openspecimen,krishagni/openspecimen,NCIP/catissue-core,NCIP/catissue-core,krishagni/openspecimen
package edu.wustl.catissuecore.action; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import edu.wustl.catissuecore.actionForm.CollectionEventParametersForm; import edu.wustl.catissuecore.actionForm.CreateSpecimenForm; import edu.wustl.catissuecore.actionForm.NewSpecimenForm; import edu.wustl.catissuecore.actionForm.ReceivedEventParametersForm; import edu.wustl.catissuecore.applet.AppletConstants; import edu.wustl.catissuecore.bizlogic.BizLogicFactory; import edu.wustl.catissuecore.bizlogic.NewSpecimenBizLogic; import edu.wustl.catissuecore.domain.CollectionEventParameters; import edu.wustl.catissuecore.domain.ReceivedEventParameters; import edu.wustl.catissuecore.domain.Specimen; import edu.wustl.catissuecore.domain.SpecimenCollectionGroup; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.catissuecore.util.global.Utility; import edu.wustl.common.beans.NameValueBean; import edu.wustl.common.beans.SessionDataBean; import edu.wustl.common.bizlogic.IBizLogic; import edu.wustl.common.cde.CDE; import edu.wustl.common.cde.CDEManager; import edu.wustl.common.cde.PermissibleValue; import edu.wustl.common.factory.AbstractBizLogicFactory; import edu.wustl.common.factory.AbstractDomainObjectFactory; import edu.wustl.common.factory.MasterFactory; import edu.wustl.common.util.MapDataParser; import edu.wustl.common.util.global.ApplicationProperties; import edu.wustl.common.util.logger.Logger; /** * This action contains methods that are called by MultipleSpecimenApplet * Currently it includes: * * 1. initData * 2. submitSpecimens * 3. getResult * * @author Rahul Ner */ public class MultipleSpecimenAppletAction extends BaseAppletAction { /** * This map contains the mapping for the each specimen and its selected class. * key - specimen no in the applet * values - selected class. * */ Map classMap; /** * This method is called by Multiple specimen data model during initialization to * set the list that are displayed in the drop down form. * It returns in following list * * 1. Tissue site list * 2. Tissue side list * 3. Pathological status list * 4. Map of specimen class and type . refer to getSpecimenClassTypeMap method. * * @param actionMapping * @param actionForm * @param request * @param response * @return * @throws Exception */ public ActionForward initData(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { Map DataListsMap = new HashMap(); Map specimenClassTypeMap = getSpecimenClassTypeMap(); List specimenClassList = new ArrayList(); specimenClassList.add(Constants.SELECT_OPTION); specimenClassList.addAll(specimenClassTypeMap.keySet()); specimenClassTypeMap.put(Constants.SELECT_OPTION, new String[]{Constants.SELECT_OPTION}); DataListsMap.put(Constants.SPECIMEN_TYPE_MAP, specimenClassTypeMap); DataListsMap.put(Constants.SPECIMEN_CLASS_LIST, specimenClassList.toArray()); DataListsMap.put(Constants.TISSUE_SITE_LIST, Utility.getListForCDE( Constants.CDE_NAME_TISSUE_SITE).toArray()); DataListsMap.put(Constants.TISSUE_SIDE_LIST, Utility.getListForCDE( Constants.CDE_NAME_TISSUE_SIDE).toArray()); DataListsMap.put(Constants.PATHOLOGICAL_STATUS_LIST, Utility.getListForCDE( Constants.CDE_NAME_PATHOLOGICAL_STATUS).toArray()); //------------specimen collection group NewSpecimenBizLogic bizLogic = (NewSpecimenBizLogic) BizLogicFactory.getInstance() .getBizLogic(Constants.NEW_SPECIMEN_FORM_ID); String sourceObjectName = SpecimenCollectionGroup.class.getName(); String[] displayNameFields = {"name"}; String valueField = Constants.SYSTEM_IDENTIFIER; List specimenGroupList = bizLogic.getList(sourceObjectName, displayNameFields, valueField, true); ArrayList specimenGroupArrayList = new ArrayList(); specimenGroupArrayList = getNameStringArray(specimenGroupList); DataListsMap.put(Constants.SPECIMEN_COLLECTION_GROUP_LIST, specimenGroupArrayList.toArray() ); // ------------------------------------ writeMapToResponse(response, DataListsMap); return null; } /** * This method saves multiple specimens. * * 1. It preprocess specimen map (map from paplet table model). * 2. Converts each specimen to specific type of specimen by appending its class name. * 3. Adds Associates objects which are present in the session to the specimen. * 4. Parses specimen map to convert it to specimen domain object using map data parser. * 5. post Processes each specimen to add inital values like acfivity status. TODO: can be clubed into first step. * 6. Saves Specimens using bizLogic layer. * 7. Send success or failure to the applet. In case of failure, messages are also send to applet. * * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.ServletRequest, javax.servlet.ServletResponse) */ public ActionForward submitSpecimens(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { String target; Map resultMap = new HashMap(); try { Map specimenMap = (Map) request.getAttribute(Constants.INPUT_APPLET_DATA); System.out.println("Submitting the specimen : " + specimenMap); preprocessSpecimanMap(specimenMap); System.out.println("After preprocessSpecimanMap"); Map fixedSpecimenMap = appendClassValue(specimenMap); System.out.println("After fixedSpecimenMap"); Map multipleSpecimenSessionMap = (Map) request.getSession().getAttribute( Constants.MULTIPLE_SPECIMEN_MAP_KEY); processAssociatedObjectsMap(fixedSpecimenMap, multipleSpecimenSessionMap); System.out.println("After processAssociatedObjectsMap"); MapDataParser specimenParser = new MapDataParser("edu.wustl.catissuecore.domain"); System.out.println("After specimenParser"); Collection specimenCollection = specimenParser.generateData(fixedSpecimenMap); //Read session form bean map to associate derived specimens Map multipleSpecimenFormBeanMap = (Map) request.getSession().getAttribute( Constants.MULTIPLE_SPECIMEN_FORM_BEAN_MAP_KEY); Map multipleSpecimenEventsFormBean = (Map) request.getSession().getAttribute(Constants.MULTIPLE_SPECIMEN_EVENT_MAP_KEY); if(multipleSpecimenEventsFormBean != null) processEvents(specimenCollection,multipleSpecimenEventsFormBean); Map finalMap = processFormBeansMap(specimenCollection,multipleSpecimenFormBeanMap); //call bizLogic to save specimenCollection. It will first validate all the specimens. insertSpecimens(request, finalMap); //if success return to report page request.getSession().setAttribute(Constants.SAVED_SPECIMEN_COLLECTION, specimenCollection); target = Constants.SUCCESS; //clean up activity. multipleSpecimenSessionMap = null; request.getSession().setAttribute(Constants.MULTIPLE_SPECIMEN_MAP_KEY, null); } catch (Exception e) { //return to same applet page incase of failure. target = Constants.FAILURE; String errorMsg = e.getMessage(); if(errorMsg.startsWith("For input string")) { errorMsg = "Please enter valid Quantity (Instead of " + errorMsg.replaceFirst("For","") + ")"; // temporary fix for error message } resultMap.put(Constants.ERROR_DETAIL, errorMsg); e.printStackTrace(); } //send response to the applet. resultMap.put(Constants.MULTIPLE_SPECIMEN_RESULT, target); writeMapToResponse(response, resultMap); return null; } private Map processFormBeansMap(Collection specimenCollection, Map multipleSpecimenFormBeanMap) throws Exception { Map finalSpecimenMap = new HashMap(); AbstractDomainObjectFactory abstractDomainObjectFactory = (AbstractDomainObjectFactory) MasterFactory.getFactory( ApplicationProperties.getValue("app.domainObjectFactory")); Iterator specimenCollectionIterator = specimenCollection.iterator(); //set default values for the specimen. while (specimenCollectionIterator.hasNext()) { Specimen specimen = (Specimen) specimenCollectionIterator.next(); specimen.setAvailable(new Boolean(true)); specimen.setAvailableQuantity(specimen.getQuantity()); List derivedFormBeans = null; //Associate derived specimens. if(multipleSpecimenFormBeanMap!=null) { derivedFormBeans = (List) multipleSpecimenFormBeanMap.get(AppletConstants.SPECIMEN_PREFIX + specimen.getId() + "_" + "derive"); } List derivedSpecimens = new ArrayList(); // if no derived, continue with next if( derivedFormBeans != null ) { for (int i=0;i<derivedFormBeans.size();i++) { CreateSpecimenForm derivedSpecimenFormBean = (CreateSpecimenForm) derivedFormBeans.get(i); derivedSpecimenFormBean.setParentSpecimenId(specimen.getId().toString()); Specimen derivedSpecimen = (Specimen) abstractDomainObjectFactory.getDomainObject(Constants.CREATE_SPECIMEN_FORM_ID, derivedSpecimenFormBean); derivedSpecimen.setSpecimenCollectionGroup(null); derivedSpecimens.add(derivedSpecimen); } } finalSpecimenMap.put(specimen,derivedSpecimens); } return finalSpecimenMap; } /** * This method puts all the values defined for the associated object. * * @param specimenMap * @param multipleSpecimenSessionMap */ private void processAssociatedObjectsMap(Map specimenMap, Map multipleSpecimenSessionMap) { if(multipleSpecimenSessionMap == null) { return; } Iterator sessionMapItr = multipleSpecimenSessionMap.keySet().iterator(); while (sessionMapItr.hasNext()) { String key = (String) sessionMapItr.next(); if (key.endsWith(Constants.APPEND_COUNT)) { //ignore counts keys continue; } Object associatedObject = multipleSpecimenSessionMap.get(key); if (associatedObject instanceof String) { // e.g. comments objects String newKeyInSpecimenMap = getUpdatedKey(key); specimenMap.put(newKeyInSpecimenMap, associatedObject); } else if (associatedObject instanceof Map) { //e.g. external Identifier Map associatedObjectMap = (Map) associatedObject; // remove corrosponding key from main map. specimenMap.remove(getUpdatedKey(key)); Iterator associatedObjectsMapItr = (associatedObjectMap).keySet().iterator(); while (associatedObjectsMapItr.hasNext()) { String objectKey = (String) associatedObjectsMapItr.next(); String newKeyInSpecimenMap = getConsolidatedKey(key, objectKey); specimenMap.put(newKeyInSpecimenMap, associatedObjectMap.get(objectKey)); } } } } /** * e.g * if Session map contains key "Specimen:1_externalIdentifierCollection" and value as a another map, * so key will be "Specimen:1_externalIdentifierCollection" * and associatedObjectKey is "ExternalIdentifier:1_id" and to this key some value is associated in that another map. * And if for specimen 1 , "Molecular" class is selected, * * it will return MolecularSpecimen:1_ExternalIdentifier:1_id * */ private String getConsolidatedKey(String key, String associatedObjectKey) { String keyWithClass = getUpdatedKey(key); String tempKey = keyWithClass.split("_")[0]; return tempKey + "_" + associatedObjectKey; } /** * This method is called by applet when submit method return success. It forwards to the report page. */ public ActionForward getResult(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { String target = (String) request.getParameter(Constants.MULTIPLE_SPECIMEN_RESULT); Collection specimenCollection = (Collection) request.getSession().getAttribute( Constants.SAVED_SPECIMEN_COLLECTION); request.getSession().setAttribute(Constants.SAVED_SPECIMEN_COLLECTION, null); request.setAttribute(Constants.SAVED_SPECIMEN_COLLECTION, specimenCollection); ActionMessages msgs = new ActionMessages(); msgs.add("success", new ActionMessage("multipleSpecimen.add.success", String .valueOf(specimenCollection.size()))); saveMessages(request, msgs); return actionMapping.findForward(target); } /** * This method processes input specimens map. * * 1. initialize map which contains for each specimen its selected class. * 2. If class is not selected for any specimen it throws exception * 3. It removes unneccessary keys(keys that are no longer required) from the map. * * @param specimenMap inputMap */ private void preprocessSpecimanMap(Map specimenMap) throws Exception { classMap = new HashMap(); int noOfSpecimens = Integer.parseInt((String) specimenMap .get(AppletConstants.NO_OF_SPECIMENS)); specimenMap.remove(AppletConstants.NO_OF_SPECIMENS); for (int i = 1; i <= noOfSpecimens; i++) { String classValue = (String) specimenMap.get(AppletConstants.SPECIMEN_PREFIX + i + "_" + "class"); if (classValue == null || classValue.trim().length() == 0 || classValue.equals("-- Select --")) { throw new Exception(ApplicationProperties.getValue("protocol.class.errMsg") + " for Specimen number " + i); } String quantityKey = AppletConstants.SPECIMEN_PREFIX + i + "_" + "Quantity_value"; String quantityValue = (String) specimenMap.get(quantityKey); try { Long.parseLong(quantityValue); } catch (NumberFormatException e) { throw new Exception("Please enter valid Quantity for Specimen number " + i); } Long storageContainer = (Long) specimenMap.get(AppletConstants.SPECIMEN_PREFIX + i + "_" + "StorageContainer_id"); if (storageContainer == null) { throw new Exception("Please give valid Storage Position for Specimen number " + i); } classMap.put(String.valueOf(i), classValue); if (!classValue.equals("Molecular")) { specimenMap.remove(AppletConstants.SPECIMEN_PREFIX + i + "_" + "concentrationInMicrogramPerMicroliter"); } specimenMap.remove(AppletConstants.SPECIMEN_PREFIX + i + "_" + "class"); specimenMap.remove(AppletConstants.SPECIMEN_PREFIX + i + "_" + "StorageContainer_temp"); specimenMap.remove(AppletConstants.SPECIMEN_PREFIX + i + "_" + "derive"); // mandar : to remove the label entry. specimenMap.remove(AppletConstants.SPECIMEN_PREFIX + i + "_" + AppletConstants.MULTIPLE_SPECIMEN_LOCATION_LABEL); specimenMap.put(AppletConstants.SPECIMEN_PREFIX + i + "_" + "activityStatus", Constants.ACTIVITY_STATUS_ACTIVE); //specimenMap.put(AppletConstants.SPECIMEN_PREFIX + i + "_" + "available" ,new Boolean(true)); } } /** * This method saves collection of specimens to the database. * TODO Error handling. * @param request * @param specimenCollection */ private void insertSpecimens(HttpServletRequest request, Map specimenMap) throws Exception { IBizLogic bizLogic; bizLogic = AbstractBizLogicFactory.getBizLogic(ApplicationProperties .getValue("app.bizLogicFactory"), "getBizLogic", Constants.NEW_SPECIMEN_FORM_ID); SessionDataBean sessionBean = (SessionDataBean) request.getSession().getAttribute( Constants.SESSION_DATA); bizLogic.insert(specimenMap, sessionBean, Constants.HIBERNATE_DAO); } /** * This method changes map given by table model and updated following things. * 1. Appends each key with the selected class value. * * @param specimenMap * @return */ private Map appendClassValue(Map inputMap) { Map newMap = new HashMap(); if (inputMap == null) { return newMap; } Iterator it = inputMap.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); String newKey = getUpdatedKey(key); String value = String.valueOf(inputMap.get(key)); newMap.put(newKey, value); } return newMap; } /** * This method returns updated key depending on class selected for a specimen * * if user has selected Fluid as specimen class for specimen no 2 then for the key "Specimen:2_pathologicalStatus" * this method will return "FluidSpecimen:2_pathologicalStatus". * * @param key e.g. * @return */ private String getUpdatedKey(String key) { String specimenNo = key.substring(key.indexOf(":") + 1, key.indexOf("_")); return (String) classMap.get(specimenNo) + key; } /** * This method returns a map where * * key - Specimen Class in String form * | * |___value arrayList of corrosponding Specimen types. * * * @return map */ private Map getSpecimenClassTypeMap() { Map specimenClassTypeMap = new HashMap(); CDE specimenClassCDE = CDEManager.getCDEManager().getCDE(Constants.CDE_NAME_SPECIMEN_CLASS); Set setPV = specimenClassCDE.getPermissibleValues(); Iterator specimenClassItr = setPV.iterator(); while (specimenClassItr.hasNext()) { PermissibleValue pValue = (PermissibleValue) specimenClassItr.next(); Set subPV = pValue.getSubPermissibleValues(); Iterator specimenTypeItr = subPV.iterator(); List specimenType = new ArrayList(); specimenType.add(Constants.SELECT_OPTION); while (specimenTypeItr.hasNext()) { PermissibleValue specimenTypePV = (PermissibleValue) specimenTypeItr.next(); specimenType.add(specimenTypePV.getValue()); } specimenClassTypeMap.put(pValue.getValue(), specimenType.toArray()); } return specimenClassTypeMap; } private void processEvents(Collection specimenCollection, Map multipleSpecimenFormBeanMap) throws Exception { Iterator specimenCollectionIterator = specimenCollection.iterator(); //set default values for the specimen. int i = 1; while (specimenCollectionIterator.hasNext()) { Specimen specimen = (Specimen) specimenCollectionIterator.next(); NewSpecimenForm form = (NewSpecimenForm) multipleSpecimenFormBeanMap.get("Specimen:"+i+"_specimenEventCollection"); if(form == null) { throw new Exception("Please Give Events for specimen number "+i); } else { Collection specimenEventCollection = new HashSet(); CollectionEventParametersForm collectionEvent = new CollectionEventParametersForm(); collectionEvent.setCollectionProcedure(form .getCollectionEventCollectionProcedure()); collectionEvent.setComments(form.getCollectionEventComments()); collectionEvent.setContainer(form.getCollectionEventContainer()); collectionEvent.setTimeInHours(form.getCollectionEventTimeInHours()); collectionEvent.setTimeInMinutes(form.getCollectionEventTimeInMinutes()); collectionEvent.setDateOfEvent(form.getCollectionEventdateOfEvent()); collectionEvent.setUserId(form.getCollectionEventUserId()); collectionEvent.setOperation(form.getOperation()); CollectionEventParameters collectionEventParameters = new CollectionEventParameters(); collectionEventParameters.setAllValues(collectionEvent); //collectionEventParameters.setSpecimen(specimen); Logger.out.debug("Before specimenEventCollection.size(): " + specimenEventCollection.size()); specimenEventCollection.add(collectionEventParameters); Logger.out.debug("After specimenEventCollection.size(): " + specimenEventCollection.size()); Logger.out.debug("...14-July-06... : CollectionEvent set"); Logger.out.debug("Setting Received event in specimen domain object"); //setting received event values ReceivedEventParametersForm receivedEvent = new ReceivedEventParametersForm(); receivedEvent.setComments(form.getReceivedEventComments()); receivedEvent.setDateOfEvent(form.getReceivedEventDateOfEvent()); receivedEvent.setReceivedQuality(form.getReceivedEventReceivedQuality()); receivedEvent.setUserId(form.getReceivedEventUserId()); receivedEvent.setTimeInMinutes(form.getReceivedEventTimeInMinutes()); receivedEvent.setTimeInHours(form.getReceivedEventTimeInHours()); receivedEvent.setOperation(form.getOperation()); ReceivedEventParameters receivedEventParameters = new ReceivedEventParameters(); receivedEventParameters.setAllValues(receivedEvent); //receivedEventParameters.setSpecimen(specimen); Logger.out.debug("Before specimenEventCollection.size(): " + specimenEventCollection.size()); specimenEventCollection.add(receivedEventParameters); Logger.out.debug("After specimenEventCollection.size(): " + specimenEventCollection.size()); specimen.setSpecimenEventCollection(specimenEventCollection); Logger.out.debug("...14-July-06... : ReceivedEvent set"); } i++; } } private ArrayList getNameStringArray(List specimenGroupList) { ArrayList returnArrayList =new ArrayList(); for(int cnt=0;cnt<specimenGroupList.size();cnt++ ) { NameValueBean bean = (NameValueBean)specimenGroupList.get(cnt ); returnArrayList.add(bean.getName()); } return returnArrayList; } }
WEB-INF/src/edu/wustl/catissuecore/action/MultipleSpecimenAppletAction.java
package edu.wustl.catissuecore.action; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import edu.wustl.catissuecore.actionForm.CollectionEventParametersForm; import edu.wustl.catissuecore.actionForm.CreateSpecimenForm; import edu.wustl.catissuecore.actionForm.NewSpecimenForm; import edu.wustl.catissuecore.actionForm.ReceivedEventParametersForm; import edu.wustl.catissuecore.applet.AppletConstants; import edu.wustl.catissuecore.bizlogic.BizLogicFactory; import edu.wustl.catissuecore.bizlogic.NewSpecimenBizLogic; import edu.wustl.catissuecore.domain.CollectionEventParameters; import edu.wustl.catissuecore.domain.ReceivedEventParameters; import edu.wustl.catissuecore.domain.Specimen; import edu.wustl.catissuecore.domain.SpecimenCollectionGroup; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.catissuecore.util.global.Utility; import edu.wustl.common.beans.NameValueBean; import edu.wustl.common.beans.SessionDataBean; import edu.wustl.common.bizlogic.IBizLogic; import edu.wustl.common.cde.CDE; import edu.wustl.common.cde.CDEManager; import edu.wustl.common.cde.PermissibleValue; import edu.wustl.common.factory.AbstractBizLogicFactory; import edu.wustl.common.factory.AbstractDomainObjectFactory; import edu.wustl.common.factory.MasterFactory; import edu.wustl.common.util.MapDataParser; import edu.wustl.common.util.global.ApplicationProperties; import edu.wustl.common.util.logger.Logger; /** * This action contains methods that are called by MultipleSpecimenApplet * Currently it includes: * * 1. initData * 2. submitSpecimens * 3. getResult * * @author Rahul Ner */ public class MultipleSpecimenAppletAction extends BaseAppletAction { /** * This map contains the mapping for the each specimen and its selected class. * key - specimen no in the applet * values - selected class. * */ Map classMap; /** * This method is called by Multiple specimen data model during initialization to * set the list that are displayed in the drop down form. * It returns in following list * * 1. Tissue site list * 2. Tissue side list * 3. Pathological status list * 4. Map of specimen class and type . refer to getSpecimenClassTypeMap method. * * @param actionMapping * @param actionForm * @param request * @param response * @return * @throws Exception */ public ActionForward initData(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { Map DataListsMap = new HashMap(); Map specimenClassTypeMap = getSpecimenClassTypeMap(); List specimenClassList = new ArrayList(); specimenClassList.add(Constants.SELECT_OPTION); specimenClassList.addAll(specimenClassTypeMap.keySet()); specimenClassTypeMap.put(Constants.SELECT_OPTION, new String[]{Constants.SELECT_OPTION}); DataListsMap.put(Constants.SPECIMEN_TYPE_MAP, specimenClassTypeMap); DataListsMap.put(Constants.SPECIMEN_CLASS_LIST, specimenClassList.toArray()); DataListsMap.put(Constants.TISSUE_SITE_LIST, Utility.getListForCDE( Constants.CDE_NAME_TISSUE_SITE).toArray()); DataListsMap.put(Constants.TISSUE_SIDE_LIST, Utility.getListForCDE( Constants.CDE_NAME_TISSUE_SIDE).toArray()); DataListsMap.put(Constants.PATHOLOGICAL_STATUS_LIST, Utility.getListForCDE( Constants.CDE_NAME_PATHOLOGICAL_STATUS).toArray()); //------------specimen collection group NewSpecimenBizLogic bizLogic = (NewSpecimenBizLogic) BizLogicFactory.getInstance() .getBizLogic(Constants.NEW_SPECIMEN_FORM_ID); String sourceObjectName = SpecimenCollectionGroup.class.getName(); String[] displayNameFields = {"name"}; String valueField = Constants.SYSTEM_IDENTIFIER; List specimenGroupList = bizLogic.getList(sourceObjectName, displayNameFields, valueField, true); ArrayList specimenGroupArrayList = new ArrayList(); specimenGroupArrayList = getNameStringArray(specimenGroupList); DataListsMap.put(Constants.SPECIMEN_COLLECTION_GROUP_LIST, specimenGroupArrayList.toArray() ); // ------------------------------------ writeMapToResponse(response, DataListsMap); return null; } /** * This method saves multiple specimens. * * 1. It preprocess specimen map (map from paplet table model). * 2. Converts each specimen to specific type of specimen by appending its class name. * 3. Adds Associates objects which are present in the session to the specimen. * 4. Parses specimen map to convert it to specimen domain object using map data parser. * 5. post Processes each specimen to add inital values like acfivity status. TODO: can be clubed into first step. * 6. Saves Specimens using bizLogic layer. * 7. Send success or failure to the applet. In case of failure, messages are also send to applet. * * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.ServletRequest, javax.servlet.ServletResponse) */ public ActionForward submitSpecimens(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { String target; Map resultMap = new HashMap(); try { Map specimenMap = (Map) request.getAttribute(Constants.INPUT_APPLET_DATA); System.out.println("Submitting the specimen : " + specimenMap); preprocessSpecimanMap(specimenMap); System.out.println("After preprocessSpecimanMap"); Map fixedSpecimenMap = appendClassValue(specimenMap); System.out.println("After fixedSpecimenMap"); Map multipleSpecimenSessionMap = (Map) request.getSession().getAttribute( Constants.MULTIPLE_SPECIMEN_MAP_KEY); processAssociatedObjectsMap(fixedSpecimenMap, multipleSpecimenSessionMap); System.out.println("After processAssociatedObjectsMap"); MapDataParser specimenParser = new MapDataParser("edu.wustl.catissuecore.domain"); System.out.println("After specimenParser"); Collection specimenCollection = specimenParser.generateData(fixedSpecimenMap); //Read session form bean map to associate derived specimens Map multipleSpecimenFormBeanMap = (Map) request.getSession().getAttribute( Constants.MULTIPLE_SPECIMEN_FORM_BEAN_MAP_KEY); Map multipleSpecimenEventsFormBean = (Map) request.getSession().getAttribute(Constants.MULTIPLE_SPECIMEN_EVENT_MAP_KEY); if(multipleSpecimenEventsFormBean != null) processEvents(specimenCollection,multipleSpecimenEventsFormBean); Map finalMap = processFormBeansMap(specimenCollection,multipleSpecimenFormBeanMap); //call bizLogic to save specimenCollection. It will first validate all the specimens. insertSpecimens(request, finalMap); //if success return to report page request.getSession().setAttribute(Constants.SAVED_SPECIMEN_COLLECTION, specimenCollection); target = Constants.SUCCESS; //clean up activity. multipleSpecimenSessionMap = null; request.getSession().setAttribute(Constants.MULTIPLE_SPECIMEN_MAP_KEY, null); } catch (Exception e) { //return to same applet page incase of failure. target = Constants.FAILURE; String errorMsg = e.getMessage(); if(errorMsg.startsWith("For input string")) { errorMsg = "Please enter valid Quantity (Instead of " + errorMsg.replaceFirst("For","") + ")"; // temporary fix for error message } resultMap.put(Constants.ERROR_DETAIL, errorMsg); e.printStackTrace(); } //send response to the applet. resultMap.put(Constants.MULTIPLE_SPECIMEN_RESULT, target); writeMapToResponse(response, resultMap); return null; } private Map processFormBeansMap(Collection specimenCollection, Map multipleSpecimenFormBeanMap) throws Exception { Map finalSpecimenMap = new HashMap(); AbstractDomainObjectFactory abstractDomainObjectFactory = (AbstractDomainObjectFactory) MasterFactory.getFactory( ApplicationProperties.getValue("app.domainObjectFactory")); Iterator specimenCollectionIterator = specimenCollection.iterator(); //set default values for the specimen. while (specimenCollectionIterator.hasNext()) { Specimen specimen = (Specimen) specimenCollectionIterator.next(); specimen.setAvailable(new Boolean(true)); specimen.setAvailableQuantity(specimen.getQuantity()); List derivedFormBeans = null; //Associate derived specimens. if(multipleSpecimenFormBeanMap!=null) { derivedFormBeans = (List) multipleSpecimenFormBeanMap.get(AppletConstants.SPECIMEN_PREFIX + specimen.getId() + "_" + "derive"); } List derivedSpecimens = new ArrayList(); // if no derived, continue with next if( derivedFormBeans != null ) { for (int i=0;i<derivedFormBeans.size();i++) { CreateSpecimenForm derivedSpecimenFormBean = (CreateSpecimenForm) derivedFormBeans.get(i); derivedSpecimenFormBean.setParentSpecimenId(specimen.getId().toString()); Specimen derivedSpecimen = (Specimen) abstractDomainObjectFactory.getDomainObject(Constants.CREATE_SPECIMEN_FORM_ID, derivedSpecimenFormBean); derivedSpecimen.setSpecimenCollectionGroup(null); derivedSpecimens.add(derivedSpecimen); } } finalSpecimenMap.put(specimen,derivedSpecimens); } return finalSpecimenMap; } /** * This method puts all the values defined for the associated object. * * @param specimenMap * @param multipleSpecimenSessionMap */ private void processAssociatedObjectsMap(Map specimenMap, Map multipleSpecimenSessionMap) { if(multipleSpecimenSessionMap == null) { return; } Iterator sessionMapItr = multipleSpecimenSessionMap.keySet().iterator(); while (sessionMapItr.hasNext()) { String key = (String) sessionMapItr.next(); if (key.endsWith(Constants.APPEND_COUNT)) { //ignore counts keys continue; } Object associatedObject = multipleSpecimenSessionMap.get(key); if (associatedObject instanceof String) { // e.g. comments objects String newKeyInSpecimenMap = getUpdatedKey(key); specimenMap.put(newKeyInSpecimenMap, associatedObject); } else if (associatedObject instanceof Map) { //e.g. external Identifier Map associatedObjectMap = (Map) associatedObject; // remove corrosponding key from main map. specimenMap.remove(getUpdatedKey(key)); Iterator associatedObjectsMapItr = (associatedObjectMap).keySet().iterator(); while (associatedObjectsMapItr.hasNext()) { String objectKey = (String) associatedObjectsMapItr.next(); String newKeyInSpecimenMap = getConsolidatedKey(key, objectKey); specimenMap.put(newKeyInSpecimenMap, associatedObjectMap.get(objectKey)); } } } } /** * e.g * if Session map contains key "Specimen:1_externalIdentifierCollection" and value as a another map, * so key will be "Specimen:1_externalIdentifierCollection" * and associatedObjectKey is "ExternalIdentifier:1_id" and to this key some value is associated in that another map. * And if for specimen 1 , "Molecular" class is selected, * * it will return MolecularSpecimen:1_ExternalIdentifier:1_id * */ private String getConsolidatedKey(String key, String associatedObjectKey) { String keyWithClass = getUpdatedKey(key); String tempKey = keyWithClass.split("_")[0]; return tempKey + "_" + associatedObjectKey; } /** * This method is called by applet when submit method return success. It forwards to the report page. */ public ActionForward getResult(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { String target = (String) request.getParameter(Constants.MULTIPLE_SPECIMEN_RESULT); Collection specimenCollection = (Collection) request.getSession().getAttribute( Constants.SAVED_SPECIMEN_COLLECTION); request.getSession().setAttribute(Constants.SAVED_SPECIMEN_COLLECTION, null); request.setAttribute(Constants.SAVED_SPECIMEN_COLLECTION, specimenCollection); ActionMessages msgs = new ActionMessages(); msgs.add("success", new ActionMessage("multipleSpecimen.add.success", String .valueOf(specimenCollection.size()))); saveMessages(request, msgs); return actionMapping.findForward(target); } /** * This method processes input specimens map. * * 1. initialize map which contains for each specimen its selected class. * 2. If class is not selected for any specimen it throws exception * 3. It removes unneccessary keys(keys that are no longer required) from the map. * * @param specimenMap inputMap */ private void preprocessSpecimanMap(Map specimenMap) throws Exception { classMap = new HashMap(); int noOfSpecimens = Integer.parseInt((String) specimenMap .get(AppletConstants.NO_OF_SPECIMENS)); specimenMap.remove(AppletConstants.NO_OF_SPECIMENS); for (int i = 1; i <= noOfSpecimens; i++) { String classValue = (String) specimenMap.get(AppletConstants.SPECIMEN_PREFIX + i + "_" + "class"); if (classValue == null || classValue.trim().length() == 0 || classValue.equals("-- Select --")) { throw new Exception(ApplicationProperties.getValue("protocol.class.errMsg") + " for Specimen number " + i); } String quantityKey = AppletConstants.SPECIMEN_PREFIX + i + "_" + "Quantity_value"; String quantityValue = (String) specimenMap.get(quantityKey); try { Long.parseLong(quantityValue); } catch (NumberFormatException e) { throw new Exception("Please enter valid Quantity for Specimen number " + i); } classMap.put(String.valueOf(i), classValue); if (!classValue.equals("Molecular")) { specimenMap.remove(AppletConstants.SPECIMEN_PREFIX + i + "_" + "concentrationInMicrogramPerMicroliter"); } specimenMap.remove(AppletConstants.SPECIMEN_PREFIX + i + "_" + "class"); specimenMap.remove(AppletConstants.SPECIMEN_PREFIX + i + "_" + "StorageContainer_temp"); specimenMap.remove(AppletConstants.SPECIMEN_PREFIX + i + "_" + "derive"); // mandar : to remove the label entry. specimenMap.remove(AppletConstants.SPECIMEN_PREFIX + i + "_" + AppletConstants.MULTIPLE_SPECIMEN_LOCATION_LABEL); specimenMap.put(AppletConstants.SPECIMEN_PREFIX + i + "_" + "activityStatus", Constants.ACTIVITY_STATUS_ACTIVE); //specimenMap.put(AppletConstants.SPECIMEN_PREFIX + i + "_" + "available" ,new Boolean(true)); } } /** * This method saves collection of specimens to the database. * TODO Error handling. * @param request * @param specimenCollection */ private void insertSpecimens(HttpServletRequest request, Map specimenMap) throws Exception { IBizLogic bizLogic; bizLogic = AbstractBizLogicFactory.getBizLogic(ApplicationProperties .getValue("app.bizLogicFactory"), "getBizLogic", Constants.NEW_SPECIMEN_FORM_ID); SessionDataBean sessionBean = (SessionDataBean) request.getSession().getAttribute( Constants.SESSION_DATA); bizLogic.insert(specimenMap, sessionBean, Constants.HIBERNATE_DAO); } /** * This method changes map given by table model and updated following things. * 1. Appends each key with the selected class value. * * @param specimenMap * @return */ private Map appendClassValue(Map inputMap) { Map newMap = new HashMap(); if (inputMap == null) { return newMap; } Iterator it = inputMap.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); String newKey = getUpdatedKey(key); String value = String.valueOf(inputMap.get(key)); newMap.put(newKey, value); } return newMap; } /** * This method returns updated key depending on class selected for a specimen * * if user has selected Fluid as specimen class for specimen no 2 then for the key "Specimen:2_pathologicalStatus" * this method will return "FluidSpecimen:2_pathologicalStatus". * * @param key e.g. * @return */ private String getUpdatedKey(String key) { String specimenNo = key.substring(key.indexOf(":") + 1, key.indexOf("_")); return (String) classMap.get(specimenNo) + key; } /** * This method returns a map where * * key - Specimen Class in String form * | * |___value arrayList of corrosponding Specimen types. * * * @return map */ private Map getSpecimenClassTypeMap() { Map specimenClassTypeMap = new HashMap(); CDE specimenClassCDE = CDEManager.getCDEManager().getCDE(Constants.CDE_NAME_SPECIMEN_CLASS); Set setPV = specimenClassCDE.getPermissibleValues(); Iterator specimenClassItr = setPV.iterator(); while (specimenClassItr.hasNext()) { PermissibleValue pValue = (PermissibleValue) specimenClassItr.next(); Set subPV = pValue.getSubPermissibleValues(); Iterator specimenTypeItr = subPV.iterator(); List specimenType = new ArrayList(); specimenType.add(Constants.SELECT_OPTION); while (specimenTypeItr.hasNext()) { PermissibleValue specimenTypePV = (PermissibleValue) specimenTypeItr.next(); specimenType.add(specimenTypePV.getValue()); } specimenClassTypeMap.put(pValue.getValue(), specimenType.toArray()); } return specimenClassTypeMap; } private void processEvents(Collection specimenCollection, Map multipleSpecimenFormBeanMap) throws Exception { Iterator specimenCollectionIterator = specimenCollection.iterator(); //set default values for the specimen. int i = 1; while (specimenCollectionIterator.hasNext()) { Specimen specimen = (Specimen) specimenCollectionIterator.next(); NewSpecimenForm form = (NewSpecimenForm) multipleSpecimenFormBeanMap.get("Specimen:"+i+"_specimenEventCollection"); if(form == null) { throw new Exception("Give Events for specimen"+i); } else { Collection specimenEventCollection = new HashSet(); CollectionEventParametersForm collectionEvent = new CollectionEventParametersForm(); collectionEvent.setCollectionProcedure(form .getCollectionEventCollectionProcedure()); collectionEvent.setComments(form.getCollectionEventComments()); collectionEvent.setContainer(form.getCollectionEventContainer()); collectionEvent.setTimeInHours(form.getCollectionEventTimeInHours()); collectionEvent.setTimeInMinutes(form.getCollectionEventTimeInMinutes()); collectionEvent.setDateOfEvent(form.getCollectionEventdateOfEvent()); collectionEvent.setUserId(form.getCollectionEventUserId()); collectionEvent.setOperation(form.getOperation()); CollectionEventParameters collectionEventParameters = new CollectionEventParameters(); collectionEventParameters.setAllValues(collectionEvent); //collectionEventParameters.setSpecimen(specimen); Logger.out.debug("Before specimenEventCollection.size(): " + specimenEventCollection.size()); specimenEventCollection.add(collectionEventParameters); Logger.out.debug("After specimenEventCollection.size(): " + specimenEventCollection.size()); Logger.out.debug("...14-July-06... : CollectionEvent set"); Logger.out.debug("Setting Received event in specimen domain object"); //setting received event values ReceivedEventParametersForm receivedEvent = new ReceivedEventParametersForm(); receivedEvent.setComments(form.getReceivedEventComments()); receivedEvent.setDateOfEvent(form.getReceivedEventDateOfEvent()); receivedEvent.setReceivedQuality(form.getReceivedEventReceivedQuality()); receivedEvent.setUserId(form.getReceivedEventUserId()); receivedEvent.setTimeInMinutes(form.getReceivedEventTimeInMinutes()); receivedEvent.setTimeInHours(form.getReceivedEventTimeInHours()); receivedEvent.setOperation(form.getOperation()); ReceivedEventParameters receivedEventParameters = new ReceivedEventParameters(); receivedEventParameters.setAllValues(receivedEvent); //receivedEventParameters.setSpecimen(specimen); Logger.out.debug("Before specimenEventCollection.size(): " + specimenEventCollection.size()); specimenEventCollection.add(receivedEventParameters); Logger.out.debug("After specimenEventCollection.size(): " + specimenEventCollection.size()); specimen.setSpecimenEventCollection(specimenEventCollection); Logger.out.debug("...14-July-06... : ReceivedEvent set"); } i++; } } private ArrayList getNameStringArray(List specimenGroupList) { ArrayList returnArrayList =new ArrayList(); for(int cnt=0;cnt<specimenGroupList.size();cnt++ ) { NameValueBean bean = (NameValueBean)specimenGroupList.get(cnt ); returnArrayList.add(bean.getName()); } return returnArrayList; } }
added validation and changed msg for event SVN-Revision: 4680
WEB-INF/src/edu/wustl/catissuecore/action/MultipleSpecimenAppletAction.java
added validation and changed msg for event
<ide><path>EB-INF/src/edu/wustl/catissuecore/action/MultipleSpecimenAppletAction.java <ide> { <ide> throw new Exception("Please enter valid Quantity for Specimen number " + i); <ide> } <add> <add> Long storageContainer = (Long) specimenMap.get(AppletConstants.SPECIMEN_PREFIX + i + "_" + "StorageContainer_id"); <ide> <add> if (storageContainer == null) <add> { <add> throw new Exception("Please give valid Storage Position for Specimen number " + i); <add> } <add> <ide> classMap.put(String.valueOf(i), classValue); <ide> <ide> if (!classValue.equals("Molecular")) <ide> NewSpecimenForm form = (NewSpecimenForm) multipleSpecimenFormBeanMap.get("Specimen:"+i+"_specimenEventCollection"); <ide> if(form == null) <ide> { <del> throw new Exception("Give Events for specimen"+i); <add> throw new Exception("Please Give Events for specimen number "+i); <ide> } <ide> else <ide> {
Java
apache-2.0
719393f8bac8500647ef41ec09f984af4d4174a0
0
jalaziz/cens-whatsinvasive
package edu.ucla.cens.whatsinvasive; import java.io.File; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import android.app.Activity; import android.app.ListActivity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.os.Bundle; import android.os.Handler; import android.text.util.Linkify; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnCreateContextMenuListener; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ResourceCursorAdapter; import android.widget.TextView; import android.widget.TwoLineListItem; import android.widget.AdapterView.OnItemClickListener; import edu.ucla.cens.whatsinvasive.data.PhotoDatabase; import edu.ucla.cens.whatsinvasive.data.PhotoDatabase.PhotoDatabaseRow; import edu.ucla.cens.whatsinvasive.tools.Media; public class Queue extends ListActivity implements PhotoDatabase.OnChangeListener { private final int CONTEXT_VIEW = 1; private final int CONTEXT_EDIT_NOTE = 2; private final int CONTEXT_REMOVE = 3; private static final int ACTIVITY_EDIT_NOTE = 0; private PhotoDatabase mDatabase; private Cursor mCursor; private Handler mHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.queue); this.setTitle(R.string.title_queue); mHandler = new Handler(); TextView extrat = new TextView(this); extrat.setAutoLinkMask(Linkify.WEB_URLS); extrat.setText(getString(R.string.queue_message_full)); extrat.setTextSize(18); extrat.setClickable(false); extrat.setLongClickable(false); getListView().addFooterView(extrat); getListView().setFooterDividersEnabled(true); mDatabase = new PhotoDatabase(this); getListView().setOnItemClickListener(new OnItemClickListener(){ public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { if(!(arg1 instanceof TextView) ) arg1.performLongClick(); }}); getListView().setOnCreateContextMenuListener(new OnCreateContextMenuListener(){ public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; TagData data = (TagData) info.targetView.getTag(); if(data != null){ menu.setHeaderTitle(getString(R.string.queue_actions)); menu.add(0, CONTEXT_VIEW, 1, getString(R.string.queue_view)); if(data.uploaded == null) { menu.add(0, CONTEXT_EDIT_NOTE, 2, getString(R.string.queue_edit_note)); menu.add(0, CONTEXT_REMOVE, 3, getString(R.string.queue_do_not_upload)); } } } }); } public void onDatabseChanged(PhotoDatabase source) { mHandler.post(new Runnable() { public void run() { if(Queue.this.mCursor != null) Queue.this.mCursor.requery(); } }); } @Override protected void onResume() { mDatabase.tryOpen(); PhotoDatabase.addChangeListener(this); mCursor = mDatabase.getReadCursor(); startManagingCursor(mCursor); setListAdapter(new QueueAdapter(this, mCursor)); super.onResume(); } @Override protected void onPause() { // We have to close the database here so that the other // activities (e.g. ViewTag) can use the PhotoDatabase PhotoDatabase.removeChangeListener(this); mDatabase.close(); super.onPause(); } @Override protected void onStop() { // We have to close the cursor here and not in the onPause method // if we want to avoid the empty view from being displayed before the // view is killed mCursor.close(); super.onStop(); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo(); TagData data = (TagData) menuInfo.targetView.getTag(); switch (item.getItemId()) { case CONTEXT_VIEW: Intent intent = new Intent(this, ViewTag.class); intent.putExtra("id", data.id); startActivity(intent); break; case CONTEXT_EDIT_NOTE: PhotoDatabaseRow row; row = mDatabase.fetchPhoto(data.id); Intent intent2 = new Intent(this, NoteEdit.class); intent2.putExtra("id", data.id); String title = getString(R.string.note_title_prefix) + " " + row.tagsValue; intent2.putExtra("title", title); intent2.putExtra("note", row.noteValue); startActivityForResult(intent2, ACTIVITY_EDIT_NOTE); break; case CONTEXT_REMOVE: mDatabase.deletePhoto(data.id); if(data.filename!=null) (new File(data.filename)).delete(); break; } return false; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch(requestCode) { case ACTIVITY_EDIT_NOTE: if(resultCode == Activity.RESULT_OK) { int rowId = data.getIntExtra("id", -1); String note = data.getStringExtra("note"); mDatabase.tryOpen(); mDatabase.updateNote(rowId, note); break; } } } private class QueueAdapter extends ResourceCursorAdapter { public QueueAdapter(Context context, Cursor c) { super(context, R.layout.queue_list_item, c, true); } @Override public void bindView(View v, Context context, Cursor cursor) { int indexTags = cursor.getColumnIndexOrThrow(PhotoDatabase.KEY_PHOTO_TAGS); int indexTime = cursor.getColumnIndexOrThrow(PhotoDatabase.KEY_PHOTO_TIME); int indexPhoto = cursor.getColumnIndexOrThrow(PhotoDatabase.KEY_PHOTO_FILENAME); int indexUploaded = cursor.getColumnIndexOrThrow(PhotoDatabase.KEY_PHOTO_UPLOADED); int indexLat = cursor.getColumnIndexOrThrow(PhotoDatabase.KEY_PHOTO_LATITUDE); int indexLon = cursor.getColumnIndexOrThrow(PhotoDatabase.KEY_PHOTO_LONGITUDE); TwoLineListItem view = (TwoLineListItem) v; view.getText1().setText((cursor.getCount() - cursor.getPosition()) +") "+ cursor.getString(indexTags)); view.getText1().setTextSize(16); String time = cursor.getString(indexTime); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); df.setTimeZone(TimeZone.getTimeZone("UTC")); Date date = new Date(0); try { date = df.parse(time); } catch (ParseException e) { e.printStackTrace(); } df.setTimeZone(TimeZone.getDefault()); String text = getString(R.string.tag_tagged_at) + " " + df.format(date); if(!cursor.isNull(indexUploaded)) text += "\nUploaded "+ cursor.getString(indexUploaded); view.getText2().setText(text); TagData data = new TagData(); ImageView image = (ImageView) view.findViewById(android.R.id.selectedIcon); if(cursor.getString(indexPhoto) != null){ String photo = cursor.getString(indexPhoto); if((new File(photo)).exists()){ data.filename = photo; if(cursor.isNull(indexUploaded)) image.setImageBitmap(resizeImage(photo, false)); else image.setImageBitmap(resizeImage(photo, true)); }else{ image.setImageBitmap(null); } }else{ Bitmap preview = Bitmap.createBitmap(80, 60, Bitmap.Config.ARGB_8888); if(cursor.isNull(indexUploaded)){ image.setImageBitmap(preview); }else{ Bitmap overlay = BitmapFactory.decodeResource(Queue.this.getResources(), R.drawable.btn_check_buttonless_on); Canvas canvas = new Canvas(preview); canvas.drawBitmap(overlay, 26, 10, null); image.setImageBitmap(preview); } } data.id = cursor.getInt(cursor.getColumnIndex(PhotoDatabase.KEY_PHOTO_ROWID)); data.lat = cursor.getString(indexLat); data.lon = cursor.getString(indexLon); data.uploaded = cursor.getString(indexUploaded); v.setTag(data); } private Bitmap resizeImage(String path, boolean uploaded){ Bitmap thumb = Media.resizeImage(path, new Media.Size(48,48)); if(uploaded) { Bitmap preview = Bitmap.createBitmap(thumb.getWidth(), thumb.getHeight(), Bitmap.Config.ARGB_8888); Bitmap overlay = BitmapFactory.decodeResource(Queue.this.getResources(), R.drawable.btn_check_buttonless_on); Canvas canvas = new Canvas(preview); canvas.drawBitmap(thumb, 0, 0, null); canvas.drawBitmap(overlay, (thumb.getWidth()/2)-14, 10, null); return preview; } else { return thumb; } } } private class TagData { public String lat; public String lon; public int id; public String filename; public String uploaded; } }
src/edu/ucla/cens/whatsinvasive/Queue.java
package edu.ucla.cens.whatsinvasive; import java.io.File; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import android.app.Activity; import android.app.ListActivity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.text.util.Linkify; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnCreateContextMenuListener; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ResourceCursorAdapter; import android.widget.TextView; import android.widget.Toast; import android.widget.TwoLineListItem; import android.widget.AdapterView.OnItemClickListener; import edu.ucla.cens.whatsinvasive.data.PhotoDatabase; import edu.ucla.cens.whatsinvasive.data.PhotoDatabase.PhotoDatabaseRow; import edu.ucla.cens.whatsinvasive.tools.Media; public class Queue extends ListActivity implements PhotoDatabase.OnChangeListener { private final int CONTEXT_SHOW_ON_MAP = 0; private final int CONTEXT_VIEW = 1; private final int CONTEXT_EDIT_NOTE = 2; private final int CONTEXT_REMOVE = 3; private static final int ACTIVITY_EDIT_NOTE = 0; private PhotoDatabase mDatabase; private Cursor mCursor; private Handler mHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.queue); this.setTitle(R.string.title_queue); mHandler = new Handler(); TextView extrat = new TextView(this); extrat.setAutoLinkMask(Linkify.WEB_URLS); extrat.setText(getString(R.string.queue_message_full)); extrat.setTextSize(18); extrat.setClickable(false); extrat.setLongClickable(false); getListView().addFooterView(extrat); getListView().setFooterDividersEnabled(true); mDatabase = new PhotoDatabase(this); getListView().setOnItemClickListener(new OnItemClickListener(){ public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { if(!(arg1 instanceof TextView) ) arg1.performLongClick(); }}); getListView().setOnCreateContextMenuListener(new OnCreateContextMenuListener(){ public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; TagData data = (TagData) info.targetView.getTag(); if(data != null){ menu.setHeaderTitle(getString(R.string.queue_actions)); menu.add(0, CONTEXT_SHOW_ON_MAP, 0, getString(R.string.queue_show_map)); menu.add(0, CONTEXT_VIEW, 1, getString(R.string.queue_view)); if(data.uploaded == null) { menu.add(0, CONTEXT_EDIT_NOTE, 2, getString(R.string.queue_edit_note)); menu.add(0, CONTEXT_REMOVE, 3, getString(R.string.queue_do_not_upload)); } } } }); } public void onDatabseChanged(PhotoDatabase source) { mHandler.post(new Runnable() { public void run() { if(Queue.this.mCursor != null) Queue.this.mCursor.requery(); } }); } @Override protected void onResume() { mDatabase.tryOpen(); PhotoDatabase.addChangeListener(this); mCursor = mDatabase.getReadCursor(); startManagingCursor(mCursor); setListAdapter(new QueueAdapter(this, mCursor)); super.onResume(); } @Override protected void onPause() { // We have to close the database here so that the other // activities (e.g. ViewTag) can use the PhotoDatabase PhotoDatabase.removeChangeListener(this); mDatabase.close(); super.onPause(); } @Override protected void onStop() { // We have to close the cursor here and not in the onPause method // if we want to avoid the empty view from being displayed before the // view is killed mCursor.close(); super.onStop(); } private void showOnMap(String lat, String lon){ if(lat != null && lon != null){ Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:"+ lat +","+ lon)); Queue.this.startActivity(intent); } else { Toast.makeText(Queue.this, getString(R.string.queue_no_location), Toast.LENGTH_SHORT).show(); } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo(); TagData data = (TagData) menuInfo.targetView.getTag(); switch (item.getItemId()) { case CONTEXT_SHOW_ON_MAP: showOnMap(data.lat, data.lon); break; case CONTEXT_VIEW: Intent intent = new Intent(this, ViewTag.class); intent.putExtra("id", data.id); startActivity(intent); break; case CONTEXT_EDIT_NOTE: PhotoDatabaseRow row; row = mDatabase.fetchPhoto(data.id); Intent intent2 = new Intent(this, NoteEdit.class); intent2.putExtra("id", data.id); String title = getString(R.string.note_title_prefix) + " " + row.tagsValue; intent2.putExtra("title", title); intent2.putExtra("note", row.noteValue); startActivityForResult(intent2, ACTIVITY_EDIT_NOTE); break; case CONTEXT_REMOVE: mDatabase.deletePhoto(data.id); if(data.filename!=null) (new File(data.filename)).delete(); break; } return false; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch(requestCode) { case ACTIVITY_EDIT_NOTE: if(resultCode == Activity.RESULT_OK) { int rowId = data.getIntExtra("id", -1); String note = data.getStringExtra("note"); mDatabase.tryOpen(); mDatabase.updateNote(rowId, note); break; } } } private class QueueAdapter extends ResourceCursorAdapter { public QueueAdapter(Context context, Cursor c) { super(context, R.layout.queue_list_item, c, true); } @Override public void bindView(View v, Context context, Cursor cursor) { int indexTags = cursor.getColumnIndexOrThrow(PhotoDatabase.KEY_PHOTO_TAGS); int indexTime = cursor.getColumnIndexOrThrow(PhotoDatabase.KEY_PHOTO_TIME); int indexPhoto = cursor.getColumnIndexOrThrow(PhotoDatabase.KEY_PHOTO_FILENAME); int indexUploaded = cursor.getColumnIndexOrThrow(PhotoDatabase.KEY_PHOTO_UPLOADED); int indexLat = cursor.getColumnIndexOrThrow(PhotoDatabase.KEY_PHOTO_LATITUDE); int indexLon = cursor.getColumnIndexOrThrow(PhotoDatabase.KEY_PHOTO_LONGITUDE); TwoLineListItem view = (TwoLineListItem) v; view.getText1().setText((cursor.getCount() - cursor.getPosition()) +") "+ cursor.getString(indexTags)); view.getText1().setTextSize(16); String time = cursor.getString(indexTime); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); df.setTimeZone(TimeZone.getTimeZone("UTC")); Date date = new Date(0); try { date = df.parse(time); } catch (ParseException e) { e.printStackTrace(); } df.setTimeZone(TimeZone.getDefault()); String text = getString(R.string.tag_tagged_at) + " " + df.format(date); if(!cursor.isNull(indexUploaded)) text += "\nUploaded "+ cursor.getString(indexUploaded); view.getText2().setText(text); TagData data = new TagData(); ImageView image = (ImageView) view.findViewById(android.R.id.selectedIcon); if(cursor.getString(indexPhoto) != null){ String photo = cursor.getString(indexPhoto); if((new File(photo)).exists()){ data.filename = photo; if(cursor.isNull(indexUploaded)) image.setImageBitmap(resizeImage(photo, false)); else image.setImageBitmap(resizeImage(photo, true)); }else{ image.setImageBitmap(null); } }else{ Bitmap preview = Bitmap.createBitmap(80, 60, Bitmap.Config.ARGB_8888); if(cursor.isNull(indexUploaded)){ image.setImageBitmap(preview); }else{ Bitmap overlay = BitmapFactory.decodeResource(Queue.this.getResources(), R.drawable.btn_check_buttonless_on); Canvas canvas = new Canvas(preview); canvas.drawBitmap(overlay, 26, 10, null); image.setImageBitmap(preview); } } data.id = cursor.getInt(cursor.getColumnIndex(PhotoDatabase.KEY_PHOTO_ROWID)); data.lat = cursor.getString(indexLat); data.lon = cursor.getString(indexLon); data.uploaded = cursor.getString(indexUploaded); v.setTag(data); } private Bitmap resizeImage(String path, boolean uploaded){ Bitmap thumb = Media.resizeImage(path, new Media.Size(48,48)); if(uploaded) { Bitmap preview = Bitmap.createBitmap(thumb.getWidth(), thumb.getHeight(), Bitmap.Config.ARGB_8888); Bitmap overlay = BitmapFactory.decodeResource(Queue.this.getResources(), R.drawable.btn_check_buttonless_on); Canvas canvas = new Canvas(preview); canvas.drawBitmap(thumb, 0, 0, null); canvas.drawBitmap(overlay, (thumb.getWidth()/2)-14, 10, null); return preview; } else { return thumb; } } } private class TagData { public String lat; public String lon; public int id; public String filename; public String uploaded; } }
Removed "View on Map" from Queue.
src/edu/ucla/cens/whatsinvasive/Queue.java
Removed "View on Map" from Queue.
<ide><path>rc/edu/ucla/cens/whatsinvasive/Queue.java <ide> import android.graphics.Bitmap; <ide> import android.graphics.BitmapFactory; <ide> import android.graphics.Canvas; <del>import android.net.Uri; <ide> import android.os.Bundle; <ide> import android.os.Handler; <ide> import android.text.util.Linkify; <ide> import android.widget.ImageView; <ide> import android.widget.ResourceCursorAdapter; <ide> import android.widget.TextView; <del>import android.widget.Toast; <ide> import android.widget.TwoLineListItem; <ide> import android.widget.AdapterView.OnItemClickListener; <ide> import edu.ucla.cens.whatsinvasive.data.PhotoDatabase; <ide> import edu.ucla.cens.whatsinvasive.tools.Media; <ide> <ide> public class Queue extends ListActivity implements PhotoDatabase.OnChangeListener { <del> private final int CONTEXT_SHOW_ON_MAP = 0; <ide> private final int CONTEXT_VIEW = 1; <ide> private final int CONTEXT_EDIT_NOTE = 2; <ide> private final int CONTEXT_REMOVE = 3; <ide> AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; <ide> TagData data = (TagData) info.targetView.getTag(); <ide> if(data != null){ <del> menu.setHeaderTitle(getString(R.string.queue_actions)); <del> menu.add(0, CONTEXT_SHOW_ON_MAP, 0, getString(R.string.queue_show_map)); <add> menu.setHeaderTitle(getString(R.string.queue_actions)); <ide> menu.add(0, CONTEXT_VIEW, 1, getString(R.string.queue_view)); <ide> if(data.uploaded == null) { <ide> menu.add(0, CONTEXT_EDIT_NOTE, 2, getString(R.string.queue_edit_note)); <ide> super.onStop(); <ide> } <ide> <del> private void showOnMap(String lat, String lon){ <del> if(lat != null && lon != null){ <del> Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:"+ lat +","+ lon)); <del> Queue.this.startActivity(intent); <del> } else { <del> Toast.makeText(Queue.this, getString(R.string.queue_no_location), Toast.LENGTH_SHORT).show(); <del> } <del> } <del> <ide> @Override <ide> public boolean onContextItemSelected(MenuItem item) { <ide> AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo(); <ide> TagData data = (TagData) menuInfo.targetView.getTag(); <ide> <ide> switch (item.getItemId()) { <del> case CONTEXT_SHOW_ON_MAP: <del> showOnMap(data.lat, data.lon); <del> <del> break; <ide> case CONTEXT_VIEW: <ide> Intent intent = new Intent(this, ViewTag.class); <ide> intent.putExtra("id", data.id);
Java
epl-1.0
20c09a9dbb225242b5bbd265aff7489061b459e7
0
ChristophSonnberger/crypto,jcryptool/crypto,kevinott/crypto,tassadarius/crypto,kevinott/crypto,ChristophSonnberger/crypto,jcryptool/crypto,tassadarius/crypto
package org.jcryptool.visual.sig.algorithm; import java.security.*; import org.jcryptool.core.logging.utils.LogUtil; import org.jcryptool.visual.sig.SigPlugin; public class SigGeneration { public static String signature; /** * This method signed a hash stored in Hash.jave with a given signature * method. * * @param signaturemethod * Chosen signature method to sign the hash. * @param input * hash form Hash.java * @return * @throws Exception */ public static byte[] SignInput(String signaturemethod, byte[] input) throws Exception { // get String to generate the key String keySig = null; // Generators are currently available for RSA and DSA. if (signaturemethod == "SHA1withDSA" || signaturemethod == "SHA1withECDSA" || signaturemethod == "SHA256withECDSA" || signaturemethod == "SHA384withECDSA" || signaturemethod == "SHA512withECDSA") { keySig = "DSA"; } else { keySig = "RSA"; } byte[] signatureArray = null; try { // Generate keypair KeyPairGenerator keyGen = KeyPairGenerator.getInstance(keySig); keyGen.initialize(1024); KeyPair key = keyGen.generateKeyPair(); // Get a signature object using the MD5 and RSA combo // and sign the input with the private key Signature sig = Signature.getInstance(signaturemethod); sig.initSign(key.getPrivate()); sig.update(input); signatureArray = sig.sign(); signature = new String(Hash.bytesToHex(signatureArray)); // Hex // String org.jcryptool.visual.sig.algorithm.Input.signature = signatureArray; return signatureArray; } catch (Exception ex) { LogUtil.logError(SigPlugin.PLUGIN_ID, ex); } return signatureArray; } }
org.jcryptool.visual.sig/src/org/jcryptool/visual/sig/algorithm/SigGeneration.java
package org.jcryptool.visual.sig.algorithm; import java.security.*; import org.jcryptool.core.logging.utils.LogUtil; import org.jcryptool.visual.sig.SigPlugin; public class SigGeneration { public static String signature; /** * This method signed a hash stored in Hash.jave with a given signature * method. * * @param signaturemethod * Chosen signature method to sign the hash. * @param input * hash form Hash.java * @return * @throws Exception */ public static byte[] SignInput(String signaturemethod, byte[] input) throws Exception { // get String to generate the key String keySig = null; // Generators are currently available for RSA and DSA. if (signaturemethod == "MD5withRSA" || signaturemethod == "SHA1withRSA" || signaturemethod == "SHA256withRSA" || signaturemethod == "SHA384withRSA" || signaturemethod == "SHA512withRSA" || signaturemethod == "SHA1withRSAandMGF1" || signaturemethod == "SHA256withRSAandMGF1" || signaturemethod == "SHA384withRSAandMGF1" || signaturemethod == "SHA512withRSAandMGF1") { keySig = "RSA"; } else { keySig = "DSA"; } byte[] signatureArray = null; try { // Generate keypair KeyPairGenerator keyGen = KeyPairGenerator.getInstance(keySig); keyGen.initialize(1024); KeyPair key = keyGen.generateKeyPair(); // Get a signature object using the MD5 and RSA combo // and sign the input with the private key Signature sig = Signature.getInstance(signaturemethod); sig.initSign(key.getPrivate()); sig.update(input); signatureArray = sig.sign(); signature = new String(Hash.bytesToHex(signatureArray)); // Hex // String org.jcryptool.visual.sig.algorithm.Input.signature = signatureArray; return signatureArray; } catch (Exception ex) { LogUtil.logError(SigPlugin.PLUGIN_ID, ex); } return signatureArray; } }
Changed if-statement to get String to generate key.
org.jcryptool.visual.sig/src/org/jcryptool/visual/sig/algorithm/SigGeneration.java
Changed if-statement to get String to generate key.
<ide><path>rg.jcryptool.visual.sig/src/org/jcryptool/visual/sig/algorithm/SigGeneration.java <ide> // get String to generate the key <ide> String keySig = null; <ide> // Generators are currently available for RSA and DSA. <del> if (signaturemethod == "MD5withRSA" || signaturemethod == "SHA1withRSA" <del> || signaturemethod == "SHA256withRSA" <del> || signaturemethod == "SHA384withRSA" <del> || signaturemethod == "SHA512withRSA" <del> || signaturemethod == "SHA1withRSAandMGF1" <del> || signaturemethod == "SHA256withRSAandMGF1" <del> || signaturemethod == "SHA384withRSAandMGF1" <del> || signaturemethod == "SHA512withRSAandMGF1") { <add> if (signaturemethod == "SHA1withDSA" <add> || signaturemethod == "SHA1withECDSA" <add> || signaturemethod == "SHA256withECDSA" <add> || signaturemethod == "SHA384withECDSA" <add> || signaturemethod == "SHA512withECDSA") { <add> keySig = "DSA"; <add> } else { <ide> keySig = "RSA"; <del> } else { <del> keySig = "DSA"; <ide> } <ide> <ide> byte[] signatureArray = null;
JavaScript
mit
5e6a692795dd648ce8bec7352a7965909e391bba
0
plyo/react-color,eibay/react-color,conorhastings/react-spectrum,kazi1010feni/react-color,JedWatson/react-color,JunisphereSystemsAG/react-color,Scratch-it/react-color,fikriauliya/react-color,tommy351/react-color,MingNeo/react-color,tastemade/react-color,mWater/react-color,Drooids/react-color,fikriauliya/react-color,hellocreep/react-color,socialtables/react-spectrum,Scratch-it/react-color,OhJia/react-color,casesandberg/react-color,socialtables/react-color,beni55/react-color,beni55/react-color,keppelen/react-color,mWater/react-color,rickyvetter/react-color,liuyanghejerry/react-color,conorhastings/react-color,9o/react-color,bradparks/react-color,keppelen/react-color,fungxu/react-color,eibay/react-color,sent1nel/react-color,kidaa/react-color,sent1nel/react-color,OhJia/react-color,sugarshin/react-color,fungxu/react-color,Drooids/react-color,bradparks/react-color,liuyanghejerry/react-color,socialtables/react-color,JunisphereSystemsAG/react-color,JonathanMatthey/react-color,carabina/react-color,MingNeo/react-color,plyo/react-color,hellocreep/react-color,9o/react-color,sugarshin/react-color,rickyvetter/react-color,JonathanMatthey/react-color,tastemade/react-color,carabina/react-color,conorhastings/react-color,kazi1010feni/react-color,tommy351/react-color,kidaa/react-color
var gulp = require('gulp'); var gutil = require('gulp-util'); var webpack = require('webpack'); var WebpackDevServer = require('webpack-dev-server'); var webpackConfig = require('./webpack.config.js'); var babel = require('gulp-babel'); var mapStyles = require('react-map-styles'); var modify = require('gulp-modify'); gulp.task('docs', function(callback) { var port = 9100; var docs = Object.create(webpackConfig); docs.entry = ['webpack-dev-server/client?http://localhost:' + port, 'webpack/hot/dev-server', docs.entry[0]]; docs.module.loaders[0].loaders.unshift('react-hot-loader'); docs.module.loaders[1].loaders.unshift('react-hot-loader'); docs.devtool = 'eval'; docs.debug = true; new WebpackDevServer(webpack(docs), { publicPath: '/' + docs.output.publicPath, hot: true, stats: { cached: false, cachedAssets: false, colors: true, exclude: ['node_modules', 'components'], }, }).listen(port, 'localhost', function(err) { if (err) throw new gutil.PluginError('webpack-dev-server', err); gutil.log('[webpack-dev-server]', 'http://localhost:' + port + '/'); }); }); gulp.task('build', function(done) { var build = Object.create(webpackConfig); build.plugins = [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production'), }, }), new webpack.optimize.DedupePlugin(), ]; webpack(build, function(err, stats) { if (err) { throw new Error(err); } done(); }); }); gulp.task('bundle', function(done) { return gulp.src('./src/**/*') .pipe(modify({ fileModifier: function(file, contents) { return mapStyles(contents); }, })) .pipe(babel()) .pipe(gulp.dest('lib')); }); gulp.task('bundle-material', function(done) { return gulp.src('./modules/react-material-design/src/**/*') .pipe(modify({ fileModifier: function(file, contents) { return mapStyles(contents); }, })) .pipe(babel()) .pipe(gulp.dest('./modules/react-material-design/lib')); }); gulp.task('bundle-docs', function(done) { return gulp.src('./modules/react-docs/src/**/*') .pipe(modify({ fileModifier: function(file, contents) { return mapStyles(contents); }, })) .pipe(babel()) .pipe(gulp.dest('./modules/react-docs/lib')); }); gulp.task('bundle-layout', function(done) { return gulp.src('./modules/react-basic-layout/src/**/*') .pipe(modify({ fileModifier: function(file, contents) { return mapStyles(contents); }, })) .pipe(babel()) .pipe(gulp.dest('./modules/react-basic-layout/lib')); }); gulp.task('bundle-move', function(done) { return gulp.src('./modules/react-move/src/**/*') .pipe(modify({ fileModifier: function(file, contents) { return mapStyles(contents); }, })) .pipe(babel()) .pipe(gulp.dest('./modules/react-move/lib')); }); gulp.task('prod', ['build', 'bundle', 'bundle-material', 'bundle-docs', 'bundle-layout', 'bundle-move']);
gulpfile.js
var gulp = require('gulp'); var gutil = require('gulp-util'); var webpack = require('webpack'); var WebpackDevServer = require('webpack-dev-server'); var webpackConfig = require('./webpack.config.js'); var babel = require('gulp-babel'); var mapStyles = require('react-map-styles'); var modify = require('gulp-modify'); gulp.task('docs', function(callback) { var port = 9100; var docs = Object.create(webpackConfig); docs.entry = ['webpack-dev-server/client?http://localhost:' + port, 'webpack/hot/dev-server', docs.entry[0]]; docs.module.loaders[0].loaders.unshift('react-hot-loader'); docs.module.loaders[1].loaders.unshift('react-hot-loader'); docs.devtool = 'eval'; docs.debug = true; new WebpackDevServer(webpack(docs), { publicPath: '/' + docs.output.publicPath, hot: true, stats: { cached: false, cachedAssets: false, colors: true, exclude: ['node_modules', 'components'], }, }).listen(port, 'localhost', function(err) { if (err) throw new gutil.PluginError('webpack-dev-server', err); gutil.log('[webpack-dev-server]', 'http://localhost:' + port + '/'); }); }); gulp.task('build', function(done) { var build = Object.create(webpackConfig); build.plugins = [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production'), }, }), new webpack.optimize.DedupePlugin(), ]; webpack(build, function(err, stats) { if (err) { throw new Error(err); } done(); }); }); gulp.task('bundle', function(done) { return gulp.src('./src/**/*') .pipe(modify({ fileModifier: function(file, contents) { return mapStyles(contents); }, })) .pipe(babel()) .pipe(gulp.dest('lib')); }); gulp.task('bundle-material', function(done) { return gulp.src('./modules/react-material-design/src/**/*') .pipe(modify({ fileModifier: function(file, contents) { return mapStyles(contents); }, })) .pipe(babel()) .pipe(gulp.dest('./modules/react-material-design/lib')); }); gulp.task('bundle-docs', function(done) { return gulp.src('./modules/react-docs/src/**/*') .pipe(modify({ fileModifier: function(file, contents) { return mapStyles(contents); }, })) .pipe(babel()) .pipe(gulp.dest('./modules/react-docs/lib')); }); gulp.task('bundle-layout', function(done) { return gulp.src('./modules/react-basic-layout/src/**/*') .pipe(modify({ fileModifier: function(file, contents) { return mapStyles(contents); }, })) .pipe(babel()) .pipe(gulp.dest('./modules/react-basic-layout/lib')); }); gulp.task('bundle-move', function(done) { return gulp.src('./modules/react-move/src/**/*') .pipe(modify({ fileModifier: function(file, contents) { return mapStyles(contents); }, })) .pipe(babel()) .pipe(gulp.dest('./modules/react-move/lib')); });
gulp prod
gulpfile.js
gulp prod
<ide><path>ulpfile.js <ide> .pipe(babel()) <ide> .pipe(gulp.dest('./modules/react-move/lib')); <ide> }); <add> <add>gulp.task('prod', ['build', 'bundle', 'bundle-material', 'bundle-docs', 'bundle-layout', 'bundle-move']);
JavaScript
mit
0d4fcce7b8c86b6cf5b41521ca4bebde0b44474c
0
josephbaena/CS147-Project,josephbaena/CS147-Project
var models = require('../models'); exports.view = function(req, res) { var sessionEmail = req.session.email; if (sessionEmail != null && req.session.fb_id == null) { console.log(req.session.email); models.User.find({"email": req.session.email}, function (err, user) { var dept_nums = user[0]["courses"]; //array of course dept_num models.Course.find({ 'dept_num': { $in : dept_nums} }, function(err, courses) { if (err) throw err; var input = { "courses": courses, "user": user[0] } console.log("MAAAAGIC!"); console.log(input); res.render('home', input); return; }); var input = { "courses": all_courses, "user": user[0] } console.log(input + "sessionEmail side"); res.render('home', input); } ); } else if(req.session.fb_id != null){ models.User.find({"fb_id": req.session.fb_id}, function (err, user) { var dept_nums = user[0]["courses"]; //array of course dept_num console.log(user[0]); if(user[0].length == 0 || dept_nums.length == 0){ render('home', []); return; } all_courses = []; console.log(dept_nums.length); for (var i = 0; i < dept_nums.length; i++) { models.Course.find({"dept_num": dept_nums[i]}, function (err, course) { console.log(course); console.log(course[0]); all_courses.push(course[0]); } ); } var input = { "courses": all_courses, "user": user[0] } console.log(input); res.render('home', input); } ); } else { // not logged in -> send to home page //console.log() res.render('index', {}); } };
routes/home.js
var models = require('../models'); exports.view = function(req, res) { var sessionEmail = req.session.email; if (sessionEmail != null && req.session.fb_id == null) { console.log(req.session.email); models.User.find({"email": req.session.email}, function (err, user) { var dept_nums = user[0]["courses"]; //array of course dept_num models.Course.find({ 'dept_num': { $in : dept_nums} }, function(err, courses) { if (err) throw err; var input = { "courses": courses, "user": user[0] } console.log("MAAAAGIC!"); console.log(input); res.render('home', input); return; }); var input = { "courses": all_courses, "user": user[0] } console.log(input + "sessionEmail side"); res.render('home', input); } ); } else if(req.session.fb_id != null){ models.User.find({"fb_id": req.session.fb_id}, function (err, user) { var dept_nums = user[0]["courses"]; //array of course dept_num console.log(user[0]); if(user[0].length == 0 || dept_nums.length == 0){ render('home', []); return; } all_courses = []; console.log(dept_nums.length); for (var i = 0; i < dept_nums.length; i++) { models.Course.find({"dept_num": dept_nums[i]}, function (err, course) { all_courses.push(course[0]); } ); } var input = { "courses": all_courses, "user": user[0] } console.log(input); res.render('home', input); } ); } else { // not logged in -> send to home page //console.log() res.render('index', {}); } };
fb.13
routes/home.js
fb.13
<ide><path>outes/home.js <ide> for (var i = 0; i < dept_nums.length; i++) { <ide> models.Course.find({"dept_num": dept_nums[i]}, <ide> function (err, course) { <add> console.log(course); <add> console.log(course[0]); <ide> all_courses.push(course[0]); <ide> } <ide> );
Java
mit
error: pathspec 'src/main/java/interpres/ast/VirtualExpression.java' did not match any file(s) known to git
ad307d8e3f359612e00069f3beca5392912801db
1
thomasbrus/interpres
package interpres.ast; import interpres.language.DefinitionTable; import interpres.language.values.Value; public class VirtualExpression extends AST { private Value value; public VirtualExpression(Value value) { this.value = value; } public Value evaluate(DefinitionTable definitionTable) { return this.value; } public Value quote() { return this.value; } }
src/main/java/interpres/ast/VirtualExpression.java
Added virtual expression (used in core.list.map)
src/main/java/interpres/ast/VirtualExpression.java
Added virtual expression (used in core.list.map)
<ide><path>rc/main/java/interpres/ast/VirtualExpression.java <add>package interpres.ast; <add> <add>import interpres.language.DefinitionTable; <add>import interpres.language.values.Value; <add> <add>public class VirtualExpression extends AST { <add> private Value value; <add> <add> public VirtualExpression(Value value) { <add> this.value = value; <add> } <add> <add> public Value evaluate(DefinitionTable definitionTable) { <add> return this.value; <add> } <add> <add> public Value quote() { <add> return this.value; <add> } <add>} <add>
Java
apache-2.0
31bd969d1cc3151c60cc01d1a9ecee4596100f17
0
tateshitah/jspwiki,tateshitah/jspwiki,tateshitah/jspwiki,tateshitah/jspwiki
package com.ecyrd.jspwiki; import junit.framework.*; import java.io.*; import java.util.*; import com.ecyrd.jspwiki.providers.*; public class WikiEngineTest extends TestCase { public static final String NAME1 = "Test1"; Properties props = new Properties(); WikiEngine engine; public WikiEngineTest( String s ) { super( s ); } public void setUp() throws Exception { props.load( getClass().getClassLoader().getResourceAsStream("/jspwiki.properties") ); engine = new TestEngine2(props); } public void tearDown() { String files = props.getProperty( FileSystemProvider.PROP_PAGEDIR ); File f = new File( files, NAME1+FileSystemProvider.FILE_EXT ); f.delete(); } public void testNonExistantDirectory() throws Exception { String tmpdir = System.getProperties().getProperty("java.tmpdir"); String dirname = "non-existant-directory"; String newdir = tmpdir + File.separator + dirname; props.setProperty( FileSystemProvider.PROP_PAGEDIR, newdir ); try { WikiEngine test = new TestEngine2( props ); fail( "Wiki did not warn about wrong property." ); } catch( WikiException e ) { // This is okay. } } public void testNonExistantDirProperty() throws Exception { props.remove( FileSystemProvider.PROP_PAGEDIR ); try { WikiEngine test = new TestEngine2( props ); fail( "Wiki did not warn about missing property." ); } catch( WikiException e ) { // This is okay. } } public void testNonExistantPage() throws Exception { String pagename = "Test1"; assertEquals( "Page already exists", false, engine.pageExists( pagename ) ); } public void testPutPage() { String text = "Foobar.\r\n"; String name = NAME1; engine.saveText( name, text ); assertEquals( "page does not exist", true, engine.pageExists( name ) ); assertEquals( "wrong content", text, engine.getText( name ) ); } public void testGetHTML() { String text = "''Foobar.''"; String name = NAME1; engine.saveText( name, text ); String data = engine.getHTML( name ); assertEquals( "<I>Foobar.</I>\n", data ); } public void testEncodeNameLatin1() { String name = "abc"; assertEquals( "abc%E5%E4%F6", engine.encodeName(name) ); } public void testEncodeNameUTF8() throws Exception { String name = "\u0041\u2262\u0391\u002E"; props.setProperty( WikiEngine.PROP_ENCODING, "UTF-8" ); WikiEngine engine = new TestEngine2( props ); assertEquals( "A%E2%89%A2%CE%91.", engine.encodeName(name) ); } public void testReadLinks() throws Exception { String src="Foobar. [Foobar]. Frobozz. [This is a link]."; Object[] result = engine.scanWikiLinks( src ).toArray(); assertEquals( "item 0", result[0], "Foobar" ); assertEquals( "item 1", result[1], "ThisIsALink" ); } /** * Tries to find an existing class. */ public void testFindClass() throws Exception { Class foo = WikiEngine.findWikiClass( "WikiPage", "com.ecyrd.jspwiki" ); assertEquals( foo.getName(), "com.ecyrd.jspwiki.WikiPage" ); } /** * Non-existant classes should throw ClassNotFoundEx. */ public void testFindClassNoClass() throws Exception { try { Class foo = WikiEngine.findWikiClass( "MubbleBubble", "com.ecyrd.jspwiki" ); fail("Found class"); } catch( ClassNotFoundException e ) { // Expected } } public static Test suite() { return new TestSuite( WikiEngineTest.class ); } }
tests/com/ecyrd/jspwiki/WikiEngineTest.java
package com.ecyrd.jspwiki; import junit.framework.*; import java.io.*; import java.util.*; import com.ecyrd.jspwiki.providers.*; public class WikiEngineTest extends TestCase { public static final String NAME1 = "Test1"; Properties props = new Properties(); WikiEngine engine; public WikiEngineTest( String s ) { super( s ); } public void setUp() throws Exception { props.load( getClass().getClassLoader().getResourceAsStream("/jspwiki.properties") ); engine = new TestEngine2(props); } public void tearDown() { String files = props.getProperty( FileSystemProvider.PROP_PAGEDIR ); File f = new File( files, NAME1+FileSystemProvider.FILE_EXT ); f.delete(); } public void testNonExistantDirectory() throws Exception { String tmpdir = System.getProperties().getProperty("java.tmpdir"); String dirname = "non-existant-directory"; String newdir = tmpdir + File.separator + dirname; props.setProperty( FileSystemProvider.PROP_PAGEDIR, newdir ); try { WikiEngine test = new TestEngine2( props ); fail( "Wiki did not warn about wrong property." ); } catch( WikiException e ) { // This is okay. } } public void testNonExistantDirProperty() throws Exception { props.remove( FileSystemProvider.PROP_PAGEDIR ); try { WikiEngine test = new TestEngine2( props ); fail( "Wiki did not warn about missing property." ); } catch( WikiException e ) { // This is okay. } } public void testNonExistantPage() throws Exception { String pagename = "Test1"; assertEquals( "Page already exists", false, engine.pageExists( pagename ) ); } public void testPutPage() { String text = "Foobar.\r\n"; String name = NAME1; engine.saveText( name, text ); assertEquals( "page does not exist", true, engine.pageExists( name ) ); assertEquals( "wrong content", text, engine.getText( name ) ); } public void testGetHTML() { String text = "''Foobar.''"; String name = NAME1; engine.saveText( name, text ); String data = engine.getHTML( name ); assertEquals( "<I>Foobar.</I>\n", data ); } public void testEncodeNameLatin1() { String name = "abc"; assertEquals( "abc%E5%E4%F6", engine.encodeName(name) ); } public void testEncodeNameUTF8() throws Exception { String name = "\u0041\u2262\u0391\u002E"; props.setProperty( WikiEngine.PROP_ENCODING, "UTF-8" ); WikiEngine engine = new TestEngine2( props ); assertEquals( "A%E2%89%A2%CE%91.", engine.encodeName(name) ); } private static int ITERATIONS = 100; public void testSpeed1() throws Exception { InputStream is = getClass().getClassLoader().getResourceAsStream("/TextFormattingRules.txt"); Reader in = new InputStreamReader( is, "ISO-8859-1" ); StringWriter out = new StringWriter(); FileUtil.copyContents( in, out ); engine.saveText( NAME1, out.toString() ); long start = System.currentTimeMillis(); for( int i = 0; i < ITERATIONS; i++ ) { String txt = engine.getHTML( NAME1 ); assertTrue( 0 != txt.length() ); } long end = System.currentTimeMillis(); System.out.println( ITERATIONS+" pages took "+(end-start)+" ms (="+ ((end-start)/(double)ITERATIONS)+" ms/page)" ); } public void testReadLinks() throws Exception { String src="Foobar. [Foobar]. Frobozz. [This is a link]."; Object[] result = engine.scanWikiLinks( src ).toArray(); assertEquals( "item 0", result[0], "Foobar" ); assertEquals( "item 1", result[1], "ThisIsALink" ); } /** * Tries to find an existing class. */ public void testFindClass() throws Exception { Class foo = WikiEngine.findWikiClass( "WikiPage", "com.ecyrd.jspwiki" ); assertEquals( foo.getName(), "com.ecyrd.jspwiki.WikiPage" ); } /** * Non-existant classes should throw ClassNotFoundEx. */ public void testFindClassNoClass() throws Exception { try { Class foo = WikiEngine.findWikiClass( "MubbleBubble", "com.ecyrd.jspwiki" ); fail("Found class"); } catch( ClassNotFoundException e ) { // Expected } } public static Test suite() { return new TestSuite( WikiEngineTest.class ); } }
Moved testSpeed1() to StressTestSpeed git-svn-id: 6c0206e3b9edd104850923da33ebd73b435d374d@621731 13f79535-47bb-0310-9956-ffa450edef68
tests/com/ecyrd/jspwiki/WikiEngineTest.java
Moved testSpeed1() to StressTestSpeed
<ide><path>ests/com/ecyrd/jspwiki/WikiEngineTest.java <ide> engine.encodeName(name) ); <ide> } <ide> <del> private static int ITERATIONS = 100; <del> <del> public void testSpeed1() <del> throws Exception <del> { <del> InputStream is = getClass().getClassLoader().getResourceAsStream("/TextFormattingRules.txt"); <del> Reader in = new InputStreamReader( is, "ISO-8859-1" ); <del> StringWriter out = new StringWriter(); <del> <del> FileUtil.copyContents( in, out ); <del> <del> engine.saveText( NAME1, out.toString() ); <del> <del> long start = System.currentTimeMillis(); <del> <del> for( int i = 0; i < ITERATIONS; i++ ) <del> { <del> String txt = engine.getHTML( NAME1 ); <del> assertTrue( 0 != txt.length() ); <del> } <del> <del> long end = System.currentTimeMillis(); <del> <del> System.out.println( ITERATIONS+" pages took "+(end-start)+" ms (="+ <del> ((end-start)/(double)ITERATIONS)+" ms/page)" ); <del> } <del> <ide> public void testReadLinks() <ide> throws Exception <ide> {
Java
epl-1.0
57814092d82fd6e7e833c5d8e72e3e5e903976c6
0
rrimmana/birt-1,rrimmana/birt-1,Charling-Huang/birt,Charling-Huang/birt,rrimmana/birt-1,rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt,sguan-actuate/birt,sguan-actuate/birt,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1,Charling-Huang/birt,sguan-actuate/birt
/******************************************************************************* * Copyright (c) 2007, 2008 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.chart.reportitem; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.eclipse.birt.chart.factory.IDataRowExpressionEvaluator; import org.eclipse.birt.chart.factory.IGroupedDataRowExpressionEvaluator; import org.eclipse.birt.chart.model.Chart; import org.eclipse.birt.chart.model.ChartWithAxes; import org.eclipse.birt.chart.model.ChartWithoutAxes; import org.eclipse.birt.chart.model.Serializer; import org.eclipse.birt.chart.model.component.Axis; import org.eclipse.birt.chart.model.component.Series; import org.eclipse.birt.chart.model.data.Query; import org.eclipse.birt.chart.model.data.SeriesDefinition; import org.eclipse.birt.chart.model.data.impl.SeriesDefinitionImpl; import org.eclipse.birt.chart.model.impl.ChartModelHelper; import org.eclipse.birt.chart.render.IActionRenderer; import org.eclipse.birt.chart.reportitem.api.ChartCubeUtil; import org.eclipse.birt.chart.reportitem.api.ChartItemUtil; import org.eclipse.birt.chart.reportitem.api.ChartReportItemHelper; import org.eclipse.birt.chart.reportitem.api.IChartReportItem; import org.eclipse.birt.chart.util.ChartUtil; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.data.engine.api.IBaseExpression; import org.eclipse.birt.data.engine.api.IBaseQueryDefinition; import org.eclipse.birt.data.engine.api.IBinding; import org.eclipse.birt.data.engine.api.IScriptExpression; import org.eclipse.birt.data.engine.api.ISubqueryDefinition; import org.eclipse.birt.data.engine.api.querydefn.Binding; import org.eclipse.birt.data.engine.api.querydefn.GroupDefinition; import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression; import org.eclipse.birt.data.engine.api.querydefn.SubqueryDefinition; import org.eclipse.birt.data.engine.core.DataException; import org.eclipse.birt.report.data.adapter.api.IModelAdapter; import org.eclipse.birt.report.data.adapter.api.IModelAdapter.ExpressionLocation; import org.eclipse.birt.report.engine.api.IHTMLActionHandler; import org.eclipse.birt.report.engine.api.script.IReportContext; import org.eclipse.birt.report.engine.extension.IBaseResultSet; import org.eclipse.birt.report.engine.extension.ICubeResultSet; import org.eclipse.birt.report.engine.extension.IQueryResultSet; import org.eclipse.birt.report.engine.extension.IReportItemPresentation; import org.eclipse.birt.report.engine.extension.IReportItemPresentationInfo; import org.eclipse.birt.report.item.crosstab.core.ICrosstabConstants; import org.eclipse.birt.report.item.crosstab.core.de.CrosstabReportItemHandle; import org.eclipse.birt.report.model.api.AggregationArgumentHandle; import org.eclipse.birt.report.model.api.ComputedColumnHandle; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.Expression; import org.eclipse.birt.report.model.api.ExpressionHandle; import org.eclipse.birt.report.model.api.ExpressionListHandle; import org.eclipse.birt.report.model.api.ExtendedItemHandle; import org.eclipse.birt.report.model.api.GroupHandle; import org.eclipse.birt.report.model.api.ListingHandle; import org.eclipse.birt.report.model.api.ParamBindingHandle; import org.eclipse.birt.report.model.api.ReportItemHandle; import org.eclipse.birt.report.model.api.SlotHandle; import org.eclipse.birt.report.model.api.elements.structures.AggregationArgument; import org.eclipse.birt.report.model.api.elements.structures.ComputedColumn; import org.eclipse.birt.report.model.api.extension.ExtendedElementException; import org.eclipse.birt.report.model.api.olap.CubeHandle; import org.eclipse.birt.report.model.api.olap.HierarchyHandle; import org.eclipse.birt.report.model.api.util.CubeUtil; import org.eclipse.birt.report.model.elements.interfaces.IGroupElementModel; import org.eclipse.core.runtime.IAdapterManager; import org.eclipse.emf.common.util.EList; /** * Utility class for Chart integration as report item */ public class ChartReportItemUtil extends ChartItemUtil { /** * The field indicates it will revise chart model under reference report * item case. */ public static final int REVISE_REFERENCE_REPORT_ITEM = 1; private static final IChartReportItemFactory baseFactory = new ChartReportItemFactoryBase( ); /** * Revise chart model. * * @param reviseType * @param cm * @param itemHandle */ public static void reviseChartModel( int reviseType, Chart cm, ReportItemHandle itemHandle ) { switch ( reviseType ) { case REVISE_REFERENCE_REPORT_ITEM : String[] categoryExprs = ChartUtil.getCategoryExpressions( cm ); if ( itemHandle.getDataBindingReference( ) != null && isBaseGroupingDefined( cm ) && !( categoryExprs.length > 0 && isSharedGroupExpression( categoryExprs[0], itemHandle ) ) ) { // In older version of chart, it is allowed to set grouping // on category series when sharing report item, but now it // isn't allowed, so this calls will revise chart model to // remove category series grouping flag for the case. SeriesDefinition baseSD = null; if ( cm instanceof ChartWithAxes ) { ChartWithAxes cwa = (ChartWithAxes) cm; baseSD = cwa.getBaseAxes( )[0].getSeriesDefinitions( ) .get( 0 ); } else if ( cm instanceof ChartWithoutAxes ) { ChartWithoutAxes cwoa = (ChartWithoutAxes) cm; baseSD = cwoa.getSeriesDefinitions( ).get( 0 ); } if ( baseSD != null && baseSD.getGrouping( ) != null ) { baseSD.getGrouping( ).unsetEnabled( ); } } break; } } /** * Checks if chart should use internal grouping or DTE grouping. * * @param chartHandle * handle with version * @return true means old report using internal grouping * @since 2.3.1 */ public static boolean isOldChartUsingInternalGroup( ReportItemHandle chartHandle, Chart cm ) { String reportVer = chartHandle.getModuleHandle( ).getVersion( ); if ( reportVer == null || ChartUtil.compareVersion( reportVer, "3.2.16" ) < 0 ) //$NON-NLS-1$ { return true; } // Since if the chart is serialized into a document, the version number // will always be // the newest, so we can only detect an old chart using internal group // with following facts: // 1. the chart has an grouping on base seriesDefination // 2. shared binding is used. // 3. whether the chart is sharing data with a table or list // 4. the shared binding is not grouped. if ( chartHandle.getDataBindingReference( ) != null && isBaseGroupingDefined( cm ) && isSharingTableData( chartHandle ) && !isSharedGroupExpression( ChartUtil.getCategoryExpressions( cm )[0], chartHandle ) ) { return true; } return false; } /** * Check whether the reportitem is sharing data with a table or list. * * @param handle * @return */ private static boolean isSharingTableData( ReportItemHandle handle ) { return getReportItemReference( handle ) instanceof ListingHandle; } /** * Check if specified expression is a grouping expression of shared report * item. * * @param expression * @param handle * @return group expression or not */ @SuppressWarnings("unchecked") private static boolean isSharedGroupExpression( String expression, ReportItemHandle handle ) { ReportItemHandle itemHandle = getReportItemReference( handle ); if ( itemHandle instanceof ListingHandle ) { List<GroupHandle> groupList = new ArrayList<GroupHandle>( ); SlotHandle groups = ( (ListingHandle) itemHandle ).getGroups( ); for ( Iterator<GroupHandle> iter = groups.iterator( ); iter.hasNext( ); ) { groupList.add( iter.next( ) ); } if ( groupList.size( ) == 0 ) { return false; } ExpressionCodec exprCodec = ChartModelHelper.instance( ) .createExpressionCodec( ); for ( GroupHandle gh : groupList ) { loadExpression( exprCodec, gh ); if ( expression.contains( exprCodec.getBindingName( ) ) ) { return true; } } } return false; } /** * Checks if result set is empty * * @param set * result set * @throws BirtException * @since 2.3 */ public static boolean isEmpty( IBaseResultSet set ) throws BirtException { if ( set instanceof IQueryResultSet ) { return ( (IQueryResultSet) set ).isEmpty( ); } // TODO add code to check empty for ICubeResultSet return false; } public static <T> T getAdapter( Object adaptable, Class<T> adapterClass ) { IAdapterManager adapterManager = org.eclipse.birt.core.framework.Platform.getAdapterManager( ); return adapterClass.cast( adapterManager.loadAdapter( adaptable, adapterClass.getName( ) ) ); } public static IReportItemPresentation instanceReportItemPresentation( ExtendedItemHandle handle, IReportItemPresentationInfo info ) { IChartReportItemFactory factory = getAdapter( handle, IChartReportItemFactory.class ); if ( factory == null ) { factory = baseFactory; } return factory.createReportItemPresentation( info ); } public static IActionRenderer instanceActionRenderer( ExtendedItemHandle handle, IHTMLActionHandler handler, IDataRowExpressionEvaluator evaluator, IReportContext context ) { IChartReportItemFactory factory = getAdapter( handle, IChartReportItemFactory.class ); if ( factory == null ) { factory = baseFactory; } return factory.createActionRenderer( handle, handler, evaluator, context ); } public static Serializer instanceSerializer( ExtendedItemHandle handle ) { IChartReportItemFactory factory = getAdapter( handle, IChartReportItemFactory.class ); if ( factory == null ) { factory = baseFactory; } return factory.createSerializer( handle ); } public static ChartCubeQueryHelper instanceCubeQueryHelper( ExtendedItemHandle handle, Chart cm, IModelAdapter modelAdapter ) { IChartReportItemFactory factory = getAdapter( handle, IChartReportItemFactory.class ); if ( factory == null ) { factory = baseFactory; } return factory.createCubeQueryHelper( handle, cm, modelAdapter ); } public static ChartBaseQueryHelper instanceQueryHelper( ExtendedItemHandle handle, Chart cm, IModelAdapter modelAdapter ) { IChartReportItemFactory factory = getAdapter( handle, IChartReportItemFactory.class ); if ( factory == null ) { factory = baseFactory; } return factory.createQueryHelper( handle, cm, modelAdapter ); } public static IGroupedDataRowExpressionEvaluator instanceCubeEvaluator( ExtendedItemHandle handle, Chart cm, ICubeResultSet set ) { IChartReportItemFactory factory = getAdapter( handle, IChartReportItemFactory.class ); if ( factory == null ) { factory = baseFactory; } return factory.createCubeEvaluator( cm, set ); } public static IChartReportItem instanceChartReportItem( ExtendedItemHandle handle ) { IChartReportItemFactory factory = getAdapter( handle, IChartReportItemFactory.class ); if ( factory == null ) { factory = baseFactory; } return factory.createChartReportItem( handle ); } /** * Checks if shared scale is needed when computation * * @param eih * handle * @param cm * chart model * @return shared binding needed or not * @since 2.3 */ public static boolean canScaleShared( ReportItemHandle eih, Chart cm ) { return cm instanceof ChartWithAxes && eih.getDataSet( ) == null && getBindingHolder( eih ) != null && ChartCubeUtil.isInXTabMeasureCell( eih ); } /** * In some cases, if the expression in subquery is a simple binding, and * this binding is from parent query, should copy the binding from parent * and insert into subquery. * * @param query * subquery * @param expr * expression * @throws DataException * @since 2.3.1 and 2.4.0 */ @SuppressWarnings({ "deprecation", "unchecked" }) public static void copyAndInsertBindingFromContainer( ISubqueryDefinition query, String expr ) throws DataException { ExpressionCodec exprCodec = ChartModelHelper.instance( ) .createExpressionCodec( ); String bindingName = exprCodec.getRowBindingName( expr, false ); if ( bindingName != null && !query.getBindings( ).containsKey( bindingName ) && query.getParentQuery( ) .getBindings( ) .containsKey( bindingName ) ) { // Copy the binding from container and insert it into // subquery IBinding parentBinding = (IBinding) query.getParentQuery( ) .getBindings( ) .get( bindingName ); IBinding binding = new Binding( bindingName, parentBinding.getExpression( ) ); binding.setAggrFunction( parentBinding.getAggrFunction( ) ); binding.setDataType( parentBinding.getDataType( ) ); binding.setDisplayName( parentBinding.getDisplayName( ) ); binding.setFilter( parentBinding.getFilter( ) ); // Copy aggregations List<String> aggregationOnList = parentBinding.getAggregatOns( ); if ( aggregationOnList != null ) { for ( String aggregateOn : aggregationOnList ) { binding.addAggregateOn( aggregateOn ); // Copy groups if used and not added previously if ( findGroupInQuery( query, aggregateOn ) == null ) { GroupDefinition group = findGroupInQuery( query.getParentQuery( ), aggregateOn ); if ( group != null ) { ( (SubqueryDefinition) query ).addGroup( group ); } } } } // Copy arguments List<?> argumentsList = parentBinding.getArguments( ); if ( argumentsList != null ) { for ( Object argument : argumentsList ) { binding.addArgument( (IBaseExpression) argument ); } } // Exportable is true for new subquery bindings query.addBinding( binding ); } } @SuppressWarnings("unchecked") private static GroupDefinition findGroupInQuery( IBaseQueryDefinition query, String groupName ) { List<GroupDefinition> groups = query.getGroups( ); if ( groups != null ) { for ( GroupDefinition group : groups ) { if ( group.getName( ).equals( groupName ) ) { return group; } } } return null; } /** * Copy chart's sample data. * * @param srcCM * @param targetCM * @since 2.6.2 */ public static void copyChartSampleData( Chart srcCM, Chart targetCM ) { if ( srcCM.getSampleData( ) != null ) { targetCM.setSampleData( srcCM.getSampleData( ).copyInstance( ) ); } else { targetCM.setSampleData( null ); } } /** * Copy series definition from one chart model to another. * * @param srcCM * @param targetCM * @since 2.5 */ public static void copyChartSeriesDefinition( Chart srcCM, Chart targetCM ) { boolean isSameType = srcCM.getType( ).equals( targetCM.getType( ) ); // Copy category series definitions. EList<SeriesDefinition> srcRsds = ChartUtil.getBaseSeriesDefinitions( srcCM ); EList<SeriesDefinition> tagRsds = ChartUtil.getBaseSeriesDefinitions( targetCM ); for ( int i = 0; i < srcRsds.size( ); i++ ) { SeriesDefinition sd = srcRsds.get( i ); SeriesDefinition tagSD = null; if ( i >= tagRsds.size( ) ) { tagSD = SeriesDefinitionImpl.create( ); // Add to target chart model. if ( targetCM instanceof ChartWithAxes ) { ( (ChartWithAxes) targetCM ).getAxes( ) .get( 0 ) .getSeriesDefinitions( ) .add( tagSD ); } else if ( targetCM instanceof ChartWithoutAxes ) { ( (ChartWithoutAxes) targetCM ).getSeriesDefinitions( ) .add( tagSD ); } } else { tagSD = tagRsds.get( i ); } copySDQueryAttributes( sd, tagSD ); if ( srcCM instanceof ChartWithAxes && targetCM instanceof ChartWithAxes ) { // Also update axis type if ( ( (ChartWithAxes) srcCM ).getAxes( ).get( 0 ).isSetType( ) ) { ( (ChartWithAxes) targetCM ).getAxes( ) .get( 0 ) .setType( ( (ChartWithAxes) srcCM ).getAxes( ) .get( 0 ) .getType( ) ); } } } // Copy Y series definitions. if ( targetCM instanceof ChartWithAxes ) { EList<Axis> tagAxisList = ( (ChartWithAxes) targetCM ).getAxes( ) .get( 0 ) .getAssociatedAxes( ); if ( srcCM instanceof ChartWithAxes ) { EList<Axis> srcAxisList = ( (ChartWithAxes) srcCM ).getAxes( ) .get( 0 ) .getAssociatedAxes( ); if ( tagAxisList.size( ) > srcAxisList.size( ) ) { for ( int i = ( tagAxisList.size( ) - 1 ); i >= srcAxisList.size( ); i-- ) { tagAxisList.remove( i ); } } if ( isSameType ) { // If source chart type is equal with target chart type, // copy additional axes from source into target. for ( int i = 0; i < srcAxisList.size( ); i++ ) { if ( i >= tagAxisList.size( ) ) { // src size > target size, copy pending axis from // source to target. tagAxisList.add( srcAxisList.get( i ) .copyInstance( ) ); } srcRsds = srcAxisList.get( i ).getSeriesDefinitions( ); tagRsds = tagAxisList.get( i ).getSeriesDefinitions( ); copySDListQueryAttributes( srcRsds, tagRsds, isSameType ); // Also update axis type if ( srcAxisList.get( i ).isSetType( ) ) { tagAxisList.get( i ).setType( srcAxisList.get( i ).getType( ) ); } } } else { int minsize = srcAxisList.size( ) > tagAxisList.size( ) ? tagAxisList.size( ) : srcAxisList.size( ); for ( int i = 0; i < minsize; i++ ) { srcRsds = srcAxisList.get( i ).getSeriesDefinitions( ); tagRsds = tagAxisList.get( i ).getSeriesDefinitions( ); copySDListQueryAttributes( srcRsds, tagRsds, isSameType ); // Also update axis type if ( srcAxisList.get( i ).isSetType( ) ) { tagAxisList.get( i ).setType( srcAxisList.get( i ).getType( ) ); } } } } else { srcRsds = ( (ChartWithoutAxes) srcCM ).getSeriesDefinitions( ) .get( 0 ) .getSeriesDefinitions( ); if ( tagAxisList.size( ) > 1 ) { for ( int i = 1; i < tagAxisList.size( ); i++ ) { tagAxisList.remove( i ); } } tagRsds = tagAxisList.get( 0 ).getSeriesDefinitions( ); copySDListQueryAttributes( srcRsds, tagRsds, isSameType ); } } else { tagRsds = ( (ChartWithoutAxes) targetCM ).getSeriesDefinitions( ) .get( 0 ) .getSeriesDefinitions( ); if ( srcCM instanceof ChartWithAxes ) { srcRsds = ( (ChartWithAxes) srcCM ).getAxes( ) .get( 0 ) .getAssociatedAxes( ) .get( 0 ) .getSeriesDefinitions( ); } else { srcRsds = ( (ChartWithoutAxes) srcCM ).getSeriesDefinitions( ) .get( 0 ) .getSeriesDefinitions( ); } copySDListQueryAttributes( srcRsds, tagRsds, isSameType ); } } /** * @param srcRsds * @param tagRsds */ private static void copySDListQueryAttributes( EList<SeriesDefinition> srcRsds, EList<SeriesDefinition> tagRsds, boolean sameChartType ) { if ( tagRsds.size( ) > srcRsds.size( ) ) { for ( int i = ( tagRsds.size( ) - 1 ); i >= srcRsds.size( ); i-- ) { tagRsds.remove( i ); } } if ( sameChartType ) { for ( int i = 0; i < srcRsds.size( ); i++ ) { if ( i >= tagRsds.size( ) ) { // Copy tagRsds.add( srcRsds.get( i ).copyInstance( ) ); } SeriesDefinition sd = srcRsds.get( i ); SeriesDefinition tagSD = tagRsds.get( i ); copySDQueryAttributes( sd, tagSD ); } } else { int minSDsize = srcRsds.size( ) > tagRsds.size( ) ? tagRsds.size( ) : srcRsds.size( ); for ( int i = 0; i < minSDsize; i++ ) { SeriesDefinition sd = srcRsds.get( i ); SeriesDefinition tagSD = tagRsds.get( i ); copySDQueryAttributes( sd, tagSD ); } } } /** * @param sd * @param tagSD */ private static void copySDQueryAttributes( SeriesDefinition sd, SeriesDefinition tagSD ) { if ( sd.getQuery( ) != null ) { tagSD.setQuery( sd.getQuery( ).copyInstance( ) ); } else { tagSD.setQuery( null ); } if ( sd.getGrouping( ) != null ) { tagSD.setGrouping( sd.getGrouping( ).copyInstance( ) ); } else { tagSD.setGrouping( null ); } if ( sd.isSetSorting( ) ) { tagSD.setSorting( sd.getSorting( ) ); } if ( sd.getSortKey( ) != null ) { tagSD.setSortKey( sd.getSortKey( ).copyInstance( ) ); } else { tagSD.setSortKey( null ); } if ( sd.isSetZOrder( ) ) { tagSD.setZOrder( sd.getZOrder( ) ); } int tagSize = tagSD.getSeries( ).size( ); int srcSize = sd.getSeries( ).size( ); if ( tagSize > srcSize ) { for ( int i = ( tagSize - 1 ); i >= srcSize; i-- ) tagSD.getSeries( ).remove( i ); } // Copy data definitions. int i = 0; for ( ; i < srcSize; i++ ) { if ( i >= tagSize ) { // New a series and copy data definitions. Series tagSeries = tagSD.getSeries( ).get( 0 ).copyInstance( ); tagSD.getSeries( ).add( tagSeries ); Series srcSeries = sd.getSeries( ).get( i ); tagSeries.getDataDefinition( ).clear( ); for ( Query q : srcSeries.getDataDefinition( ) ) tagSeries.getDataDefinition( ).add( q.copyInstance( ) ); } else { // Copy data definitions. Series tagSeries = tagSD.getSeries( ).get( i ); Series srcSeries = sd.getSeries( ).get( i ); tagSeries.getDataDefinition( ).clear( ); for ( Query q : srcSeries.getDataDefinition( ) ) tagSeries.getDataDefinition( ).add( q.copyInstance( ) ); } } } public static ScriptExpression newExpression( IModelAdapter adapter, ComputedColumnHandle binding ) { ExpressionHandle eh = binding.getExpressionProperty( ComputedColumn.EXPRESSION_MEMBER ); if ( eh == null || eh.getValue( ) == null ) { return null; } return adapter.adaptExpression( (Expression) eh.getValue( ) ); } public static ScriptExpression newExpression( IModelAdapter adapter, AggregationArgumentHandle binding ) { ExpressionHandle eh = binding.getExpressionProperty( AggregationArgument.VALUE_MEMBER ); if ( eh == null || eh.getValue( ) == null ) { return null; } return adapter.adaptExpression( (Expression) eh.getValue( ) ); } public static List<ScriptExpression> newExpression( IModelAdapter adapter, ParamBindingHandle binding ) { ExpressionListHandle eh = binding.getExpressionListHandle( ); List<Expression> exprs = eh.getListValue( ); if ( exprs == null ) { return Collections.emptyList( ); } List<ScriptExpression> ses = new ArrayList<ScriptExpression>( exprs.size( ) ); for ( Expression expr : exprs ) { ses.add( adapter.adaptExpression( expr ) ); } return ses; } public static ScriptExpression newExpression( IModelAdapter adapter, ExpressionCodec exprCodec, String expr ) { exprCodec.decode( expr ); return adapter.adaptExpression( new Expression( exprCodec.getExpression( ), exprCodec.getType( ) ) ); } public static IScriptExpression adaptExpression( ExpressionCodec exprCodec, IModelAdapter modelAdapter, boolean bCube ) { return modelAdapter.adaptExpression( new Expression( exprCodec.getExpression( ), exprCodec.getType( ) ), bCube ? ExpressionLocation.CUBE : ExpressionLocation.TABLE ); } public static Expression getExpression( GroupHandle gh ) { ExpressionHandle eh = gh.getExpressionProperty( IGroupElementModel.KEY_EXPR_PROP ); if ( eh != null && eh.getValue( ) != null ) { return (Expression) eh.getValue( ); } return null; } public static boolean isKeepCubeHierarchyAndNotCubeTopLevelOnCategory( Chart model, CubeHandle cubeHandle, ReportItemHandle itemHandle ) { if ( model == null ) { return false; } boolean isKeepCubeHierarchy = isKeepCubeHierarchyOnCategory( model ); if ( !isKeepCubeHierarchy ) { return false; } if ( cubeHandle == null ) { return false; } SeriesDefinition sd = ChartUtil.getBaseSeriesDefinitions( model ) .get( 0 ); Query query = ChartUtil.getDataQuery( sd, 0 ); return !isCubeTopLevel( query, itemHandle ); } public static boolean isKeepCubeHierarchyAndNotCubeTopLevelOnSeries( Chart model, CubeHandle cubeHandle, ReportItemHandle itemHandle ) { if ( model == null ) { return false; } boolean isKeepCubeHierarchy = isKeepCubeHierarchyOnSeries( model ); if ( !isKeepCubeHierarchy ) { return false; } if ( cubeHandle == null ) { return false; } Query query = ChartUtil.getAllOrthogonalSeriesDefinitions( model ) .get( 0 ) .getQuery( ); return !isCubeTopLevel( query, itemHandle ); } public static ExpressionCodec getDimensionExpresion(String definition,ReportItemHandle itemHandle){ ExpressionCodec exprc = ChartModelHelper.instance( ) .createExpressionCodec( ); String bindName = exprc.getBindingName( definition ); Iterator<ComputedColumnHandle> iterator = ChartReportItemUtil.getColumnDataBindings( itemHandle ); while ( iterator.hasNext( ) ) { ComputedColumnHandle binding = iterator.next( ); if ( binding.getName( ).equals( bindName ) ) { ChartItemUtil.loadExpression( exprc, binding ); break; } } if ( exprc.isDimensionExpresion( ) ) { return exprc; } else { return null; } } private static boolean isCubeTopLevel( Query query ,ReportItemHandle itemHandle) { ExpressionCodec exprc = ChartModelHelper.instance( ) .createExpressionCodec( ); String bindName = exprc.getBindingName( query.getDefinition( ) ); Iterator<ComputedColumnHandle> iterator = ChartReportItemUtil.getColumnDataBindings( itemHandle ); while ( iterator.hasNext( ) ) { ComputedColumnHandle binding = iterator.next( ); if ( binding.getName( ).equals( bindName ) ) { ChartItemUtil.loadExpression( exprc, binding ); break; } } if ( !exprc.isDimensionExpresion( ) ) { return false; } CubeHandle cube = ChartReportItemHelper.instance( ) .getBindingCubeHandle( itemHandle ); // Add row/column edge String[] levels = exprc.getLevelNames( ); String dimensionName = levels[0]; HierarchyHandle hieHandle = cube.getDimension( dimensionName ) .getDefaultHierarchy( ); // If not multi-dimension return true;If multi-dimension, // return true if is parent top level if ( hieHandle.getLevelCount( ) != 0 && ( hieHandle.getLevelCount( ) == 1 || hieHandle.getLevel( 0 ) .getName( ) .equals( levels[1] ) ) ) { return true; } else { return false; } } public static boolean validateCubeResultSetBinding( ReportItemHandle itemHandle, Chart cm ) throws ExtendedElementException { ReportItemHandle handle = null; if ( ChartItemUtil.isReportItemReference( itemHandle ) || ChartItemUtil.isInMultiViews( itemHandle ) ) { handle = ChartItemUtil.getReportItemReference( itemHandle ); } if ( handle == null ) { handle = ChartItemUtil.getInheritedHandle( itemHandle ); } boolean isCrosstab = false; if ( handle instanceof ExtendedItemHandle ) { isCrosstab = "Crosstab".equals( ( (ExtendedItemHandle) handle ).getExtensionName( ) ); //$NON-NLS-1$ } else { DesignElementHandle container = itemHandle.getContainer( ); while ( container != null ) { if ( container instanceof ExtendedItemHandle && "Crosstab".equals( ( (ExtendedItemHandle) container ).getExtensionName( ) ) ) //$NON-NLS-1$ { handle = (ReportItemHandle) container; isCrosstab = true; break; } container = container.getContainer( ); } } if ( !isCrosstab ) { return true; // not cross tab, ignore. } CrosstabReportItemHandle crossTab = (CrosstabReportItemHandle) ( (ExtendedItemHandle) handle ).getReportItem( ); ExpressionCodec exprCodec = ChartModelHelper.instance( ) .createExpressionCodec( ); List<String> rowAxisDimensions = new ArrayList<String>( ); List<String> colAxisDimensions = new ArrayList<String>( ); /* get cross tab row and column dimensions */ if ( crossTab.getCrosstabView( ICrosstabConstants.ROW_AXIS_TYPE ) != null ) { rowAxisDimensions = ChartReportItemHelper.instance( ) .getLevelBindingNamesOfCrosstab( crossTab.getCrosstabView( ICrosstabConstants.ROW_AXIS_TYPE ), itemHandle ); } if ( crossTab.getCrosstabView( ICrosstabConstants.COLUMN_AXIS_TYPE ) != null ) { colAxisDimensions = ChartReportItemHelper.instance( ) .getLevelBindingNamesOfCrosstab( crossTab.getCrosstabView( ICrosstabConstants.COLUMN_AXIS_TYPE ), itemHandle ); } // get all bindings Map<String, ComputedColumnHandle> bindingMap = new LinkedHashMap<String, ComputedColumnHandle>( ); for ( Iterator<ComputedColumnHandle> bindings = ChartReportItemUtil.getAllColumnBindingsIterator( itemHandle ); bindings.hasNext( ); ) { ComputedColumnHandle column = bindings.next( ); bindingMap.put( column.getName( ), column ); } for ( SeriesDefinition seriesDefinition : ChartUtil.getAllOrthogonalSeriesDefinitions( cm ) ) { Series series = seriesDefinition.getDesignTimeSeries( ); List<Query> queries = series.getDataDefinition( ); for ( Query query : queries ) { String bindingName = exprCodec.getBindingName( query.getDefinition( ) ); ComputedColumnHandle computedBinding = bindingMap.get( bindingName ); if ( computedBinding == null ) { return false; // if orthogonal series binding does not // exist, it must be removed in cross-tab } @SuppressWarnings("unchecked") List<String> aggOnList = computedBinding.getAggregateOnList( ); String[] categoryExpressions = ChartUtil.getCategoryExpressions( cm ); String[] yOptionalExpressions = ChartUtil.getYOptoinalExpressions( cm ); boolean isInXTab = ChartCubeUtil.isInXTabMeasureCell( itemHandle ); if ( aggOnList.size( ) > 0 ) { // check first aggregation on category and optionalY. if ( !searchAggregation( aggOnList.get( 0 ), bindingMap, rowAxisDimensions, colAxisDimensions, categoryExpressions, yOptionalExpressions, itemHandle ) ) { return false; } } if ( !isInXTab && aggOnList.size( ) > 1 ) // XTab has category // only. { if ( !searchAggregation( aggOnList.get( 1 ), bindingMap, rowAxisDimensions, colAxisDimensions, categoryExpressions, yOptionalExpressions, itemHandle ) ) { return false; } } } } return true; } private static boolean searchAggregation( String aggOn, Map<String, ComputedColumnHandle> bindingMap, List<String> rowAxisDimensions, List<String> colAxisDimensions, String[] catecoryBindNames, String[] yOptionalBindNames, ReportItemHandle itemHandle ) { ExpressionCodec exprCodec = null; if ( itemHandle instanceof ExtendedItemHandle ) { exprCodec = ChartReportItemHelper.instance( ) .createExpressionCodec( (ExtendedItemHandle) itemHandle ); } else { exprCodec = ChartModelHelper.instance( ).createExpressionCodec( ); } String[] levelNames = CubeUtil.splitLevelName( aggOn ); ComputedColumnHandle cch = ChartReportItemHelper.instance( ) .findDimensionBinding( exprCodec, levelNames[0], levelNames[1], bindingMap.values( ), itemHandle ); if ( cch == null || cch.getName( ) == null ) { return false; // dimension binding not found } /* see aggregation is on row or column dimension */ List<String> dimensions = null; if ( rowAxisDimensions.contains( cch.getName( ) ) ) { dimensions = rowAxisDimensions; } else if ( colAxisDimensions.contains( cch.getName( ) ) ) { dimensions = colAxisDimensions; } if ( dimensions != null ) { for ( String field : catecoryBindNames ) { if ( dimensions.contains( exprCodec.getBindingName( field ) ) ) { return true; } } for ( String field : yOptionalBindNames ) { if ( dimensions.contains( exprCodec.getBindingName( field ) ) ) { return true; } } } return false; } }
chart/org.eclipse.birt.chart.reportitem/src/org/eclipse/birt/chart/reportitem/ChartReportItemUtil.java
/******************************************************************************* * Copyright (c) 2007, 2008 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.chart.reportitem; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.eclipse.birt.chart.factory.IDataRowExpressionEvaluator; import org.eclipse.birt.chart.factory.IGroupedDataRowExpressionEvaluator; import org.eclipse.birt.chart.model.Chart; import org.eclipse.birt.chart.model.ChartWithAxes; import org.eclipse.birt.chart.model.ChartWithoutAxes; import org.eclipse.birt.chart.model.Serializer; import org.eclipse.birt.chart.model.component.Axis; import org.eclipse.birt.chart.model.component.Series; import org.eclipse.birt.chart.model.data.Query; import org.eclipse.birt.chart.model.data.SeriesDefinition; import org.eclipse.birt.chart.model.data.impl.SeriesDefinitionImpl; import org.eclipse.birt.chart.model.impl.ChartModelHelper; import org.eclipse.birt.chart.render.IActionRenderer; import org.eclipse.birt.chart.reportitem.api.ChartCubeUtil; import org.eclipse.birt.chart.reportitem.api.ChartItemUtil; import org.eclipse.birt.chart.reportitem.api.ChartReportItemHelper; import org.eclipse.birt.chart.reportitem.api.IChartReportItem; import org.eclipse.birt.chart.util.ChartUtil; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.data.engine.api.IBaseExpression; import org.eclipse.birt.data.engine.api.IBaseQueryDefinition; import org.eclipse.birt.data.engine.api.IBinding; import org.eclipse.birt.data.engine.api.IScriptExpression; import org.eclipse.birt.data.engine.api.ISubqueryDefinition; import org.eclipse.birt.data.engine.api.querydefn.Binding; import org.eclipse.birt.data.engine.api.querydefn.GroupDefinition; import org.eclipse.birt.data.engine.api.querydefn.ScriptExpression; import org.eclipse.birt.data.engine.api.querydefn.SubqueryDefinition; import org.eclipse.birt.data.engine.core.DataException; import org.eclipse.birt.report.data.adapter.api.IModelAdapter; import org.eclipse.birt.report.data.adapter.api.IModelAdapter.ExpressionLocation; import org.eclipse.birt.report.engine.api.IHTMLActionHandler; import org.eclipse.birt.report.engine.api.script.IReportContext; import org.eclipse.birt.report.engine.extension.IBaseResultSet; import org.eclipse.birt.report.engine.extension.ICubeResultSet; import org.eclipse.birt.report.engine.extension.IQueryResultSet; import org.eclipse.birt.report.engine.extension.IReportItemPresentation; import org.eclipse.birt.report.engine.extension.IReportItemPresentationInfo; import org.eclipse.birt.report.item.crosstab.core.ICrosstabConstants; import org.eclipse.birt.report.item.crosstab.core.de.CrosstabReportItemHandle; import org.eclipse.birt.report.model.api.AggregationArgumentHandle; import org.eclipse.birt.report.model.api.ComputedColumnHandle; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.Expression; import org.eclipse.birt.report.model.api.ExpressionHandle; import org.eclipse.birt.report.model.api.ExpressionListHandle; import org.eclipse.birt.report.model.api.ExtendedItemHandle; import org.eclipse.birt.report.model.api.GroupHandle; import org.eclipse.birt.report.model.api.ListingHandle; import org.eclipse.birt.report.model.api.ParamBindingHandle; import org.eclipse.birt.report.model.api.ReportItemHandle; import org.eclipse.birt.report.model.api.SlotHandle; import org.eclipse.birt.report.model.api.elements.structures.AggregationArgument; import org.eclipse.birt.report.model.api.elements.structures.ComputedColumn; import org.eclipse.birt.report.model.api.extension.ExtendedElementException; import org.eclipse.birt.report.model.api.olap.CubeHandle; import org.eclipse.birt.report.model.api.olap.HierarchyHandle; import org.eclipse.birt.report.model.api.util.CubeUtil; import org.eclipse.birt.report.model.elements.interfaces.IGroupElementModel; import org.eclipse.core.runtime.IAdapterManager; import org.eclipse.emf.common.util.EList; /** * Utility class for Chart integration as report item */ public class ChartReportItemUtil extends ChartItemUtil { /** * The field indicates it will revise chart model under reference report * item case. */ public static final int REVISE_REFERENCE_REPORT_ITEM = 1; private static final IChartReportItemFactory baseFactory = new ChartReportItemFactoryBase( ); /** * Revise chart model. * * @param reviseType * @param cm * @param itemHandle */ public static void reviseChartModel( int reviseType, Chart cm, ReportItemHandle itemHandle ) { switch ( reviseType ) { case REVISE_REFERENCE_REPORT_ITEM : String[] categoryExprs = ChartUtil.getCategoryExpressions( cm ); if ( itemHandle.getDataBindingReference( ) != null && isBaseGroupingDefined( cm ) && !( categoryExprs.length > 0 && isSharedGroupExpression( categoryExprs[0], itemHandle ) ) ) { // In older version of chart, it is allowed to set grouping // on category series when sharing report item, but now it // isn't allowed, so this calls will revise chart model to // remove category series grouping flag for the case. SeriesDefinition baseSD = null; if ( cm instanceof ChartWithAxes ) { ChartWithAxes cwa = (ChartWithAxes) cm; baseSD = cwa.getBaseAxes( )[0].getSeriesDefinitions( ) .get( 0 ); } else if ( cm instanceof ChartWithoutAxes ) { ChartWithoutAxes cwoa = (ChartWithoutAxes) cm; baseSD = cwoa.getSeriesDefinitions( ).get( 0 ); } if ( baseSD != null && baseSD.getGrouping( ) != null ) { baseSD.getGrouping( ).unsetEnabled( ); } } break; } } /** * Checks if chart should use internal grouping or DTE grouping. * * @param chartHandle * handle with version * @return true means old report using internal grouping * @since 2.3.1 */ public static boolean isOldChartUsingInternalGroup( ReportItemHandle chartHandle, Chart cm ) { String reportVer = chartHandle.getModuleHandle( ).getVersion( ); if ( reportVer == null || ChartUtil.compareVersion( reportVer, "3.2.16" ) < 0 ) //$NON-NLS-1$ { return true; } // Since if the chart is serialized into a document, the version number // will always be // the newest, so we can only detect an old chart using internal group // with following facts: // 1. the chart has an grouping on base seriesDefination // 2. shared binding is used. // 3. whether the chart is sharing data with a table or list // 4. the shared binding is not grouped. if ( chartHandle.getDataBindingReference( ) != null && isBaseGroupingDefined( cm ) && isSharingTableData( chartHandle ) && !isSharedGroupExpression( ChartUtil.getCategoryExpressions( cm )[0], chartHandle ) ) { return true; } return false; } /** * Check whether the reportitem is sharing data with a table or list. * * @param handle * @return */ private static boolean isSharingTableData( ReportItemHandle handle ) { return getReportItemReference( handle ) instanceof ListingHandle; } /** * Check if specified expression is a grouping expression of shared report * item. * * @param expression * @param handle * @return group expression or not */ @SuppressWarnings("unchecked") private static boolean isSharedGroupExpression( String expression, ReportItemHandle handle ) { ReportItemHandle itemHandle = getReportItemReference( handle ); if ( itemHandle instanceof ListingHandle ) { List<GroupHandle> groupList = new ArrayList<GroupHandle>( ); SlotHandle groups = ( (ListingHandle) itemHandle ).getGroups( ); for ( Iterator<GroupHandle> iter = groups.iterator( ); iter.hasNext( ); ) { groupList.add( iter.next( ) ); } if ( groupList.size( ) == 0 ) { return false; } ExpressionCodec exprCodec = ChartModelHelper.instance( ) .createExpressionCodec( ); for ( GroupHandle gh : groupList ) { loadExpression( exprCodec, gh ); if ( expression.contains( exprCodec.getBindingName( ) ) ) { return true; } } } return false; } /** * Checks if result set is empty * * @param set * result set * @throws BirtException * @since 2.3 */ public static boolean isEmpty( IBaseResultSet set ) throws BirtException { if ( set instanceof IQueryResultSet ) { return ( (IQueryResultSet) set ).isEmpty( ); } // TODO add code to check empty for ICubeResultSet return false; } public static <T> T getAdapter( Object adaptable, Class<T> adapterClass ) { IAdapterManager adapterManager = org.eclipse.birt.core.framework.Platform.getAdapterManager( ); return adapterClass.cast( adapterManager.loadAdapter( adaptable, adapterClass.getName( ) ) ); } public static IReportItemPresentation instanceReportItemPresentation( ExtendedItemHandle handle, IReportItemPresentationInfo info ) { IChartReportItemFactory factory = getAdapter( handle, IChartReportItemFactory.class ); if ( factory == null ) { factory = baseFactory; } return factory.createReportItemPresentation( info ); } public static IActionRenderer instanceActionRenderer( ExtendedItemHandle handle, IHTMLActionHandler handler, IDataRowExpressionEvaluator evaluator, IReportContext context ) { IChartReportItemFactory factory = getAdapter( handle, IChartReportItemFactory.class ); if ( factory == null ) { factory = baseFactory; } return factory.createActionRenderer( handle, handler, evaluator, context ); } public static Serializer instanceSerializer( ExtendedItemHandle handle ) { IChartReportItemFactory factory = getAdapter( handle, IChartReportItemFactory.class ); if ( factory == null ) { factory = baseFactory; } return factory.createSerializer( handle ); } public static ChartCubeQueryHelper instanceCubeQueryHelper( ExtendedItemHandle handle, Chart cm, IModelAdapter modelAdapter ) { IChartReportItemFactory factory = getAdapter( handle, IChartReportItemFactory.class ); if ( factory == null ) { factory = baseFactory; } return factory.createCubeQueryHelper( handle, cm, modelAdapter ); } public static ChartBaseQueryHelper instanceQueryHelper( ExtendedItemHandle handle, Chart cm, IModelAdapter modelAdapter ) { IChartReportItemFactory factory = getAdapter( handle, IChartReportItemFactory.class ); if ( factory == null ) { factory = baseFactory; } return factory.createQueryHelper( handle, cm, modelAdapter ); } public static IGroupedDataRowExpressionEvaluator instanceCubeEvaluator( ExtendedItemHandle handle, Chart cm, ICubeResultSet set ) { IChartReportItemFactory factory = getAdapter( handle, IChartReportItemFactory.class ); if ( factory == null ) { factory = baseFactory; } return factory.createCubeEvaluator( cm, set ); } public static IChartReportItem instanceChartReportItem( ExtendedItemHandle handle ) { IChartReportItemFactory factory = getAdapter( handle, IChartReportItemFactory.class ); if ( factory == null ) { factory = baseFactory; } return factory.createChartReportItem( handle ); } /** * Checks if shared scale is needed when computation * * @param eih * handle * @param cm * chart model * @return shared binding needed or not * @since 2.3 */ public static boolean canScaleShared( ReportItemHandle eih, Chart cm ) { return cm instanceof ChartWithAxes && eih.getDataSet( ) == null && getBindingHolder( eih ) != null && ChartCubeUtil.isInXTabMeasureCell( eih ); } /** * In some cases, if the expression in subquery is a simple binding, and * this binding is from parent query, should copy the binding from parent * and insert into subquery. * * @param query * subquery * @param expr * expression * @throws DataException * @since 2.3.1 and 2.4.0 */ @SuppressWarnings({ "deprecation", "unchecked" }) public static void copyAndInsertBindingFromContainer( ISubqueryDefinition query, String expr ) throws DataException { ExpressionCodec exprCodec = ChartModelHelper.instance( ) .createExpressionCodec( ); String bindingName = exprCodec.getRowBindingName( expr, false ); if ( bindingName != null && !query.getBindings( ).containsKey( bindingName ) && query.getParentQuery( ) .getBindings( ) .containsKey( bindingName ) ) { // Copy the binding from container and insert it into // subquery IBinding parentBinding = (IBinding) query.getParentQuery( ) .getBindings( ) .get( bindingName ); IBinding binding = new Binding( bindingName, parentBinding.getExpression( ) ); binding.setAggrFunction( parentBinding.getAggrFunction( ) ); binding.setDataType( parentBinding.getDataType( ) ); binding.setDisplayName( parentBinding.getDisplayName( ) ); binding.setFilter( parentBinding.getFilter( ) ); // Copy aggregations List<String> aggregationOnList = parentBinding.getAggregatOns( ); if ( aggregationOnList != null ) { for ( String aggregateOn : aggregationOnList ) { binding.addAggregateOn( aggregateOn ); // Copy groups if used and not added previously if ( findGroupInQuery( query, aggregateOn ) == null ) { GroupDefinition group = findGroupInQuery( query.getParentQuery( ), aggregateOn ); if ( group != null ) { ( (SubqueryDefinition) query ).addGroup( group ); } } } } // Copy arguments List<?> argumentsList = parentBinding.getArguments( ); if ( argumentsList != null ) { for ( Object argument : argumentsList ) { binding.addArgument( (IBaseExpression) argument ); } } // Exportable is true for new subquery bindings query.addBinding( binding ); } } @SuppressWarnings("unchecked") private static GroupDefinition findGroupInQuery( IBaseQueryDefinition query, String groupName ) { List<GroupDefinition> groups = query.getGroups( ); if ( groups != null ) { for ( GroupDefinition group : groups ) { if ( group.getName( ).equals( groupName ) ) { return group; } } } return null; } /** * Copy chart's sample data. * * @param srcCM * @param targetCM * @since 2.6.2 */ public static void copyChartSampleData( Chart srcCM, Chart targetCM ) { if ( srcCM.getSampleData( ) != null ) { targetCM.setSampleData( srcCM.getSampleData( ).copyInstance( ) ); } else { targetCM.setSampleData( null ); } } /** * Copy series definition from one chart model to another. * * @param srcCM * @param targetCM * @since 2.5 */ public static void copyChartSeriesDefinition( Chart srcCM, Chart targetCM ) { boolean isSameType = srcCM.getType( ).equals( targetCM.getType( ) ); // Copy category series definitions. EList<SeriesDefinition> srcRsds = ChartUtil.getBaseSeriesDefinitions( srcCM ); EList<SeriesDefinition> tagRsds = ChartUtil.getBaseSeriesDefinitions( targetCM ); for ( int i = 0; i < srcRsds.size( ); i++ ) { SeriesDefinition sd = srcRsds.get( i ); SeriesDefinition tagSD = null; if ( i >= tagRsds.size( ) ) { tagSD = SeriesDefinitionImpl.create( ); // Add to target chart model. if ( targetCM instanceof ChartWithAxes ) { ( (ChartWithAxes) targetCM ).getAxes( ) .get( 0 ) .getSeriesDefinitions( ) .add( tagSD ); } else if ( targetCM instanceof ChartWithoutAxes ) { ( (ChartWithoutAxes) targetCM ).getSeriesDefinitions( ) .add( tagSD ); } } else { tagSD = tagRsds.get( i ); } copySDQueryAttributes( sd, tagSD ); if ( srcCM instanceof ChartWithAxes && targetCM instanceof ChartWithAxes ) { // Also update axis type if ( ( (ChartWithAxes) srcCM ).getAxes( ).get( 0 ).isSetType( ) ) { ( (ChartWithAxes) targetCM ).getAxes( ) .get( 0 ) .setType( ( (ChartWithAxes) srcCM ).getAxes( ) .get( 0 ) .getType( ) ); } } } // Copy Y series definitions. if ( targetCM instanceof ChartWithAxes ) { EList<Axis> tagAxisList = ( (ChartWithAxes) targetCM ).getAxes( ) .get( 0 ) .getAssociatedAxes( ); if ( srcCM instanceof ChartWithAxes ) { EList<Axis> srcAxisList = ( (ChartWithAxes) srcCM ).getAxes( ) .get( 0 ) .getAssociatedAxes( ); if ( tagAxisList.size( ) > srcAxisList.size( ) ) { for ( int i = ( tagAxisList.size( ) - 1 ); i >= srcAxisList.size( ); i-- ) { tagAxisList.remove( i ); } } if ( isSameType ) { // If source chart type is equal with target chart type, // copy additional axes from source into target. for ( int i = 0; i < srcAxisList.size( ); i++ ) { if ( i >= tagAxisList.size( ) ) { // src size > target size, copy pending axis from // source to target. tagAxisList.add( srcAxisList.get( i ) .copyInstance( ) ); } srcRsds = srcAxisList.get( i ).getSeriesDefinitions( ); tagRsds = tagAxisList.get( i ).getSeriesDefinitions( ); copySDListQueryAttributes( srcRsds, tagRsds, isSameType ); // Also update axis type if ( srcAxisList.get( i ).isSetType( ) ) { tagAxisList.get( i ).setType( srcAxisList.get( i ).getType( ) ); } } } else { int minsize = srcAxisList.size( ) > tagAxisList.size( ) ? tagAxisList.size( ) : srcAxisList.size( ); for ( int i = 0; i < minsize; i++ ) { srcRsds = srcAxisList.get( i ).getSeriesDefinitions( ); tagRsds = tagAxisList.get( i ).getSeriesDefinitions( ); copySDListQueryAttributes( srcRsds, tagRsds, isSameType ); // Also update axis type if ( srcAxisList.get( i ).isSetType( ) ) { tagAxisList.get( i ).setType( srcAxisList.get( i ).getType( ) ); } } } } else { srcRsds = ( (ChartWithoutAxes) srcCM ).getSeriesDefinitions( ) .get( 0 ) .getSeriesDefinitions( ); if ( tagAxisList.size( ) > 1 ) { for ( int i = 1; i < tagAxisList.size( ); i++ ) { tagAxisList.remove( i ); } } tagRsds = tagAxisList.get( 0 ).getSeriesDefinitions( ); copySDListQueryAttributes( srcRsds, tagRsds, isSameType ); } } else { tagRsds = ( (ChartWithoutAxes) targetCM ).getSeriesDefinitions( ) .get( 0 ) .getSeriesDefinitions( ); if ( srcCM instanceof ChartWithAxes ) { srcRsds = ( (ChartWithAxes) srcCM ).getAxes( ) .get( 0 ) .getAssociatedAxes( ) .get( 0 ) .getSeriesDefinitions( ); } else { srcRsds = ( (ChartWithoutAxes) srcCM ).getSeriesDefinitions( ) .get( 0 ) .getSeriesDefinitions( ); } copySDListQueryAttributes( srcRsds, tagRsds, isSameType ); } } /** * @param srcRsds * @param tagRsds */ private static void copySDListQueryAttributes( EList<SeriesDefinition> srcRsds, EList<SeriesDefinition> tagRsds, boolean sameChartType ) { if ( tagRsds.size( ) > srcRsds.size( ) ) { for ( int i = ( tagRsds.size( ) - 1 ); i >= srcRsds.size( ); i-- ) { tagRsds.remove( i ); } } if ( sameChartType ) { for ( int i = 0; i < srcRsds.size( ); i++ ) { if ( i >= tagRsds.size( ) ) { // Copy tagRsds.add( srcRsds.get( i ).copyInstance( ) ); } SeriesDefinition sd = srcRsds.get( i ); SeriesDefinition tagSD = tagRsds.get( i ); copySDQueryAttributes( sd, tagSD ); } } else { int minSDsize = srcRsds.size( ) > tagRsds.size( ) ? tagRsds.size( ) : srcRsds.size( ); for ( int i = 0; i < minSDsize; i++ ) { SeriesDefinition sd = srcRsds.get( i ); SeriesDefinition tagSD = tagRsds.get( i ); copySDQueryAttributes( sd, tagSD ); } } } /** * @param sd * @param tagSD */ private static void copySDQueryAttributes( SeriesDefinition sd, SeriesDefinition tagSD ) { if ( sd.getQuery( ) != null ) { tagSD.setQuery( sd.getQuery( ).copyInstance( ) ); } else { tagSD.setQuery( null ); } if ( sd.getGrouping( ) != null ) { tagSD.setGrouping( sd.getGrouping( ).copyInstance( ) ); } else { tagSD.setGrouping( null ); } if ( sd.isSetSorting( ) ) { tagSD.setSorting( sd.getSorting( ) ); } if ( sd.getSortKey( ) != null ) { tagSD.setSortKey( sd.getSortKey( ).copyInstance( ) ); } else { tagSD.setSortKey( null ); } if ( sd.isSetZOrder( ) ) { tagSD.setZOrder( sd.getZOrder( ) ); } int tagSize = tagSD.getSeries( ).size( ); int srcSize = sd.getSeries( ).size( ); if ( tagSize > srcSize ) { for ( int i = ( tagSize - 1 ); i >= srcSize; i-- ) tagSD.getSeries( ).remove( i ); } // Copy data definitions. int i = 0; for ( ; i < srcSize; i++ ) { if ( i >= tagSize ) { // New a series and copy data definitions. Series tagSeries = tagSD.getSeries( ).get( 0 ).copyInstance( ); tagSD.getSeries( ).add( tagSeries ); Series srcSeries = sd.getSeries( ).get( i ); tagSeries.getDataDefinition( ).clear( ); for ( Query q : srcSeries.getDataDefinition( ) ) tagSeries.getDataDefinition( ).add( q.copyInstance( ) ); } else { // Copy data definitions. Series tagSeries = tagSD.getSeries( ).get( i ); Series srcSeries = sd.getSeries( ).get( i ); tagSeries.getDataDefinition( ).clear( ); for ( Query q : srcSeries.getDataDefinition( ) ) tagSeries.getDataDefinition( ).add( q.copyInstance( ) ); } } } public static ScriptExpression newExpression( IModelAdapter adapter, ComputedColumnHandle binding ) { ExpressionHandle eh = binding.getExpressionProperty( ComputedColumn.EXPRESSION_MEMBER ); if ( eh == null || eh.getValue( ) == null ) { return null; } return adapter.adaptExpression( (Expression) eh.getValue( ) ); } public static ScriptExpression newExpression( IModelAdapter adapter, AggregationArgumentHandle binding ) { ExpressionHandle eh = binding.getExpressionProperty( AggregationArgument.VALUE_MEMBER ); if ( eh == null || eh.getValue( ) == null ) { return null; } return adapter.adaptExpression( (Expression) eh.getValue( ) ); } public static List<ScriptExpression> newExpression( IModelAdapter adapter, ParamBindingHandle binding ) { ExpressionListHandle eh = binding.getExpressionListHandle( ); List<Expression> exprs = eh.getListValue( ); if ( exprs == null ) { return Collections.emptyList( ); } List<ScriptExpression> ses = new ArrayList<ScriptExpression>( exprs.size( ) ); for ( Expression expr : exprs ) { ses.add( adapter.adaptExpression( expr ) ); } return ses; } public static ScriptExpression newExpression( IModelAdapter adapter, ExpressionCodec exprCodec, String expr ) { exprCodec.decode( expr ); return adapter.adaptExpression( new Expression( exprCodec.getExpression( ), exprCodec.getType( ) ) ); } public static IScriptExpression adaptExpression( ExpressionCodec exprCodec, IModelAdapter modelAdapter, boolean bCube ) { return modelAdapter.adaptExpression( new Expression( exprCodec.getExpression( ), exprCodec.getType( ) ), bCube ? ExpressionLocation.CUBE : ExpressionLocation.TABLE ); } public static Expression getExpression( GroupHandle gh ) { ExpressionHandle eh = gh.getExpressionProperty( IGroupElementModel.KEY_EXPR_PROP ); if ( eh != null && eh.getValue( ) != null ) { return (Expression) eh.getValue( ); } return null; } public static boolean isKeepCubeHierarchyAndNotCubeTopLevelOnCategory( Chart model, CubeHandle cubeHandle, ReportItemHandle itemHandle ) { boolean isKeepCubeHierarchy = isKeepCubeHierarchyOnCategory( model ); if ( !isKeepCubeHierarchy ) { return false; } if ( cubeHandle == null ) { return false; } SeriesDefinition sd = ChartUtil.getBaseSeriesDefinitions( model ) .get( 0 ); Query query = ChartUtil.getDataQuery( sd, 0 ); return !isCubeTopLevel( query, itemHandle ); } public static boolean isKeepCubeHierarchyAndNotCubeTopLevelOnSeries( Chart model, CubeHandle cubeHandle, ReportItemHandle itemHandle ) { boolean isKeepCubeHierarchy = isKeepCubeHierarchyOnSeries( model ); if ( !isKeepCubeHierarchy ) { return false; } if ( cubeHandle == null ) { return false; } Query query = ChartUtil.getAllOrthogonalSeriesDefinitions( model ) .get( 0 ) .getQuery( ); return !isCubeTopLevel( query, itemHandle ); } public static ExpressionCodec getDimensionExpresion(String definition,ReportItemHandle itemHandle){ ExpressionCodec exprc = ChartModelHelper.instance( ) .createExpressionCodec( ); String bindName = exprc.getBindingName( definition ); Iterator<ComputedColumnHandle> iterator = ChartReportItemUtil.getColumnDataBindings( itemHandle ); while ( iterator.hasNext( ) ) { ComputedColumnHandle binding = iterator.next( ); if ( binding.getName( ).equals( bindName ) ) { ChartItemUtil.loadExpression( exprc, binding ); break; } } if ( exprc.isDimensionExpresion( ) ) { return exprc; } else { return null; } } private static boolean isCubeTopLevel( Query query ,ReportItemHandle itemHandle) { ExpressionCodec exprc = ChartModelHelper.instance( ) .createExpressionCodec( ); String bindName = exprc.getBindingName( query.getDefinition( ) ); Iterator<ComputedColumnHandle> iterator = ChartReportItemUtil.getColumnDataBindings( itemHandle ); while ( iterator.hasNext( ) ) { ComputedColumnHandle binding = iterator.next( ); if ( binding.getName( ).equals( bindName ) ) { ChartItemUtil.loadExpression( exprc, binding ); break; } } if ( !exprc.isDimensionExpresion( ) ) { return false; } CubeHandle cube = ChartReportItemHelper.instance( ) .getBindingCubeHandle( itemHandle ); // Add row/column edge String[] levels = exprc.getLevelNames( ); String dimensionName = levels[0]; HierarchyHandle hieHandle = cube.getDimension( dimensionName ) .getDefaultHierarchy( ); // If not multi-dimension return true;If multi-dimension, // return true if is parent top level if ( hieHandle.getLevelCount( ) != 0 && ( hieHandle.getLevelCount( ) == 1 || hieHandle.getLevel( 0 ) .getName( ) .equals( levels[1] ) ) ) { return true; } else { return false; } } public static boolean validateCubeResultSetBinding( ReportItemHandle itemHandle, Chart cm ) throws ExtendedElementException { ReportItemHandle handle = null; if ( ChartItemUtil.isReportItemReference( itemHandle ) || ChartItemUtil.isInMultiViews( itemHandle ) ) { handle = ChartItemUtil.getReportItemReference( itemHandle ); } if ( handle == null ) { handle = ChartItemUtil.getInheritedHandle( itemHandle ); } boolean isCrosstab = false; if ( handle instanceof ExtendedItemHandle ) { isCrosstab = "Crosstab".equals( ( (ExtendedItemHandle) handle ).getExtensionName( ) ); //$NON-NLS-1$ } else { DesignElementHandle container = itemHandle.getContainer( ); while ( container != null ) { if ( container instanceof ExtendedItemHandle && "Crosstab".equals( ( (ExtendedItemHandle) container ).getExtensionName( ) ) ) //$NON-NLS-1$ { handle = (ReportItemHandle) container; isCrosstab = true; break; } container = container.getContainer( ); } } if ( !isCrosstab ) { return true; // not cross tab, ignore. } CrosstabReportItemHandle crossTab = (CrosstabReportItemHandle) ( (ExtendedItemHandle) handle ).getReportItem( ); ExpressionCodec exprCodec = ChartModelHelper.instance( ) .createExpressionCodec( ); List<String> rowAxisDimensions = new ArrayList<String>( ); List<String> colAxisDimensions = new ArrayList<String>( ); /* get cross tab row and column dimensions */ if ( crossTab.getCrosstabView( ICrosstabConstants.ROW_AXIS_TYPE ) != null ) { rowAxisDimensions = ChartReportItemHelper.instance( ) .getLevelBindingNamesOfCrosstab( crossTab.getCrosstabView( ICrosstabConstants.ROW_AXIS_TYPE ), itemHandle ); } if ( crossTab.getCrosstabView( ICrosstabConstants.COLUMN_AXIS_TYPE ) != null ) { colAxisDimensions = ChartReportItemHelper.instance( ) .getLevelBindingNamesOfCrosstab( crossTab.getCrosstabView( ICrosstabConstants.COLUMN_AXIS_TYPE ), itemHandle ); } // get all bindings Map<String, ComputedColumnHandle> bindingMap = new LinkedHashMap<String, ComputedColumnHandle>( ); for ( Iterator<ComputedColumnHandle> bindings = ChartReportItemUtil.getAllColumnBindingsIterator( itemHandle ); bindings.hasNext( ); ) { ComputedColumnHandle column = bindings.next( ); bindingMap.put( column.getName( ), column ); } for ( SeriesDefinition seriesDefinition : ChartUtil.getAllOrthogonalSeriesDefinitions( cm ) ) { Series series = seriesDefinition.getDesignTimeSeries( ); List<Query> queries = series.getDataDefinition( ); for ( Query query : queries ) { String bindingName = exprCodec.getBindingName( query.getDefinition( ) ); ComputedColumnHandle computedBinding = bindingMap.get( bindingName ); if ( computedBinding == null ) { return false; // if orthogonal series binding does not // exist, it must be removed in cross-tab } @SuppressWarnings("unchecked") List<String> aggOnList = computedBinding.getAggregateOnList( ); String[] categoryExpressions = ChartUtil.getCategoryExpressions( cm ); String[] yOptionalExpressions = ChartUtil.getYOptoinalExpressions( cm ); boolean isInXTab = ChartCubeUtil.isInXTabMeasureCell( itemHandle ); if ( aggOnList.size( ) > 0 ) { // check first aggregation on category and optionalY. if ( !searchAggregation( aggOnList.get( 0 ), bindingMap, rowAxisDimensions, colAxisDimensions, categoryExpressions, yOptionalExpressions, itemHandle ) ) { return false; } } if ( !isInXTab && aggOnList.size( ) > 1 ) // XTab has category // only. { if ( !searchAggregation( aggOnList.get( 1 ), bindingMap, rowAxisDimensions, colAxisDimensions, categoryExpressions, yOptionalExpressions, itemHandle ) ) { return false; } } } } return true; } private static boolean searchAggregation( String aggOn, Map<String, ComputedColumnHandle> bindingMap, List<String> rowAxisDimensions, List<String> colAxisDimensions, String[] catecoryBindNames, String[] yOptionalBindNames, ReportItemHandle itemHandle ) { ExpressionCodec exprCodec = null; if ( itemHandle instanceof ExtendedItemHandle ) { exprCodec = ChartReportItemHelper.instance( ) .createExpressionCodec( (ExtendedItemHandle) itemHandle ); } else { exprCodec = ChartModelHelper.instance( ).createExpressionCodec( ); } String[] levelNames = CubeUtil.splitLevelName( aggOn ); ComputedColumnHandle cch = ChartReportItemHelper.instance( ) .findDimensionBinding( exprCodec, levelNames[0], levelNames[1], bindingMap.values( ), itemHandle ); if ( cch == null || cch.getName( ) == null ) { return false; // dimension binding not found } /* see aggregation is on row or column dimension */ List<String> dimensions = null; if ( rowAxisDimensions.contains( cch.getName( ) ) ) { dimensions = rowAxisDimensions; } else if ( colAxisDimensions.contains( cch.getName( ) ) ) { dimensions = colAxisDimensions; } if ( dimensions != null ) { for ( String field : catecoryBindNames ) { if ( dimensions.contains( exprCodec.getBindingName( field ) ) ) { return true; } } for ( String field : yOptionalBindNames ) { if ( dimensions.contains( exprCodec.getBindingName( field ) ) ) { return true; } } } return false; } }
Fixed potential bug, check null chart model case.
chart/org.eclipse.birt.chart.reportitem/src/org/eclipse/birt/chart/reportitem/ChartReportItemUtil.java
Fixed potential bug, check null chart model case.
<ide><path>hart/org.eclipse.birt.chart.reportitem/src/org/eclipse/birt/chart/reportitem/ChartReportItemUtil.java <ide> public static boolean isKeepCubeHierarchyAndNotCubeTopLevelOnCategory( <ide> Chart model, CubeHandle cubeHandle, ReportItemHandle itemHandle ) <ide> { <add> if ( model == null ) <add> { <add> return false; <add> } <ide> boolean isKeepCubeHierarchy = isKeepCubeHierarchyOnCategory( model ); <ide> <ide> if ( !isKeepCubeHierarchy ) <ide> public static boolean isKeepCubeHierarchyAndNotCubeTopLevelOnSeries( <ide> Chart model, CubeHandle cubeHandle, ReportItemHandle itemHandle ) <ide> { <add> if ( model == null ) <add> { <add> return false; <add> } <add> <ide> boolean isKeepCubeHierarchy = isKeepCubeHierarchyOnSeries( model ); <ide> <ide> if ( !isKeepCubeHierarchy )
Java
apache-2.0
b41fc2c1df19bcf81c72a5aacaff37af6b1b05f3
0
BroadleafCommerce/blc-paypal,BroadleafCommerce/blc-authorizenet
/* * Copyright 2008-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.broadleafcommerce.payment.service.module; import com.braintreegateway.Result; import com.braintreegateway.Transaction; import org.broadleafcommerce.common.money.Money; import org.broadleafcommerce.common.time.SystemTime; import org.broadleafcommerce.core.order.domain.FulfillmentGroup; import org.broadleafcommerce.core.payment.domain.PaymentInfo; import org.broadleafcommerce.core.payment.domain.PaymentResponseItem; import org.broadleafcommerce.core.payment.domain.PaymentResponseItemImpl; import org.broadleafcommerce.core.payment.service.PaymentContext; import org.broadleafcommerce.core.payment.service.exception.PaymentException; import org.broadleafcommerce.core.payment.service.module.PaymentModule; import org.broadleafcommerce.core.payment.service.type.PaymentInfoType; import org.broadleafcommerce.profile.core.domain.Address; import org.broadleafcommerce.profile.core.domain.AddressImpl; import org.broadleafcommerce.profile.core.service.CountryService; import org.broadleafcommerce.profile.core.service.StateService; import org.broadleafcommerce.vendor.braintree.service.payment.BraintreePaymentRequest; import org.broadleafcommerce.vendor.braintree.service.payment.BraintreePaymentService; import org.broadleafcommerce.vendor.braintree.service.payment.MessageConstants; import org.broadleafcommerce.vendor.braintree.service.payment.type.BraintreeMethodType; import org.broadleafcommerce.vendor.braintree.service.payment.type.BraintreeRefundType; import org.springframework.util.Assert; import java.util.HashMap; import java.util.Map; /** * Created by IntelliJ IDEA. * User: chadharchar * Date: 3/19/12 * Time: 9:15 AM * To change this template use File | Settings | File Templates. */ public class BraintreePaymentModule implements PaymentModule { private BraintreePaymentService braintreePaymentService; private StateService stateService; private CountryService countryService; @Override public PaymentResponseItem authorize(PaymentContext paymentContext) throws PaymentException { //authorize transaction throw new PaymentException("The authorize method is not supported by this org.broadleafcommerce.payment.service.module.BraintreePaymentModule"); } @Override public PaymentResponseItem reverseAuthorize(PaymentContext paymentContext) throws PaymentException { //void transaction after submitted for settlement BraintreePaymentRequest request = buildBasicRequest(paymentContext, BraintreeMethodType.VOID); Assert.isTrue(paymentContext.getPaymentInfo().getAdditionalFields().containsKey(MessageConstants.BRAINTREEID), "Must pass a BRAINTREEID value on the additionalFields of the PaymentInfo instance."); Result<Transaction> result; try { result = getBraintreePaymentService().process(request); } catch (org.broadleafcommerce.common.vendor.service.exception.PaymentException e) { throw new PaymentException(e); } PaymentResponseItem responseItem = buildBasicResponse(result, paymentContext); return responseItem; } @Override public PaymentResponseItem debit(PaymentContext paymentContext) throws PaymentException { //submit for settlement BraintreePaymentRequest request = buildBasicRequest(paymentContext, BraintreeMethodType.SUBMIT); Assert.isTrue(paymentContext.getPaymentInfo().getAdditionalFields().containsKey(MessageConstants.BRAINTREEID), "Must pass a BRAINTREEID value on the additionalFields of the PaymentInfo instance."); Result<Transaction> result; try { result = getBraintreePaymentService().process(request); } catch (org.broadleafcommerce.common.vendor.service.exception.PaymentException e) { throw new PaymentException(e); } PaymentResponseItem responseItem = buildBasicResponse(result, paymentContext); return responseItem; } @Override public PaymentResponseItem authorizeAndDebit(PaymentContext paymentContext) throws PaymentException { //submit form to braintree then submit transaction for settlement BraintreePaymentRequest request = buildBasicRequest(paymentContext, BraintreeMethodType.CONFIRM); Assert.isTrue(paymentContext.getPaymentInfo().getAdditionalFields().containsKey(MessageConstants.QUERYSTRING), "Must pass a QUERYSTRING value on the additionalFields of the PaymentInfo instance."); PaymentInfo paymentInfo = paymentContext.getPaymentInfo(); Result<Transaction> result; try { result = getBraintreePaymentService().process(request); paymentInfo.getAdditionalFields().remove(MessageConstants.QUERYSTRING); } catch (org.broadleafcommerce.common.vendor.service.exception.PaymentException e) { throw new PaymentException(e); } PaymentResponseItem responseItem = buildBasicResponse(result, paymentContext); if(responseItem.getTransactionSuccess()) { paymentContext.getPaymentInfo().getAdditionalFields().put(MessageConstants.BRAINTREEID, responseItem.getTransactionId()); responseItem = debit(paymentContext); } return responseItem; } @Override public PaymentResponseItem credit(PaymentContext paymentContext) throws PaymentException { //refund transaction BraintreePaymentRequest request = buildBasicRequest(paymentContext, BraintreeMethodType.REFUND); Assert.isTrue(paymentContext.getPaymentInfo().getAdditionalFields().containsKey(MessageConstants.BRAINTREEID), "Must pass a BRAINTREEID value on the additionalFields of the PaymentInfo instance."); Result<Transaction> result; try { result = getBraintreePaymentService().process(request); } catch (org.broadleafcommerce.common.vendor.service.exception.PaymentException e) { throw new PaymentException(e); } PaymentResponseItem responseItem = buildBasicResponse(result, paymentContext); return responseItem; } @Override public PaymentResponseItem voidPayment(PaymentContext paymentContext) throws PaymentException { //void transaction before submitted for settlement return reverseAuthorize(paymentContext); } public BraintreePaymentRequest buildBasicRequest(PaymentContext paymentContext, BraintreeMethodType methodType) { BraintreePaymentRequest request = new BraintreePaymentRequest(); request.setMethodType(methodType); if(methodType == BraintreeMethodType.CONFIRM){ request.setQueryString(paymentContext.getPaymentInfo().getAdditionalFields().get(MessageConstants.QUERYSTRING)); } else { request.setTransactionID(paymentContext.getPaymentInfo().getAdditionalFields().get(MessageConstants.BRAINTREEID)); } if(methodType == BraintreeMethodType.REFUND){ request.setRefundType(BraintreeRefundType.FULL); } return request; } private PaymentResponseItem buildBasicResponse(Result<Transaction> result, PaymentContext paymentContext) { PaymentResponseItem responseItem = new PaymentResponseItemImpl(); responseItem.setTransactionSuccess(result.isSuccess()); responseItem.setTransactionTimestamp(SystemTime.asDate()); Map<String, String> map = new HashMap<String, String>(); map.put(MessageConstants.MESSAGE, result.getMessage()); if(result.isSuccess()) { setTargetResponse(result, paymentContext, responseItem, map); } else if(result.getTransaction() != null){ setTransactionResponse(result, paymentContext, responseItem, map); } else { responseItem.setAmountPaid(new Money(0)); } responseItem.setAdditionalFields(map); return responseItem; } public void setTargetResponse(Result<Transaction> result, PaymentContext paymentContext, PaymentResponseItem responseItem, Map<String, String> map) { responseItem.setAmountPaid(new Money(result.getTarget().getAmount())); responseItem.setTransactionId(result.getTarget().getId()); responseItem.setAuthorizationCode(result.getTarget().getProcessorAuthorizationCode()); responseItem.setProcessorResponseCode(result.getTarget().getProcessorResponseCode()); responseItem.setProcessorResponseText(result.getTarget().getProcessorResponseText()); responseItem.setAvsCode(result.getTarget().getAvsStreetAddressResponseCode()); responseItem.setCvvCode(result.getTarget().getCvvResponseCode()); map.put(MessageConstants.CARDTYPE, result.getTarget().getCreditCard().getCardType()); map.put(MessageConstants.EXPIRATIONMONTH, result.getTarget().getCreditCard().getExpirationMonth()); map.put(MessageConstants.EXPIRATIONYEAR, result.getTarget().getCreditCard().getExpirationYear()); map.put(MessageConstants.LASTFOUR, result.getTarget().getCreditCard().getLast4()); setBillingInfo(result.getTarget(), paymentContext); setShippingInfo(result.getTarget(), paymentContext); } public void setBillingInfo(Transaction result, PaymentContext paymentContext) { if (result.getBillingAddress() != null && !isBraintreeAddressEmpty(result.getBillingAddress())) { Address billingAddress = new AddressImpl(); billingAddress.setFirstName(result.getBillingAddress().getFirstName()); billingAddress.setLastName(result.getBillingAddress().getLastName()); billingAddress.setCompanyName(result.getBillingAddress().getCompany()); billingAddress.setAddressLine1(result.getBillingAddress().getStreetAddress()); billingAddress.setAddressLine2(result.getBillingAddress().getExtendedAddress()); billingAddress.setCity(result.getBillingAddress().getLocality()); if (result.getBillingAddress().getRegion() != null && stateService.findStateByAbbreviation(result.getBillingAddress().getRegion()) != null ) { billingAddress.setState(stateService.findStateByAbbreviation(result.getBillingAddress().getRegion())); } billingAddress.setCountry(countryService.findCountryByAbbreviation(result.getBillingAddress().getCountryCodeAlpha2())); billingAddress.setPostalCode(result.getBillingAddress().getPostalCode()); paymentContext.getPaymentInfo().setAddress(billingAddress); } } public void setShippingInfo(Transaction result, PaymentContext paymentContext) { if (result.getShippingAddress() != null && !isBraintreeAddressEmpty(result.getShippingAddress()) && paymentContext.getPaymentInfo().getOrder().getFulfillmentGroups().size() == 1) { // If you pass the shipping address to Braintree, there has to be an existing fulfillment group on the order. // This must be done because of pricing considerations. // The fulfillment group must be constructed when adding to the cart or sometime before calling the gateway. This depends on UX. // This default implementation assumes one fulfillment group per order because braintree only supports a single shipping address. // Override this method if necessary. FulfillmentGroup fulfillmentGroup = paymentContext.getPaymentInfo().getOrder().getFulfillmentGroups().get(0); if (fulfillmentGroup != null) { Address shippingAddress = new AddressImpl(); shippingAddress.setFirstName(result.getShippingAddress().getFirstName()); shippingAddress.setLastName(result.getShippingAddress().getLastName()); shippingAddress.setCompanyName(result.getShippingAddress().getCompany()); shippingAddress.setAddressLine1(result.getShippingAddress().getStreetAddress()); shippingAddress.setAddressLine2(result.getShippingAddress().getExtendedAddress()); shippingAddress.setCity(result.getShippingAddress().getLocality()); if (result.getShippingAddress().getRegion() != null && stateService.findStateByAbbreviation(result.getShippingAddress().getRegion()) != null ) { shippingAddress.setState(stateService.findStateByAbbreviation(result.getShippingAddress().getRegion())); } shippingAddress.setCountry(countryService.findCountryByAbbreviation(result.getShippingAddress().getCountryCodeAlpha2())); shippingAddress.setPostalCode(result.getShippingAddress().getPostalCode()); fulfillmentGroup.setAddress(shippingAddress); } } } public void setTransactionResponse(Result<Transaction> result, PaymentContext paymentContext, PaymentResponseItem responseItem, Map<String, String> map) { responseItem.setAmountPaid(new Money(result.getTransaction().getAmount())); responseItem.setTransactionId(result.getTransaction().getId()); responseItem.setAuthorizationCode(result.getTransaction().getProcessorAuthorizationCode()); responseItem.setProcessorResponseCode(result.getTransaction().getProcessorResponseCode()); responseItem.setProcessorResponseText(result.getTransaction().getProcessorResponseText()); responseItem.setAvsCode(result.getTransaction().getAvsStreetAddressResponseCode()); responseItem.setCvvCode(result.getTransaction().getCvvResponseCode()); map.put(MessageConstants.CARDTYPE, result.getTransaction().getCreditCard().getCardType()); map.put(MessageConstants.EXPIRATIONMONTH, result.getTransaction().getCreditCard().getExpirationMonth()); map.put(MessageConstants.EXPIRATIONYEAR, result.getTransaction().getCreditCard().getExpirationYear()); map.put(MessageConstants.LASTFOUR, result.getTransaction().getCreditCard().getLast4()); setBillingInfo(result.getTransaction(), paymentContext); setShippingInfo(result.getTransaction(), paymentContext); } @Override public PaymentResponseItem balance(PaymentContext paymentContext) throws PaymentException { throw new PaymentException("The balance method is not supported by this org.broadleafcommerce.payment.service.module.BraintreePaymentModule"); } @Override public Boolean isValidCandidate(PaymentInfoType paymentType) { return paymentType == PaymentInfoType.CREDIT_CARD; } private boolean isBraintreeAddressEmpty(com.braintreegateway.Address braintreeAddress) { if (braintreeAddress.getCompany() == null && braintreeAddress.getCountryCodeAlpha2() == null && braintreeAddress.getCountryCodeAlpha3() == null && braintreeAddress.getCountryCodeAlpha3() == null && braintreeAddress.getCountryCodeNumeric() == null && braintreeAddress.getCountryName() == null && braintreeAddress.getCreatedAt() == null && braintreeAddress.getCustomerId() == null && braintreeAddress.getExtendedAddress() == null && braintreeAddress.getFirstName() == null && braintreeAddress.getId() == null && braintreeAddress.getLastName() == null && braintreeAddress.getLocality() == null && braintreeAddress.getPostalCode() == null && braintreeAddress.getRegion() == null && braintreeAddress.getStreetAddress() == null && braintreeAddress.getUpdatedAt() == null) { return true; } return false; } public BraintreePaymentService getBraintreePaymentService() { return braintreePaymentService; } public void setBraintreePaymentService(BraintreePaymentService braintreePaymentService) { this.braintreePaymentService = braintreePaymentService; } public StateService getStateService() { return stateService; } public void setStateService(StateService stateService) { this.stateService = stateService; } public CountryService getCountryService() { return countryService; } public void setCountryService(CountryService countryService) { this.countryService = countryService; } }
payment/broadleaf-braintree/src/main/java/org/broadleafcommerce/payment/service/module/BraintreePaymentModule.java
/* * Copyright 2008-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.broadleafcommerce.payment.service.module; import com.braintreegateway.Result; import com.braintreegateway.Transaction; import org.broadleafcommerce.common.money.Money; import org.broadleafcommerce.common.time.SystemTime; import org.broadleafcommerce.core.order.domain.FulfillmentGroup; import org.broadleafcommerce.core.payment.domain.PaymentInfo; import org.broadleafcommerce.core.payment.domain.PaymentResponseItem; import org.broadleafcommerce.core.payment.domain.PaymentResponseItemImpl; import org.broadleafcommerce.core.payment.service.PaymentContext; import org.broadleafcommerce.core.payment.service.exception.PaymentException; import org.broadleafcommerce.core.payment.service.module.PaymentModule; import org.broadleafcommerce.core.payment.service.type.PaymentInfoType; import org.broadleafcommerce.profile.core.domain.Address; import org.broadleafcommerce.profile.core.domain.AddressImpl; import org.broadleafcommerce.profile.core.service.CountryService; import org.broadleafcommerce.profile.core.service.StateService; import org.broadleafcommerce.vendor.braintree.service.payment.BraintreePaymentRequest; import org.broadleafcommerce.vendor.braintree.service.payment.BraintreePaymentService; import org.broadleafcommerce.vendor.braintree.service.payment.MessageConstants; import org.broadleafcommerce.vendor.braintree.service.payment.type.BraintreeMethodType; import org.broadleafcommerce.vendor.braintree.service.payment.type.BraintreeRefundType; import org.springframework.util.Assert; import java.util.HashMap; import java.util.Map; /** * Created by IntelliJ IDEA. * User: chadharchar * Date: 3/19/12 * Time: 9:15 AM * To change this template use File | Settings | File Templates. */ public class BraintreePaymentModule implements PaymentModule { private BraintreePaymentService braintreePaymentService; private StateService stateService; private CountryService countryService; @Override public PaymentResponseItem authorize(PaymentContext paymentContext) throws PaymentException { //authorize transaction throw new PaymentException("The authorize method is not supported by this org.broadleafcommerce.payment.service.module.BraintreePaymentModule"); } @Override public PaymentResponseItem reverseAuthorize(PaymentContext paymentContext) throws PaymentException { //void transaction after submitted for settlement BraintreePaymentRequest request = buildBasicRequest(paymentContext, BraintreeMethodType.VOID); Assert.isTrue(paymentContext.getPaymentInfo().getAdditionalFields().containsKey(MessageConstants.BRAINTREEID), "Must pass a BRAINTREEID value on the additionalFields of the PaymentInfo instance."); Result<Transaction> result; try { result = getBraintreePaymentService().process(request); } catch (org.broadleafcommerce.common.vendor.service.exception.PaymentException e) { throw new PaymentException(e); } PaymentResponseItem responseItem = buildBasicResponse(result, paymentContext); return responseItem; } @Override public PaymentResponseItem debit(PaymentContext paymentContext) throws PaymentException { //submit for settlement BraintreePaymentRequest request = buildBasicRequest(paymentContext, BraintreeMethodType.SUBMIT); Assert.isTrue(paymentContext.getPaymentInfo().getAdditionalFields().containsKey(MessageConstants.BRAINTREEID), "Must pass a BRAINTREEID value on the additionalFields of the PaymentInfo instance."); Result<Transaction> result; try { result = getBraintreePaymentService().process(request); } catch (org.broadleafcommerce.common.vendor.service.exception.PaymentException e) { throw new PaymentException(e); } PaymentResponseItem responseItem = buildBasicResponse(result, paymentContext); return responseItem; } @Override public PaymentResponseItem authorizeAndDebit(PaymentContext paymentContext) throws PaymentException { //submit form to braintree then submit transaction for settlement BraintreePaymentRequest request = buildBasicRequest(paymentContext, BraintreeMethodType.CONFIRM); Assert.isTrue(paymentContext.getPaymentInfo().getAdditionalFields().containsKey(MessageConstants.QUERYSTRING), "Must pass a QUERYSTRING value on the additionalFields of the PaymentInfo instance."); PaymentInfo paymentInfo = paymentContext.getPaymentInfo(); Result<Transaction> result; try { result = getBraintreePaymentService().process(request); paymentInfo.getAdditionalFields().remove(MessageConstants.QUERYSTRING); } catch (org.broadleafcommerce.common.vendor.service.exception.PaymentException e) { throw new PaymentException(e); } PaymentResponseItem responseItem = buildBasicResponse(result, paymentContext); if(responseItem.getTransactionSuccess()) { paymentContext.getPaymentInfo().getAdditionalFields().put(MessageConstants.BRAINTREEID, responseItem.getTransactionId()); responseItem = debit(paymentContext); } return responseItem; } @Override public PaymentResponseItem credit(PaymentContext paymentContext) throws PaymentException { //refund transaction BraintreePaymentRequest request = buildBasicRequest(paymentContext, BraintreeMethodType.REFUND); Assert.isTrue(paymentContext.getPaymentInfo().getAdditionalFields().containsKey(MessageConstants.BRAINTREEID), "Must pass a BRAINTREEID value on the additionalFields of the PaymentInfo instance."); Result<Transaction> result; try { result = getBraintreePaymentService().process(request); } catch (org.broadleafcommerce.common.vendor.service.exception.PaymentException e) { throw new PaymentException(e); } PaymentResponseItem responseItem = buildBasicResponse(result, paymentContext); return responseItem; } @Override public PaymentResponseItem voidPayment(PaymentContext paymentContext) throws PaymentException { //void transaction before submitted for settlement return reverseAuthorize(paymentContext); } public BraintreePaymentRequest buildBasicRequest(PaymentContext paymentContext, BraintreeMethodType methodType) { BraintreePaymentRequest request = new BraintreePaymentRequest(); request.setMethodType(methodType); if(methodType == BraintreeMethodType.CONFIRM){ request.setQueryString(paymentContext.getPaymentInfo().getAdditionalFields().get(MessageConstants.QUERYSTRING)); } else { request.setTransactionID(paymentContext.getPaymentInfo().getAdditionalFields().get(MessageConstants.BRAINTREEID)); } if(methodType == BraintreeMethodType.REFUND){ request.setRefundType(BraintreeRefundType.FULL); } return request; } private PaymentResponseItem buildBasicResponse(Result<Transaction> result, PaymentContext paymentContext) { PaymentResponseItem responseItem = new PaymentResponseItemImpl(); responseItem.setTransactionSuccess(result.isSuccess()); responseItem.setTransactionTimestamp(SystemTime.asDate()); Map<String, String> map = new HashMap<String, String>(); map.put(MessageConstants.MESSAGE, result.getMessage()); if(result.isSuccess()) { setTargetResponse(result, paymentContext, responseItem, map); } else if(result.getTransaction() != null){ setTransactionResponse(result, paymentContext, responseItem, map); } else { responseItem.setAmountPaid(new Money(0)); } responseItem.setAdditionalFields(map); return responseItem; } public void setTargetResponse(Result<Transaction> result, PaymentContext paymentContext, PaymentResponseItem responseItem, Map<String, String> map) { responseItem.setAmountPaid(new Money(result.getTarget().getAmount())); responseItem.setTransactionId(result.getTarget().getId()); responseItem.setAuthorizationCode(result.getTarget().getProcessorAuthorizationCode()); responseItem.setProcessorResponseCode(result.getTarget().getProcessorResponseCode()); responseItem.setProcessorResponseText(result.getTarget().getProcessorResponseText()); responseItem.setAvsCode(result.getTarget().getAvsStreetAddressResponseCode()); responseItem.setCvvCode(result.getTarget().getCvvResponseCode()); map.put(MessageConstants.CARDTYPE, result.getTarget().getCreditCard().getCardType()); map.put(MessageConstants.EXPIRATIONMONTH, result.getTarget().getCreditCard().getExpirationMonth()); map.put(MessageConstants.EXPIRATIONYEAR, result.getTarget().getCreditCard().getExpirationYear()); map.put(MessageConstants.LASTFOUR, result.getTarget().getCreditCard().getLast4()); setBillingInfo(result.getTarget(), paymentContext); setShippingInfo(result.getTarget(), paymentContext); } public void setBillingInfo(Transaction result, PaymentContext paymentContext) { if (result.getBillingAddress() != null) { Address billingAddress = new AddressImpl(); billingAddress.setFirstName(result.getBillingAddress().getFirstName()); billingAddress.setLastName(result.getBillingAddress().getLastName()); billingAddress.setCompanyName(result.getBillingAddress().getCompany()); billingAddress.setAddressLine1(result.getBillingAddress().getStreetAddress()); billingAddress.setAddressLine2(result.getBillingAddress().getExtendedAddress()); billingAddress.setCity(result.getBillingAddress().getLocality()); if (result.getBillingAddress().getRegion() != null && stateService.findStateByAbbreviation(result.getBillingAddress().getRegion()) != null ) { billingAddress.setState(stateService.findStateByAbbreviation(result.getBillingAddress().getRegion())); } billingAddress.setCountry(countryService.findCountryByAbbreviation(result.getBillingAddress().getCountryCodeAlpha2())); billingAddress.setPostalCode(result.getBillingAddress().getPostalCode()); paymentContext.getPaymentInfo().setAddress(billingAddress); } } public void setShippingInfo(Transaction result, PaymentContext paymentContext) { if (result.getShippingAddress() != null && paymentContext.getPaymentInfo().getOrder().getFulfillmentGroups().size() == 1) { // If you pass the shipping address to Braintree, there has to be an existing fulfillment group on the order. // This must be done because of pricing considerations. // The fulfillment group must be constructed when adding to the cart or sometime before calling the gateway. This depends on UX. // This default implementation assumes one fulfillment group per order because braintree only supports a single shipping address. // Override this method if necessary. FulfillmentGroup fulfillmentGroup = paymentContext.getPaymentInfo().getOrder().getFulfillmentGroups().get(0); if (fulfillmentGroup != null) { Address shippingAddress = new AddressImpl(); shippingAddress.setFirstName(result.getShippingAddress().getFirstName()); shippingAddress.setLastName(result.getShippingAddress().getLastName()); shippingAddress.setCompanyName(result.getShippingAddress().getCompany()); shippingAddress.setAddressLine1(result.getShippingAddress().getStreetAddress()); shippingAddress.setAddressLine2(result.getShippingAddress().getExtendedAddress()); shippingAddress.setCity(result.getShippingAddress().getLocality()); if (result.getShippingAddress().getRegion() != null && stateService.findStateByAbbreviation(result.getShippingAddress().getRegion()) != null ) { shippingAddress.setState(stateService.findStateByAbbreviation(result.getShippingAddress().getRegion())); } shippingAddress.setCountry(countryService.findCountryByAbbreviation(result.getShippingAddress().getCountryCodeAlpha2())); shippingAddress.setPostalCode(result.getShippingAddress().getPostalCode()); fulfillmentGroup.setAddress(shippingAddress); } } } public void setTransactionResponse(Result<Transaction> result, PaymentContext paymentContext, PaymentResponseItem responseItem, Map<String, String> map) { responseItem.setAmountPaid(new Money(result.getTransaction().getAmount())); responseItem.setTransactionId(result.getTransaction().getId()); responseItem.setAuthorizationCode(result.getTransaction().getProcessorAuthorizationCode()); responseItem.setProcessorResponseCode(result.getTransaction().getProcessorResponseCode()); responseItem.setProcessorResponseText(result.getTransaction().getProcessorResponseText()); responseItem.setAvsCode(result.getTransaction().getAvsStreetAddressResponseCode()); responseItem.setCvvCode(result.getTransaction().getCvvResponseCode()); map.put(MessageConstants.CARDTYPE, result.getTransaction().getCreditCard().getCardType()); map.put(MessageConstants.EXPIRATIONMONTH, result.getTransaction().getCreditCard().getExpirationMonth()); map.put(MessageConstants.EXPIRATIONYEAR, result.getTransaction().getCreditCard().getExpirationYear()); map.put(MessageConstants.LASTFOUR, result.getTransaction().getCreditCard().getLast4()); setBillingInfo(result.getTransaction(), paymentContext); setShippingInfo(result.getTransaction(), paymentContext); } @Override public PaymentResponseItem balance(PaymentContext paymentContext) throws PaymentException { throw new PaymentException("The balance method is not supported by this org.broadleafcommerce.payment.service.module.BraintreePaymentModule"); } @Override public Boolean isValidCandidate(PaymentInfoType paymentType) { return paymentType == PaymentInfoType.CREDIT_CARD; } public BraintreePaymentService getBraintreePaymentService() { return braintreePaymentService; } public void setBraintreePaymentService(BraintreePaymentService braintreePaymentService) { this.braintreePaymentService = braintreePaymentService; } public StateService getStateService() { return stateService; } public void setStateService(StateService stateService) { this.stateService = stateService; } public CountryService getCountryService() { return countryService; } public void setCountryService(CountryService countryService) { this.countryService = countryService; } }
fixing braintree shipping method
payment/broadleaf-braintree/src/main/java/org/broadleafcommerce/payment/service/module/BraintreePaymentModule.java
fixing braintree shipping method
<ide><path>ayment/broadleaf-braintree/src/main/java/org/broadleafcommerce/payment/service/module/BraintreePaymentModule.java <ide> } <ide> <ide> public void setBillingInfo(Transaction result, PaymentContext paymentContext) { <del> if (result.getBillingAddress() != null) { <add> if (result.getBillingAddress() != null && !isBraintreeAddressEmpty(result.getBillingAddress())) { <ide> Address billingAddress = new AddressImpl(); <ide> billingAddress.setFirstName(result.getBillingAddress().getFirstName()); <ide> billingAddress.setLastName(result.getBillingAddress().getLastName()); <ide> } <ide> <ide> public void setShippingInfo(Transaction result, PaymentContext paymentContext) { <del> if (result.getShippingAddress() != null && paymentContext.getPaymentInfo().getOrder().getFulfillmentGroups().size() == 1) { <add> if (result.getShippingAddress() != null && <add> !isBraintreeAddressEmpty(result.getShippingAddress()) && <add> paymentContext.getPaymentInfo().getOrder().getFulfillmentGroups().size() == 1) { <ide> // If you pass the shipping address to Braintree, there has to be an existing fulfillment group on the order. <ide> // This must be done because of pricing considerations. <ide> // The fulfillment group must be constructed when adding to the cart or sometime before calling the gateway. This depends on UX. <ide> return paymentType == PaymentInfoType.CREDIT_CARD; <ide> } <ide> <add> private boolean isBraintreeAddressEmpty(com.braintreegateway.Address braintreeAddress) { <add> if (braintreeAddress.getCompany() == null && <add> braintreeAddress.getCountryCodeAlpha2() == null && <add> braintreeAddress.getCountryCodeAlpha3() == null && <add> braintreeAddress.getCountryCodeAlpha3() == null && <add> braintreeAddress.getCountryCodeNumeric() == null && <add> braintreeAddress.getCountryName() == null && <add> braintreeAddress.getCreatedAt() == null && <add> braintreeAddress.getCustomerId() == null && <add> braintreeAddress.getExtendedAddress() == null && <add> braintreeAddress.getFirstName() == null && <add> braintreeAddress.getId() == null && <add> braintreeAddress.getLastName() == null && <add> braintreeAddress.getLocality() == null && <add> braintreeAddress.getPostalCode() == null && <add> braintreeAddress.getRegion() == null && <add> braintreeAddress.getStreetAddress() == null && <add> braintreeAddress.getUpdatedAt() == null) { <add> return true; <add> } <add> return false; <add> } <add> <ide> public BraintreePaymentService getBraintreePaymentService() { <ide> return braintreePaymentService; <ide> }
Java
mit
61c6e3042726e0fbd37504dfba7adf04b1a449e8
0
johan12345/opacclient,geomcmaster/opacclient,johan12345/opacclient,ruediger-w/opacclient,thesebas/opacclient,raphaelm/opacclient,raphaelm/opacclient,ruediger-w/opacclient,simon04/opacclient,johan12345/opacclient,simon04/opacclient,johan12345/opacclient,hurzl/opacclient,opacapp/opacclient,hurzl/opacclient,opacapp/opacclient,geomcmaster/opacclient,hurzl/opacclient,geomcmaster/opacclient,opacapp/opacclient,thesebas/opacclient,opacapp/opacclient,ruediger-w/opacclient,opacapp/opacclient,thesebas/opacclient,johan12345/opacclient,raphaelm/opacclient,ruediger-w/opacclient,ruediger-w/opacclient,simon04/opacclient
/** * Copyright (C) 2013 by Rüdiger Wurth under the MIT license: * * 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. */ package de.geeksfactory.opacclient.apis; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.acra.ACRA; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import android.content.ContentValues; import android.os.Bundle; import de.geeksfactory.opacclient.NotReachableException; import de.geeksfactory.opacclient.networking.HTTPClient; import de.geeksfactory.opacclient.objects.Account; import de.geeksfactory.opacclient.objects.AccountData; import de.geeksfactory.opacclient.objects.Detail; import de.geeksfactory.opacclient.objects.DetailledItem; import de.geeksfactory.opacclient.objects.Filter; import de.geeksfactory.opacclient.objects.Filter.Option; import de.geeksfactory.opacclient.objects.Library; import de.geeksfactory.opacclient.objects.SearchRequestResult; import de.geeksfactory.opacclient.objects.SearchResult; import de.geeksfactory.opacclient.objects.SearchResult.MediaType; import de.geeksfactory.opacclient.storage.MetaDataSource; /** * @author Ruediger Wurth, 16.02.2013 Web identification: * "copyright 1992-2011 by BiBer GmbH" * * BiBer gestartet mit Stadtbibliothek Offenburg start URL: * http://217.86.216.47/opac/de/qsim_frm.html.S * * open: issue #23: Basic support for library system "Biber" -> Essen * issue #32: Integration of "BiBer" (copyright 2006) -> Karlsruhe * https://opac.karlsruhe.de/ issue #33: Integration of "BiBer" * (copyright 1992) -> Essen * * Features: In getResult(), mixed table layout is supported: * column-wise and row-wise In getResult(), amazon bitmaps are supported * * Katalogsuche tested with * * Name Media amazon copy Media Branch Account type Bitmaps table types * support images avail search * -------------------------------------------------------------------- * BaWu/Friedrichshafen ok yes yes yes yes - BaWu/Lahr ok yes yes yes no * - BaWu/Offenburg ok n/a no yes n/a yes Bay/Aschaffenburg ok n/a no * yes n/a - Bay/Wuerzburg ok yes yes yes yes - NRW/Duisburg ok yes yes * yes n/a - NRW/Erkrath n/a yes no yes not sup.yes NRW/Essen n/a n/a no * yes not sup.- NRW/Gelsenkirchen ok yes yes yes yes - NRW/Hagen ok yes * yes yes yes yes NRW/Herford n/a yes yes yes n/a - NRW/Luenen ok yes * no yes n/a - NRW/MuelheimRuhr ok yes yes yes yes yes */ public class BiBer1992 extends BaseApi { private String m_opac_url = ""; private String m_opac_dir = "opac"; // sometimes also "opax" private JSONObject m_data; private MetaDataSource m_metadata; private boolean m_initialised = false; private String m_last_error; private Library m_library; private List<NameValuePair> m_nameValuePairs = new ArrayList<NameValuePair>( 2); protected static HashMap<String, MediaType> defaulttypes = new HashMap<String, MediaType>(); static { } // private int m_resultcount = 10; // private long logged_in; // private Account logged_in_as; // we have to limit num of results because PUSH attribute SHOW=20 does not // work: // number of results is always 50 which is too much final private int numOfResultsPerPage = 20; // from HTML: // <option value="AW">Autor</option> // <option value="TW">Titelwort</option> // <option value="DW">Thema</option> // <option value="PP">Standort</option> // <option value="IS">ISBN/ISSN</option> // <option value="PU">Verlag</option> // <option value="PY">Ersch.-Jahr</option> // <option value="LA">Sprache</option> @Override public String[] getSearchFields() { return new String[] { KEY_SEARCH_QUERY_TITLE, KEY_SEARCH_QUERY_AUTHOR, KEY_SEARCH_QUERY_KEYWORDA, KEY_SEARCH_QUERY_ISBN, KEY_SEARCH_QUERY_YEAR, KEY_SEARCH_QUERY_SYSTEM, KEY_SEARCH_QUERY_PUBLISHER, KEY_SEARCH_QUERY_CATEGORY, KEY_SEARCH_QUERY_BRANCH }; } @Override public String getLast_error() { return m_last_error; } private void setMediaTypeFromImageFilename(SearchResult sr, String imagename) { String[] fparts1 = imagename.split("/"); // "images/31.gif.S" String[] fparts2 = fparts1[fparts1.length - 1].split("\\."); // "31.gif.S" String lookup = fparts2[0]; // "31" if (m_data.has("mediatypes")) { try { String typeStr = m_data.getJSONObject("mediatypes").getString( lookup); sr.setType(MediaType.valueOf(typeStr)); } catch (Exception e) { if (defaulttypes.containsKey(lookup)) { sr.setType(defaulttypes.get(lookup)); } } } else { if (defaulttypes.containsKey(lookup)) { sr.setType(defaulttypes.get(lookup)); } } } /* * Parser for non XML compliant html part: (the crazy way) Get text from * <input> without end tag </input> * * Example Offenburg: <input type="radio" name="MT" * value="MTYP10">Belletristik&nbsp;&nbsp; Regex1: value="MTYP10".*?>([^<]+) */ private String parse_option_regex(Element inputTag) { String optStr = inputTag.val(); String html = inputTag.parent().html(); String result = optStr; String regex1 = "value=\"" + optStr + "\".*?>([^<]+)"; String[] regexList = new String[] { regex1 }; for (String regex : regexList) { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(html); if (matcher.find()) { result = matcher.group(1); result = result.replaceAll("&nbsp;", " ").trim(); break; } } return result; } /* * ----- media types ----- Example Wuerzburg: <td ...><input type="checkbox" * name="MT" value="1" ...></td> <td ...><img src="../image/spacer.gif.S" * title="Buch"><br>Buch</td> * * Example Friedrichshafen: <td ...><input type="checkbox" name="MS" * value="1" ...></td> <td ...><img src="../image/spacer.gif.S" * title="Buch"><br>Buch</td> * * Example Offenburg: <input type="radio" name="MT" checked * value="MTYP0">Alles&nbsp;&nbsp; <input type="radio" name="MT" * value="MTYP10">Belletristik&nbsp;&nbsp; Unfortunately Biber miss the end * tag </input>, so opt.text() does not work! (at least Offenburg) * * Example Essen, Aschaffenburg: <input type="radio" name="MT" checked * value="MTYP0"><img src="../image/all.gif.S" title="Alles"> <input * type="radio" name="MT" value="MTYP7"><img src="../image/cdrom.gif.S" * title="CD-ROM"> * * ----- Branches ----- Example Essen,Erkrath: no closing </option> !!! * cannot be parsed by Jsoup, so not supported <select name="AORT"> <option * value="ZWST1">Altendorf </select> * * Example Hagen, Würzburg, Friedrichshafen: <select name="ZW" class="sel1"> * <option selected value="ZWST0">Alle Bibliotheksorte</option> </select> */ private void extract_meta(Document doc) { m_metadata.open(); m_metadata.clearMeta(m_library.getIdent()); // get media types Elements mt_opts = doc.select("form input[name~=(MT|MS)]"); for (int i = 0; i < mt_opts.size(); i++) { Element opt = mt_opts.get(i); if (!opt.val().equals("")) { String text = opt.text(); if (text.length() == 0) { // text is empty, check layouts: // Essen: <input name="MT"><img title="mediatype"> // Schaffenb: <input name="MT"><img alt="mediatype"> Element img = opt.nextElementSibling(); if (img != null && img.tagName().equals("img")) { text = img.attr("title"); if (text.equals("")) { text = img.attr("alt"); } } } if (text.length() == 0) { // text is still empty, check table layout, Example // Friedrichshafen // <td><input name="MT"></td> <td><img // title="mediatype"></td> Element td1 = opt.parent(); Element td2 = td1.nextElementSibling(); if (td2 != null) { Elements td2Children = td2.select("img[title]"); if (td2Children.size() > 0) { text = td2Children.get(0).attr("title"); } } } if (text.length() == 0) { // text is still empty: missing end tag like Offenburg text = parse_option_regex(opt); } // ignore "all" because this is anyway added by this app if ((text.length() > 0) && !text.equalsIgnoreCase("alle") && !text.equalsIgnoreCase("alles")) { m_metadata.addMeta(MetaDataSource.META_TYPE_CATEGORY, m_library.getIdent(), opt.val(), text); } } } // get branches Elements br_opts = doc.select("form select[name=ZW] option"); for (int i = 0; i < br_opts.size(); i++) { Element opt = br_opts.get(i); // suppress "Alle Standorte", because "all" is added anyway by this // app if (!opt.val().equals("") && !opt.text().equals("") && !opt.text().startsWith("Alle")) { m_metadata.addMeta(MetaDataSource.META_TYPE_BRANCH, m_library.getIdent(), opt.val(), opt.text()); } } m_metadata.close(); } /* * Check connection to OPAC and get media types */ @Override public void start() throws IOException, NotReachableException { HttpGet httpget; if (m_opac_dir.equals("opax")) httpget = new HttpGet(m_opac_url + "/" + m_opac_dir + "/de/qsim.html.S"); else httpget = new HttpGet(m_opac_url + "/" + m_opac_dir + "/de/qsim_main.S"); HttpResponse response = http_client.execute(httpget); if (response.getStatusLine().getStatusCode() == 500) { throw new NotReachableException(); } m_initialised = true; String html = convertStreamToString(response.getEntity().getContent()); response.getEntity().consumeContent(); Document doc = Jsoup.parse(html); m_metadata.open(); if (!m_metadata.hasMeta(m_library.getIdent())) { m_metadata.close(); extract_meta(doc); } else { m_metadata.close(); } } @Override public void init(MetaDataSource metadata, Library lib) { http_client = HTTPClient.getNewHttpClient(lib); m_metadata = metadata; m_library = lib; m_data = lib.getData(); try { m_opac_url = m_data.getString("baseurl"); m_opac_dir = m_data.getString("opacdir"); } catch (JSONException e) { ACRA.getErrorReporter().handleException(e); } } public static String getStringFromBundle(Bundle bundle, String key) { // Workaround for Bundle.getString(key, default) being available not // before API 12 String res = bundle.getString(key); if (res == null) res = ""; return res; } /* * HTTP Push */ @Override public SearchRequestResult search(Bundle query) throws IOException, NotReachableException { if (!m_initialised) start(); String mediaType = getStringFromBundle(query, KEY_SEARCH_QUERY_CATEGORY); if (mediaType.equals("")) { mediaType = "MTYP0"; // key for "All" } String branch = getStringFromBundle(query, KEY_SEARCH_QUERY_BRANCH); if (branch.equals("")) { branch = "ZWST0"; // key for "All" } m_nameValuePairs.clear(); m_nameValuePairs.add(new BasicNameValuePair("CNN1", "AND")); m_nameValuePairs.add(new BasicNameValuePair("CNN2", "AND")); m_nameValuePairs.add(new BasicNameValuePair("CNN3", "AND")); m_nameValuePairs.add(new BasicNameValuePair("CNN4", "AND")); m_nameValuePairs.add(new BasicNameValuePair("CNN5", "AND")); m_nameValuePairs.add(new BasicNameValuePair("CNN6", "AND")); m_nameValuePairs.add(new BasicNameValuePair("CNN7", "AND")); m_nameValuePairs.add(new BasicNameValuePair("FLD1", getStringFromBundle(query, KEY_SEARCH_QUERY_AUTHOR))); m_nameValuePairs.add(new BasicNameValuePair("FLD2", getStringFromBundle(query, KEY_SEARCH_QUERY_TITLE))); m_nameValuePairs.add(new BasicNameValuePair("FLD3", getStringFromBundle(query, KEY_SEARCH_QUERY_KEYWORDA))); m_nameValuePairs.add(new BasicNameValuePair("FLD4", getStringFromBundle(query, KEY_SEARCH_QUERY_SYSTEM))); m_nameValuePairs.add(new BasicNameValuePair("FLD5", getStringFromBundle(query, KEY_SEARCH_QUERY_ISBN))); m_nameValuePairs.add(new BasicNameValuePair("FLD6", getStringFromBundle(query, KEY_SEARCH_QUERY_PUBLISHER))); m_nameValuePairs.add(new BasicNameValuePair("FLD7", getStringFromBundle(query, KEY_SEARCH_QUERY_YEAR))); m_nameValuePairs.add(new BasicNameValuePair("FUNC", "qsel")); m_nameValuePairs.add(new BasicNameValuePair("LANG", "de")); m_nameValuePairs.add(new BasicNameValuePair("MT", mediaType)); m_nameValuePairs.add(new BasicNameValuePair("REG1", "AW")); m_nameValuePairs.add(new BasicNameValuePair("REG2", "TW")); m_nameValuePairs.add(new BasicNameValuePair("REG3", "DW")); m_nameValuePairs.add(new BasicNameValuePair("REG4", "PP")); m_nameValuePairs.add(new BasicNameValuePair("REG5", "IS")); m_nameValuePairs.add(new BasicNameValuePair("REG6", "PU")); m_nameValuePairs.add(new BasicNameValuePair("REG7", "PY")); m_nameValuePairs.add(new BasicNameValuePair("SHOW", "20")); // but // result // brings 50 m_nameValuePairs.add(new BasicNameValuePair("SHOWSTAT", "N")); m_nameValuePairs.add(new BasicNameValuePair("ZW", branch)); m_nameValuePairs.add(new BasicNameValuePair("FROMPOS", "1")); return searchGetPage(1); } /* * (non-Javadoc) * * @see de.geeksfactory.opacclient.apis.OpacApi#searchGetPage(int) */ @Override public SearchRequestResult searchGetPage(int page) throws IOException, NotReachableException { int startNum = (page - 1) * numOfResultsPerPage + 1; // remove last element = "FROMPOS", and add a new one m_nameValuePairs.remove(m_nameValuePairs.size() - 1); m_nameValuePairs.add(new BasicNameValuePair("FROMPOS", String .valueOf(startNum))); String html = httpPost(m_opac_url + "/" + m_opac_dir + "/query.C", new UrlEncodedFormEntity(m_nameValuePairs)); return parse_search(html, page); } /* * result table format: JSON "rows_per_hit" = 1: One <tr> per hit JSON * "rows_per_hit" = 2: Two <tr> per hit (default) <form> <table> <tr * valign="top"> <td class="td3" ...><a href=...><img ...></a></td> (row is * optional, only in some bibs) <td class="td2" ...><input ...></td> <td * width="34%">TITEL</td> <td width="34%">&nbsp;</td> <td width="6%" * align="center">2009</td> <td width="*" align="left">DVD0 Seew</td> </tr> * <tr valign="top"> <td class="td3" ...>&nbsp;...</td> <td class="td2" * ...>&nbsp;...</td> <td colspan="4" ...><font size="-1"><font * class="p1">Erwachsenenbibliothek</font></font><div * class="hr4"></div></td> </tr> */ private SearchRequestResult parse_search(String html, int page) { List<SearchResult> results = new ArrayList<SearchResult>(); Document doc = Jsoup.parse(html); Elements trList = doc.select("form table tr[valign]"); // <tr // valign="top"> Elements elem = null; int rows_per_hit = 2; try { int rows = m_data.getInt("rows_per_hit"); rows_per_hit = rows; } catch (JSONException e) { } // Overall search results // are very differently layouted, but have always the text: // "....Treffer Gesamt (nnn)" int results_total; Pattern pattern = Pattern.compile("Treffer Gesamt \\(([0-9]+)\\)"); Matcher matcher = pattern.matcher(html); if (matcher.find()) { results_total = Integer.parseInt(matcher.group(1)); } else { results_total = -1; } // limit to 20 entries int numOfEntries = trList.size() / rows_per_hit; // two rows per entry if (numOfEntries > numOfResultsPerPage) numOfEntries = numOfResultsPerPage; for (int i = 0; i < numOfEntries; i++) { Element tr = trList.get(i * rows_per_hit); SearchResult sr = new SearchResult(); // ID as href tag elem = tr.select("td a"); if (elem.size() > 0) { String hrefID = elem.get(0).attr("href"); sr.setId(hrefID); } else { // no ID as href found, look for the ID in the input form elem = tr.select("td input"); if (elem.size() > 0) { String nameID = elem.get(0).attr("name").trim(); String hrefID = "/" + m_opac_dir + "/ftitle.C?LANG=de&FUNC=full&" + nameID + "=YES"; sr.setId(hrefID); } } // media type try { elem = tr.select("td img"); if (elem.size() > 0) { setMediaTypeFromImageFilename(sr, elem.get(0).attr("src")); } } catch (NumberFormatException e) { } // description String desc = ""; try { // array "searchtable" list the column numbers of the // description JSONArray searchtable = m_data.getJSONArray("searchtable"); for (int j = 0; j < searchtable.length(); j++) { int colNum = searchtable.getInt(j); if (j > 0) desc = desc + "<br />"; desc = desc + tr.child(colNum).html(); } } catch (Exception e) { e.printStackTrace(); } // remove links "<a ...>...</a> // needed for Friedrichshafen: "Warenkorb", "Vormerkung" // Herford: "Medienkorb" desc = desc.replaceAll("<a .*?</a>", ""); sr.setInnerhtml(desc); // number sr.setNr(i / rows_per_hit); results.add(sr); } // m_resultcount = results.size(); return new SearchRequestResult(results, results_total, page); } /* * (non-Javadoc) * * @see * de.geeksfactory.opacclient.apis.OpacApi#getResultById(java.lang.String) */ @Override public DetailledItem getResultById(String id, String homebranch) throws IOException, NotReachableException { if (!m_initialised) start(); // normally full path like // "/opac/ftitle.C?LANG=de&FUNC=full&331313252=YES" // but sometimes (Wuerzburg) "ftitle.C?LANG=de&FUNC=full&331313252=YES" if (!id.startsWith("/")) { id = "/" + m_opac_dir + "/" + id; } HttpGet httpget = new HttpGet(m_opac_url + id); HttpResponse response = http_client.execute(httpget); String html = convertStreamToString(response.getEntity().getContent()); response.getEntity().consumeContent(); return parse_result(html); } /* * (non-Javadoc) * * @see de.geeksfactory.opacclient.apis.OpacApi#getResult(int) */ @Override public DetailledItem getResult(int position) throws IOException { // not needed, normall all search results should have an ID, // so getResultById() is called return null; } /* * Two-column table inside of a form 1st column is category, e.g. * "Verfasser" 2nd column is content, e.g. "Bach, Johann Sebastian" In some * rows, the 1st column is empty, then 2nd column is continued text from row * above. * * Some libraries have a second section for the copies in stock (Exemplare). * This 2nd section has reverse layout. * * |-------------------| | Subject | Content | |-------------------| | * Subject | Content | |-------------------| | | Content | * |-------------------| | Subject | Content | * |-------------------------------------------------| | | Site | Signatur| * ID | State | |-------------------------------------------------| | | * Content | Content | Content | Content | * |-------------------------------------------------| */ private DetailledItem parse_result(String html) { DetailledItem item = new DetailledItem(); Document document = Jsoup.parse(html); Elements rows = document.select("html body form table tr"); // Elements rows = document.select("html body div form table tr"); // Element rowReverseSubject = null; Detail detail = null; // prepare copiestable ContentValues copy_last_content = null; int copy_row = 0; String[] copy_keys = new String[] { DetailledItem.KEY_COPY_BARCODE, // "barcode"; DetailledItem.KEY_COPY_BRANCH, // "zst"; DetailledItem.KEY_COPY_DEPARTMENT, // "abt"; DetailledItem.KEY_COPY_LOCATION, // "ort"; DetailledItem.KEY_COPY_STATUS, // "status"; DetailledItem.KEY_COPY_RETURN, // "rueckgabe"; DetailledItem.KEY_COPY_RESERVATIONS // "vorbestellt"; }; int[] copy_map = new int[] { 3, 1, -1, 1, 4, -1, -1 }; try { JSONObject map = m_data.getJSONObject("copiestable"); for (int i = 0; i < copy_keys.length; i++) { if (map.has(copy_keys[i])) copy_map[i] = map.getInt(copy_keys[i]); } } catch (Exception e) { // "copiestable" is optional } // go through all rows for (Element row : rows) { Elements columns = row.select("td"); if (columns.size() == 2) { // HTML tag "&nbsp;" is encoded as 0xA0 String firstColumn = columns.get(0).text() .replace("\u00a0", " ").trim(); String secondColumn = columns.get(1).text() .replace("\u00a0", " ").trim(); if (firstColumn.length() > 0) { // 1st column is category if (firstColumn.equalsIgnoreCase("titel")) { detail = null; item.setTitle(secondColumn); } else { detail = new Detail(firstColumn, secondColumn); item.getDetails().add(detail); } } else { // 1st column is empty, so it is an extension to last // category if (detail != null) { String content = detail.getContent() + "\n" + secondColumn; detail.setContent(content); } else { // detail==0, so it's the first row // check if there is an amazon image if (columns.get(0).select("a img[src]").size() > 0) { item.setCover(columns.get(0).select("a img") .first().attr("src")); } } } } else if (columns.size() > 2) { // This is the second section: the copies in stock ("Exemplare") // With reverse layout: first row is headline, skipped via // (copy_row > 0) if (copy_row > 0) { ContentValues e = new ContentValues(); for (int j = 0; j < copy_keys.length; j++) { int col = copy_map[j]; if (col > -1) { String text = ""; if (copy_keys[j] .equals(DetailledItem.KEY_COPY_BRANCH)) { // for "Standort" only use ownText() to suppress // Link "Wegweiser" text = columns.get(col).ownText() .replace("\u00a0", " ").trim(); } if (text.length() == 0) { // text of children text = columns.get(col).text() .replace("\u00a0", " ").trim(); } if (text.length() == 0) { // empty table cell, take the one above // this is sometimes the case for "Standort" if (copy_keys[j] .equals(DetailledItem.KEY_COPY_STATUS)) { // but do it not for Status text = " "; } else { text = copy_last_content .getAsString(copy_keys[j]); } } e.put(copy_keys[j], text); } } if (e.containsKey(DetailledItem.KEY_COPY_BRANCH) && e.containsKey(DetailledItem.KEY_COPY_LOCATION) && e.getAsString(DetailledItem.KEY_COPY_LOCATION) .equals(e .getAsString(DetailledItem.KEY_COPY_BRANCH))) e.remove(DetailledItem.KEY_COPY_LOCATION); item.addCopy(e); copy_last_content = e; }// ignore 1st row copy_row++; }// if columns.size }// for rows return item; } /* * (non-Javadoc) * * @see * de.geeksfactory.opacclient.apis.OpacApi#reservation(java.lang.String, * de.geeksfactory.opacclient.objects.Account, int, java.lang.String) */ @Override public ReservationResult reservation(String reservation_info, Account account, int useraction, String selection) throws IOException { // TODO reservations not yet supported return null; } /* * (non-Javadoc) * * @see * de.geeksfactory.opacclient.apis.OpacApi#prolong(de.geeksfactory.opacclient * .objects.Account, java.lang.String) * * Offenburg, prolong negative result: <table border="1" width="100%"> <tr> * <th ...>Nr</th> <th ...>Signatur / Kurztitel</th> <th * ...>F&auml;llig</th> <th ...>Status</th> </tr> <tr> <td * ...>101103778</td> <td ...>Hyde / Hyde, Anthony: Der Mann aus </td> <td * ...>09.04.2013</td> <td ...><font class="p1">verl&auml;ngerbar ab * 03.04.13, nicht verl&auml;ngert</font> <br>Bitte wenden Sie sich an Ihre * Bibliothek!</td> </tr> </table> * * Offenburg, prolong positive result: TO BE DESCRIBED */ @Override public ProlongResult prolong(String media, Account account, int useraction, String Selection) throws IOException { String command; // prolong media via http POST // Offenburg: URL is .../opac/verl.C // Hagen: URL is .../opax/renewmedia.C if (m_opac_dir.equals("opax")) { command = "/renewmedia.C"; } else { command = "/verl.C"; } List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair(media, "YES")); nameValuePairs .add(new BasicNameValuePair("BENUTZER", account.getName())); nameValuePairs.add(new BasicNameValuePair("FUNC", "verl")); nameValuePairs.add(new BasicNameValuePair("LANG", "de")); nameValuePairs.add(new BasicNameValuePair("PASSWORD", account .getPassword())); String html = httpPost(m_opac_url + "/" + m_opac_dir + command, new UrlEncodedFormEntity(nameValuePairs)); Document doc = Jsoup.parse(html); // Check result: // First we look for a cell with text "Status" // and store the column number // Then we look in the rows below at this column if // we find any text. Stop at first text we find. // This text must start with "verl�ngert" Elements rowElements = doc.select("table tr"); int statusCol = -1; // Status column not yet found // rows loop for (int i = 0; i < rowElements.size(); i++) { Element tr = rowElements.get(i); Elements tdList = tr.children(); // <th> or <td> // columns loop for (int j = 0; j < tdList.size(); j++) { String cellText = tdList.get(j).text().trim(); if (statusCol < 0) { // we look for cell with text "Status" if (cellText.equals("Status")) { statusCol = j; break; // next row } } else { // we look only at Status column // In "Hagen", there are some extra empty rows below if ((j == statusCol) && (cellText.length() > 0)) { // Status found if (cellText.matches("verl.ngert.*")) { return new ProlongResult(MultiStepResult.Status.OK); } else { return new ProlongResult( MultiStepResult.Status.ERROR, cellText); } } } }// for columns }// for rows return new ProlongResult(MultiStepResult.Status.ERROR, "unknown result"); } /* * (non-Javadoc) * * @see * de.geeksfactory.opacclient.apis.OpacApi#cancel(de.geeksfactory.opacclient * .objects.Account, java.lang.String) */ @Override public boolean cancel(Account account, String media) throws IOException { // TODO reservations not yet supported return false; } /* * (non-Javadoc) * * @see * de.geeksfactory.opacclient.apis.OpacApi#account(de.geeksfactory.opacclient * .objects.Account) * * POST-format: BENUTZER xxxxxxxxx FUNC medk LANG de PASSWORD ddmmyyyy */ @Override public AccountData account(Account account) throws IOException, JSONException { AccountData res = new AccountData(account.getId()); // get media List<ContentValues> medien = accountGetMedia(account, res); res.setLent(medien); // get reservations List<ContentValues> reservations = accountGetReservations(account); res.setReservations(reservations); return res; } private List<ContentValues> accountGetMedia(Account account, AccountData res) throws IOException, JSONException { List<ContentValues> medien = new ArrayList<ContentValues>(); // get media list via http POST Document doc = accountHttpPost(account, "medk"); if (doc == null) { return medien; } // parse result list JSONObject copymap = m_data.getJSONObject("accounttable"); Pattern expire = Pattern.compile("Ausweisg.ltigkeit: ([0-9.]+)"); Pattern fees = Pattern.compile("([0-9,.]+) ."); for (Element td : doc.select(".td01x09n")) { String text = td.text().trim(); if (expire.matcher(text).matches()) { res.setValidUntil(expire.matcher(text).replaceAll("$1")); } else if (fees.matcher(text).matches()) { res.setPendingFees(text); } } SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy"); Elements rowElements = doc.select("form[name=medkl] table tr"); // rows: skip 1st row -> title row for (int i = 1; i < rowElements.size(); i++) { Element tr = rowElements.get(i); if (tr.child(0).tagName().equals("th")) continue; ContentValues e = new ContentValues(); // columns: all elements of one media Iterator<?> keys = copymap.keys(); while (keys.hasNext()) { String key = (String) keys.next(); int index; try { index = copymap.has(key) ? copymap.getInt(key) : -1; } catch (JSONException e1) { index = -1; } if (index >= 0) { String value = tr.child(index).text().trim(); // Author and Title is the same field: "autor: title" // sometimes there is no ":" then only the title is given if (key.equals(AccountData.KEY_LENT_AUTHOR)) { if (value.contains(":")) { // Autor: remove everything starting at ":" value = value.replaceFirst("\\:.*", "").trim(); value = value.replaceFirst("^.* /", "").trim(); } else { // no Autor given value = ""; } } else if (key.equals(AccountData.KEY_LENT_TITLE)) { // Title: remove everything up to ":" value = value.replaceFirst(".*\\:", "").trim(); } if (value.length() != 0) { e.put(key, value); } } } if (tr.select("input[type=checkbox][value=YES]").size() > 0) e.put(AccountData.KEY_LENT_LINK, tr.select("input[type=checkbox][value=YES]").attr( "name")); // calculate lent timestamp for notification purpose if (e.containsKey(AccountData.KEY_LENT_DEADLINE)) { try { e.put(AccountData.KEY_LENT_DEADLINE_TIMESTAMP, sdf.parse( e.getAsString(AccountData.KEY_LENT_DEADLINE)) .getTime()); } catch (ParseException e1) { e1.printStackTrace(); } } medien.add(e); } return medien; } private List<ContentValues> accountGetReservations(Account account) throws IOException, JSONException { List<ContentValues> reservations = new ArrayList<ContentValues>(); if (!m_data.has("reservationtable")) { // reservations not specifically supported, let's just try it // with default values but fail silently JSONObject restblobj = new JSONObject(); restblobj.put("author", 3); restblobj.put("availability", 6); restblobj.put("branch", -1); restblobj.put("cancelurl", -1); restblobj.put("expirationdate", 5); restblobj.put("title", 3); m_data.put("reservationtable", restblobj); try { return accountGetReservations(account); } catch (Exception e) { return reservations; } } // get reservations list via http POST Document doc = accountHttpPost(account, "vorm"); if (doc == null) { // error message as html result return reservations; } // parse result list JSONObject copymap = m_data.getJSONObject("reservationtable"); Elements rowElements = doc.select("form[name=vorml] table tr"); // rows: skip 1st row -> title row for (int i = 1; i < rowElements.size(); i++) { Element tr = rowElements.get(i); if (tr.child(0).tagName().equals("th")) continue; ContentValues e = new ContentValues(); // columns: all elements of one media Iterator<?> keys = copymap.keys(); while (keys.hasNext()) { String key = (String) keys.next(); int index = copymap.getInt(key); if (index >= 0) { String value = tr.child(index).text(); // Author and Title is the same field: "autor: title" // sometimes there is no ":" then only the title is given if (key.equals(AccountData.KEY_RESERVATION_AUTHOR)) { if (value.contains(":")) { // Autor: remove everything starting at ":" value = value.replaceFirst("\\:.*", "").trim(); value = value.replaceFirst("^.* /", "").trim(); } else { // no Autor given value = ""; } } else if (key.equals(AccountData.KEY_RESERVATION_TITLE)) { // Title: remove everything up to ":" value = value.replaceFirst(".*\\:", "").trim(); } if (value.length() != 0) { e.put(key, value); } } } reservations.add(e); } return reservations; } private Document accountHttpPost(Account account, String func) throws IOException { // get media list via http POST List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("FUNC", func)); nameValuePairs.add(new BasicNameValuePair("LANG", "de")); nameValuePairs .add(new BasicNameValuePair("BENUTZER", account.getName())); nameValuePairs.add(new BasicNameValuePair("PASSWORD", account .getPassword())); String html = httpPost(m_opac_url + "/" + m_opac_dir + "/user.C", new UrlEncodedFormEntity(nameValuePairs)); Document doc = Jsoup.parse(html); // Error recognition // <title>OPAC Fehler</title> if (doc.title().contains("Fehler")) { String errText = "unknown error"; Elements elTable = doc.select("table"); if (elTable.size() > 0) { errText = elTable.get(0).text(); } m_last_error = errText; return null; } return doc; } @Override public boolean isAccountSupported(Library library) { return !library.getData().isNull("accounttable"); } @Override public boolean isAccountExtendable() { return false; } @Override public String getAccountExtendableInfo(Account account) throws IOException, NotReachableException { return null; } @Override public String getShareUrl(String id, String title) { // id is normally full path like // "/opac/ftitle.C?LANG=de&FUNC=full&331313252=YES" // but sometimes (Wuerzburg) "ftitle.C?LANG=de&FUNC=full&331313252=YES" if (!id.startsWith("/")) { id = "/" + m_opac_dir + "/" + id; } return m_opac_url + id; } @Override public int getSupportFlags() { return 0; } @Override public boolean prolongAll(Account account) throws IOException { return false; } @Override public SearchRequestResult filterResults(Filter filter, Option option) { // TODO Auto-generated method stub return null; } }
src/de/geeksfactory/opacclient/apis/BiBer1992.java
/** * Copyright (C) 2013 by Rüdiger Wurth under the MIT license: * * 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. */ package de.geeksfactory.opacclient.apis; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.acra.ACRA; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import android.content.ContentValues; import android.os.Bundle; import de.geeksfactory.opacclient.NotReachableException; import de.geeksfactory.opacclient.networking.HTTPClient; import de.geeksfactory.opacclient.objects.Account; import de.geeksfactory.opacclient.objects.AccountData; import de.geeksfactory.opacclient.objects.Detail; import de.geeksfactory.opacclient.objects.DetailledItem; import de.geeksfactory.opacclient.objects.Filter; import de.geeksfactory.opacclient.objects.Filter.Option; import de.geeksfactory.opacclient.objects.Library; import de.geeksfactory.opacclient.objects.SearchRequestResult; import de.geeksfactory.opacclient.objects.SearchResult; import de.geeksfactory.opacclient.objects.SearchResult.MediaType; import de.geeksfactory.opacclient.storage.MetaDataSource; /** * @author Ruediger Wurth, 16.02.2013 Web identification: * "copyright 1992-2011 by BiBer GmbH" * * BiBer gestartet mit Stadtbibliothek Offenburg start URL: * http://217.86.216.47/opac/de/qsim_frm.html.S * * open: issue #23: Basic support for library system "Biber" -> Essen * issue #32: Integration of "BiBer" (copyright 2006) -> Karlsruhe * https://opac.karlsruhe.de/ issue #33: Integration of "BiBer" * (copyright 1992) -> Essen * * Features: In getResult(), mixed table layout is supported: * column-wise and row-wise In getResult(), amazon bitmaps are supported * * Katalogsuche tested with * * Name Media amazon copy Media Branch Account type Bitmaps table types * support images avail search * -------------------------------------------------------------------- * BaWu/Friedrichshafen ok yes yes yes yes - BaWu/Lahr ok yes yes yes no * - BaWu/Offenburg ok n/a no yes n/a yes Bay/Aschaffenburg ok n/a no * yes n/a - Bay/Wuerzburg ok yes yes yes yes - NRW/Duisburg ok yes yes * yes n/a - NRW/Erkrath n/a yes no yes not sup.yes NRW/Essen n/a n/a no * yes not sup.- NRW/Gelsenkirchen ok yes yes yes yes - NRW/Hagen ok yes * yes yes yes yes NRW/Herford n/a yes yes yes n/a - NRW/Luenen ok yes * no yes n/a - NRW/MuelheimRuhr ok yes yes yes yes yes */ public class BiBer1992 extends BaseApi { private String m_opac_url = ""; private String m_opac_dir = "opac"; // sometimes also "opax" private JSONObject m_data; private MetaDataSource m_metadata; private boolean m_initialised = false; private String m_last_error; private Library m_library; private List<NameValuePair> m_nameValuePairs = new ArrayList<NameValuePair>( 2); protected static HashMap<String, MediaType> defaulttypes = new HashMap<String, MediaType>(); static { } // private int m_resultcount = 10; // private long logged_in; // private Account logged_in_as; // we have to limit num of results because PUSH attribute SHOW=20 does not // work: // number of results is always 50 which is too much final private int numOfResultsPerPage = 20; // from HTML: // <option value="AW">Autor</option> // <option value="TW">Titelwort</option> // <option value="DW">Thema</option> // <option value="PP">Standort</option> // <option value="IS">ISBN/ISSN</option> // <option value="PU">Verlag</option> // <option value="PY">Ersch.-Jahr</option> // <option value="LA">Sprache</option> @Override public String[] getSearchFields() { return new String[] { KEY_SEARCH_QUERY_TITLE, KEY_SEARCH_QUERY_AUTHOR, KEY_SEARCH_QUERY_KEYWORDA, KEY_SEARCH_QUERY_ISBN, KEY_SEARCH_QUERY_YEAR, KEY_SEARCH_QUERY_SYSTEM, KEY_SEARCH_QUERY_PUBLISHER, KEY_SEARCH_QUERY_CATEGORY, KEY_SEARCH_QUERY_BRANCH }; } @Override public String getLast_error() { return m_last_error; } private void setMediaTypeFromImageFilename(SearchResult sr, String imagename) { String[] fparts1 = imagename.split("/"); // "images/31.gif.S" String[] fparts2 = fparts1[fparts1.length - 1].split("\\."); // "31.gif.S" String lookup = fparts2[0]; // "31" if (m_data.has("mediatypes")) { try { String typeStr = m_data.getJSONObject("mediatypes").getString( lookup); sr.setType(MediaType.valueOf(typeStr)); } catch (Exception e) { if (defaulttypes.containsKey(lookup)) { sr.setType(defaulttypes.get(lookup)); } } } else { if (defaulttypes.containsKey(lookup)) { sr.setType(defaulttypes.get(lookup)); } } } /* * Parser for non XML compliant html part: (the crazy way) Get text from * <input> without end tag </input> * * Example Offenburg: <input type="radio" name="MT" * value="MTYP10">Belletristik&nbsp;&nbsp; Regex1: value="MTYP10".*?>([^<]+) */ private String parse_option_regex(Element inputTag) { String optStr = inputTag.val(); String html = inputTag.parent().html(); String result = optStr; String regex1 = "value=\"" + optStr + "\".*?>([^<]+)"; String[] regexList = new String[] { regex1 }; for (String regex : regexList) { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(html); if (matcher.find()) { result = matcher.group(1); result = result.replaceAll("&nbsp;", " ").trim(); break; } } return result; } /* * ----- media types ----- Example Wuerzburg: <td ...><input type="checkbox" * name="MT" value="1" ...></td> <td ...><img src="../image/spacer.gif.S" * title="Buch"><br>Buch</td> * * Example Friedrichshafen: <td ...><input type="checkbox" name="MS" * value="1" ...></td> <td ...><img src="../image/spacer.gif.S" * title="Buch"><br>Buch</td> * * Example Offenburg: <input type="radio" name="MT" checked * value="MTYP0">Alles&nbsp;&nbsp; <input type="radio" name="MT" * value="MTYP10">Belletristik&nbsp;&nbsp; Unfortunately Biber miss the end * tag </input>, so opt.text() does not work! (at least Offenburg) * * Example Essen, Aschaffenburg: <input type="radio" name="MT" checked * value="MTYP0"><img src="../image/all.gif.S" title="Alles"> <input * type="radio" name="MT" value="MTYP7"><img src="../image/cdrom.gif.S" * title="CD-ROM"> * * ----- Branches ----- Example Essen,Erkrath: no closing </option> !!! * cannot be parsed by Jsoup, so not supported <select name="AORT"> <option * value="ZWST1">Altendorf </select> * * Example Hagen, Würzburg, Friedrichshafen: <select name="ZW" class="sel1"> * <option selected value="ZWST0">Alle Bibliotheksorte</option> </select> */ private void extract_meta(Document doc) { m_metadata.open(); m_metadata.clearMeta(m_library.getIdent()); // get media types Elements mt_opts = doc.select("form input[name~=(MT|MS)]"); for (int i = 0; i < mt_opts.size(); i++) { Element opt = mt_opts.get(i); if (!opt.val().equals("")) { String text = opt.text(); if (text.length() == 0) { // text is empty, check layouts: // Essen: <input name="MT"><img title="mediatype"> // Schaffenb: <input name="MT"><img alt="mediatype"> Element img = opt.nextElementSibling(); if (img != null && img.tagName().equals("img")) { text = img.attr("title"); if (text.equals("")) { text = img.attr("alt"); } } } if (text.length() == 0) { // text is still empty, check table layout, Example // Friedrichshafen // <td><input name="MT"></td> <td><img // title="mediatype"></td> Element td1 = opt.parent(); Element td2 = td1.nextElementSibling(); if (td2 != null) { Elements td2Children = td2.select("img[title]"); if (td2Children.size() > 0) { text = td2Children.get(0).attr("title"); } } } if (text.length() == 0) { // text is still empty: missing end tag like Offenburg text = parse_option_regex(opt); } // ignore "all" because this is anyway added by this app if ((text.length() > 0) && !text.equalsIgnoreCase("alle") && !text.equalsIgnoreCase("alles")) { m_metadata.addMeta(MetaDataSource.META_TYPE_CATEGORY, m_library.getIdent(), opt.val(), text); } } } // get branches Elements br_opts = doc.select("form select[name=ZW] option"); for (int i = 0; i < br_opts.size(); i++) { Element opt = br_opts.get(i); // suppress "Alle Standorte", because "all" is added anyway by this // app if (!opt.val().equals("") && !opt.text().equals("") && !opt.text().startsWith("Alle")) { m_metadata.addMeta(MetaDataSource.META_TYPE_BRANCH, m_library.getIdent(), opt.val(), opt.text()); } } m_metadata.close(); } /* * Check connection to OPAC and get media types */ @Override public void start() throws IOException, NotReachableException { HttpGet httpget; if (m_opac_dir.equals("opax")) httpget = new HttpGet(m_opac_url + "/" + m_opac_dir + "/de/qsim.html.S"); else httpget = new HttpGet(m_opac_url + "/" + m_opac_dir + "/de/qsim_main.S"); HttpResponse response = http_client.execute(httpget); if (response.getStatusLine().getStatusCode() == 500) { throw new NotReachableException(); } m_initialised = true; String html = convertStreamToString(response.getEntity().getContent()); response.getEntity().consumeContent(); Document doc = Jsoup.parse(html); m_metadata.open(); if (!m_metadata.hasMeta(m_library.getIdent())) { m_metadata.close(); extract_meta(doc); } else { m_metadata.close(); } } @Override public void init(MetaDataSource metadata, Library lib) { http_client = HTTPClient.getNewHttpClient(lib); m_metadata = metadata; m_library = lib; m_data = lib.getData(); try { m_opac_url = m_data.getString("baseurl"); m_opac_dir = m_data.getString("opacdir"); } catch (JSONException e) { ACRA.getErrorReporter().handleException(e); } } public static String getStringFromBundle(Bundle bundle, String key) { // Workaround for Bundle.getString(key, default) being available not // before API 12 String res = bundle.getString(key); if (res == null) res = ""; return res; } /* * HTTP Push */ @Override public SearchRequestResult search(Bundle query) throws IOException, NotReachableException { if (!m_initialised) start(); String mediaType = getStringFromBundle(query, KEY_SEARCH_QUERY_CATEGORY); if (mediaType.equals("")) { mediaType = "MTYP0"; // key for "All" } String branch = getStringFromBundle(query, KEY_SEARCH_QUERY_BRANCH); if (branch.equals("")) { branch = "ZWST0"; // key for "All" } m_nameValuePairs.clear(); m_nameValuePairs.add(new BasicNameValuePair("CNN1", "AND")); m_nameValuePairs.add(new BasicNameValuePair("CNN2", "AND")); m_nameValuePairs.add(new BasicNameValuePair("CNN3", "AND")); m_nameValuePairs.add(new BasicNameValuePair("CNN4", "AND")); m_nameValuePairs.add(new BasicNameValuePair("CNN5", "AND")); m_nameValuePairs.add(new BasicNameValuePair("CNN6", "AND")); m_nameValuePairs.add(new BasicNameValuePair("CNN7", "AND")); m_nameValuePairs.add(new BasicNameValuePair("FLD1", getStringFromBundle(query, KEY_SEARCH_QUERY_AUTHOR))); m_nameValuePairs.add(new BasicNameValuePair("FLD2", getStringFromBundle(query, KEY_SEARCH_QUERY_TITLE))); m_nameValuePairs.add(new BasicNameValuePair("FLD3", getStringFromBundle(query, KEY_SEARCH_QUERY_KEYWORDA))); m_nameValuePairs.add(new BasicNameValuePair("FLD4", getStringFromBundle(query, KEY_SEARCH_QUERY_SYSTEM))); m_nameValuePairs.add(new BasicNameValuePair("FLD5", getStringFromBundle(query, KEY_SEARCH_QUERY_ISBN))); m_nameValuePairs.add(new BasicNameValuePair("FLD6", getStringFromBundle(query, KEY_SEARCH_QUERY_PUBLISHER))); m_nameValuePairs.add(new BasicNameValuePair("FLD7", getStringFromBundle(query, KEY_SEARCH_QUERY_YEAR))); m_nameValuePairs.add(new BasicNameValuePair("FUNC", "qsel")); m_nameValuePairs.add(new BasicNameValuePair("LANG", "de")); m_nameValuePairs.add(new BasicNameValuePair("MT", mediaType)); m_nameValuePairs.add(new BasicNameValuePair("REG1", "AW")); m_nameValuePairs.add(new BasicNameValuePair("REG2", "TW")); m_nameValuePairs.add(new BasicNameValuePair("REG3", "DW")); m_nameValuePairs.add(new BasicNameValuePair("REG4", "PP")); m_nameValuePairs.add(new BasicNameValuePair("REG5", "IS")); m_nameValuePairs.add(new BasicNameValuePair("REG6", "PU")); m_nameValuePairs.add(new BasicNameValuePair("REG7", "PY")); m_nameValuePairs.add(new BasicNameValuePair("SHOW", "20")); // but // result // brings 50 m_nameValuePairs.add(new BasicNameValuePair("SHOWSTAT", "N")); m_nameValuePairs.add(new BasicNameValuePair("ZW", branch)); m_nameValuePairs.add(new BasicNameValuePair("FROMPOS", "1")); return searchGetPage(1); } /* * (non-Javadoc) * * @see de.geeksfactory.opacclient.apis.OpacApi#searchGetPage(int) */ @Override public SearchRequestResult searchGetPage(int page) throws IOException, NotReachableException { int startNum = (page - 1) * numOfResultsPerPage + 1; // remove last element = "FROMPOS", and add a new one m_nameValuePairs.remove(m_nameValuePairs.size() - 1); m_nameValuePairs.add(new BasicNameValuePair("FROMPOS", String .valueOf(startNum))); String html = httpPost(m_opac_url + "/" + m_opac_dir + "/query.C", new UrlEncodedFormEntity(m_nameValuePairs)); return parse_search(html, page); } /* * result table format: JSON "rows_per_hit" = 1: One <tr> per hit JSON * "rows_per_hit" = 2: Two <tr> per hit (default) <form> <table> <tr * valign="top"> <td class="td3" ...><a href=...><img ...></a></td> (row is * optional, only in some bibs) <td class="td2" ...><input ...></td> <td * width="34%">TITEL</td> <td width="34%">&nbsp;</td> <td width="6%" * align="center">2009</td> <td width="*" align="left">DVD0 Seew</td> </tr> * <tr valign="top"> <td class="td3" ...>&nbsp;...</td> <td class="td2" * ...>&nbsp;...</td> <td colspan="4" ...><font size="-1"><font * class="p1">Erwachsenenbibliothek</font></font><div * class="hr4"></div></td> </tr> */ private SearchRequestResult parse_search(String html, int page) { List<SearchResult> results = new ArrayList<SearchResult>(); Document doc = Jsoup.parse(html); Elements trList = doc.select("form table tr[valign]"); // <tr // valign="top"> Elements elem = null; int rows_per_hit = 2; try { int rows = m_data.getInt("rows_per_hit"); rows_per_hit = rows; } catch (JSONException e) { } // Overall search results // are very differently layouted, but have always the text: // "....Treffer Gesamt (nnn)" int results_total; Pattern pattern = Pattern.compile("Treffer Gesamt \\(([0-9]+)\\)"); Matcher matcher = pattern.matcher(html); if (matcher.find()) { results_total = Integer.parseInt(matcher.group(1)); } else { results_total = -1; } // limit to 20 entries int numOfEntries = trList.size() / rows_per_hit; // two rows per entry if (numOfEntries > numOfResultsPerPage) numOfEntries = numOfResultsPerPage; for (int i = 0; i < numOfEntries; i++) { Element tr = trList.get(i * rows_per_hit); SearchResult sr = new SearchResult(); // ID as href tag elem = tr.select("td a"); if (elem.size() > 0) { String hrefID = elem.get(0).attr("href"); sr.setId(hrefID); } else { // no ID as href found, look for the ID in the input form elem = tr.select("td input"); if (elem.size() > 0) { String nameID = elem.get(0).attr("name").trim(); String hrefID = "/" + m_opac_dir + "/ftitle.C?LANG=de&FUNC=full&" + nameID + "=YES"; sr.setId(hrefID); } } // media type try { elem = tr.select("td img"); if (elem.size() > 0) { setMediaTypeFromImageFilename(sr, elem.get(0).attr("src")); } } catch (NumberFormatException e) { } // description String desc = ""; try { // array "searchtable" list the column numbers of the // description JSONArray searchtable = m_data.getJSONArray("searchtable"); for (int j = 0; j < searchtable.length(); j++) { int colNum = searchtable.getInt(j); if (j > 0) desc = desc + "<br />"; desc = desc + tr.child(colNum).html(); } } catch (Exception e) { e.printStackTrace(); } // remove links "<a ...>...</a> // needed for Friedrichshafen: "Warenkorb", "Vormerkung" // Herford: "Medienkorb" desc = desc.replaceAll("<a .*?</a>", ""); sr.setInnerhtml(desc); // number sr.setNr(i / rows_per_hit); results.add(sr); } // m_resultcount = results.size(); return new SearchRequestResult(results, results_total, page); } /* * (non-Javadoc) * * @see * de.geeksfactory.opacclient.apis.OpacApi#getResultById(java.lang.String) */ @Override public DetailledItem getResultById(String id, String homebranch) throws IOException, NotReachableException { if (!m_initialised) start(); // normally full path like // "/opac/ftitle.C?LANG=de&FUNC=full&331313252=YES" // but sometimes (Wuerzburg) "ftitle.C?LANG=de&FUNC=full&331313252=YES" if (!id.startsWith("/")) { id = "/" + m_opac_dir + "/" + id; } HttpGet httpget = new HttpGet(m_opac_url + id); HttpResponse response = http_client.execute(httpget); String html = convertStreamToString(response.getEntity().getContent()); response.getEntity().consumeContent(); return parse_result(html); } /* * (non-Javadoc) * * @see de.geeksfactory.opacclient.apis.OpacApi#getResult(int) */ @Override public DetailledItem getResult(int position) throws IOException { // not needed, normall all search results should have an ID, // so getResultById() is called return null; } /* * Two-column table inside of a form 1st column is category, e.g. * "Verfasser" 2nd column is content, e.g. "Bach, Johann Sebastian" In some * rows, the 1st column is empty, then 2nd column is continued text from row * above. * * Some libraries have a second section for the copies in stock (Exemplare). * This 2nd section has reverse layout. * * |-------------------| | Subject | Content | |-------------------| | * Subject | Content | |-------------------| | | Content | * |-------------------| | Subject | Content | * |-------------------------------------------------| | | Site | Signatur| * ID | State | |-------------------------------------------------| | | * Content | Content | Content | Content | * |-------------------------------------------------| */ private DetailledItem parse_result(String html) { DetailledItem item = new DetailledItem(); Document document = Jsoup.parse(html); Elements rows = document.select("html body form table tr"); // Elements rows = document.select("html body div form table tr"); // Element rowReverseSubject = null; Detail detail = null; // prepare copiestable ContentValues copy_last_content = null; int copy_row = 0; String[] copy_keys = new String[] { DetailledItem.KEY_COPY_BARCODE, // "barcode"; DetailledItem.KEY_COPY_BRANCH, // "zst"; DetailledItem.KEY_COPY_DEPARTMENT, // "abt"; DetailledItem.KEY_COPY_LOCATION, // "ort"; DetailledItem.KEY_COPY_STATUS, // "status"; DetailledItem.KEY_COPY_RETURN, // "rueckgabe"; DetailledItem.KEY_COPY_RESERVATIONS // "vorbestellt"; }; int[] copy_map = new int[] { 3, 1, -1, 1, 4, -1, -1 }; try { JSONObject map = m_data.getJSONObject("copiestable"); for (int i = 0; i < copy_keys.length; i++) { if (map.has(copy_keys[i])) copy_map[i] = map.getInt(copy_keys[i]); } } catch (Exception e) { // "copiestable" is optional } // go through all rows for (Element row : rows) { Elements columns = row.select("td"); if (columns.size() == 2) { // HTML tag "&nbsp;" is encoded as 0xA0 String firstColumn = columns.get(0).text() .replace("\u00a0", " ").trim(); String secondColumn = columns.get(1).text() .replace("\u00a0", " ").trim(); if (firstColumn.length() > 0) { // 1st column is category if (firstColumn.equalsIgnoreCase("titel")) { detail = null; item.setTitle(secondColumn); } else { detail = new Detail(firstColumn, secondColumn); item.getDetails().add(detail); } } else { // 1st column is empty, so it is an extension to last // category if (detail != null) { String content = detail.getContent() + "\n" + secondColumn; detail.setContent(content); } else { // detail==0, so it's the first row // check if there is an amazon image if (columns.get(0).select("a img[src]").size() > 0) { item.setCover(columns.get(0).select("a img") .first().attr("src")); } } } } else if (columns.size() > 2) { // This is the second section: the copies in stock ("Exemplare") // With reverse layout: first row is headline, skipped via // (copy_row > 0) if (copy_row > 0) { ContentValues e = new ContentValues(); for (int j = 0; j < copy_keys.length; j++) { int col = copy_map[j]; if (col > -1) { String text = ""; if (copy_keys[j] .equals(DetailledItem.KEY_COPY_BRANCH)) { // for "Standort" only use ownText() to suppress // Link "Wegweiser" text = columns.get(col).ownText() .replace("\u00a0", " ").trim(); } if (text.length() == 0) { // text of children text = columns.get(col).text() .replace("\u00a0", " ").trim(); } if (text.length() == 0) { // empty table cell, take the one above // this is sometimes the case for "Standort" if (copy_keys[j] .equals(DetailledItem.KEY_COPY_STATUS)) { // but do it not for Status text = " "; } else { text = copy_last_content .getAsString(copy_keys[j]); } } e.put(copy_keys[j], text); } } if (e.containsKey(DetailledItem.KEY_COPY_BRANCH) && e.containsKey(DetailledItem.KEY_COPY_LOCATION) && e.getAsString(DetailledItem.KEY_COPY_LOCATION) .equals(e .getAsString(DetailledItem.KEY_COPY_BRANCH))) e.remove(DetailledItem.KEY_COPY_LOCATION); item.addCopy(e); copy_last_content = e; }// ignore 1st row copy_row++; }// if columns.size }// for rows return item; } /* * (non-Javadoc) * * @see * de.geeksfactory.opacclient.apis.OpacApi#reservation(java.lang.String, * de.geeksfactory.opacclient.objects.Account, int, java.lang.String) */ @Override public ReservationResult reservation(String reservation_info, Account account, int useraction, String selection) throws IOException { // TODO reservations not yet supported return null; } /* * (non-Javadoc) * * @see * de.geeksfactory.opacclient.apis.OpacApi#prolong(de.geeksfactory.opacclient * .objects.Account, java.lang.String) * * Offenburg, prolong negative result: <table border="1" width="100%"> <tr> * <th ...>Nr</th> <th ...>Signatur / Kurztitel</th> <th * ...>F&auml;llig</th> <th ...>Status</th> </tr> <tr> <td * ...>101103778</td> <td ...>Hyde / Hyde, Anthony: Der Mann aus </td> <td * ...>09.04.2013</td> <td ...><font class="p1">verl&auml;ngerbar ab * 03.04.13, nicht verl&auml;ngert</font> <br>Bitte wenden Sie sich an Ihre * Bibliothek!</td> </tr> </table> * * Offenburg, prolong positive result: TO BE DESCRIBED */ @Override public ProlongResult prolong(String media, Account account, int useraction, String Selection) throws IOException { String command; // prolong media via http POST // Offenburg: URL is .../opac/verl.C // Hagen: URL is .../opax/renewmedia.C if (m_opac_dir.equals("opax")) { command = "/renewmedia.C"; } else { command = "/verl.C"; } List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair(media, "YES")); nameValuePairs .add(new BasicNameValuePair("BENUTZER", account.getName())); nameValuePairs.add(new BasicNameValuePair("FUNC", "verl")); nameValuePairs.add(new BasicNameValuePair("LANG", "de")); nameValuePairs.add(new BasicNameValuePair("PASSWORD", account .getPassword())); String html = httpPost(m_opac_url + "/" + m_opac_dir + command, new UrlEncodedFormEntity(nameValuePairs)); Document doc = Jsoup.parse(html); // Check result: // First we look for a cell with text "Status" // and store the column number // Then we look in the rows below at this column if // we find any text. Stop at first text we find. // This text must start with "verl�ngert" Elements rowElements = doc.select("table tr"); int statusCol = -1; // Status column not yet found // rows loop for (int i = 0; i < rowElements.size(); i++) { Element tr = rowElements.get(i); Elements tdList = tr.children(); // <th> or <td> // columns loop for (int j = 0; j < tdList.size(); j++) { String cellText = tdList.get(j).text().trim(); if (statusCol < 0) { // we look for cell with text "Status" if (cellText.equals("Status")) { statusCol = j; break; // next row } } else { // we look only at Status column // In "Hagen", there are some extra empty rows below if ((j == statusCol) && (cellText.length() > 0)) { // Status found if (cellText.matches("verl.ngert.*")) { return new ProlongResult(MultiStepResult.Status.OK); } else { return new ProlongResult( MultiStepResult.Status.ERROR, cellText); } } } }// for columns }// for rows return new ProlongResult(MultiStepResult.Status.ERROR, "unknown result"); } /* * (non-Javadoc) * * @see * de.geeksfactory.opacclient.apis.OpacApi#cancel(de.geeksfactory.opacclient * .objects.Account, java.lang.String) */ @Override public boolean cancel(Account account, String media) throws IOException { // TODO reservations not yet supported return false; } /* * (non-Javadoc) * * @see * de.geeksfactory.opacclient.apis.OpacApi#account(de.geeksfactory.opacclient * .objects.Account) * * POST-format: BENUTZER xxxxxxxxx FUNC medk LANG de PASSWORD ddmmyyyy */ @Override public AccountData account(Account account) throws IOException, JSONException { AccountData res = new AccountData(account.getId()); // get media List<ContentValues> medien = accountGetMedia(account); res.setLent(medien); // get reservations List<ContentValues> reservations = accountGetReservations(account); res.setReservations(reservations); return res; } private List<ContentValues> accountGetMedia(Account account) throws IOException, JSONException { List<ContentValues> medien = new ArrayList<ContentValues>(); // get media list via http POST Document doc = accountHttpPost(account, "medk"); if (doc == null) { return medien; } // parse result list JSONObject copymap = m_data.getJSONObject("accounttable"); SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy"); Elements rowElements = doc.select("form[name=medkl] table tr"); // rows: skip 1st row -> title row for (int i = 1; i < rowElements.size(); i++) { Element tr = rowElements.get(i); if (tr.child(0).tagName().equals("th")) continue; ContentValues e = new ContentValues(); // columns: all elements of one media Iterator<?> keys = copymap.keys(); while (keys.hasNext()) { String key = (String) keys.next(); int index; try { index = copymap.has(key) ? copymap.getInt(key) : -1; } catch (JSONException e1) { index = -1; } if (index >= 0) { String value = tr.child(index).text(); // Author and Title is the same field: "autor: title" // sometimes there is no ":" then only the title is given if (key.equals(AccountData.KEY_LENT_AUTHOR)) { if (value.contains(":")) { // Autor: remove everything starting at ":" value = value.replaceFirst("\\:.*", "").trim(); value = value.replaceFirst("^.* /", "").trim(); } else { // no Autor given value = ""; } } else if (key.equals(AccountData.KEY_LENT_TITLE)) { // Title: remove everything up to ":" value = value.replaceFirst(".*\\:", "").trim(); } if (value.length() != 0) { e.put(key, value); } } } if (tr.select("input[type=checkbox][value=YES]").size() > 0) e.put(AccountData.KEY_LENT_LINK, tr.select("input[type=checkbox][value=YES]").attr( "name")); // calculate lent timestamp for notification purpose if (e.containsKey(AccountData.KEY_LENT_DEADLINE)) { try { e.put(AccountData.KEY_LENT_DEADLINE_TIMESTAMP, sdf.parse( e.getAsString(AccountData.KEY_LENT_DEADLINE)) .getTime()); } catch (ParseException e1) { e1.printStackTrace(); } } medien.add(e); } return medien; } private List<ContentValues> accountGetReservations(Account account) throws IOException, JSONException { List<ContentValues> reservations = new ArrayList<ContentValues>(); if (!m_data.has("reservationtable")) { // reservations not specifically supported, let's just try it // with default values but fail silently JSONObject restblobj = new JSONObject(); restblobj.put("author", 3); restblobj.put("availability", 6); restblobj.put("branch", -1); restblobj.put("cancelurl", -1); restblobj.put("expirationdate", 5); restblobj.put("title", 3); m_data.put("reservationtable", restblobj); try { return accountGetReservations(account); } catch (Exception e) { return reservations; } } // get reservations list via http POST Document doc = accountHttpPost(account, "vorm"); if (doc == null) { // error message as html result return reservations; } // parse result list JSONObject copymap = m_data.getJSONObject("reservationtable"); Elements rowElements = doc.select("form[name=vorml] table tr"); // rows: skip 1st row -> title row for (int i = 1; i < rowElements.size(); i++) { Element tr = rowElements.get(i); if (tr.child(0).tagName().equals("th")) continue; ContentValues e = new ContentValues(); // columns: all elements of one media Iterator<?> keys = copymap.keys(); while (keys.hasNext()) { String key = (String) keys.next(); int index = copymap.getInt(key); if (index >= 0) { String value = tr.child(index).text(); // Author and Title is the same field: "autor: title" // sometimes there is no ":" then only the title is given if (key.equals(AccountData.KEY_RESERVATION_AUTHOR)) { if (value.contains(":")) { // Autor: remove everything starting at ":" value = value.replaceFirst("\\:.*", "").trim(); value = value.replaceFirst("^.* /", "").trim(); } else { // no Autor given value = ""; } } else if (key.equals(AccountData.KEY_RESERVATION_TITLE)) { // Title: remove everything up to ":" value = value.replaceFirst(".*\\:", "").trim(); } if (value.length() != 0) { e.put(key, value); } } } reservations.add(e); } return reservations; } private Document accountHttpPost(Account account, String func) throws IOException { // get media list via http POST List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("FUNC", func)); nameValuePairs.add(new BasicNameValuePair("LANG", "de")); nameValuePairs .add(new BasicNameValuePair("BENUTZER", account.getName())); nameValuePairs.add(new BasicNameValuePair("PASSWORD", account .getPassword())); String html = httpPost(m_opac_url + "/" + m_opac_dir + "/user.C", new UrlEncodedFormEntity(nameValuePairs)); Document doc = Jsoup.parse(html); // Error recognition // <title>OPAC Fehler</title> if (doc.title().contains("Fehler")) { String errText = "unknown error"; Elements elTable = doc.select("table"); if (elTable.size() > 0) { errText = elTable.get(0).text(); } m_last_error = errText; return null; } return doc; } @Override public boolean isAccountSupported(Library library) { return !library.getData().isNull("accounttable"); } @Override public boolean isAccountExtendable() { return false; } @Override public String getAccountExtendableInfo(Account account) throws IOException, NotReachableException { return null; } @Override public String getShareUrl(String id, String title) { // id is normally full path like // "/opac/ftitle.C?LANG=de&FUNC=full&331313252=YES" // but sometimes (Wuerzburg) "ftitle.C?LANG=de&FUNC=full&331313252=YES" if (!id.startsWith("/")) { id = "/" + m_opac_dir + "/" + id; } return m_opac_url + id; } @Override public int getSupportFlags() { return 0; } @Override public boolean prolongAll(Account account) throws IOException { return false; } @Override public SearchRequestResult filterResults(Filter filter, Option option) { // TODO Auto-generated method stub return null; } }
BiBer: pending fees and account expiry date
src/de/geeksfactory/opacclient/apis/BiBer1992.java
BiBer: pending fees and account expiry date
<ide><path>rc/de/geeksfactory/opacclient/apis/BiBer1992.java <ide> AccountData res = new AccountData(account.getId()); <ide> <ide> // get media <del> List<ContentValues> medien = accountGetMedia(account); <add> List<ContentValues> medien = accountGetMedia(account, res); <ide> res.setLent(medien); <ide> <ide> // get reservations <ide> return res; <ide> } <ide> <del> private List<ContentValues> accountGetMedia(Account account) <add> private List<ContentValues> accountGetMedia(Account account, AccountData res) <ide> throws IOException, JSONException { <ide> <ide> List<ContentValues> medien = new ArrayList<ContentValues>(); <ide> // parse result list <ide> JSONObject copymap = m_data.getJSONObject("accounttable"); <ide> <add> Pattern expire = Pattern.compile("Ausweisg.ltigkeit: ([0-9.]+)"); <add> Pattern fees = Pattern.compile("([0-9,.]+) ."); <add> for (Element td : doc.select(".td01x09n")) { <add> String text = td.text().trim(); <add> if (expire.matcher(text).matches()) { <add> res.setValidUntil(expire.matcher(text).replaceAll("$1")); <add> } else if (fees.matcher(text).matches()) { <add> res.setPendingFees(text); <add> } <add> } <ide> SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy"); <ide> Elements rowElements = doc.select("form[name=medkl] table tr"); <ide> <ide> index = -1; <ide> } <ide> if (index >= 0) { <del> String value = tr.child(index).text(); <add> String value = tr.child(index).text().trim(); <ide> <ide> // Author and Title is the same field: "autor: title" <ide> // sometimes there is no ":" then only the title is given
Java
epl-1.0
fef8b776dc4e5c05ecb109561e92c7381ca67a56
0
myyate/capsule,isdom/capsule,puniverse/capsule,trance1st/capsule,isdom/capsule,danthegoodman/capsule,leolujuyi/capsule,angrilove/capsule,lookfirst/capsule,puniverse/capsule,guiquanz/capsule,myyate/capsule,victorbriz/capsule,guiquanz/capsule,lookfirst/capsule,trance1st/capsule,lookfirst/capsule,lookfirst/capsule,leolujuyi/capsule,kevintvh/capsule,tal-m/capsule,lookfirst/capsule,victorbriz/capsule,kevintvh/capsule,angrilove/capsule,danthegoodman/capsule,tal-m/capsule
/* * Capsule * Copyright (c) 2014, Parallel Universe Software Co. All rights reserved. * * This program and the accompanying materials are licensed under the terms * of the Eclipse Public License v1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package capsule; import java.io.PrintStream; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.maven.repository.internal.MavenRepositorySystemUtils; import org.apache.maven.settings.Server; import org.apache.maven.settings.Settings; import org.apache.maven.settings.building.DefaultSettingsBuilderFactory; import org.apache.maven.settings.building.DefaultSettingsBuildingRequest; import org.apache.maven.settings.building.SettingsBuildingException; import org.apache.maven.settings.crypto.DefaultSettingsDecrypter; import org.apache.maven.settings.crypto.DefaultSettingsDecryptionRequest; import org.apache.maven.settings.crypto.SettingsDecryptionResult; import org.eclipse.aether.ConfigurationProperties; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.RepositoryException; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.artifact.DefaultArtifact; import org.eclipse.aether.collection.CollectRequest; import org.eclipse.aether.collection.CollectResult; import org.eclipse.aether.collection.DependencyCollectionException; import org.eclipse.aether.graph.Dependency; import org.eclipse.aether.graph.Exclusion; import org.eclipse.aether.impl.DefaultServiceLocator; import org.eclipse.aether.repository.AuthenticationSelector; import org.eclipse.aether.repository.LocalRepository; import org.eclipse.aether.repository.MirrorSelector; import org.eclipse.aether.repository.ProxySelector; import org.eclipse.aether.repository.RemoteRepository; import org.eclipse.aether.repository.RepositoryPolicy; import org.eclipse.aether.resolution.ArtifactResult; import org.eclipse.aether.resolution.DependencyRequest; import org.eclipse.aether.resolution.DependencyResolutionException; import org.eclipse.aether.resolution.VersionRangeRequest; import org.eclipse.aether.resolution.VersionRangeResult; import org.eclipse.aether.resolution.VersionRequest; import org.eclipse.aether.resolution.VersionResult; import org.eclipse.aether.util.artifact.JavaScopes; import org.eclipse.aether.util.graph.transformer.ConflictResolver; import org.eclipse.aether.util.repository.AuthenticationBuilder; import org.eclipse.aether.util.repository.ConservativeAuthenticationSelector; import org.eclipse.aether.util.repository.DefaultAuthenticationSelector; import org.eclipse.aether.util.repository.DefaultMirrorSelector; import org.eclipse.aether.util.repository.DefaultProxySelector; import org.eclipse.aether.version.Version; import org.sonatype.plexus.components.cipher.DefaultPlexusCipher; import org.sonatype.plexus.components.cipher.PlexusCipherException; import org.sonatype.plexus.components.sec.dispatcher.DefaultSecDispatcher; /** * Uses Aether as the Maven dependency manager. */ public class DependencyManagerImpl implements DependencyManager { /* * see http://git.eclipse.org/c/aether/aether-ant.git/tree/src/main/java/org/eclipse/aether/internal/ant/AntRepoSys.java */ //<editor-fold desc="Constants"> /////////// Constants /////////////////////////////////// private static final String PROP_OFFLINE = "capsule.offline"; private static final String PROP_CONNECT_TIMEOUT = "capsule.connect.timeout"; private static final String PROP_REQUEST_TIMEOUT = "capsule.request.timeout"; private static final String PROP_MAVEN_HOME = "maven.home"; private static final String PROP_USER_HOME = "user.home"; private static final String PROP_OS_NAME = "os.name"; private static final String ENV_MAVEN_HOME = "M2_HOME"; private static final String ENV_CONNECT_TIMEOUT = "CAPSULE_CONNECT_TIMEOUT"; private static final String ENV_REQUEST_TIMEOUT = "CAPSULE_REQUEST_TIMEOUT"; private static final String LATEST_VERSION = "[0,)"; private static final String SETTINGS_XML = "settings.xml"; private static final Path MAVEN_HOME = getMavenHome(); private static final Path DEFAULT_LOCAL_MAVEN = Paths.get(System.getProperty(PROP_USER_HOME), ".m2"); private static final Map<String, String> WELL_KNOWN_REPOS = stringMap( "central", "central(https://repo1.maven.org/maven2/)", "central-http", "central(http://repo1.maven.org/maven2/)", "jcenter", "jcenter(https://jcenter.bintray.com/)", "jcenter-http", "jcenter(http://jcenter.bintray.com/)", "local", "local(file:" + DEFAULT_LOCAL_MAVEN.resolve("repository") + ")" ); private static final int LOG_NONE = 0; private static final int LOG_QUIET = 1; private static final int LOG_VERBOSE = 2; private static final int LOG_DEBUG = 3; private static final String LOG_PREFIX = "CAPSULE: "; //</editor-fold> private final boolean forceRefresh; private final boolean offline; private final boolean allowSnapshots; private final RepositorySystem system; private final RepositorySystemSession session; private final List<RemoteRepository> repos; private final int logLevel; private final Settings settings; //<editor-fold desc="Construction and Setup"> /////////// Construction and Setup /////////////////////////////////// public DependencyManagerImpl(Path localRepoPath, List<String> repos, boolean forceRefresh, boolean allowSnapshots, int logLevel) { this.logLevel = logLevel; this.allowSnapshots = allowSnapshots; this.forceRefresh = forceRefresh; this.offline = isPropertySet(PROP_OFFLINE, false); log(LOG_DEBUG, "Offline: " + offline); if (localRepoPath == null) localRepoPath = DEFAULT_LOCAL_MAVEN.resolve("repository"); final LocalRepository localRepo = new LocalRepository(localRepoPath.toFile()); this.settings = getSettings(); this.system = newRepositorySystem(); this.session = newRepositorySession(system, localRepo); if (repos == null) repos = Arrays.asList("central"); this.repos = new ArrayList<RemoteRepository>(); for (String r : repos) this.repos.add(createRepo(r, allowSnapshots)); log(LOG_VERBOSE, "Dependency manager initialized with repositories: " + this.repos); } private static Path getMavenHome() { String mhome = emptyToNull(System.getenv(ENV_MAVEN_HOME)); if (mhome == null) mhome = System.getProperty(PROP_MAVEN_HOME); return mhome != null ? Paths.get(mhome) : null; } private static RepositorySystem newRepositorySystem() { /* * We're using DefaultServiceLocator rather than Guice/Sisu because it's more lightweight. * This method pulls together the necessary Aether components and plugins. */ final DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator(); locator.setErrorHandler(new DefaultServiceLocator.ErrorHandler() { @Override public void serviceCreationFailed(Class<?> type, Class<?> impl, Throwable ex) { throw new RuntimeException("Service creation failed for type " + type.getName() + " with impl " + impl, ex); } }); locator.addService(org.eclipse.aether.spi.connector.RepositoryConnectorFactory.class, org.eclipse.aether.connector.basic.BasicRepositoryConnectorFactory.class); locator.addService(org.eclipse.aether.spi.connector.transport.TransporterFactory.class, org.eclipse.aether.transport.http.HttpTransporterFactory.class); locator.addService(org.eclipse.aether.spi.connector.transport.TransporterFactory.class, org.eclipse.aether.transport.file.FileTransporterFactory.class); // Takari (support concurrent downloads) locator.setService(org.eclipse.aether.impl.SyncContextFactory.class, LockingSyncContextFactory.class); locator.setService(org.eclipse.aether.spi.io.FileProcessor.class, LockingFileProcessor.class); return locator.getService(RepositorySystem.class); } private RepositorySystemSession newRepositorySession(RepositorySystem system, LocalRepository localRepo) { final DefaultRepositorySystemSession s = MavenRepositorySystemUtils.newSession(); s.setConfigProperty(ConfigurationProperties.CONNECT_TIMEOUT, propertyOrEnv(PROP_CONNECT_TIMEOUT, ENV_CONNECT_TIMEOUT)); s.setConfigProperty(ConfigurationProperties.REQUEST_TIMEOUT, propertyOrEnv(PROP_REQUEST_TIMEOUT, ENV_REQUEST_TIMEOUT)); s.setConfigProperty(ConflictResolver.CONFIG_PROP_VERBOSE, true); s.setOffline(offline); s.setUpdatePolicy(forceRefresh ? RepositoryPolicy.UPDATE_POLICY_ALWAYS : RepositoryPolicy.UPDATE_POLICY_NEVER); s.setLocalRepositoryManager(system.newLocalRepositoryManager(s, localRepo)); s.setProxySelector(getProxySelector(settings)); s.setMirrorSelector(getMirrorSelector(settings)); s.setAuthenticationSelector(getAuthSelector(settings)); if (logLevel > LOG_NONE) { final PrintStream out = prefixStream(System.err, LOG_PREFIX); s.setTransferListener(new ConsoleTransferListener(isLogging(LOG_VERBOSE), out)); s.setRepositoryListener(new ConsoleRepositoryListener(isLogging(LOG_VERBOSE), out)); } return s; } //</editor-fold> //<editor-fold desc="Operations"> /////////// Operations /////////////////////////////////// private CollectRequest collect() { return new CollectRequest().setRepositories(repos); } @Override public void printDependencyTree(List<String> coords, String type, PrintStream out) { printDependencyTree(collect().setDependencies(toDependencies(coords, type)), out); } @Override public void printDependencyTree(String coords, String type, PrintStream out) { printDependencyTree(collect().setRoot(toDependency(coords, type)), out); } private void printDependencyTree(CollectRequest collectRequest, PrintStream out) { try { CollectResult collectResult = system.collectDependencies(session, collectRequest); collectResult.getRoot().accept(new ConsoleDependencyGraphDumper(out)); } catch (DependencyCollectionException e) { throw new RuntimeException(e); } } @Override public List<Path> resolveDependencies(List<String> coords, String type) { return resolve(collect().setDependencies(toDependencies(coords, type))); } @Override public List<Path> resolveDependency(String coords, String type) { return resolve(collect().setRoot(toDependency(coords, type))); // resolveDependencies(Collections.singletonList(coords), type); } private List<Path> resolve(CollectRequest collectRequest) { try { final DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, null); final List<ArtifactResult> artifactResults = system.resolveDependencies(session, dependencyRequest).getArtifactResults(); final List<Path> jars = new ArrayList<Path>(); for (ArtifactResult artifactResult : artifactResults) jars.add(artifactResult.getArtifact().getFile().toPath().toAbsolutePath()); return jars; } catch (DependencyResolutionException e) { throw new RuntimeException("Error resolving dependencies.", e); } } @Override public String getLatestVersion(String coords, String type) { return artifactToCoords(getLatestVersion0(coords, type)); } private Artifact getLatestVersion0(String coords, String type) { try { final Artifact artifact = coordsToArtifact(coords, type); final String version; if (isVersionRange(artifact.getVersion())) { final VersionRangeRequest request = new VersionRangeRequest().setRepositories(repos).setArtifact(artifact); final VersionRangeResult result = system.resolveVersionRange(session, request); final Version highestVersion = result.getHighestVersion(); version = highestVersion != null ? highestVersion.toString() : null; } else { final VersionRequest request = new VersionRequest().setRepositories(repos).setArtifact(artifact); final VersionResult result = system.resolveVersion(session, request); version = result.getVersion(); } if (version == null) throw new RuntimeException("Could not find any version of artifact " + coords + " (looking for: " + artifact + ")"); return artifact.setVersion(version); } catch (RepositoryException e) { throw new RuntimeException(e); } } private static boolean isVersionRange(String version) { return version.startsWith("(") || version.startsWith("["); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Parsing"> /////////// Parsing /////////////////////////////////// // visible for testing static Dependency toDependency(String coords, String type) { return new Dependency(coordsToArtifact(coords, type), JavaScopes.RUNTIME, false, getExclusions(coords)); } private static Dependency toDependency(Artifact artifact) { return new Dependency(artifact, JavaScopes.RUNTIME, false, null); } private static List<Dependency> toDependencies(List<String> coords, String type) { final List<Dependency> deps = new ArrayList<Dependency>(coords.size()); for (String c : coords) deps.add(toDependency(c, type)); return deps; } private static String artifactToCoords(Artifact artifact) { if (artifact == null) return null; return artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion() + ((artifact.getClassifier() != null && !artifact.getClassifier().isEmpty()) ? (":" + artifact.getClassifier()) : ""); } private static final Pattern PAT_DEPENDENCY = Pattern.compile("(?<groupId>[^:\\(]+):(?<artifactId>[^:\\(]+)(:(?<version>\\(?[^:\\(]*))?(:(?<classifier>[^:\\(]+))?(\\((?<exclusions>[^\\(\\)]*)\\))?"); private static Artifact coordsToArtifact(final String depString, String type) { final Matcher m = PAT_DEPENDENCY.matcher(depString); if (!m.matches()) throw new IllegalArgumentException("Could not parse dependency: " + depString); final String groupId = m.group("groupId"); final String artifactId = m.group("artifactId"); String version = m.group("version"); if (version == null || version.isEmpty()) version = LATEST_VERSION; final String classifier = m.group("classifier"); return new DefaultArtifact(groupId, artifactId, classifier, type, version); } private static Collection<Exclusion> getExclusions(String depString) { final Matcher m = PAT_DEPENDENCY.matcher(depString); if (!m.matches()) throw new IllegalArgumentException("Could not parse dependency: " + depString); if (m.group("exclusions") == null || m.group("exclusions").isEmpty()) return null; final List<String> exclusionPatterns = Arrays.asList(m.group("exclusions").split(",")); final List<Exclusion> exclusions = new ArrayList<Exclusion>(); for (String ex : exclusionPatterns) { String[] coords = ex.trim().split(":"); if (coords.length != 2) throw new IllegalArgumentException("Illegal exclusion dependency coordinates: " + depString + " (in exclusion " + ex + ")"); exclusions.add(new Exclusion(coords[0], coords[1], "*", "*")); } return exclusions; } private static final Pattern PAT_REPO = Pattern.compile("(?<id>[^(]+)(\\((?<url>[^\\)]+)\\))?"); // visible for testing static RemoteRepository createRepo(String repo, boolean allowSnapshots) { final Matcher m = PAT_REPO.matcher(repo); if (!m.matches()) throw new IllegalArgumentException("Could not parse repository: " + repo); String id = m.group("id"); String url = m.group("url"); if (url == null && WELL_KNOWN_REPOS.containsKey(id)) return createRepo(WELL_KNOWN_REPOS.get(id), allowSnapshots); if (url == null) url = id; RepositoryPolicy releasePolicy = new RepositoryPolicy(true, RepositoryPolicy.UPDATE_POLICY_NEVER, RepositoryPolicy.CHECKSUM_POLICY_WARN); RepositoryPolicy snapshotPolicy = allowSnapshots ? releasePolicy : new RepositoryPolicy(false, null, null); if (url.startsWith("file:")) { releasePolicy = new RepositoryPolicy(releasePolicy.isEnabled(), releasePolicy.getUpdatePolicy(), RepositoryPolicy.CHECKSUM_POLICY_IGNORE); snapshotPolicy = releasePolicy; } return new RemoteRepository.Builder(id, "default", url).setReleasePolicy(releasePolicy).setSnapshotPolicy(snapshotPolicy).build(); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Setup Helpers"> /////////// Setup Helpers /////////////////////////////////// private static Settings getSettings() { final DefaultSettingsBuildingRequest request = new DefaultSettingsBuildingRequest(); request.setUserSettingsFile(DEFAULT_LOCAL_MAVEN.resolve(SETTINGS_XML).toFile()); request.setGlobalSettingsFile(MAVEN_HOME != null ? MAVEN_HOME.resolve("conf").resolve(SETTINGS_XML).toFile() : null); request.setSystemProperties(getSystemProperties()); try { final Settings settings = new DefaultSettingsBuilderFactory().newInstance().build(request).getEffectiveSettings(); final SettingsDecryptionResult result = newDefaultSettingsDecrypter().decrypt(new DefaultSettingsDecryptionRequest(settings)); settings.setServers(result.getServers()); settings.setProxies(result.getProxies()); return settings; } catch (SettingsBuildingException e) { throw new RuntimeException(e); } } private static Properties getSystemProperties() { Properties props = new Properties(); getEnvProperties(props); props.putAll(System.getProperties()); return props; } private static Properties getEnvProperties(Properties props) { if (props == null) props = new Properties(); boolean envCaseInsensitive = isWindows(); for (Map.Entry<String, String> entry : System.getenv().entrySet()) { String key = entry.getKey(); if (envCaseInsensitive) key = key.toUpperCase(Locale.ENGLISH); key = "env." + key; props.put(key, entry.getValue()); } return props; } private static ProxySelector getProxySelector(Settings settings) { final DefaultProxySelector selector = new DefaultProxySelector(); for (org.apache.maven.settings.Proxy proxy : settings.getProxies()) { AuthenticationBuilder auth = new AuthenticationBuilder(); auth.addUsername(proxy.getUsername()).addPassword(proxy.getPassword()); selector.add(new org.eclipse.aether.repository.Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), auth.build()), proxy.getNonProxyHosts()); } return selector; } private static MirrorSelector getMirrorSelector(Settings settings) { final DefaultMirrorSelector selector = new DefaultMirrorSelector(); for (org.apache.maven.settings.Mirror mirror : settings.getMirrors()) selector.add(String.valueOf(mirror.getId()), mirror.getUrl(), mirror.getLayout(), false, mirror.getMirrorOf(), mirror.getMirrorOfLayouts()); return selector; } private static AuthenticationSelector getAuthSelector(Settings settings) { final DefaultAuthenticationSelector selector = new DefaultAuthenticationSelector(); for (Server server : settings.getServers()) { AuthenticationBuilder auth = new AuthenticationBuilder(); auth.addUsername(server.getUsername()).addPassword(server.getPassword()); auth.addPrivateKey(server.getPrivateKey(), server.getPassphrase()); selector.add(server.getId(), auth.build()); } return new ConservativeAuthenticationSelector(selector); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="General Utils"> /////////// General Utils /////////////////////////////////// private static PrintStream prefixStream(PrintStream out, final String prefix) { return new PrintStream(out) { @Override public void println(String x) { super.println(prefix + x); } }; } private static String propertyOrEnv(String propName, String envVar) { String val = System.getProperty(propName); if (val == null) val = emptyToNull(System.getenv(envVar)); return val; } private static Boolean isPropertySet(String property, boolean defaultValue) { final String val = System.getProperty(property); if (val == null) return defaultValue; return "".equals(val) | Boolean.parseBoolean(val); } private static String emptyToNull(String s) { if (s == null) return null; s = s.trim(); return s.isEmpty() ? null : s; } private static Map<String, String> stringMap(String... ss) { final Map<String, String> m = new HashMap<>(); for (int i = 0; i < ss.length / 2; i++) m.put(ss[i * 2], ss[i * 2 + 1]); return Collections.unmodifiableMap(m); } private static boolean isWindows() { return System.getProperty(PROP_OS_NAME).toLowerCase().startsWith("windows"); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Logging"> /////////// Logging /////////////////////////////////// private boolean isLogging(int level) { return level <= logLevel; } private void log(int level, String str) { if (isLogging(level)) System.err.println(LOG_PREFIX + str); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="DI Workarounds"> /////////// DI Workarounds /////////////////////////////////// private static DefaultSettingsDecrypter newDefaultSettingsDecrypter() { /* * see: * http://git.eclipse.org/c/aether/aether-ant.git/tree/src/main/java/org/eclipse/aether/internal/ant/AntSettingsDecryptorFactory.java * http://git.eclipse.org/c/aether/aether-ant.git/tree/src/main/java/org/eclipse/aether/internal/ant/AntSecDispatcher.java */ DefaultSecDispatcher secDispatcher = new DefaultSecDispatcher() { { _configurationFile = "~/.m2/settings-security.xml"; try { _cipher = new DefaultPlexusCipher(); } catch (PlexusCipherException e) { throw new RuntimeException(e); } } }; final DefaultSettingsDecrypter decrypter = new DefaultSettingsDecrypter(); try { java.lang.reflect.Field field = decrypter.getClass().getDeclaredField("securityDispatcher"); field.setAccessible(true); field.set(decrypter, secDispatcher); } catch (ReflectiveOperationException e) { throw new AssertionError(e); } return decrypter; } // necessary if we want to forgo Guice/Sisu injection and use DefaultServiceLocator instead private static final io.takari.filemanager.FileManager takariFileManager = new io.takari.filemanager.internal.DefaultFileManager(); public static class LockingFileProcessor extends io.takari.aether.concurrency.LockingFileProcessor { public LockingFileProcessor() { super(takariFileManager); } } public static class LockingSyncContextFactory extends io.takari.aether.concurrency.LockingSyncContextFactory { public LockingSyncContextFactory() { super(takariFileManager); } } //</editor-fold> }
capsule/src/main/java/capsule/DependencyManagerImpl.java
/* * Capsule * Copyright (c) 2014, Parallel Universe Software Co. All rights reserved. * * This program and the accompanying materials are licensed under the terms * of the Eclipse Public License v1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package capsule; import java.io.PrintStream; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.maven.repository.internal.MavenRepositorySystemUtils; import org.apache.maven.settings.Server; import org.apache.maven.settings.Settings; import org.apache.maven.settings.building.DefaultSettingsBuilderFactory; import org.apache.maven.settings.building.DefaultSettingsBuildingRequest; import org.apache.maven.settings.building.SettingsBuildingException; import org.apache.maven.settings.crypto.DefaultSettingsDecrypter; import org.apache.maven.settings.crypto.DefaultSettingsDecryptionRequest; import org.apache.maven.settings.crypto.SettingsDecryptionResult; import org.eclipse.aether.ConfigurationProperties; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.RepositoryException; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.artifact.DefaultArtifact; import org.eclipse.aether.collection.CollectRequest; import org.eclipse.aether.collection.CollectResult; import org.eclipse.aether.collection.DependencyCollectionException; import org.eclipse.aether.graph.Dependency; import org.eclipse.aether.graph.Exclusion; import org.eclipse.aether.impl.DefaultServiceLocator; import org.eclipse.aether.repository.AuthenticationSelector; import org.eclipse.aether.repository.LocalRepository; import org.eclipse.aether.repository.MirrorSelector; import org.eclipse.aether.repository.ProxySelector; import org.eclipse.aether.repository.RemoteRepository; import org.eclipse.aether.repository.RepositoryPolicy; import org.eclipse.aether.resolution.ArtifactResult; import org.eclipse.aether.resolution.DependencyRequest; import org.eclipse.aether.resolution.DependencyResolutionException; import org.eclipse.aether.resolution.VersionRangeRequest; import org.eclipse.aether.resolution.VersionRangeResult; import org.eclipse.aether.resolution.VersionRequest; import org.eclipse.aether.resolution.VersionResult; import org.eclipse.aether.util.artifact.JavaScopes; import org.eclipse.aether.util.graph.transformer.ConflictResolver; import org.eclipse.aether.util.repository.AuthenticationBuilder; import org.eclipse.aether.util.repository.ConservativeAuthenticationSelector; import org.eclipse.aether.util.repository.DefaultAuthenticationSelector; import org.eclipse.aether.util.repository.DefaultMirrorSelector; import org.eclipse.aether.util.repository.DefaultProxySelector; import org.eclipse.aether.version.Version; import org.sonatype.plexus.components.cipher.DefaultPlexusCipher; import org.sonatype.plexus.components.cipher.PlexusCipherException; import org.sonatype.plexus.components.sec.dispatcher.DefaultSecDispatcher; /** * Uses Aether as the Maven dependency manager. */ public class DependencyManagerImpl implements DependencyManager { /* * see http://git.eclipse.org/c/aether/aether-ant.git/tree/src/main/java/org/eclipse/aether/internal/ant/AntRepoSys.java */ //<editor-fold desc="Constants"> /////////// Constants /////////////////////////////////// private static final String PROP_OFFLINE = "capsule.offline"; private static final String PROP_CONNECT_TIMEOUT = "capsule.connect.timeout"; private static final String PROP_REQUEST_TIMEOUT = "capsule.request.timeout"; private static final String PROP_MAVEN_HOME = "maven.home"; private static final String PROP_USER_HOME = "user.home"; private static final String PROP_OS_NAME = "os.name"; private static final String ENV_MAVEN_HOME = "M2_HOME"; private static final String ENV_CONNECT_TIMEOUT = "CAPSULE_CONNECT_TIMEOUT"; private static final String ENV_REQUEST_TIMEOUT = "CAPSULE_REQUEST_TIMEOUT"; private static final String LATEST_VERSION = "[0,)"; private static final String SETTINGS_XML = "settings.xml"; private static final Path MAVEN_HOME = getMavenHome(); private static final Path DEFAULT_LOCAL_MAVEN = Paths.get(System.getProperty(PROP_USER_HOME), ".m2"); private static final Map<String, String> WELL_KNOWN_REPOS = stringMap( "central", "central(https://repo1.maven.org/maven2/)", "central-http", "central(http://repo1.maven.org/maven2/)", "jcenter", "jcenter(https://jcenter.bintray.com/)", "jcenter-http", "jcenter(http://jcenter.bintray.com/)", "local", "local(file:" + DEFAULT_LOCAL_MAVEN.resolve("repository") + ")" ); private static final int LOG_NONE = 0; private static final int LOG_QUIET = 1; private static final int LOG_VERBOSE = 2; private static final int LOG_DEBUG = 3; private static final String LOG_PREFIX = "CAPSULE: "; //</editor-fold> private final boolean forceRefresh; private final boolean offline; private final boolean allowSnapshots; private final RepositorySystem system; private final RepositorySystemSession session; private final List<RemoteRepository> repos; private final int logLevel; private final Settings settings; //<editor-fold desc="Construction and Setup"> /////////// Construction and Setup /////////////////////////////////// public DependencyManagerImpl(Path localRepoPath, List<String> repos, boolean forceRefresh, boolean allowSnapshots, int logLevel) { this.logLevel = logLevel; this.allowSnapshots = allowSnapshots; this.forceRefresh = forceRefresh; this.offline = isPropertySet(PROP_OFFLINE, false); log(LOG_DEBUG, "Offline: " + offline); if (localRepoPath == null) localRepoPath = DEFAULT_LOCAL_MAVEN.resolve("repository"); final LocalRepository localRepo = new LocalRepository(localRepoPath.toFile()); this.settings = getSettings(); this.system = newRepositorySystem(); this.session = newRepositorySession(system, localRepo); if (repos == null) repos = Arrays.asList("central"); this.repos = new ArrayList<RemoteRepository>(); for (String r : repos) this.repos.add(createRepo(r, allowSnapshots)); log(LOG_VERBOSE, "Dependency manager initialized with repositories: " + this.repos); } private static Settings getSettings() { final DefaultSettingsBuildingRequest request = new DefaultSettingsBuildingRequest(); request.setUserSettingsFile(DEFAULT_LOCAL_MAVEN.resolve(SETTINGS_XML).toFile()); request.setGlobalSettingsFile(MAVEN_HOME != null ? MAVEN_HOME.resolve("conf").resolve(SETTINGS_XML).toFile() : null); request.setSystemProperties(getSystemProperties()); try { final Settings settings = new DefaultSettingsBuilderFactory().newInstance().build(request).getEffectiveSettings(); final SettingsDecryptionResult result = newDefaultSettingsDecrypter().decrypt(new DefaultSettingsDecryptionRequest(settings)); settings.setServers(result.getServers()); settings.setProxies(result.getProxies()); return settings; } catch (SettingsBuildingException e) { throw new RuntimeException(e); } } private static RepositorySystem newRepositorySystem() { /* * We're using DefaultServiceLocator rather than Guice/Sisu because it's more lightweight. * This method pulls together the necessary Aether components and plugins. */ final DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator(); locator.setErrorHandler(new DefaultServiceLocator.ErrorHandler() { @Override public void serviceCreationFailed(Class<?> type, Class<?> impl, Throwable ex) { throw new RuntimeException("Service creation failed for type " + type.getName() + " with impl " + impl, ex); } }); locator.addService(org.eclipse.aether.spi.connector.RepositoryConnectorFactory.class, org.eclipse.aether.connector.basic.BasicRepositoryConnectorFactory.class); locator.addService(org.eclipse.aether.spi.connector.transport.TransporterFactory.class, org.eclipse.aether.transport.http.HttpTransporterFactory.class); locator.addService(org.eclipse.aether.spi.connector.transport.TransporterFactory.class, org.eclipse.aether.transport.file.FileTransporterFactory.class); // Takari (support concurrent downloads) locator.setService(org.eclipse.aether.impl.SyncContextFactory.class, LockingSyncContextFactory.class); locator.setService(org.eclipse.aether.spi.io.FileProcessor.class, LockingFileProcessor.class); return locator.getService(RepositorySystem.class); } private RepositorySystemSession newRepositorySession(RepositorySystem system, LocalRepository localRepo) { final DefaultRepositorySystemSession s = MavenRepositorySystemUtils.newSession(); s.setConfigProperty(ConfigurationProperties.CONNECT_TIMEOUT, propertyOrEnv(PROP_CONNECT_TIMEOUT, ENV_CONNECT_TIMEOUT)); s.setConfigProperty(ConfigurationProperties.REQUEST_TIMEOUT, propertyOrEnv(PROP_REQUEST_TIMEOUT, ENV_REQUEST_TIMEOUT)); s.setConfigProperty(ConflictResolver.CONFIG_PROP_VERBOSE, true); s.setOffline(offline); s.setUpdatePolicy(forceRefresh ? RepositoryPolicy.UPDATE_POLICY_ALWAYS : RepositoryPolicy.UPDATE_POLICY_NEVER); s.setLocalRepositoryManager(system.newLocalRepositoryManager(s, localRepo)); s.setProxySelector(getProxySelector(settings)); s.setMirrorSelector(getMirrorSelector(settings)); s.setAuthenticationSelector(getAuthSelector(settings)); if (logLevel > LOG_NONE) { final PrintStream out = prefixStream(System.err, LOG_PREFIX); s.setTransferListener(new ConsoleTransferListener(isLogging(LOG_VERBOSE), out)); s.setRepositoryListener(new ConsoleRepositoryListener(isLogging(LOG_VERBOSE), out)); } return s; } //</editor-fold> //<editor-fold desc="Operations"> /////////// Operations /////////////////////////////////// private CollectRequest collect() { return new CollectRequest().setRepositories(repos); } @Override public void printDependencyTree(List<String> coords, String type, PrintStream out) { printDependencyTree(collect().setDependencies(toDependencies(coords, type)), out); } @Override public void printDependencyTree(String coords, String type, PrintStream out) { printDependencyTree(collect().setRoot(toDependency(coords, type)), out); } private void printDependencyTree(CollectRequest collectRequest, PrintStream out) { try { CollectResult collectResult = system.collectDependencies(session, collectRequest); collectResult.getRoot().accept(new ConsoleDependencyGraphDumper(out)); } catch (DependencyCollectionException e) { throw new RuntimeException(e); } } @Override public List<Path> resolveDependencies(List<String> coords, String type) { return resolve(collect().setDependencies(toDependencies(coords, type))); } @Override public List<Path> resolveDependency(String coords, String type) { return resolve(collect().setRoot(toDependency(coords, type))); // resolveDependencies(Collections.singletonList(coords), type); } private List<Path> resolve(CollectRequest collectRequest) { try { final DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, null); final List<ArtifactResult> artifactResults = system.resolveDependencies(session, dependencyRequest).getArtifactResults(); final List<Path> jars = new ArrayList<Path>(); for (ArtifactResult artifactResult : artifactResults) jars.add(artifactResult.getArtifact().getFile().toPath().toAbsolutePath()); return jars; } catch (DependencyResolutionException e) { throw new RuntimeException("Error resolving dependencies.", e); } } @Override public String getLatestVersion(String coords, String type) { return artifactToCoords(getLatestVersion0(coords, type)); } private Artifact getLatestVersion0(String coords, String type) { try { final Artifact artifact = coordsToArtifact(coords, type); final String version; if (isVersionRange(artifact.getVersion())) { final VersionRangeRequest request = new VersionRangeRequest().setRepositories(repos).setArtifact(artifact); final VersionRangeResult result = system.resolveVersionRange(session, request); final Version highestVersion = result.getHighestVersion(); version = highestVersion != null ? highestVersion.toString() : null; } else { final VersionRequest request = new VersionRequest().setRepositories(repos).setArtifact(artifact); final VersionResult result = system.resolveVersion(session, request); version = result.getVersion(); } if (version == null) throw new RuntimeException("Could not find any version of artifact " + coords + " (looking for: " + artifact + ")"); return artifact.setVersion(version); } catch (RepositoryException e) { throw new RuntimeException(e); } } private static boolean isVersionRange(String version) { return version.startsWith("(") || version.startsWith("["); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Parsing"> /////////// Parsing /////////////////////////////////// // visible for testing static Dependency toDependency(String coords, String type) { return new Dependency(coordsToArtifact(coords, type), JavaScopes.RUNTIME, false, getExclusions(coords)); } private static Dependency toDependency(Artifact artifact) { return new Dependency(artifact, JavaScopes.RUNTIME, false, null); } private static List<Dependency> toDependencies(List<String> coords, String type) { final List<Dependency> deps = new ArrayList<Dependency>(coords.size()); for (String c : coords) deps.add(toDependency(c, type)); return deps; } private static String artifactToCoords(Artifact artifact) { if (artifact == null) return null; return artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion() + ((artifact.getClassifier() != null && !artifact.getClassifier().isEmpty()) ? (":" + artifact.getClassifier()) : ""); } private static final Pattern PAT_DEPENDENCY = Pattern.compile("(?<groupId>[^:\\(]+):(?<artifactId>[^:\\(]+)(:(?<version>\\(?[^:\\(]*))?(:(?<classifier>[^:\\(]+))?(\\((?<exclusions>[^\\(\\)]*)\\))?"); private static Artifact coordsToArtifact(final String depString, String type) { final Matcher m = PAT_DEPENDENCY.matcher(depString); if (!m.matches()) throw new IllegalArgumentException("Could not parse dependency: " + depString); final String groupId = m.group("groupId"); final String artifactId = m.group("artifactId"); String version = m.group("version"); if (version == null || version.isEmpty()) version = LATEST_VERSION; final String classifier = m.group("classifier"); return new DefaultArtifact(groupId, artifactId, classifier, type, version); } private static Collection<Exclusion> getExclusions(String depString) { final Matcher m = PAT_DEPENDENCY.matcher(depString); if (!m.matches()) throw new IllegalArgumentException("Could not parse dependency: " + depString); if (m.group("exclusions") == null || m.group("exclusions").isEmpty()) return null; final List<String> exclusionPatterns = Arrays.asList(m.group("exclusions").split(",")); final List<Exclusion> exclusions = new ArrayList<Exclusion>(); for (String ex : exclusionPatterns) { String[] coords = ex.trim().split(":"); if (coords.length != 2) throw new IllegalArgumentException("Illegal exclusion dependency coordinates: " + depString + " (in exclusion " + ex + ")"); exclusions.add(new Exclusion(coords[0], coords[1], "*", "*")); } return exclusions; } private static final Pattern PAT_REPO = Pattern.compile("(?<id>[^(]+)(\\((?<url>[^\\)]+)\\))?"); // visible for testing static RemoteRepository createRepo(String repo, boolean allowSnapshots) { final Matcher m = PAT_REPO.matcher(repo); if (!m.matches()) throw new IllegalArgumentException("Could not parse repository: " + repo); String id = m.group("id"); String url = m.group("url"); if (url == null && WELL_KNOWN_REPOS.containsKey(id)) return createRepo(WELL_KNOWN_REPOS.get(id), allowSnapshots); if (url == null) url = id; RepositoryPolicy releasePolicy = new RepositoryPolicy(true, RepositoryPolicy.UPDATE_POLICY_NEVER, RepositoryPolicy.CHECKSUM_POLICY_WARN); RepositoryPolicy snapshotPolicy = allowSnapshots ? releasePolicy : new RepositoryPolicy(false, null, null); if (url.startsWith("file:")) { releasePolicy = new RepositoryPolicy(releasePolicy.isEnabled(), releasePolicy.getUpdatePolicy(), RepositoryPolicy.CHECKSUM_POLICY_IGNORE); snapshotPolicy = releasePolicy; } return new RemoteRepository.Builder(id, "default", url).setReleasePolicy(releasePolicy).setSnapshotPolicy(snapshotPolicy).build(); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Setup Helpers"> /////////// Setup Helpers /////////////////////////////////// private static Path getMavenHome() { String mhome = emptyToNull(System.getenv(ENV_MAVEN_HOME)); if (mhome == null) mhome = System.getProperty(PROP_MAVEN_HOME); return mhome != null ? Paths.get(mhome) : null; } private static Properties getSystemProperties() { Properties props = new Properties(); getEnvProperties(props); props.putAll(System.getProperties()); return props; } private static Properties getEnvProperties(Properties props) { if (props == null) props = new Properties(); boolean envCaseInsensitive = isWindows(); for (Map.Entry<String, String> entry : System.getenv().entrySet()) { String key = entry.getKey(); if (envCaseInsensitive) key = key.toUpperCase(Locale.ENGLISH); key = "env." + key; props.put(key, entry.getValue()); } return props; } private static ProxySelector getProxySelector(Settings settings) { final DefaultProxySelector selector = new DefaultProxySelector(); for (org.apache.maven.settings.Proxy proxy : settings.getProxies()) { AuthenticationBuilder auth = new AuthenticationBuilder(); auth.addUsername(proxy.getUsername()).addPassword(proxy.getPassword()); selector.add(new org.eclipse.aether.repository.Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), auth.build()), proxy.getNonProxyHosts()); } return selector; } private static MirrorSelector getMirrorSelector(Settings settings) { final DefaultMirrorSelector selector = new DefaultMirrorSelector(); for (org.apache.maven.settings.Mirror mirror : settings.getMirrors()) selector.add(String.valueOf(mirror.getId()), mirror.getUrl(), mirror.getLayout(), false, mirror.getMirrorOf(), mirror.getMirrorOfLayouts()); return selector; } private static AuthenticationSelector getAuthSelector(Settings settings) { final DefaultAuthenticationSelector selector = new DefaultAuthenticationSelector(); for (Server server : settings.getServers()) { AuthenticationBuilder auth = new AuthenticationBuilder(); auth.addUsername(server.getUsername()).addPassword(server.getPassword()); auth.addPrivateKey(server.getPrivateKey(), server.getPassphrase()); selector.add(server.getId(), auth.build()); } return new ConservativeAuthenticationSelector(selector); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="General Utils"> /////////// General Utils /////////////////////////////////// private static PrintStream prefixStream(PrintStream out, final String prefix) { return new PrintStream(out) { @Override public void println(String x) { super.println(prefix + x); } }; } private static String propertyOrEnv(String propName, String envVar) { String val = System.getProperty(propName); if (val == null) val = emptyToNull(System.getenv(envVar)); return val; } private static Boolean isPropertySet(String property, boolean defaultValue) { final String val = System.getProperty(property); if (val == null) return defaultValue; return "".equals(val) | Boolean.parseBoolean(val); } private static String emptyToNull(String s) { if (s == null) return null; s = s.trim(); return s.isEmpty() ? null : s; } private static Map<String, String> stringMap(String... ss) { final Map<String, String> m = new HashMap<>(); for (int i = 0; i < ss.length / 2; i++) m.put(ss[i * 2], ss[i * 2 + 1]); return Collections.unmodifiableMap(m); } private static boolean isWindows() { return System.getProperty(PROP_OS_NAME).toLowerCase().startsWith("windows"); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Logging"> /////////// Logging /////////////////////////////////// private boolean isLogging(int level) { return level <= logLevel; } private void log(int level, String str) { if (isLogging(level)) System.err.println(LOG_PREFIX + str); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="DI Workarounds"> /////////// DI Workarounds /////////////////////////////////// private static DefaultSettingsDecrypter newDefaultSettingsDecrypter() { /* * see: * http://git.eclipse.org/c/aether/aether-ant.git/tree/src/main/java/org/eclipse/aether/internal/ant/AntSettingsDecryptorFactory.java * http://git.eclipse.org/c/aether/aether-ant.git/tree/src/main/java/org/eclipse/aether/internal/ant/AntSecDispatcher.java */ DefaultSecDispatcher secDispatcher = new DefaultSecDispatcher() { { _configurationFile = "~/.m2/settings-security.xml"; try { _cipher = new DefaultPlexusCipher(); } catch (PlexusCipherException e) { throw new RuntimeException(e); } } }; final DefaultSettingsDecrypter decrypter = new DefaultSettingsDecrypter(); try { java.lang.reflect.Field field = decrypter.getClass().getDeclaredField("securityDispatcher"); field.setAccessible(true); field.set(decrypter, secDispatcher); } catch (ReflectiveOperationException e) { throw new AssertionError(e); } return decrypter; } // necessary if we want to forgo Guice/Sisu injection and use DefaultServiceLocator instead private static final io.takari.filemanager.FileManager takariFileManager = new io.takari.filemanager.internal.DefaultFileManager(); public static class LockingFileProcessor extends io.takari.aether.concurrency.LockingFileProcessor { public LockingFileProcessor() { super(takariFileManager); } } public static class LockingSyncContextFactory extends io.takari.aether.concurrency.LockingSyncContextFactory { public LockingSyncContextFactory() { super(takariFileManager); } } //</editor-fold> }
organization
capsule/src/main/java/capsule/DependencyManagerImpl.java
organization
<ide><path>apsule/src/main/java/capsule/DependencyManagerImpl.java <ide> /** <ide> * Uses Aether as the Maven dependency manager. <ide> */ <add> <add> <ide> public class DependencyManagerImpl implements DependencyManager { <ide> /* <ide> * see http://git.eclipse.org/c/aether/aether-ant.git/tree/src/main/java/org/eclipse/aether/internal/ant/AntRepoSys.java <ide> log(LOG_VERBOSE, "Dependency manager initialized with repositories: " + this.repos); <ide> } <ide> <del> private static Settings getSettings() { <del> final DefaultSettingsBuildingRequest request = new DefaultSettingsBuildingRequest(); <del> request.setUserSettingsFile(DEFAULT_LOCAL_MAVEN.resolve(SETTINGS_XML).toFile()); <del> request.setGlobalSettingsFile(MAVEN_HOME != null ? MAVEN_HOME.resolve("conf").resolve(SETTINGS_XML).toFile() : null); <del> request.setSystemProperties(getSystemProperties()); <del> <del> try { <del> final Settings settings = new DefaultSettingsBuilderFactory().newInstance().build(request).getEffectiveSettings(); <del> final SettingsDecryptionResult result = newDefaultSettingsDecrypter().decrypt(new DefaultSettingsDecryptionRequest(settings)); <del> <del> settings.setServers(result.getServers()); <del> settings.setProxies(result.getProxies()); <del> <del> return settings; <del> } catch (SettingsBuildingException e) { <del> throw new RuntimeException(e); <del> } <add> private static Path getMavenHome() { <add> String mhome = emptyToNull(System.getenv(ENV_MAVEN_HOME)); <add> if (mhome == null) <add> mhome = System.getProperty(PROP_MAVEN_HOME); <add> return mhome != null ? Paths.get(mhome) : null; <ide> } <ide> <ide> private static RepositorySystem newRepositorySystem() { <ide> <ide> //<editor-fold defaultstate="collapsed" desc="Setup Helpers"> <ide> /////////// Setup Helpers /////////////////////////////////// <del> private static Path getMavenHome() { <del> String mhome = emptyToNull(System.getenv(ENV_MAVEN_HOME)); <del> if (mhome == null) <del> mhome = System.getProperty(PROP_MAVEN_HOME); <del> return mhome != null ? Paths.get(mhome) : null; <add> private static Settings getSettings() { <add> final DefaultSettingsBuildingRequest request = new DefaultSettingsBuildingRequest(); <add> request.setUserSettingsFile(DEFAULT_LOCAL_MAVEN.resolve(SETTINGS_XML).toFile()); <add> request.setGlobalSettingsFile(MAVEN_HOME != null ? MAVEN_HOME.resolve("conf").resolve(SETTINGS_XML).toFile() : null); <add> request.setSystemProperties(getSystemProperties()); <add> <add> try { <add> final Settings settings = new DefaultSettingsBuilderFactory().newInstance().build(request).getEffectiveSettings(); <add> final SettingsDecryptionResult result = newDefaultSettingsDecrypter().decrypt(new DefaultSettingsDecryptionRequest(settings)); <add> <add> settings.setServers(result.getServers()); <add> settings.setProxies(result.getProxies()); <add> <add> return settings; <add> } catch (SettingsBuildingException e) { <add> throw new RuntimeException(e); <add> } <ide> } <ide> <ide> private static Properties getSystemProperties() {
Java
bsd-3-clause
080371ce7ee146bd575820e2956f04f66aa903d8
0
NCIP/c3pr,NCIP/c3pr,NCIP/c3pr
package edu.duke.cabig.c3pr.domain; import edu.duke.cabig.c3pr.utils.ProjectedList; import edu.duke.cabig.c3pr.utils.StringUtils; import gov.nih.nci.cabig.ctms.collections.LazyListHelper; import gov.nih.nci.cabig.ctms.domain.AbstractMutableDomainObject; import java.util.ArrayList; import java.util.List; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import org.apache.commons.collections15.functors.InstantiateFactory; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; import org.hibernate.annotations.Where; /** * A systematic evaluation of an observation or an intervention (for example, * treatment, drug, device, procedure or system) in one or more subjects. * Frequently this is a test of a particular hypothesis about the treatment, * drug, device, procedure or system. [CDAM] A study can be either primary or * correlative. A study is considered a primary study if it has one or more * correlative studies. A correlative study extends the objectives or * observations of a primary study, enrolling the same, or a subset of the same, * subjects as the primary study. A Clinical Trial is a Study with type= * "intervention" with subjects of type="human". * * @author Priyatam */ @Entity @Table(name = "STUDIES") @GenericGenerator(name = "id-generator", strategy = "native", parameters = { @Parameter(name = "sequence", value = "STUDIES_ID_SEQ") }) public class Study extends AbstractMutableDomainObject implements Comparable<Study> { private String blindedIndicator; private String multiInstitutionIndicator; private String randomizedIndicator; private String shortTitleText; private String longTitleText; private String descriptionText; private String precisText; private String phaseCode; private String status; private String type; private String primaryIdentifier; private Integer targetAccrualNumber; private List<Epoch> epochs; private RandomizationType randomizationType; private List<StudyDisease> studyDiseases = new ArrayList<StudyDisease>(); private List<StudyOrganization> studyOrganizations; private List<Identifier> identifiers; // TODO move into Command Object private String[] diseaseTermIds; private String diseaseCategoryAsText; private LazyListHelper lazyListHelper; // private ParameterizedInstantiateFactory<Identifier> identifierFactory; public Study() { lazyListHelper = new LazyListHelper(); lazyListHelper.add(StudySite.class, new ParameterizedBiDirectionalInstantiateFactory<StudySite>( StudySite.class, this)); lazyListHelper .add( StudyFundingSponsor.class, new ParameterizedBiDirectionalInstantiateFactory<StudyFundingSponsor>( StudyFundingSponsor.class, this)); lazyListHelper .add( StudyCoordinatingCenter.class, new ParameterizedBiDirectionalInstantiateFactory<StudyCoordinatingCenter>( StudyCoordinatingCenter.class, this)); // lazyListHelper.add(Epoch.class, epochFactory); lazyListHelper .add( TreatmentEpoch.class, new ParameterizedBiDirectionalInstantiateFactory<TreatmentEpoch>( TreatmentEpoch.class, this)); lazyListHelper .add( NonTreatmentEpoch.class, new ParameterizedBiDirectionalInstantiateFactory<NonTreatmentEpoch>( NonTreatmentEpoch.class, this)); lazyListHelper.add(SystemAssignedIdentifier.class, new ParameterizedInstantiateFactory<SystemAssignedIdentifier>( SystemAssignedIdentifier.class)); lazyListHelper .add( OrganizationAssignedIdentifier.class, new ParameterizedInstantiateFactory<OrganizationAssignedIdentifier>( OrganizationAssignedIdentifier.class)); lazyListHelper.add(StudyAmendment.class, new InstantiateFactory<StudyAmendment>(StudyAmendment.class)); // mandatory, so that the lazy-projected list is managed properly. setStudyOrganizations(new ArrayList<StudyOrganization>()); setEpochs(new ArrayList<Epoch>()); setIdentifiers(new ArrayList<Identifier>()); } @Transient public List<Identifier> getLocalIdentifiers() { List<Identifier> localIdentifiers = new ArrayList<Identifier>(); for (Identifier identifier : getIdentifiers()) { if ("Protocol Authority Identifier".equals(identifier.getType()) || "Coordinating Center Identifier".equals(identifier .getType())) { // nothing } else { localIdentifiers.add(identifier); } } return localIdentifiers; } @Transient public List<StudySite> getStudySites() { return lazyListHelper.getLazyList(StudySite.class); } public void setStudySites(List<StudySite> studySites) { // do nothing } @Transient public List<StudyFundingSponsor> getStudyFundingSponsors() { return lazyListHelper.getLazyList(StudyFundingSponsor.class); } public void setStudyFundingSponsors( List<StudyFundingSponsor> studyFundingSponsors) { // do nothing } @Transient public List<StudyCoordinatingCenter> getStudyCoordinatingCenters() { return lazyListHelper.getLazyList(StudyCoordinatingCenter.class); } public void setStudyCoordinatingCenters( List<StudyCoordinatingCenter> studyCoordinatingCenters) { // do nothing } @OneToMany(mappedBy = "study", fetch = FetchType.LAZY) @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) public List<StudyOrganization> getStudyOrganizations() { return studyOrganizations; } public void setStudyOrganizations(List<StudyOrganization> studyOrganizations) { this.studyOrganizations = studyOrganizations; // initialize projected list for StudySite, StudyFundingSponsor and // StudyCoordinatingCenter lazyListHelper.setInternalList(StudySite.class, new ProjectedList<StudySite>(this.studyOrganizations, StudySite.class)); lazyListHelper.setInternalList(StudyFundingSponsor.class, new ProjectedList<StudyFundingSponsor>(this.studyOrganizations, StudyFundingSponsor.class)); lazyListHelper .setInternalList(StudyCoordinatingCenter.class, new ProjectedList<StudyCoordinatingCenter>( this.studyOrganizations, StudyCoordinatingCenter.class)); } public void addStudyOrganization(StudyOrganization so) { this.getStudyOrganizations().add(so); so.setStudy(this); } public void removeStudyOrganization(StudyOrganization so) { this.getStudyOrganizations().remove(so); } public void addEpoch(Epoch epoch) throws RuntimeException { for (Epoch epochPresent : getEpochs()) { if (epochPresent.equals(epoch)) { throw new RuntimeException("epoch with same name already exists in study"); } } epoch.setStudy(this); getEpochs().add(epoch); } public void removeEpoch(Epoch epoch) { lazyListHelper.getLazyList(Epoch.class).remove(epoch); } public void addStudySite(StudySite studySite) { studySite.setStudy(this); lazyListHelper.getLazyList(StudySite.class).add(studySite); } public void removeStudySite(StudySite studySite) { lazyListHelper.getLazyList(StudySite.class).remove(studySite); } public void addStudyDisease(StudyDisease studyDisease) { studyDisease.setStudy(this); studyDiseases.add(studyDisease); } public void addIdentifier(Identifier identifier) { getIdentifiers().add(identifier); } public void removeIdentifier(Identifier identifier) { getIdentifiers().remove(identifier); } @Transient public OrganizationAssignedIdentifier getFundingSponsorAssignedIdentifier() { for (OrganizationAssignedIdentifier orgIdentifier:this.getOrganizationAssignedIdentifiers()){ if (orgIdentifier.getType().equals("Protocol Authority Identifier")) return orgIdentifier; } return null; } // / BEAN PROPERTIES // TODO: this stuff should really, really not be in here. It's // web-view/entry specific. @Transient public String[] getDiseaseTermIds() { return diseaseTermIds; } @Transient public String getDiseaseCategoryAsText() { return diseaseCategoryAsText; } @OneToMany @Cascade( { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) @JoinColumn(name = "STU_ID") public List<Identifier> getIdentifiers() { return identifiers; } public void setIdentifiers(List<Identifier> identifiers) { this.identifiers = identifiers; lazyListHelper.setInternalList(SystemAssignedIdentifier.class, new ProjectedList<SystemAssignedIdentifier>(this.identifiers, SystemAssignedIdentifier.class)); lazyListHelper .setInternalList(OrganizationAssignedIdentifier.class, new ProjectedList<OrganizationAssignedIdentifier>( this.identifiers, OrganizationAssignedIdentifier.class)); } @Transient public List<SystemAssignedIdentifier> getSystemAssignedIdentifiers() { return lazyListHelper.getLazyList(SystemAssignedIdentifier.class); } public void setSystemAssignedIdentifiers( List<SystemAssignedIdentifier> systemAssignedIdentifiers) { // do nothing } @Transient public List<OrganizationAssignedIdentifier> getOrganizationAssignedIdentifiers() { return lazyListHelper.getLazyList(OrganizationAssignedIdentifier.class); } public void setOrganizationAssignedIdentifiers( List<OrganizationAssignedIdentifier> organizationAssignedIdentifiers) { // do nothing } @OneToMany(mappedBy = "study", fetch = FetchType.LAZY) @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) public List<Epoch> getEpochs() { return epochs; } public void addAmendment(final StudyAmendment amendment) { getStudyAmendments().add(amendment); } @OneToMany(fetch = FetchType.LAZY) @JoinColumn(name = "stu_id", nullable = false) @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) public List<StudyAmendment> getStudyAmendmentsInternal() { return lazyListHelper.getInternalList(StudyAmendment.class); } public void setStudyAmendmentsInternal(final List<StudyAmendment> amendments) { lazyListHelper.setInternalList(StudyAmendment.class, amendments); } @Transient public List<StudyAmendment> getStudyAmendments() { return lazyListHelper.getLazyList(StudyAmendment.class); } public void setStudyAmendments(final List<StudyAmendment> amendments) { setStudyAmendmentsInternal(amendments); } public void setEpochs(List<Epoch> epochs) { this.epochs = epochs; lazyListHelper.setInternalList(TreatmentEpoch.class, new ProjectedList<TreatmentEpoch>(this.epochs, TreatmentEpoch.class)); lazyListHelper.setInternalList(NonTreatmentEpoch.class, new ProjectedList<NonTreatmentEpoch>(this.epochs, NonTreatmentEpoch.class)); } @Transient public List<TreatmentEpoch> getTreatmentEpochs() { return lazyListHelper.getLazyList(TreatmentEpoch.class); } public void setTreatmentEpochs(List<TreatmentEpoch> treatmentEpochs) { // do nothing } @Transient public List<NonTreatmentEpoch> getNonTreatmentEpochs() { return lazyListHelper.getLazyList(NonTreatmentEpoch.class); } public void setNonTreatmentEpochs(List<NonTreatmentEpoch> nonTreatmentEpochs) { // do nothing } @OneToMany(mappedBy = "study", fetch = FetchType.LAZY) @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) public List<StudyDisease> getStudyDiseases() { return studyDiseases; } public void setStudyDiseases(List<StudyDisease> studyDiseases) { this.studyDiseases = studyDiseases; } public void setDiseaseTermIds(String[] diseaseTermIds) { this.diseaseTermIds = diseaseTermIds; } public void setDiseaseCategoryAsText(String diseaseCategoryAsText) { this.diseaseCategoryAsText = diseaseCategoryAsText; } public String getDescriptionText() { return descriptionText; } public void setDescriptionText(String descriptionText) { this.descriptionText = descriptionText; } public String getLongTitleText() { return longTitleText; } public void setLongTitleText(String longTitleText) { this.longTitleText = longTitleText; } public String getPhaseCode() { return phaseCode; } public void setPhaseCode(String phaseCode) { this.phaseCode = phaseCode; } public String getPrecisText() { return precisText; } public void setPrecisText(String precisText) { this.precisText = precisText; } public String getShortTitleText() { return shortTitleText; } public void setShortTitleText(String shortTitleText) { this.shortTitleText = shortTitleText; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Integer getTargetAccrualNumber() { return targetAccrualNumber; } public void setTargetAccrualNumber(Integer targetAccrualNumber) { this.targetAccrualNumber = targetAccrualNumber; } public String getType() { return type; } public void setType(String type) { this.type = type; } public int compareTo(Study o) { if (this.equals(o)) return 0; return 1; } @Override public int hashCode() { final int PRIME = 31; int result=super.hashCode(); result = PRIME * result + ((getFundingSponsorAssignedIdentifier() == null) ? 0 : getFundingSponsorAssignedIdentifier().hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (getClass() != obj.getClass()) return false; final Study other = (Study) obj; if ((this.getFundingSponsorAssignedIdentifier() == null)|| (other.getFundingSponsorAssignedIdentifier()==null)) { return false;} else if (!((this.getFundingSponsorAssignedIdentifier().getValue()).equals(other.getFundingSponsorAssignedIdentifier().getValue()))) {return false;} else if (!((this.getFundingSponsorAssignedIdentifier().getHealthcareSite()).equals(other.getFundingSponsorAssignedIdentifier().getHealthcareSite()))) {return false;} return true; } @Transient public String getTrimmedShortTitleText() { return StringUtils.getTrimmedText(shortTitleText, 40); } @Transient public String getPrimaryIdentifier() { for (Identifier identifier : getIdentifiers()) { if (identifier.getPrimaryIndicator().booleanValue() == true) { return identifier.getValue(); } } return primaryIdentifier; } public String getBlindedIndicator() { return blindedIndicator; } public void setBlindedIndicator(String blindedIndicator) { this.blindedIndicator = blindedIndicator; } public String getMultiInstitutionIndicator() { return multiInstitutionIndicator; } public void setMultiInstitutionIndicator(String multiInstitutionIndicator) { this.multiInstitutionIndicator = multiInstitutionIndicator; } public String getRandomizedIndicator() { return randomizedIndicator; } public void setRandomizedIndicator(String randomizedIndicator) { this.randomizedIndicator = randomizedIndicator; } public RandomizationType getRandomizationType() { return randomizationType; } public void setRandomizationType(RandomizationType randomizationType) { this.randomizationType = randomizationType; } }
codebase/projects/core/src/java/edu/duke/cabig/c3pr/domain/Study.java
package edu.duke.cabig.c3pr.domain; import edu.duke.cabig.c3pr.utils.ProjectedList; import edu.duke.cabig.c3pr.utils.StringUtils; import gov.nih.nci.cabig.ctms.collections.LazyListHelper; import gov.nih.nci.cabig.ctms.domain.AbstractMutableDomainObject; import java.util.ArrayList; import java.util.List; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import org.apache.commons.collections15.functors.InstantiateFactory; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; import org.hibernate.annotations.Where; /** * A systematic evaluation of an observation or an * intervention (for example, treatment, drug, device, procedure or system) in one * or more subjects. Frequently this is a test of a particular hypothesis about * the treatment, drug, device, procedure or system. [CDAM] A study can be either * primary or correlative. A study is considered a primary study if it has one or * more correlative studies. A correlative study extends the objectives or * observations of a primary study, enrolling the same, or a subset of the same, * subjects as the primary study. A Clinical Trial is a Study with type= * "intervention" with subjects of type="human". * * @author Priyatam */ @Entity @Table(name = "STUDIES") @GenericGenerator(name = "id-generator", strategy = "native", parameters = { @Parameter(name = "sequence", value = "STUDIES_ID_SEQ") } ) public class Study extends AbstractMutableDomainObject implements Comparable<Study>{ private String blindedIndicator; private String multiInstitutionIndicator; private String randomizedIndicator; private String shortTitleText; private String longTitleText; private String descriptionText; private String precisText; private String phaseCode; private String status; private String type; private String primaryIdentifier; private Integer targetAccrualNumber; private List<Epoch> epochs; private RandomizationType randomizationType; private List<StudyDisease> studyDiseases = new ArrayList<StudyDisease>(); private List<StudyOrganization> studyOrganizations; private List<Identifier> identifiers; // TODO move into Command Object private String[] diseaseTermIds; private String diseaseCategoryAsText; private LazyListHelper lazyListHelper; //private ParameterizedInstantiateFactory<Identifier> identifierFactory; public Study() { lazyListHelper = new LazyListHelper(); // identifierFactory = new ParameterizedInstantiateFactory(); /* lazyListHelper.add(Identifier.class, identifierFactory); lazyListHelper.add(SystemAssignedIdentifier.class, new InstantiateFactory<SystemAssignedIdentifier>( SystemAssignedIdentifier.class)); lazyListHelper.add(OrganizationAssignedIdentifier.class, new InstantiateFactory<OrganizationAssignedIdentifier>( OrganizationAssignedIdentifier.class));*/ // lazyListHelper.add(StudySite.class, new BiDirectionalInstantiateFactory<StudySite>(StudySite.class,this)); lazyListHelper.add(StudySite.class, new ParameterizedBiDirectionalInstantiateFactory<StudySite>(StudySite.class,this)); lazyListHelper.add(StudyFundingSponsor.class, new ParameterizedBiDirectionalInstantiateFactory<StudyFundingSponsor>(StudyFundingSponsor.class,this)); lazyListHelper.add(StudyCoordinatingCenter.class, new ParameterizedBiDirectionalInstantiateFactory<StudyCoordinatingCenter>(StudyCoordinatingCenter.class,this)); // lazyListHelper.add(Epoch.class, epochFactory); lazyListHelper.add(TreatmentEpoch.class, new ParameterizedBiDirectionalInstantiateFactory<TreatmentEpoch>(TreatmentEpoch.class,this)); lazyListHelper.add(NonTreatmentEpoch.class, new ParameterizedBiDirectionalInstantiateFactory<NonTreatmentEpoch>(NonTreatmentEpoch.class,this)); lazyListHelper.add(SystemAssignedIdentifier.class, new ParameterizedInstantiateFactory<SystemAssignedIdentifier>(SystemAssignedIdentifier.class)); lazyListHelper.add(OrganizationAssignedIdentifier.class, new ParameterizedInstantiateFactory<OrganizationAssignedIdentifier>(OrganizationAssignedIdentifier.class )); // mandatory, so that the lazy-projected list is managed properly. setStudyOrganizations(new ArrayList<StudyOrganization>()); setEpochs(new ArrayList<Epoch>()); setIdentifiers(new ArrayList<Identifier>()); } @Transient public List<Identifier> getLocalIdentifiers() { List<Identifier> localIdentifiers = new ArrayList<Identifier>(); for (Identifier identifier : getIdentifiers()) { if ("Protocol Authority Identifier".equals(identifier.getType()) || "Coordinating Center Identifier".equals(identifier .getType())) { // nothing } else { localIdentifiers.add(identifier); } } return localIdentifiers; } @Transient public List<StudySite> getStudySites() { return lazyListHelper.getLazyList(StudySite.class); } public void setStudySites(List<StudySite> studySites) { // do nothing } @Transient public List<StudyFundingSponsor> getStudyFundingSponsors() { return lazyListHelper.getLazyList(StudyFundingSponsor.class); } public void setStudyFundingSponsors(List<StudyFundingSponsor> studyFundingSponsors) { // do nothing } @Transient public List<StudyCoordinatingCenter> getStudyCoordinatingCenters() { return lazyListHelper.getLazyList(StudyCoordinatingCenter.class); } public void setStudyCoordinatingCenters(List<StudyCoordinatingCenter> studyCoordinatingCenters) { // do nothing } @OneToMany(mappedBy = "study", fetch = FetchType.LAZY) @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) public List<StudyOrganization> getStudyOrganizations() { return studyOrganizations; } public void setStudyOrganizations(List<StudyOrganization> studyOrganizations) { this.studyOrganizations = studyOrganizations; //initialize projected list for StudySite, StudyFundingSponsor and StudyCoordinatingCenter lazyListHelper.setInternalList(StudySite.class, new ProjectedList<StudySite>(this.studyOrganizations, StudySite.class)); lazyListHelper.setInternalList(StudyFundingSponsor.class, new ProjectedList<StudyFundingSponsor>(this.studyOrganizations, StudyFundingSponsor.class)); lazyListHelper.setInternalList(StudyCoordinatingCenter.class, new ProjectedList<StudyCoordinatingCenter>(this.studyOrganizations, StudyCoordinatingCenter.class)); } public void addStudyOrganization(StudyOrganization so){ this.getStudyOrganizations().add(so); so.setStudy(this); } public void removeStudyOrganization(StudyOrganization so){ this.getStudyOrganizations().remove(so); } public void addEpoch(Epoch epoch) { epoch.setStudy(this); getEpochs().add(epoch); } public void removeEpoch(Epoch epoch) { lazyListHelper.getLazyList(Epoch.class).remove(epoch); } public void addStudySite(StudySite studySite) { studySite.setStudy(this); lazyListHelper.getLazyList(StudySite.class).add(studySite); } public void removeStudySite(StudySite studySite) { lazyListHelper.getLazyList(StudySite.class).remove(studySite); } public void addStudyDisease(StudyDisease studyDisease) { studyDisease.setStudy(this); studyDiseases.add(studyDisease); } public void addIdentifier(Identifier identifier) { getIdentifiers().add(identifier); } public void removeIdentifier(Identifier identifier) { getIdentifiers().remove(identifier); } /// BEAN PROPERTIES // TODO: this stuff should really, really not be in here. It's // web-view/entry specific. @Transient public String[] getDiseaseTermIds() { return diseaseTermIds; } @Transient public String getDiseaseCategoryAsText() { return diseaseCategoryAsText; } @OneToMany @Cascade({CascadeType.ALL, CascadeType.DELETE_ORPHAN}) @JoinColumn(name = "STU_ID") public List<Identifier> getIdentifiers() { return identifiers; } public void setIdentifiers(List<Identifier> identifiers) { this.identifiers=identifiers; lazyListHelper.setInternalList(SystemAssignedIdentifier.class,new ProjectedList<SystemAssignedIdentifier>(this.identifiers, SystemAssignedIdentifier.class)); lazyListHelper.setInternalList(OrganizationAssignedIdentifier.class,new ProjectedList<OrganizationAssignedIdentifier>(this.identifiers, OrganizationAssignedIdentifier.class)); } @Transient public List<SystemAssignedIdentifier> getSystemAssignedIdentifiers() { return lazyListHelper.getLazyList(SystemAssignedIdentifier.class); } public void setSystemAssignedIdentifiers(List<SystemAssignedIdentifier> systemAssignedIdentifiers) { // do nothing } @Transient public List<OrganizationAssignedIdentifier> getOrganizationAssignedIdentifiers() { return lazyListHelper.getLazyList(OrganizationAssignedIdentifier.class); } public void setOrganizationAssignedIdentifiers(List<OrganizationAssignedIdentifier> organizationAssignedIdentifiers) { // do nothing } /* @OneToMany @Cascade({CascadeType.ALL, CascadeType.DELETE_ORPHAN}) @JoinColumn(name = "STU_ID") public List<Identifier> getIdentifiersInternal() { return lazyListHelper.getInternalList(Identifier.class); } @Transient public List<Identifier> getIdentifiers() { return lazyListHelper.getLazyList(Identifier.class); } public void setIdentifiers( List<Identifier> identifiers) { lazyListHelper.setInternalList(Identifier.class, identifiers); } public void setIdentifiersInternal( List<Identifier> identifiers) { lazyListHelper.setInternalList(Identifier.class, identifiers); } @OneToMany(fetch = FetchType.LAZY) @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) @JoinColumn(name = "STU_ID") @Where(clause = "DTYPE = 'SAI'") public List<SystemAssignedIdentifier> getSystemAssignedIdentifiersInternal() { return lazyListHelper .getInternalList(SystemAssignedIdentifier.class); } @Transient public List<SystemAssignedIdentifier> getSystemAssignedIdentifiers() { return lazyListHelper.getLazyList(SystemAssignedIdentifier.class); } public void setSystemAssignedIdentifiers( List<SystemAssignedIdentifier> systemAssignedIdentifiers) { lazyListHelper.setInternalList(SystemAssignedIdentifier.class, systemAssignedIdentifiers); } public void setSystemAssignedIdentifiersInternal( List<SystemAssignedIdentifier> systemAssignedIdentifiers) { lazyListHelper.setInternalList(SystemAssignedIdentifier.class, systemAssignedIdentifiers); } @OneToMany(fetch = FetchType.LAZY) @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) @JoinColumn(name = "STU_ID") @Where(clause = "DTYPE = 'OAI'") public List<OrganizationAssignedIdentifier> getOrganizationAssignedIdentifiersInternal() { return lazyListHelper .getInternalList(OrganizationAssignedIdentifier.class); } @Transient public List<OrganizationAssignedIdentifier> getOrganizationAssignedIdentifiers() { return lazyListHelper.getLazyList(OrganizationAssignedIdentifier.class); } public void setOrganizationAssignedIdentifiers( List<OrganizationAssignedIdentifier> organizationAssignedIdentifiers) { lazyListHelper.setInternalList(OrganizationAssignedIdentifier.class, organizationAssignedIdentifiers); } public void setOrganizationAssignedIdentifiersInternal( List<OrganizationAssignedIdentifier> organizationAssignedIdentifiers) { lazyListHelper.setInternalList(OrganizationAssignedIdentifier.class, organizationAssignedIdentifiers); }*/ @OneToMany(mappedBy = "study", fetch = FetchType.LAZY) @Cascade(value = {CascadeType.ALL, CascadeType.DELETE_ORPHAN}) public List<Epoch> getEpochs() { return epochs; } public void setEpochs(List<Epoch> epochs) { this.epochs=epochs; lazyListHelper.setInternalList(TreatmentEpoch.class,new ProjectedList<TreatmentEpoch>(this.epochs, TreatmentEpoch.class)); lazyListHelper.setInternalList(NonTreatmentEpoch.class,new ProjectedList<NonTreatmentEpoch>(this.epochs, NonTreatmentEpoch.class)); } @Transient public List<TreatmentEpoch> getTreatmentEpochs(){ return lazyListHelper.getLazyList(TreatmentEpoch.class); } public void setTreatmentEpochs(List<TreatmentEpoch> treatmentEpochs){ // do nothing } @Transient public List<NonTreatmentEpoch> getNonTreatmentEpochs(){ return lazyListHelper.getLazyList(NonTreatmentEpoch.class); } public void setNonTreatmentEpochs(List<NonTreatmentEpoch> nonTreatmentEpochs){ // do nothing } @OneToMany(mappedBy = "study", fetch = FetchType.LAZY) @Cascade(value = {CascadeType.ALL, CascadeType.DELETE_ORPHAN}) public List<StudyDisease> getStudyDiseases() { return studyDiseases; } public void setStudyDiseases(List<StudyDisease> studyDiseases) { this.studyDiseases = studyDiseases; } public void setDiseaseTermIds(String[] diseaseTermIds) { this.diseaseTermIds = diseaseTermIds; } public void setDiseaseCategoryAsText(String diseaseCategoryAsText) { this.diseaseCategoryAsText = diseaseCategoryAsText; } public String getDescriptionText() { return descriptionText; } public void setDescriptionText(String descriptionText) { this.descriptionText = descriptionText; } public String getLongTitleText() { return longTitleText; } public void setLongTitleText(String longTitleText) { this.longTitleText = longTitleText; } public String getPhaseCode() { return phaseCode; } public void setPhaseCode(String phaseCode) { this.phaseCode = phaseCode; } public String getPrecisText() { return precisText; } public void setPrecisText(String precisText) { this.precisText = precisText; } public String getShortTitleText() { return shortTitleText; } public void setShortTitleText(String shortTitleText) { this.shortTitleText = shortTitleText; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Integer getTargetAccrualNumber() { return targetAccrualNumber; } public void setTargetAccrualNumber(Integer targetAccrualNumber) { this.targetAccrualNumber = targetAccrualNumber; } public String getType() { return type; } public void setType(String type) { this.type = type; } public int compareTo(Study o) { if (this.equals((Study) o)) return 0; return 1; } /*@Override public int hashCode() { final int PRIME = 31; int result = super.hashCode(); result = PRIME * result + ((epochs == null) ? 0 : epochs.hashCode()); result = PRIME * result + ((identifiers == null) ? 0 : identifiers.hashCode()); result = PRIME * result + ((longTitleText == null) ? 0 : longTitleText.hashCode()); result = PRIME * result + ((phaseCode == null) ? 0 : phaseCode.hashCode()); result = PRIME * result + ((status == null) ? 0 : status.hashCode()); result = PRIME * result + ((studySites == null) ? 0 : studySites.hashCode()); result = PRIME * result + ((type == null) ? 0 : type.hashCode()); return result; } */ /*@Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; final Study other = (Study) obj; if (epochs == null) { if (other.epochs != null) return false; } else if (!epochs.equals(other.epochs)) return false; if (identifiers == null) { if (other.identifiers != null) return false; } else if (!identifiers.equals(other.identifiers)) return false; if (longTitleText == null) { if (other.longTitleText != null) return false; } else if (!longTitleText.equals(other.longTitleText)) return false; if (phaseCode == null) { if (other.phaseCode != null) return false; } else if (!phaseCode.equals(other.phaseCode)) return false; if (status == null) { if (other.status != null) return false; } else if (!status.equals(other.status)) return false; if (studySites == null) { if (other.studySites != null) return false; } else if (!studySites.equals(other.studySites)) return false; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; }*/ @Transient public String getTrimmedShortTitleText() { return StringUtils.getTrimmedText(shortTitleText, 40); } @Transient public String getPrimaryIdentifier() { for (Identifier identifier : getIdentifiers()) { if (identifier.getPrimaryIndicator().booleanValue() == true) { return identifier.getValue(); } } return primaryIdentifier; } public String getBlindedIndicator() { return blindedIndicator; } public void setBlindedIndicator(String blindedIndicator) { this.blindedIndicator = blindedIndicator; } public String getMultiInstitutionIndicator() { return multiInstitutionIndicator; } public void setMultiInstitutionIndicator(String multiInstitutionIndicator) { this.multiInstitutionIndicator = multiInstitutionIndicator; } public String getRandomizedIndicator() { return randomizedIndicator; } public void setRandomizedIndicator(String randomizedIndicator) { this.randomizedIndicator = randomizedIndicator; } public RandomizationType getRandomizationType() { return randomizationType; } public void setRandomizationType(RandomizationType randomizationType) { this.randomizationType = randomizationType; } }
added study amendments associations, updated equalsTo and hashCode
codebase/projects/core/src/java/edu/duke/cabig/c3pr/domain/Study.java
added study amendments associations, updated equalsTo and hashCode
<ide><path>odebase/projects/core/src/java/edu/duke/cabig/c3pr/domain/Study.java <ide> import org.hibernate.annotations.Where; <ide> <ide> /** <del> * A systematic evaluation of an observation or an <del> * intervention (for example, treatment, drug, device, procedure or system) in one <del> * or more subjects. Frequently this is a test of a particular hypothesis about <del> * the treatment, drug, device, procedure or system. [CDAM] A study can be either <del> * primary or correlative. A study is considered a primary study if it has one or <del> * more correlative studies. A correlative study extends the objectives or <add> * A systematic evaluation of an observation or an intervention (for example, <add> * treatment, drug, device, procedure or system) in one or more subjects. <add> * Frequently this is a test of a particular hypothesis about the treatment, <add> * drug, device, procedure or system. [CDAM] A study can be either primary or <add> * correlative. A study is considered a primary study if it has one or more <add> * correlative studies. A correlative study extends the objectives or <ide> * observations of a primary study, enrolling the same, or a subset of the same, <ide> * subjects as the primary study. A Clinical Trial is a Study with type= <ide> * "intervention" with subjects of type="human". <del> * <add> * <ide> * @author Priyatam <ide> */ <ide> <ide> @Entity <ide> @Table(name = "STUDIES") <del>@GenericGenerator(name = "id-generator", strategy = "native", <del> parameters = { <del> @Parameter(name = "sequence", value = "STUDIES_ID_SEQ") <del> } <del>) <del>public class Study extends AbstractMutableDomainObject implements Comparable<Study>{ <del> <add>@GenericGenerator(name = "id-generator", strategy = "native", parameters = { @Parameter(name = "sequence", value = "STUDIES_ID_SEQ") }) <add>public class Study extends AbstractMutableDomainObject implements <add> Comparable<Study> { <add> <ide> private String blindedIndicator; <del> private String multiInstitutionIndicator; <del> private String randomizedIndicator; <del> private String shortTitleText; <del> private String longTitleText; <del> private String descriptionText; <del> private String precisText; <del> private String phaseCode; <del> private String status; <del> private String type; <del> private String primaryIdentifier; <del> private Integer targetAccrualNumber; <del> private List<Epoch> epochs; <del> private RandomizationType randomizationType; <del> private List<StudyDisease> studyDiseases = new ArrayList<StudyDisease>(); <del> private List<StudyOrganization> studyOrganizations; <del> private List<Identifier> identifiers; <del> <del> <del> // TODO move into Command Object <del> private String[] diseaseTermIds; <del> private String diseaseCategoryAsText; <del> <del> private LazyListHelper lazyListHelper; <del> //private ParameterizedInstantiateFactory<Identifier> identifierFactory; <del> <del> <del> public Study() { <del> lazyListHelper = new LazyListHelper(); <del> // identifierFactory = new ParameterizedInstantiateFactory(); <del> /* lazyListHelper.add(Identifier.class, identifierFactory); <add> <add> private String multiInstitutionIndicator; <add> <add> private String randomizedIndicator; <add> <add> private String shortTitleText; <add> <add> private String longTitleText; <add> <add> private String descriptionText; <add> <add> private String precisText; <add> <add> private String phaseCode; <add> <add> private String status; <add> <add> private String type; <add> <add> private String primaryIdentifier; <add> <add> private Integer targetAccrualNumber; <add> <add> private List<Epoch> epochs; <add> <add> private RandomizationType randomizationType; <add> <add> private List<StudyDisease> studyDiseases = new ArrayList<StudyDisease>(); <add> <add> private List<StudyOrganization> studyOrganizations; <add> <add> private List<Identifier> identifiers; <add> <add> // TODO move into Command Object <add> private String[] diseaseTermIds; <add> <add> private String diseaseCategoryAsText; <add> <add> private LazyListHelper lazyListHelper; <add> <add> // private ParameterizedInstantiateFactory<Identifier> identifierFactory; <add> <add> public Study() { <add> lazyListHelper = new LazyListHelper(); <add> lazyListHelper.add(StudySite.class, <add> new ParameterizedBiDirectionalInstantiateFactory<StudySite>( <add> StudySite.class, this)); <add> lazyListHelper <add> .add( <add> StudyFundingSponsor.class, <add> new ParameterizedBiDirectionalInstantiateFactory<StudyFundingSponsor>( <add> StudyFundingSponsor.class, this)); <add> lazyListHelper <add> .add( <add> StudyCoordinatingCenter.class, <add> new ParameterizedBiDirectionalInstantiateFactory<StudyCoordinatingCenter>( <add> StudyCoordinatingCenter.class, this)); <add> <add> // lazyListHelper.add(Epoch.class, epochFactory); <add> lazyListHelper <add> .add( <add> TreatmentEpoch.class, <add> new ParameterizedBiDirectionalInstantiateFactory<TreatmentEpoch>( <add> TreatmentEpoch.class, this)); <add> lazyListHelper <add> .add( <add> NonTreatmentEpoch.class, <add> new ParameterizedBiDirectionalInstantiateFactory<NonTreatmentEpoch>( <add> NonTreatmentEpoch.class, this)); <ide> lazyListHelper.add(SystemAssignedIdentifier.class, <del> new InstantiateFactory<SystemAssignedIdentifier>( <add> new ParameterizedInstantiateFactory<SystemAssignedIdentifier>( <ide> SystemAssignedIdentifier.class)); <del> lazyListHelper.add(OrganizationAssignedIdentifier.class, <del> new InstantiateFactory<OrganizationAssignedIdentifier>( <del> OrganizationAssignedIdentifier.class));*/ <del> // lazyListHelper.add(StudySite.class, new BiDirectionalInstantiateFactory<StudySite>(StudySite.class,this)); <del> lazyListHelper.add(StudySite.class, new ParameterizedBiDirectionalInstantiateFactory<StudySite>(StudySite.class,this)); <del> lazyListHelper.add(StudyFundingSponsor.class, new ParameterizedBiDirectionalInstantiateFactory<StudyFundingSponsor>(StudyFundingSponsor.class,this)); <del> lazyListHelper.add(StudyCoordinatingCenter.class, new ParameterizedBiDirectionalInstantiateFactory<StudyCoordinatingCenter>(StudyCoordinatingCenter.class,this)); <del> <del> // lazyListHelper.add(Epoch.class, epochFactory); <del> lazyListHelper.add(TreatmentEpoch.class, new ParameterizedBiDirectionalInstantiateFactory<TreatmentEpoch>(TreatmentEpoch.class,this)); <del> lazyListHelper.add(NonTreatmentEpoch.class, new ParameterizedBiDirectionalInstantiateFactory<NonTreatmentEpoch>(NonTreatmentEpoch.class,this)); <del> lazyListHelper.add(SystemAssignedIdentifier.class, <del> new ParameterizedInstantiateFactory<SystemAssignedIdentifier>(SystemAssignedIdentifier.class)); <del> lazyListHelper.add(OrganizationAssignedIdentifier.class, <del> new ParameterizedInstantiateFactory<OrganizationAssignedIdentifier>(OrganizationAssignedIdentifier.class <del> )); <del> // mandatory, so that the lazy-projected list is managed properly. <del> setStudyOrganizations(new ArrayList<StudyOrganization>()); <del> setEpochs(new ArrayList<Epoch>()); <del> setIdentifiers(new ArrayList<Identifier>()); <del> <del> } <del> @Transient <add> lazyListHelper <add> .add( <add> OrganizationAssignedIdentifier.class, <add> new ParameterizedInstantiateFactory<OrganizationAssignedIdentifier>( <add> OrganizationAssignedIdentifier.class)); <add> lazyListHelper.add(StudyAmendment.class, new InstantiateFactory<StudyAmendment>(StudyAmendment.class)); <add> // mandatory, so that the lazy-projected list is managed properly. <add> setStudyOrganizations(new ArrayList<StudyOrganization>()); <add> setEpochs(new ArrayList<Epoch>()); <add> setIdentifiers(new ArrayList<Identifier>()); <add> <add> } <add> <add> @Transient <ide> public List<Identifier> getLocalIdentifiers() { <ide> List<Identifier> localIdentifiers = new ArrayList<Identifier>(); <ide> for (Identifier identifier : getIdentifiers()) { <ide> } <ide> return localIdentifiers; <ide> } <del> <del> @Transient <del> public List<StudySite> getStudySites() { <del> return lazyListHelper.getLazyList(StudySite.class); <del> } <del> <del> public void setStudySites(List<StudySite> studySites) { <del> // do nothing <del> } <del> <del> @Transient <add> <add> @Transient <add> public List<StudySite> getStudySites() { <add> return lazyListHelper.getLazyList(StudySite.class); <add> } <add> <add> public void setStudySites(List<StudySite> studySites) { <add> // do nothing <add> } <add> <add> @Transient <ide> public List<StudyFundingSponsor> getStudyFundingSponsors() { <ide> return lazyListHelper.getLazyList(StudyFundingSponsor.class); <ide> } <del> <del> public void setStudyFundingSponsors(List<StudyFundingSponsor> studyFundingSponsors) { <del> // do nothing <del> } <del> <del> @Transient <add> <add> public void setStudyFundingSponsors( <add> List<StudyFundingSponsor> studyFundingSponsors) { <add> // do nothing <add> } <add> <add> @Transient <ide> public List<StudyCoordinatingCenter> getStudyCoordinatingCenters() { <ide> return lazyListHelper.getLazyList(StudyCoordinatingCenter.class); <ide> } <del> <del> public void setStudyCoordinatingCenters(List<StudyCoordinatingCenter> studyCoordinatingCenters) { <del> // do nothing <del> } <del> <add> <add> public void setStudyCoordinatingCenters( <add> List<StudyCoordinatingCenter> studyCoordinatingCenters) { <add> // do nothing <add> } <add> <ide> @OneToMany(mappedBy = "study", fetch = FetchType.LAZY) <ide> @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) <ide> public List<StudyOrganization> getStudyOrganizations() { <ide> return studyOrganizations; <ide> } <del> public void setStudyOrganizations(List<StudyOrganization> studyOrganizations) { <del> this.studyOrganizations = studyOrganizations; <del> //initialize projected list for StudySite, StudyFundingSponsor and StudyCoordinatingCenter <del> lazyListHelper.setInternalList(StudySite.class, <del> new ProjectedList<StudySite>(this.studyOrganizations, StudySite.class)); <del> lazyListHelper.setInternalList(StudyFundingSponsor.class, <del> new ProjectedList<StudyFundingSponsor>(this.studyOrganizations, StudyFundingSponsor.class)); <del> lazyListHelper.setInternalList(StudyCoordinatingCenter.class, <del> new ProjectedList<StudyCoordinatingCenter>(this.studyOrganizations, StudyCoordinatingCenter.class)); <del> } <del> <del> public void addStudyOrganization(StudyOrganization so){ <add> <add> public void setStudyOrganizations(List<StudyOrganization> studyOrganizations) { <add> this.studyOrganizations = studyOrganizations; <add> // initialize projected list for StudySite, StudyFundingSponsor and <add> // StudyCoordinatingCenter <add> lazyListHelper.setInternalList(StudySite.class, <add> new ProjectedList<StudySite>(this.studyOrganizations, <add> StudySite.class)); <add> lazyListHelper.setInternalList(StudyFundingSponsor.class, <add> new ProjectedList<StudyFundingSponsor>(this.studyOrganizations, <add> StudyFundingSponsor.class)); <add> lazyListHelper <add> .setInternalList(StudyCoordinatingCenter.class, <add> new ProjectedList<StudyCoordinatingCenter>( <add> this.studyOrganizations, <add> StudyCoordinatingCenter.class)); <add> } <add> <add> public void addStudyOrganization(StudyOrganization so) { <ide> this.getStudyOrganizations().add(so); <ide> so.setStudy(this); <ide> } <add> <add> public void removeStudyOrganization(StudyOrganization so) { <add> this.getStudyOrganizations().remove(so); <add> } <add> <add> public void addEpoch(Epoch epoch) throws RuntimeException { <add> for (Epoch epochPresent : getEpochs()) { <add> if (epochPresent.equals(epoch)) { <add> throw new RuntimeException("epoch with same name already exists in study"); <add> } <add> } <add> epoch.setStudy(this); <add> getEpochs().add(epoch); <add> } <add> <add> public void removeEpoch(Epoch epoch) { <add> lazyListHelper.getLazyList(Epoch.class).remove(epoch); <add> } <add> <add> public void addStudySite(StudySite studySite) { <add> studySite.setStudy(this); <add> lazyListHelper.getLazyList(StudySite.class).add(studySite); <add> } <add> <add> public void removeStudySite(StudySite studySite) { <add> lazyListHelper.getLazyList(StudySite.class).remove(studySite); <add> } <add> <add> public void addStudyDisease(StudyDisease studyDisease) { <add> studyDisease.setStudy(this); <add> studyDiseases.add(studyDisease); <add> } <add> <add> public void addIdentifier(Identifier identifier) { <add> getIdentifiers().add(identifier); <add> } <add> <add> public void removeIdentifier(Identifier identifier) { <add> getIdentifiers().remove(identifier); <add> } <ide> <del> public void removeStudyOrganization(StudyOrganization so){ <del> this.getStudyOrganizations().remove(so); <del> } <del> <del> public void addEpoch(Epoch epoch) { <del> epoch.setStudy(this); <del> getEpochs().add(epoch); <del> } <del> <del> public void removeEpoch(Epoch epoch) { <del> lazyListHelper.getLazyList(Epoch.class).remove(epoch); <del> } <del> <del> public void addStudySite(StudySite studySite) { <del> studySite.setStudy(this); <del> lazyListHelper.getLazyList(StudySite.class).add(studySite); <del> } <del> <del> public void removeStudySite(StudySite studySite) { <del> lazyListHelper.getLazyList(StudySite.class).remove(studySite); <del> } <del> <del> public void addStudyDisease(StudyDisease studyDisease) { <del> studyDisease.setStudy(this); <del> studyDiseases.add(studyDisease); <del> } <del> <del> public void addIdentifier(Identifier identifier) { <del> getIdentifiers().add(identifier); <del> } <del> <del> public void removeIdentifier(Identifier identifier) { <del> getIdentifiers().remove(identifier); <del> } <del> <del> /// BEAN PROPERTIES <del> <del>// TODO: this stuff should really, really not be in here. It's <add> @Transient <add> public OrganizationAssignedIdentifier getFundingSponsorAssignedIdentifier() <add> { <add> for (OrganizationAssignedIdentifier orgIdentifier:this.getOrganizationAssignedIdentifiers()){ <add> if (orgIdentifier.getType().equals("Protocol Authority Identifier")) return orgIdentifier; <add> } <add> return null; <add> } <add> <add> // / BEAN PROPERTIES <add> <add> // TODO: this stuff should really, really not be in here. It's <ide> // web-view/entry specific. <del> @Transient <del> public String[] getDiseaseTermIds() { <del> return diseaseTermIds; <del> } <del> <del> @Transient <del> public String getDiseaseCategoryAsText() { <del> return diseaseCategoryAsText; <del> } <del> <del> @OneToMany <del> @Cascade({CascadeType.ALL, CascadeType.DELETE_ORPHAN}) <del> @JoinColumn(name = "STU_ID") <del> public List<Identifier> getIdentifiers() { <del> return identifiers; <del> } <del> <del> public void setIdentifiers(List<Identifier> identifiers) { <del> this.identifiers=identifiers; <del> lazyListHelper.setInternalList(SystemAssignedIdentifier.class,new ProjectedList<SystemAssignedIdentifier>(this.identifiers, SystemAssignedIdentifier.class)); <del> lazyListHelper.setInternalList(OrganizationAssignedIdentifier.class,new ProjectedList<OrganizationAssignedIdentifier>(this.identifiers, OrganizationAssignedIdentifier.class)); <del> } <del> <del> @Transient <del> public List<SystemAssignedIdentifier> getSystemAssignedIdentifiers() <del> { <del> return lazyListHelper.getLazyList(SystemAssignedIdentifier.class); <del> } <del> <del> public void setSystemAssignedIdentifiers(List<SystemAssignedIdentifier> systemAssignedIdentifiers) <del> { <del> // do nothing <del> } <del> <del> @Transient <del> public List<OrganizationAssignedIdentifier> getOrganizationAssignedIdentifiers() <del> { <del> return lazyListHelper.getLazyList(OrganizationAssignedIdentifier.class); <del> } <del> <del> public void setOrganizationAssignedIdentifiers(List<OrganizationAssignedIdentifier> organizationAssignedIdentifiers) <del> { <del> // do nothing <del> } <del> <del> /* <del> @OneToMany <del> @Cascade({CascadeType.ALL, CascadeType.DELETE_ORPHAN}) <del> @JoinColumn(name = "STU_ID") <del> public List<Identifier> getIdentifiersInternal() { <del> return lazyListHelper.getInternalList(Identifier.class); <del> } <del> <del> @Transient <add> @Transient <add> public String[] getDiseaseTermIds() { <add> return diseaseTermIds; <add> } <add> <add> @Transient <add> public String getDiseaseCategoryAsText() { <add> return diseaseCategoryAsText; <add> } <add> <add> @OneToMany <add> @Cascade( { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) <add> @JoinColumn(name = "STU_ID") <ide> public List<Identifier> getIdentifiers() { <del> return lazyListHelper.getLazyList(Identifier.class); <del> } <del> <del> <del> public void setIdentifiers( <del> List<Identifier> identifiers) { <del> lazyListHelper.setInternalList(Identifier.class, <del> identifiers); <del> } <del> <del> public void setIdentifiersInternal( <del> List<Identifier> identifiers) { <del> lazyListHelper.setInternalList(Identifier.class, <del> identifiers); <del> } <del> <del> @OneToMany(fetch = FetchType.LAZY) <del> @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) <del> @JoinColumn(name = "STU_ID") <del> @Where(clause = "DTYPE = 'SAI'") <del> public List<SystemAssignedIdentifier> getSystemAssignedIdentifiersInternal() { <del> return lazyListHelper <del> .getInternalList(SystemAssignedIdentifier.class); <add> return identifiers; <add> } <add> <add> public void setIdentifiers(List<Identifier> identifiers) { <add> this.identifiers = identifiers; <add> lazyListHelper.setInternalList(SystemAssignedIdentifier.class, <add> new ProjectedList<SystemAssignedIdentifier>(this.identifiers, <add> SystemAssignedIdentifier.class)); <add> lazyListHelper <add> .setInternalList(OrganizationAssignedIdentifier.class, <add> new ProjectedList<OrganizationAssignedIdentifier>( <add> this.identifiers, <add> OrganizationAssignedIdentifier.class)); <ide> } <ide> <ide> @Transient <ide> <ide> public void setSystemAssignedIdentifiers( <ide> List<SystemAssignedIdentifier> systemAssignedIdentifiers) { <del> lazyListHelper.setInternalList(SystemAssignedIdentifier.class, <del> systemAssignedIdentifiers); <del> } <add> // do nothing <add> } <add> <add> @Transient <add> public List<OrganizationAssignedIdentifier> getOrganizationAssignedIdentifiers() { <add> return lazyListHelper.getLazyList(OrganizationAssignedIdentifier.class); <add> } <add> <add> public void setOrganizationAssignedIdentifiers( <add> List<OrganizationAssignedIdentifier> organizationAssignedIdentifiers) { <add> // do nothing <add> } <add> <add> @OneToMany(mappedBy = "study", fetch = FetchType.LAZY) <add> @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) <add> public List<Epoch> getEpochs() { <add> return epochs; <add> } <add> <add> public void addAmendment(final StudyAmendment amendment) { <add> getStudyAmendments().add(amendment); <add> } <add> <add> @OneToMany(fetch = FetchType.LAZY) <add> @JoinColumn(name = "stu_id", nullable = false) <add> @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) <add> public List<StudyAmendment> getStudyAmendmentsInternal() { <add> return lazyListHelper.getInternalList(StudyAmendment.class); <add> } <add> <add> public void setStudyAmendmentsInternal(final List<StudyAmendment> amendments) { <add> lazyListHelper.setInternalList(StudyAmendment.class, amendments); <add> } <add> <add> @Transient <add> public List<StudyAmendment> getStudyAmendments() { <add> return lazyListHelper.getLazyList(StudyAmendment.class); <add> } <add> <add> public void setStudyAmendments(final List<StudyAmendment> amendments) { <add> setStudyAmendmentsInternal(amendments); <add> } <add> <add> public void setEpochs(List<Epoch> epochs) { <add> this.epochs = epochs; <add> lazyListHelper.setInternalList(TreatmentEpoch.class, <add> new ProjectedList<TreatmentEpoch>(this.epochs, <add> TreatmentEpoch.class)); <add> lazyListHelper.setInternalList(NonTreatmentEpoch.class, <add> new ProjectedList<NonTreatmentEpoch>(this.epochs, <add> NonTreatmentEpoch.class)); <add> } <add> <add> @Transient <add> public List<TreatmentEpoch> getTreatmentEpochs() { <add> return lazyListHelper.getLazyList(TreatmentEpoch.class); <add> } <add> <add> public void setTreatmentEpochs(List<TreatmentEpoch> treatmentEpochs) { <add> // do nothing <add> } <add> <add> @Transient <add> public List<NonTreatmentEpoch> getNonTreatmentEpochs() { <add> return lazyListHelper.getLazyList(NonTreatmentEpoch.class); <add> } <add> <add> public void setNonTreatmentEpochs(List<NonTreatmentEpoch> nonTreatmentEpochs) { <add> // do nothing <add> } <add> <add> @OneToMany(mappedBy = "study", fetch = FetchType.LAZY) <add> @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) <add> public List<StudyDisease> getStudyDiseases() { <add> return studyDiseases; <add> } <add> <add> public void setStudyDiseases(List<StudyDisease> studyDiseases) { <add> this.studyDiseases = studyDiseases; <add> } <add> <add> public void setDiseaseTermIds(String[] diseaseTermIds) { <add> this.diseaseTermIds = diseaseTermIds; <add> } <add> <add> public void setDiseaseCategoryAsText(String diseaseCategoryAsText) { <add> this.diseaseCategoryAsText = diseaseCategoryAsText; <add> } <add> <add> public String getDescriptionText() { <add> return descriptionText; <add> } <add> <add> public void setDescriptionText(String descriptionText) { <add> this.descriptionText = descriptionText; <add> } <add> <add> public String getLongTitleText() { <add> return longTitleText; <add> } <add> <add> public void setLongTitleText(String longTitleText) { <add> this.longTitleText = longTitleText; <add> } <add> <add> public String getPhaseCode() { <add> return phaseCode; <add> } <add> <add> public void setPhaseCode(String phaseCode) { <add> this.phaseCode = phaseCode; <add> } <add> <add> public String getPrecisText() { <add> return precisText; <add> } <add> <add> public void setPrecisText(String precisText) { <add> this.precisText = precisText; <add> } <add> <add> public String getShortTitleText() { <add> return shortTitleText; <add> } <add> <add> public void setShortTitleText(String shortTitleText) { <add> this.shortTitleText = shortTitleText; <add> } <add> <add> public String getStatus() { <add> return status; <add> } <add> <add> public void setStatus(String status) { <add> this.status = status; <add> } <add> <add> public Integer getTargetAccrualNumber() { <add> return targetAccrualNumber; <add> } <add> <add> public void setTargetAccrualNumber(Integer targetAccrualNumber) { <add> this.targetAccrualNumber = targetAccrualNumber; <add> } <add> <add> public String getType() { <add> return type; <add> } <add> <add> public void setType(String type) { <add> this.type = type; <add> } <add> <add> public int compareTo(Study o) { <add> if (this.equals(o)) <add> return 0; <add> <add> return 1; <add> } <add> <add> <add> @Override public int hashCode() { final int PRIME = 31; int result=super.hashCode(); result = PRIME * result + ((getFundingSponsorAssignedIdentifier() == null) ? 0 : <add> getFundingSponsorAssignedIdentifier().hashCode()); return result; } <ide> <ide> <del> public void setSystemAssignedIdentifiersInternal( <del> List<SystemAssignedIdentifier> systemAssignedIdentifiers) { <del> lazyListHelper.setInternalList(SystemAssignedIdentifier.class, <del> systemAssignedIdentifiers); <del> <del> } <del> <del> @OneToMany(fetch = FetchType.LAZY) <del> @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) <del> @JoinColumn(name = "STU_ID") <del> @Where(clause = "DTYPE = 'OAI'") <del> public List<OrganizationAssignedIdentifier> getOrganizationAssignedIdentifiersInternal() { <del> return lazyListHelper <del> .getInternalList(OrganizationAssignedIdentifier.class); <del> } <del> <del> @Transient <del> public List<OrganizationAssignedIdentifier> getOrganizationAssignedIdentifiers() { <del> return lazyListHelper.getLazyList(OrganizationAssignedIdentifier.class); <del> } <del> <del> public void setOrganizationAssignedIdentifiers( <del> List<OrganizationAssignedIdentifier> organizationAssignedIdentifiers) { <del> lazyListHelper.setInternalList(OrganizationAssignedIdentifier.class, <del> organizationAssignedIdentifiers); <del> } <del> <del> public void setOrganizationAssignedIdentifiersInternal( <del> List<OrganizationAssignedIdentifier> organizationAssignedIdentifiers) { <del> lazyListHelper.setInternalList(OrganizationAssignedIdentifier.class, <del> organizationAssignedIdentifiers); <del> <del> }*/ <del> <del> @OneToMany(mappedBy = "study", fetch = FetchType.LAZY) <del> @Cascade(value = {CascadeType.ALL, CascadeType.DELETE_ORPHAN}) <del> public List<Epoch> getEpochs() { <del> return epochs; <del> } <del> <del> public void setEpochs(List<Epoch> epochs) { <del> this.epochs=epochs; <del> lazyListHelper.setInternalList(TreatmentEpoch.class,new ProjectedList<TreatmentEpoch>(this.epochs, TreatmentEpoch.class)); <del> lazyListHelper.setInternalList(NonTreatmentEpoch.class,new ProjectedList<NonTreatmentEpoch>(this.epochs, NonTreatmentEpoch.class)); <del> } <del> <del> @Transient <del> public List<TreatmentEpoch> getTreatmentEpochs(){ <del> return lazyListHelper.getLazyList(TreatmentEpoch.class); <del> } <del> <del> public void setTreatmentEpochs(List<TreatmentEpoch> treatmentEpochs){ <del> // do nothing <del> } <del> <del> @Transient <del> public List<NonTreatmentEpoch> getNonTreatmentEpochs(){ <del> return lazyListHelper.getLazyList(NonTreatmentEpoch.class); <del> } <del> <del> public void setNonTreatmentEpochs(List<NonTreatmentEpoch> nonTreatmentEpochs){ <del> // do nothing <del> } <del> <del> <del> @OneToMany(mappedBy = "study", fetch = FetchType.LAZY) <del> @Cascade(value = {CascadeType.ALL, CascadeType.DELETE_ORPHAN}) <del> public List<StudyDisease> getStudyDiseases() { <del> return studyDiseases; <del> } <del> <del> public void setStudyDiseases(List<StudyDisease> studyDiseases) { <del> this.studyDiseases = studyDiseases; <del> } <del> <del> public void setDiseaseTermIds(String[] diseaseTermIds) { <del> this.diseaseTermIds = diseaseTermIds; <del> } <del> <del> public void setDiseaseCategoryAsText(String diseaseCategoryAsText) { <del> this.diseaseCategoryAsText = diseaseCategoryAsText; <del> } <del> <del> public String getDescriptionText() { <del> return descriptionText; <del> } <del> <del> public void setDescriptionText(String descriptionText) { <del> this.descriptionText = descriptionText; <del> } <del> <del> public String getLongTitleText() { <del> return longTitleText; <del> } <del> <del> public void setLongTitleText(String longTitleText) { <del> this.longTitleText = longTitleText; <del> } <del> <del> public String getPhaseCode() { <del> return phaseCode; <del> } <del> <del> public void setPhaseCode(String phaseCode) { <del> this.phaseCode = phaseCode; <del> } <del> <del> public String getPrecisText() { <del> return precisText; <del> } <del> <del> public void setPrecisText(String precisText) { <del> this.precisText = precisText; <del> } <del> <del> public String getShortTitleText() { <del> return shortTitleText; <del> } <del> <del> public void setShortTitleText(String shortTitleText) { <del> this.shortTitleText = shortTitleText; <del> } <del> <del> public String getStatus() { <del> return status; <del> } <del> <del> public void setStatus(String status) { <del> this.status = status; <del> } <del> <del> public Integer getTargetAccrualNumber() { <del> return targetAccrualNumber; <del> } <del> <del> public void setTargetAccrualNumber(Integer targetAccrualNumber) { <del> this.targetAccrualNumber = targetAccrualNumber; <del> } <del> <del> public String getType() { <del> return type; <del> } <del> <del> public void setType(String type) { <del> this.type = type; <del> } <del> <del> public int compareTo(Study o) { <del> if (this.equals((Study) o)) return 0; <del> <del> return 1; <del> } <del> <del> /*@Override <del> public int hashCode() { <del> final int PRIME = 31; <del> int result = super.hashCode(); <del> result = PRIME * result + ((epochs == null) ? 0 : epochs.hashCode()); <del> result = PRIME * result + ((identifiers == null) ? 0 : identifiers.hashCode()); <del> result = PRIME * result + ((longTitleText == null) ? 0 : longTitleText.hashCode()); <del> result = PRIME * result + ((phaseCode == null) ? 0 : phaseCode.hashCode()); <del> result = PRIME * result + ((status == null) ? 0 : status.hashCode()); <del> result = PRIME * result + ((studySites == null) ? 0 : studySites.hashCode()); <del> result = PRIME * result + ((type == null) ? 0 : type.hashCode()); <del> return result; <del> } <del> */ <del> /*@Override <del> public boolean equals(Object obj) { <del> if (this == obj) <del> return true; <del> if (!super.equals(obj)) <del> return false; <del> if (getClass() != obj.getClass()) <del> return false; <del> final Study other = (Study) obj; <del> if (epochs == null) { <del> if (other.epochs != null) <del> return false; <del> } else if (!epochs.equals(other.epochs)) <del> return false; <del> if (identifiers == null) { <del> if (other.identifiers != null) <del> return false; <del> } else if (!identifiers.equals(other.identifiers)) <del> return false; <del> if (longTitleText == null) { <del> if (other.longTitleText != null) <del> return false; <del> } else if (!longTitleText.equals(other.longTitleText)) <del> return false; <del> if (phaseCode == null) { <del> if (other.phaseCode != null) <del> return false; <del> } else if (!phaseCode.equals(other.phaseCode)) <del> return false; <del> if (status == null) { <del> if (other.status != null) <del> return false; <del> } else if (!status.equals(other.status)) <del> return false; <del> if (studySites == null) { <del> if (other.studySites != null) <del> return false; <del> } else if (!studySites.equals(other.studySites)) <del> return false; <del> if (type == null) { <del> if (other.type != null) <del> return false; <del> } else if (!type.equals(other.type)) <del> return false; <del> return true; <del> }*/ <del> <del> @Transient <del> public String getTrimmedShortTitleText() { <del> return StringUtils.getTrimmedText(shortTitleText, 40); <del> } <del> <del> @Transient <del> public String getPrimaryIdentifier() { <del> for (Identifier identifier : getIdentifiers()) { <del> if (identifier.getPrimaryIndicator().booleanValue() == true) { <del> return identifier.getValue(); <del> } <del> } <del> <del> return primaryIdentifier; <del> } <del> <del> public String getBlindedIndicator() { <del> return blindedIndicator; <del> } <del> <del> public void setBlindedIndicator(String blindedIndicator) { <del> this.blindedIndicator = blindedIndicator; <del> } <del> <del> public String getMultiInstitutionIndicator() { <del> return multiInstitutionIndicator; <del> } <del> <del> public void setMultiInstitutionIndicator(String multiInstitutionIndicator) { <del> this.multiInstitutionIndicator = multiInstitutionIndicator; <del> } <del> <del> public String getRandomizedIndicator() { <del> return randomizedIndicator; <del> } <del> <del> public void setRandomizedIndicator(String randomizedIndicator) { <del> this.randomizedIndicator = randomizedIndicator; <del> } <del> <add> @Override public boolean equals(Object obj) { if (this == obj) return <add> true; if (getClass() != <add> obj.getClass()) return false; final Study other = (Study) obj; <add> if ((this.getFundingSponsorAssignedIdentifier() == null)|| (other.getFundingSponsorAssignedIdentifier()==null)) { <add> return false;} <add> else if (!((this.getFundingSponsorAssignedIdentifier().getValue()).equals(other.getFundingSponsorAssignedIdentifier().getValue()))) {return false;} <add> else if (!((this.getFundingSponsorAssignedIdentifier().getHealthcareSite()).equals(other.getFundingSponsorAssignedIdentifier().getHealthcareSite()))) {return false;} <add> return true; } <add> <add> <add> @Transient <add> public String getTrimmedShortTitleText() { <add> return StringUtils.getTrimmedText(shortTitleText, 40); <add> } <add> <add> @Transient <add> public String getPrimaryIdentifier() { <add> for (Identifier identifier : getIdentifiers()) { <add> if (identifier.getPrimaryIndicator().booleanValue() == true) { <add> return identifier.getValue(); <add> } <add> } <add> <add> return primaryIdentifier; <add> } <add> <add> public String getBlindedIndicator() { <add> return blindedIndicator; <add> } <add> <add> public void setBlindedIndicator(String blindedIndicator) { <add> this.blindedIndicator = blindedIndicator; <add> } <add> <add> public String getMultiInstitutionIndicator() { <add> return multiInstitutionIndicator; <add> } <add> <add> public void setMultiInstitutionIndicator(String multiInstitutionIndicator) { <add> this.multiInstitutionIndicator = multiInstitutionIndicator; <add> } <add> <add> public String getRandomizedIndicator() { <add> return randomizedIndicator; <add> } <add> <add> public void setRandomizedIndicator(String randomizedIndicator) { <add> this.randomizedIndicator = randomizedIndicator; <add> } <add> <ide> public RandomizationType getRandomizationType() { <ide> return randomizationType; <ide> }
Java
mit
04721deb68d2aa9f1e85b5f185acf5af760d9e36
0
matthieu637/cpp-2a-info,matthieu637/cpp-2a-info,matthieu637/cpp-2a-info,david540/cpp-2a-info,david540/cpp-2a-info,david540/cpp-2a-info
package core; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.apache.commons.lang3.tuple.Pair; public class Marche { private boolean ouvert; private boolean fini; private long debut; private Map<Action, Set<Ordre>> liste_achats; private Map<Action, Set<Ordre>> liste_ventes; private List<Joueur> liste_joueurs; private Set<Integer> liste_id_ordres; private Map<Action, Set<Echange>> historiques; private final Lock mutex = new ReentrantLock(); private Thread timer = null; public Marche() { ouvert = false; fini = false; liste_achats = new HashMap<>(); liste_ventes = new HashMap<>(); historiques = new HashMap<>(); for (Action a : Action.values()) { liste_achats.put(a, new TreeSet<Ordre>()); liste_ventes.put(a, new TreeSet<Ordre>()); historiques.put(a, new TreeSet<Echange>()); } liste_joueurs = new LinkedList<>(); liste_id_ordres = new TreeSet<>(); if(Config.getInstance().BANQUE){ Joueur banque = creer_joueur("banque"); banque.setSolde_euros(Integer.MAX_VALUE); int max_action_en_jeu = Config.getInstance().SOLDE_ACTIONS_INIT*Action.values().length*100;//100 joueurs for(Action a : Action.values()){ banque.getSolde_actions().put(a, Integer.MAX_VALUE); achat(banque, a, 0.25f, max_action_en_jeu); vend(banque, a, 25.0f, max_action_en_jeu); } } } public boolean est_ouvert() { return ouvert; } public void commence() { ouvert = true; debut = System.currentTimeMillis(); timer = new Thread() { @Override public void run() { try { Thread.sleep(1000 * 60 * Config.getInstance().TEMPS_PARTIE); } catch (InterruptedException e) { //might be interrupted if creator leaves //don't print error in this case } fini = true; try { Thread.sleep(1000 * 60); // sleep 1 s to be sure fini is taking into account } catch (InterruptedException e) { //might be interrupted if creator leaves //don't print error in this case } //fermer tous les ordres for(Joueur joueur : liste_joueurs){ List<Integer> ordre_supprimer = new LinkedList<>(); for(Pair<Integer, Ordre> t : joueur.getOperationsOuvertes()){ ordre_supprimer.add(t.getLeft()); } for(Integer i : ordre_supprimer){ annuler(joueur, i); } } } }; timer.start(); } public boolean est_fini() { return fini; } public synchronized Joueur creer_joueur(String nom) { Joueur j = new Joueur(nom); liste_joueurs.add(j); return j; } public synchronized boolean nom_possible(String nom) { for (Joueur j : liste_joueurs) if (j.getNom().equalsIgnoreCase(nom)) return false; return true; } public Set<Ordre> getListeAchats(Action a) { return liste_achats.get(a); } public Set<Ordre> getListeVentes(Action a) { return liste_ventes.get(a); } public Set<Echange> getHistoriqueEchanges(Action a) { return historiques.get(a); } public int achat(Joueur joueur_achat, Action a, float prix_achat, int volume_achat) { if (volume_achat <= 0.0) return -5; if (prix_achat <= 0.0) return -6; mutex.lock(); int argent_joueur = joueur_achat.getSolde_euros(); int argent_engage = (int) (volume_achat * prix_achat); if (argent_joueur < argent_engage) { mutex.unlock(); return -7; } Iterator<Ordre> it = liste_ventes.get(a).iterator(); while (it.hasNext() && volume_achat > 0) { Ordre vente = it.next(); Joueur joueur_vente = vente.getJoueur(); if (prix_achat >= vente.prix) { Echange e = new Echange(joueur_vente, joueur_achat, vente.prix, Math.min(vente.volume, volume_achat)); historiques.get(a).add(e); // l'achat est complete if (volume_achat <= vente.volume) { int volume_vendu = volume_achat; joueur_vente.setSolde_euros(joueur_vente.getSolde_euros() + (int) (vente.prix * volume_vendu)); joueur_achat.setSolde_euros(joueur_achat.getSolde_euros() - (int) (vente.prix * volume_vendu)); joueur_achat.getSolde_actions().put(a, joueur_achat.getSolde_actions().get(a) + volume_vendu); vente.setVolume(vente.getVolume() - volume_vendu); //ordre restant vide if(vente.getVolume() == 0){ Integer id_vente = vente.getId_ordre(); joueur_vente.retirerOperation(id_vente); it.remove(); } mutex.unlock(); return 0; } // volume_achat > vente.volume int volume_vendu = vente.volume; joueur_vente.setSolde_euros(joueur_vente.getSolde_euros() + (int) (vente.prix * volume_vendu)); joueur_achat.setSolde_euros(joueur_achat.getSolde_euros() - (int) (vente.prix * volume_vendu)); joueur_achat.getSolde_actions().put(a, joueur_achat.getSolde_actions().get(a) + volume_vendu); vente.setVolume(vente.getVolume() - volume_vendu); // remove Integer id_vente = vente.getId_ordre(); joueur_vente.retirerOperation(id_vente); it.remove(); volume_achat -= volume_vendu; } else break; } // provisionne le reste joueur_achat.setSolde_euros(joueur_achat.getSolde_euros() - (int) (prix_achat * volume_achat)); int id = creer_id_ordre(); Ordre achat = new Achat(id, a, prix_achat, volume_achat, joueur_achat); liste_achats.get(a).add(achat); joueur_achat.getOperationsOuvertes().add(Pair.of(id, achat)); mutex.unlock(); return id; } public Object vend(Joueur joueur_vente, Action a, float prix_vente, int volume_vente) { if (volume_vente <= 0.0) return -8; if (prix_vente <= 0.0) return -9; mutex.lock(); int volume_joueur = joueur_vente.getSolde_actions().get(a); if (volume_joueur < volume_vente) { mutex.unlock(); return -10; } joueur_vente.getSolde_actions().put(a, volume_joueur - volume_vente); Iterator<Ordre> it = liste_achats.get(a).iterator(); while (it.hasNext() && volume_vente > 0) { Achat achat = (Achat) it.next(); Joueur joueur_achat = achat.getJoueur(); if (prix_vente <= achat.prix) { Echange e = new Echange(joueur_vente, joueur_achat, achat.prix, Math.min(achat.volume, volume_vente)); historiques.get(a).add(e); // la vente est complete if (volume_vente <= achat.volume) { int volume_vendu = volume_vente; joueur_vente.setSolde_euros(joueur_vente.getSolde_euros() + (int) (achat.prix * volume_vendu)); joueur_achat.getSolde_actions().put(a, joueur_achat.getSolde_actions().get(a) + volume_vendu); // achat.setArgent_paye(achat.getArgent_paye() + (int) (achat.prix * volume_vendu)); achat.setVolume(achat.getVolume() - volume_vente); //ordre restant vide if(achat.getVolume() == 0){ Integer id_achat = achat.getId_ordre(); joueur_achat.retirerOperation(id_achat); it.remove(); } mutex.unlock(); return 0; } // volume_vente > vente.volume int volume_vendu = achat.volume; joueur_vente.setSolde_euros(joueur_vente.getSolde_euros() + (int) (achat.prix * volume_vendu)); joueur_achat.getSolde_actions().put(a, joueur_achat.getSolde_actions().get(a) + volume_vendu); // achat.setArgent_paye(achat.getArgent_paye() + (int) (achat.prix * volume_vendu)); achat.setVolume(achat.getVolume() - volume_vente); // remove Integer id_achat = achat.getId_ordre(); joueur_achat.retirerOperation(id_achat); it.remove(); volume_vente -= volume_vendu; } else break; } int id = creer_id_ordre(); Ordre vente = new Vente(id, a, prix_vente, volume_vente, joueur_vente); liste_ventes.get(a).add(vente); joueur_vente.getOperationsOuvertes().add(Pair.of(id, vente)); mutex.unlock(); return id; } public int suivre(Joueur joueur, Integer ordre) { mutex.lock(); Ordre o = joueur.contientOperation(ordre); if (o == null) { mutex.unlock(); return 0; } int vol = o.getVolume(); mutex.unlock(); return vol; } public int annuler(Joueur joueur, int ordre_id) { mutex.lock(); Ordre o = joueur.contientOperation(ordre_id); if (o == null) { mutex.unlock(); return -11; } if (o instanceof Achat) { liste_achats.get(o.action).remove(o); joueur.retirerOperation(ordre_id); int argent_recupere = (int) (o.prix * o.volume); if (argent_recupere > 0) joueur.setSolde_euros(joueur.getSolde_euros() + argent_recupere); mutex.unlock(); return argent_recupere; } else { liste_ventes.get(o.action).remove(o); joueur.retirerOperation(ordre_id); int nb_action = joueur.getSolde_actions().get(o.action); joueur.getSolde_actions().put(o.action, nb_action + o.volume); mutex.unlock(); return o.volume; } } private synchronized int creer_id_ordre() { int numero_partie = (int) (Math.random() * 100000000); while (liste_id_ordres.contains((Integer) numero_partie)) numero_partie = (int) (Math.random() * 100000000); liste_id_ordres.add(numero_partie); return numero_partie; } public synchronized void retirer_joueur(Joueur joueur) { List<Integer> ordre_supprimer = new LinkedList<>(); for(Pair<Integer, Ordre> t : joueur.getOperationsOuvertes()){ ordre_supprimer.add(t.getLeft()); } for(Integer i : ordre_supprimer){ annuler(joueur, i); } liste_joueurs.remove(joueur); } public String fin() { StringBuffer sb = new StringBuffer(liste_joueurs.size() * 100); sb.append("{'temps':"); long secondes = ((debut + Config.getInstance().TEMPS_PARTIE * 60 * 1000) - System.currentTimeMillis()) / 1000; if (secondes < 0) secondes = 0; sb.append(String.valueOf(secondes)); if (fini) { sb.append(",'classement':["); Collections.sort(liste_joueurs); for(Joueur j : liste_joueurs){ sb.append("'"); sb.append(j.getNom()); sb.append("',"); } sb.deleteCharAt(sb.length()-1); sb.append("]"); } sb.append("}"); return new String(sb); } @Override public String toString() { return "Marche [ouvert=" + ouvert + ", fini=" + fini + ", debut=" + debut + ", liste_achats=" + liste_achats + ", liste_ventes=" + liste_ventes + ", liste_joueurs=" + liste_joueurs + ", liste_id_ordres=" + liste_id_ordres + ", historiques=" + historiques + ", mutex=" + mutex + "]"; } public void destroy(){ if(timer != null){ timer.interrupt(); } } }
2017/SimBourse/src/core/Marche.java
package core; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.apache.commons.lang3.tuple.Pair; public class Marche { private boolean ouvert; private boolean fini; private long debut; private Map<Action, Set<Ordre>> liste_achats; private Map<Action, Set<Ordre>> liste_ventes; private List<Joueur> liste_joueurs; private Set<Integer> liste_id_ordres; private Map<Action, Set<Echange>> historiques; private final Lock mutex = new ReentrantLock(); private Thread timer = null; public Marche() { ouvert = false; fini = false; liste_achats = new HashMap<>(); liste_ventes = new HashMap<>(); historiques = new HashMap<>(); for (Action a : Action.values()) { liste_achats.put(a, new TreeSet<Ordre>()); liste_ventes.put(a, new TreeSet<Ordre>()); historiques.put(a, new TreeSet<Echange>()); } liste_joueurs = new LinkedList<>(); liste_id_ordres = new TreeSet<>(); if(Config.getInstance().BANQUE){ Joueur banque = creer_joueur("banque"); banque.setSolde_euros(Integer.MAX_VALUE); int max_action_en_jeu = Config.getInstance().SOLDE_ACTIONS_INIT*Action.values().length*100;//100 joueurs for(Action a : Action.values()){ banque.getSolde_actions().put(a, Integer.MAX_VALUE); achat(banque, a, 0.25f, max_action_en_jeu); vend(banque, a, 25.0f, max_action_en_jeu); } } } public boolean est_ouvert() { return ouvert; } public void commence() { ouvert = true; debut = System.currentTimeMillis(); timer = new Thread() { @Override public void run() { try { Thread.sleep(1000 * 60 * Config.getInstance().TEMPS_PARTIE); } catch (InterruptedException e) { //might be interrupted if creator leaves //don't print error in this case } fini = true; try { Thread.sleep(1000 * 60); // sleep 1 s to be sure fini is taking into account } catch (InterruptedException e) { //might be interrupted if creator leaves //don't print error in this case } //fermer tous les ordres for(Joueur joueur : liste_joueurs){ List<Integer> ordre_supprimer = new LinkedList<>(); for(Pair<Integer, Ordre> t : joueur.getOperationsOuvertes()){ ordre_supprimer.add(t.getLeft()); } for(Integer i : ordre_supprimer){ annuler(joueur, i); } } } }; timer.start(); } public boolean est_fini() { return fini; } public synchronized Joueur creer_joueur(String nom) { Joueur j = new Joueur(nom); liste_joueurs.add(j); return j; } public synchronized boolean nom_possible(String nom) { for (Joueur j : liste_joueurs) if (j.getNom().equalsIgnoreCase(nom)) return false; return true; } public Set<Ordre> getListeAchats(Action a) { return liste_achats.get(a); } public Set<Ordre> getListeVentes(Action a) { return liste_ventes.get(a); } public Set<Echange> getHistoriqueEchanges(Action a) { return historiques.get(a); } public int achat(Joueur joueur_achat, Action a, float prix_achat, int volume_achat) { if (volume_achat <= 0.0) return -5; if (prix_achat <= 0.0) return -6; mutex.lock(); int argent_joueur = joueur_achat.getSolde_euros(); int argent_engage = (int) (volume_achat * prix_achat); if (argent_joueur < argent_engage) { mutex.unlock(); return -7; } Iterator<Ordre> it = liste_ventes.get(a).iterator(); while (it.hasNext() && volume_achat > 0) { Ordre vente = it.next(); Joueur joueur_vente = vente.getJoueur(); if (prix_achat >= vente.prix) { Echange e = new Echange(joueur_vente, joueur_achat, vente.prix, Math.min(vente.volume, volume_achat)); historiques.get(a).add(e); // l'achat est complete if (volume_achat <= vente.volume) { int volume_vendu = volume_achat; joueur_vente.setSolde_euros(joueur_vente.getSolde_euros() + (int) (vente.prix * volume_vendu)); joueur_achat.setSolde_euros(joueur_achat.getSolde_euros() - (int) (vente.prix * volume_vendu)); joueur_achat.getSolde_actions().put(a, joueur_achat.getSolde_actions().get(a) + volume_vendu); vente.setVolume(vente.getVolume() - volume_vendu); mutex.unlock(); return 0; } // volume_achat > vente.volume int volume_vendu = vente.volume; joueur_vente.setSolde_euros(joueur_vente.getSolde_euros() + (int) (vente.prix * volume_vendu)); joueur_achat.setSolde_euros(joueur_achat.getSolde_euros() - (int) (vente.prix * volume_vendu)); joueur_achat.getSolde_actions().put(a, joueur_achat.getSolde_actions().get(a) + volume_vendu); vente.setVolume(vente.getVolume() - volume_vendu); // remove Integer id_vente = vente.getId_ordre(); joueur_vente.retirerOperation(id_vente); it.remove(); volume_achat -= volume_vendu; } else break; } // provisionne le reste joueur_achat.setSolde_euros(joueur_achat.getSolde_euros() - (int) (prix_achat * volume_achat)); int id = creer_id_ordre(); Ordre achat = new Achat(id, a, prix_achat, volume_achat, joueur_achat); liste_achats.get(a).add(achat); joueur_achat.getOperationsOuvertes().add(Pair.of(id, achat)); mutex.unlock(); return id; } public Object vend(Joueur joueur_vente, Action a, float prix_vente, int volume_vente) { if (volume_vente <= 0.0) return -8; if (prix_vente <= 0.0) return -9; mutex.lock(); int volume_joueur = joueur_vente.getSolde_actions().get(a); if (volume_joueur < volume_vente) { mutex.unlock(); return -10; } joueur_vente.getSolde_actions().put(a, volume_joueur - volume_vente); Iterator<Ordre> it = liste_achats.get(a).iterator(); while (it.hasNext() && volume_vente > 0) { Achat achat = (Achat) it.next(); Joueur joueur_achat = achat.getJoueur(); if (prix_vente <= achat.prix) { Echange e = new Echange(joueur_vente, joueur_achat, achat.prix, Math.min(achat.volume, volume_vente)); historiques.get(a).add(e); // la vente est complete if (volume_vente <= achat.volume) { int volume_vendu = volume_vente; joueur_vente.setSolde_euros(joueur_vente.getSolde_euros() + (int) (achat.prix * volume_vendu)); joueur_achat.getSolde_actions().put(a, joueur_achat.getSolde_actions().get(a) + volume_vendu); // achat.setArgent_paye(achat.getArgent_paye() + (int) (achat.prix * volume_vendu)); achat.setVolume(achat.getVolume() - volume_vente); mutex.unlock(); return 0; } // volume_vente > vente.volume int volume_vendu = achat.volume; joueur_vente.setSolde_euros(joueur_vente.getSolde_euros() + (int) (achat.prix * volume_vendu)); joueur_achat.getSolde_actions().put(a, joueur_achat.getSolde_actions().get(a) + volume_vendu); // achat.setArgent_paye(achat.getArgent_paye() + (int) (achat.prix * volume_vendu)); achat.setVolume(achat.getVolume() - volume_vente); // remove Integer id_vente = achat.getId_ordre(); joueur_achat.retirerOperation(id_vente); it.remove(); volume_vente -= volume_vendu; } else break; } int id = creer_id_ordre(); Ordre vente = new Vente(id, a, prix_vente, volume_vente, joueur_vente); liste_ventes.get(a).add(vente); joueur_vente.getOperationsOuvertes().add(Pair.of(id, vente)); mutex.unlock(); return id; } public int suivre(Joueur joueur, Integer ordre) { mutex.lock(); Ordre o = joueur.contientOperation(ordre); if (o == null) { mutex.unlock(); return 0; } int vol = o.getVolume(); mutex.unlock(); return vol; } public int annuler(Joueur joueur, int ordre_id) { mutex.lock(); Ordre o = joueur.contientOperation(ordre_id); if (o == null) { mutex.unlock(); return -11; } if (o instanceof Achat) { liste_achats.get(o.action).remove(o); joueur.retirerOperation(ordre_id); int argent_recupere = (int) (o.prix * o.volume); if (argent_recupere > 0) joueur.setSolde_euros(joueur.getSolde_euros() + argent_recupere); mutex.unlock(); return argent_recupere; } else { liste_ventes.get(o.action).remove(o); joueur.retirerOperation(ordre_id); int nb_action = joueur.getSolde_actions().get(o.action); joueur.getSolde_actions().put(o.action, nb_action + o.volume); mutex.unlock(); return o.volume; } } private synchronized int creer_id_ordre() { int numero_partie = (int) (Math.random() * 100000000); while (liste_id_ordres.contains((Integer) numero_partie)) numero_partie = (int) (Math.random() * 100000000); liste_id_ordres.add(numero_partie); return numero_partie; } public synchronized void retirer_joueur(Joueur joueur) { List<Integer> ordre_supprimer = new LinkedList<>(); for(Pair<Integer, Ordre> t : joueur.getOperationsOuvertes()){ ordre_supprimer.add(t.getLeft()); } for(Integer i : ordre_supprimer){ annuler(joueur, i); } liste_joueurs.remove(joueur); } public String fin() { StringBuffer sb = new StringBuffer(liste_joueurs.size() * 100); sb.append("{'temps':"); long secondes = ((debut + Config.getInstance().TEMPS_PARTIE * 60 * 1000) - System.currentTimeMillis()) / 1000; if (secondes < 0) secondes = 0; sb.append(String.valueOf(secondes)); if (fini) { sb.append(",'classement':["); Collections.sort(liste_joueurs); for(Joueur j : liste_joueurs){ sb.append("'"); sb.append(j.getNom()); sb.append("',"); } sb.deleteCharAt(sb.length()-1); sb.append("]"); } sb.append("}"); return new String(sb); } @Override public String toString() { return "Marche [ouvert=" + ouvert + ", fini=" + fini + ", debut=" + debut + ", liste_achats=" + liste_achats + ", liste_ventes=" + liste_ventes + ", liste_joueurs=" + liste_joueurs + ", liste_id_ordres=" + liste_id_ordres + ", historiques=" + historiques + ", mutex=" + mutex + "]"; } public void destroy(){ if(timer != null){ timer.interrupt(); } } }
correction bug https://github.com/matthieu637/cpp-2a-info/pull/2
2017/SimBourse/src/core/Marche.java
correction bug https://github.com/matthieu637/cpp-2a-info/pull/2
<ide><path>017/SimBourse/src/core/Marche.java <ide> joueur_achat.setSolde_euros(joueur_achat.getSolde_euros() - (int) (vente.prix * volume_vendu)); <ide> joueur_achat.getSolde_actions().put(a, joueur_achat.getSolde_actions().get(a) + volume_vendu); <ide> vente.setVolume(vente.getVolume() - volume_vendu); <add> <add> //ordre restant vide <add> if(vente.getVolume() == 0){ <add> Integer id_vente = vente.getId_ordre(); <add> joueur_vente.retirerOperation(id_vente); <add> it.remove(); <add> } <ide> <ide> mutex.unlock(); <ide> return 0; <ide> // achat.setArgent_paye(achat.getArgent_paye() + (int) (achat.prix * volume_vendu)); <ide> achat.setVolume(achat.getVolume() - volume_vente); <ide> <add> //ordre restant vide <add> if(achat.getVolume() == 0){ <add> Integer id_achat = achat.getId_ordre(); <add> joueur_achat.retirerOperation(id_achat); <add> it.remove(); <add> } <add> <ide> mutex.unlock(); <ide> return 0; <ide> } <ide> achat.setVolume(achat.getVolume() - volume_vente); <ide> <ide> // remove <del> Integer id_vente = achat.getId_ordre(); <del> joueur_achat.retirerOperation(id_vente); <add> Integer id_achat = achat.getId_ordre(); <add> joueur_achat.retirerOperation(id_achat); <ide> it.remove(); <ide> <ide> volume_vente -= volume_vendu;
Java
apache-2.0
c56cd9750de2ce19d766abbb994f5653d523b936
0
cloud-software-foundation/c5-replicator,cloud-software-foundation/c5-replicator,quantiply-fork/c5-replicator,quantiply-fork/c5-replicator
/* * Copyright (C) 2014 Ohm Data * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package c5db.discovery; import c5db.codec.UdpProtostuffDecoder; import c5db.codec.UdpProtostuffEncoder; import c5db.discovery.generated.Availability; import c5db.discovery.generated.ModuleDescriptor; import c5db.interfaces.C5Server; import c5db.interfaces.DiscoveryModule; import c5db.interfaces.discovery.NewNodeVisible; import c5db.interfaces.discovery.NodeInfo; import c5db.interfaces.discovery.NodeInfoReply; import c5db.interfaces.discovery.NodeInfoRequest; import c5db.interfaces.server.ModuleStateChange; import c5db.messages.generated.ModuleType; import c5db.util.FiberOnly; import com.google.common.collect.ImmutableMap; import com.google.common.util.concurrent.AbstractService; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.socket.DatagramChannel; import io.netty.channel.socket.nio.NioDatagramChannel; import org.jetlang.channels.MemoryChannel; import org.jetlang.channels.MemoryRequestChannel; import org.jetlang.channels.Request; import org.jetlang.channels.RequestChannel; import org.jetlang.fibers.Fiber; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; /** * Uses broadcast UDP packets to discover 'adjacent' nodes in the cluster. Maintains * a state table for them, and provides information to other modules as they request it. * <p/> * Currently UDP broadcast has some issues on Mac OSX vs Linux. The big question, * specifically, is what happens when multiple processes bind to 255.255.255.255:PORT * and send packets? Which processes receive such packets? * <ul> * <li>On Mac OSX 10.8/9, all processes reliably recieve all packets including * the originating process</li> * <li>On Linux (Ubuntu, modern) a variety of things appear to occur: * <ul> * <li>First to bind receives all packets</li> * <li>All processes receives all packets</li> * <li>No one receives any packets</li> * <li>Please fill this doc in!</li> * </ul></li> * </ul> * <p/> * The beacon service needs to be refactored and different discovery methods need to be * pluggable but all behind the discovery module interface. */ public class BeaconService extends AbstractService implements DiscoveryModule { private static final Logger LOG = LoggerFactory.getLogger(BeaconService.class); public static final String LOOPBACK_ADDRESS = "127.0.0.1"; public static final String BROADCAST_ADDRESS = "255.255.255.255"; @Override public ModuleType getModuleType() { return ModuleType.Discovery; } @Override public boolean hasPort() { return true; } @Override public int port() { return discoveryPort; } @Override public String acceptCommand(String commandString) { return null; } private final RequestChannel<NodeInfoRequest, NodeInfoReply> nodeInfoRequests = new MemoryRequestChannel<>(); @Override public RequestChannel<NodeInfoRequest, NodeInfoReply> getNodeInfo() { return nodeInfoRequests; } @Override public ListenableFuture<NodeInfoReply> getNodeInfo(long nodeId, ModuleType module) { SettableFuture<NodeInfoReply> future = SettableFuture.create(); fiber.execute(() -> { NodeInfo peer = peers.get(nodeId); if (peer == null) { future.set(NodeInfoReply.NO_REPLY); } else { Integer servicePort = peer.modules.get(module); if (servicePort == null) { future.set(NodeInfoReply.NO_REPLY); } else { List<String> peerAddrs = peer.availability.getAddressesList(); future.set(new NodeInfoReply(true, peerAddrs, servicePort)); } } }); return future; } @FiberOnly private void handleNodeInfoRequest(Request<NodeInfoRequest, NodeInfoReply> message) { NodeInfoRequest req = message.getRequest(); NodeInfo peer = peers.get(req.nodeId); if (peer == null) { message.reply(NodeInfoReply.NO_REPLY); return; } Integer servicePort = peer.modules.get(req.moduleType); if (servicePort == null) { message.reply(NodeInfoReply.NO_REPLY); return; } List<String> peerAddrs = peer.availability.getAddressesList(); // does this module run on that peer? message.reply(new NodeInfoReply(true, peerAddrs, servicePort)); } @Override public String toString() { return "BeaconService{" + "discoveryPort=" + discoveryPort + ", nodeId=" + nodeId + '}'; } // For main system modules/pubsub stuff. private final C5Server c5Server; private final long nodeId; private final int discoveryPort; private final EventLoopGroup eventLoop; private final Map<ModuleType, Integer> moduleInfo = new HashMap<>(); private final Map<Long, NodeInfo> peers = new HashMap<>(); private final org.jetlang.channels.Channel<Availability> incomingMessages = new MemoryChannel<>(); private final Fiber fiber; // These should be final, but they are initialized in doStart(). private Channel broadcastChannel = null; private InetSocketAddress sendAddress = null; private Bootstrap bootstrap = null; private List<String> localIPs; public class BeaconMessageHandler extends SimpleChannelInboundHandler<Availability> { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { LOG.warn("Exception, ignoring datagram", cause); } @Override protected void channelRead0(ChannelHandlerContext ctx, Availability msg) throws Exception { incomingMessages.publish(msg); } } /** * @param nodeId the id of this node. * @param discoveryPort the port to send discovery beacons on and to listen to * @throws InterruptedException * @throws SocketException */ public BeaconService(long nodeId, int discoveryPort, final Fiber fiber, EventLoopGroup eventLoop, Map<ModuleType, Integer> modules, C5Server theC5Server ) throws InterruptedException, SocketException { this.discoveryPort = discoveryPort; this.nodeId = nodeId; this.fiber = fiber; moduleInfo.putAll(modules); this.c5Server = theC5Server; this.eventLoop = eventLoop; } @Override public ListenableFuture<ImmutableMap<Long, NodeInfo>> getState() { final SettableFuture<ImmutableMap<Long, NodeInfo>> future = SettableFuture.create(); fiber.execute(() -> { future.set(getCopyOfState()); }); return future; } org.jetlang.channels.Channel<NewNodeVisible> newNodeVisibleChannel = new MemoryChannel<>(); @Override public org.jetlang.channels.Channel<NewNodeVisible> getNewNodeNotifications() { return newNodeVisibleChannel; } private ImmutableMap<Long, NodeInfo> getCopyOfState() { return ImmutableMap.copyOf(peers); } @FiberOnly private void sendBeacon() { if (broadcastChannel == null) { LOG.debug("Channel not available yet, deferring beacon send"); return; } LOG.trace("Sending beacon broadcast message to {}", sendAddress); List<ModuleDescriptor> msgModules = new ArrayList<>(moduleInfo.size()); for (ModuleType moduleType : moduleInfo.keySet()) { msgModules.add( new ModuleDescriptor(moduleType, moduleInfo.get(moduleType)) ); } Availability beaconMessage = new Availability(nodeId, 0, localIPs, msgModules); broadcastChannel.writeAndFlush(new UdpProtostuffEncoder.UdpProtostuffMessage<>(sendAddress, beaconMessage)); // Fix issue #76, feed back the beacon Message to our own database: processWireMessage(beaconMessage); } @FiberOnly private void processWireMessage(Availability message) { LOG.trace("Got incoming message {}", message); if (message.getNodeId() == 0) { // if (!message.hasNodeId()) { LOG.error("Incoming availability message does not have node id, ignoring!"); return; } // Always just overwrite what was already there for now. // TODO consider a more sophisticated merge strategy? NodeInfo nodeInfo = new NodeInfo(message); if (!peers.containsKey(message.getNodeId())) { getNewNodeNotifications().publish(new NewNodeVisible(message.getNodeId(), nodeInfo)); } peers.put(message.getNodeId(), nodeInfo); } @FiberOnly private void serviceChange(ModuleStateChange message) { if (message.state == State.RUNNING) { LOG.debug("BeaconService adding running module {} on port {}", message.module.getModuleType(), message.module.port()); moduleInfo.put(message.module.getModuleType(), message.module.port()); } else if (message.state == State.STOPPING || message.state == State.FAILED || message.state == State.TERMINATED) { LOG.debug("BeaconService removed module {} on port {} with state {}", message.module.getModuleType(), message.module.port(), message.state); moduleInfo.remove(message.module.getModuleType()); } else { LOG.debug("BeaconService got unknown state module change {}", message); } } @Override protected void doStart() { eventLoop.next().execute(() -> { bootstrap = new Bootstrap(); bootstrap.group(eventLoop) .channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .option(ChannelOption.SO_REUSEADDR, true) .handler(new ChannelInitializer<DatagramChannel>() { @Override protected void initChannel(DatagramChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast("protobufDecoder", new UdpProtostuffDecoder<>(Availability.getSchema(), false)); p.addLast("protobufEncoder", new UdpProtostuffEncoder<>(Availability.getSchema(), false)); p.addLast("beaconMessageHandler", new BeaconMessageHandler()); } }); // Wait, this is why we are in a new executor... //noinspection RedundantCast bootstrap.bind(discoveryPort).addListener((ChannelFutureListener) future -> { broadcastChannel = future.channel(); }); if (c5Server.isSingleNodeMode()) { sendAddress = new InetSocketAddress(LOOPBACK_ADDRESS, discoveryPort); } else { sendAddress = new InetSocketAddress(BROADCAST_ADDRESS, discoveryPort); } //Availability.Builder msgBuilder = Availability.newBuilder(nodeInfoFragment); try { localIPs = getLocalIPs(); } catch (SocketException e) { LOG.error("SocketException:", e); notifyFailed(e); } //msgBuilder.addAllAddresses(getLocalIPs()); //beaconMessage = msgBuilder.build(); // Schedule fiber tasks and subscriptions. incomingMessages.subscribe(fiber, this::processWireMessage); nodeInfoRequests.subscribe(fiber, this::handleNodeInfoRequest); fiber.scheduleAtFixedRate(this::sendBeacon, 2, 10, TimeUnit.SECONDS); c5Server.getModuleStateChangeChannel().subscribe(fiber, this::serviceChange); fiber.start(); notifyStarted(); }); } @Override protected void doStop() { eventLoop.next().execute(() -> { fiber.dispose(); notifyStopped(); }); } private List<String> getLocalIPs() throws SocketException { List<String> ips = new LinkedList<>(); for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements(); ) { NetworkInterface iface = interfaces.nextElement(); if (iface.isPointToPoint()) { continue; //ignore tunnel type interfaces } for (Enumeration<InetAddress> addrs = iface.getInetAddresses(); addrs.hasMoreElements(); ) { InetAddress addr = addrs.nextElement(); if (addr.isLoopbackAddress() || addr.isLinkLocalAddress() || addr.isAnyLocalAddress()) { continue; } ips.add(addr.getHostAddress()); } } return ips; } }
c5db/src/main/java/c5db/discovery/BeaconService.java
/* * Copyright (C) 2014 Ohm Data * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package c5db.discovery; import c5db.codec.UdpProtostuffDecoder; import c5db.codec.UdpProtostuffEncoder; import c5db.discovery.generated.Availability; import c5db.discovery.generated.ModuleDescriptor; import c5db.interfaces.C5Server; import c5db.interfaces.DiscoveryModule; import c5db.interfaces.discovery.NewNodeVisible; import c5db.interfaces.discovery.NodeInfo; import c5db.interfaces.discovery.NodeInfoReply; import c5db.interfaces.discovery.NodeInfoRequest; import c5db.interfaces.server.ModuleStateChange; import c5db.messages.generated.ModuleType; import c5db.util.FiberOnly; import com.google.common.collect.ImmutableMap; import com.google.common.util.concurrent.AbstractService; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.socket.DatagramChannel; import io.netty.channel.socket.nio.NioDatagramChannel; import org.jetlang.channels.MemoryChannel; import org.jetlang.channels.MemoryRequestChannel; import org.jetlang.channels.Request; import org.jetlang.channels.RequestChannel; import org.jetlang.core.Callback; import org.jetlang.fibers.Fiber; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; /** * Uses broadcast UDP packets to discover 'adjacent' nodes in the cluster. Maintains * a state table for them, and provides information to other modules as they request it. * <p/> * Currently UDP broadcast has some issues on Mac OSX vs Linux. The big question, * specifically, is what happens when multiple processes bind to 255.255.255.255:PORT * and send packets? Which processes receive such packets? * <ul> * <li>On Mac OSX 10.8/9, all processes reliably recieve all packets including * the originating process</li> * <li>On Linux (Ubuntu, modern) a variety of things appear to occur: * <ul> * <li>First to bind receives all packets</li> * <li>All processes receives all packets</li> * <li>No one receives any packets</li> * <li>Please fill this doc in!</li> * </ul></li> * </ul> * <p/> * The beacon service needs to be refactored and different discovery methods need to be * pluggable but all behind the discovery module interface. */ public class BeaconService extends AbstractService implements DiscoveryModule { private static final Logger LOG = LoggerFactory.getLogger(BeaconService.class); public static final String LOOPBACK_ADDRESS = "127.0.0.1"; public static final String BROADCAST_ADDRESS = "255.255.255.255"; @Override public ModuleType getModuleType() { return ModuleType.Discovery; } @Override public boolean hasPort() { return true; } @Override public int port() { return discoveryPort; } @Override public String acceptCommand(String commandString) { return null; } private final RequestChannel<NodeInfoRequest, NodeInfoReply> nodeInfoRequests = new MemoryRequestChannel<>(); @Override public RequestChannel<NodeInfoRequest, NodeInfoReply> getNodeInfo() { return nodeInfoRequests; } @Override public ListenableFuture<NodeInfoReply> getNodeInfo(long nodeId, ModuleType module) { SettableFuture<NodeInfoReply> future = SettableFuture.create(); fiber.execute(() -> { NodeInfo peer = peers.get(nodeId); if (peer == null) { future.set(NodeInfoReply.NO_REPLY); } else { Integer servicePort = peer.modules.get(module); if (servicePort == null) { future.set(NodeInfoReply.NO_REPLY); } else { List<String> peerAddrs = peer.availability.getAddressesList(); future.set(new NodeInfoReply(true, peerAddrs, servicePort)); } } }); return future; } @FiberOnly private void handleNodeInfoRequest(Request<NodeInfoRequest, NodeInfoReply> message) { NodeInfoRequest req = message.getRequest(); NodeInfo peer = peers.get(req.nodeId); if (peer == null) { message.reply(NodeInfoReply.NO_REPLY); return; } Integer servicePort = peer.modules.get(req.moduleType); if (servicePort == null) { message.reply(NodeInfoReply.NO_REPLY); return; } List<String> peerAddrs = peer.availability.getAddressesList(); // does this module run on that peer? message.reply(new NodeInfoReply(true, peerAddrs, servicePort)); } @Override public String toString() { return "BeaconService{" + "discoveryPort=" + discoveryPort + ", nodeId=" + nodeId + '}'; } // For main system modules/pubsub stuff. private final C5Server c5Server; private final long nodeId; private final int discoveryPort; private final EventLoopGroup eventLoop; private final Map<ModuleType, Integer> moduleInfo = new HashMap<>(); private final Map<Long, NodeInfo> peers = new HashMap<>(); private final org.jetlang.channels.Channel<Availability> incomingMessages = new MemoryChannel<>(); private final Fiber fiber; // These should be final, but they are initialized in doStart(). private Channel broadcastChannel = null; private InetSocketAddress sendAddress = null; private Bootstrap bootstrap = null; private List<String> localIPs; public class BeaconMessageHandler extends SimpleChannelInboundHandler<Availability> { @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { LOG.warn("Exception, ignoring datagram", cause); } @Override protected void channelRead0(ChannelHandlerContext ctx, Availability msg) throws Exception { incomingMessages.publish(msg); } } /** * @param nodeId the id of this node. * @param discoveryPort the port to send discovery beacons on and to listen to * @throws InterruptedException * @throws SocketException */ public BeaconService(long nodeId, int discoveryPort, final Fiber fiber, EventLoopGroup eventLoop, Map<ModuleType, Integer> modules, C5Server theC5Server ) throws InterruptedException, SocketException { this.discoveryPort = discoveryPort; this.nodeId = nodeId; this.fiber = fiber; moduleInfo.putAll(modules); this.c5Server = theC5Server; this.eventLoop = eventLoop; } @Override public ListenableFuture<ImmutableMap<Long, NodeInfo>> getState() { final SettableFuture<ImmutableMap<Long, NodeInfo>> future = SettableFuture.create(); fiber.execute(new Runnable() { @Override public void run() { future.set(getCopyOfState()); } }); return future; } org.jetlang.channels.Channel<NewNodeVisible> newNodeVisibleChannel = new MemoryChannel<>(); @Override public org.jetlang.channels.Channel<NewNodeVisible> getNewNodeNotifications() { return newNodeVisibleChannel; } private ImmutableMap<Long, NodeInfo> getCopyOfState() { return ImmutableMap.copyOf(peers); } @FiberOnly private void sendBeacon() { if (broadcastChannel == null) { LOG.debug("Channel not available yet, deferring beacon send"); return; } LOG.trace("Sending beacon broadcast message to {}", sendAddress); List<ModuleDescriptor> msgModules = new ArrayList<>(moduleInfo.size()); for (ModuleType moduleType : moduleInfo.keySet()) { msgModules.add( new ModuleDescriptor(moduleType, moduleInfo.get(moduleType)) ); } Availability beaconMessage = new Availability(nodeId, 0, localIPs, msgModules); broadcastChannel.writeAndFlush(new UdpProtostuffEncoder.UdpProtostuffMessage<>(sendAddress, beaconMessage)); // Fix issue #76, feed back the beacon Message to our own database: processWireMessage(beaconMessage); } @FiberOnly private void processWireMessage(Availability message) { LOG.trace("Got incoming message {}", message); if (message.getNodeId() == 0) { // if (!message.hasNodeId()) { LOG.error("Incoming availability message does not have node id, ignoring!"); return; } // Always just overwrite what was already there for now. // TODO consider a more sophisticated merge strategy? NodeInfo nodeInfo = new NodeInfo(message); if (!peers.containsKey(message.getNodeId())) { getNewNodeNotifications().publish(new NewNodeVisible(message.getNodeId(), nodeInfo)); } peers.put(message.getNodeId(), nodeInfo); } @FiberOnly private void serviceChange(ModuleStateChange message) { if (message.state == State.RUNNING) { LOG.debug("BeaconService adding running module {} on port {}", message.module.getModuleType(), message.module.port()); moduleInfo.put(message.module.getModuleType(), message.module.port()); } else if (message.state == State.STOPPING || message.state == State.FAILED || message.state == State.TERMINATED) { LOG.debug("BeaconService removed module {} on port {} with state {}", message.module.getModuleType(), message.module.port(), message.state); moduleInfo.remove(message.module.getModuleType()); } else { LOG.debug("BeaconService got unknown state module change {}", message); } } @Override protected void doStart() { eventLoop.next().execute(new Runnable() { @Override public void run() { bootstrap = new Bootstrap(); bootstrap.group(eventLoop) .channel(NioDatagramChannel.class) .option(ChannelOption.SO_BROADCAST, true) .option(ChannelOption.SO_REUSEADDR, true) .handler(new ChannelInitializer<DatagramChannel>() { @Override protected void initChannel(DatagramChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast("protobufDecoder", new UdpProtostuffDecoder<>(Availability.getSchema(), false)); p.addLast("protobufEncoder", new UdpProtostuffEncoder<>(Availability.getSchema(), false)); p.addLast("beaconMessageHandler", new BeaconMessageHandler()); } }); // Wait, this is why we are in a new executor... bootstrap.bind(discoveryPort).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { broadcastChannel = future.channel(); } }); if (c5Server.isSingleNodeMode()) { sendAddress = new InetSocketAddress(LOOPBACK_ADDRESS, discoveryPort); } else { sendAddress = new InetSocketAddress(BROADCAST_ADDRESS, discoveryPort); } //Availability.Builder msgBuilder = Availability.newBuilder(nodeInfoFragment); try { localIPs = getLocalIPs(); } catch (SocketException e) { LOG.error("SocketException:", e); notifyFailed(e); } //msgBuilder.addAllAddresses(getLocalIPs()); //beaconMessage = msgBuilder.build(); // Schedule fiber tasks and subscriptions. incomingMessages.subscribe(fiber, new Callback<Availability>() { @Override public void onMessage(Availability message) { processWireMessage(message); } }); nodeInfoRequests.subscribe(fiber, new Callback<Request<NodeInfoRequest, NodeInfoReply>>() { @Override public void onMessage(Request<NodeInfoRequest, NodeInfoReply> message) { handleNodeInfoRequest(message); } }); fiber.scheduleAtFixedRate(new Runnable() { @Override public void run() { sendBeacon(); } }, 2, 10, TimeUnit.SECONDS); c5Server.getModuleStateChangeChannel().subscribe(fiber, new Callback<ModuleStateChange>() { @Override public void onMessage(ModuleStateChange message) { serviceChange(message); } }); fiber.start(); notifyStarted(); } }); } @Override protected void doStop() { eventLoop.next().execute(new Runnable() { @Override public void run() { fiber.dispose(); notifyStopped(); } }); } private List<String> getLocalIPs() throws SocketException { List<String> ips = new LinkedList<>(); for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements(); ) { NetworkInterface iface = interfaces.nextElement(); if (iface.isPointToPoint()) { continue; //ignore tunnel type interfaces } for (Enumeration<InetAddress> addrs = iface.getInetAddresses(); addrs.hasMoreElements(); ) { InetAddress addr = addrs.nextElement(); if (addr.isLoopbackAddress() || addr.isLinkLocalAddress() || addr.isAnyLocalAddress()) { continue; } ips.add(addr.getHostAddress()); } } return ips; } }
Remove BeaconService inspections (lambda and method ref conversions)
c5db/src/main/java/c5db/discovery/BeaconService.java
Remove BeaconService inspections (lambda and method ref conversions)
<ide><path>5db/src/main/java/c5db/discovery/BeaconService.java <ide> import com.google.common.util.concurrent.SettableFuture; <ide> import io.netty.bootstrap.Bootstrap; <ide> import io.netty.channel.Channel; <del>import io.netty.channel.ChannelFuture; <ide> import io.netty.channel.ChannelFutureListener; <ide> import io.netty.channel.ChannelHandlerContext; <ide> import io.netty.channel.ChannelInitializer; <ide> import org.jetlang.channels.MemoryRequestChannel; <ide> import org.jetlang.channels.Request; <ide> import org.jetlang.channels.RequestChannel; <del>import org.jetlang.core.Callback; <ide> import org.jetlang.fibers.Fiber; <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <ide> public ListenableFuture<ImmutableMap<Long, NodeInfo>> getState() { <ide> final SettableFuture<ImmutableMap<Long, NodeInfo>> future = SettableFuture.create(); <ide> <del> fiber.execute(new Runnable() { <del> @Override <del> public void run() { <del> future.set(getCopyOfState()); <del> } <add> fiber.execute(() -> { <add> future.set(getCopyOfState()); <ide> }); <ide> <ide> return future; <ide> <ide> @Override <ide> protected void doStart() { <del> eventLoop.next().execute(new Runnable() { <del> @Override <del> public void run() { <del> bootstrap = new Bootstrap(); <del> bootstrap.group(eventLoop) <del> .channel(NioDatagramChannel.class) <del> .option(ChannelOption.SO_BROADCAST, true) <del> .option(ChannelOption.SO_REUSEADDR, true) <del> .handler(new ChannelInitializer<DatagramChannel>() { <del> @Override <del> protected void initChannel(DatagramChannel ch) throws Exception { <del> ChannelPipeline p = ch.pipeline(); <del> <del> p.addLast("protobufDecoder", <del> new UdpProtostuffDecoder<>(Availability.getSchema(), false)); <del> <del> p.addLast("protobufEncoder", <del> new UdpProtostuffEncoder<>(Availability.getSchema(), false)); <del> <del> p.addLast("beaconMessageHandler", new BeaconMessageHandler()); <del> } <del> }); <del> // Wait, this is why we are in a new executor... <del> bootstrap.bind(discoveryPort).addListener(new ChannelFutureListener() { <del> @Override <del> public void operationComplete(ChannelFuture future) throws Exception { <del> broadcastChannel = future.channel(); <del> } <del> }); <del> if (c5Server.isSingleNodeMode()) { <del> sendAddress = new InetSocketAddress(LOOPBACK_ADDRESS, discoveryPort); <del> } else { <del> sendAddress = new InetSocketAddress(BROADCAST_ADDRESS, discoveryPort); <del> } <del> //Availability.Builder msgBuilder = Availability.newBuilder(nodeInfoFragment); <del> try { <del> localIPs = getLocalIPs(); <del> } catch (SocketException e) { <del> LOG.error("SocketException:", e); <del> notifyFailed(e); <del> } <del> //msgBuilder.addAllAddresses(getLocalIPs()); <del> //beaconMessage = msgBuilder.build(); <del> <del> // Schedule fiber tasks and subscriptions. <del> incomingMessages.subscribe(fiber, new Callback<Availability>() { <del> @Override <del> public void onMessage(Availability message) { <del> processWireMessage(message); <del> } <del> }); <del> nodeInfoRequests.subscribe(fiber, new Callback<Request<NodeInfoRequest, NodeInfoReply>>() { <del> @Override <del> public void onMessage(Request<NodeInfoRequest, NodeInfoReply> message) { <del> handleNodeInfoRequest(message); <del> } <del> }); <del> <del> fiber.scheduleAtFixedRate(new Runnable() { <del> @Override <del> public void run() { <del> sendBeacon(); <del> } <del> }, 2, 10, TimeUnit.SECONDS); <del> <del> c5Server.getModuleStateChangeChannel().subscribe(fiber, new Callback<ModuleStateChange>() { <del> @Override <del> public void onMessage(ModuleStateChange message) { <del> serviceChange(message); <del> } <del> }); <del> <del> fiber.start(); <del> <del> notifyStarted(); <del> <del> } <add> eventLoop.next().execute(() -> { <add> bootstrap = new Bootstrap(); <add> bootstrap.group(eventLoop) <add> .channel(NioDatagramChannel.class) <add> .option(ChannelOption.SO_BROADCAST, true) <add> .option(ChannelOption.SO_REUSEADDR, true) <add> .handler(new ChannelInitializer<DatagramChannel>() { <add> @Override <add> protected void initChannel(DatagramChannel ch) throws Exception { <add> ChannelPipeline p = ch.pipeline(); <add> <add> p.addLast("protobufDecoder", <add> new UdpProtostuffDecoder<>(Availability.getSchema(), false)); <add> <add> p.addLast("protobufEncoder", <add> new UdpProtostuffEncoder<>(Availability.getSchema(), false)); <add> <add> p.addLast("beaconMessageHandler", new BeaconMessageHandler()); <add> } <add> }); <add> // Wait, this is why we are in a new executor... <add> //noinspection RedundantCast <add> bootstrap.bind(discoveryPort).addListener((ChannelFutureListener) future -> { <add> broadcastChannel = future.channel(); <add> }); <add> if (c5Server.isSingleNodeMode()) { <add> sendAddress = new InetSocketAddress(LOOPBACK_ADDRESS, discoveryPort); <add> } else { <add> sendAddress = new InetSocketAddress(BROADCAST_ADDRESS, discoveryPort); <add> } <add> //Availability.Builder msgBuilder = Availability.newBuilder(nodeInfoFragment); <add> try { <add> localIPs = getLocalIPs(); <add> } catch (SocketException e) { <add> LOG.error("SocketException:", e); <add> notifyFailed(e); <add> } <add> //msgBuilder.addAllAddresses(getLocalIPs()); <add> //beaconMessage = msgBuilder.build(); <add> <add> // Schedule fiber tasks and subscriptions. <add> incomingMessages.subscribe(fiber, this::processWireMessage); <add> nodeInfoRequests.subscribe(fiber, this::handleNodeInfoRequest); <add> <add> fiber.scheduleAtFixedRate(this::sendBeacon, 2, 10, TimeUnit.SECONDS); <add> <add> c5Server.getModuleStateChangeChannel().subscribe(fiber, this::serviceChange); <add> <add> fiber.start(); <add> <add> notifyStarted(); <add> <ide> }); <ide> } <ide> <ide> @Override <ide> protected void doStop() { <del> eventLoop.next().execute(new Runnable() { <del> @Override <del> public void run() { <del> fiber.dispose(); <del> <del> notifyStopped(); <del> } <add> eventLoop.next().execute(() -> { <add> fiber.dispose(); <add> <add> notifyStopped(); <ide> }); <ide> } <ide>
Java
epl-1.0
2e7e06f2f360917afdd4a4c87c562c4cf05cb97d
0
miomin/Keeper
package scu.miomin.com.keeper.activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import scu.miomin.com.keeper.R; import scu.miomin.com.keeper.baseactivity.BaseActivity; import scu.miomin.com.keeper.util.ToastUtils; /** * 描述:绘制心电图的界面 创建日期:2015/5/23 * * @author 莫绪旻 */ public class AddFollowupActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_followup); } public static void actionStart(Context context) { Intent intent = new Intent(context, AddFollowupActivity.class); context.startActivity(intent); } public void back(View view) { super.onBackPressed(); } public void add(View view) { ToastUtils.showToast(this, getResources().getString(R.string.addSucceed)); super.onBackPressed(); } }
KeeperApp/src/main/java/scu/miomin/com/keeper/activity/AddFollowupActivity.java
package scu.miomin.com.keeper.activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import scu.miomin.com.keeper.R; import scu.miomin.com.keeper.baseactivity.BaseActivity; import scu.miomin.com.keeper.util.ToastUtils; /** * 描述:绘制心电图的界面 创建日期:2015/5/23 * * @author 莫绪旻 */ public class AddFollowupActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_followup); } public static void actionStart(Context context) { Intent intent = new Intent(context, AddFollowupActivity.class); context.startActivity(intent); } public void back(View view) { super.onBackPressed(); } public void add(View view) { ToastUtils.showToast(this, getResources().getString(R.string.addSucceed)); super.onBackPressed(); } }
AddFollowupActivity
KeeperApp/src/main/java/scu/miomin/com/keeper/activity/AddFollowupActivity.java
AddFollowupActivity
<ide><path>eeperApp/src/main/java/scu/miomin/com/keeper/activity/AddFollowupActivity.java <ide> setContentView(R.layout.activity_add_followup); <ide> <ide> <del> <del> <ide> } <ide> <ide> public static void actionStart(Context context) {
Java
apache-2.0
cb96bffa671eeca3a4b345e1c3d58960547e61c0
0
google/walt,google/walt,google/walt,google/walt
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.chromium.latency.walt; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.text.method.ScrollingMovementMethod; import android.view.Choreographer; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.io.IOException; import java.util.ArrayList; import java.util.Locale; import static org.chromium.latency.walt.Utils.getIntPreference; /** * Measurement of screen response time when switching between black and white. */ public class ScreenResponseFragment extends Fragment implements View.OnClickListener { private static final int curveTimeout = 1000; // milliseconds private static final int curveBlinkTime = 250; // milliseconds private Activity activity; private SimpleLogger logger; private WaltDevice waltDevice; private Handler handler = new Handler(); TextView blackBox; private int timesToBlink; int initiatedBlinks = 0; int detectedBlinks = 0; boolean isBoxWhite = false; long lastFrameStartTime; long lastFrameCallbackTime; long lastSetBackgroundTime; ArrayList<Double> deltas = new ArrayList<>(); private static final int color_gray = Color.argb(0xFF, 0xBB, 0xBB, 0xBB); private StringBuilder brightnessCurveData = new StringBuilder(); public ScreenResponseFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { timesToBlink = getIntPreference(getContext(), R.string.preference_screen_blinks, 20); activity = getActivity(); waltDevice = WaltDevice.getInstance(getContext()); logger = SimpleLogger.getInstance(getContext()); // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_screen_response, container, false); } @Override public void onResume() { super.onResume(); // restartMeasurement(); blackBox = (TextView) activity.findViewById(R.id.txt_black_box_screen); // Register this fragment class as the listener for some button clicks activity.findViewById(R.id.button_restart_screen_response).setOnClickListener(this); activity.findViewById(R.id.button_start_screen_response).setOnClickListener(this); activity.findViewById(R.id.button_brightness_curve).setOnClickListener(this); } void startMeasurement() { // TODO: Add a stop button to interrupt the measurement deltas.clear(); initiatedBlinks = 0; detectedBlinks = 0; blackBox.setText(""); blackBox.setBackgroundColor(Color.WHITE); isBoxWhite = true; handler.postDelayed(startBlinking, 300); } Runnable startBlinking = new Runnable() { @Override public void run() { try { // Check for PWM WaltDevice.TriggerMessage tmsg = waltDevice.readTriggerMessage(WaltDevice.CMD_SEND_LAST_SCREEN); logger.log("Blink count was: "+ tmsg.count); waltDevice.softReset(); waltDevice.syncClock(); // Note, sync also sends CMD_RESET (but not simpleSync). waltDevice.command(WaltDevice.CMD_AUTO_SCREEN_ON); waltDevice.startListener(); } catch (IOException e) { logger.log("Error: " + e.getMessage()); } // Register a callback for triggers waltDevice.setTriggerHandler(triggerHandler); // post doBlink runnable handler.postDelayed(doBlinkRunnable, 100); } }; Runnable doBlinkRunnable = new Runnable() { @Override public void run() { logger.log("======\ndoBlink.run(), initiatedBlinks = " + initiatedBlinks + " detectedBlinks = " + detectedBlinks); // Check if we saw some transitions without blinking, this would usually mean // the screen has PWM enabled, warn and ask the user to turn it off. if (initiatedBlinks == 0 && detectedBlinks > 1) { logger.log("Unexpected blinks detected, probably PWM, turn it off"); // TODO: show a dialog here instructing to turn off PWM and finish this properly return; } if (initiatedBlinks >= timesToBlink) { finishAndShowStats(); return; } // * 2 flip the screen, save time as last flip time (last flip direction?) isBoxWhite = !isBoxWhite; int nextColor = isBoxWhite ? Color.WHITE : Color.BLACK; initiatedBlinks++; blackBox.setBackgroundColor(nextColor); lastSetBackgroundTime = waltDevice.clock.micros(); // TODO: is this the right time to save? // Set up a callback to run on next frame render to collect the timestamp Choreographer.getInstance().postFrameCallback(new Choreographer.FrameCallback() { @Override public void doFrame(long frameTimeNanos) { // frameTimeNanos is he time in nanoseconds when the frame started being // rendered, in the nanoTime() timebase. lastFrameStartTime = frameTimeNanos / 1000 - waltDevice.clock.baseTime; lastFrameCallbackTime = System.nanoTime() / 1000 - waltDevice.clock.baseTime; } }); // Repost doBlink to some far away time to blink again even if nothing arrives from // Teensy. This callback will almost always get cancelled by onIncomingTimestamp() handler.postDelayed(doBlinkRunnable, 600); // TODO: config and or randomiz the delay, } }; private WaltDevice.TriggerHandler triggerHandler = new WaltDevice.TriggerHandler() { @Override public void onReceive(WaltDevice.TriggerMessage tmsg) { // Remove the far away doBlink callback handler.removeCallbacks(doBlinkRunnable); detectedBlinks++; logger.log("blink counts " + initiatedBlinks + " " + detectedBlinks); if (initiatedBlinks == 0) { if (detectedBlinks < 5) { logger.log("got incoming but initiatedBlinks = 0"); return; } else { logger.log("Looks like PWM is used for this screen, turn auto brightness off and set it to max brightness"); // TODO: show a modal dialog here saying the same as the log msg above return; } } double dt = (tmsg.t - lastFrameStartTime) / 1000.; deltas.add(dt); logger.log(String.format(Locale.US, "Times [ms]: setBG:%.3f callback:%.3f physical:%.3f black2white:%d", (lastSetBackgroundTime - lastFrameStartTime) / 1000.0 , (lastFrameCallbackTime - lastFrameStartTime) / 1000.0, dt, isBoxWhite ? 1: 0 )); // Schedule another blink soon-ish handler.postDelayed(doBlinkRunnable, 50); // TODO: randomize the delay } }; void finishAndShowStats() { // Stop the USB listener waltDevice.stopListener(); // Unregister trigger handler waltDevice.clearTriggerHandler(); waltDevice.sendAndFlush(WaltDevice.CMD_AUTO_SCREEN_OFF); waltDevice.checkDrift(); // Show deltas and the median logger.log("deltas: " + deltas.toString()); logger.log(String.format(Locale.US, "Median latency %.1f ms", Utils.median(deltas) )); blackBox.setText(logger.getLogText()); blackBox.setMovementMethod(new ScrollingMovementMethod()); blackBox.setBackgroundColor(color_gray); } @Override public void onClick(View v) { if (v.getId() == R.id.button_restart_screen_response) { // TODO: change to "Stop measurement?" blackBox.setBackgroundColor(Color.BLACK); return; } if (v.getId() == R.id.button_start_screen_response) { logger.log("Starting screen response measurement"); startMeasurement(); return; } if (v.getId() == R.id.button_brightness_curve) { logger.log("Starting screen brightness curve measurement"); startBrightnessCurve(); return; } } private WaltDevice.TriggerHandler brightnessTriggerHandler = new WaltDevice.TriggerHandler() { @Override public void onReceive(WaltDevice.TriggerMessage tmsg) { logger.log("ERROR: Brightness curve trigger got a trigger message, " + "this should never happen." ); } @Override public void onReceiveRaw(String s) { brightnessCurveData.append(s); if (s.trim().equals("end")) { // Remove the delayed callbed and run it now handler.removeCallbacks(finishBrightnessCurve); handler.post(finishBrightnessCurve); } } }; void startBrightnessCurve() { try { waltDevice.syncClock(); waltDevice.startListener(); } catch (IOException e) { logger.log("Error starting test: " + e.getMessage()); return; } waltDevice.setTriggerHandler(brightnessTriggerHandler); blackBox.setText(""); long tStart = waltDevice.clock.micros(); try { waltDevice.command(WaltDevice.CMD_BRIGHTNESS_CURVE); } catch (IOException e) { logger.log("Error sending command CMD_BRIGHTNESS_CURVE: " + e.getMessage()); return; } blackBox.setBackgroundColor(Color.WHITE); logger.log("=== Screen brightness curve: ===\nt_start: " + tStart); handler.postDelayed(finishBrightnessCurve, curveTimeout); // Schedule the screen to flip back to black in curveBlinkTime ms handler.postDelayed(new Runnable() { @Override public void run() { long tBack = waltDevice.clock.micros(); blackBox.setBackgroundColor(Color.BLACK); logger.log("t_back: " + tBack); } }, curveBlinkTime); } Runnable finishBrightnessCurve = new Runnable() { @Override public void run() { waltDevice.stopListener(); waltDevice.clearTriggerHandler(); // TODO: Add option to save this data into a separate file rather than the main log. logger.log(brightnessCurveData.toString()); logger.log("=== End of screen brightness data ==="); blackBox.setText(logger.getLogText()); blackBox.setMovementMethod(new ScrollingMovementMethod()); blackBox.setBackgroundColor(color_gray); } }; }
android/WALT/app/src/main/java/org/chromium/latency/walt/ScreenResponseFragment.java
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.chromium.latency.walt; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.text.method.ScrollingMovementMethod; import android.view.Choreographer; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.io.IOException; import java.util.ArrayList; import java.util.Locale; import static org.chromium.latency.walt.Utils.getIntPreference; /** * Measurement of screen response time when switching between black and white. */ public class ScreenResponseFragment extends Fragment implements View.OnClickListener { private static final int curveTimeout = 1000; // milliseconds private static final int curveBlinkTime = 250; // milliseconds private Activity activity; private SimpleLogger logger; private WaltDevice waltDevice; private Handler handler = new Handler(); TextView mBlackBox; private int timesToBlink; int mInitiatedBlinks = 0; int mDetectedBlinks = 0; boolean mIsBoxWhite = false; long lastFrameStartTime; long lastFrameCallbackTime; long lastSetBackgroundTime; ArrayList<Double> deltas = new ArrayList<>(); private static final int color_gray = Color.argb(0xFF, 0xBB, 0xBB, 0xBB); private StringBuilder brightnessCurveData = new StringBuilder(); public ScreenResponseFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { timesToBlink = getIntPreference(getContext(), R.string.preference_screen_blinks, 20); activity = getActivity(); waltDevice = WaltDevice.getInstance(getContext()); logger = SimpleLogger.getInstance(getContext()); // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_screen_response, container, false); } @Override public void onResume() { super.onResume(); // restartMeasurement(); mBlackBox = (TextView) activity.findViewById(R.id.txt_black_box_screen); // Register this fragment class as the listener for some button clicks activity.findViewById(R.id.button_restart_screen_response).setOnClickListener(this); activity.findViewById(R.id.button_start_screen_response).setOnClickListener(this); activity.findViewById(R.id.button_brightness_curve).setOnClickListener(this); } void startMeasurement() { // TODO: Add a stop button to interrupt the measurement deltas.clear(); mInitiatedBlinks = 0; mDetectedBlinks = 0; mBlackBox.setText(""); mBlackBox.setBackgroundColor(Color.WHITE); mIsBoxWhite = true; handler.postDelayed(startBlinking, 300); } Runnable startBlinking = new Runnable() { @Override public void run() { try { // Check for PWM WaltDevice.TriggerMessage tmsg = waltDevice.readTriggerMessage(WaltDevice.CMD_SEND_LAST_SCREEN); logger.log("Blink count was: "+ tmsg.count); waltDevice.softReset(); waltDevice.syncClock(); // Note, sync also sends CMD_RESET (but not simpleSync). waltDevice.command(WaltDevice.CMD_AUTO_SCREEN_ON); waltDevice.startListener(); } catch (IOException e) { logger.log("Error: " + e.getMessage()); } // Register a callback for triggers waltDevice.setTriggerHandler(triggerHandler); // post doBlink runnable handler.postDelayed(doBlinkRunnable, 100); } }; Runnable doBlinkRunnable = new Runnable() { @Override public void run() { logger.log("======\ndoBlink.run(), mInitiatedBlinks = " + mInitiatedBlinks + " mDetectedBlinks = " + mDetectedBlinks); // Check if we saw some transitions without blinking, this would usually mean // the screen has PWM enabled, warn and ask the user to turn it off. if (mInitiatedBlinks == 0 && mDetectedBlinks > 1) { logger.log("Unexpected blinks detected, probably PWM, turn it off"); // TODO: show a dialog here instructing to turn off PWM and finish this properly return; } if (mInitiatedBlinks >= timesToBlink) { finishAndShowStats(); return; } // * 2 flip the screen, save time as last flip time (last flip direction?) mIsBoxWhite = !mIsBoxWhite; int nextColor = mIsBoxWhite ? Color.WHITE : Color.BLACK; mInitiatedBlinks++; mBlackBox.setBackgroundColor(nextColor); lastSetBackgroundTime = waltDevice.clock.micros(); // TODO: is this the right time to save? // Set up a callback to run on next frame render to collect the timestamp Choreographer.getInstance().postFrameCallback(new Choreographer.FrameCallback() { @Override public void doFrame(long frameTimeNanos) { // frameTimeNanos is he time in nanoseconds when the frame started being // rendered, in the nanoTime() timebase. lastFrameStartTime = frameTimeNanos / 1000 - waltDevice.clock.baseTime; lastFrameCallbackTime = System.nanoTime() / 1000 - waltDevice.clock.baseTime; } }); // Repost doBlink to some far away time to blink again even if nothing arrives from // Teensy. This callback will almost always get cancelled by onIncomingTimestamp() handler.postDelayed(doBlinkRunnable, 600); // TODO: config and or randomiz the delay, } }; private WaltDevice.TriggerHandler triggerHandler = new WaltDevice.TriggerHandler() { @Override public void onReceive(WaltDevice.TriggerMessage tmsg) { // Remove the far away doBlink callback handler.removeCallbacks(doBlinkRunnable); mDetectedBlinks++; logger.log("blink counts " + mInitiatedBlinks + " " + mDetectedBlinks); if (mInitiatedBlinks == 0) { if (mDetectedBlinks < 5) { logger.log("got incoming but mInitiatedBlinks = 0"); return; } else { logger.log("Looks like PWM is used for this screen, turn auto brightness off and set it to max brightness"); // TODO: show a modal dialog here saying the same as the log msg above return; } } double dt = (tmsg.t - lastFrameStartTime) / 1000.; deltas.add(dt); logger.log(String.format(Locale.US, "Times [ms]: setBG:%.3f callback:%.3f physical:%.3f black2white:%d", (lastSetBackgroundTime - lastFrameStartTime) / 1000.0 , (lastFrameCallbackTime - lastFrameStartTime) / 1000.0, dt, mIsBoxWhite? 1: 0 )); // Schedule another blink soon-ish handler.postDelayed(doBlinkRunnable, 50); // TODO: randomize the delay } }; void finishAndShowStats() { // Stop the USB listener waltDevice.stopListener(); // Unregister trigger handler waltDevice.clearTriggerHandler(); waltDevice.sendAndFlush(WaltDevice.CMD_AUTO_SCREEN_OFF); waltDevice.checkDrift(); // Show deltas and the median logger.log("deltas: " + deltas.toString()); logger.log(String.format(Locale.US, "Median latency %.1f ms", Utils.median(deltas) )); mBlackBox.setText(logger.getLogText()); mBlackBox.setMovementMethod(new ScrollingMovementMethod()); mBlackBox.setBackgroundColor(color_gray); } @Override public void onClick(View v) { if (v.getId() == R.id.button_restart_screen_response) { // TODO: change to "Stop measurement?" mBlackBox.setBackgroundColor(Color.BLACK); return; } if (v.getId() == R.id.button_start_screen_response) { logger.log("Starting screen response measurement"); startMeasurement(); return; } if (v.getId() == R.id.button_brightness_curve) { logger.log("Starting screen brightness curve measurement"); startBrightnessCurve(); return; } } private WaltDevice.TriggerHandler brightnessTriggerHandler = new WaltDevice.TriggerHandler() { @Override public void onReceive(WaltDevice.TriggerMessage tmsg) { logger.log("ERROR: Brightness curve trigger got a trigger message, " + "this should never happen." ); } @Override public void onReceiveRaw(String s) { brightnessCurveData.append(s); if (s.trim().equals("end")) { // Remove the delayed callbed and run it now handler.removeCallbacks(finishBrightnessCurve); handler.post(finishBrightnessCurve); } } }; void startBrightnessCurve() { try { waltDevice.syncClock(); waltDevice.startListener(); } catch (IOException e) { logger.log("Error starting test: " + e.getMessage()); return; } waltDevice.setTriggerHandler(brightnessTriggerHandler); mBlackBox.setText(""); long tStart = waltDevice.clock.micros(); try { waltDevice.command(WaltDevice.CMD_BRIGHTNESS_CURVE); } catch (IOException e) { logger.log("Error sending command CMD_BRIGHTNESS_CURVE: " + e.getMessage()); return; } mBlackBox.setBackgroundColor(Color.WHITE); logger.log("=== Screen brightness curve: ===\nt_start: " + tStart); handler.postDelayed(finishBrightnessCurve, curveTimeout); // Schedule the screen to flip back to black in curveBlinkTime ms handler.postDelayed(new Runnable() { @Override public void run() { long tBack = waltDevice.clock.micros(); mBlackBox.setBackgroundColor(Color.BLACK); logger.log("t_back: " + tBack); } }, curveBlinkTime); } Runnable finishBrightnessCurve = new Runnable() { @Override public void run() { waltDevice.stopListener(); waltDevice.clearTriggerHandler(); // TODO: Add option to save this data into a separate file rather than the main log. logger.log(brightnessCurveData.toString()); logger.log("=== End of screen brightness data ==="); mBlackBox.setText(logger.getLogText()); mBlackBox.setMovementMethod(new ScrollingMovementMethod()); mBlackBox.setBackgroundColor(color_gray); } }; }
Renaming - get rid of m prefixes in screen response fragment
android/WALT/app/src/main/java/org/chromium/latency/walt/ScreenResponseFragment.java
Renaming - get rid of m prefixes in screen response fragment
<ide><path>ndroid/WALT/app/src/main/java/org/chromium/latency/walt/ScreenResponseFragment.java <ide> private SimpleLogger logger; <ide> private WaltDevice waltDevice; <ide> private Handler handler = new Handler(); <del> TextView mBlackBox; <add> TextView blackBox; <ide> private int timesToBlink; <del> int mInitiatedBlinks = 0; <del> int mDetectedBlinks = 0; <del> boolean mIsBoxWhite = false; <add> int initiatedBlinks = 0; <add> int detectedBlinks = 0; <add> boolean isBoxWhite = false; <ide> long lastFrameStartTime; <ide> long lastFrameCallbackTime; <ide> long lastSetBackgroundTime; <ide> public void onResume() { <ide> super.onResume(); <ide> // restartMeasurement(); <del> mBlackBox = (TextView) activity.findViewById(R.id.txt_black_box_screen); <add> blackBox = (TextView) activity.findViewById(R.id.txt_black_box_screen); <ide> <ide> <ide> // Register this fragment class as the listener for some button clicks <ide> // TODO: Add a stop button to interrupt the measurement <ide> deltas.clear(); <ide> <del> mInitiatedBlinks = 0; <del> mDetectedBlinks = 0; <del> <del> mBlackBox.setText(""); <del> mBlackBox.setBackgroundColor(Color.WHITE); <del> mIsBoxWhite = true; <add> initiatedBlinks = 0; <add> detectedBlinks = 0; <add> <add> blackBox.setText(""); <add> blackBox.setBackgroundColor(Color.WHITE); <add> isBoxWhite = true; <ide> <ide> handler.postDelayed(startBlinking, 300); <ide> } <ide> Runnable doBlinkRunnable = new Runnable() { <ide> @Override <ide> public void run() { <del> logger.log("======\ndoBlink.run(), mInitiatedBlinks = " + mInitiatedBlinks + " mDetectedBlinks = " + mDetectedBlinks); <add> logger.log("======\ndoBlink.run(), initiatedBlinks = " + initiatedBlinks + " detectedBlinks = " + detectedBlinks); <ide> // Check if we saw some transitions without blinking, this would usually mean <ide> // the screen has PWM enabled, warn and ask the user to turn it off. <del> if (mInitiatedBlinks == 0 && mDetectedBlinks > 1) { <add> if (initiatedBlinks == 0 && detectedBlinks > 1) { <ide> logger.log("Unexpected blinks detected, probably PWM, turn it off"); <ide> // TODO: show a dialog here instructing to turn off PWM and finish this properly <ide> return; <ide> } <ide> <del> if (mInitiatedBlinks >= timesToBlink) { <add> if (initiatedBlinks >= timesToBlink) { <ide> finishAndShowStats(); <ide> return; <ide> } <ide> <ide> // * 2 flip the screen, save time as last flip time (last flip direction?) <ide> <del> mIsBoxWhite = !mIsBoxWhite; <del> int nextColor = mIsBoxWhite ? Color.WHITE : Color.BLACK; <del> mInitiatedBlinks++; <del> mBlackBox.setBackgroundColor(nextColor); <add> isBoxWhite = !isBoxWhite; <add> int nextColor = isBoxWhite ? Color.WHITE : Color.BLACK; <add> initiatedBlinks++; <add> blackBox.setBackgroundColor(nextColor); <ide> lastSetBackgroundTime = waltDevice.clock.micros(); // TODO: is this the right time to save? <ide> <ide> // Set up a callback to run on next frame render to collect the timestamp <ide> // Remove the far away doBlink callback <ide> handler.removeCallbacks(doBlinkRunnable); <ide> <del> mDetectedBlinks++; <del> logger.log("blink counts " + mInitiatedBlinks + " " + mDetectedBlinks); <del> if (mInitiatedBlinks == 0) { <del> if (mDetectedBlinks < 5) { <del> logger.log("got incoming but mInitiatedBlinks = 0"); <add> detectedBlinks++; <add> logger.log("blink counts " + initiatedBlinks + " " + detectedBlinks); <add> if (initiatedBlinks == 0) { <add> if (detectedBlinks < 5) { <add> logger.log("got incoming but initiatedBlinks = 0"); <ide> return; <ide> } else { <ide> logger.log("Looks like PWM is used for this screen, turn auto brightness off and set it to max brightness"); <ide> (lastSetBackgroundTime - lastFrameStartTime) / 1000.0 , <ide> (lastFrameCallbackTime - lastFrameStartTime) / 1000.0, <ide> dt, <del> mIsBoxWhite? 1: 0 <add> isBoxWhite ? 1: 0 <ide> )); <ide> <ide> // Schedule another blink soon-ish <ide> Utils.median(deltas) <ide> )); <ide> <del> mBlackBox.setText(logger.getLogText()); <del> mBlackBox.setMovementMethod(new ScrollingMovementMethod()); <del> mBlackBox.setBackgroundColor(color_gray); <add> blackBox.setText(logger.getLogText()); <add> blackBox.setMovementMethod(new ScrollingMovementMethod()); <add> blackBox.setBackgroundColor(color_gray); <ide> } <ide> <ide> @Override <ide> public void onClick(View v) { <ide> if (v.getId() == R.id.button_restart_screen_response) { <ide> // TODO: change to "Stop measurement?" <del> mBlackBox.setBackgroundColor(Color.BLACK); <add> blackBox.setBackgroundColor(Color.BLACK); <ide> return; <ide> } <ide> <ide> <ide> waltDevice.setTriggerHandler(brightnessTriggerHandler); <ide> <del> mBlackBox.setText(""); <add> blackBox.setText(""); <ide> <ide> long tStart = waltDevice.clock.micros(); <ide> <ide> return; <ide> } <ide> <del> mBlackBox.setBackgroundColor(Color.WHITE); <add> blackBox.setBackgroundColor(Color.WHITE); <ide> <ide> logger.log("=== Screen brightness curve: ===\nt_start: " + tStart); <ide> <ide> @Override <ide> public void run() { <ide> long tBack = waltDevice.clock.micros(); <del> mBlackBox.setBackgroundColor(Color.BLACK); <add> blackBox.setBackgroundColor(Color.BLACK); <ide> logger.log("t_back: " + tBack); <ide> <ide> } <ide> logger.log(brightnessCurveData.toString()); <ide> logger.log("=== End of screen brightness data ==="); <ide> <del> mBlackBox.setText(logger.getLogText()); <del> mBlackBox.setMovementMethod(new ScrollingMovementMethod()); <del> mBlackBox.setBackgroundColor(color_gray); <add> blackBox.setText(logger.getLogText()); <add> blackBox.setMovementMethod(new ScrollingMovementMethod()); <add> blackBox.setBackgroundColor(color_gray); <ide> } <ide> }; <ide> }
Java
epl-1.0
6a34f40faffd0511c75a3114ef54eaf9628d8738
0
miomin/Keeper
package scu.miomin.com.keeper.bean; /** * 描述:生日实体类 创建日期:2015/11/3 * * @author 莫绪旻 */ public class BirthdayBean { private int year; private int month; private int day; public BirthdayBean(int year, int month, int day) { this.year = year; this.month = month; this.day = day; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } public int getDay() { return day; } public void setDay(int day) { this.day = day; } @Override public String toString() { String birthday = year + "-"; if (month < 10) birthday = birthday + "0" + month + "-"; else birthday = birthday + month + "-"; if (day < 10) birthday = birthday + "0" + day; else birthday = birthday + day; return birthday; } }
app/src/main/java/scu/miomin/com/keeper/bean/BirthdayBean.java
package scu.miomin.com.keeper.bean; /** * 描述:生日实体类 创建日期:2015/11/3 * * @author 莫绪旻 */ public class BirthdayBean { private int year; private int month; private int day; public BirthdayBean(int year, int month, int day) { this.year = year; this.month = month; this.day = day; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } public int getDay() { return day; } public void setDay(int day) { this.day = day; } @Override public String toString() { String birthday = year + "-"; if (month < 10) birthday = birthday + "0" + month + "-"; else birthday = birthday + month + "-"; if (day < 10) birthday = birthday + "0" + day; else birthday = birthday + day; return birthday; } }
第一次提交library
app/src/main/java/scu/miomin/com/keeper/bean/BirthdayBean.java
第一次提交library
<ide><path>pp/src/main/java/scu/miomin/com/keeper/bean/BirthdayBean.java <ide> <ide> private int year; <ide> private int month; <add> <ide> private int day; <ide> <ide> public BirthdayBean(int year, int month, int day) {
JavaScript
mit
40d204a18b5d617f175aa585929ce5c2a3417a43
0
Xotic750/astrodate
/* AstroDate * * home: https://github.com/Xotic750/astrodate * * Copyright (C) 2013 Graham Fairweather (a.k.a: Xotic750) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ (function (thisContext, privateUndefined) { 'use strict'; // Safari 2.x NFE bug fix // http://kangax.github.io/nfe/ var tempSafariNFE; (function (name, definition) { /*global module, require, define */ var bigNumberFunc = 'BigNumber', bigNumberString = bigNumberFunc.toLowerCase(), projectPaths, projectConfig; if ('object' === typeof module && null !== module && 'object' === typeof module.exports && null !== module.exports) { module.exports = definition(require(bigNumberString + '.js')); } else if ('function' === typeof define && 'object' === typeof define.amd && null !== define.amd) { projectPaths = {}; projectConfig = {}; projectPaths[bigNumberString] = '//cdn.jsdelivr.net/bignumber.js/1.1.0/bignumber.min'; projectConfig[bigNumberString] = {}; require.config({ paths: projectPaths, config: projectConfig }); // "name" should be removed when finished with local testing define(name, [bigNumberString], definition); } else { thisContext[name] = definition(thisContext[bigNumberFunc]); } /*global */ }('astrodate', (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe/ var nfeDefinition; tempSafariNFE = function nfeDefinition(BigNumber) { BigNumber.config({ DECIMAL_PLACES: 9, ROUNDING_MODE: 0, EXPONENTIAL_AT: [-7, 20], RANGE: [-1000000000, 1000000000], ERRORS: true }); var VERSION = '0.5.1', //MAX_INTEGER = 9007199254740991, //MIN_INTEGER = -9007199254740991, UWORD32 = Math.pow(2, 32), MAX_UINT32 = UWORD32 - 1, languages = {}, baseObject = {}, defaultProperties, baseArray = [], baseString = '', toObjectString, baseNumber = 0, baseBoolean = true, fullKeys, dayKeys, monthKeys, protoName = '__proto__', invalidISOCharsRx = new RegExp('[^\\d\\-+WT Z:,\\.]'), replaceTokenRX = new RegExp('([^\\\']+)|(\\\'[^\\\']+\\\')', 'g'), toObject, //j2000 = [2000, 1, 1, 11, 58, 55, 816], extend, arrayIndexOf, objectDefineProperty, objectDefineProperties, objectFreeze, objectIsFrozen, hasProperty, objectHasOwnProperty, objectGetOwnPropertyDescriptor, arrayIsArray, objectInstanceOf, objectGetPrototypeOf, isPlainObject, objectKeys, stringTrim, stringRepeat, stringSplit, //stringStartsWith, //stringEndsWith, stringContains, toObjectFixIndexedAccess, //arrayUnshift, arrayForEach, arraySome, arrayMap, //arrayFilter, arrayReduce, objectIs, numberToInteger, numberIsNaN, numberIsFinite, mathSign, AstroDate, datePatterns, timePatterns, formatTypes, nameTypes, widthTypes, widthTypeShort, defaultLanguage, calendarTypes, leapSeconds; function toNumber(inputArg) { return +inputArg; } function strictEqual(a, b) { return a === b; } function lt(number, limit) { return number < limit; } function lte(number, limit) { return number <= limit; } function gt(number, limit) { return number > limit; } function gte(number, limit) { return number >= limit; } function mod(number1, number2) { return number1 % number2; } function clamp(number, min, max) { return Math.min(Math.max(number, min), max); } function inRange(number, min, max) { return gte(number, min) && lte(number, max); } function isUndefined(inputArg) { return strictEqual(typeof inputArg, 'undefined'); } function isNull(inputArg) { return strictEqual(inputArg, null); } function isBoolean(inputArg) { return strictEqual(inputArg, true) || strictEqual(inputArg, false); } function isNumber(inputArg) { return strictEqual(typeof inputArg, 'number'); } function isZero(inputArg) { return strictEqual(inputArg, 0); } function isString(inputArg) { return strictEqual(typeof inputArg, 'string'); } function isEmptyString(inputArg) { return strictEqual(inputArg, ''); } /* function isNumeric(inputArg) { var val = false, string; if (isNumber(inputArg) || isString(inputArg)) { string = inputArg.toString().replace(/^[+\-]?/, ""); if (!isNaN(parseFloat(string)) && isFinite(string)) { val = true; } } return val; } */ function checkObjectCoercible(inputArg) { if (isUndefined(inputArg) || isNull(inputArg)) { throw new TypeError('Cannot convert "' + inputArg + '" to object'); } return inputArg; } toObject = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe/ var CtrBoolean = baseBoolean.constructor, CtrNumber = baseNumber.constructor, CtrString = baseString.constructor, nfeToObject; tempSafariNFE = function nfeToObject(inputArg) { var object = checkObjectCoercible(inputArg); if (isBoolean(object)) { object = new CtrBoolean(object); } else if (isNumber(object)) { object = new CtrNumber(object); } else if (isString(object)) { object = new CtrString(object); } return object; }; nfeToObject = null; return tempSafariNFE; }()); // named anyToString instead of toString because of SpiderMonkey and Blackberry bug function anyToString(inputArg) { var val; if (isString(inputArg)) { val = inputArg; } else if (isUndefined(inputArg)) { val = 'undefined'; } else { val = String(inputArg); } return val; } toObjectString = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe/ var toStringFN = baseObject.toString, nfeToObjectString; try { if (strictEqual(toStringFN.call(), '[object Undefined]') && strictEqual(toStringFN.call(null), '[object Null]')) { tempSafariNFE = function nfeToObjectString(object) { return toStringFN.call(object); }; } } catch (exception) { tempSafariNFE = null; } if (isNull(tempSafariNFE)) { tempSafariNFE = function nfeToObjectString(object) { var val; if (isUndefined(object)) { val = '[object Undefined]'; } else if (isNull(object)) { val = '[object Null]'; } else { val = toStringFN.call(object); } return val; }; } nfeToObjectString = null; return tempSafariNFE; }()); function isRegExp(inputArg) { return strictEqual(toObjectString(inputArg), '[object RegExp]'); } function isObject(inputArg) { return strictEqual(toObjectString(inputArg), '[object Object]'); } function isFunction(inputArg) { return strictEqual(toObjectString(inputArg), '[object Function]'); } function isTypeObject(inputArg) { return (!isNull(inputArg) && strictEqual(typeof inputArg, 'object')) || isRegExp(inputArg); } // named arrayIsArray instead of isArray because of SpiderMonkey and Blackberry bug arrayIsArray = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe/ var isArrayFN = baseArray.isArray, nfeIsArray; if (isFunction(isArrayFN)) { tempSafariNFE = isArrayFN; } else { tempSafariNFE = function nfeIsArray(inputArg) { return strictEqual(toObjectString(inputArg), '[object Array]'); }; } nfeIsArray = null; return tempSafariNFE; }()); function isEmptyArray(inputArg) { var val; if (arrayIsArray(inputArg) || (isTypeObject(inputArg) && !isFunction(inputArg) && hasProperty(inputArg, 'length'))) { val = isZero(inputArg.length); } else { val = null; } return val; } function arrayFirst(inputArg) { var val; if (!isEmptyArray(inputArg)) { val = inputArg[0]; } return val; } function arrayLast(inputArg) { var val; if (!isEmptyArray(inputArg)) { val = inputArg[inputArg.length - 1]; } return val; } function isDate(inputArg) { return strictEqual(toObjectString(inputArg), '[object Date]'); } // named objectIs instead of objectIs because of SpiderMonkey and Blackberry bug objectIs = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe/ var isIsFn = baseObject.constructor.is, nfeIs; if (isFunction(isIsFn)) { tempSafariNFE = isIsFn; } else { tempSafariNFE = function nfeIs(x, y) { var val; if (strictEqual(x, y)) { if (isZero(x)) { val = strictEqual(1 / x, 1 / y); } else { val = true; } } else { val = !strictEqual(x, x) && !strictEqual(y, y); } return val; }; } nfeIs = null; return tempSafariNFE; }()); // named numberIsNaN instead of isNaN because of SpiderMonkey and Blackberry bug numberIsNaN = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe/ var isNaNFN = baseNumber.constructor.isNaN, nfeIsNaN; if (isFunction(isNaNFN)) { tempSafariNFE = isNaNFN; } else { tempSafariNFE = function nfeIsNaN(number) { return objectIs(number, NaN); }; } nfeIsNaN = null; return tempSafariNFE; }()); // named numberIsFinite instead of isFinite because of SpiderMonkey and Blackberry bug numberIsFinite = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe/ var isFiniteFN = baseNumber.constructor.isFinite, nfeIsFinite; if (isFunction(isFiniteFN)) { tempSafariNFE = isFiniteFN; } else { tempSafariNFE = function nfeIsFinite(number) { return isNumber(number) && isFinite(number); }; } nfeIsFinite = null; return tempSafariNFE; }()); // named mathSign instead of sign because of SpiderMonkey and Blackberry bug mathSign = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe/ var signFN = Math.sign, nfeSign; if (isFunction(signFN)) { tempSafariNFE = signFN; } else { tempSafariNFE = function nfeSign(value) { var number = toNumber(value), val; if (isZero(number) || numberIsNaN(number)) { val = number; } else if (lt(number, 0)) { val = -1; } else { val = 1; } return val; }; } nfeSign = null; return tempSafariNFE; }()); // named numberToInteger instead of toInteger because of SpiderMonkey and Blackberry bug numberToInteger = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe/ var toIntegerFN = Number.toInteger, nfeToInteger; if (isFunction(toIntegerFN)) { tempSafariNFE = toIntegerFN; } else { tempSafariNFE = function nfeToInteger(inputArg) { var number = toNumber(inputArg), val; if (numberIsNaN(number)) { val = +0; } else if (isZero(number) || !numberIsFinite(number)) { val = number; } else { val = mathSign(number) * Math.floor(Math.abs(number)); } return val; }; } nfeToInteger = null; return tempSafariNFE; }()); /* function toInt32(inputArg) { var number = toNumber(inputArg), int32bit, val; if (isZero(number) || !numberIsFinite(number)) { val = +0; } else { int32bit = mod(mathSign(number) * Math.floor(Math.abs(number)), UWORD32); if (gt(int32bit, UWORD32)) { val = int32bit - UWORD32; } else { val = int32bit; } } return val; } */ function toUint32(inputArg) { var number = toNumber(inputArg), val; if (isZero(number) || !numberIsFinite(number)) { val = +0; } else { val = mod(mathSign(number) * Math.floor(Math.abs(number)), UWORD32); } return val; } // named stringSplit instead of split because of SpiderMonkey and Blackberry bug stringSplit = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe/ var splitFN = baseString.split, compliantExecNpcg = isUndefined(/()??/.exec('')[1]), nfeSplit; function replacer(separator, match, args) { var length = args.length - 2, index; arrayFirst(match).replace(separator, function () { for (index = 1; lt(index, length); index += 1) { if (isUndefined(arguments[index])) { match[index] = privateUndefined; } } }); } tempSafariNFE = function nfeSplit(str, separator, limit) { var string = anyToString(checkObjectCoercible(str)), output, flags, lastLastIndex, separator2, match, lastIndex, lastLength, val; if (isRegExp(separator)) { flags = 'g'; if (separator.ignoreCase) { flags += 'i'; } if (separator.multiline) { flags += 'm'; } if (separator.extended) { flags += 'x'; } if (separator.sticky) { flags += 'y'; } separator = new RegExp(separator.source, flags); if (!compliantExecNpcg) { separator2 = new RegExp('^' + separator.source + '$(?!\\s)', flags); } if (isUndefined(limit)) { limit = MAX_UINT32; } else { limit = toUint32(limit); } output = []; flags = 'g'; lastLastIndex = 0; match = separator.exec(string); while (match) { lastIndex = match.index + arrayFirst(match).length; if (lastIndex > lastLastIndex) { output.push(string.slice(lastLastIndex, match.index)); if (!compliantExecNpcg && gt(match.length, 1)) { replacer(separator2, match, arguments); } if (gt(match.length, 1) && lt(match.index, string.length)) { output = output.concat(match.slice(1)); } lastLength = arrayFirst(match).length; lastLastIndex = lastIndex; if (gte(output.length, limit)) { break; } } if (strictEqual(separator.lastIndex, match.index)) { separator.lastIndex += 1; } match = separator.exec(string); } if (strictEqual(lastLastIndex, string.length)) { if (lastLength || !separator.test('')) { output.push(''); } } else { output.push(string.slice(lastLastIndex)); } if (gt(output.length, limit)) { return output.slice(0, limit); } val = output; } else { val = splitFN.call(str, separator, limit); } return val; }; nfeSplit = null; return tempSafariNFE; }()); function firstChar(inputArg) { return anyToString(checkObjectCoercible(inputArg)).charAt(0); } function firstCharIs(inputArg, character) { return strictEqual(firstChar(inputArg), firstChar(character)); } function lastChar(inputArg) { var thisStr = anyToString(checkObjectCoercible(inputArg)); return thisStr.charAt(thisStr.length - 1); } function lastCharIs(inputArg, character) { return strictEqual(lastChar(inputArg), firstChar(character)); } function countCharacter(inputArg, character) { return clamp(stringSplit(anyToString(checkObjectCoercible(inputArg)), firstChar(character)).length - 1, 0, Number.POSITIVE_INFINITY); } function padLeadingChar(inputArg, character, size) { var string = anyToString(checkObjectCoercible(inputArg)), singleChar = firstChar(character), count = numberToInteger(size) - string.length; if (lt(count, 0) || strictEqual(count, Infinity)) { count = 0; } return stringRepeat(singleChar, count) + string; } // named stringRepeat instead of repeat because of SpiderMonkey and Blackberry bug stringRepeat = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var repeatFN = baseString.constructor.repeat, nfeRepeat; function rep(s, times) { var half, val; if (lt(times, 1)) { val = ''; } else if (mod(times, 2)) { val = rep(s, times - 1) + s; } else { half = rep(s, times / 2); val = half + half; } return val; } if (isFunction(repeatFN)) { tempSafariNFE = function nfeRepeat(string, times) { return repeatFN.call(string, times); }; } else { tempSafariNFE = function nfeRepeat(string, count) { var thisString = anyToString(checkObjectCoercible(string)), times = numberToInteger(count); if (lt(times, 0) || strictEqual(times, Infinity)) { throw new RangeError(); } return rep(thisString, times); }; } nfeRepeat = null; return tempSafariNFE; }()); /* // named stringStartsWith instead of startsWith because of SpiderMonkey and Blackberry bug stringStartsWith = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var startsWithFN = baseString.constructor.startsWith, nfeStartsWith; if (isFunction(startsWithFN)) { tempSafariNFE = function nfeStartsWith(string, searchString, position) { return startsWithFN.call(string, searchString, position); }; } else { tempSafariNFE = function nfeStartsWith(string, searchString, position) { var thisStr = anyToString(checkObjectCoercible(string)), searchStr = anyToString(searchString), thisLen = thisStr.length, start = clamp(toInteger(position), 0, thisLen); return strictEqual(thisStr.slice(start, start + thisLen), searchStr); }; } nfeStartsWith = null; return tempSafariNFE; }()); */ /* // named stringEndsWith instead of endsWith because of SpiderMonkey and Blackberry bug stringEndsWith = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var endsWithFN = baseString.constructor.endsWith, nfeEndsWith; if (isFunction(endsWithFN)) { tempSafariNFE = function nfeEndsWith(string, searchString, position) { return endsWithFN.call(string, searchString, position); }; } else { tempSafariNFE = function nfeEndsWith(string, searchString, position) { var thisStr = anyToString(checkObjectCoercible(string)), searchStr = anyToString(searchString), thisLen = thisStr.length, end, start; if (isUndefined(position)) { position = thisLen; } else { position = toInteger(position); } end = clamp(position, 0, thisLen); start = end - searchStr.length; return gte(start, 0) && strictEqual(thisStr.slice(start, end), searchStr); }; } nfeEndsWith = null; return tempSafariNFE; }()); */ // named stringContains instead of contains because of SpiderMonkey and Blackberry bug stringContains = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var containsFN = baseString.constructor.contains, nfeContains; if (isFunction(containsFN)) { tempSafariNFE = function nfeContains(string, searchString, position) { return containsFN.call(string, searchString, position); }; } else { tempSafariNFE = function nfeContains(string, searchString, position) { var thisStr = anyToString(checkObjectCoercible(string)), searchStr = anyToString(searchString), thisLen = thisStr.length; if (isUndefined(position)) { position = 0; } else { position = numberToInteger(position); } return !strictEqual(baseString.indexOf.call(thisStr, searchStr, clamp(position, 0, thisLen)), -1); }; } nfeContains = null; return tempSafariNFE; }()); // named objectGetPrototypeOf instead of getPrototypeOf because of SpiderMonkey and Blackberry bug objectGetPrototypeOf = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var getPrototypeOfFN = baseObject.constructor.getPrototypeOf, nfeGetPrototypeOf, bocProto; if (isFunction(getPrototypeOfFN)) { tempSafariNFE = getPrototypeOfFN; } else if (isNull(baseObject.constructor.prototype[protoName])) { tempSafariNFE = function nfeGetPrototypeOf(object) { return object[protoName]; }; } else { bocProto = baseObject.constructor.prototype; tempSafariNFE = function nfeGetPrototypeOf(object) { if (strictEqual(object, bocProto)) { return null; } var ctrProto = object.constructor.prototype; if (strictEqual(object, ctrProto)) { return bocProto; } return ctrProto; }; } nfeGetPrototypeOf = null; return tempSafariNFE; }()); hasProperty = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var nfeHasProperty; tempSafariNFE = function nfehasProperty(object, property) { return property in object; }; nfeHasProperty = null; return tempSafariNFE; }()); function arrayContains(array, searchElement) { return !strictEqual(arrayIndexOf(array, searchElement), -1); } // http://ecma-international.org/ecma-262/5.1/#sec-15.2.4.5 // Create our own local "hasOwnProperty" function: native -> shim -> sham // named objectHasOwnProperty instead of hasOwnProperty because of SpiderMonkey and Blackberry bug objectHasOwnProperty = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var hasOwnPropertyFN = baseObject.hasOwnProperty, // to combat old IE8- issues, min support IE6 propertyIsEnumerableFN = baseObject.propertyIsEnumerable, hasDontEnumBug = true, testObject = { toString: null }, nfeHasOwnProperty; // use nfeHasOwnProperty to save a var for (nfeHasOwnProperty in testObject) { if (strictEqual(nfeHasOwnProperty, 'toString') && isNull(testObject[nfeHasOwnProperty])) { hasDontEnumBug = false; } } function checkDontEnums(object, property) { return hasDontEnumBug && arrayContains(defaultProperties, property) && hasProperty(object, property) && !strictEqual(object[property], objectGetPrototypeOf(object)[property]); } if (isFunction(hasOwnPropertyFN)) { tempSafariNFE = function nfeHasOwnProperty(object, property) { return hasOwnPropertyFN.call(object, property) || checkDontEnums(object, property); }; } else if (isFunction(propertyIsEnumerableFN)) { tempSafariNFE = function nfeHasOwnProperty(object, property) { return propertyIsEnumerableFN.call(object, property) || checkDontEnums(object, property); }; } else { tempSafariNFE = function nfeHasOwnProperty(object, property) { return hasProperty(object, property) && isUndefined(objectGetPrototypeOf(object)[property]); }; } nfeHasOwnProperty = null; return tempSafariNFE; }()); toObjectFixIndexedAccess = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var boxedString = baseObject.constructor('a'), splitString = !strictEqual(boxedString[0], 'a') || !hasProperty(boxedString, 0), nfeToObjectFixIndexedAccess; if (splitString) { tempSafariNFE = function nfeToObjectFixIndexedAccess(inputArg) { var object; if (isString(inputArg)) { object = stringSplit(inputArg, ''); } else { object = toObject(inputArg); } return object; }; } else { tempSafariNFE = toObject; } nfeToObjectFixIndexedAccess = null; return tempSafariNFE; }()); // named arrayForEach instead of forEach because of SpiderMonkey and Blackberry bug arrayForEach = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var forEachFN = baseArray.forEach, nfeForEach; if (isFunction(forEachFN)) { tempSafariNFE = function nfeForEach(array, fn, thisArg) { return forEachFN.call(array, fn, thisArg); }; } else { tempSafariNFE = function nfeForEach(array, fn, thisArg) { var object = toObjectFixIndexedAccess(array), length, index; if (!isFunction(fn)) { throw new TypeError(fn + ' is not a function'); } for (index = 0, length = toUint32(object.length); lt(index, length); index += 1) { if (hasProperty(object, index)) { fn.call(thisArg, object[index], index, object); } } }; } nfeForEach = null; return tempSafariNFE; }()); // named arraySome instead of some because of SpiderMonkey and Blackberry bug arraySome = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var someFN = baseArray.some, nfeSome; if (isFunction(someFN)) { tempSafariNFE = function nfeSome(array, fn, thisArg) { return someFN.call(array, fn, thisArg); }; } else { tempSafariNFE = function nfeSome(array, fn, thisArg) { var object = toObjectFixIndexedAccess(array), length, index, val; if (!isFunction(fn)) { throw new TypeError(fn + ' is not a function'); } for (index = 0, length = toUint32(object.length), val = false; lt(index, length); index += 1) { if (hasProperty(object, index) && fn.call(thisArg, object[index], index, object)) { val = true; break; } } return val; }; } nfeSome = null; return tempSafariNFE; }()); // named arrayMap instead of map because of SpiderMonkey and Blackberry bug arrayMap = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var mapFN = baseArray.map, nfeMap; if (isFunction(mapFN)) { tempSafariNFE = function nfeMap(array, fn, thisArg) { return mapFN.call(array, fn, thisArg); }; } else { tempSafariNFE = function nfeMap(array, fn, thisArg) { var object = toObjectFixIndexedAccess(array), length, index, arr; if (!isFunction(fn)) { throw new TypeError(fn + ' is not a function'); } for (index = 0, length = toUint32(object.length), arr = []; lt(index, length); index += 1) { arr[index] = fn.call(thisArg, object[index], index, object); } return arr; }; } nfeMap = null; return tempSafariNFE; }()); /* function returnElement(element) { return element; } */ /* function argumentsToArray(args) { return arrayMap(args, returnElement); } */ // named arrayUnshift instead of unshift because of SpiderMonkey and Blackberry bug /* arrayUnshift = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var unshiftFN = baseArray.unshift, nfeUnshift; if (strictEqual(unshiftFN.call([], 0), 1)) { tempSafariNFE = function nfeUnshift(array) { return unshiftFN.apply(array, argumentsToArray(arguments).slice(1)); }; } else { tempSafariNFE = function nfeUnshift(array) { unshiftFN.apply(array, argumentsToArray(arguments).slice(1)); return array.length; }; } nfeUnshift = null; return tempSafariNFE; }()); */ /* // named arrayFilter instead of filter because of SpiderMonkey and Blackberry bug arrayFilter = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var filterFN = baseArray.filter, nfeFilter; if (isFunction(filterFN)) { tempSafariNFE = function nfeFilter(array, fn, thisArg) { return filterFN.call(array, fn, thisArg); }; } else { tempSafariNFE = function nfeFilter(array, fn, thisArg) { var object = toObjectFixIndexedAccess(array), length, arr, index, element; if (!isFunction(fn)) { throw new TypeError(fn + " is not a function"); } for (index = 0, length = toUint32(object.length), arr = []; lt(index, length); index += 1) { element = object[index]; if (fn.call(thisArg, element, index, object)) { arr[index] = element; } } return arr; }; } nfeFilter = null; return tempSafariNFE; }()); */ // named arrayReduce instead of reduce because of SpiderMonkey and Blackberry bug arrayReduce = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var reduceFN = baseArray.reduce, errString = 'Reduce of empty array with no initial value', nfeReduce; if (isFunction(reduceFN)) { tempSafariNFE = function nfeReduce(array, fn, initialValue) { return reduceFN.call(array, fn, initialValue); }; } else { tempSafariNFE = function nfeReduce(array, fn, initialValue) { var object = toObjectFixIndexedAccess(array), length, k, index, accumulator, kPresent; if (!isFunction(fn)) { throw new TypeError(fn + ' is not a function'); } if (isZero(length) && lt(arguments.length, 3)) { throw new TypeError(errString); } k = 0; if (gt(arguments.length, 2)) { accumulator = initialValue; } else { for (k = 0, length = toUint32(object.length), kPresent = false; !kPresent && lt(k, length); k += 1) { kPresent = hasProperty(object, k); if (kPresent) { accumulator = object[k]; } } if (!kPresent) { throw new TypeError(errString); } } for (index = k; lt(index, length); index += 1) { if (hasProperty(object, index)) { accumulator = fn.call(privateUndefined, accumulator, object[index], index, object); } } return accumulator; }; } nfeReduce = null; return tempSafariNFE; }()); // named stringTrim instead of trim because of SpiderMonkey and Blackberry bug stringTrim = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe/ var trimFN = baseString.constructor.trim, whiteSpacesList = [ 0x0009, // Tab 0x000a, // Line Feed 0x000b, // Vertical Tab 0x000c, // Form Feed 0x000d, // Carriage Return 0x0020, // Space 0x0085, // Next line 0x00a0, // No-break space 0x1680, // Ogham space mark 0x180e, // Mongolian vowel separator 0x2000, // En quad 0x2001, // Em quad 0x2002, // En space 0x2003, // Em space 0x2004, // Three-per-em space 0x2005, // Four-per-em space 0x2006, // Six-per-em space 0x2007, // Figure space 0x2008, // Punctuation space 0x2009, // Thin space 0x200a, // Hair space 0x200b, // Zero width space 0x2028, // Line separator 0x2029, // Paragraph separator 0x202f, // Narrow no-break space 0x205f, // Medium mathematical space 0x3000, // Ideographic space 0xfeff // Byte Order Mark ], testString, whiteSpacesString, wsTrimRX, nfeTrim, nfeBuildTestString, nfeBuildWhiteSpaceString; tempSafariNFE = function nfeBuildTestString(previous, element) { return previous + String.fromCharCode(element); }; testString = arrayReduce(whiteSpacesList, tempSafariNFE, ''); if (isFunction(trimFN) && isZero(trimFN.call(testString).length)) { tempSafariNFE = function nfeTrim(inputArg) { return trimFN.call(inputArg); }; } else { tempSafariNFE = function nfeBuildWhiteSpaceString(previous, element) { return previous + '\\u' + padLeadingChar(element.toString(16), '0', 4); }; whiteSpacesString = arrayReduce(whiteSpacesList, tempSafariNFE, ''); wsTrimRX = new RegExp('^[' + whiteSpacesString + ']+|[' + whiteSpacesString + ']+$', 'g'); tempSafariNFE = function nfeTrim(inputArg) { return anyToString(checkObjectCoercible(inputArg)).replace(wsTrimRX, ''); }; } nfeTrim = null; nfeBuildTestString = null; nfeBuildWhiteSpaceString = null; return tempSafariNFE; }()); // http://ecma-international.org/ecma-262/5.1/#sec-15.4.4.14 // Create our own local "indexOf" function: native -> polyfill // named arrayIndexOf instead of indexOf because of SpiderMonkey and Blackberry bug arrayIndexOf = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var indexOfFN = baseArray.indexOf, nfeIndexOf; if (isFunction(indexOfFN) && strictEqual(indexOfFN.call([0, 1], 1, 2), 1)) { tempSafariNFE = function nfeIndexOf(array, searchElement, fromIndex) { return indexOfFN.call(array, searchElement, fromIndex); }; } else { tempSafariNFE = function nfeIndexOf(array, searchElement, fromIndex) { var object = toObjectFixIndexedAccess(array), length = toUint32(object.length), index, start, val; if (isZero(length)) { val = -1; } else { if (gt(arguments.length, 2)) { fromIndex = numberToInteger(fromIndex); } else { fromIndex = 0; } if (gte(fromIndex, length)) { val = -1; } else { if (gte(fromIndex, 0)) { start = fromIndex; } else { start = length - Math.abs(fromIndex); } if (lt(start, 0)) { start = 0; } for (index = start, val = -1; lt(index, length); index += 1) { if (hasProperty(object, index) && strictEqual(searchElement, object[index])) { val = index; break; } } } } return val; }; } nfeIndexOf = null; return tempSafariNFE; }()); // named objectKeys instead of keys because of SpiderMonkey and Blackberry bug objectKeys = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var keysFN = baseObject.keys, nfeKeys; if (isFunction(keysFN)) { tempSafariNFE = keysFN; } else { tempSafariNFE = function nfeKeys(object) { if (!isTypeObject(object) && !isFunction(object)) { throw new TypeError('Object.keys called on a non-object'); } var props = [], prop; for (prop in object) { if (objectHasOwnProperty(object, prop)) { props.push(prop); } } return props; }; } nfeKeys = null; return tempSafariNFE; }()); // http://ecma-international.org/ecma-262/5.1/#sec-15.4.4.14 // Create our own local "defineProperty" function: native -> sham // named objectDefineProperty instead of defineProperty because of SpiderMonkey and Blackberry bug objectDefineProperty = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var definePropertyFN = baseObject.constructor.defineProperty, defineGetter = '__defineGetter__', defineSetter = '__defineSetter__', defineGetterFN, defineSetterFN, testObject, nfeDefineProperty; if (isFunction(definePropertyFN)) { try { testObject = definePropertyFN({}, 'sentinel', { value: null }); if (!isNull(testObject.sentinel)) { definePropertyFN = null; } } catch (exception) { definePropertyFN = null; } } if (isFunction(definePropertyFN)) { tempSafariNFE = definePropertyFN; } else { defineGetterFN = baseObject[defineGetter]; defineSetterFN = baseObject[defineSetter]; tempSafariNFE = function nfeDefineProperty(object, property, descriptor) { var prototype; if (!isTypeObject(object) && !isFunction(object)) { throw new TypeError('Object.defineProperty called on non-object'); } if (!isTypeObject(descriptor) && !isFunction(descriptor)) { throw new TypeError('Property description must be an object'); } if (objectHasOwnProperty(descriptor, 'value')) { if (isNull(objectGetPrototypeOf(baseObject)[protoName])) { prototype = object[protoName]; object[protoName] = objectGetPrototypeOf(baseObject); delete object[property]; object[property] = descriptor.value; object[protoName] = prototype; } else { object[property] = descriptor.value; } } else { if (!isFunction(defineGetterFN) || !isFunction(defineSetterFN)) { throw new TypeError('getters & setters can not be defined on this javascript engine'); } if (isFunction(descriptor.get)) { defineGetterFN.call(object, property, descriptor.get); } if (isFunction(descriptor.set)) { defineSetterFN.call(object, property, descriptor.set); } } return object; }; } nfeDefineProperty = null; return tempSafariNFE; }()); // Create our own local "defineProperties" function: native -> sham // named objectDefineProperties instead of defineProperties because of SpiderMonkey and Blackberry bug objectDefineProperties = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var definePropertiesFN = baseObject.constructor.defineProperties, nfeDefineProperties; if (isFunction(definePropertiesFN)) { tempSafariNFE = definePropertiesFN; } else { tempSafariNFE = function nfeDefineProperties(object, props) { if (!isTypeObject(object) && !isFunction(object)) { throw new TypeError('Object.defineProperties called on non-object'); } if (!isTypeObject(props) && !isFunction(props)) { throw new TypeError('Property description must be an object'); } arrayForEach(objectKeys(props), function (key) { objectDefineProperty(object, key, props[key]); }); return object; }; } nfeDefineProperties = null; return tempSafariNFE; }()); // Create our own local "getOwnPropertyDescriptor" function: native -> sham // named objectGetOwnPropertyDescriptor instead of getOwnPropertyDescriptor because of SpiderMonkey and Blackberry bug objectGetOwnPropertyDescriptor = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var getOwnPropertyDescriptorFN = baseObject.constructor.getOwnPropertyDescriptor, lookupGetter = '__lookupGetter__', lookupSetter = '__lookupSetter__', lookupGetterFN, lookupSetterFN, testObject, nfeGetOwnPropertyDescriptor; if (isFunction(getOwnPropertyDescriptorFN)) { try { testObject = { sentinel: null }; if (!isNull(getOwnPropertyDescriptorFN(testObject, 'sentinel').value)) { getOwnPropertyDescriptorFN = null; } } catch (exception) { getOwnPropertyDescriptorFN = null; } } if (isFunction(getOwnPropertyDescriptorFN)) { tempSafariNFE = getOwnPropertyDescriptorFN; } else { lookupGetterFN = baseObject[lookupGetter]; lookupSetterFN = baseObject[lookupSetter]; tempSafariNFE = function nfeGetOwnPropertyDescriptor(object, property) { var descriptor, prototype, getter, setter; if (!isTypeObject(object) && !isFunction(object)) { throw new TypeError('Object.getOwnPropertyDescriptor called on a non-object'); } if (objectHasOwnProperty(object, property)) { descriptor = { enumerable: true, configurable: true }; if (isFunction(lookupGetterFN) && isFunction(lookupSetterFN)) { prototype = object[protoName]; object[protoName] = objectGetPrototypeOf(baseObject); getter = lookupGetterFN.call(object, property); setter = lookupSetterFN.call(object, property); object[protoName] = prototype; if (isFunction(getter) || isFunction(setter)) { if (isFunction(getter)) { descriptor.get = getter; } if (isFunction(setter)) { descriptor.set = setter; } } } else { descriptor.value = object[property]; descriptor.writable = true; } } return descriptor; }; } nfeGetOwnPropertyDescriptor = null; return getOwnPropertyDescriptorFN; }()); // Create our own local "freeze" function: native -> sham // named objectFreeze instead of freeze because of SpiderMonkey and Blackberry bug objectFreeze = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var freezeFN = baseObject.constructor.freeze, nfeFreeze; if (isFunction(freezeFN)) { tempSafariNFE = freezeFN; } else { tempSafariNFE = function nfeFreeze(object) { if (!isTypeObject(object) && !isFunction(object)) { throw new TypeError('Object.freeze called on non-object'); } return object; }; } nfeFreeze = null; return tempSafariNFE; }()); // detect a Rhino bug and patch it try { objectFreeze(function () { return; }); } catch (exception) { objectFreeze = (function (freezeObject) { var nfeFreeze; tempSafariNFE = function nfeFreeze(object) { var val; if (isFunction(object)) { val = object; } else { val = freezeObject(object); } return val; }; nfeFreeze = null; return tempSafariNFE; }(objectFreeze)); } // Create our own local "isFrozen" function: native -> sham // named objectIsFrozen instead of isFrozen because of SpiderMonkey and Blackberry bug objectIsFrozen = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var isFrozenFN = baseObject.constructor.isFrozen, nfeIsFrozen; if (isFunction(isFrozenFN)) { tempSafariNFE = isFrozenFN; } else { tempSafariNFE = function nfeIsFrozen(object) { if (!isTypeObject(object) && !isFunction(object)) { throw new TypeError('Object.isFrozen called on non-object'); } return false; }; } nfeIsFrozen = null; return tempSafariNFE; }()); function deepFreeze(object) { objectFreeze(object); arrayForEach(objectKeys(object), function (propKey) { var prop = object[propKey]; if ((isTypeObject(prop) || isFunction(prop)) && !objectIsFrozen(prop)) { deepFreeze(prop); } }); } // named objectInstanceOf instead of instanceOf because of SpiderMonkey and Blackberry bug objectInstanceOf = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var isPrototypeOfFN = baseObject.constructor.prototype.isPrototypeOf, nfeInstanceOf; if (isFunction(isPrototypeOfFN)) { tempSafariNFE = function nfeInstanceOf(object, ctr) { if (!isFunction(ctr)) { throw new TypeError('Expecting a function in instanceOf check'); } return isPrototypeOfFN.call(ctr.prototype, object); }; } else if (isFunction(objectGetPrototypeOf)) { tempSafariNFE = function nfeInstanceOf(object, ctr) { if (!isFunction(ctr)) { throw new TypeError('Expecting a function in instanceOf check'); } var val = false; while (object) { if (strictEqual(object, ctr.prototype)) { val = true; break; } object = objectGetPrototypeOf(object); } return val; }; } nfeInstanceOf = null; return tempSafariNFE; }()); isPlainObject = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var baseObjectPrototype = objectGetPrototypeOf(baseObject), nfeIsPlainObject; tempSafariNFE = function nfeIsPlainObject(object) { return isObject(object) && strictEqual(objectGetPrototypeOf(object), baseObjectPrototype); }; nfeIsPlainObject = null; return tempSafariNFE; }()); extend = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var nfeExtend; tempSafariNFE = function nfeExtend(target, source) { if (!isTypeObject(target) && !isFunction(target)) { throw new TypeError('extend called on a non-object'); } arrayForEach(objectKeys(source), function (key) { objectDefineProperty(target, key, objectGetOwnPropertyDescriptor(source, key)); }); return target; }; nfeExtend = null; return tempSafariNFE; }()); function bnZero() { return new BigNumber(0); } function bnOne() { return new BigNumber(1); } objectDefineProperties(BigNumber.prototype, { trunc: { value: function () { return this.round(0, 1); } }, inRange: { value: function (min, max) { return this.gte(min) && this.lte(max); } }, modf: { value: function () { var bn = this; if (bn.isFinite()) { bn = bn.mod(bn.trunc()); } else { bn = new BigNumber(NaN); } return bn; } }, difference: { value: function (value) { var diff; if (this.gt(value)) { diff = this.minus(value); } else { diff = this.neg().plus(value); } return diff; } }, factorial: { value: (function () { var factorialLookup = {}; return function (exponentialAt) { var n, config, previousConfig, i, val; if (this.lt(0) || !this.isFinite() || !this.modf().isZero()) { val = new BigNumber(NaN); } else { if (!isNumber(exponentialAt) && !isString(exponentialAt) && (BigNumber.isBigNumber(exponentialAt) && (exponentialAt.lt(0) || !exponentialAt.isFinite()))) { exponentialAt = new BigNumber(BigNumber.config().EXPONENTIAL_AT[1]); } if (!BigNumber.isBigNumber(exponentialAt)) { exponentialAt = new BigNumber(exponentialAt); } n = this.toString(); if (!factorialLookup[n]) { config = new BigNumber.config(); previousConfig = {}; extend(previousConfig, config); BigNumber.config({ DECIMAL_PLACES: 20, ROUNDING_MODE: 4, EXPONENTIAL_AT: [-7, parseInt(exponentialAt.toString(), 10)], RANGE: [-1000000000, 1000000000], ERRORS: true }); factorialLookup[n] = bnOne(); for (i = 2; lte(i, n); i += 1) { factorialLookup[n] = factorialLookup[n].times(i); } extend(config, previousConfig); } val = factorialLookup[n]; } return val; }; }()) }, toRadians: { value: function (decimalPlacesOfPI) { return this.times(BigNumber.pi(decimalPlacesOfPI).div(180)); } }, padLeadingZero: { value: function (size) { return padLeadingChar(this.toString(), '0', size); } } }); objectDefineProperties(BigNumber, { isBigNumber: { value: function (inputArg) { return isObject(inputArg) && objectInstanceOf(inputArg, BigNumber); } }, trunc: { value: function (number) { return new BigNumber(number).trunc(); } }, modf: { value: function (number) { return new BigNumber(number).modf(); } }, difference: { value: function (number1, number2) { return new BigNumber(number1).difference(number2); } }, factorial: { value: function (number, exponentialAt) { return new BigNumber(number).factorial(exponentialAt); } }, pi: { value: (function () { var piLookup = {}; return function (decimalPlaces) { if (!numberIsFinite(decimalPlaces) || lt(decimalPlaces, 0)) { decimalPlaces = new BigNumber.config().DECIMAL_PLACES; } else { decimalPlaces = Math.floor(decimalPlaces); } var lookupProp = decimalPlaces.toString(), config, previousConfig, k = 0, sum, ta, tb, divisor, a, b; if (!piLookup[lookupProp]) { config = new BigNumber.config(); previousConfig = {}; extend(previousConfig, config); BigNumber.config({ DECIMAL_PLACES: decimalPlaces, ROUNDING_MODE: 4, EXPONENTIAL_AT: [-7, 20], RANGE: [-1000000000, 1000000000], ERRORS: true }); sum = bnZero(); a = ta = new BigNumber(16).div(5); b = tb = new BigNumber(-4).div(239); while (!a.equals(b)) { divisor = k * 2 + 1; a = ta.div(divisor); b = tb.div(divisor); sum = sum.plus(a).plus(b); ta = ta.neg().div(25); tb = tb.neg().div(57121); k += 1; } extend(config, previousConfig); piLookup[lookupProp] = sum; } return piLookup[lookupProp]; }; }()) }, toRadians: { value: function (number, decimalPlacesPI) { return new BigNumber(number).toRadians(decimalPlacesPI); } }, normaliseAngle: { value: function (angle) { var newAngle = new BigNumber(angle); while (newAngle.lt(-360)) { newAngle = newAngle.plus(360); } while (newAngle.gt(360)) { newAngle = newAngle.minus(360); } return newAngle; } }, toPositiveAngle: { value: function (angle) { var newAngle = new BigNumber.normaliseAngle(angle); if (lt(newAngle, 0)) { newAngle = newAngle.plus(360); } return newAngle; } }, sin: { value: (function () { var sineLookup = {}; return function (angle) { var newAngle = new BigNumber.normaliseAngle(angle), lookupProp = newAngle.toString(), sum, prev, k, fact, i; if (!sineLookup[lookupProp]) { sum = newAngle; prev = bnZero(); i = 1; k = 3; while (!sum.equals(prev)) { prev = sum; fact = new BigNumber.factorial(k); if (strictEqual(mod(mod(i, 2), 2), 1)) { sum = sum.minus(newAngle.pow(k).div(fact)); } else { sum = sum.plus(newAngle.pow(k).div(fact)); } i += 1; k += 2; } sineLookup[lookupProp] = sum; } return sineLookup[lookupProp]; }; }()) } }); /* function InvalidError(message) { //this.name = "InvalidError"; this.message = message || ""; } InvalidError.prototype = new Error(); function NotImplimentedError(message) { //this.name = "NotImplementedError"; this.message = message || ""; } NotImplimentedError.prototype = new Error(); */ function isDateValid(dateObject) { return isDate(dateObject) && !numberIsNaN(dateObject.getTime()); } function isGregorianLeapYear(struct) { return struct.year.mod(400).isZero() || (!struct.year.mod(100).isZero() && struct.year.mod(4).isZero()); } function isJulianLeapYear(struct) { return struct.year.mod(4).equals(0); } function daysInGregorianMonth(struct) { var days; if (struct.month.eq(2)) { days = new BigNumber(28); if (isGregorianLeapYear(struct)) { days = days.plus(1); } } else { days = struct.month.minus(1).mod(7).mod(2).neg().plus(31); } return days; } function daysInJulianMonth(struct) { var days = new BigNumber(28); if (struct.month.eq(2) && isJulianLeapYear(struct)) { days = days.plus(1); } return days; } function daysInGregorianYear(struct) { var days = new BigNumber(365); if (isGregorianLeapYear(struct)) { days = days.plus(1); } return days; } function daysInJulianYear(struct) { var days = new BigNumber(365); if (isJulianLeapYear(struct)) { days = days.plus(1); } return days; } function inYearRange(year) { return year.isFinite(); } function inMonthRange(month) { return month.inRange(1, 12); } function inDayRange(day, dim) { return day.inRange(1, dim); } function inHourRange(hour) { return hour.inRange(0, 24); } function inMinuteRange(minute, hour) { return (hour.equals(24) && minute.isZero()) || (!hour.equals(24) && minute.gte(0) && minute.lt(60)); } function inSecondRange(second, struct) { var maxSecond = 60, leapSecond; if (struct.year.gte(1961) && struct.hour.equals(23) && struct.minute.equals(59)) { if (!isPlainObject(leapSeconds)) { throw new Error('No leap second table!'); } leapSecond = leapSeconds[struct.year.toString()]; if (isPlainObject(leapSecond)) { leapSecond = leapSecond[struct.month.toString()]; if (isPlainObject(leapSecond)) { leapSecond = toNumber(leapSecond[struct.day.toString()]); if (numberIsFinite(leapSecond)) { maxSecond += leapSecond; } } } } return (struct.hour.equals(24) && second.isZero()) || (!struct.hour.equals(24) && second.gte(0) && second.lt(maxSecond)); } function inMillisecondRange(millisecond, hour) { return (hour.equals(24) && millisecond.isZero()) || (!hour.equals(24) && millisecond.gte(0) && millisecond.lt(1000)); } function inOffsetRange(offset) { return offset.inRange(-1440, 1440); } /* function inWeekRange(week, year) { return offset.inRange(1, 53); } function inWeekDayRange(weekDay) { return weekDay.inRange(1, 7); } */ function isValid(struct, julian) { var valid = false; if (isPlainObject(struct)) { valid = !arraySome(fullKeys, function (element) { var bn = struct[element.full], dim; if (!BigNumber.isBigNumber(bn)) { return true; } switch (element.full) { case 'year': if (!inYearRange(bn)) { return true; } break; case 'month': if (!inMonthRange(bn)) { return true; } break; case 'day': if (strictEqual(julian, true)) { dim = daysInJulianMonth(struct); } else { dim = daysInGregorianMonth(struct); } if (!inDayRange(bn, dim)) { return true; } break; case 'hour': if (!inHourRange(bn)) { return true; } break; case 'minute': if (!inMinuteRange(bn, struct.hour)) { return true; } break; case 'second': if (!inSecondRange(bn, struct)) { return true; } break; case 'millisecond': if (!inMillisecondRange(bn, struct.hour)) { return true; } break; case 'offset': if (!inOffsetRange(bn)) { return true; } break; /* case 'week': if (!inWeekRange(bn)) { return true; } break; case 'weekDay': if (!inWeekDayRange(bn)) { return true; } break; */ default: throw new Error(element.full); } return false; }); } return valid; } function dayOfGregorianYear(struct) { var k; if (isGregorianLeapYear(struct)) { k = 1; } else { k = 2; } return struct.month.times(275).div(9).floor().minus(struct.month.plus(9).div(12).floor().times(k)).plus(struct.day).minus(30); } function dayOfJulianYear(struct) { var doy = struct.month.times(28).plus(struct.day); if (struct.month.gte(2) && isJulianLeapYear(struct)) { doy = doy.plus(1); } return doy; } function normaliseUnits(unitString) { var unit; if (isString(unitString)) { unitString = stringTrim(unitString).toLowerCase(); if (gt(unitString.length, 2) && lastCharIs(unitString, 's')) { unitString = unitString.slice(0, -1); } arraySome(fullKeys, function (element) { var val; if (strictEqual(unitString, element.alias) || strictEqual(unitString, element.full)) { unit = element.full; val = true; } else { val = false; } return val; }); } return unit; } function timeTo(struct, unit) { var value; switch (normaliseUnits(unit)) { case 'day': value = struct.hour.div(24).plus(struct.minute.div(1440)).plus(struct.second.div(86400)).plus(struct.millisecond.div(86400000)); break; case 'hour': value = struct.hour.plus(struct.minute.div(60)).plus(struct.second.div(3600)).plus(struct.millisecond.div(3600000)); break; case 'minute': value = struct.hour.times(60).plus(struct.minute).plus(struct.second.div(60)).plus(struct.millisecond.div(60000)); break; case 'second': value = struct.hour.times(3600).plus(struct.minute.times(60)).plus(struct.second).plus(struct.millisecond.div(1000)); break; case 'millisecond': value = struct.hour.times(3600000).plus(struct.minute.times(60000)).plus(struct.second.times(1000)).plus(struct.millisecond); break; default: throw new Error(unit); } return value; } function gregorianToJd(struct) { var b = struct.year.minus(1), c = b.times(365), d = b.div(4).floor(), e = b.div(100).floor().neg(), f = b.div(400).floor(), g = struct.month.times(367).minus(362).div(12).floor(), h; if (struct.month.gt(2)) { if (isGregorianLeapYear(struct)) { h = -1; } else { h = -2; } } else { h = 0; } return new BigNumber(1721424.5).plus(c).plus(d).plus(e).plus(f).plus(g.plus(h).plus(struct.day).floor()).plus(timeTo(struct, 'day')); } /* function gregorianToJdn(struct) { return gregorianToJd(struct).trunc(); } */ function objectValues(inputArg, order) { var val; if (arrayIsArray(order)) { val = order; } else { val = objectKeys(inputArg); } return arrayMap(val, function (key) { return inputArg[key]; }); } function makeNamesMin(objectNames, order) { var arrayNames = objectValues(objectNames, order), arrayMinNames = [], count = 0, maxLength = 0, arrayNamesLength = arrayNames.length; function sliceCountCompare(element) { var characters = element.slice(0, count + 1), ret; if (arrayContains(arrayMinNames, characters)) { ret = true; } else { arrayMinNames.push(characters); ret = false; } return ret; } arrayForEach(arrayNames, function (element) { var length = element.length; if (gt(length, maxLength)) { maxLength = length; } }); while (!strictEqual(arrayMinNames.length, arrayNamesLength) && lt(count, maxLength)) { arrayMinNames.length = 0; arraySome(arrayNames, sliceCountCompare); count += 1; } return arrayMinNames; } nameTypes = ['format', 'stand-alone']; deepFreeze(nameTypes); widthTypes = ['wide', 'abbreviated', 'short', 'narrow']; widthTypeShort = widthTypes[2]; deepFreeze(widthTypes); function makeNamesArray(name, type, width, lang, order) { var val; if (!isString(type) || isEmptyString(type) || !arrayContains(nameTypes, type)) { type = arrayLast(nameTypes); } if (!isString(width) || isEmptyString(width) || !arrayContains(widthTypes, width)) { width = arrayFirst(widthTypes); } if (!isString(lang) || isEmptyString(lang) || !isPlainObject(languages[lang])) { if (!isString(defaultLanguage) || isEmptyString(defaultLanguage) || !isPlainObject(languages[defaultLanguage])) { throw new Error('Language not loaded!'); } lang = defaultLanguage; } if (strictEqual(width, widthTypeShort) && isUndefined(languages[lang].calendars.gregorian[name][type][width])) { val = makeNamesMin(languages[lang].calendars.gregorian[name][type].abbreviated, order); } else { val = objectValues(languages[lang].calendars.gregorian[name][type][width], order); } return val; } function dayOfWeekNumber(struct) { var day = gregorianToJd(struct).plus(1.5).mod(7).floor(); if (day.lt(0)) { day = day.plus(7); } return day; } function weekDayNumber(struct) { var bnWeekDay = dayOfWeekNumber(struct); if (bnWeekDay.isZero()) { bnWeekDay = new BigNumber(7); } return bnWeekDay; } function cldrDayKey(struct) { return dayKeys[toNumber(dayOfWeekNumber(struct))]; } function dayOfWeek(struct, width, lang) { var val; if (!isString(lang) || isEmptyString(lang) || !isPlainObject(languages[lang])) { if (!isString(defaultLanguage) || isEmptyString(defaultLanguage) || !isPlainObject(languages[defaultLanguage])) { throw new Error('Language not loaded!'); } lang = defaultLanguage; } if (!isString(width) || isEmptyString(width) || !arrayContains(objectKeys(languages[lang].calendars.gregorian.days[arrayFirst(nameTypes)]), width)) { width = arrayFirst(widthTypes); } if (strictEqual(width, widthTypeShort) && isUndefined(languages[lang].calendars.gregorian.days[arrayFirst(nameTypes)][width])) { val = makeNamesMin(languages[lang].calendars.gregorian.days[arrayFirst(nameTypes)].abbreviated); } else { val = languages[lang].calendars.gregorian.days[arrayFirst(nameTypes)][width]; } return val[cldrDayKey(struct)]; } function monthName(struct, width, lang) { var val; if (!isString(lang) || isEmptyString(lang) || !isPlainObject(languages[lang])) { if (!isString(defaultLanguage) || isEmptyString(defaultLanguage) || !isPlainObject(languages[defaultLanguage])) { throw new Error('Language not loaded!'); } lang = defaultLanguage; } if (!isString(width) || isEmptyString(width) || !arrayContains(objectKeys(languages[lang].calendars.gregorian.months.format), width)) { width = arrayFirst(widthTypes); } if (strictEqual(width, widthTypeShort) && isUndefined(languages[lang].calendars.gregorian.days[arrayFirst(nameTypes)][width])) { val = makeNamesMin(languages[lang].calendars.gregorian.days[arrayFirst(nameTypes)].abbreviated); } else { val = languages[lang].calendars.gregorian.days[arrayFirst(nameTypes)][width]; } return val[struct.month.toString()]; } function fractionToTime(fraction, fractionIn, struct, julian) { var time = {}, totalMs, days; fraction = new BigNumber(fraction); switch (fractionIn) { case 'year': if (strictEqual(julian, true)) { days = daysInJulianYear(struct); } else { days = daysInGregorianYear(struct); } totalMs = fraction.times(days.times(86400000)); break; case 'month': if (strictEqual(julian, true)) { days = daysInJulianMonth(struct); } else { days = daysInGregorianMonth(struct); } totalMs = fraction.times(days.times(86400000)); break; case 'day': totalMs = fraction.times(86400000); break; case 'hour': totalMs = fraction.times(3600000); break; case 'minute': totalMs = fraction.times(60000); break; case 'second': totalMs = fraction.times(1000); break; case 'millisecond': totalMs = fraction; break; default: throw new Error(fractionIn); } time.hour = totalMs.div(3600000).floor(); time.minute = totalMs.minus(time.hour.times(3600000)).div(60000).floor(); time.second = totalMs.minus(time.hour.times(3600000)).minus(time.minute.times(60000)).div(1000).floor(); time.millisecond = totalMs.minus(time.hour.times(3600000)).minus(time.minute.times(60000)).minus(time.second.times(1000)).floor(); return time; } function getTime(struct) { return gregorianToJd(struct).minus(2440587.5).times(86400000).floor(); } // DeltaT //http://eclipse.gsfc.nasa.gov/SEhelp/deltatpoly2004.html function deltaTime(struct, canonCorrection) { var y = struct.year.plus(struct.month.minus(0.5).div(12)), u, t, r; if (struct.year.inRange(-500, 2150)) { if (struct.year.lt(500)) { u = y.div(100); r = new BigNumber(10583.6).minus(u.times(1014.41)).plus(u.pow(2).times(33.78311)).minus(u.pow(3).times(5.952053)).minus(u.pow(4).times(0.1798452)).plus(u.pow(5).times(0.022174192)).plus(u.pow(6).times(0.0090316521)); } else if (struct.year.lt(1600)) { u = y.minus(1000).div(100); r = new BigNumber(1574.2).minus(u.times(556.01)).plus(u.pow(2).times(71.23472)).plus(u.pow(3).times(0.319781)).minus(u.pow(4).times(0.8503463)).minus(u.pow(5).times(0.005050998)).plus(u.pow(6).times(0.0083572073)); } else if (struct.year.lt(1700)) { t = y.minus(1600); r = new BigNumber(120).minus(t.times(0.9808)).minus(t.pow(2).times(0.01532)).plus(t.pow(3).div(7129)); } else if (struct.year.lt(1800)) { t = y.minus(1700); r = new BigNumber(8.83).plus(t.times(0.1603)).minus(t.pow(2).times(0.0059285)).plus(t.pow(3).times(0.00013336)).minus(t.pow(4).div(1174000)); } else if (struct.year.lt(1860)) { t = y.minus(1800); r = new BigNumber(13.72).minus(t.times(0.332447)).plus(t.pow(2).times(0.0068612)).plus(t.pow(3).times(0.0041116)).minus(t.pow(4).times(0.00037436)).plus(t.pow(5).times(0.0000121272)).minus(t.pow(6).times(0.0000001699)).plus(t.pow(7).times(0.000000000875)); } else if (struct.year.lt(1900)) { t = y.minus(1860); r = new BigNumber(7.62).plus(t.times(0.5737)).minus(t.pow(2).times(0.251754)).plus(t.pow(3).times(0.01680668)).minus(t.pow(4).times(0.0004473624)).plus(t.pow(5).div(233174)); } else if (struct.year.lt(1920)) { t = y.minus(1900); r = new BigNumber(-2.79).plus(t.times(1.494119)).minus(t.pow(2).times(0.0598939)).plus(t.pow(3).times(0.0061966)).minus(t.pow(4).times(0.000197)); } else if (struct.year.lt(1941)) { t = y.minus(1920); r = new BigNumber(21.20).plus(t.times(0.84493)).minus(t.pow(2).times(0.076100)).plus(t.pow(3).times(0.0020936)); } else if (struct.year.lt(1961)) { t = y.minus(1950); r = new BigNumber(29.07).plus(t.times(0.407)).minus(t.pow(2).div(233)).plus(t.pow(3).div(2547)); } else if (struct.year.lt(1986)) { t = y.minus(1975); r = new BigNumber(45.45).plus(t.times(1.067)).minus(t.pow(2).div(260)).minus(t.pow(3).div(718)); } else if (struct.year.lt(2005)) { t = y.minus(2000); r = new BigNumber(63.86).plus(t.times(0.3345)).minus(t.pow(2).times(0.060374)).plus(t.pow(3).times(0.0017275)).plus(t.pow(4).times(0.000651814)).plus(t.pow(5).times(0.00002373599)); } else if (struct.year.lt(2050)) { t = y.minus(2000); r = new BigNumber(62.92).plus(t.times(0.32217)).plus(t.pow(2).times(0.005589)); } else { r = new BigNumber(-20).plus(y.minus(1820).div(100).pow(2).times(32)).minus(y.neg().plus(2150).times(0.5628)); } } else { u = y.minus(1820).div(100); r = u.pow(2).times(32).plus(-20); } if (canonCorrection && !struct.year.inRange(1955, 2004)) { r.plus(y.minus(1955).pow(2).times(-0.000012932)); } return r.times(1000).trunc(); } function arrayToStruct(arr, julian) { var struct = {}; if (arrayIsArray(arr)) { arraySome(fullKeys, function (element, index) { var value = arr[index], bn, dim; if (isNumber(value) || isString(value) || BigNumber.isBigNumber(value)) { bn = new BigNumber(value); } else { bn = new BigNumber(NaN); } switch (element.full) { case 'year': if (!inYearRange(bn)) { struct = {}; return true; } break; case 'month': if (isUndefined(value)) { bn = bnOne(); } if (!inMonthRange(bn)) { struct = {}; return true; } break; case 'day': if (strictEqual(julian, true)) { dim = daysInJulianMonth(struct); } else { dim = daysInGregorianMonth(struct); } if (isUndefined(value)) { bn = bnOne(); } if (!inDayRange(bn, dim)) { struct = {}; return true; } break; case 'hour': if (isUndefined(value)) { bn = bnZero(); } if (!inHourRange(bn)) { struct = {}; return true; } break; case 'minute': if (isUndefined(value)) { bn = bnZero(); } if (!inMinuteRange(bn, struct.hour)) { struct = {}; return true; } break; case 'second': if (isUndefined(value)) { bn = bnZero(); } if (!inSecondRange(bn, struct)) { struct = {}; return true; } break; case 'millisecond': if (isUndefined(value)) { bn = bnZero(); } if (!inMillisecondRange(bn, struct.hour)) { struct = {}; return true; } break; case 'offset': if (isUndefined(value)) { bn = bnZero(); } if (!inOffsetRange(bn)) { struct = {}; return true; } break; default: throw new Error(element); } struct[element.full] = bn; return false; }); } return struct; } function structToArray(struct) { var arr; if (isValid(struct)) { arr = arrayMap(fullKeys, function (element) { return struct[element.full]; }); } else { arr = []; } return arr; } function returnElementToString(element) { return element.toString(); } function structToArrayOfString(struct) { return arrayMap(structToArray(struct), returnElementToString); } function objectToStruct(object, julian) { var struct = {}; if (isPlainObject(object)) { arraySome(fullKeys, function (element) { var value = object[element.alias] || object[element.full] || object[element.full + 's'], bn, dim; if (isNumber(value) || isString(value) || BigNumber.isBigNumber(value)) { bn = new BigNumber(value); } else { bn = new BigNumber(NaN); } switch (element.full) { case 'year': if (!inYearRange(bn)) { struct = {}; return true; } break; case 'month': if (isUndefined(value)) { bn = bnOne(); } if (!inMonthRange(bn)) { struct = {}; return true; } break; case 'day': if (strictEqual(julian, true)) { dim = daysInJulianMonth(struct); } else { dim = daysInGregorianMonth(struct); } if (isUndefined(value)) { bn = bnOne(); } if (!inDayRange(bn, dim)) { struct = {}; return true; } break; case 'hour': if (isUndefined(value)) { bn = bnZero(); } if (!inHourRange(bn)) { struct = {}; return true; } break; case 'minute': if (isUndefined(value)) { bn = bnZero(); } if (!inMinuteRange(bn, struct.hour)) { struct = {}; return true; } break; case 'second': if (isUndefined(value)) { bn = bnZero(); } if (!inSecondRange(bn, struct)) { struct = {}; return true; } break; case 'millisecond': if (isUndefined(value)) { bn = bnZero(); } if (!inMillisecondRange(bn, struct.hour)) { struct = {}; return true; } break; case 'offset': if (isUndefined(value)) { bn = bnZero(); } if (!inOffsetRange(bn)) { struct = {}; return true; } break; default: throw new Error(element); } struct[element.full] = bn; return false; }); } return struct; } function structToObject(struct) { var newObject = {}; if (isPlainObject(struct)) { arrayForEach(objectKeys(struct), function (key) { newObject[key] = struct[key].toString(); }); } return newObject; } function dateToStruct(date) { var struct = {}; if (isDateValid(date)) { arrayForEach(fullKeys, function (element) { var value = new BigNumber(date[element.local]()); if (strictEqual(element.full, 'month')) { value = value.plus(1); } struct[element.full] = value; }); } return struct; } function julianToJd(struct) { var year = struct.year, month, a, b, jd; month = struct.month; if (month.lte(2)) { year = year.minus(1); month = month.plus(12); } a = year.plus(4716).times(365.25).floor(); b = month.plus(1).times(30.6001).floor(); jd = a.plus(b).plus(struct.day).minus(1524.5).plus(timeTo(struct, 'day')); return jd; } /* function julianToJdn(struct) { return julianToJd(struct).trunc(); } */ function jdToGregorian(julianDay) { var struct = {}, jd = new BigNumber(julianDay), a, b; if (jd.isFinite()) { jd = jd.plus(0.5); a = jd.plus(68569).floor(); b = a.times(4).div(146097).floor(); a = a.minus(b.times(146097).plus(3).div(4).floor()); struct.year = a.plus(1).times(4000).div(1461001).floor(); a = a.minus(struct.year.times(1461).div(4).floor()).plus(31); struct.month = a.times(80).div(2447).floor(); struct.day = a.minus(struct.month.times(2447).div(80).floor()); a = struct.month.div(11).floor(); struct.month = struct.month.plus(2).minus(a.times(12)); struct.year = b.minus(49).times(100).plus(struct.year).plus(a).floor(); struct.offset = bnZero(); extend(struct, fractionToTime(jd.modf().abs(), 'day')); } return struct; } function jdToJulian(julianDay) { var struct = {}, jd = new BigNumber(julianDay), a, b, c, d, e, g; if (jd.isFinite()) { jd = jd.plus(0.5); a = jd.floor(); b = a.plus(1524); c = b.minus(122.1).div(365.25).floor(); d = c.times(365.25).floor(); g = b.minus(d); e = g.div(30.6001).floor(); struct.day = g.minus(e.times(30.6001).floor()); if (e.lt(14)) { struct.month = e.minus(1); } else { struct.month = e.minus(13); } if (struct.month.gt(2)) { struct.year = c.minus(4716); } else { struct.year = c.minus(4715); } struct.offset = bnZero(); extend(struct, fractionToTime(jd.modf().abs(), 'day')); } return struct; } function gregorianToMJD(struct) { return gregorianToJd(struct).minus(2400000.5); } function julianToMJD(struct) { return julianToJd(struct).minus(2400000.5); } function jdToMJD(jd) { return jd.minus(2400000.5); } function gregorianToJulian(struct) { var newStruct; if (isValid(struct)) { newStruct = jdToJulian(gregorianToJd(struct)); } else { newStruct = {}; } return newStruct; } function julianToGregorian(struct) { var newStruct; if (isValid(struct)) { newStruct = jdToGregorian(julianToJd(struct)); } else { newStruct = {}; } return newStruct; } function gregorianEaster(struct) { var a = struct.year.mod(19), b = struct.year.div(100).floor(), c = struct.year.mod(100).floor(), d = b.div(4), e = b.mod(4), f = b.plus(8).div(25).floor(), g = b.minus(f).plus(1).div(3).floor(), h = new BigNumber(19).times(a).plus(b).minus(d).minus(g).plus(15).mod(30), i = c.div(4).floor(), k = c.mod(4), l = new BigNumber(32).plus(e.times(2)).plus(i.times(2)).minus(h).minus(k).mod(7), m = a.plus(h.times(11)).plus(l.times(22)).div(451).floor(), n = h.plus(l).minus(m.times(7)).plus(114); return new AstroDate([struct.year, n.div(31).floor(), n.mod(31).plus(1)]); } function julianEaster(struct) { var a = struct.year.mod(4), b = struct.year.mod(7), c = struct.year.mod(19), d = c.times(19).plus(15).mod(30), e = a.times(2).plus(b.times(4)).minus(d).plus(34).mod(7), f = d.plus(e).plus(114); return new AstroDate([struct.year, f.div(31).floor().minus(1), f.mod(31).plus(1)]); } function toUT(struct) { return jdToGregorian(gregorianToJd(struct).times(86400000).plus(struct.offset.times(60000)).div(86400000)); } function toTT(struct) { var offset = struct.offset, structTT = jdToGregorian(gregorianToJd(struct).times(86400000).minus(deltaTime(struct)).div(86400000)); structTT.offset = offset; return structTT; } function bnGetTimezoneOffset() { return new BigNumber(new Date().getTimezoneOffset()); } function toLocal(struct) { var timezoneOffset = bnGetTimezoneOffset(), structLocal = jdToGregorian(gregorianToJd(struct).times(86400000).plus(struct.offset.times(60000)).minus(bnGetTimezoneOffset().times(60000)).div(86400000)); structLocal.offset = timezoneOffset; return structLocal; } /* function toTAI(struct) { var offset = struct.offset, structTT = jdToGregorian(gregorianToJd(struct).times(86400000).minus(deltaTime(struct)).minus(32184).div(86400000)); structTT.offset = offset; return structTT; } function toGPS(struct) { var offset = struct.offset, structTT = jdToGregorian(gregorianToJd(struct).times(86400000).minus(deltaTime(struct)).minus(51184).div(86400000)); structTT.offset = offset; return structTT; } */ function toISOString(struct, userPadding) { var string, index, count, padding, last, value, key, number; number = toNumber(userPadding); if (lt(number, 5) || !numberIsFinite(number)) { number = 6; } index = 0; string = ''; for (count = 0; lt(count, 3); count += 1) { if (isUndefined(struct[fullKeys[count].full])) { index = 3; break; } } for (last = fullKeys.length - 1; lt(index, last); index += 1) { key = fullKeys[index].full; value = struct[key]; if (strictEqual(key, 'year')) { if (value.lt(0)) { string += '-'; padding = number; } else if (value.gte(10000)) { string += '+'; padding = number; } else { padding = 4; } } else if (strictEqual(key, 'hour')) { string += 'T'; padding = 2; } else if (strictEqual(key, 'millisecond')) { padding = 3; } else { padding = 2; } string += value.abs().padLeadingZero(padding); if (lt(index, 2)) { string += '-'; } else if (inRange(index, 3, 4)) { string += ':'; } else if (strictEqual(key, 'second')) { string += '.'; } } value = struct.offset; if (value.isZero()) { string += 'Z'; } else { if (value.lte(0)) { string += '+'; } else { string += '-'; } value = fractionToTime(value.abs(), 'minute'); string += value.hour.padLeadingZero(2); string += ':'; string += value.minute.padLeadingZero(2); } return string; } function isoHasValidCharacterCounts(string) { var val; if (!inRange(countCharacter(string, ' ') + countCharacter(string, 'T'), 0, 1)) { val = false; } else if (!inRange(countCharacter(string, 'W'), 0, 1)) { val = false; } else if (!inRange(countCharacter(string, 'Z'), 0, 1)) { val = false; } else if (!inRange(countCharacter(string, '.') + countCharacter(string, ','), 0, 1)) { val = false; } else if (!inRange(countCharacter(string, '+'), 0, 2)) { val = false; } else if (!inRange(countCharacter(string, '-'), 0, 4)) { val = false; } else if (!inRange(countCharacter(string, ':'), 0, 4)) { val = false; } else if (lt(string.replace(/\D/g, '').length, 2)) { val = false; } else { val = true; } return val; } function ordinalToCalendar(year, dayOfYear) { var struct = { year: new BigNumber(year), month: bnOne(), day: bnOne(), hour: bnZero(), minute: bnZero(), second: bnZero(), millisecond: bnZero() }, daysInYear = daysInGregorianYear(struct), result; dayOfYear = new BigNumber(dayOfYear); if (dayOfYear.inRange(1, daysInYear)) { struct = jdToGregorian(gregorianToJd(struct).plus(dayOfYear).minus(1)); result = { sign: 1, year: struct.year, month: struct.month, day: struct.day }; } return result; } function weekDateToCalendar(year, week, weekDay) { var struct = { year: new BigNumber(year), month: bnOne(), day: new BigNumber(4), hour: bnZero(), minute: bnZero(), second: bnZero(), millisecond: bnZero() }, weekDayJan4 = weekDayNumber(struct), dayOfYear; dayOfYear = new BigNumber(7).times(week).plus(weekDay).minus(weekDayJan4.plus(3)); if (dayOfYear.lt(1)) { struct.year = struct.year.minus(1); dayOfYear = daysInGregorianYear(struct).plus(dayOfYear); } else if (dayOfYear.gt(daysInGregorianYear(struct))) { struct.year = struct.year.plus(1); dayOfYear = dayOfYear.minus(daysInGregorianYear(struct)); } return ordinalToCalendar(struct.year, dayOfYear); } function calendarToWeekDate(struct) { var weekDay = weekDayNumber(struct), year = struct.year, month = struct.month, nearestThursday, val; nearestThursday = struct.day.plus(4).minus(weekDay); if (struct.month.equals(12) && nearestThursday.gt(31)) { val = { year: year.plus(1), week: bnOne(), weekDay: weekDay }; } else { if (struct.month.equals(1) && nearestThursday.lt(1)) { year = struct.year.minus(1); month = 12; nearestThursday = nearestThursday.plus(31); } val = { year: year, week: dayOfGregorianYear({year: year, month: month, day: nearestThursday}).div(7).floor().plus(1), weekDay: weekDay }; } return val; } function isNotNegativeZero(bn, sign) { return strictEqual(sign, '+') || !bn.isZero() || (bn.isZero() && !strictEqual(sign, '-')); } function hourMinuteToMinutes(minute, second) { return new BigNumber(minute).times(60).plus(second); } function hourFractionToTime(number) { return fractionToTime('0.' + number, 'hour'); } function minuteFractionToTime(number) { return fractionToTime('0.' + number, 'minute'); } function secondFractionToTime(number) { return fractionToTime('0.' + number, 'second'); } function toSignMultipler(sign) { return sign + '1'; } datePatterns = { basic: [{ regex: /^(\d{2})$/, func: function (rxResult) { return { year: new BigNumber(rxResult[1] + '00'), month: bnOne(), day: bnOne() }; } }, { regex: /^(\d{4})$/, func: function (rxResult) { return { year: new BigNumber(rxResult[1]), month: bnOne(), day: bnOne() }; } }, { regex: /^(\d{4})(\d{2})(\d{2})$/, func: function (rxResult) { return { year: new BigNumber(rxResult[1]), month: new BigNumber(rxResult[2]), day: new BigNumber(rxResult[3]) }; } }, { regex: /^(\d{4})(\d{3})$/, func: function (rxResult) { return ordinalToCalendar(rxResult[1], rxResult[2]); } }, { regex: /^(\d{4})W(\d{2})$/, func: function (rxResult) { return weekDateToCalendar(rxResult[1], rxResult[2], 1); } }, { regex: /^(\d{4})W(\d{2})([1-7]{1})$/, func: function (rxResult) { return weekDateToCalendar(rxResult[1], rxResult[2], rxResult[3]); } }], extended: [{ // need to add tests for -0 regex: /^([\-+]{1})(\d{5,})-(\d{2})$/, func: function (rxResult) { return { year: new BigNumber(rxResult[2]).times(toSignMultipler(rxResult[1])), month: new BigNumber(rxResult[3]), day: bnOne() }; } }, { regex: /^(\d{4})-(\d{2})$/, func: function (rxResult) { return { year: new BigNumber(rxResult[1]), month: new BigNumber(rxResult[2]), day: bnOne() }; } }, { regex: /^(\d{4})-(\d{2})-(\d{2})$/, func: function (rxResult) { return { year: new BigNumber(rxResult[1]), month: new BigNumber(rxResult[2]), day: new BigNumber(rxResult[3]) }; } }, { regex: /^([\-+]{1})(\d{5,})-(\d{2})-(\d{2})$/, func: function (rxResult) { return { year: new BigNumber(rxResult[2]).times(toSignMultipler(rxResult[1])), month: new BigNumber(rxResult[3]), day: new BigNumber(rxResult[4]) }; } }, { regex: /^(\d{4})-(\d{3})$/, func: function (rxResult) { return ordinalToCalendar(rxResult[1], rxResult[2]); } }, { regex: /^(\d{4})-W(\d{2})$/, func: function (rxResult) { return weekDateToCalendar(rxResult[1], rxResult[2], 1); } }, { regex: /^(\d{4})-W(\d{2})-([1-7]{1})$/, func: function (rxResult) { return weekDateToCalendar(rxResult[1], rxResult[2], rxResult[3]); } }, { regex: /^([\-+]{1})(\d{5,})-(\d{3})$/, func: function (rxResult) { return ordinalToCalendar(new BigNumber(rxResult[2]).times(toSignMultipler(rxResult[1])), rxResult[3]); } }, { regex: /^([\-+]{1})(\d{5,})-W(\d{2})$/, func: function (rxResult) { return weekDateToCalendar(new BigNumber(rxResult[2]).times(toSignMultipler(rxResult[1])), rxResult[3], 1); } }, { regex: /^([\-+]{1})(\d{5,})-W(\d{2})-([1-7]{1})$/, func: function (rxResult) { return weekDateToCalendar(new BigNumber(rxResult[2]).times(toSignMultipler(rxResult[1])), rxResult[3], rxResult[4]); } }] }; deepFreeze(datePatterns); timePatterns = { basic: [{ regex: /^(\d{2})$/, func: function (rxResult) { return { hour: new BigNumber(rxResult[1]), minute: bnZero(), second: bnZero(), millisecond: bnZero(), offset: bnGetTimezoneOffset() }; } }, { regex: /^(\d{2})(\d{2})$/, func: function (rxResult) { return { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: bnZero(), millisecond: bnZero(), offset: bnGetTimezoneOffset() }; } }, { regex: /^(\d{2})(\d{2})(\d{2})$/, func: function (rxResult) { return { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: new BigNumber(rxResult[3]), millisecond: bnZero(), offset: bnGetTimezoneOffset() }; } }, { regex: /^(\d{2})Z$/, func: function (rxResult) { return { hour: new BigNumber(rxResult[1]), minute: bnZero(), second: bnZero(), millisecond: bnZero(), offset: bnZero() }; } }, { regex: /^(\d{2})(\d{2})Z$/, func: function (rxResult) { return { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: bnZero(), millisecond: bnZero(), offset: bnZero() }; } }, { regex: /^(\d{2})(\d{2})(\d{2})Z$/, func: function (rxResult) { return { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: new BigNumber(rxResult[3]), millisecond: bnZero(), offset: bnZero() }; } }, { regex: /^(\d{2})([\-+]{1})(\d{2})$/, func: function (rxResult) { var sign = rxResult[2], offset = hourMinuteToMinutes(rxResult[3], 0), val; if (isNotNegativeZero(offset, sign)) { val = { hour: new BigNumber(rxResult[1]), minute: bnZero(), second: bnZero(), millisecond: bnZero(), offset: offset.times(toSignMultipler(sign)).neg() }; } return val; } }, { regex: /^(\d{2})(\d{2})([\-+]{1})(\d{2})$/, func: function (rxResult) { var sign = rxResult[3], offset = hourMinuteToMinutes(rxResult[4], 0), val; if (isNotNegativeZero(offset, sign)) { val = { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: bnZero(), millisecond: bnZero(), offset: offset.times(toSignMultipler(sign)).neg() }; } return val; } }, { regex: /^(\d{2})(\d{2})(\d{2})([\-+]{1})(\d{2})$/, func: function (rxResult) { var sign = rxResult[4], offset = hourMinuteToMinutes(rxResult[5], 0), val; if (isNotNegativeZero(offset, sign)) { val = { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: new BigNumber(rxResult[3]), millisecond: bnZero(), offset: offset.times(toSignMultipler(sign)).neg() }; } return val; } }, { regex: /^(\d{2})([\-+]{1})(\d{2})(\d{2})$/, func: function (rxResult) { var sign = rxResult[2], offset = hourMinuteToMinutes(rxResult[3], rxResult[4]), val; if (isNotNegativeZero(offset, sign)) { val = { hour: new BigNumber(rxResult[1]), minute: bnZero(), second: bnZero(), millisecond: bnZero(), offset: offset.times(toSignMultipler(sign)).neg() }; } return val; } }, { regex: /^(\d{2})(\d{2})([\-+]{1})(\d{2})(\d{2})$/, func: function (rxResult) { var sign = rxResult[3], offset = hourMinuteToMinutes(rxResult[4], rxResult[5]), val; if (isNotNegativeZero(offset, sign)) { val = { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: bnZero(), millisecond: bnZero(), offset: offset.times(toSignMultipler(sign)).neg() }; } return val; } }, { regex: /^(\d{2})(\d{2})(\d{2})([\-+]{1})(\d{2})(\d{2})$/, func: function (rxResult) { var sign = rxResult[4], offset = hourMinuteToMinutes(rxResult[5], rxResult[6]), val; if (isNotNegativeZero(offset, sign)) { val = { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: new BigNumber(rxResult[3]), millisecond: bnZero(), offset: offset.times(toSignMultipler(sign)).neg() }; } return val; } }, { regex: /^(\d{2})[\.,]{1}(\d{1,})$/, func: function (rxResult) { var val = hourFractionToTime(rxResult[2]); val.hour = new BigNumber(rxResult[1]); val.offset = bnGetTimezoneOffset(); return val; } }, { regex: /^(\d{2})(\d{2})[\.,]{1}(\d{1,})$/, func: function (rxResult) { var val = minuteFractionToTime(rxResult[3]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.offset = bnGetTimezoneOffset(); return val; } }, { regex: /^(\d{2})(\d{2})(\d{2})[\.,]{1}(\d{1,})$/, func: function (rxResult) { var val = secondFractionToTime(rxResult[4]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.second = new BigNumber(rxResult[3]); val.offset = bnGetTimezoneOffset(); return val; } }, { regex: /^(\d{2})[\.,]{1}(\d{1,})Z$/, func: function (rxResult) { var val = hourFractionToTime(rxResult[2]); val.hour = new BigNumber(rxResult[1]); val.offset = bnZero(); return val; } }, { regex: /^(\d{2})(\d{2})[\.,]{1}(\d{1,})Z$/, func: function (rxResult) { var val = minuteFractionToTime(rxResult[3]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[1]); val.offset = bnZero(); return val; } }, { regex: /^(\d{2})(\d{2})(\d{2})[\.,]{1}(\d{1,})Z$/, func: function (rxResult) { var val = secondFractionToTime(rxResult[4]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.second = new BigNumber(rxResult[3]); val.offset = bnZero(); return val; } }, { regex: /^(\d{2})[\.,]{1}(\d{1,})([\-+]{1})(\d{2})$/, func: function (rxResult) { var sign = rxResult[3], offset = hourMinuteToMinutes(rxResult[4], 0), val; if (isNotNegativeZero(offset, sign)) { val = hourFractionToTime(rxResult[2]); val.hour = new BigNumber(rxResult[1]); val.offset = offset.times(toSignMultipler(sign)).neg(); } return val; } }, { regex: /^(\d{2})(\d{2})[\.,]{1}(\d{1,})([\-+]{1})(\d{2})$/, func: function (rxResult) { var sign = rxResult[4], offset = hourMinuteToMinutes(rxResult[5], 0), val; if (isNotNegativeZero(offset, sign)) { val = minuteFractionToTime(rxResult[3]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.offset = offset.times(toSignMultipler(sign)).neg(); } return val; } }, { regex: /^(\d{2})(\d{2})(\d{2})[\.,]{1}(\d{1,})([\-+]{1})(\d{2})$/, func: function (rxResult) { var sign = rxResult[5], offset = hourMinuteToMinutes(rxResult[6], 0), val; if (isNotNegativeZero(offset, sign)) { val = secondFractionToTime(rxResult[4]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.minute = new BigNumber(rxResult[3]); val.offset = offset.times(toSignMultipler(sign)).neg(); } return val; } }, { regex: /^(\d{2})[\.,]{1}(\d{1,})([\-+]{1})(\d{2})(\d{2})$/, func: function (rxResult) { var sign = rxResult[3], offset = hourMinuteToMinutes(rxResult[4], rxResult[5]), val; if (isNotNegativeZero(offset, sign)) { val = hourFractionToTime(rxResult[2]); val.hour = new BigNumber(rxResult[1]); val.offset = offset.times(toSignMultipler(sign)).neg(); } return val; } }, { regex: /^(\d{2})(\d{2})[\.,]{1}(\d{1,})([\-+]{1})(\d{2})(\d{2})$/, func: function (rxResult) { var sign = rxResult[4], offset = hourMinuteToMinutes(rxResult[5], rxResult[6]), val; if (isNotNegativeZero(offset, sign)) { val = minuteFractionToTime(rxResult[3]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.offset = offset.times(toSignMultipler(sign)).neg(); } return val; } }, { regex: /^(\d{2})(\d{2})(\d{2})[\.,]{1}(\d{1,})([\-+]{1})(\d{2})(\d{2})$/, func: function (rxResult) { var sign = rxResult[5], offset = hourMinuteToMinutes(rxResult[6], rxResult[7]), val; if (isNotNegativeZero(offset, sign)) { val = secondFractionToTime(rxResult[4]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.minute = new BigNumber(rxResult[3]); val.offset = offset.times(toSignMultipler(sign)).neg(); } return val; } }], extended: [{ regex: /^(\d{2})$/, func: function (rxResult) { return { hour: new BigNumber(rxResult[1]), minute: bnZero(), second: bnZero(), millisecond: bnZero(), offset: bnGetTimezoneOffset() }; } }, { regex: /^(\d{2}):(\d{2})$/, func: function (rxResult) { return { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: bnZero(), millisecond: bnZero(), offset: bnGetTimezoneOffset() }; } }, { regex: /^(\d{2}):(\d{2}):(\d{2})$/, func: function (rxResult) { return { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: new BigNumber(rxResult[3]), millisecond: bnZero(), offset: bnGetTimezoneOffset() }; } }, { regex: /^(\d{2})Z$/, func: function (rxResult) { return { hour: new BigNumber(rxResult[1]), minute: bnZero(), second: bnZero(), millisecond: bnZero(), offset: bnZero() }; } }, { regex: /^(\d{2}):(\d{2})Z$/, func: function (rxResult) { return { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: bnZero(), millisecond: bnZero(), offset: bnZero() }; } }, { regex: /^(\d{2}):(\d{2}):(\d{2})Z$/, func: function (rxResult) { return { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: new BigNumber(rxResult[3]), millisecond: bnZero(), offset: bnZero() }; } }, { regex: /^(\d{2}):([\-+]{1})(\d{2})$/, func: function (rxResult) { var sign = rxResult[2], offset = hourMinuteToMinutes(rxResult[3], 0), val; if (isNotNegativeZero(offset, sign)) { val = { hour: new BigNumber(rxResult[1]), minute: bnZero(), second: bnZero(), millisecond: bnZero(), offset: offset.times(toSignMultipler(sign)).neg() }; } return val; } }, { regex: /^(\d{2}):(\d{2})([\-+]{1})(\d{2})$/, func: function (rxResult) { var sign = rxResult[3], offset = hourMinuteToMinutes(rxResult[4], 0), val; if (isNotNegativeZero(offset, sign)) { val = { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: bnZero(), millisecond: bnZero(), offset: offset.times(toSignMultipler(sign)).neg() }; } return val; } }, { regex: /^(\d{2}):(\d{2}):(\d{2})([\-+]{1})(\d{2})$/, func: function (rxResult) { var sign = rxResult[4], offset = hourMinuteToMinutes(rxResult[5], 0), val; if (isNotNegativeZero(offset, sign)) { val = { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: new BigNumber(rxResult[3]), millisecond: bnZero(), offset: offset.times(toSignMultipler(sign)).neg() }; } return val; } }, { regex: /^(\d{2})([\-+]{1})(\d{2}):(\d{2})$/, func: function (rxResult) { var sign = rxResult[2], offset = hourMinuteToMinutes(rxResult[3], rxResult[4]), val; if (isNotNegativeZero(offset, sign)) { val = { hour: new BigNumber(rxResult[1]), minute: bnZero(), second: bnZero(), millisecond: bnZero(), offset: offset.times(toSignMultipler(sign)).neg() }; } return val; } }, { regex: /^(\d{2}):(\d{2})([\-+]{1})(\d{2}):(\d{2})$/, func: function (rxResult) { var sign = rxResult[3], offset = hourMinuteToMinutes(rxResult[4], rxResult[5]), val; if (isNotNegativeZero(offset, sign)) { val = { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: bnZero(), millisecond: bnZero(), offset: offset.times(toSignMultipler(sign)).neg() }; } return val; } }, { regex: /^(\d{2}):(\d{2}):(\d{2})([\-+]{1})(\d{2}):(\d{2})$/, func: function (rxResult) { var sign = rxResult[4], offset = hourMinuteToMinutes(rxResult[5], rxResult[6]), val; if (isNotNegativeZero(offset, sign)) { val = { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: new BigNumber(rxResult[3]), millisecond: bnZero(), offset: offset.times(toSignMultipler(sign)).neg() }; } return val; } }, { regex: /^(\d{2})[\.,]{1}(\d{1,})$/, func: function (rxResult) { var val = hourFractionToTime(rxResult[2]); val.hour = new BigNumber(rxResult[1]); val.offset = bnGetTimezoneOffset(); return val; } }, { regex: /^(\d{2}):(\d{2})[\.,]{1}(\d{1,})$/, func: function (rxResult) { var val = minuteFractionToTime(rxResult[3]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.offset = bnGetTimezoneOffset(); return val; } }, { regex: /^(\d{2}):(\d{2}):(\d{2})[\.,]{1}(\d{1,})$/, func: function (rxResult) { var val = secondFractionToTime(rxResult[4]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.second = new BigNumber(rxResult[3]); val.offset = bnGetTimezoneOffset(); return val; } }, { regex: /^(\d{2})[\.,]{1}(\d{1,})Z$/, func: function (rxResult) { var val = hourFractionToTime(rxResult[2]); val.hour = new BigNumber(rxResult[1]); val.offset = bnZero(); return val; } }, { regex: /^(\d{2}):(\d{2})[\.,]{1}(\d{1,})Z$/, func: function (rxResult) { var val = minuteFractionToTime(rxResult[3]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[1]); val.offset = bnZero(); return val; } }, { regex: /^(\d{2}):(\d{2}):(\d{2})[\.,]{1}(\d{1,})Z$/, func: function (rxResult) { var val = secondFractionToTime(rxResult[4]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.second = new BigNumber(rxResult[3]); val.offset = bnZero(); return val; } }, { regex: /^(\d{2})[\.,]{1}(\d{1,})([\-+]{1})(\d{2})$/, func: function (rxResult) { var sign = rxResult[3], offset = hourMinuteToMinutes(rxResult[4], 0), val; if (isNotNegativeZero(offset, sign)) { val = hourFractionToTime(rxResult[2]); val.hour = new BigNumber(rxResult[1]); val.offset = offset.times(toSignMultipler(sign)).neg(); } return val; } }, { regex: /^(\d{2}):(\d{2})[\.,]{1}(\d{1,})([\-+]{1})(\d{2})$/, func: function (rxResult) { var sign = rxResult[4], offset = hourMinuteToMinutes(rxResult[5], 0), val; if (isNotNegativeZero(offset, sign)) { val = minuteFractionToTime(rxResult[3]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.offset = offset.times(toSignMultipler(sign)).neg(); } return val; } }, { regex: /^(\d{2}):(\d{2}):(\d{2})[\.,]{1}(\d{1,})([\-+]{1})(\d{2})$/, func: function (rxResult) { var sign = rxResult[5], offset = hourMinuteToMinutes(rxResult[6], 0), val; if (isNotNegativeZero(offset, sign)) { val = secondFractionToTime(rxResult[4]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.second = new BigNumber(rxResult[3]); val.offset = offset.times(toSignMultipler(sign)).neg(); } return val; } }, { regex: /^(\d{2})[\.,]{1}(\d{1,})([\-+]{1})(\d{2}):(\d{2})$/, func: function (rxResult) { var sign = rxResult[3], offset = hourMinuteToMinutes(rxResult[4], rxResult[5]), val; if (isNotNegativeZero(offset, sign)) { val = hourFractionToTime(rxResult[2]); val.hour = new BigNumber(rxResult[1]); val.offset = offset.times(toSignMultipler(sign)).neg(); } return val; } }, { regex: /^(\d{2}):(\d{2})[\.,]{1}(\d{1,})([\-+]{1})(\d{2}):(\d{2})$/, func: function (rxResult) { var sign = rxResult[4], offset = hourMinuteToMinutes(rxResult[5], rxResult[6]), val; if (isNotNegativeZero(offset, sign)) { val = minuteFractionToTime(rxResult[3]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.offset = offset.times(toSignMultipler(sign)).neg(); } return val; } }, { regex: /^(\d{2}):(\d{2}):(\d{2})[\.,]{1}(\d{1,})([\-+]{1})(\d{2}):(\d{2})$/, func: function (rxResult) { var sign = rxResult[5], offset = hourMinuteToMinutes(rxResult[6], rxResult[7]), val; if (isNotNegativeZero(offset, sign)) { val = secondFractionToTime(rxResult[4]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.second = new BigNumber(rxResult[3]); val.offset = offset.times(toSignMultipler(sign)).neg(); } return val; } }] }; deepFreeze(timePatterns); function isoSplitDateTime(string) { var dtObject = { date: '', time: '' }, firstSplit = stringSplit(stringTrim(string), /[T ]/), splitLength = firstSplit.length, element; if (inRange(splitLength, 1, 2)) { if (strictEqual(splitLength, 1)) { element = arrayFirst(firstSplit); // we make a best guess if (strictEqual(element.slice(-4), '-') || firstCharIs(element, '+') || firstCharIs(element, '-') || strictEqual(element.length, 2) || gte(countCharacter(element, '-'), 2) || stringContains(element, 'W')) { // only ordinal dates have a "-" at -4 // only dates begin with "+" or "-" // dates and times can be only 2 digits but will default to date unless preceeded with " " or "T" // only dates have 2 or more "-" // only dates have a week number "W" dtObject.date = element; dtObject.time = '00'; } else if (lastCharIs(element, 'Z') || stringContains(element, ':') || stringContains(element, '.') || stringContains(element, ',') || stringContains(element, '+') || strictEqual(element.slice(-3), '-')) { // only times end with a "Z" // only times contain a ":" or a "." or a "," // only times contain a "+" that is not at the beginning // only times have a "-" at -3 dtObject.date = '00'; dtObject.time = element; } else { // otherwise we guess it is a date dtObject.date = element; dtObject.time = '00'; } } else { dtObject.date = arrayFirst(firstSplit) || '00'; dtObject.time = arrayLast(firstSplit); } } return dtObject; } function isoParse(isoString) { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var dtObject = { input: isoString }, nfeSearchPatterns, searchString; if (isString(isoString) && !isEmptyString(isoString) && !invalidISOCharsRx.test(isoString) && isoHasValidCharacterCounts(isoString)) { tempSafariNFE = function nfeSearchPatterns(pattern) { var rxResult = pattern.regex.exec(searchString), val = false, result; if (!isNull(rxResult)) { result = pattern.func(rxResult); if (!isUndefined(result)) { extend(dtObject, result); } val = true; } return val; }; extend(dtObject, isoSplitDateTime(isoString)); searchString = dtObject.date; if (!arraySome(datePatterns.basic, tempSafariNFE)) { if (arraySome(datePatterns.extended, tempSafariNFE)) { searchString = dtObject.time; arraySome(timePatterns.extended, tempSafariNFE); } } else { searchString = dtObject.time; arraySome(timePatterns.basic, tempSafariNFE); } } nfeSearchPatterns = null; return dtObject; } function getCorrectStruct(thisAstroDate, struct) { if (thisAstroDate.isTT()) { struct = toTT(struct); } if (thisAstroDate.isUT()) { struct = toUT(struct); } else if (thisAstroDate.isLocal()) { struct = toLocal(struct); } return struct; } function cldrPadLeadingZero(strNum, size) { var firsrCharacter, val; if (isString(strNum) && !isEmptyString(strNum)) { if ((/^\d+$/).test(strNum) && new BigNumber(strNum).isFinite()) { firsrCharacter = firstChar(strNum); val = ''; if (strictEqual(firsrCharacter, '-')) { strNum = strNum.slice(1); size -= 1; val = firsrCharacter; } val += padLeadingChar(strNum, '0', size); } else { val = strNum; } } return val; } function escapeRegex(string) { return string.replace(/[\[\](){}?*+\^$\\.|]/g, '\\$&'); } function wrapInChar(string, character) { return character + string + character; } function replaceToken(pattern, token, value) { if (!isString(token) || isEmptyString(token)) { throw new Error(); } var firstCharacter, count, copyMatch; if ((/^([|]?\S{1}\{\d+,{1}\d*\})+$/).test(token)) { copyMatch = token; } else if ((/^\{\d{1}\}$/).test(token)) { token = escapeRegex(token); copyMatch = token; } else { firstCharacter = firstChar(token); count = token.length; if (!strictEqual(count, countCharacter(token, firstCharacter))) { throw new Error(token); } copyMatch = token + '(?!' + firstCharacter + ')'; } function replacer($0) { return $0.replace(new RegExp(token, 'g'), wrapInChar(cldrPadLeadingZero(value, $0.length), '\'')); } function tokenReplacer($0, $1, $2) { var val; if ($0) { if ($1) { val = $1.replace(new RegExp(copyMatch, 'g'), replacer); } else { val = $2; } } return val; } return pattern.replace(replaceTokenRX, tokenReplacer); } function strip(string, pattern) { return string.replace(new RegExp(escapeRegex(pattern), 'g'), ''); } function stripSingleQuotes(string) { return strip(string, '\''); } formatTypes = ['full', 'long', 'medium', 'short']; deepFreeze(formatTypes); calendarTypes = { julian: { abbreviated: 'OS', wide: 'Julian', narrow: 'O' }, gregorian: { abbreviated: 'NS', wide: 'Gregorian', narrow: 'N' } }; deepFreeze(calendarTypes); function formatDate(struct, pattern, julian, lang) { if (!isString(pattern) || isEmptyString(pattern)) { pattern = arrayFirst(formatTypes); } if (!isString(lang) || isEmptyString(lang) || !isPlainObject(languages[lang])) { if (!isString(defaultLanguage) || isEmptyString(defaultLanguage) || !isPlainObject(languages[defaultLanguage])) { throw new Error('Language not loaded!'); } lang = defaultLanguage; } var gregorian = languages[lang].calendars.gregorian, dateFormats = gregorian.dateFormats, eras = gregorian.eras, months = gregorian.months, days = gregorian.days, eraNum, year, sign, month, doy, day, temp, weekDate, week, mjd; if (arrayContains(formatTypes, pattern)) { /* switch (pattern) { case 'long': calendarPattern = '\'(\'CCCC\')\''; break; case 'medium': calendarPattern = '\'(\'C\')\''; break; case 'short': calendarPattern = '\'(\'CCCCCC\')\''; break; default: calendarPattern = '\'(\'CCCC\')\''; } */ pattern = dateFormats[pattern]; } /* if (julian) { calendarType = 'julian'; } else { calendarType = 'gregorian'; } */ /* pattern = replaceToken(pattern, 'CCCCC', calendarTypes[calendarType].narrow); pattern = replaceToken(pattern, 'CCCC', calendarTypes[calendarType].wide); pattern = replaceToken(pattern, 'C{1,3}', calendarTypes[calendarType].abbreviated); */ if (struct.year.lt(1)) { eraNum = 0; } else { eraNum = 1; } pattern = replaceToken(pattern, 'GGGGG', eras.eraNarrow[eraNum.toString()]); pattern = replaceToken(pattern, 'GGGG', eras.eraNames[eraNum.toString()]); pattern = replaceToken(pattern, 'G{1,3}', eras.eraNames[eraNum.toString()]); year = struct.year.plus(eraNum - 1); if (year.lt(0)) { sign = '-'; } else { sign = ''; } year = year.abs().toString(); temp = sign + year; pattern = replaceToken(pattern, 'y{3,}', temp); pattern = replaceToken(pattern, 'yy', sign + year.slice(-2)); pattern = replaceToken(pattern, 'y', temp); pattern = replaceToken(pattern, 'U{1,}', temp); year = struct.year; if (year.lt(0)) { sign = '-'; } else { sign = ''; } year = year.toString(); temp = sign + year; pattern = replaceToken(pattern, 'u{1,}', temp); /* weekDate = calendarToWeekDate(struct); year = weekDate.year.plus(eraNum - 1); if (year.lt(0)) { sign = '-'; } else { sign = ''; } */ year = year.toString(); temp = sign + year; pattern = replaceToken(pattern, 'Y{1,}', year); //week = weekDate.week.toString(); //pattern = replaceToken(pattern, 'w{1,2}', week); //pattern = replaceToken(pattern, 'W', value); /* pattern = replaceToken(pattern, 'Q{1,2}', value); pattern = replaceToken(pattern, 'QQQ', value); pattern = replaceToken(pattern, 'QQQQ', value); pattern = replaceToken(pattern, 'q{1,2}', value); pattern = replaceToken(pattern, 'qqq', value); pattern = replaceToken(pattern, 'qqqq', value); */ month = struct.month.toString(); pattern = replaceToken(pattern, 'MMMMM', months.format.narrow[month]); pattern = replaceToken(pattern, 'MMMM', months.format.wide[month]); pattern = replaceToken(pattern, 'MMM', months.format.abbreviated[month]); pattern = replaceToken(pattern, 'M{1,2}', month); pattern = replaceToken(pattern, 'LLLLL', months[arrayLast(nameTypes)].narrow[month]); pattern = replaceToken(pattern, 'LLLL', months[arrayLast(nameTypes)].wide[month]); pattern = replaceToken(pattern, 'LLL', months[arrayLast(nameTypes)].abbreviated[month]); pattern = replaceToken(pattern, 'L{1,2}', month); pattern = replaceToken(pattern, 'd{1,2}', struct.day.toString()); if (julian) { doy = dayOfJulianYear(gregorianToJulian(struct)).toString(); } else { doy = dayOfGregorianYear(struct).toString(); } pattern = replaceToken(pattern, 'D{1,3}', doy); //pattern = replaceToken(pattern, 'F', value); if (julian) { mjd = julianToMJD(toUT(struct)); } else { mjd = gregorianToMJD(toUT(struct)); } pattern = replaceToken(pattern, 'g{1,}', mjd.toString()); day = cldrDayKey(struct); temp = days.format[arrayLast(formatTypes)]; if (isUndefined(temp)) { temp = makeNamesMin(days.format.abbreviated)[day]; } pattern = replaceToken(pattern, 'EEEEEE', temp); pattern = replaceToken(pattern, 'eeeeee', temp); temp = days.format.narrow[day]; pattern = replaceToken(pattern, 'EEEEE', temp); pattern = replaceToken(pattern, 'eeeee', temp); temp = days.format.wide[day]; pattern = replaceToken(pattern, 'EEEE', temp); pattern = replaceToken(pattern, 'eeee', temp); temp = days.format.abbreviated[day]; pattern = replaceToken(pattern, 'E{1,3}', temp); pattern = replaceToken(pattern, 'eeee', temp); //pattern = replaceToken(pattern, 'e{1,2}', local starting day of the week); temp = days[arrayLast(nameTypes)][arrayLast(formatTypes)]; if (isUndefined(temp)) { temp = makeNamesMin(days[arrayLast(nameTypes)].abbreviated)[day]; } pattern = replaceToken(pattern, 'cccccc', temp); pattern = replaceToken(pattern, 'ccccc', days[arrayLast(nameTypes)].narrow[day]); pattern = replaceToken(pattern, 'cccc', days[arrayLast(nameTypes)].wide[day]); pattern = replaceToken(pattern, 'ccc', days[arrayLast(nameTypes)].abbreviated[day]); //pattern = replaceToken(pattern, 'c', weekDayNumber(struct).toString()); // same as 'e': local starting day of the week return pattern; } function formatTime(struct, pattern, lang) { if (!isString(pattern) || isEmptyString(pattern)) { pattern = arrayFirst(formatTypes); } if (!isString(lang) || isEmptyString(lang) || !isPlainObject(languages[lang])) { if (!isString(defaultLanguage) || isEmptyString(defaultLanguage) || !isPlainObject(languages[defaultLanguage])) { throw new Error('Language not loaded!'); } lang = defaultLanguage; } var gregorian = languages[lang].calendars.gregorian, timeFormats = gregorian.timeFormats, dayPeriods = gregorian.dayPeriods, timeZoneNames = languages[lang].timeZoneNames, hourFormat = timeZoneNames.hourFormat, gmtFormat = timeZoneNames.gmtFormat, etc = timeZoneNames.zone.Etc, dayPeriod, hour, offset, offsetFormat, zulu = '\'Z\'', iso; if (arrayContains(formatTypes, pattern)) { pattern = timeFormats[pattern]; } if (struct.hour.inRange(12, 23)) { dayPeriod = 'pm'; } else { dayPeriod = 'am'; } pattern = replaceToken(pattern, 'a', dayPeriods.format.abbreviated[dayPeriod]); hour = struct.hour.plus(11).mod(12).plus(1); pattern = replaceToken(pattern, 'h{1,2}', hour.toString()); pattern = replaceToken(pattern, 'H{1,2}', struct.hour.toString()); pattern = replaceToken(pattern, 'K{1,2}', hour.minus(1).toString()); // if hour is 24, needs to be handled in date too //temp = new AstroDate().julianDay(new AstroDate().julianDay()); //pattern = replaceToken(pattern, 'k{1,2}', struct.hour.plus(1).toString()); //pattern = replaceToken(pattern, 'j{1,2}', struct.hour.toString()); pattern = replaceToken(pattern, 'm{1,2}', struct.minute.toString()); pattern = replaceToken(pattern, 's{1,2}', struct.second.toString()); pattern = replaceToken(pattern, 'S{1,}', struct.millisecond.toString()); //pattern = replaceToken(pattern, 'A{1,}', value); offsetFormat = hourFormat.split(';'); if (struct.offset.lte(0)) { offsetFormat = arrayFirst(offsetFormat); } else { offsetFormat = arrayLast(offsetFormat); } offset = fractionToTime(struct.offset.abs(), 'minute'); offsetFormat = replaceToken(offsetFormat, 'H{1,2}', offset.hour.toString()); offsetFormat = replaceToken(offsetFormat, 'm{1,2}', offset.minute.toString()); pattern = replaceToken(pattern, 'ZZZZZ', offsetFormat); pattern = replaceToken(pattern, 'xxxxx', offsetFormat); pattern = replaceToken(pattern, 'xxx', offsetFormat); if (struct.offset.isZero()) { iso = zulu; } else { iso = offsetFormat; } pattern = replaceToken(pattern, 'XXXXX', iso); pattern = replaceToken(pattern, 'XXX', iso); gmtFormat = replaceToken(gmtFormat, '{0}', offsetFormat); pattern = replaceToken(pattern, 'OOOO', gmtFormat); pattern = replaceToken(pattern, 'zzzz', gmtFormat); pattern = replaceToken(pattern, 'ZZZZ', gmtFormat); pattern = replaceToken(pattern, 'vvvv', gmtFormat); pattern = replaceToken(pattern, 'v', gmtFormat); pattern = replaceToken(pattern, 'VVVV', gmtFormat); if (struct.offset.lte(0)) { offsetFormat = '+HHMM'; } else { offsetFormat = '-HHMM'; } offsetFormat = replaceToken(offsetFormat, 'H{1,2}', offset.hour.toString()); offsetFormat = replaceToken(offsetFormat, 'm{1,2}', offset.minute.toString()); pattern = replaceToken(pattern, 'Z{1,3}', offsetFormat); pattern = replaceToken(pattern, 'XXXX', iso); pattern = replaceToken(pattern, 'XX', iso); pattern = replaceToken(pattern, 'xxxx', offsetFormat); pattern = replaceToken(pattern, 'xx', offsetFormat); gmtFormat = replaceToken(gmtFormat, '{0}', offsetFormat); pattern = replaceToken(pattern, 'O', gmtFormat); pattern = replaceToken(pattern, 'z{1,3}', gmtFormat); pattern = replaceToken(pattern, 'V{2,3}', etc.Unknown.exemplarCity); pattern = replaceToken(pattern, 'V', etc.Unknown.exemplarCity.slice(0, 3).toLowerCase()); return pattern; } function formatDateTime(struct, pattern, julian, lang) { if (!isString(pattern) || isEmptyString(pattern)) { pattern = arrayFirst(formatTypes); } if (!isString(lang) || isEmptyString(lang) || !isPlainObject(languages[lang])) { if (!isString(defaultLanguage) || isEmptyString(defaultLanguage) || !isPlainObject(languages[defaultLanguage])) { throw new Error('Language not loaded!'); } lang = defaultLanguage; } var gregorian = languages[lang].calendars.gregorian, dateTimeFormats = gregorian.dateTimeFormats, dateTimeFormat; if (arrayContains(objectKeys(dateTimeFormats), pattern)) { dateTimeFormat = dateTimeFormats[pattern]; dateTimeFormat = replaceToken(dateTimeFormat, '{1}', formatDate(struct, pattern, julian, lang)); dateTimeFormat = replaceToken(dateTimeFormat, '{0}', formatTime(struct, pattern, lang)); } else { dateTimeFormat = formatDate(struct, pattern, julian, lang); dateTimeFormat = formatTime(struct, dateTimeFormat, lang); } return dateTimeFormat; } AstroDate = function () { var args = arguments, input = arguments, argsLength = args.length, isJulian = false, isUT = false, isTT = false, isLocal = false, error = null, currentLanguage = defaultLanguage, struct, arg; objectDefineProperties(this, { getter: { value: function (key) { var got; if (isUndefined(key)) { got = extend({}, struct); } else if (isString(key)) { switch (key) { case 'struct': got = extend({}, struct); break; case 'isJulian': got = isJulian; break; case 'isUT': got = isUT; break; case 'isTT': got = isTT; break; case 'isLocal': got = isLocal; break; case 'args': got = args; break; case 'input': got = input; break; case 'error': got = error; break; case 'lang': got = currentLanguage; break; default: throw new SyntaxError(key); } } else { throw new TypeError(key); } return got; } }, setter: { value: function (key, value) { var unit = normaliseUnits(key), valid = false, bn, dim; if (unit) { bn = new BigNumber(value); switch (unit) { case 'year': valid = inYearRange(bn); break; case 'month': valid = inMonthRange(bn); break; case 'day': if (strictEqual(isJulian, true)) { dim = daysInJulianMonth(struct); } else { dim = daysInGregorianMonth(struct); } valid = inDayRange(bn, dim); break; case 'hour': valid = inHourRange(bn); break; case 'minute': valid = inMinuteRange(bn, struct.hour); break; case 'second': valid = inSecondRange(bn, struct); break; case 'millisecond': valid = inMillisecondRange(bn, struct.hour); break; case 'offset': valid = inOffsetRange(bn); break; default: throw new Error(unit); } if (valid) { struct[unit] = bn; } else { struct = {}; } } else if (arrayIsArray(key)) { struct = arrayToStruct(key, false); } else if (AstroDate.isAstroDate(key)) { struct = key.getter(); isJulian = key.isJulian(); } else if (isDate(key)) { struct = dateToStruct(key); } else if (isString(key)) { switch (key) { case 'input': input = value; break; case 'error': error = value; break; case 'struct': if (isValid(value)) { struct = extend({}, value); } else { struct = {}; } break; case 'isJulian': isJulian = Boolean(value); break; case 'isUT': isUT = Boolean(value); break; case 'isTT': isTT = Boolean(value); break; case 'isLocal': isLocal = Boolean(value); break; case 'lang': if (isString(value) && !isEmptyString(value) && isPlainObject(languages[value])) { currentLanguage = value; } break; default: struct = isoParse(key); } } else { throw new SyntaxError(key); } return this; } } }); switch (argsLength.toString()) { case '0': struct = dateToStruct(new Date()); break; case '1': arg = arrayFirst(args); if (AstroDate.isAstroDate(arg)) { isJulian = arg.getter('isJulian'); struct = extend({}, arg.getter()); } else if (arrayIsArray(arg)) { struct = arrayToStruct(arg, false); } else if (isDate(arg)) { struct = dateToStruct(arg); } else if (isNumber(arg)) { struct = dateToStruct(new Date(arg)); } else if (isString(arg)) { struct = isoParse(arg); } else if (isPlainObject(arg)) { struct = objectToStruct(arg); if (!isValid(struct)) { struct = {}; } } else { throw new TypeError(arg); } break; case '2': arg = arrayFirst(args); if (isString(arg)) { arg = stringTrim(arg).toLowerCase(); switch (arg) { case 'j': arg = args[1]; if (arrayIsArray(arg)) { struct = julianToGregorian(arrayToStruct(arg, true)); } else if (isPlainObject(arg)) { struct = objectToStruct(arg, true); if (isValid(struct, true)) { struct = julianToGregorian(struct); } else { struct = {}; } } else { throw new TypeError(arg); } break; case 'g': arg = args[1]; if (arrayIsArray(arg)) { struct = arrayToStruct(arg, false); } else if (isPlainObject(arg)) { struct = objectToStruct(arg); if (!isValid(struct)) { struct = {}; } } else { throw new TypeError(arg); } break; case 'jd': arg = args[1]; this.julianDay(arg); break; default: throw new SyntaxError(arg); } } else { throw new TypeError(arg); } break; default: throw new SyntaxError(argsLength); } if (!isValid(struct)) { struct = {}; } }; objectDefineProperties(AstroDate.prototype, { julian: { value: function () { return this.setter('isJulian', true); } }, gregorian: { value: function () { return this.setter('isJulian', false); } }, local: { value: function () { this.setter('isLocal', true); this.setter('isUT', false); return this; } }, UT: { value: function () { this.setter('isLocal', false); this.setter('isUT', true); return this; } }, TT: { value: function () { return this.setter('isTT', true); } }, civil: { value: function () { return this.setter('isTT', false); } }, raw: { value: function () { this.setter('isLocal', false); this.setter('isUT', false); this.setter('isTT', false); return this; } }, isJulian: { value: function () { return this.getter('isJulian'); } }, isGregorian: { value: function () { return !this.getter('isJulian'); } }, isUT: { value: function () { return this.getter('isUT'); } }, isTT: { value: function () { return this.getter('isTT'); } }, isCivil: { value: function () { return !this.getter('isTT'); } }, isLocal: { value: function () { return this.getter('isLocal'); } }, isRaw: { value: function () { return !this.getter('isUT') && !this.getter('isTT') && this.getter('isLocal'); } }, currentLang: { value: function () { return this.getter('lang'); } }, isWeekDay: { value: function () { var val; if (this.isValid()) { val = weekDayNumber(getCorrectStruct(this, this.getter())).inRange(1, 5); } return val; } }, isWeekend: { value: function () { var val; if (this.isValid()) { val = weekDayNumber(getCorrectStruct(this, this.getter())).inRange(6, 7); } return val; } }, zone: { value: function () { var val; if (this.isValid()) { val = getCorrectStruct(this, this.getter()).offset.toString(); } return val; } }, isValid: { value: function () { return isValid(this.getter()); } }, parse: { value: function (isoString) { var val; if (isString(isoString)) { val = this.setter('struct', isoParse(isoString)); } else { throw new TypeError(isoString); } return val; } }, toString: { value: function (pattern) { var struct, string, isJulian; if (this.isValid()) { isJulian = this.isJulian(); if (isJulian) { struct = jdToJulian(this.julianDay()); } else { struct = this.getter(); } struct = getCorrectStruct(this, struct); string = stripSingleQuotes(formatDateTime(struct, pattern, isJulian, this.currentLang())); } else { string = 'Invalid Date'; } return string; } }, toDateString: { value: function (pattern) { var struct, string, isJulian; if (this.isValid()) { isJulian = this.isJulian(); if (isJulian) { struct = jdToJulian(this.julianDay()); } else { struct = this.getter(); } struct = getCorrectStruct(this, struct); string = stripSingleQuotes(formatDate(struct, pattern, isJulian, this.currentLang())); } else { string = 'Invalid Date'; } return string; } }, toTimeString: { value: function (pattern) { var struct, string, isJulian; if (this.isValid()) { isJulian = this.isJulian(); if (isJulian) { struct = jdToJulian(this.julianDay()); } else { struct = this.getter(); } struct = getCorrectStruct(this, struct); string = stripSingleQuotes(formatTime(struct, pattern, this.currentLang())); } else { string = 'Invalid Date'; } return string; } }, toISOString: { value: function (padding) { var val; if (this.isValid()) { val = toISOString(getCorrectStruct(this, this.getter()), padding); } else { val = 'Invalid Date'; } return val; } }, valueOf: { value: function () { var val; if (this.isJulian()) { val = this.julianDay(); } else { val = this.getTime(); } return val; } }, unix: { value: function () { var struct, val; if (this.isValid()) { if (this.isTT()) { struct = toTT(this.getter()); } else { struct = this.getter(); } val = getTime(toUT(struct)).div(1000).trunc().toString(); } return val; } }, object: { value: function (dateObject) { var struct, val; if (isUndefined(dateObject)) { if (this.isValid()) { struct = getCorrectStruct(this, this.getter()); if (this.isJulian()) { val = structToObject(gregorianToJulian(struct)); } else { val = structToObject(struct); } } } else if (isPlainObject(dateObject)) { val = this.setter('struct', objectToStruct(dateObject, this.isJulian())); } else { throw new TypeError(dateObject); } return val; } }, clone: { value: function () { return new AstroDate(this); } }, array: { value: function (dateArray) { var struct, val; if (isUndefined(dateArray)) { if (this.isValid()) { struct = getCorrectStruct(this, this.getter()); if (this.isJulian()) { val = structToArrayOfString(gregorianToJulian(struct)); } else { val = structToArrayOfString(struct); } } } else if (arrayIsArray(dateArray)) { val = this.setter('struct', arrayToStruct(dateArray, this.isJulian())); } else { throw new TypeError(dateArray); } return val; } }, date: { value: function (date) { var val; if (isUndefined(date)) { if (this.isValid()) { val = new Date(parseInt(this.getTime(), 10)); } else { val = new Date(NaN); } } else if (isDate(date)) { val = this.setter(date); } else { throw new TypeError(date); } return val; } }, getTime: { value: function () { var struct, val; if (this.isValid()) { if (this.isTT()) { struct = toTT(this.getter()); } else { struct = this.getter(); } val = getTime(toUT(struct)).toString(); } return val; } }, deltaTime: { value: function () { var val; if (this.isValid()) { val = deltaTime(getCorrectStruct(this, this.getter())).toString(); } return val; } }, timeTo: { value: function (unit) { var val; if (this.isValid()) { val = timeTo(getCorrectStruct(this, this.getter()), normaliseUnits(unit)).toString(); } return val; } }, julianDay: { value: function (julianDay) { var struct, val; if (isUndefined(julianDay)) { if (this.isValid()) { if (this.isTT()) { struct = toTT(this.getter()); } else { struct = this.getter(); } val = gregorianToJd(toUT(struct)).toString(); } } else if (isNumber(julianDay) || isString(julianDay) || BigNumber.isBigNumber(julianDay)) { val = this.setter('struct', jdToGregorian(julianDay)); } else { throw new TypeError(julianDay); } return val; } }, easter: { value: function () { var struct, val; if (this.isValid()) { struct = getCorrectStruct(this, this.getter()); if (this.isJulian()) { val = julianEaster(gregorianToJulian(struct)); } else { val = gregorianEaster(struct); } } return val; } }, monthOfYear: { value: function (type) { var val, struct; if (this.isValid()) { struct = getCorrectStruct(this, this.getter()); if (this.isJulian()) { val = monthName(gregorianToJulian(struct), type, this.currentLang()); } else { val = monthName(struct, type, this.currentLang()); } } return val; } }, dayOfWeek: { value: function (type) { var val; if (this.isValid()) { val = dayOfWeek(getCorrectStruct(this, this.getter()), type, this.currentLang()); } return val; } }, isLeapYear: { value: function () { var struct, val; if (this.isValid()) { struct = getCorrectStruct(this, this.getter()); if (this.isJulian()) { val = isJulianLeapYear(gregorianToJulian(struct)); } else { val = isGregorianLeapYear(struct); } } return val; } }, daysInYear: { value: function () { var struct, val; if (this.isValid()) { struct = getCorrectStruct(this, this.getter()); if (this.isJulian()) { val = daysInJulianYear(gregorianToJulian(struct)).toString(); } else { val = daysInGregorianYear(struct).toString(); } } return val; } }, daysInMonth: { value: function () { var struct, val; if (this.isValid()) { struct = getCorrectStruct(this, this.getter()); if (this.isJulian()) { val = daysInJulianMonth(gregorianToJulian(struct)).toString(); } else { val = daysInGregorianMonth(struct).toString(); } } return val; } }, dayOfYear: { value: function () { var struct, val; if (this.isValid()) { struct = getCorrectStruct(this, this.getter()); if (this.isJulian()) { val = dayOfJulianYear(gregorianToJulian(struct)).toString(); } else { val = dayOfGregorianYear(struct).toString(); } } return val; } }, json: { value: function (jsonString) { var struct, propArray, val; if (isUndefined(jsonString)) { if (isFunction(JSON.stringify)) { val = JSON.stringify(this.object()); } else { struct = this.object(); propArray = arrayMap(objectKeys(struct), function (key) { return '"' + key + '":"' + struct[key] + '"'; }); val = '{' + propArray.join(',') + '}'; } } else if (isString(jsonString)) { if (isFunction(JSON.parse)) { struct = objectToStruct(JSON.parse(jsonString), this.isJulian()); } else { /*jslint evil: true */ struct = objectToStruct(new Function('return' + jsonString)(), this.isJulian()); /*jslint evil: false */ } if (!isValid(struct)) { throw new SyntaxError(struct); } val = this.setter('struct', struct); } else { throw new TypeError(jsonString); } return val; } }, toJSON: { value: function (padding) { return this.toISOString(padding); } }, calendarToWeekDate: { value: function () { var val; if (this.isValid()) { val = structToObject(calendarToWeekDate(getCorrectStruct(this, this.getter()))); } return val; } }, lang: { value: function (id) { if (isString(id) && !isEmptyString(id) && isPlainObject(languages[id])) { this.setter('lang', id); } return this; } } }); objectDefineProperties(AstroDate, { version: { value: VERSION }, lang: { value: function (id, object, freeze) { var val; if (isString(id) && !isEmptyString(id)) { if (isPlainObject(object)) { languages[id] = object; if (!strictEqual(freeze, false)) { deepFreeze(languages[id]); } } if (isPlainObject(languages[id])) { val = languages[id]; defaultLanguage = id; } } return val; } }, leapSeconds: { value: function (object, freeze) { if (isPlainObject(object)) { leapSeconds = object; if (!strictEqual(freeze, false)) { deepFreeze(leapSeconds); } } return leapSeconds; } }, BigNumber: { value: BigNumber }, normaliseUnits: { value: function (unitString) { return normaliseUnits(unitString); } }, isAstroDate: { value: function (inputArg) { return isObject(inputArg) && objectInstanceOf(inputArg, AstroDate); } }, now: { value: function () { return new AstroDate().getTime(); } }, julianDay: { value: function () { return new AstroDate().julianDay(); } }, unix: { value: function () { return new AstroDate().unix(); } }, months: { value: function (type, size, lang) { return makeNamesArray('months', type, size, lang, monthKeys); } }, weekDays: { value: function (type, size, lang) { return makeNamesArray('days', type, size, lang, dayKeys); } } }); defaultProperties = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; deepFreeze(defaultProperties); fullKeys = [{ full: 'year', alias: 'y', local: 'getFullYear' }, { full: 'month', alias: 'M', local: 'getMonth' }, { full: 'day', alias: 'd', local: 'getDate' }, { full: 'hour', alias: 'h', local: 'getHours' }, { full: 'minute', alias: 'm', local: 'getMinutes' }, { full: 'second', alias: 's', local: 'getSeconds' }, { full: 'millisecond', alias: 'ms', local: 'getMilliseconds' }, { full: 'offset', alias: 'z', local: 'getTimezoneOffset' }]; /* , { full: 'week', alias: 'W', local: null }, { full: 'weekDay', alias: 'E', local: null } */ deepFreeze(fullKeys); monthKeys = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']; deepFreeze(monthKeys); dayKeys = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']; deepFreeze(dayKeys); arrayForEach([BigNumber, BigNumber.prototype], function (element) { arrayForEach(objectKeys(element), function (key) { objectDefineProperty(element, key, { enumerable: false, configurable: false, writeable: false }); }); }); AstroDate.lang('root', { 'codePatterns': { 'language': '{0}', 'script': '{0}', 'territory': '{0}' }, 'types': { 'calendar': { 'japanese': 'japanese', 'iso8601': 'iso8601', 'coptic': 'coptic', 'dangi': 'dangi', 'ethiopic': 'ethiopic', 'ethiopic-amete-alem': 'ethiopic-amete-alem', 'gregorian': 'gregorian', 'hebrew': 'hebrew', 'persian': 'persian', 'roc': 'roc', 'chinese': 'chinese', 'buddhist': 'buddhist', 'indian': 'indian', 'islamic': 'islamic', 'islamic-civil': 'islamic-civil', 'islamic-rgsa': 'islamic-rgsa', 'islamic-tbla': 'islamic-tbla', 'islamic-umalqura': 'islamic-umalqura' }, 'collation': { 'phonebook': 'phonebook', 'gb2312han': 'gb2312han', 'eor': 'eor', 'ducet': 'ducet', 'dictionary': 'dictionary', 'big5han': 'big5han', 'traditional': 'traditional', 'zhuyin': 'zhuyin', 'unihan': 'unihan', 'stroke': 'stroke', 'searchjl': 'searchjl', 'search': 'search', 'reformed': 'reformed', 'pinyin': 'pinyin', 'standard': 'standard' }, 'numbers': { 'laoo': 'laoo', 'lanatham': 'lanatham', 'lana': 'lana', 'knda': 'knda', 'khmr': 'khmr', 'kali': 'kali', 'jpanfin': 'jpanfin', 'jpan': 'jpan', 'java': 'java', 'hebr': 'hebr', 'hantfin': 'hantfin', 'hant': 'hant', 'hansfin': 'hansfin', 'hans': 'hans', 'hanidec': 'hanidec', 'guru': 'guru', 'cakm': 'cakm', 'brah': 'brah', 'beng': 'beng', 'bali': 'bali', 'armnlow': 'armnlow', 'armn': 'armn', 'arabext': 'arabext', 'arab': 'arab', 'cham': 'cham', 'deva': 'deva', 'orya': 'orya', 'osma': 'osma', 'roman': 'roman', 'romanlow': 'romanlow', 'saur': 'saur', 'shrd': 'shrd', 'sora': 'sora', 'sund': 'sund', 'vaii': 'vaii', 'tibt': 'tibt', 'thai': 'thai', 'telu': 'telu', 'tamldec': 'tamldec', 'taml': 'taml', 'talu': 'talu', 'takr': 'takr', 'olck': 'olck', 'nkoo': 'nkoo', 'mymrshan': 'mymrshan', 'mymr': 'mymr', 'mtei': 'mtei', 'mong': 'mong', 'mlym': 'mlym', 'limb': 'limb', 'lepc': 'lepc', 'latn': 'latn', 'gujr': 'gujr', 'greklow': 'greklow', 'grek': 'grek', 'geor': 'geor', 'fullwide': 'fullwide', 'ethi': 'ethi' } }, 'keys': { 'calendar': 'calendar', 'collation': 'collation', 'currency': 'currency', 'numbers': 'numbers' }, 'localeDisplayPattern': { 'localePattern': '{0} ({1})', 'localeSeparator': '{0}, {1}', 'localeKeyTypePattern': '{0}: {1}' }, 'timeZoneNames': { 'hourFormat': '+HH:mm;-HH:mm', 'gmtFormat': 'GMT{0}', 'gmtZeroFormat': 'GMT', 'regionFormat': '{0}', 'regionFormat-type-daylight': '{0} (+1)', 'regionFormat-type-standard': '{0} (+0)', 'fallbackFormat': '{1} ({0})', 'zone': { 'Pacific': { 'Saipan': { 'exemplarCity': 'Saipan' }, 'Rarotonga': { 'exemplarCity': 'Rarotonga' }, 'Port_Moresby': { 'exemplarCity': 'Port Moresby' }, 'Ponape': { 'exemplarCity': 'Pohnpei' }, 'Pitcairn': { 'exemplarCity': 'Pitcairn' }, 'Palau': { 'exemplarCity': 'Palau' }, 'Auckland': { 'exemplarCity': 'Auckland' }, 'Apia': { 'exemplarCity': 'Apia' }, 'Funafuti': { 'exemplarCity': 'Funafuti' }, 'Galapagos': { 'exemplarCity': 'Galapagos' }, 'Gambier': { 'exemplarCity': 'Gambier' }, 'Guadalcanal': { 'exemplarCity': 'Guadalcanal' }, 'Guam': { 'exemplarCity': 'Guam' }, 'Honolulu': { 'exemplarCity': 'Honolulu' }, 'Wallis': { 'exemplarCity': 'Wallis' }, 'Wake': { 'exemplarCity': 'Wake' }, 'Truk': { 'exemplarCity': 'Chuuk' }, 'Tongatapu': { 'exemplarCity': 'Tongatapu' }, 'Tarawa': { 'exemplarCity': 'Tarawa' }, 'Tahiti': { 'exemplarCity': 'Tahiti' }, 'Kiritimati': { 'exemplarCity': 'Kiritimati' }, 'Johnston': { 'exemplarCity': 'Johnston' }, 'Chatham': { 'exemplarCity': 'Chatham' }, 'Easter': { 'exemplarCity': 'Easter' }, 'Efate': { 'exemplarCity': 'Efate' }, 'Enderbury': { 'exemplarCity': 'Enderbury' }, 'Fakaofo': { 'exemplarCity': 'Fakaofo' }, 'Fiji': { 'exemplarCity': 'Fiji' }, 'Kosrae': { 'exemplarCity': 'Kosrae' }, 'Kwajalein': { 'exemplarCity': 'Kwajalein' }, 'Majuro': { 'exemplarCity': 'Majuro' }, 'Marquesas': { 'exemplarCity': 'Marquesas' }, 'Midway': { 'exemplarCity': 'Midway' }, 'Nauru': { 'exemplarCity': 'Nauru' }, 'Niue': { 'exemplarCity': 'Niue' }, 'Norfolk': { 'exemplarCity': 'Norfolk' }, 'Noumea': { 'exemplarCity': 'Noumea' }, 'Pago_Pago': { 'exemplarCity': 'Pago Pago' } }, 'Australia': { 'Lindeman': { 'exemplarCity': 'Lindeman' }, 'Hobart': { 'exemplarCity': 'Hobart' }, 'Eucla': { 'exemplarCity': 'Eucla' }, 'Darwin': { 'exemplarCity': 'Darwin' }, 'Sydney': { 'exemplarCity': 'Sydney' }, 'Perth': { 'exemplarCity': 'Perth' }, 'Melbourne': { 'exemplarCity': 'Melbourne' }, 'Lord_Howe': { 'exemplarCity': 'Lord Howe' }, 'Adelaide': { 'exemplarCity': 'Adelaide' }, 'Brisbane': { 'exemplarCity': 'Brisbane' }, 'Broken_Hill': { 'exemplarCity': 'Broken Hill' }, 'Currie': { 'exemplarCity': 'Currie' } }, 'Indian': { 'Maldives': { 'exemplarCity': 'Maldives' }, 'Mahe': { 'exemplarCity': 'Mahe' }, 'Kerguelen': { 'exemplarCity': 'Kerguelen' }, 'Reunion': { 'exemplarCity': 'Reunion' }, 'Mayotte': { 'exemplarCity': 'Mayotte' }, 'Mauritius': { 'exemplarCity': 'Mauritius' }, 'Antananarivo': { 'exemplarCity': 'Antananarivo' }, 'Chagos': { 'exemplarCity': 'Chagos' }, 'Christmas': { 'exemplarCity': 'Christmas' }, 'Cocos': { 'exemplarCity': 'Cocos' }, 'Comoro': { 'exemplarCity': 'Comoro' } }, 'Etc': { 'GMT-11': { 'exemplarCity': 'GMT-11' }, 'GMT-10': { 'exemplarCity': 'GMT-10' }, 'GMT-1': { 'exemplarCity': 'GMT-1' }, 'GMT9': { 'exemplarCity': 'GMT+9' }, 'GMT8': { 'exemplarCity': 'GMT+8' }, 'GMT7': { 'exemplarCity': 'GMT+7' }, 'GMT6': { 'exemplarCity': 'GMT+6' }, 'GMT5': { 'exemplarCity': 'GMT+5' }, 'GMT': { 'exemplarCity': 'GMT' }, 'GMT1': { 'exemplarCity': 'GMT+1' }, 'GMT10': { 'exemplarCity': 'GMT+10' }, 'GMT11': { 'exemplarCity': 'GMT+11' }, 'GMT-3': { 'exemplarCity': 'GMT-3' }, 'GMT-4': { 'exemplarCity': 'GMT-4' }, 'GMT-5': { 'exemplarCity': 'GMT-5' }, 'GMT-6': { 'exemplarCity': 'GMT-6' }, 'GMT-7': { 'exemplarCity': 'GMT-7' }, 'GMT-8': { 'exemplarCity': 'GMT-8' }, 'GMT-9': { 'exemplarCity': 'GMT-9' }, 'Unknown': { 'exemplarCity': 'Unknown' }, 'GMT-2': { 'exemplarCity': 'GMT-2' }, 'GMT-14': { 'exemplarCity': 'GMT-14' }, 'GMT-13': { 'exemplarCity': 'GMT-13' }, 'GMT-12': { 'exemplarCity': 'GMT-12' }, 'GMT4': { 'exemplarCity': 'GMT+4' }, 'GMT3': { 'exemplarCity': 'GMT+3' }, 'GMT2': { 'exemplarCity': 'GMT+2' }, 'GMT12': { 'exemplarCity': 'GMT+12' } }, 'Antarctica': { 'Rothera': { 'exemplarCity': 'Rothera' }, 'Palmer': { 'exemplarCity': 'Palmer' }, 'McMurdo': { 'exemplarCity': 'McMurdo' }, 'Vostok': { 'exemplarCity': 'Vostok' }, 'Syowa': { 'exemplarCity': 'Syowa' }, 'South_Pole': { 'exemplarCity': 'South Pole' }, 'Casey': { 'exemplarCity': 'Casey' }, 'Davis': { 'exemplarCity': 'Davis' }, 'DumontDUrville': { 'exemplarCity': 'Dumont d\u02BCUrville' }, 'Macquarie': { 'exemplarCity': 'Macquarie' }, 'Mawson': { 'exemplarCity': 'Mawson' } }, 'Arctic': { 'Longyearbyen': { 'exemplarCity': 'Longyearbyen' } }, 'America': { 'Toronto': { 'exemplarCity': 'Toronto' }, 'Tijuana': { 'exemplarCity': 'Tijuana' }, 'Thunder_Bay': { 'exemplarCity': 'Thunder Bay' }, 'Thule': { 'exemplarCity': 'Thule' }, 'Tegucigalpa': { 'exemplarCity': 'Tegucigalpa' }, 'Swift_Current': { 'exemplarCity': 'Swift Current' }, 'Chicago': { 'exemplarCity': 'Chicago' }, 'Cayman': { 'exemplarCity': 'Cayman' }, 'Cayenne': { 'exemplarCity': 'Cayenne' }, 'Catamarca': { 'exemplarCity': 'Catamarca' }, 'Caracas': { 'exemplarCity': 'Caracas' }, 'Cancun': { 'exemplarCity': 'Cancun' }, 'Campo_Grande': { 'exemplarCity': 'Campo Grande' }, 'Cambridge_Bay': { 'exemplarCity': 'Cambridge Bay' }, 'Buenos_Aires': { 'exemplarCity': 'Buenos Aires' }, 'Boise': { 'exemplarCity': 'Boise' }, 'Asuncion': { 'exemplarCity': 'Asuncion' }, 'Aruba': { 'exemplarCity': 'Aruba' }, 'Argentina': { 'Rio_Gallegos': { 'exemplarCity': 'Rio Gallegos' }, 'San_Juan': { 'exemplarCity': 'San Juan' }, 'Ushuaia': { 'exemplarCity': 'Ushuaia' }, 'La_Rioja': { 'exemplarCity': 'La Rioja' }, 'San_Luis': { 'exemplarCity': 'San Luis' }, 'Salta': { 'exemplarCity': 'Salta' }, 'Tucuman': { 'exemplarCity': 'Tucuman' } }, 'Araguaina': { 'exemplarCity': 'Araguaina' }, 'Antigua': { 'exemplarCity': 'Antigua' }, 'Anguilla': { 'exemplarCity': 'Anguilla' }, 'Anchorage': { 'exemplarCity': 'Anchorage' }, 'Adak': { 'exemplarCity': 'Adak' }, 'Bahia': { 'exemplarCity': 'Bahia' }, 'Bahia_Banderas': { 'exemplarCity': 'Bahia Banderas' }, 'Barbados': { 'exemplarCity': 'Barbados' }, 'Belem': { 'exemplarCity': 'Belem' }, 'Belize': { 'exemplarCity': 'Belize' }, 'Blanc-Sablon': { 'exemplarCity': 'Blanc-Sablon' }, 'Boa_Vista': { 'exemplarCity': 'Boa Vista' }, 'Bogota': { 'exemplarCity': 'Bogota' }, 'Curacao': { 'exemplarCity': 'Curacao' }, 'Danmarkshavn': { 'exemplarCity': 'Danmarkshavn' }, 'Dawson': { 'exemplarCity': 'Dawson' }, 'Dawson_Creek': { 'exemplarCity': 'Dawson Creek' }, 'Denver': { 'exemplarCity': 'Denver' }, 'Detroit': { 'exemplarCity': 'Detroit' }, 'Hermosillo': { 'exemplarCity': 'Hermosillo' }, 'Indiana': { 'Vincennes': { 'exemplarCity': 'Vincennes, Indiana' }, 'Petersburg': { 'exemplarCity': 'Petersburg, Indiana' }, 'Tell_City': { 'exemplarCity': 'Tell City, Indiana' }, 'Knox': { 'exemplarCity': 'Knox, Indiana' }, 'Winamac': { 'exemplarCity': 'Winamac, Indiana' }, 'Marengo': { 'exemplarCity': 'Marengo, Indiana' }, 'Vevay': { 'exemplarCity': 'Vevay, Indiana' } }, 'Indianapolis': { 'exemplarCity': 'Indianapolis' }, 'Inuvik': { 'exemplarCity': 'Inuvik' }, 'Iqaluit': { 'exemplarCity': 'Iqaluit' }, 'Jamaica': { 'exemplarCity': 'Jamaica' }, 'Jujuy': { 'exemplarCity': 'Jujuy' }, 'Juneau': { 'exemplarCity': 'Juneau' }, 'Yellowknife': { 'exemplarCity': 'Yellowknife' }, 'Yakutat': { 'exemplarCity': 'Yakutat' }, 'Winnipeg': { 'exemplarCity': 'Winnipeg' }, 'Whitehorse': { 'exemplarCity': 'Whitehorse' }, 'Vancouver': { 'exemplarCity': 'Vancouver' }, 'Tortola': { 'exemplarCity': 'Tortola' }, 'Kralendijk': { 'exemplarCity': 'Kralendijk' }, 'Kentucky': { 'Monticello': { 'exemplarCity': 'Monticello, Kentucky' } }, 'Havana': { 'exemplarCity': 'Havana' }, 'Halifax': { 'exemplarCity': 'Halifax' }, 'Guyana': { 'exemplarCity': 'Guyana' }, 'Guayaquil': { 'exemplarCity': 'Guayaquil' }, 'Guatemala': { 'exemplarCity': 'Guatemala' }, 'Guadeloupe': { 'exemplarCity': 'Guadeloupe' }, 'Grenada': { 'exemplarCity': 'Grenada' }, 'Grand_Turk': { 'exemplarCity': 'Grand Turk' }, 'Goose_Bay': { 'exemplarCity': 'Goose Bay' }, 'Godthab': { 'exemplarCity': 'Nuuk' }, 'Glace_Bay': { 'exemplarCity': 'Glace Bay' }, 'Fortaleza': { 'exemplarCity': 'Fortaleza' }, 'El_Salvador': { 'exemplarCity': 'El Salvador' }, 'Eirunepe': { 'exemplarCity': 'Eirunepe' }, 'Edmonton': { 'exemplarCity': 'Edmonton' }, 'Dominica': { 'exemplarCity': 'Dominica' }, 'Chihuahua': { 'exemplarCity': 'Chihuahua' }, 'Coral_Harbour': { 'exemplarCity': 'Atikokan' }, 'Cordoba': { 'exemplarCity': 'Cordoba' }, 'Costa_Rica': { 'exemplarCity': 'Costa Rica' }, 'Creston': { 'exemplarCity': 'Creston' }, 'Cuiaba': { 'exemplarCity': 'Cuiaba' }, 'La_Paz': { 'exemplarCity': 'La Paz' }, 'Lima': { 'exemplarCity': 'Lima' }, 'Los_Angeles': { 'exemplarCity': 'Los Angeles' }, 'Louisville': { 'exemplarCity': 'Louisville' }, 'Lower_Princes': { 'exemplarCity': 'Lower Prince\'s Quarter' }, 'Maceio': { 'exemplarCity': 'Maceio' }, 'Managua': { 'exemplarCity': 'Managua' }, 'Manaus': { 'exemplarCity': 'Manaus' }, 'Marigot': { 'exemplarCity': 'Marigot' }, 'Martinique': { 'exemplarCity': 'Martinique' }, 'Matamoros': { 'exemplarCity': 'Matamoros' }, 'Mazatlan': { 'exemplarCity': 'Mazatlan' }, 'Mendoza': { 'exemplarCity': 'Mendoza' }, 'Menominee': { 'exemplarCity': 'Menominee' }, 'Merida': { 'exemplarCity': 'Merida' }, 'Metlakatla': { 'exemplarCity': 'Metlakatla' }, 'Mexico_City': { 'exemplarCity': 'Mexico City' }, 'Miquelon': { 'exemplarCity': 'Miquelon' }, 'Moncton': { 'exemplarCity': 'Moncton' }, 'Monterrey': { 'exemplarCity': 'Monterrey' }, 'Montevideo': { 'exemplarCity': 'Montevideo' }, 'Montreal': { 'exemplarCity': 'Montreal' }, 'Montserrat': { 'exemplarCity': 'Montserrat' }, 'Nassau': { 'exemplarCity': 'Nassau' }, 'New_York': { 'exemplarCity': 'New York' }, 'Nipigon': { 'exemplarCity': 'Nipigon' }, 'Nome': { 'exemplarCity': 'Nome' }, 'Noronha': { 'exemplarCity': 'Noronha' }, 'North_Dakota': { 'Beulah': { 'exemplarCity': 'Beulah, North Dakota' }, 'New_Salem': { 'exemplarCity': 'New Salem, North Dakota' }, 'Center': { 'exemplarCity': 'Center, North Dakota' } }, 'Ojinaga': { 'exemplarCity': 'Ojinaga' }, 'Panama': { 'exemplarCity': 'Panama' }, 'Pangnirtung': { 'exemplarCity': 'Pangnirtung' }, 'Paramaribo': { 'exemplarCity': 'Paramaribo' }, 'Phoenix': { 'exemplarCity': 'Phoenix' }, 'Port-au-Prince': { 'exemplarCity': 'Port-au-Prince' }, 'Port_of_Spain': { 'exemplarCity': 'Port of Spain' }, 'Porto_Velho': { 'exemplarCity': 'Porto Velho' }, 'Puerto_Rico': { 'exemplarCity': 'Puerto Rico' }, 'Rainy_River': { 'exemplarCity': 'Rainy River' }, 'Rankin_Inlet': { 'exemplarCity': 'Rankin Inlet' }, 'Recife': { 'exemplarCity': 'Recife' }, 'Regina': { 'exemplarCity': 'Regina' }, 'Resolute': { 'exemplarCity': 'Resolute' }, 'Rio_Branco': { 'exemplarCity': 'Rio Branco' }, 'Santa_Isabel': { 'exemplarCity': 'Santa Isabel' }, 'Santarem': { 'exemplarCity': 'Santarem' }, 'Santiago': { 'exemplarCity': 'Santiago' }, 'Santo_Domingo': { 'exemplarCity': 'Santo Domingo' }, 'Sao_Paulo': { 'exemplarCity': 'Sao Paulo' }, 'Scoresbysund': { 'exemplarCity': 'Ittoqqortoormiit' }, 'Shiprock': { 'exemplarCity': 'Shiprock' }, 'Sitka': { 'exemplarCity': 'Sitka' }, 'St_Barthelemy': { 'exemplarCity': 'St. Barthelemy' }, 'St_Johns': { 'exemplarCity': 'St. John\u02BCs' }, 'St_Kitts': { 'exemplarCity': 'St. Kitts' }, 'St_Lucia': { 'exemplarCity': 'St. Lucia' }, 'St_Thomas': { 'exemplarCity': 'St. Thomas' }, 'St_Vincent': { 'exemplarCity': 'St. Vincent' } }, 'Atlantic': { 'South_Georgia': { 'exemplarCity': 'South Georgia' }, 'Reykjavik': { 'exemplarCity': 'Reykjavik' }, 'Stanley': { 'exemplarCity': 'Stanley' }, 'St_Helena': { 'exemplarCity': 'St. Helena' }, 'Azores': { 'exemplarCity': 'Azores' }, 'Bermuda': { 'exemplarCity': 'Bermuda' }, 'Canary': { 'exemplarCity': 'Canary' }, 'Cape_Verde': { 'exemplarCity': 'Cape Verde' }, 'Faeroe': { 'exemplarCity': 'Faroe' }, 'Madeira': { 'exemplarCity': 'Madeira' } }, 'Europe': { 'Oslo': { 'exemplarCity': 'Oslo' }, 'Moscow': { 'exemplarCity': 'Moscow' }, 'Monaco': { 'exemplarCity': 'Monaco' }, 'Minsk': { 'exemplarCity': 'Minsk' }, 'Mariehamn': { 'exemplarCity': 'Mariehamn' }, 'Malta': { 'exemplarCity': 'Malta' }, 'Madrid': { 'exemplarCity': 'Madrid' }, 'Luxembourg': { 'exemplarCity': 'Luxembourg' }, 'London': { 'exemplarCity': 'London' }, 'Ljubljana': { 'exemplarCity': 'Ljubljana' }, 'Lisbon': { 'exemplarCity': 'Lisbon' }, 'Kiev': { 'exemplarCity': 'Kiev' }, 'Kaliningrad': { 'exemplarCity': 'Kaliningrad' }, 'Jersey': { 'exemplarCity': 'Jersey' }, 'Istanbul': { 'exemplarCity': 'Istanbul' }, 'Isle_of_Man': { 'exemplarCity': 'Isle of Man' }, 'Bucharest': { 'exemplarCity': 'Bucharest' }, 'Brussels': { 'exemplarCity': 'Brussels' }, 'Bratislava': { 'exemplarCity': 'Bratislava' }, 'Berlin': { 'exemplarCity': 'Berlin' }, 'Belgrade': { 'exemplarCity': 'Belgrade' }, 'Athens': { 'exemplarCity': 'Athens' }, 'Andorra': { 'exemplarCity': 'Andorra' }, 'Amsterdam': { 'exemplarCity': 'Amsterdam' }, 'Simferopol': { 'exemplarCity': 'Simferopol' }, 'Skopje': { 'exemplarCity': 'Skopje' }, 'Sofia': { 'exemplarCity': 'Sofia' }, 'Stockholm': { 'exemplarCity': 'Stockholm' }, 'Tallinn': { 'exemplarCity': 'Tallinn' }, 'Tirane': { 'exemplarCity': 'Tirane' }, 'Uzhgorod': { 'exemplarCity': 'Uzhgorod' }, 'Vaduz': { 'exemplarCity': 'Vaduz' }, 'Zurich': { 'exemplarCity': 'Zurich' }, 'Zaporozhye': { 'exemplarCity': 'Zaporozhye' }, 'Zagreb': { 'exemplarCity': 'Zagreb' }, 'Warsaw': { 'exemplarCity': 'Warsaw' }, 'Volgograd': { 'exemplarCity': 'Volgograd' }, 'Vilnius': { 'exemplarCity': 'Vilnius' }, 'Vienna': { 'exemplarCity': 'Vienna' }, 'Vatican': { 'exemplarCity': 'Vatican' }, 'Sarajevo': { 'exemplarCity': 'Sarajevo' }, 'San_Marino': { 'exemplarCity': 'San Marino' }, 'Samara': { 'exemplarCity': 'Samara' }, 'Rome': { 'exemplarCity': 'Rome' }, 'Riga': { 'exemplarCity': 'Riga' }, 'Prague': { 'exemplarCity': 'Prague' }, 'Podgorica': { 'exemplarCity': 'Podgorica' }, 'Paris': { 'exemplarCity': 'Paris' }, 'Helsinki': { 'exemplarCity': 'Helsinki' }, 'Guernsey': { 'exemplarCity': 'Guernsey' }, 'Gibraltar': { 'exemplarCity': 'Gibraltar' }, 'Dublin': { 'exemplarCity': 'Dublin' }, 'Copenhagen': { 'exemplarCity': 'Copenhagen' }, 'Chisinau': { 'exemplarCity': 'Chisinau' }, 'Busingen': { 'exemplarCity': 'Busingen' }, 'Budapest': { 'exemplarCity': 'Budapest' } }, 'Africa': { 'Libreville': { 'exemplarCity': 'Libreville' }, 'Lagos': { 'exemplarCity': 'Lagos' }, 'Kinshasa': { 'exemplarCity': 'Kinshasa' }, 'Kigali': { 'exemplarCity': 'Kigali' }, 'Khartoum': { 'exemplarCity': 'Khartoum' }, 'Kampala': { 'exemplarCity': 'Kampala' }, 'Juba': { 'exemplarCity': 'Juba' }, 'Johannesburg': { 'exemplarCity': 'Johannesburg' }, 'Harare': { 'exemplarCity': 'Harare' }, 'Gaborone': { 'exemplarCity': 'Gaborone' }, 'Freetown': { 'exemplarCity': 'Freetown' }, 'El_Aaiun': { 'exemplarCity': 'El Aaiun' }, 'Douala': { 'exemplarCity': 'Douala' }, 'Djibouti': { 'exemplarCity': 'Djibouti' }, 'Dar_es_Salaam': { 'exemplarCity': 'Dar es Salaam' }, 'Dakar': { 'exemplarCity': 'Dakar' }, 'Banjul': { 'exemplarCity': 'Banjul' }, 'Bangui': { 'exemplarCity': 'Bangui' }, 'Bamako': { 'exemplarCity': 'Bamako' }, 'Asmera': { 'exemplarCity': 'Asmara' }, 'Malabo': { 'exemplarCity': 'Malabo' }, 'Maputo': { 'exemplarCity': 'Maputo' }, 'Maseru': { 'exemplarCity': 'Maseru' }, 'Mbabane': { 'exemplarCity': 'Mbabane' }, 'Mogadishu': { 'exemplarCity': 'Mogadishu' }, 'Monrovia': { 'exemplarCity': 'Monrovia' }, 'Nairobi': { 'exemplarCity': 'Nairobi' }, 'Ndjamena': { 'exemplarCity': 'Ndjamena' }, 'Windhoek': { 'exemplarCity': 'Windhoek' }, 'Tunis': { 'exemplarCity': 'Tunis' }, 'Tripoli': { 'exemplarCity': 'Tripoli' }, 'Sao_Tome': { 'exemplarCity': 'Sao Tome' }, 'Porto-Novo': { 'exemplarCity': 'Porto-Novo' }, 'Ouagadougou': { 'exemplarCity': 'Ouagadougou' }, 'Nouakchott': { 'exemplarCity': 'Nouakchott' }, 'Niamey': { 'exemplarCity': 'Niamey' }, 'Lusaka': { 'exemplarCity': 'Lusaka' }, 'Lubumbashi': { 'exemplarCity': 'Lubumbashi' }, 'Luanda': { 'exemplarCity': 'Luanda' }, 'Lome': { 'exemplarCity': 'Lome' }, 'Conakry': { 'exemplarCity': 'Conakry' }, 'Ceuta': { 'exemplarCity': 'Ceuta' }, 'Casablanca': { 'exemplarCity': 'Casablanca' }, 'Cairo': { 'exemplarCity': 'Cairo' }, 'Bujumbura': { 'exemplarCity': 'Bujumbura' }, 'Brazzaville': { 'exemplarCity': 'Brazzaville' }, 'Blantyre': { 'exemplarCity': 'Blantyre' }, 'Bissau': { 'exemplarCity': 'Bissau' }, 'Abidjan': { 'exemplarCity': 'Abidjan' }, 'Accra': { 'exemplarCity': 'Accra' }, 'Addis_Ababa': { 'exemplarCity': 'Addis Ababa' }, 'Algiers': { 'exemplarCity': 'Algiers' } }, 'Asia': { 'Shanghai': { 'exemplarCity': 'Shanghai' }, 'Seoul': { 'exemplarCity': 'Seoul' }, 'Samarkand': { 'exemplarCity': 'Samarkand' }, 'Sakhalin': { 'exemplarCity': 'Sakhalin' }, 'Saigon': { 'exemplarCity': 'Ho Chi Minh' }, 'Riyadh': { 'exemplarCity': 'Riyadh' }, 'Rangoon': { 'exemplarCity': 'Rangoon' }, 'Qyzylorda': { 'exemplarCity': 'Qyzylorda' }, 'Qatar': { 'exemplarCity': 'Qatar' }, 'Pyongyang': { 'exemplarCity': 'Pyongyang' }, 'Pontianak': { 'exemplarCity': 'Pontianak' }, 'Phnom_Penh': { 'exemplarCity': 'Phnom Penh' }, 'Oral': { 'exemplarCity': 'Oral' }, 'Omsk': { 'exemplarCity': 'Omsk' }, 'Novosibirsk': { 'exemplarCity': 'Novosibirsk' }, 'Baghdad': { 'exemplarCity': 'Baghdad' }, 'Chongqing': { 'exemplarCity': 'Chongqing' }, 'Colombo': { 'exemplarCity': 'Colombo' }, 'Damascus': { 'exemplarCity': 'Damascus' }, 'Dhaka': { 'exemplarCity': 'Dhaka' }, 'Dili': { 'exemplarCity': 'Dili' }, 'Dubai': { 'exemplarCity': 'Dubai' }, 'Dushanbe': { 'exemplarCity': 'Dushanbe' }, 'Gaza': { 'exemplarCity': 'Gaza' }, 'Harbin': { 'exemplarCity': 'Harbin' }, 'Hebron': { 'exemplarCity': 'Hebron' }, 'Hong_Kong': { 'exemplarCity': 'Hong Kong' }, 'Hovd': { 'exemplarCity': 'Hovd' }, 'Irkutsk': { 'exemplarCity': 'Irkutsk' }, 'Jakarta': { 'exemplarCity': 'Jakarta' }, 'Jayapura': { 'exemplarCity': 'Jayapura' }, 'Ulaanbaatar': { 'exemplarCity': 'Ulaanbaatar' }, 'Urumqi': { 'exemplarCity': 'Urumqi' }, 'Ust-Nera': { 'exemplarCity': 'Ust-Nera' }, 'Vientiane': { 'exemplarCity': 'Vientiane' }, 'Vladivostok': { 'exemplarCity': 'Vladivostok' }, 'Yakutsk': { 'exemplarCity': 'Yakutsk' }, 'Yekaterinburg': { 'exemplarCity': 'Yekaterinburg' }, 'Yerevan': { 'exemplarCity': 'Yerevan' }, 'Tokyo': { 'exemplarCity': 'Tokyo' }, 'Thimphu': { 'exemplarCity': 'Thimphu' }, 'Tehran': { 'exemplarCity': 'Tehran' }, 'Tbilisi': { 'exemplarCity': 'Tbilisi' }, 'Tashkent': { 'exemplarCity': 'Tashkent' }, 'Taipei': { 'exemplarCity': 'Taipei' }, 'Singapore': { 'exemplarCity': 'Singapore' }, 'Jerusalem': { 'exemplarCity': 'Jerusalem' }, 'Ashgabat': { 'exemplarCity': 'Ashgabat' }, 'Aqtobe': { 'exemplarCity': 'Aqtobe' }, 'Aqtau': { 'exemplarCity': 'Aqtau' }, 'Anadyr': { 'exemplarCity': 'Anadyr' }, 'Amman': { 'exemplarCity': 'Amman' }, 'Almaty': { 'exemplarCity': 'Almaty' }, 'Aden': { 'exemplarCity': 'Aden' }, 'Bahrain': { 'exemplarCity': 'Bahrain' }, 'Baku': { 'exemplarCity': 'Baku' }, 'Bangkok': { 'exemplarCity': 'Bangkok' }, 'Beirut': { 'exemplarCity': 'Beirut' }, 'Bishkek': { 'exemplarCity': 'Bishkek' }, 'Brunei': { 'exemplarCity': 'Brunei' }, 'Calcutta': { 'exemplarCity': 'Kolkata' }, 'Choibalsan': { 'exemplarCity': 'Choibalsan' }, 'Kabul': { 'exemplarCity': 'Kabul' }, 'Kamchatka': { 'exemplarCity': 'Kamchatka' }, 'Karachi': { 'exemplarCity': 'Karachi' }, 'Kashgar': { 'exemplarCity': 'Kashgar' }, 'Katmandu': { 'exemplarCity': 'Kathmandu' }, 'Khandyga': { 'exemplarCity': 'Khandyga' }, 'Krasnoyarsk': { 'exemplarCity': 'Krasnoyarsk' }, 'Kuala_Lumpur': { 'exemplarCity': 'Kuala Lumpur' }, 'Kuching': { 'exemplarCity': 'Kuching' }, 'Kuwait': { 'exemplarCity': 'Kuwait' }, 'Macau': { 'exemplarCity': 'Macau' }, 'Magadan': { 'exemplarCity': 'Magadan' }, 'Makassar': { 'exemplarCity': 'Makassar' }, 'Manila': { 'exemplarCity': 'Manila' }, 'Muscat': { 'exemplarCity': 'Muscat' }, 'Nicosia': { 'exemplarCity': 'Nicosia' }, 'Novokuznetsk': { 'exemplarCity': 'Novokuznetsk' } } } }, 'calendars': { 'gregorian': { 'months': { 'format': { 'abbreviated': { '8': 'M08', '7': 'M07', '6': 'M06', '5': 'M05', '12': 'M12', '11': 'M11', '10': 'M10', '9': 'M09', '1': 'M01', '2': 'M02', '3': 'M03', '4': 'M04' }, 'narrow': { '8': '8', '7': '7', '6': '6', '5': '5', '12': '12', '11': '11', '10': '10', '9': '9', '1': '1', '2': '2', '3': '3', '4': '4' }, 'wide': { '8': 'M08', '7': 'M07', '6': 'M06', '5': 'M05', '12': 'M12', '11': 'M11', '10': 'M10', '9': 'M09', '1': 'M01', '2': 'M02', '3': 'M03', '4': 'M04' } }, 'stand-alone': { 'abbreviated': { '8': 'M08', '7': 'M07', '6': 'M06', '5': 'M05', '12': 'M12', '11': 'M11', '10': 'M10', '9': 'M09', '1': 'M01', '2': 'M02', '3': 'M03', '4': 'M04' }, 'narrow': { '8': '8', '7': '7', '6': '6', '5': '5', '12': '12', '11': '11', '10': '10', '9': '9', '1': '1', '2': '2', '3': '3', '4': '4' }, 'wide': { '8': 'M08', '7': 'M07', '6': 'M06', '5': 'M05', '12': 'M12', '11': 'M11', '10': 'M10', '9': 'M09', '1': 'M01', '2': 'M02', '3': 'M03', '4': 'M04' } } }, 'days': { 'format': { 'abbreviated': { 'sun': 'Sun', 'mon': 'Mon', 'tue': 'Tue', 'wed': 'Wed', 'thu': 'Thu', 'fri': 'Fri', 'sat': 'Sat' }, 'narrow': { 'sun': 'S', 'mon': 'M', 'tue': 'T', 'wed': 'W', 'thu': 'T', 'fri': 'F', 'sat': 'S' }, 'short': { 'sun': 'Sun', 'mon': 'Mon', 'tue': 'Tue', 'wed': 'Wed', 'thu': 'Thu', 'fri': 'Fri', 'sat': 'Sat' }, 'wide': { 'sun': 'Sun', 'mon': 'Mon', 'tue': 'Tue', 'wed': 'Wed', 'thu': 'Thu', 'fri': 'Fri', 'sat': 'Sat' } }, 'stand-alone': { 'abbreviated': { 'sun': 'Sun', 'mon': 'Mon', 'tue': 'Tue', 'wed': 'Wed', 'thu': 'Thu', 'fri': 'Fri', 'sat': 'Sat' }, 'narrow': { 'sun': 'S', 'mon': 'M', 'tue': 'T', 'wed': 'W', 'thu': 'T', 'fri': 'F', 'sat': 'S' }, 'short': { 'sun': 'Sun', 'mon': 'Mon', 'tue': 'Tue', 'wed': 'Wed', 'thu': 'Thu', 'fri': 'Fri', 'sat': 'Sat' }, 'wide': { 'sun': 'Sun', 'mon': 'Mon', 'tue': 'Tue', 'wed': 'Wed', 'thu': 'Thu', 'fri': 'Fri', 'sat': 'Sat' } } }, 'quarters': { 'format': { 'abbreviated': { '1': 'Q1', '2': 'Q2', '3': 'Q3', '4': 'Q4' }, 'narrow': { '1': '1', '2': '2', '3': '3', '4': '4' }, 'wide': { '1': 'Q1', '2': 'Q2', '3': 'Q3', '4': 'Q4' } }, 'stand-alone': { 'abbreviated': { '1': 'Q1', '2': 'Q2', '3': 'Q3', '4': 'Q4' }, 'narrow': { '1': '1', '2': '2', '3': '3', '4': '4' }, 'wide': { '1': 'Q1', '2': 'Q2', '3': 'Q3', '4': 'Q4' } } }, 'dayPeriods': { 'format': { 'abbreviated': { 'am': 'AM', 'pm': 'PM' }, 'narrow': { 'am': 'AM', 'pm': 'PM' }, 'wide': { 'am': 'AM', 'pm': 'PM' } }, 'stand-alone': { 'abbreviated': { 'am': 'AM', 'pm': 'PM' }, 'narrow': { 'am': 'AM', 'pm': 'PM' }, 'wide': { 'am': 'AM', 'pm': 'PM' } } }, 'eras': { 'eraNames': { '0': 'BCE', '0-alt-variant': 'BCE', '1': 'CE', '1-alt-variant': 'CE' }, 'eraAbbr': { '0': 'BCE', '0-alt-variant': 'BCE', '1': 'CE', '1-alt-variant': 'CE' }, 'eraNarrow': { '0': 'BCE', '0-alt-variant': 'BCE', '1': 'CE', '1-alt-variant': 'CE' } }, 'dateFormats': { 'full': 'y MMMM d, EEEE', 'long': 'y MMMM d', 'medium': 'y MMM d', 'short': 'y-MM-dd' }, 'timeFormats': { 'full': 'HH:mm:ss zzzz', 'long': 'HH:mm:ss z', 'medium': 'HH:mm:ss', 'short': 'HH:mm' }, 'dateTimeFormats': { 'full': '{1} {0}', 'long': '{1} {0}', 'medium': '{1} {0}', 'short': '{1} {0}', 'availableFormats': { 'Hms': 'HH:mm:ss', 'hms': 'h:mm:ss a', 'Hm': 'HH:mm', 'hm': 'h:mm a', 'H': 'HH', 'h': 'h a', 'GyMMMEd': 'G y MMM d, E', 'GyMMMd': 'G y MMM d', 'd': 'd', 'Ed': 'd, E', 'Ehm': 'E h:mm a', 'EHm': 'E HH:mm', 'Ehms': 'E h:mm:ss a', 'EHms': 'E HH:mm:ss', 'Gy': 'G y', 'GyMMM': 'G y MMM', 'yM': 'y-MM', 'yMd': 'y-MM-dd', 'yMEd': 'y-MM-dd, E', 'yMMM': 'y MMM', 'yMMMd': 'y MMM d', 'yMMMEd': 'y MMM d, E', 'yQQQ': 'y QQQ', 'yQQQQ': 'y QQQQ', 'y': 'y', 'ms': 'mm:ss', 'MMMEd': 'MMM d, E', 'MMMd': 'MMM d', 'MMM': 'LLL', 'MEd': 'MM-dd, E', 'Md': 'MM-dd', 'M': 'L' }, 'appendItems': { 'Second': '{0} ({2}: {1})', 'Quarter': '{0} ({2}: {1})', 'Month': '{0} ({2}: {1})', 'Year': '{1} {0}', 'Week': '{0} ({2}: {1})', 'Timezone': '{0} {1}', 'Day': '{0} ({2}: {1})', 'Day-Of-Week': '{0} {1}', 'Era': '{1} {0}', 'Hour': '{0} ({2}: {1})', 'Minute': '{0} ({2}: {1})' }, 'intervalFormats': { 'MMMEd': { 'd': 'MMM d, E \u2013 MMM d, E', 'M': 'MMM d, E \u2013 MMM d, E' }, 'MMMd': { 'd': 'MMM d\u2013d', 'M': 'MMM d \u2013 MMM d' }, 'MMM': { 'M': 'LLL\u2013LLL' }, 'MEd': { 'd': 'MM-dd, E \u2013 MM-dd, E', 'M': 'MM-dd, E \u2013 MM-dd, E' }, 'Md': { 'd': 'MM-dd \u2013 MM-dd', 'M': 'MM-dd \u2013 MM-dd' }, 'M': { 'M': 'MM\u2013MM' }, 'Hv': { 'H': 'HH\u2013HH v' }, 'hv': { 'a': 'h a \u2013 h a v', 'h': 'h\u2013h a v' }, 'y': { 'y': 'y\u2013y' }, 'yM': { 'M': 'y-MM \u2013 y-MM', 'y': 'y-MM \u2013 y-MM' }, 'yMd': { 'd': 'y-MM-dd \u2013 y-MM-dd', 'M': 'y-MM-dd \u2013 y-MM-dd', 'y': 'y-MM-dd \u2013 y-MM-dd' }, 'yMEd': { 'd': 'y-MM-dd, E \u2013 y-MM-dd, E', 'M': 'y-MM-dd, E \u2013 y-MM-dd, E', 'y': 'y-MM-dd, E \u2013 y-MM-dd, E' }, 'yMMM': { 'M': 'y MMM\u2013MMM', 'y': 'y MMM \u2013 y MMM' }, 'yMMMd': { 'd': 'y MMM d\u2013d', 'M': 'y MMM d \u2013 MMM d', 'y': 'y MMM d \u2013 y MMM d' }, 'yMMMEd': { 'd': 'y MMM d, E \u2013 MMM d, E', 'M': 'y MMM d, E \u2013 MMM d, E', 'y': 'y MMM d, E \u2013 y MMM d, E' }, 'yMMMM': { 'M': 'y MMMM\u2013MMMM', 'y': 'y MMMM \u2013 y MMMM' }, 'Hmv': { 'H': 'HH:mm\u2013HH:mm v', 'm': 'HH:mm\u2013HH:mm v' }, 'hmv': { 'a': 'h:mm a \u2013 h:mm a v', 'h': 'h:mm\u2013h:mm a v', 'm': 'h:mm\u2013h:mm a v' }, 'Hm': { 'H': 'HH:mm\u2013HH:mm', 'm': 'HH:mm\u2013HH:mm' }, 'hm': { 'a': 'h:mm a \u2013 h:mm a', 'h': 'h:mm\u2013h:mm a', 'm': 'h:mm\u2013h:mm a' }, 'H': { 'H': 'HH\u2013HH' }, 'h': { 'a': 'h a \u2013 h a', 'h': 'h\u2013h a' }, 'd': { 'd': 'd\u2013d' }, 'intervalFormatFallback': '{0} \u2013 {1}' } } } } }, false); AstroDate.leapSeconds({ '1972': { '6': { '30': 1 }, '12': { '31': 1 } }, '1973': { '12': { '31': 1 } }, '1974': { '12': { '31': 1 } }, '1975': { '12': { '31': 1 } }, '1976': { '12': { '31': 1 } }, '1977': { '12': { '31': 1 } }, '1978': { '12': { '31': 1 } }, '1979': { '12': { '31': 1 } }, '1981': { '6': { '30': 1 } }, '1982': { '6': { '30': 1 } }, '1983': { '6': { '30': 1 } }, '1985': { '6': { '30': 1 } }, '1987': { '12': { '31': 1 } }, '1989': { '12': { '31': 1 } }, '1990': { '12': { '31': 1 } }, '1992': { '6': { '30': 1 } }, '1993': { '6': { '30': 1 } }, '1994': { '6': { '30': 1 } }, '1995': { '12': { '31': 1 } }, '1997': { '6': { '30': 1 } }, '1998': { '12': { '31': 1 } }, '2005': { '12': { '31': 1 } }, '2008': { '12': { '31': 1 } }, '2012': { '6': { '30': 1 } }, 'total': { '6': { '30': 10 }, '12': { '31': 15 }, 'sum': 35 } }, false); return AstroDate; }; nfeDefinition = null; return tempSafariNFE; }()))); tempSafariNFE = null; }((function (thisContext) { 'use strict'; /*global window, global, self */ // detect the global context of the environment if ('object' === typeof window && null !== window && window.window === window) { thisContext = window; } else if ('object' === typeof global && null !== global && global.global === global) { thisContext = global; } else if ('object' === typeof self && null !== self && self.self === self) { thisContext = self; } if ('object' !== typeof thisContext || null === thisContext) { throw new TypeError('Invalid global context'); } /*global */ return thisContext; }(this)), (function () { 'use strict'; // return undefined for privateUndefined return; }())));
astrodate.js
/* AstroDate * * home: https://github.com/Xotic750/astrodate * * Copyright (C) 2013 Graham Fairweather (a.k.a: Xotic750) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ (function (thisContext, privateUndefined) { 'use strict'; // Safari 2.x NFE bug fix // http://kangax.github.io/nfe/ var tempSafariNFE; (function (name, definition) { /*global module, require, define */ var bigNumberFunc = 'BigNumber', bigNumberString = bigNumberFunc.toLowerCase(), projectPaths, projectConfig; if ('object' === typeof module && null !== module && 'object' === typeof module.exports && null !== module.exports) { module.exports = definition(require(bigNumberString + '.js')); } else if ('function' === typeof define && 'object' === typeof define.amd && null !== define.amd) { projectPaths = {}; projectConfig = {}; projectPaths[bigNumberString] = '//cdn.jsdelivr.net/bignumber.js/1.1.0/bignumber.min'; projectConfig[bigNumberString] = {}; require.config({ paths: projectPaths, config: projectConfig }); // "name" should be removed when finished with local testing define(name, [bigNumberString], definition); } else { thisContext[name] = definition(thisContext[bigNumberFunc]); } /*global */ }('astrodate', (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe/ var nfeDefinition; tempSafariNFE = function nfeDefinition(BigNumber) { BigNumber.config({ DECIMAL_PLACES: 9, ROUNDING_MODE: 0, EXPONENTIAL_AT: [-7, 20], RANGE: [-1000000000, 1000000000], ERRORS: true }); var VERSION = '0.5.1', //MAX_INTEGER = 9007199254740991, //MIN_INTEGER = -9007199254740991, UWORD32 = Math.pow(2, 32), MAX_UINT32 = UWORD32 - 1, languages = {}, baseObject = {}, defaultProperties, baseArray = [], baseString = '', toObjectString, baseNumber = 0, baseBoolean = true, fullKeys, dayKeys, monthKeys, protoName = '__proto__', invalidISOCharsRx = new RegExp('[^\\d\\-+WT Z:,\\.]'), replaceTokenRX = new RegExp('([^\\\']+)|(\\\'[^\\\']+\\\')', 'g'), toObject, //j2000 = [2000, 1, 1, 11, 58, 55, 816], extend, arrayIndexOf, objectDefineProperty, objectDefineProperties, objectFreeze, objectIsFrozen, hasProperty, objectHasOwnProperty, objectGetOwnPropertyDescriptor, arrayIsArray, objectInstanceOf, objectGetPrototypeOf, isPlainObject, objectKeys, stringTrim, stringRepeat, stringSplit, //stringStartsWith, //stringEndsWith, stringContains, toObjectFixIndexedAccess, //arrayUnshift, arrayForEach, arraySome, arrayMap, //arrayFilter, arrayReduce, objectIs, numberToInteger, numberIsNaN, numberIsFinite, mathSign, AstroDate, datePatterns, timePatterns, formatTypes, nameTypes, widthTypes, widthTypeShort, defaultLanguage, calendarTypes, leapSeconds; function toNumber(inputArg) { return +inputArg; } function strictEqual(a, b) { return a === b; } function lt(number, limit) { return number < limit; } function lte(number, limit) { return number <= limit; } function gt(number, limit) { return number > limit; } function gte(number, limit) { return number >= limit; } function mod(number1, number2) { return number1 % number2; } function clamp(number, min, max) { return Math.min(Math.max(number, min), max); } function inRange(number, min, max) { return gte(number, min) && lte(number, max); } function isUndefined(inputArg) { return strictEqual(typeof inputArg, 'undefined'); } function isNull(inputArg) { return strictEqual(inputArg, null); } function isBoolean(inputArg) { return strictEqual(inputArg, true) || strictEqual(inputArg, false); } function isNumber(inputArg) { return strictEqual(typeof inputArg, 'number'); } function isZero(inputArg) { return strictEqual(inputArg, 0); } function isString(inputArg) { return strictEqual(typeof inputArg, 'string'); } function isEmptyString(inputArg) { return strictEqual(inputArg, ''); } /* function isNumeric(inputArg) { var val = false, string; if (isNumber(inputArg) || isString(inputArg)) { string = inputArg.toString().replace(/^[+\-]?/, ""); if (!isNaN(parseFloat(string)) && isFinite(string)) { val = true; } } return val; } */ function checkObjectCoercible(inputArg) { if (isUndefined(inputArg) || isNull(inputArg)) { throw new TypeError('Cannot convert "' + inputArg + '" to object'); } return inputArg; } toObject = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe/ var CtrBoolean = baseBoolean.constructor, CtrNumber = baseNumber.constructor, CtrString = baseString.constructor, nfeToObject; tempSafariNFE = function nfeToObject(inputArg) { var object = checkObjectCoercible(inputArg); if (isBoolean(object)) { object = new CtrBoolean(object); } else if (isNumber(object)) { object = new CtrNumber(object); } else if (isString(object)) { object = new CtrString(object); } return object; }; nfeToObject = null; return tempSafariNFE; }()); // named anyToString instead of toString because of SpiderMonkey and Blackberry bug function anyToString(inputArg) { var val; if (isString(inputArg)) { val = inputArg; } else if (isUndefined(inputArg)) { val = 'undefined'; } else { val = String(inputArg); } return val; } toObjectString = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe/ var toStringFN = baseObject.toString, nfeToObjectString; try { if (strictEqual(toStringFN.call(), '[object Undefined]') && strictEqual(toStringFN.call(null), '[object Null]')) { tempSafariNFE = function nfeToObjectString(object) { return toStringFN.call(object); }; } } catch (exception) { tempSafariNFE = null; } if (isNull(tempSafariNFE)) { tempSafariNFE = function nfeToObjectString(object) { var val; if (isUndefined(object)) { val = '[object Undefined]'; } else if (isNull(object)) { val = '[object Null]'; } else { val = toStringFN.call(object); } return val; }; } nfeToObjectString = null; return tempSafariNFE; }()); function isRegExp(inputArg) { return strictEqual(toObjectString(inputArg), '[object RegExp]'); } function isObject(inputArg) { return strictEqual(toObjectString(inputArg), '[object Object]'); } function isFunction(inputArg) { return strictEqual(toObjectString(inputArg), '[object Function]'); } function isTypeObject(inputArg) { return (!isNull(inputArg) && strictEqual(typeof inputArg, 'object')) || isRegExp(inputArg); } // named arrayIsArray instead of isArray because of SpiderMonkey and Blackberry bug arrayIsArray = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe/ var isArrayFN = baseArray.isArray, nfeIsArray; if (isFunction(isArrayFN)) { tempSafariNFE = isArrayFN; } else { tempSafariNFE = function nfeIsArray(inputArg) { return strictEqual(toObjectString(inputArg), '[object Array]'); }; } nfeIsArray = null; return tempSafariNFE; }()); function isEmptyArray(inputArg) { var val; if (arrayIsArray(inputArg) || (isTypeObject(inputArg) && !isFunction(inputArg) && hasProperty(inputArg, 'length'))) { val = isZero(inputArg.length); } else { val = null; } return val; } function arrayFirst(inputArg) { var val; if (!isEmptyArray(inputArg)) { val = inputArg[0]; } return val; } function arrayLast(inputArg) { var val; if (!isEmptyArray(inputArg)) { val = inputArg[inputArg.length - 1]; } return val; } function isDate(inputArg) { return strictEqual(toObjectString(inputArg), '[object Date]'); } // named objectIs instead of objectIs because of SpiderMonkey and Blackberry bug objectIs = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe/ var isIsFn = baseObject.constructor.is, nfeIs; if (isFunction(isIsFn)) { tempSafariNFE = isIsFn; } else { tempSafariNFE = function nfeIs(x, y) { var val; if (strictEqual(x, y)) { if (isZero(x)) { val = strictEqual(1 / x, 1 / y); } else { val = true; } } else { val = !strictEqual(x, x) && !strictEqual(y, y); } return val; }; } nfeIs = null; return tempSafariNFE; }()); // named numberIsNaN instead of isNaN because of SpiderMonkey and Blackberry bug numberIsNaN = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe/ var isNaNFN = baseNumber.constructor.isNaN, nfeIsNaN; if (isFunction(isNaNFN)) { tempSafariNFE = isNaNFN; } else { tempSafariNFE = function nfeIsNaN(number) { return objectIs(number, NaN); }; } nfeIsNaN = null; return tempSafariNFE; }()); // named numberIsFinite instead of isFinite because of SpiderMonkey and Blackberry bug numberIsFinite = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe/ var isFiniteFN = baseNumber.constructor.isFinite, nfeIsFinite; if (isFunction(isFiniteFN)) { tempSafariNFE = isFiniteFN; } else { tempSafariNFE = function nfeIsFinite(number) { return isNumber(number) && isFinite(number); }; } nfeIsFinite = null; return tempSafariNFE; }()); // named mathSign instead of sign because of SpiderMonkey and Blackberry bug mathSign = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe/ var signFN = Math.sign, nfeSign; if (isFunction(signFN)) { tempSafariNFE = signFN; } else { tempSafariNFE = function nfeSign(value) { var number = toNumber(value), val; if (isZero(number) || numberIsNaN(number)) { val = number; } else if (lt(number, 0)) { val = -1; } else { val = 1; } return val; }; } nfeSign = null; return tempSafariNFE; }()); // named numberToInteger instead of toInteger because of SpiderMonkey and Blackberry bug numberToInteger = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe/ var toIntegerFN = Number.toInteger, nfeToInteger; if (isFunction(toIntegerFN)) { tempSafariNFE = toIntegerFN; } else { tempSafariNFE = function nfeToInteger(inputArg) { var number = toNumber(inputArg), val; if (numberIsNaN(number)) { val = +0; } else if (isZero(number) || !numberIsFinite(number)) { val = number; } else { val = mathSign(number) * Math.floor(Math.abs(number)); } return val; }; } nfeToInteger = null; return tempSafariNFE; }()); /* function toInt32(inputArg) { var number = toNumber(inputArg), int32bit, val; if (isZero(number) || !numberIsFinite(number)) { val = +0; } else { int32bit = mod(mathSign(number) * Math.floor(Math.abs(number)), UWORD32); if (gt(int32bit, UWORD32)) { val = int32bit - UWORD32; } else { val = int32bit; } } return val; } */ function toUint32(inputArg) { var number = toNumber(inputArg), val; if (isZero(number) || !numberIsFinite(number)) { val = +0; } else { val = mod(mathSign(number) * Math.floor(Math.abs(number)), UWORD32); } return val; } // named stringSplit instead of split because of SpiderMonkey and Blackberry bug stringSplit = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe/ var splitFN = baseString.split, compliantExecNpcg = isUndefined(/()??/.exec('')[1]), nfeSplit; function replacer(separator, match, args) { var length = args.length - 2, index; arrayFirst(match).replace(separator, function () { for (index = 1; lt(index, length); index += 1) { if (isUndefined(arguments[index])) { match[index] = privateUndefined; } } }); } tempSafariNFE = function nfeSplit(str, separator, limit) { var string = anyToString(checkObjectCoercible(str)), output, flags, lastLastIndex, separator2, match, lastIndex, lastLength, val; if (isRegExp(separator)) { flags = 'g'; if (separator.ignoreCase) { flags += 'i'; } if (separator.multiline) { flags += 'm'; } if (separator.extended) { flags += 'x'; } if (separator.sticky) { flags += 'y'; } separator = new RegExp(separator.source, flags); if (!compliantExecNpcg) { separator2 = new RegExp('^' + separator.source + '$(?!\\s)', flags); } if (isUndefined(limit)) { limit = MAX_UINT32; } else { limit = toUint32(limit); } output = []; flags = 'g'; lastLastIndex = 0; match = separator.exec(string); while (match) { lastIndex = match.index + arrayFirst(match).length; if (lastIndex > lastLastIndex) { output.push(string.slice(lastLastIndex, match.index)); if (!compliantExecNpcg && gt(match.length, 1)) { replacer(separator2, match, arguments); } if (gt(match.length, 1) && lt(match.index, string.length)) { output = output.concat(match.slice(1)); } lastLength = arrayFirst(match).length; lastLastIndex = lastIndex; if (gte(output.length, limit)) { break; } } if (strictEqual(separator.lastIndex, match.index)) { separator.lastIndex += 1; } match = separator.exec(string); } if (strictEqual(lastLastIndex, string.length)) { if (lastLength || !separator.test('')) { output.push(''); } } else { output.push(string.slice(lastLastIndex)); } if (gt(output.length, limit)) { return output.slice(0, limit); } val = output; } else { val = splitFN.call(str, separator, limit); } return val; }; nfeSplit = null; return tempSafariNFE; }()); function firstChar(inputArg) { return anyToString(checkObjectCoercible(inputArg)).charAt(0); } function firstCharIs(inputArg, character) { return strictEqual(firstChar(inputArg), firstChar(character)); } function lastChar(inputArg) { var thisStr = anyToString(checkObjectCoercible(inputArg)); return thisStr.charAt(thisStr.length - 1); } function lastCharIs(inputArg, character) { return strictEqual(lastChar(inputArg), firstChar(character)); } function countCharacter(inputArg, character) { return clamp(stringSplit(anyToString(checkObjectCoercible(inputArg)), firstChar(character)).length - 1, 0, Number.POSITIVE_INFINITY); } function padLeadingChar(inputArg, character, size) { var string = anyToString(checkObjectCoercible(inputArg)), singleChar = firstChar(character), count = numberToInteger(size) - string.length; if (lt(count, 0) || strictEqual(count, Infinity)) { count = 0; } return stringRepeat(singleChar, count) + string; } // named stringRepeat instead of repeat because of SpiderMonkey and Blackberry bug stringRepeat = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var repeatFN = baseString.constructor.repeat, nfeRepeat; function rep(s, times) { var half, val; if (lt(times, 1)) { val = ''; } else if (mod(times, 2)) { val = rep(s, times - 1) + s; } else { half = rep(s, times / 2); val = half + half; } return val; } if (isFunction(repeatFN)) { tempSafariNFE = function nfeRepeat(string, times) { return repeatFN.call(string, times); }; } else { tempSafariNFE = function nfeRepeat(string, count) { var thisString = anyToString(checkObjectCoercible(string)), times = numberToInteger(count); if (lt(times, 0) || strictEqual(times, Infinity)) { throw new RangeError(); } return rep(thisString, times); }; } nfeRepeat = null; return tempSafariNFE; }()); /* // named stringStartsWith instead of startsWith because of SpiderMonkey and Blackberry bug stringStartsWith = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var startsWithFN = baseString.constructor.startsWith, nfeStartsWith; if (isFunction(startsWithFN)) { tempSafariNFE = function nfeStartsWith(string, searchString, position) { return startsWithFN.call(string, searchString, position); }; } else { tempSafariNFE = function nfeStartsWith(string, searchString, position) { var thisStr = anyToString(checkObjectCoercible(string)), searchStr = anyToString(searchString), thisLen = thisStr.length, start = clamp(toInteger(position), 0, thisLen); return strictEqual(thisStr.slice(start, start + thisLen), searchStr); }; } nfeStartsWith = null; return tempSafariNFE; }()); */ /* // named stringEndsWith instead of endsWith because of SpiderMonkey and Blackberry bug stringEndsWith = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var endsWithFN = baseString.constructor.endsWith, nfeEndsWith; if (isFunction(endsWithFN)) { tempSafariNFE = function nfeEndsWith(string, searchString, position) { return endsWithFN.call(string, searchString, position); }; } else { tempSafariNFE = function nfeEndsWith(string, searchString, position) { var thisStr = anyToString(checkObjectCoercible(string)), searchStr = anyToString(searchString), thisLen = thisStr.length, end, start; if (isUndefined(position)) { position = thisLen; } else { position = toInteger(position); } end = clamp(position, 0, thisLen); start = end - searchStr.length; return gte(start, 0) && strictEqual(thisStr.slice(start, end), searchStr); }; } nfeEndsWith = null; return tempSafariNFE; }()); */ // named stringContains instead of contains because of SpiderMonkey and Blackberry bug stringContains = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var containsFN = baseString.constructor.contains, nfeContains; if (isFunction(containsFN)) { tempSafariNFE = function nfeContains(string, searchString, position) { return containsFN.call(string, searchString, position); }; } else { tempSafariNFE = function nfeContains(string, searchString, position) { var thisStr = anyToString(checkObjectCoercible(string)), searchStr = anyToString(searchString), thisLen = thisStr.length; if (isUndefined(position)) { position = 0; } else { position = numberToInteger(position); } return !strictEqual(baseString.indexOf.call(thisStr, searchStr, clamp(position, 0, thisLen)), -1); }; } nfeContains = null; return tempSafariNFE; }()); // named objectGetPrototypeOf instead of getPrototypeOf because of SpiderMonkey and Blackberry bug objectGetPrototypeOf = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var getPrototypeOfFN = baseObject.constructor.getPrototypeOf, nfeGetPrototypeOf, bocProto; if (isFunction(getPrototypeOfFN)) { tempSafariNFE = getPrototypeOfFN; } else if (isNull(baseObject.constructor.prototype[protoName])) { tempSafariNFE = function nfeGetPrototypeOf(object) { return object[protoName]; }; } else { bocProto = baseObject.constructor.prototype; tempSafariNFE = function nfeGetPrototypeOf(object) { if (strictEqual(object, bocProto)) { return null; } var ctrProto = object.constructor.prototype; if (strictEqual(object, ctrProto)) { return bocProto; } return ctrProto; }; } nfeGetPrototypeOf = null; return tempSafariNFE; }()); hasProperty = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var nfeHasProperty; tempSafariNFE = function nfehasProperty(object, property) { return property in object; }; nfeHasProperty = null; return tempSafariNFE; }()); function arrayContains(array, searchElement) { return !strictEqual(arrayIndexOf(array, searchElement), -1); } // http://ecma-international.org/ecma-262/5.1/#sec-15.2.4.5 // Create our own local "hasOwnProperty" function: native -> shim -> sham // named objectHasOwnProperty instead of hasOwnProperty because of SpiderMonkey and Blackberry bug objectHasOwnProperty = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var hasOwnPropertyFN = baseObject.hasOwnProperty, // to combat old IE8- issues, min support IE6 propertyIsEnumerableFN = baseObject.propertyIsEnumerable, hasDontEnumBug = true, testObject = { toString: null }, nfeHasOwnProperty; // use nfeHasOwnProperty to save a var for (nfeHasOwnProperty in testObject) { if (strictEqual(nfeHasOwnProperty, 'toString') && isNull(testObject[nfeHasOwnProperty])) { hasDontEnumBug = false; } } function checkDontEnums(object, property) { return hasDontEnumBug && arrayContains(defaultProperties, property) && hasProperty(object, property) && !strictEqual(object[property], objectGetPrototypeOf(object)[property]); } if (isFunction(hasOwnPropertyFN)) { tempSafariNFE = function nfeHasOwnProperty(object, property) { return hasOwnPropertyFN.call(object, property) || checkDontEnums(object, property); }; } else if (isFunction(propertyIsEnumerableFN)) { tempSafariNFE = function nfeHasOwnProperty(object, property) { return propertyIsEnumerableFN.call(object, property) || checkDontEnums(object, property); }; } else { tempSafariNFE = function nfeHasOwnProperty(object, property) { return hasProperty(object, property) && isUndefined(objectGetPrototypeOf(object)[property]); }; } nfeHasOwnProperty = null; return tempSafariNFE; }()); toObjectFixIndexedAccess = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var boxedString = baseObject.constructor('a'), splitString = !strictEqual(boxedString[0], 'a') || !hasProperty(boxedString, 0), nfeToObjectFixIndexedAccess; if (splitString) { tempSafariNFE = function nfeToObjectFixIndexedAccess(inputArg) { var object; if (isString(inputArg)) { object = stringSplit(inputArg, ''); } else { object = toObject(inputArg); } return object; }; } else { tempSafariNFE = toObject; } nfeToObjectFixIndexedAccess = null; return tempSafariNFE; }()); // named arrayForEach instead of forEach because of SpiderMonkey and Blackberry bug arrayForEach = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var forEachFN = baseArray.forEach, nfeForEach; if (isFunction(forEachFN)) { tempSafariNFE = function nfeForEach(array, fn, thisArg) { return forEachFN.call(array, fn, thisArg); }; } else { tempSafariNFE = function nfeForEach(array, fn, thisArg) { var object = toObjectFixIndexedAccess(array), length, index; if (!isFunction(fn)) { throw new TypeError(fn + ' is not a function'); } for (index = 0, length = toUint32(object.length); lt(index, length); index += 1) { if (hasProperty(object, index)) { fn.call(thisArg, object[index], index, object); } } }; } nfeForEach = null; return tempSafariNFE; }()); // named arraySome instead of some because of SpiderMonkey and Blackberry bug arraySome = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var someFN = baseArray.some, nfeSome; if (isFunction(someFN)) { tempSafariNFE = function nfeSome(array, fn, thisArg) { return someFN.call(array, fn, thisArg); }; } else { tempSafariNFE = function nfeSome(array, fn, thisArg) { var object = toObjectFixIndexedAccess(array), length, index, val; if (!isFunction(fn)) { throw new TypeError(fn + ' is not a function'); } for (index = 0, length = toUint32(object.length), val = false; lt(index, length); index += 1) { if (hasProperty(object, index) && fn.call(thisArg, object[index], index, object)) { val = true; break; } } return val; }; } nfeSome = null; return tempSafariNFE; }()); // named arrayMap instead of map because of SpiderMonkey and Blackberry bug arrayMap = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var mapFN = baseArray.map, nfeMap; if (isFunction(mapFN)) { tempSafariNFE = function nfeMap(array, fn, thisArg) { return mapFN.call(array, fn, thisArg); }; } else { tempSafariNFE = function nfeMap(array, fn, thisArg) { var object = toObjectFixIndexedAccess(array), length, index, arr; if (!isFunction(fn)) { throw new TypeError(fn + ' is not a function'); } for (index = 0, length = toUint32(object.length), arr = []; lt(index, length); index += 1) { arr[index] = fn.call(thisArg, object[index], index, object); } return arr; }; } nfeMap = null; return tempSafariNFE; }()); /* function returnElement(element) { return element; } */ /* function argumentsToArray(args) { return arrayMap(args, returnElement); } */ // named arrayUnshift instead of unshift because of SpiderMonkey and Blackberry bug /* arrayUnshift = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var unshiftFN = baseArray.unshift, nfeUnshift; if (strictEqual(unshiftFN.call([], 0), 1)) { tempSafariNFE = function nfeUnshift(array) { return unshiftFN.apply(array, argumentsToArray(arguments).slice(1)); }; } else { tempSafariNFE = function nfeUnshift(array) { unshiftFN.apply(array, argumentsToArray(arguments).slice(1)); return array.length; }; } nfeUnshift = null; return tempSafariNFE; }()); */ /* // named arrayFilter instead of filter because of SpiderMonkey and Blackberry bug arrayFilter = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var filterFN = baseArray.filter, nfeFilter; if (isFunction(filterFN)) { tempSafariNFE = function nfeFilter(array, fn, thisArg) { return filterFN.call(array, fn, thisArg); }; } else { tempSafariNFE = function nfeFilter(array, fn, thisArg) { var object = toObjectFixIndexedAccess(array), length, arr, index, element; if (!isFunction(fn)) { throw new TypeError(fn + " is not a function"); } for (index = 0, length = toUint32(object.length), arr = []; lt(index, length); index += 1) { element = object[index]; if (fn.call(thisArg, element, index, object)) { arr[index] = element; } } return arr; }; } nfeFilter = null; return tempSafariNFE; }()); */ // named arrayReduce instead of reduce because of SpiderMonkey and Blackberry bug arrayReduce = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var reduceFN = baseArray.reduce, errString = 'Reduce of empty array with no initial value', nfeReduce; if (isFunction(reduceFN)) { tempSafariNFE = function nfeReduce(array, fn, initialValue) { return reduceFN.call(array, fn, initialValue); }; } else { tempSafariNFE = function nfeReduce(array, fn, initialValue) { var object = toObjectFixIndexedAccess(array), length, k, index, accumulator, kPresent; if (!isFunction(fn)) { throw new TypeError(fn + ' is not a function'); } if (isZero(length) && lt(arguments.length, 3)) { throw new TypeError(errString); } k = 0; if (gt(arguments.length, 2)) { accumulator = initialValue; } else { for (k = 0, length = toUint32(object.length), kPresent = false; !kPresent && lt(k, length); k += 1) { kPresent = hasProperty(object, k); if (kPresent) { accumulator = object[k]; } } if (!kPresent) { throw new TypeError(errString); } } for (index = k; lt(index, length); index += 1) { if (hasProperty(object, index)) { accumulator = fn.call(privateUndefined, accumulator, object[index], index, object); } } return accumulator; }; } nfeReduce = null; return tempSafariNFE; }()); // named stringTrim instead of trim because of SpiderMonkey and Blackberry bug stringTrim = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe/ var trimFN = baseString.constructor.trim, whiteSpacesList = [ 0x0009, // Tab 0x000a, // Line Feed 0x000b, // Vertical Tab 0x000c, // Form Feed 0x000d, // Carriage Return 0x0020, // Space 0x0085, // Next line 0x00a0, // No-break space 0x1680, // Ogham space mark 0x180e, // Mongolian vowel separator 0x2000, // En quad 0x2001, // Em quad 0x2002, // En space 0x2003, // Em space 0x2004, // Three-per-em space 0x2005, // Four-per-em space 0x2006, // Six-per-em space 0x2007, // Figure space 0x2008, // Punctuation space 0x2009, // Thin space 0x200a, // Hair space 0x200b, // Zero width space 0x2028, // Line separator 0x2029, // Paragraph separator 0x202f, // Narrow no-break space 0x205f, // Medium mathematical space 0x3000, // Ideographic space 0xfeff // Byte Order Mark ], testString, whiteSpacesString, wsTrimRX, nfeTrim, nfeBuildTestString, nfeBuildWhiteSpaceString; tempSafariNFE = function nfeBuildTestString(previous, element) { return previous + String.fromCharCode(element); }; testString = arrayReduce(whiteSpacesList, tempSafariNFE, ''); if (isFunction(trimFN) && isZero(trimFN.call(testString).length)) { tempSafariNFE = function nfeTrim(inputArg) { return trimFN.call(inputArg); }; } else { tempSafariNFE = function nfeBuildWhiteSpaceString(previous, element) { return previous + '\\u' + padLeadingChar(element.toString(16), '0', 4); }; whiteSpacesString = arrayReduce(whiteSpacesList, tempSafariNFE, ''); wsTrimRX = new RegExp('^[' + whiteSpacesString + ']+|[' + whiteSpacesString + ']+$', 'g'); tempSafariNFE = function nfeTrim(inputArg) { return anyToString(checkObjectCoercible(inputArg)).replace(wsTrimRX, ''); }; } nfeTrim = null; nfeBuildTestString = null; nfeBuildWhiteSpaceString = null; return tempSafariNFE; }()); // http://ecma-international.org/ecma-262/5.1/#sec-15.4.4.14 // Create our own local "indexOf" function: native -> polyfill // named arrayIndexOf instead of indexOf because of SpiderMonkey and Blackberry bug arrayIndexOf = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var indexOfFN = baseArray.indexOf, nfeIndexOf; if (isFunction(indexOfFN) && strictEqual(indexOfFN.call([0, 1], 1, 2), 1)) { tempSafariNFE = function nfeIndexOf(array, searchElement, fromIndex) { return indexOfFN.call(array, searchElement, fromIndex); }; } else { tempSafariNFE = function nfeIndexOf(array, searchElement, fromIndex) { var object = toObjectFixIndexedAccess(array), length = toUint32(object.length), index, start, val; if (isZero(length)) { val = -1; } else { if (gt(arguments.length, 2)) { fromIndex = numberToInteger(fromIndex); } else { fromIndex = 0; } if (gte(fromIndex, length)) { val = -1; } else { if (gte(fromIndex, 0)) { start = fromIndex; } else { start = length - Math.abs(fromIndex); } if (lt(start, 0)) { start = 0; } for (index = start, val = -1; lt(index, length); index += 1) { if (hasProperty(object, index) && strictEqual(searchElement, object[index])) { val = index; break; } } } } return val; }; } nfeIndexOf = null; return tempSafariNFE; }()); // named objectKeys instead of keys because of SpiderMonkey and Blackberry bug objectKeys = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var keysFN = baseObject.keys, nfeKeys; if (isFunction(keysFN)) { tempSafariNFE = keysFN; } else { tempSafariNFE = function nfeKeys(object) { if (!isTypeObject(object) && !isFunction(object)) { throw new TypeError('Object.keys called on a non-object'); } var props = [], prop; for (prop in object) { if (objectHasOwnProperty(object, prop)) { props.push(prop); } } return props; }; } nfeKeys = null; return tempSafariNFE; }()); // http://ecma-international.org/ecma-262/5.1/#sec-15.4.4.14 // Create our own local "defineProperty" function: native -> sham // named objectDefineProperty instead of defineProperty because of SpiderMonkey and Blackberry bug objectDefineProperty = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var definePropertyFN = baseObject.constructor.defineProperty, defineGetter = '__defineGetter__', defineSetter = '__defineSetter__', defineGetterFN, defineSetterFN, testObject, nfeDefineProperty; if (isFunction(definePropertyFN)) { try { testObject = definePropertyFN({}, 'sentinel', { value: null }); if (!isNull(testObject.sentinel)) { definePropertyFN = null; } } catch (exception) { definePropertyFN = null; } } if (isFunction(definePropertyFN)) { tempSafariNFE = definePropertyFN; } else { defineGetterFN = baseObject[defineGetter]; defineSetterFN = baseObject[defineSetter]; tempSafariNFE = function nfeDefineProperty(object, property, descriptor) { var prototype; if (!isTypeObject(object) && !isFunction(object)) { throw new TypeError('Object.defineProperty called on non-object'); } if (!isTypeObject(descriptor) && !isFunction(descriptor)) { throw new TypeError('Property description must be an object'); } if (objectHasOwnProperty(descriptor, 'value')) { if (isNull(objectGetPrototypeOf(baseObject)[protoName])) { prototype = object[protoName]; object[protoName] = objectGetPrototypeOf(baseObject); delete object[property]; object[property] = descriptor.value; object[protoName] = prototype; } else { object[property] = descriptor.value; } } else { if (!isFunction(defineGetterFN) || !isFunction(defineSetterFN)) { throw new TypeError('getters & setters can not be defined on this javascript engine'); } if (isFunction(descriptor.get)) { defineGetterFN.call(object, property, descriptor.get); } if (isFunction(descriptor.set)) { defineSetterFN.call(object, property, descriptor.set); } } return object; }; } nfeDefineProperty = null; return tempSafariNFE; }()); // Create our own local "defineProperties" function: native -> sham // named objectDefineProperties instead of defineProperties because of SpiderMonkey and Blackberry bug objectDefineProperties = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var definePropertiesFN = baseObject.constructor.defineProperties, nfeDefineProperties; if (isFunction(definePropertiesFN)) { tempSafariNFE = definePropertiesFN; } else { tempSafariNFE = function nfeDefineProperties(object, props) { if (!isTypeObject(object) && !isFunction(object)) { throw new TypeError('Object.defineProperties called on non-object'); } if (!isTypeObject(props) && !isFunction(props)) { throw new TypeError('Property description must be an object'); } arrayForEach(objectKeys(props), function (key) { objectDefineProperty(object, key, props[key]); }); return object; }; } nfeDefineProperties = null; return tempSafariNFE; }()); // Create our own local "getOwnPropertyDescriptor" function: native -> sham // named objectGetOwnPropertyDescriptor instead of getOwnPropertyDescriptor because of SpiderMonkey and Blackberry bug objectGetOwnPropertyDescriptor = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var getOwnPropertyDescriptorFN = baseObject.constructor.getOwnPropertyDescriptor, lookupGetter = '__lookupGetter__', lookupSetter = '__lookupSetter__', lookupGetterFN, lookupSetterFN, testObject, nfeGetOwnPropertyDescriptor; if (isFunction(getOwnPropertyDescriptorFN)) { try { testObject = { sentinel: null }; if (!isNull(getOwnPropertyDescriptorFN(testObject, 'sentinel').value)) { getOwnPropertyDescriptorFN = null; } } catch (exception) { getOwnPropertyDescriptorFN = null; } } if (isFunction(getOwnPropertyDescriptorFN)) { tempSafariNFE = getOwnPropertyDescriptorFN; } else { lookupGetterFN = baseObject[lookupGetter]; lookupSetterFN = baseObject[lookupSetter]; tempSafariNFE = function nfeGetOwnPropertyDescriptor(object, property) { var descriptor, prototype, getter, setter; if (!isTypeObject(object) && !isFunction(object)) { throw new TypeError('Object.getOwnPropertyDescriptor called on a non-object'); } if (objectHasOwnProperty(object, property)) { descriptor = { enumerable: true, configurable: true }; if (isFunction(lookupGetterFN) && isFunction(lookupSetterFN)) { prototype = object[protoName]; object[protoName] = objectGetPrototypeOf(baseObject); getter = lookupGetterFN.call(object, property); setter = lookupSetterFN.call(object, property); object[protoName] = prototype; if (isFunction(getter) || isFunction(setter)) { if (isFunction(getter)) { descriptor.get = getter; } if (isFunction(setter)) { descriptor.set = setter; } } } else { descriptor.value = object[property]; descriptor.writable = true; } } return descriptor; }; } nfeGetOwnPropertyDescriptor = null; return getOwnPropertyDescriptorFN; }()); // Create our own local "freeze" function: native -> sham // named objectFreeze instead of freeze because of SpiderMonkey and Blackberry bug objectFreeze = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var freezeFN = baseObject.constructor.freeze, nfeFreeze; if (isFunction(freezeFN)) { tempSafariNFE = freezeFN; } else { tempSafariNFE = function nfeFreeze(object) { if (!isTypeObject(object) && !isFunction(object)) { throw new TypeError('Object.freeze called on non-object'); } return object; }; } nfeFreeze = null; return tempSafariNFE; }()); // detect a Rhino bug and patch it try { objectFreeze(function () { return; }); } catch (exception) { objectFreeze = (function (freezeObject) { var nfeFreeze; tempSafariNFE = function nfeFreeze(object) { var val; if (isFunction(object)) { val = object; } else { val = freezeObject(object); } return val; }; nfeFreeze = null; return tempSafariNFE; }(objectFreeze)); } // Create our own local "isFrozen" function: native -> sham // named objectIsFrozen instead of isFrozen because of SpiderMonkey and Blackberry bug objectIsFrozen = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var isFrozenFN = baseObject.constructor.isFrozen, nfeIsFrozen; if (isFunction(isFrozenFN)) { tempSafariNFE = isFrozenFN; } else { tempSafariNFE = function nfeIsFrozen(object) { if (!isTypeObject(object) && !isFunction(object)) { throw new TypeError('Object.isFrozen called on non-object'); } return false; }; } nfeIsFrozen = null; return tempSafariNFE; }()); function deepFreeze(object) { objectFreeze(object); arrayForEach(objectKeys(object), function (propKey) { var prop = object[propKey]; if ((isTypeObject(prop) || isFunction(prop)) && !objectIsFrozen(prop)) { deepFreeze(prop); } }); } // named objectInstanceOf instead of instanceOf because of SpiderMonkey and Blackberry bug objectInstanceOf = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var isPrototypeOfFN = baseObject.constructor.prototype.isPrototypeOf, nfeInstanceOf; if (isFunction(isPrototypeOfFN)) { tempSafariNFE = function nfeInstanceOf(object, ctr) { if (!isFunction(ctr)) { throw new TypeError('Expecting a function in instanceOf check'); } return isPrototypeOfFN.call(ctr.prototype, object); }; } else if (isFunction(objectGetPrototypeOf)) { tempSafariNFE = function nfeInstanceOf(object, ctr) { if (!isFunction(ctr)) { throw new TypeError('Expecting a function in instanceOf check'); } var val = false; while (object) { if (strictEqual(object, ctr.prototype)) { val = true; break; } object = objectGetPrototypeOf(object); } return val; }; } nfeInstanceOf = null; return tempSafariNFE; }()); isPlainObject = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var baseObjectPrototype = objectGetPrototypeOf(baseObject), nfeIsPlainObject; tempSafariNFE = function nfeIsPlainObject(object) { return isObject(object) && strictEqual(objectGetPrototypeOf(object), baseObjectPrototype); }; nfeIsPlainObject = null; return tempSafariNFE; }()); extend = (function () { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var nfeExtend; tempSafariNFE = function nfeExtend(target, source) { if (!isTypeObject(target) && !isFunction(target)) { throw new TypeError('extend called on a non-object'); } arrayForEach(objectKeys(source), function (key) { objectDefineProperty(target, key, objectGetOwnPropertyDescriptor(source, key)); }); return target; }; nfeExtend = null; return tempSafariNFE; }()); function bnZero() { return new BigNumber(0); } function bnOne() { return new BigNumber(1); } objectDefineProperties(BigNumber.prototype, { trunc: { value: function () { return this.round(0, 1); } }, inRange: { value: function (min, max) { return this.gte(min) && this.lte(max); } }, modf: { value: function () { var bn = this; if (bn.isFinite()) { bn = bn.mod(bn.trunc()); } else { bn = new BigNumber(NaN); } return bn; } }, difference: { value: function (value) { var diff; if (this.gt(value)) { diff = this.minus(value); } else { diff = this.neg().plus(value); } return diff; } }, factorial: { value: (function () { var factorialLookup = {}; return function (exponentialAt) { var n, config, previousConfig, i, val; if (this.lt(0) || !this.isFinite() || !this.modf().isZero()) { val = new BigNumber(NaN); } else { if (!isNumber(exponentialAt) && !isString(exponentialAt) && (BigNumber.isBigNumber(exponentialAt) && (exponentialAt.lt(0) || !exponentialAt.isFinite()))) { exponentialAt = new BigNumber(BigNumber.config().EXPONENTIAL_AT[1]); } if (!BigNumber.isBigNumber(exponentialAt)) { exponentialAt = new BigNumber(exponentialAt); } n = this.toString(); if (!factorialLookup[n]) { config = new BigNumber.config(); previousConfig = {}; extend(previousConfig, config); BigNumber.config({ DECIMAL_PLACES: 20, ROUNDING_MODE: 4, EXPONENTIAL_AT: [-7, parseInt(exponentialAt.toString(), 10)], RANGE: [-1000000000, 1000000000], ERRORS: true }); factorialLookup[n] = bnOne(); for (i = 2; lte(i, n); i += 1) { factorialLookup[n] = factorialLookup[n].times(i); } extend(config, previousConfig); } val = factorialLookup[n]; } return val; }; }()) }, toRadians: { value: function (decimalPlacesOfPI) { return this.times(BigNumber.pi(decimalPlacesOfPI).div(180)); } }, padLeadingZero: { value: function (size) { return padLeadingChar(this.toString(), '0', size); } } }); objectDefineProperties(BigNumber, { isBigNumber: { value: function (inputArg) { return isObject(inputArg) && objectInstanceOf(inputArg, BigNumber); } }, trunc: { value: function (number) { return new BigNumber(number).trunc(); } }, modf: { value: function (number) { return new BigNumber(number).modf(); } }, difference: { value: function (number1, number2) { return new BigNumber(number1).difference(number2); } }, factorial: { value: function (number, exponentialAt) { return new BigNumber(number).factorial(exponentialAt); } }, pi: { value: (function () { var piLookup = {}; return function (decimalPlaces) { if (!numberIsFinite(decimalPlaces) || lt(decimalPlaces, 0)) { decimalPlaces = new BigNumber.config().DECIMAL_PLACES; } else { decimalPlaces = Math.floor(decimalPlaces); } var lookupProp = decimalPlaces.toString(), config, previousConfig, k = 0, sum, ta, tb, divisor, a, b; if (!piLookup[lookupProp]) { config = new BigNumber.config(); previousConfig = {}; extend(previousConfig, config); BigNumber.config({ DECIMAL_PLACES: decimalPlaces, ROUNDING_MODE: 4, EXPONENTIAL_AT: [-7, 20], RANGE: [-1000000000, 1000000000], ERRORS: true }); sum = bnZero(); a = ta = new BigNumber(16).div(5); b = tb = new BigNumber(-4).div(239); while (!a.equals(b)) { divisor = k * 2 + 1; a = ta.div(divisor); b = tb.div(divisor); sum = sum.plus(a).plus(b); ta = ta.neg().div(25); tb = tb.neg().div(57121); k += 1; } extend(config, previousConfig); piLookup[lookupProp] = sum; } return piLookup[lookupProp]; }; }()) }, toRadians: { value: function (number, decimalPlacesPI) { return new BigNumber(number).toRadians(decimalPlacesPI); } }, normaliseAngle: { value: function (angle) { var newAngle = new BigNumber(angle); while (newAngle.lt(-360)) { newAngle = newAngle.plus(360); } while (newAngle.gt(360)) { newAngle = newAngle.minus(360); } return newAngle; } }, toPositiveAngle: { value: function (angle) { var newAngle = new BigNumber.normaliseAngle(angle); if (lt(newAngle, 0)) { newAngle = newAngle.plus(360); } return newAngle; } }, sin: { value: (function () { var sineLookup = {}; return function (angle) { var newAngle = new BigNumber.normaliseAngle(angle), lookupProp = newAngle.toString(), sum, prev, k, fact, i; if (!sineLookup[lookupProp]) { sum = newAngle; prev = bnZero(); i = 1; k = 3; while (!sum.equals(prev)) { prev = sum; fact = new BigNumber.factorial(k); if (strictEqual(mod(mod(i, 2), 2), 1)) { sum = sum.minus(newAngle.pow(k).div(fact)); } else { sum = sum.plus(newAngle.pow(k).div(fact)); } i += 1; k += 2; } sineLookup[lookupProp] = sum; } return sineLookup[lookupProp]; }; }()) } }); /* function InvalidError(message) { //this.name = "InvalidError"; this.message = message || ""; } InvalidError.prototype = new Error(); function NotImplimentedError(message) { //this.name = "NotImplementedError"; this.message = message || ""; } NotImplimentedError.prototype = new Error(); */ function isDateValid(dateObject) { return isDate(dateObject) && !numberIsNaN(dateObject.getTime()); } function isGregorianLeapYear(struct) { return struct.year.mod(400).isZero() || (!struct.year.mod(100).isZero() && struct.year.mod(4).isZero()); } function isJulianLeapYear(struct) { return struct.year.mod(4).equals(0); } function daysInGregorianMonth(struct) { var days; if (struct.month.eq(2)) { days = new BigNumber(28); if (isGregorianLeapYear(struct)) { days = days.plus(1); } } else { days = struct.month.minus(1).mod(7).mod(2).neg().plus(31); } return days; } function daysInJulianMonth(struct) { var days = new BigNumber(28); if (struct.month.eq(2) && isJulianLeapYear(struct)) { days = days.plus(1); } return days; } function daysInGregorianYear(struct) { var days = new BigNumber(365); if (isGregorianLeapYear(struct)) { days = days.plus(1); } return days; } function daysInJulianYear(struct) { var days = new BigNumber(365); if (isJulianLeapYear(struct)) { days = days.plus(1); } return days; } function inYearRange(year) { return year.isFinite(); } function inMonthRange(month) { return month.inRange(1, 12); } function inDayRange(day, dim) { return day.inRange(1, dim); } function inHourRange(hour) { return hour.inRange(0, 24); } function inMinuteRange(minute, hour) { return (hour.equals(24) && minute.isZero()) || (!hour.equals(24) && minute.gte(0) && minute.lt(60)); } function inSecondRange(second, struct) { var maxSecond = 60, leapSecond; if (struct.year.gte(1961) && struct.hour.equals(23) && struct.minute.equals(59)) { if (!isPlainObject(leapSeconds)) { throw new Error('No leap second table!'); } leapSecond = leapSeconds[struct.year.toString()]; if (isPlainObject(leapSecond)) { leapSecond = leapSecond[struct.month.toString()]; if (isPlainObject(leapSecond)) { leapSecond = toNumber(leapSecond[struct.day.toString()]); if (numberIsFinite(leapSecond)) { maxSecond += leapSecond; } } } } return (struct.hour.equals(24) && second.isZero()) || (!struct.hour.equals(24) && second.gte(0) && second.lt(maxSecond)); } function inMillisecondRange(millisecond, hour) { return (hour.equals(24) && millisecond.isZero()) || (!hour.equals(24) && millisecond.gte(0) && millisecond.lt(1000)); } function inOffsetRange(offset) { return offset.inRange(-1440, 1440); } /* function inWeekRange(week, year) { return offset.inRange(1, 53); } function inWeekDayRange(weekDay) { return weekDay.inRange(1, 7); } */ function isValid(struct, julian) { var valid = false; if (isPlainObject(struct)) { valid = !arraySome(fullKeys, function (element) { var bn = struct[element.full], dim; if (!BigNumber.isBigNumber(bn)) { return true; } switch (element.full) { case 'year': if (!inYearRange(bn)) { return true; } break; case 'month': if (!inMonthRange(bn)) { return true; } break; case 'day': if (strictEqual(julian, true)) { dim = daysInJulianMonth(struct); } else { dim = daysInGregorianMonth(struct); } if (!inDayRange(bn, dim)) { return true; } break; case 'hour': if (!inHourRange(bn)) { return true; } break; case 'minute': if (!inMinuteRange(bn, struct.hour)) { return true; } break; case 'second': if (!inSecondRange(bn, struct)) { return true; } break; case 'millisecond': if (!inMillisecondRange(bn, struct.hour)) { return true; } break; case 'offset': if (!inOffsetRange(bn)) { return true; } break; /* case 'week': if (!inWeekRange(bn)) { return true; } break; case 'weekDay': if (!inWeekDayRange(bn)) { return true; } break; */ default: throw new Error(element.full); } return false; }); } return valid; } function dayOfGregorianYear(struct) { var k; if (isGregorianLeapYear(struct)) { k = 1; } else { k = 2; } return struct.month.times(275).div(9).floor().minus(struct.month.plus(9).div(12).floor().times(k)).plus(struct.day).minus(30); } function dayOfJulianYear(struct) { var doy = struct.month.times(28).plus(struct.day); if (struct.month.gte(2) && isJulianLeapYear(struct)) { doy = doy.plus(1); } return doy; } function normaliseUnits(unitString) { var unit; if (isString(unitString)) { unitString = stringTrim(unitString).toLowerCase(); if (gt(unitString.length, 2) && lastCharIs(unitString, 's')) { unitString = unitString.slice(0, -1); } arraySome(fullKeys, function (element) { var val; if (strictEqual(unitString, element.alias) || strictEqual(unitString, element.full)) { unit = element.full; val = true; } else { val = false; } return val; }); } return unit; } function timeTo(struct, unit) { var value; switch (normaliseUnits(unit)) { case 'day': value = struct.hour.div(24).plus(struct.minute.div(1440)).plus(struct.second.div(86400)).plus(struct.millisecond.div(86400000)); break; case 'hour': value = struct.hour.plus(struct.minute.div(60)).plus(struct.second.div(3600)).plus(struct.millisecond.div(3600000)); break; case 'minute': value = struct.hour.times(60).plus(struct.minute).plus(struct.second.div(60)).plus(struct.millisecond.div(60000)); break; case 'second': value = struct.hour.times(3600).plus(struct.minute.times(60)).plus(struct.second).plus(struct.millisecond.div(1000)); break; case 'millisecond': value = struct.hour.times(3600000).plus(struct.minute.times(60000)).plus(struct.second.times(1000)).plus(struct.millisecond); break; default: throw new Error(unit); } return value; } function gregorianToJd(struct) { var b = struct.year.minus(1), c = b.times(365), d = b.div(4).floor(), e = b.div(100).floor().neg(), f = b.div(400).floor(), g = struct.month.times(367).minus(362).div(12).floor(), h; if (struct.month.gt(2)) { if (isGregorianLeapYear(struct)) { h = -1; } else { h = -2; } } else { h = 0; } return new BigNumber(1721424.5).plus(c).plus(d).plus(e).plus(f).plus(g.plus(h).plus(struct.day).floor()).plus(timeTo(struct, 'day')); } /* function gregorianToJdn(struct) { return gregorianToJd(struct).trunc(); } */ function objectValues(inputArg, order) { var val; if (arrayIsArray(order)) { val = order; } else { val = objectKeys(inputArg); } return arrayMap(val, function (key) { return inputArg[key]; }); } function makeNamesMin(objectNames, order) { var arrayNames = objectValues(objectNames, order), arrayMinNames = [], count = 0, maxLength = 0, arrayNamesLength = arrayNames.length; function sliceCountCompare(element) { var characters = element.slice(0, count + 1), ret; if (arrayContains(arrayMinNames, characters)) { ret = true; } else { arrayMinNames.push(characters); ret = false; } return ret; } arrayForEach(arrayNames, function (element) { var length = element.length; if (gt(length, maxLength)) { maxLength = length; } }); while (!strictEqual(arrayMinNames.length, arrayNamesLength) && lt(count, maxLength)) { arrayMinNames.length = 0; arraySome(arrayNames, sliceCountCompare); count += 1; } return arrayMinNames; } nameTypes = ['format', 'stand-alone']; deepFreeze(nameTypes); widthTypes = ['wide', 'abbreviated', 'short', 'narrow']; widthTypeShort = widthTypes[2]; deepFreeze(widthTypes); function makeNamesArray(name, type, width, lang, order) { var val; if (!isString(type) || isEmptyString(type) || !arrayContains(nameTypes, type)) { type = arrayLast(nameTypes); } if (!isString(width) || isEmptyString(width) || !arrayContains(widthTypes, width)) { width = arrayFirst(widthTypes); } if (!isString(lang) || isEmptyString(lang) || !isPlainObject(languages[lang])) { if (!isString(defaultLanguage) || isEmptyString(defaultLanguage) || !isPlainObject(languages[defaultLanguage])) { throw new Error('Language not loaded!'); } lang = defaultLanguage; } if (strictEqual(width, widthTypeShort) && isUndefined(languages[lang].calendars.gregorian[name][type][width])) { val = makeNamesMin(languages[lang].calendars.gregorian[name][type].abbreviated, order); } else { val = objectValues(languages[lang].calendars.gregorian[name][type][width], order); } return val; } function dayOfWeekNumber(struct) { var day = gregorianToJd(struct).plus(1.5).mod(7).floor(); if (day.lt(0)) { day = day.plus(7); } return day; } function weekDayNumber(struct) { var bnWeekDay = dayOfWeekNumber(struct); if (bnWeekDay.isZero()) { bnWeekDay = new BigNumber(7); } return bnWeekDay; } function cldrDayKey(struct) { return dayKeys[toNumber(dayOfWeekNumber(struct))]; } function dayOfWeek(struct, width, lang) { var val; if (!isString(lang) || isEmptyString(lang) || !isPlainObject(languages[lang])) { if (!isString(defaultLanguage) || isEmptyString(defaultLanguage) || !isPlainObject(languages[defaultLanguage])) { throw new Error('Language not loaded!'); } lang = defaultLanguage; } if (!isString(width) || isEmptyString(width) || !arrayContains(objectKeys(languages[lang].calendars.gregorian.days[arrayFirst(nameTypes)]), width)) { width = arrayFirst(widthTypes); } if (strictEqual(width, widthTypeShort) && isUndefined(languages[lang].calendars.gregorian.days[arrayFirst(nameTypes)][width])) { val = makeNamesMin(languages[lang].calendars.gregorian.days[arrayFirst(nameTypes)].abbreviated); } else { val = languages[lang].calendars.gregorian.days[arrayFirst(nameTypes)][width]; } return val[cldrDayKey(struct)]; } function monthName(struct, width, lang) { var val; if (!isString(lang) || isEmptyString(lang) || !isPlainObject(languages[lang])) { if (!isString(defaultLanguage) || isEmptyString(defaultLanguage) || !isPlainObject(languages[defaultLanguage])) { throw new Error('Language not loaded!'); } lang = defaultLanguage; } if (!isString(width) || isEmptyString(width) || !arrayContains(objectKeys(languages[lang].calendars.gregorian.months.format), width)) { width = arrayFirst(widthTypes); } if (strictEqual(width, widthTypeShort) && isUndefined(languages[lang].calendars.gregorian.days[arrayFirst(nameTypes)][width])) { val = makeNamesMin(languages[lang].calendars.gregorian.days[arrayFirst(nameTypes)].abbreviated); } else { val = languages[lang].calendars.gregorian.days[arrayFirst(nameTypes)][width]; } return val[struct.month.toString()]; } function fractionToTime(fraction, fractionIn, struct, julian) { var time = {}, totalMs, days; fraction = new BigNumber(fraction); switch (fractionIn) { case 'year': if (strictEqual(julian, true)) { days = daysInJulianYear(struct); } else { days = daysInGregorianYear(struct); } totalMs = fraction.times(days.times(86400000)); break; case 'month': if (strictEqual(julian, true)) { days = daysInJulianMonth(struct); } else { days = daysInGregorianMonth(struct); } totalMs = fraction.times(days.times(86400000)); break; case 'day': totalMs = fraction.times(86400000); break; case 'hour': totalMs = fraction.times(3600000); break; case 'minute': totalMs = fraction.times(60000); break; case 'second': totalMs = fraction.times(1000); break; case 'millisecond': totalMs = fraction; break; default: throw new Error(fractionIn); } time.hour = totalMs.div(3600000).floor(); time.minute = totalMs.minus(time.hour.times(3600000)).div(60000).floor(); time.second = totalMs.minus(time.hour.times(3600000)).minus(time.minute.times(60000)).div(1000).floor(); time.millisecond = totalMs.minus(time.hour.times(3600000)).minus(time.minute.times(60000)).minus(time.second.times(1000)).floor(); return time; } function getTime(struct) { return gregorianToJd(struct).minus(2440587.5).times(86400000).floor(); } // DeltaT //http://eclipse.gsfc.nasa.gov/SEhelp/deltatpoly2004.html function deltaTime(struct, canonCorrection) { var y = struct.year.plus(struct.month.minus(0.5).div(12)), u, t, r; if (struct.year.inRange(-500, 2150)) { if (struct.year.lt(500)) { u = y.div(100); r = new BigNumber(10583.6).minus(u.times(1014.41)).plus(u.pow(2).times(33.78311)).minus(u.pow(3).times(5.952053)).minus(u.pow(4).times(0.1798452)).plus(u.pow(5).times(0.022174192)).plus(u.pow(6).times(0.0090316521)); } else if (struct.year.lt(1600)) { u = y.minus(1000).div(100); r = new BigNumber(1574.2).minus(u.times(556.01)).plus(u.pow(2).times(71.23472)).plus(u.pow(3).times(0.319781)).minus(u.pow(4).times(0.8503463)).minus(u.pow(5).times(0.005050998)).plus(u.pow(6).times(0.0083572073)); } else if (struct.year.lt(1700)) { t = y.minus(1600); r = new BigNumber(120).minus(t.times(0.9808)).minus(t.pow(2).times(0.01532)).plus(t.pow(3).div(7129)); } else if (struct.year.lt(1800)) { t = y.minus(1700); r = new BigNumber(8.83).plus(t.times(0.1603)).minus(t.pow(2).times(0.0059285)).plus(t.pow(3).times(0.00013336)).minus(t.pow(4).div(1174000)); } else if (struct.year.lt(1860)) { t = y.minus(1800); r = new BigNumber(13.72).minus(t.times(0.332447)).plus(t.pow(2).times(0.0068612)).plus(t.pow(3).times(0.0041116)).minus(t.pow(4).times(0.00037436)).plus(t.pow(5).times(0.0000121272)).minus(t.pow(6).times(0.0000001699)).plus(t.pow(7).times(0.000000000875)); } else if (struct.year.lt(1900)) { t = y.minus(1860); r = new BigNumber(7.62).plus(t.times(0.5737)).minus(t.pow(2).times(0.251754)).plus(t.pow(3).times(0.01680668)).minus(t.pow(4).times(0.0004473624)).plus(t.pow(5).div(233174)); } else if (struct.year.lt(1920)) { t = y.minus(1900); r = new BigNumber(-2.79).plus(t.times(1.494119)).minus(t.pow(2).times(0.0598939)).plus(t.pow(3).times(0.0061966)).minus(t.pow(4).times(0.000197)); } else if (struct.year.lt(1941)) { t = y.minus(1920); r = new BigNumber(21.20).plus(t.times(0.84493)).minus(t.pow(2).times(0.076100)).plus(t.pow(3).times(0.0020936)); } else if (struct.year.lt(1961)) { t = y.minus(1950); r = new BigNumber(29.07).plus(t.times(0.407)).minus(t.pow(2).div(233)).plus(t.pow(3).div(2547)); } else if (struct.year.lt(1986)) { t = y.minus(1975); r = new BigNumber(45.45).plus(t.times(1.067)).minus(t.pow(2).div(260)).minus(t.pow(3).div(718)); } else if (struct.year.lt(2005)) { t = y.minus(2000); r = new BigNumber(63.86).plus(t.times(0.3345)).minus(t.pow(2).times(0.060374)).plus(t.pow(3).times(0.0017275)).plus(t.pow(4).times(0.000651814)).plus(t.pow(5).times(0.00002373599)); } else if (struct.year.lt(2050)) { t = y.minus(2000); r = new BigNumber(62.92).plus(t.times(0.32217)).plus(t.pow(2).times(0.005589)); } else { r = new BigNumber(-20).plus(y.minus(1820).div(100).pow(2).times(32)).minus(y.neg().plus(2150).times(0.5628)); } } else { u = y.minus(1820).div(100); r = u.pow(2).times(32).plus(-20); } if (canonCorrection && !struct.year.inRange(1955, 2004)) { r.plus(y.minus(1955).pow(2).times(-0.000012932)); } return r.times(1000).trunc(); } function arrayToStruct(arr, julian) { var struct = {}; if (arrayIsArray(arr)) { arraySome(fullKeys, function (element, index) { var value = arr[index], bn, dim; if (isNumber(value) || isString(value) || BigNumber.isBigNumber(value)) { bn = new BigNumber(value); } else { bn = new BigNumber(NaN); } switch (element.full) { case 'year': if (!inYearRange(bn)) { struct = {}; return true; } break; case 'month': if (isUndefined(value)) { bn = bnOne(); } if (!inMonthRange(bn)) { struct = {}; return true; } break; case 'day': if (strictEqual(julian, true)) { dim = daysInJulianMonth(struct); } else { dim = daysInGregorianMonth(struct); } if (isUndefined(value)) { bn = bnOne(); } if (!inDayRange(bn, dim)) { struct = {}; return true; } break; case 'hour': if (isUndefined(value)) { bn = bnZero(); } if (!inHourRange(bn)) { struct = {}; return true; } break; case 'minute': if (isUndefined(value)) { bn = bnZero(); } if (!inMinuteRange(bn, struct.hour)) { struct = {}; return true; } break; case 'second': if (isUndefined(value)) { bn = bnZero(); } if (!inSecondRange(bn, struct)) { struct = {}; return true; } break; case 'millisecond': if (isUndefined(value)) { bn = bnZero(); } if (!inMillisecondRange(bn, struct.hour)) { struct = {}; return true; } break; case 'offset': if (isUndefined(value)) { bn = bnZero(); } if (!inOffsetRange(bn)) { struct = {}; return true; } break; default: throw new Error(element); } struct[element.full] = bn; return false; }); } return struct; } function structToArray(struct) { var arr; if (isValid(struct)) { arr = arrayMap(fullKeys, function (element) { return struct[element.full]; }); } else { arr = []; } return arr; } function returnElementToString(element) { return element.toString(); } function structToArrayOfString(struct) { return arrayMap(structToArray(struct), returnElementToString); } function objectToStruct(object, julian) { var struct = {}; if (isPlainObject(object)) { arraySome(fullKeys, function (element) { var value = object[element.alias] || object[element.full] || object[element.full + 's'], bn, dim; if (isNumber(value) || isString(value) || BigNumber.isBigNumber(value)) { bn = new BigNumber(value); } else { bn = new BigNumber(NaN); } switch (element.full) { case 'year': if (!inYearRange(bn)) { struct = {}; return true; } break; case 'month': if (isUndefined(value)) { bn = bnOne(); } if (!inMonthRange(bn)) { struct = {}; return true; } break; case 'day': if (strictEqual(julian, true)) { dim = daysInJulianMonth(struct); } else { dim = daysInGregorianMonth(struct); } if (isUndefined(value)) { bn = bnOne(); } if (!inDayRange(bn, dim)) { struct = {}; return true; } break; case 'hour': if (isUndefined(value)) { bn = bnZero(); } if (!inHourRange(bn)) { struct = {}; return true; } break; case 'minute': if (isUndefined(value)) { bn = bnZero(); } if (!inMinuteRange(bn, struct.hour)) { struct = {}; return true; } break; case 'second': if (isUndefined(value)) { bn = bnZero(); } if (!inSecondRange(bn, struct)) { struct = {}; return true; } break; case 'millisecond': if (isUndefined(value)) { bn = bnZero(); } if (!inMillisecondRange(bn, struct.hour)) { struct = {}; return true; } break; case 'offset': if (isUndefined(value)) { bn = bnZero(); } if (!inOffsetRange(bn)) { struct = {}; return true; } break; default: throw new Error(element); } struct[element.full] = bn; return false; }); } return struct; } function structToObject(struct) { var newObject = {}; if (isPlainObject(struct)) { arrayForEach(objectKeys(struct), function (key) { newObject[key] = struct[key].toString(); }); } return newObject; } function dateToStruct(date) { var struct = {}; if (isDateValid(date)) { arrayForEach(fullKeys, function (element) { var value = new BigNumber(date[element.local]()); if (strictEqual(element.full, 'month')) { value = value.plus(1); } struct[element.full] = value; }); } return struct; } function julianToJd(struct) { var year = struct.year, month, a, b, jd; month = struct.month; if (month.lte(2)) { year = year.minus(1); month = month.plus(12); } a = year.plus(4716).times(365.25).floor(); b = month.plus(1).times(30.6001).floor(); jd = a.plus(b).plus(struct.day).minus(1524.5).plus(timeTo(struct, 'day')); return jd; } /* function julianToJdn(struct) { return julianToJd(struct).trunc(); } */ function jdToGregorian(julianDay) { var struct = {}, jd = new BigNumber(julianDay), a, b; if (jd.isFinite()) { jd = jd.plus(0.5); a = jd.plus(68569).floor(); b = a.times(4).div(146097).floor(); a = a.minus(b.times(146097).plus(3).div(4).floor()); struct.year = a.plus(1).times(4000).div(1461001).floor(); a = a.minus(struct.year.times(1461).div(4).floor()).plus(31); struct.month = a.times(80).div(2447).floor(); struct.day = a.minus(struct.month.times(2447).div(80).floor()); a = struct.month.div(11).floor(); struct.month = struct.month.plus(2).minus(a.times(12)); struct.year = b.minus(49).times(100).plus(struct.year).plus(a).floor(); struct.offset = bnZero(); extend(struct, fractionToTime(jd.modf().abs(), 'day')); } return struct; } function jdToJulian(julianDay) { var struct = {}, jd = new BigNumber(julianDay), a, b, c, d, e, g; if (jd.isFinite()) { jd = jd.plus(0.5); a = jd.floor(); b = a.plus(1524); c = b.minus(122.1).div(365.25).floor(); d = c.times(365.25).floor(); g = b.minus(d); e = g.div(30.6001).floor(); struct.day = g.minus(e.times(30.6001).floor()); if (e.lt(14)) { struct.month = e.minus(1); } else { struct.month = e.minus(13); } if (struct.month.gt(2)) { struct.year = c.minus(4716); } else { struct.year = c.minus(4715); } struct.offset = bnZero(); extend(struct, fractionToTime(jd.modf().abs(), 'day')); } return struct; } function gregorianToMJD(struct) { return gregorianToJd(struct).minus(2400000.5); } function julianToMJD(struct) { return julianToJd(struct).minus(2400000.5); } function jdToMJD(jd) { return jd.minus(2400000.5); } function gregorianToJulian(struct) { var newStruct; if (isValid(struct)) { newStruct = jdToJulian(gregorianToJd(struct)); } else { newStruct = {}; } return newStruct; } function julianToGregorian(struct) { var newStruct; if (isValid(struct)) { newStruct = jdToGregorian(julianToJd(struct)); } else { newStruct = {}; } return newStruct; } function gregorianEaster(struct) { var a = struct.year.mod(19), b = struct.year.div(100).floor(), c = struct.year.mod(100).floor(), d = b.div(4), e = b.mod(4), f = b.plus(8).div(25).floor(), g = b.minus(f).plus(1).div(3).floor(), h = new BigNumber(19).times(a).plus(b).minus(d).minus(g).plus(15).mod(30), i = c.div(4).floor(), k = c.mod(4), l = new BigNumber(32).plus(e.times(2)).plus(i.times(2)).minus(h).minus(k).mod(7), m = a.plus(h.times(11)).plus(l.times(22)).div(451).floor(), n = h.plus(l).minus(m.times(7)).plus(114); return new AstroDate([struct.year, n.div(31).floor(), n.mod(31).plus(1)]); } function julianEaster(struct) { var a = struct.year.mod(4), b = struct.year.mod(7), c = struct.year.mod(19), d = c.times(19).plus(15).mod(30), e = a.times(2).plus(b.times(4)).minus(d).plus(34).mod(7), f = d.plus(e).plus(114); return new AstroDate([struct.year, f.div(31).floor().minus(1), f.mod(31).plus(1)]); } function toUT(struct) { return jdToGregorian(gregorianToJd(struct).times(86400000).plus(struct.offset.times(60000)).div(86400000)); } function toTT(struct) { var offset = struct.offset, structTT = jdToGregorian(gregorianToJd(struct).times(86400000).minus(deltaTime(struct)).div(86400000)); structTT.offset = offset; return structTT; } function bnGetTimezoneOffset() { return new BigNumber(new Date().getTimezoneOffset()); } function toLocal(struct) { var timezoneOffset = bnGetTimezoneOffset(), structLocal = jdToGregorian(gregorianToJd(struct).times(86400000).plus(struct.offset.times(60000)).minus(bnGetTimezoneOffset().times(60000)).div(86400000)); structLocal.offset = timezoneOffset; return structLocal; } /* function toTAI(struct) { var offset = struct.offset, structTT = jdToGregorian(gregorianToJd(struct).times(86400000).minus(deltaTime(struct)).minus(32184).div(86400000)); structTT.offset = offset; return structTT; } function toGPS(struct) { var offset = struct.offset, structTT = jdToGregorian(gregorianToJd(struct).times(86400000).minus(deltaTime(struct)).minus(51184).div(86400000)); structTT.offset = offset; return structTT; } */ function toISOString(struct, userPadding) { var string, index, count, padding, last, value, key, number; number = toNumber(userPadding); if (lt(number, 5) || !numberIsFinite(number)) { number = 6; } index = 0; string = ''; for (count = 0; lt(count, 3); count += 1) { if (isUndefined(struct[fullKeys[count].full])) { index = 3; break; } } for (last = fullKeys.length - 1; lt(index, last); index += 1) { key = fullKeys[index].full; value = struct[key]; if (strictEqual(key, 'year')) { if (value.lt(0)) { string += '-'; padding = number; } else if (value.gte(10000)) { string += '+'; padding = number; } else { padding = 4; } } else if (strictEqual(key, 'hour')) { string += 'T'; padding = 2; } else if (strictEqual(key, 'millisecond')) { padding = 3; } else { padding = 2; } string += value.abs().padLeadingZero(padding); if (lt(index, 2)) { string += '-'; } else if (inRange(index, 3, 4)) { string += ':'; } else if (strictEqual(key, 'second')) { string += '.'; } } value = struct.offset; if (value.isZero()) { string += 'Z'; } else { if (value.lte(0)) { string += '+'; } else { string += '-'; } value = fractionToTime(value.abs(), 'minute'); string += value.hour.padLeadingZero(2); string += ':'; string += value.minute.padLeadingZero(2); } return string; } function isoHasValidCharacterCounts(string) { var val; if (!inRange(countCharacter(string, ' ') + countCharacter(string, 'T'), 0, 1)) { val = false; } else if (!inRange(countCharacter(string, 'W'), 0, 1)) { val = false; } else if (!inRange(countCharacter(string, 'Z'), 0, 1)) { val = false; } else if (!inRange(countCharacter(string, '.') + countCharacter(string, ','), 0, 1)) { val = false; } else if (!inRange(countCharacter(string, '+'), 0, 2)) { val = false; } else if (!inRange(countCharacter(string, '-'), 0, 4)) { val = false; } else if (!inRange(countCharacter(string, ':'), 0, 4)) { val = false; } else if (lt(string.replace(/\D/g, '').length, 2)) { val = false; } else { val = true; } return val; } function ordinalToCalendar(year, dayOfYear) { var struct = { year: new BigNumber(year), month: bnOne(), day: bnOne(), hour: bnZero(), minute: bnZero(), second: bnZero(), millisecond: bnZero() }, daysInYear = daysInGregorianYear(struct), result; dayOfYear = new BigNumber(dayOfYear); if (dayOfYear.inRange(1, daysInYear)) { struct = jdToGregorian(gregorianToJd(struct).plus(dayOfYear).minus(1)); result = { sign: 1, year: struct.year, month: struct.month, day: struct.day }; } return result; } function weekDateToCalendar(year, week, weekDay) { var struct = { year: new BigNumber(year), month: bnOne(), day: new BigNumber(4), hour: bnZero(), minute: bnZero(), second: bnZero(), millisecond: bnZero() }, weekDayJan4 = weekDayNumber(struct), dayOfYear; dayOfYear = new BigNumber(7).times(week).plus(weekDay).minus(weekDayJan4.plus(3)); if (dayOfYear.lt(1)) { struct.year = struct.year.minus(1); dayOfYear = daysInGregorianYear(struct).plus(dayOfYear); } else if (dayOfYear.gt(daysInGregorianYear(struct))) { struct.year = struct.year.plus(1); dayOfYear = dayOfYear.minus(daysInGregorianYear(struct)); } return ordinalToCalendar(struct.year, dayOfYear); } function calendarToWeekDate(struct) { var weekDay = weekDayNumber(struct), year = struct.year, month = struct.month, nearestThursday, val; nearestThursday = struct.day.plus(4).minus(weekDay); if (struct.month.equals(12) && nearestThursday.gt(31)) { val = { year: year.plus(1), week: bnOne(), weekDay: weekDay }; } else { if (struct.month.equals(1) && nearestThursday.lt(1)) { year = struct.year.minus(1); month = 12; nearestThursday = nearestThursday.plus(31); } val = { year: year, week: dayOfGregorianYear({year: year, month: month, day: nearestThursday}).div(7).floor().plus(1), weekDay: weekDay }; } return val; } function isNotNegativeZero(bn, sign) { return strictEqual(sign, '+') || !bn.isZero() || (bn.isZero() && !strictEqual(sign, '-')); } function hourMinuteToMinutes(minute, second) { return new BigNumber(minute).times(60).plus(second); } function hourFractionToTime(number) { return fractionToTime('0.' + number, 'hour'); } function minuteFractionToTime(number) { return fractionToTime('0.' + number, 'minute'); } function secondFractionToTime(number) { return fractionToTime('0.' + number, 'second'); } function toSignMultipler(sign) { return sign + '1'; } datePatterns = { basic: [{ regex: /^(\d{2})$/, func: function (rxResult) { return { year: new BigNumber(rxResult[1] + '00'), month: bnOne(), day: bnOne() }; } }, { regex: /^(\d{4})$/, func: function (rxResult) { return { year: new BigNumber(rxResult[1]), month: bnOne(), day: bnOne() }; } }, { regex: /^(\d{4})(\d{2})(\d{2})$/, func: function (rxResult) { return { year: new BigNumber(rxResult[1]), month: new BigNumber(rxResult[2]), day: new BigNumber(rxResult[3]) }; } }, { regex: /^(\d{4})(\d{3})$/, func: function (rxResult) { return ordinalToCalendar(rxResult[1], rxResult[2]); } }, { regex: /^(\d{4})W(\d{2})$/, func: function (rxResult) { return weekDateToCalendar(rxResult[1], rxResult[2], 1); } }, { regex: /^(\d{4})W(\d{2})([1-7]{1})$/, func: function (rxResult) { return weekDateToCalendar(rxResult[1], rxResult[2], rxResult[3]); } }], extended: [{ // need to add tests for -0 regex: /^([\-+]{1})(\d{5,})-(\d{2})$/, func: function (rxResult) { return { year: new BigNumber(rxResult[2]).times(toSignMultipler(rxResult[1])), month: new BigNumber(rxResult[3]), day: bnOne() }; } }, { regex: /^(\d{4})-(\d{2})$/, func: function (rxResult) { return { year: new BigNumber(rxResult[1]), month: new BigNumber(rxResult[2]), day: bnOne() }; } }, { regex: /^(\d{4})-(\d{2})-(\d{2})$/, func: function (rxResult) { return { year: new BigNumber(rxResult[1]), month: new BigNumber(rxResult[2]), day: new BigNumber(rxResult[3]) }; } }, { regex: /^([\-+]{1})(\d{5,})-(\d{2})-(\d{2})$/, func: function (rxResult) { return { year: new BigNumber(rxResult[2]).times(toSignMultipler(rxResult[1])), month: new BigNumber(rxResult[3]), day: new BigNumber(rxResult[4]) }; } }, { regex: /^(\d{4})-(\d{3})$/, func: function (rxResult) { return ordinalToCalendar(rxResult[1], rxResult[2]); } }, { regex: /^(\d{4})-W(\d{2})$/, func: function (rxResult) { return weekDateToCalendar(rxResult[1], rxResult[2], 1); } }, { regex: /^(\d{4})-W(\d{2})-([1-7]{1})$/, func: function (rxResult) { return weekDateToCalendar(rxResult[1], rxResult[2], rxResult[3]); } }, { regex: /^([\-+]{1})(\d{5,})-(\d{3})$/, func: function (rxResult) { return ordinalToCalendar(new BigNumber(rxResult[2]).times(toSignMultipler(rxResult[1])), rxResult[3]); } }, { regex: /^([\-+]{1})(\d{5,})-W(\d{2})$/, func: function (rxResult) { return weekDateToCalendar(new BigNumber(rxResult[2]).times(toSignMultipler(rxResult[1])), rxResult[3], 1); } }, { regex: /^([\-+]{1})(\d{5,})-W(\d{2})-([1-7]{1})$/, func: function (rxResult) { return weekDateToCalendar(new BigNumber(rxResult[2]).times(toSignMultipler(rxResult[1])), rxResult[3], rxResult[4]); } }] }; deepFreeze(datePatterns); timePatterns = { basic: [{ regex: /^(\d{2})$/, func: function (rxResult) { return { hour: new BigNumber(rxResult[1]), minute: bnZero(), second: bnZero(), millisecond: bnZero(), offset: bnGetTimezoneOffset() }; } }, { regex: /^(\d{2})(\d{2})$/, func: function (rxResult) { return { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: bnZero(), millisecond: bnZero(), offset: bnGetTimezoneOffset() }; } }, { regex: /^(\d{2})(\d{2})(\d{2})$/, func: function (rxResult) { return { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: new BigNumber(rxResult[3]), millisecond: bnZero(), offset: bnGetTimezoneOffset() }; } }, { regex: /^(\d{2})Z$/, func: function (rxResult) { return { hour: new BigNumber(rxResult[1]), minute: bnZero(), second: bnZero(), millisecond: bnZero(), offset: bnZero() }; } }, { regex: /^(\d{2})(\d{2})Z$/, func: function (rxResult) { return { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: bnZero(), millisecond: bnZero(), offset: bnZero() }; } }, { regex: /^(\d{2})(\d{2})(\d{2})Z$/, func: function (rxResult) { return { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: new BigNumber(rxResult[3]), millisecond: bnZero(), offset: bnZero() }; } }, { regex: /^(\d{2})([\-+]{1})(\d{2})$/, func: function (rxResult) { var sign = rxResult[2], offset = hourMinuteToMinutes(rxResult[3], 0), val; if (isNotNegativeZero(offset, sign)) { val = { hour: new BigNumber(rxResult[1]), minute: bnZero(), second: bnZero(), millisecond: bnZero(), offset: offset.times(toSignMultipler(sign)).neg() }; } return val; } }, { regex: /^(\d{2})(\d{2})([\-+]{1})(\d{2})$/, func: function (rxResult) { var sign = rxResult[3], offset = hourMinuteToMinutes(rxResult[4], 0), val; if (isNotNegativeZero(offset, sign)) { val = { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: bnZero(), millisecond: bnZero(), offset: offset.times(toSignMultipler(sign)).neg() }; } return val; } }, { regex: /^(\d{2})(\d{2})(\d{2})([\-+]{1})(\d{2})$/, func: function (rxResult) { var sign = rxResult[4], offset = hourMinuteToMinutes(rxResult[5], 0), val; if (isNotNegativeZero(offset, sign)) { val = { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: new BigNumber(rxResult[3]), millisecond: bnZero(), offset: offset.times(toSignMultipler(sign)).neg() }; } return val; } }, { regex: /^(\d{2})([\-+]{1})(\d{2})(\d{2})$/, func: function (rxResult) { var sign = rxResult[2], offset = hourMinuteToMinutes(rxResult[3], rxResult[4]), val; if (isNotNegativeZero(offset, sign)) { val = { hour: new BigNumber(rxResult[1]), minute: bnZero(), second: bnZero(), millisecond: bnZero(), offset: offset.times(toSignMultipler(sign)).neg() }; } return val; } }, { regex: /^(\d{2})(\d{2})([\-+]{1})(\d{2})(\d{2})$/, func: function (rxResult) { var sign = rxResult[3], offset = hourMinuteToMinutes(rxResult[4], rxResult[5]), val; if (isNotNegativeZero(offset, sign)) { val = { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: bnZero(), millisecond: bnZero(), offset: offset.times(toSignMultipler(sign)).neg() }; } return val; } }, { regex: /^(\d{2})(\d{2})(\d{2})([\-+]{1})(\d{2})(\d{2})$/, func: function (rxResult) { var sign = rxResult[4], offset = hourMinuteToMinutes(rxResult[5], rxResult[6]), val; if (isNotNegativeZero(offset, sign)) { val = { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: new BigNumber(rxResult[3]), millisecond: bnZero(), offset: offset.times(toSignMultipler(sign)).neg() }; } return val; } }, { regex: /^(\d{2})[\.,]{1}(\d{1,})$/, func: function (rxResult) { var val = hourFractionToTime(rxResult[2]); val.hour = new BigNumber(rxResult[1]); val.offset = bnGetTimezoneOffset(); return val; } }, { regex: /^(\d{2})(\d{2})[\.,]{1}(\d{1,})$/, func: function (rxResult) { var val = minuteFractionToTime(rxResult[3]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.offset = bnGetTimezoneOffset(); return val; } }, { regex: /^(\d{2})(\d{2})(\d{2})[\.,]{1}(\d{1,})$/, func: function (rxResult) { var val = secondFractionToTime(rxResult[4]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.second = new BigNumber(rxResult[3]); val.offset = bnGetTimezoneOffset(); return val; } }, { regex: /^(\d{2})[\.,]{1}(\d{1,})Z$/, func: function (rxResult) { var val = hourFractionToTime(rxResult[2]); val.hour = new BigNumber(rxResult[1]); val.offset = bnZero(); return val; } }, { regex: /^(\d{2})(\d{2})[\.,]{1}(\d{1,})Z$/, func: function (rxResult) { var val = minuteFractionToTime(rxResult[3]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[1]); val.offset = bnZero(); return val; } }, { regex: /^(\d{2})(\d{2})(\d{2})[\.,]{1}(\d{1,})Z$/, func: function (rxResult) { var val = secondFractionToTime(rxResult[4]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.second = new BigNumber(rxResult[3]); val.offset = bnZero(); return val; } }, { regex: /^(\d{2})[\.,]{1}(\d{1,})([\-+]{1})(\d{2})$/, func: function (rxResult) { var sign = rxResult[3], offset = hourMinuteToMinutes(rxResult[4], 0), val; if (isNotNegativeZero(offset, sign)) { val = hourFractionToTime(rxResult[2]); val.hour = new BigNumber(rxResult[1]); val.offset = offset.times(toSignMultipler(sign)).neg(); } return val; } }, { regex: /^(\d{2})(\d{2})[\.,]{1}(\d{1,})([\-+]{1})(\d{2})$/, func: function (rxResult) { var sign = rxResult[4], offset = hourMinuteToMinutes(rxResult[5], 0), val; if (isNotNegativeZero(offset, sign)) { val = minuteFractionToTime(rxResult[3]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.offset = offset.times(toSignMultipler(sign)).neg(); } return val; } }, { regex: /^(\d{2})(\d{2})(\d{2})[\.,]{1}(\d{1,})([\-+]{1})(\d{2})$/, func: function (rxResult) { var sign = rxResult[5], offset = hourMinuteToMinutes(rxResult[6], 0), val; if (isNotNegativeZero(offset, sign)) { val = secondFractionToTime(rxResult[4]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.minute = new BigNumber(rxResult[3]); val.offset = offset.times(toSignMultipler(sign)).neg(); } return val; } }, { regex: /^(\d{2})[\.,]{1}(\d{1,})([\-+]{1})(\d{2})(\d{2})$/, func: function (rxResult) { var sign = rxResult[3], offset = hourMinuteToMinutes(rxResult[4], rxResult[5]), val; if (isNotNegativeZero(offset, sign)) { val = hourFractionToTime(rxResult[2]); val.hour = new BigNumber(rxResult[1]); val.offset = offset.times(toSignMultipler(sign)).neg(); } return val; } }, { regex: /^(\d{2})(\d{2})[\.,]{1}(\d{1,})([\-+]{1})(\d{2})(\d{2})$/, func: function (rxResult) { var sign = rxResult[4], offset = hourMinuteToMinutes(rxResult[5], rxResult[6]), val; if (isNotNegativeZero(offset, sign)) { val = minuteFractionToTime(rxResult[3]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.offset = offset.times(toSignMultipler(sign)).neg(); } return val; } }, { regex: /^(\d{2})(\d{2})(\d{2})[\.,]{1}(\d{1,})([\-+]{1})(\d{2})(\d{2})$/, func: function (rxResult) { var sign = rxResult[5], offset = hourMinuteToMinutes(rxResult[6], rxResult[7]), val; if (isNotNegativeZero(offset, sign)) { val = secondFractionToTime(rxResult[4]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.minute = new BigNumber(rxResult[3]); val.offset = offset.times(toSignMultipler(sign)).neg(); } return val; } }], extended: [{ regex: /^(\d{2})$/, func: function (rxResult) { return { hour: new BigNumber(rxResult[1]), minute: bnZero(), second: bnZero(), millisecond: bnZero(), offset: bnGetTimezoneOffset() }; } }, { regex: /^(\d{2}):(\d{2})$/, func: function (rxResult) { return { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: bnZero(), millisecond: bnZero(), offset: bnGetTimezoneOffset() }; } }, { regex: /^(\d{2}):(\d{2}):(\d{2})$/, func: function (rxResult) { return { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: new BigNumber(rxResult[3]), millisecond: bnZero(), offset: bnGetTimezoneOffset() }; } }, { regex: /^(\d{2})Z$/, func: function (rxResult) { return { hour: new BigNumber(rxResult[1]), minute: bnZero(), second: bnZero(), millisecond: bnZero(), offset: bnZero() }; } }, { regex: /^(\d{2}):(\d{2})Z$/, func: function (rxResult) { return { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: bnZero(), millisecond: bnZero(), offset: bnZero() }; } }, { regex: /^(\d{2}):(\d{2}):(\d{2})Z$/, func: function (rxResult) { return { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: new BigNumber(rxResult[3]), millisecond: bnZero(), offset: bnZero() }; } }, { regex: /^(\d{2}):([\-+]{1})(\d{2})$/, func: function (rxResult) { var sign = rxResult[2], offset = hourMinuteToMinutes(rxResult[3], 0), val; if (isNotNegativeZero(offset, sign)) { val = { hour: new BigNumber(rxResult[1]), minute: bnZero(), second: bnZero(), millisecond: bnZero(), offset: offset.times(toSignMultipler(sign)).neg() }; } return val; } }, { regex: /^(\d{2}):(\d{2})([\-+]{1})(\d{2})$/, func: function (rxResult) { var sign = rxResult[3], offset = hourMinuteToMinutes(rxResult[4], 0), val; if (isNotNegativeZero(offset, sign)) { val = { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: bnZero(), millisecond: bnZero(), offset: offset.times(toSignMultipler(sign)).neg() }; } return val; } }, { regex: /^(\d{2}):(\d{2}):(\d{2})([\-+]{1})(\d{2})$/, func: function (rxResult) { var sign = rxResult[4], offset = hourMinuteToMinutes(rxResult[5], 0), val; if (isNotNegativeZero(offset, sign)) { val = { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: new BigNumber(rxResult[3]), millisecond: bnZero(), offset: offset.times(toSignMultipler(sign)).neg() }; } return val; } }, { regex: /^(\d{2})([\-+]{1})(\d{2}):(\d{2})$/, func: function (rxResult) { var sign = rxResult[2], offset = hourMinuteToMinutes(rxResult[3], rxResult[4]), val; if (isNotNegativeZero(offset, sign)) { val = { hour: new BigNumber(rxResult[1]), minute: bnZero(), second: bnZero(), millisecond: bnZero(), offset: offset.times(toSignMultipler(sign)).neg() }; } return val; } }, { regex: /^(\d{2}):(\d{2})([\-+]{1})(\d{2}):(\d{2})$/, func: function (rxResult) { var sign = rxResult[3], offset = hourMinuteToMinutes(rxResult[4], rxResult[5]), val; if (isNotNegativeZero(offset, sign)) { val = { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: bnZero(), millisecond: bnZero(), offset: offset.times(toSignMultipler(sign)).neg() }; } return val; } }, { regex: /^(\d{2}):(\d{2}):(\d{2})([\-+]{1})(\d{2}):(\d{2})$/, func: function (rxResult) { var sign = rxResult[4], offset = hourMinuteToMinutes(rxResult[5], rxResult[6]), val; if (isNotNegativeZero(offset, sign)) { val = { hour: new BigNumber(rxResult[1]), minute: new BigNumber(rxResult[2]), second: new BigNumber(rxResult[3]), millisecond: bnZero(), offset: offset.times(toSignMultipler(sign)).neg() }; } return val; } }, { regex: /^(\d{2})[\.,]{1}(\d{1,})$/, func: function (rxResult) { var val = hourFractionToTime(rxResult[2]); val.hour = new BigNumber(rxResult[1]); val.offset = bnGetTimezoneOffset(); return val; } }, { regex: /^(\d{2}):(\d{2})[\.,]{1}(\d{1,})$/, func: function (rxResult) { var val = minuteFractionToTime(rxResult[3]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.offset = bnGetTimezoneOffset(); return val; } }, { regex: /^(\d{2}):(\d{2}):(\d{2})[\.,]{1}(\d{1,})$/, func: function (rxResult) { var val = secondFractionToTime(rxResult[4]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.second = new BigNumber(rxResult[3]); val.offset = bnGetTimezoneOffset(); return val; } }, { regex: /^(\d{2})[\.,]{1}(\d{1,})Z$/, func: function (rxResult) { var val = hourFractionToTime(rxResult[2]); val.hour = new BigNumber(rxResult[1]); val.offset = bnZero(); return val; } }, { regex: /^(\d{2}):(\d{2})[\.,]{1}(\d{1,})Z$/, func: function (rxResult) { var val = minuteFractionToTime(rxResult[3]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[1]); val.offset = bnZero(); return val; } }, { regex: /^(\d{2}):(\d{2}):(\d{2})[\.,]{1}(\d{1,})Z$/, func: function (rxResult) { var val = secondFractionToTime(rxResult[4]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.second = new BigNumber(rxResult[3]); val.offset = bnZero(); return val; } }, { regex: /^(\d{2})[\.,]{1}(\d{1,})([\-+]{1})(\d{2})$/, func: function (rxResult) { var sign = rxResult[3], offset = hourMinuteToMinutes(rxResult[4], 0), val; if (isNotNegativeZero(offset, sign)) { val = hourFractionToTime(rxResult[2]); val.hour = new BigNumber(rxResult[1]); val.offset = offset.times(toSignMultipler(sign)).neg(); } return val; } }, { regex: /^(\d{2}):(\d{2})[\.,]{1}(\d{1,})([\-+]{1})(\d{2})$/, func: function (rxResult) { var sign = rxResult[4], offset = hourMinuteToMinutes(rxResult[5], 0), val; if (isNotNegativeZero(offset, sign)) { val = minuteFractionToTime(rxResult[3]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.offset = offset.times(toSignMultipler(sign)).neg(); } return val; } }, { regex: /^(\d{2}):(\d{2}):(\d{2})[\.,]{1}(\d{1,})([\-+]{1})(\d{2})$/, func: function (rxResult) { var sign = rxResult[5], offset = hourMinuteToMinutes(rxResult[6], 0), val; if (isNotNegativeZero(offset, sign)) { val = secondFractionToTime(rxResult[4]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.second = new BigNumber(rxResult[3]); val.offset = offset.times(toSignMultipler(sign)).neg(); } return val; } }, { regex: /^(\d{2})[\.,]{1}(\d{1,})([\-+]{1})(\d{2}):(\d{2})$/, func: function (rxResult) { var sign = rxResult[3], offset = hourMinuteToMinutes(rxResult[4], rxResult[5]), val; if (isNotNegativeZero(offset, sign)) { val = hourFractionToTime(rxResult[2]); val.hour = new BigNumber(rxResult[1]); val.offset = offset.times(toSignMultipler(sign)).neg(); } return val; } }, { regex: /^(\d{2}):(\d{2})[\.,]{1}(\d{1,})([\-+]{1})(\d{2}):(\d{2})$/, func: function (rxResult) { var sign = rxResult[4], offset = hourMinuteToMinutes(rxResult[5], rxResult[6]), val; if (isNotNegativeZero(offset, sign)) { val = minuteFractionToTime(rxResult[3]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.offset = offset.times(toSignMultipler(sign)).neg(); } return val; } }, { regex: /^(\d{2}):(\d{2}):(\d{2})[\.,]{1}(\d{1,})([\-+]{1})(\d{2}):(\d{2})$/, func: function (rxResult) { var sign = rxResult[5], offset = hourMinuteToMinutes(rxResult[6], rxResult[7]), val; if (isNotNegativeZero(offset, sign)) { val = secondFractionToTime(rxResult[4]); val.hour = new BigNumber(rxResult[1]); val.minute = new BigNumber(rxResult[2]); val.second = new BigNumber(rxResult[3]); val.offset = offset.times(toSignMultipler(sign)).neg(); } return val; } }] }; deepFreeze(timePatterns); function isoSplitDateTime(string) { var dtObject = { date: '', time: '' }, firstSplit = stringSplit(stringTrim(string), /[T ]/), splitLength = firstSplit.length, element; if (inRange(splitLength, 1, 2)) { if (strictEqual(splitLength, 1)) { element = arrayFirst(firstSplit); // we make a best guess if (strictEqual(element.slice(-4), '-') || firstCharIs(element, '+') || firstCharIs(element, '-') || strictEqual(element.length, 2) || gte(countCharacter(element, '-'), 2) || stringContains(element, 'W')) { // only ordinal dates have a "-" at -4 // only dates begin with "+" or "-" // dates and times can be only 2 digits but will default to date unless preceeded with " " or "T" // only dates have 2 or more "-" // only dates have a week number "W" dtObject.date = element; dtObject.time = '00'; } else if (lastCharIs(element, 'Z') || stringContains(element, ':') || stringContains(element, '.') || stringContains(element, ',') || stringContains(element, '+') || strictEqual(element.slice(-3), '-')) { // only times end with a "Z" // only times contain a ":" or a "." or a "," // only times contain a "+" that is not at the beginning // only times have a "-" at -3 dtObject.date = '00'; dtObject.time = element; } else { // otherwise we guess it is a date dtObject.date = element; dtObject.time = '00'; } } else { dtObject.date = arrayFirst(firstSplit) || '00'; dtObject.time = arrayLast(firstSplit); } } return dtObject; } function isoParse(isoString) { // Unused variable for JScript NFE bug // http://kangax.github.io/nfe var dtObject = { input: isoString }, nfeSearchPatterns, searchString; if (isString(isoString) && !isEmptyString(isoString) && !invalidISOCharsRx.test(isoString) && isoHasValidCharacterCounts(isoString)) { tempSafariNFE = function nfeSearchPatterns(pattern) { var rxResult = pattern.regex.exec(searchString), val = false, result; if (!isNull(rxResult)) { result = pattern.func(rxResult); if (!isUndefined(result)) { extend(dtObject, result); } val = true; } return val; }; extend(dtObject, isoSplitDateTime(isoString)); searchString = dtObject.date; if (!arraySome(datePatterns.basic, tempSafariNFE)) { if (arraySome(datePatterns.extended, tempSafariNFE)) { searchString = dtObject.time; arraySome(timePatterns.extended, tempSafariNFE); } } else { searchString = dtObject.time; arraySome(timePatterns.basic, tempSafariNFE); } } nfeSearchPatterns = null; return dtObject; } function getCorrectStruct(thisAstroDate, struct) { if (thisAstroDate.isTT()) { struct = toTT(struct); } if (thisAstroDate.isUT()) { struct = toUT(struct); } else if (thisAstroDate.isLocal()) { struct = toLocal(struct); } return struct; } function cldrPadLeadingZero(strNum, size) { var firsrCharacter, val; if (isString(strNum) && !isEmptyString(strNum)) { if ((/^\d+$/).test(strNum) && new BigNumber(strNum).isFinite()) { firsrCharacter = firstChar(strNum); val = ''; if (strictEqual(firsrCharacter, '-')) { strNum = strNum.slice(1); size -= 1; val = firsrCharacter; } val += padLeadingChar(strNum, '0', size); } else { val = strNum; } } return val; } function escapeRegex(string) { return string.replace(/[\[\](){}?*+\^$\\.|]/g, '\\$&'); } function wrapInChar(string, character) { return character + string + character; } function replaceToken(pattern, token, value) { if (!isString(token) || isEmptyString(token)) { throw new Error(); } var firstCharacter, count, copyMatch; if ((/^([|]?\S{1}\{\d+,{1}\d*\})+$/).test(token)) { copyMatch = token; } else if ((/^\{\d{1}\}$/).test(token)) { token = escapeRegex(token); copyMatch = token; } else { firstCharacter = firstChar(token); count = token.length; if (!strictEqual(count, countCharacter(token, firstCharacter))) { throw new Error(token); } copyMatch = token + '(?!' + firstCharacter + ')'; } function replacer($0) { return $0.replace(new RegExp(token, 'g'), wrapInChar(cldrPadLeadingZero(value, $0.length), '\'')); } function tokenReplacer($0, $1, $2) { var val; if ($0) { if ($1) { val = $1.replace(new RegExp(copyMatch, 'g'), replacer); } else { val = $2; } } return val; } return pattern.replace(replaceTokenRX, tokenReplacer); } function strip(string, pattern) { return string.replace(new RegExp(escapeRegex(pattern), 'g'), ''); } function stripSingleQuotes(string) { return strip(string, '\''); } formatTypes = ['full', 'long', 'medium', 'short']; deepFreeze(formatTypes); calendarTypes = { julian: { abbreviated: 'OS', wide: 'Julian', narrow: 'O' }, gregorian: { abbreviated: 'NS', wide: 'Gregorian', narrow: 'N' } }; deepFreeze(calendarTypes); function formatDate(struct, pattern, julian, lang) { if (!isString(pattern) || isEmptyString(pattern)) { pattern = arrayFirst(formatTypes); } if (!isString(lang) || isEmptyString(lang) || !isPlainObject(languages[lang])) { if (!isString(defaultLanguage) || isEmptyString(defaultLanguage) || !isPlainObject(languages[defaultLanguage])) { throw new Error('Language not loaded!'); } lang = defaultLanguage; } var gregorian = languages[lang].calendars.gregorian, dateFormats = gregorian.dateFormats, eras = gregorian.eras, months = gregorian.months, days = gregorian.days, eraNum, year, sign, month, doy, day, temp, weekDate, week, mjd; if (arrayContains(formatTypes, pattern)) { /* switch (pattern) { case 'long': calendarPattern = '\'(\'CCCC\')\''; break; case 'medium': calendarPattern = '\'(\'C\')\''; break; case 'short': calendarPattern = '\'(\'CCCCCC\')\''; break; default: calendarPattern = '\'(\'CCCC\')\''; } */ pattern = dateFormats[pattern]; } /* if (julian) { calendarType = 'julian'; } else { calendarType = 'gregorian'; } */ /* pattern = replaceToken(pattern, 'CCCCC', calendarTypes[calendarType].narrow); pattern = replaceToken(pattern, 'CCCC', calendarTypes[calendarType].wide); pattern = replaceToken(pattern, 'C{1,3}', calendarTypes[calendarType].abbreviated); */ if (struct.year.lt(1)) { eraNum = 0; } else { eraNum = 1; } pattern = replaceToken(pattern, 'GGGGG', eras.eraNarrow[eraNum.toString()]); pattern = replaceToken(pattern, 'GGGG', eras.eraNames[eraNum.toString()]); pattern = replaceToken(pattern, 'G{1,3}', eras.eraNames[eraNum.toString()]); year = struct.year.plus(eraNum - 1); if (year.lt(0)) { sign = '-'; } else { sign = ''; } year = year.abs().toString(); temp = sign + year; pattern = replaceToken(pattern, 'y{3,}', temp); pattern = replaceToken(pattern, 'yy', sign + year.slice(-2)); pattern = replaceToken(pattern, 'y', temp); pattern = replaceToken(pattern, 'U{1,}', temp); year = struct.year; if (year.lt(0)) { sign = '-'; } else { sign = ''; } year = year.toString(); temp = sign + year; pattern = replaceToken(pattern, 'u{1,}', temp); /* weekDate = calendarToWeekDate(struct); year = weekDate.year.plus(eraNum - 1); if (year.lt(0)) { sign = '-'; } else { sign = ''; } */ year = year.toString(); temp = sign + year; pattern = replaceToken(pattern, 'Y{1,}', year); //week = weekDate.week.toString(); //pattern = replaceToken(pattern, 'w{1,2}', week); //pattern = replaceToken(pattern, 'W', value); /* pattern = replaceToken(pattern, 'Q{1,2}', value); pattern = replaceToken(pattern, 'QQQ', value); pattern = replaceToken(pattern, 'QQQQ', value); pattern = replaceToken(pattern, 'q{1,2}', value); pattern = replaceToken(pattern, 'qqq', value); pattern = replaceToken(pattern, 'qqqq', value); */ month = struct.month.toString(); pattern = replaceToken(pattern, 'MMMMM', months.format.narrow[month]); pattern = replaceToken(pattern, 'MMMM', months.format.wide[month]); pattern = replaceToken(pattern, 'MMM', months.format.abbreviated[month]); pattern = replaceToken(pattern, 'M{1,2}', month); pattern = replaceToken(pattern, 'LLLLL', months[arrayLast(nameTypes)].narrow[month]); pattern = replaceToken(pattern, 'LLLL', months[arrayLast(nameTypes)].wide[month]); pattern = replaceToken(pattern, 'LLL', months[arrayLast(nameTypes)].abbreviated[month]); pattern = replaceToken(pattern, 'L{1,2}', month); pattern = replaceToken(pattern, 'd{1,2}', struct.day.toString()); if (julian) { doy = dayOfJulianYear(gregorianToJulian(struct)).toString(); } else { doy = dayOfGregorianYear(struct).toString(); } pattern = replaceToken(pattern, 'D{1,3}', doy); //pattern = replaceToken(pattern, 'F', value); if (julian) { mjd = julianToMJD(toUT(struct)); } else { mjd = gregorianToMJD(toUT(struct)); } pattern = replaceToken(pattern, 'g{1,}', mjd.toString()); day = cldrDayKey(struct); temp = days.format[arrayLast(formatTypes)]; if (isUndefined(temp)) { temp = makeNamesMin(days.format.abbreviated)[day]; } pattern = replaceToken(pattern, 'EEEEEE', temp); pattern = replaceToken(pattern, 'eeeeee', temp); temp = days.format.narrow[day]; pattern = replaceToken(pattern, 'EEEEE', temp); pattern = replaceToken(pattern, 'eeeee', temp); temp = days.format.wide[day]; pattern = replaceToken(pattern, 'EEEE', temp); pattern = replaceToken(pattern, 'eeee', temp); temp = days.format.abbreviated[day]; pattern = replaceToken(pattern, 'E{1,3}', temp); pattern = replaceToken(pattern, 'eeee', temp); //pattern = replaceToken(pattern, 'e{1,2}', local starting day of the week); temp = days[arrayLast(nameTypes)][arrayLast(formatTypes)]; if (isUndefined(temp)) { temp = makeNamesMin(days[arrayLast(nameTypes)].abbreviated)[day]; } pattern = replaceToken(pattern, 'cccccc', temp); pattern = replaceToken(pattern, 'ccccc', days[arrayLast(nameTypes)].narrow[day]); pattern = replaceToken(pattern, 'cccc', days[arrayLast(nameTypes)].wide[day]); pattern = replaceToken(pattern, 'ccc', days[arrayLast(nameTypes)].abbreviated[day]); //pattern = replaceToken(pattern, 'c', weekDayNumber(struct).toString()); // same as 'e': local starting day of the week return pattern; } function formatTime(struct, pattern, lang) { if (!isString(pattern) || isEmptyString(pattern)) { pattern = arrayFirst(formatTypes); } if (!isString(lang) || isEmptyString(lang) || !isPlainObject(languages[lang])) { if (!isString(defaultLanguage) || isEmptyString(defaultLanguage) || !isPlainObject(languages[defaultLanguage])) { throw new Error('Language not loaded!'); } lang = defaultLanguage; } var gregorian = languages[lang].calendars.gregorian, timeFormats = gregorian.timeFormats, dayPeriods = gregorian.dayPeriods, timeZoneNames = languages[lang].timeZoneNames, hourFormat = timeZoneNames.hourFormat, gmtFormat = timeZoneNames.gmtFormat, etc = timeZoneNames.zone.Etc, dayPeriod, hour, offset, offsetFormat, zulu = '\'Z\'', iso; if (arrayContains(formatTypes, pattern)) { pattern = timeFormats[pattern]; } if (struct.hour.inRange(12, 23)) { dayPeriod = 'pm'; } else { dayPeriod = 'am'; } pattern = replaceToken(pattern, 'a', dayPeriods.format.abbreviated[dayPeriod]); hour = struct.hour.plus(11).mod(12).plus(1); pattern = replaceToken(pattern, 'h{1,2}', hour.toString()); pattern = replaceToken(pattern, 'H{1,2}', struct.hour.toString()); pattern = replaceToken(pattern, 'K{1,2}', hour.minus(1).toString()); // if hour is 24, needs to be handled in date too //temp = new AstroDate().julianDay(new AstroDate().julianDay()); //pattern = replaceToken(pattern, 'k{1,2}', struct.hour.plus(1).toString()); //pattern = replaceToken(pattern, 'j{1,2}', struct.hour.toString()); pattern = replaceToken(pattern, 'm{1,2}', struct.minute.toString()); pattern = replaceToken(pattern, 's{1,2}', struct.second.toString()); pattern = replaceToken(pattern, 'S{1,}', struct.millisecond.toString()); //pattern = replaceToken(pattern, 'A{1,}', value); offsetFormat = hourFormat.split(';'); if (struct.offset.lte(0)) { offsetFormat = arrayFirst(offsetFormat); } else { offsetFormat = arrayLast(offsetFormat); } offset = fractionToTime(struct.offset.abs(), 'minute'); offsetFormat = replaceToken(offsetFormat, 'H{1,2}', offset.hour.toString()); offsetFormat = replaceToken(offsetFormat, 'm{1,2}', offset.minute.toString()); pattern = replaceToken(pattern, 'ZZZZZ', offsetFormat); pattern = replaceToken(pattern, 'xxxxx', offsetFormat); pattern = replaceToken(pattern, 'xxx', offsetFormat); if (struct.offset.isZero()) { iso = zulu; } else { iso = offsetFormat; } pattern = replaceToken(pattern, 'XXXXX', iso); pattern = replaceToken(pattern, 'XXX', iso); gmtFormat = replaceToken(gmtFormat, '{0}', offsetFormat); pattern = replaceToken(pattern, 'OOOO', gmtFormat); pattern = replaceToken(pattern, 'zzzz', gmtFormat); pattern = replaceToken(pattern, 'ZZZZ', gmtFormat); pattern = replaceToken(pattern, 'vvvv', gmtFormat); pattern = replaceToken(pattern, 'v', gmtFormat); pattern = replaceToken(pattern, 'VVVV', gmtFormat); if (struct.offset.lte(0)) { offsetFormat = '+HHMM'; } else { offsetFormat = '-HHMM'; } offsetFormat = replaceToken(offsetFormat, 'H{1,2}', offset.hour.toString()); offsetFormat = replaceToken(offsetFormat, 'm{1,2}', offset.minute.toString()); pattern = replaceToken(pattern, 'Z{1,3}', offsetFormat); pattern = replaceToken(pattern, 'XXXX', iso); pattern = replaceToken(pattern, 'XX', iso); pattern = replaceToken(pattern, 'xxxx', offsetFormat); pattern = replaceToken(pattern, 'xx', offsetFormat); gmtFormat = replaceToken(gmtFormat, '{0}', offsetFormat); pattern = replaceToken(pattern, 'O', gmtFormat); pattern = replaceToken(pattern, 'z{1,3}', gmtFormat); pattern = replaceToken(pattern, 'V{2,3}', etc.Unknown.exemplarCity); pattern = replaceToken(pattern, 'V', etc.Unknown.exemplarCity.slice(0, 3).toLowerCase()); return pattern; } function formatDateTime(struct, pattern, julian, lang) { if (!isString(pattern) || isEmptyString(pattern)) { pattern = arrayFirst(formatTypes); } if (!isString(lang) || isEmptyString(lang) || !isPlainObject(languages[lang])) { if (!isString(defaultLanguage) || isEmptyString(defaultLanguage) || !isPlainObject(languages[defaultLanguage])) { throw new Error('Language not loaded!'); } lang = defaultLanguage; } var gregorian = languages[lang].calendars.gregorian, dateTimeFormats = gregorian.dateTimeFormats, dateTimeFormat; if (arrayContains(objectKeys(dateTimeFormats), pattern)) { dateTimeFormat = dateTimeFormats[pattern]; dateTimeFormat = replaceToken(dateTimeFormat, '{1}', formatDate(struct, pattern, julian, lang)); dateTimeFormat = replaceToken(dateTimeFormat, '{0}', formatTime(struct, pattern, lang)); } else { dateTimeFormat = formatDate(struct, pattern, julian, lang); dateTimeFormat = formatTime(struct, dateTimeFormat, lang); } return dateTimeFormat; } AstroDate = function () { var args = arguments, input = arguments, argsLength = args.length, isJulian = false, isUT = false, isTT = false, isLocal = false, error = null, currentLanguage = defaultLanguage, struct, arg; objectDefineProperties(this, { getter: { value: function (key) { var got; if (isUndefined(key)) { got = extend({}, struct); } else if (isString(key)) { switch (key) { case 'struct': got = extend({}, struct); break; case 'isJulian': got = isJulian; break; case 'isUT': got = isUT; break; case 'isTT': got = isTT; break; case 'isLocal': got = isLocal; break; case 'args': got = args; break; case 'input': got = input; break; case 'error': got = error; break; case 'lang': got = currentLanguage; break; default: throw new SyntaxError(key); } } else { throw new TypeError(key); } return got; } }, setter: { value: function (key, value) { var unit = normaliseUnits(key), valid = false, bn, dim; if (unit) { bn = new BigNumber(value); switch (unit) { case 'year': valid = inYearRange(bn); break; case 'month': valid = inMonthRange(bn); break; case 'day': if (strictEqual(isJulian, true)) { dim = daysInJulianMonth(struct); } else { dim = daysInGregorianMonth(struct); } valid = inDayRange(bn, dim); break; case 'hour': valid = inHourRange(bn); break; case 'minute': valid = inMinuteRange(bn, struct.hour); break; case 'second': valid = inSecondRange(bn, struct); break; case 'millisecond': valid = inMillisecondRange(bn, struct.hour); break; case 'offset': valid = inOffsetRange(bn); break; default: throw new Error(unit); } if (valid) { struct[unit] = bn; } else { struct = {}; } } else if (arrayIsArray(key)) { struct = arrayToStruct(key, false); } else if (AstroDate.isAstroDate(key)) { struct = key.getter(); isJulian = key.isJulian(); } else if (isDate(key)) { struct = dateToStruct(key); } else if (isString(key)) { switch (key) { case 'input': input = value; break; case 'error': error = value; break; case 'struct': if (isValid(value)) { struct = extend({}, value); } else { struct = {}; } break; case 'isJulian': isJulian = Boolean(value); break; case 'isUT': isUT = Boolean(value); break; case 'isTT': isTT = Boolean(value); break; case 'isLocal': isLocal = Boolean(value); break; case 'lang': if (isString(value) && !isEmptyString(value) && isPlainObject(languages[value])) { currentLanguage = value; } break; default: struct = isoParse(key); } } else { throw new SyntaxError(key); } return this; } } }); switch (argsLength.toString()) { case '0': struct = dateToStruct(new Date()); break; case '1': arg = arrayFirst(args); if (AstroDate.isAstroDate(arg)) { isJulian = arg.getter('isJulian'); struct = extend({}, arg.getter()); } else if (arrayIsArray(arg)) { struct = arrayToStruct(arg, false); } else if (isDate(arg)) { struct = dateToStruct(arg); } else if (isNumber(arg)) { struct = dateToStruct(new Date(arg)); } else if (isString(arg)) { struct = isoParse(arg); } else if (isPlainObject(arg)) { struct = objectToStruct(arg); if (!isValid(struct)) { struct = {}; } } else { throw new TypeError(arg); } break; case '2': arg = arrayFirst(args); if (isString(arg)) { arg = stringTrim(arg).toLowerCase(); switch (arg) { case 'j': arg = args[1]; if (arrayIsArray(arg)) { struct = julianToGregorian(arrayToStruct(arg, true)); } else if (isPlainObject(arg)) { struct = objectToStruct(arg, true); if (isValid(struct, true)) { struct = julianToGregorian(struct); } else { struct = {}; } } else { throw new TypeError(arg); } break; case 'g': arg = args[1]; if (arrayIsArray(arg)) { struct = arrayToStruct(arg, false); } else if (isPlainObject(arg)) { struct = objectToStruct(arg); if (!isValid(struct)) { struct = {}; } } else { throw new TypeError(arg); } break; case 'jd': arg = args[1]; this.julianDay(arg); break; default: throw new SyntaxError(arg); } } else { throw new TypeError(arg); } break; default: throw new SyntaxError(argsLength); } if (!isValid(struct)) { struct = {}; } }; objectDefineProperties(AstroDate.prototype, { julian: { value: function () { return this.setter('isJulian', true); } }, gregorian: { value: function () { return this.setter('isJulian', false); } }, local: { value: function () { this.setter('isLocal', true); this.setter('isUT', false); return this; } }, UT: { value: function () { this.setter('isLocal', false); this.setter('isUT', true); return this; } }, TT: { value: function () { return this.setter('isTT', true); } }, civil: { value: function () { return this.setter('isTT', false); } }, raw: { value: function () { this.setter('isLocal', false); this.setter('isUT', false); this.setter('isTT', false); return this; } }, isJulian: { value: function () { return this.getter('isJulian'); } }, isGregorian: { value: function () { return !this.getter('isJulian'); } }, isUT: { value: function () { return this.getter('isUT'); } }, isTT: { value: function () { return this.getter('isTT'); } }, isCivil: { value: function () { return !this.getter('isTT'); } }, isLocal: { value: function () { return this.getter('isLocal'); } }, isRaw: { value: function () { return !this.getter('isUT') && !this.getter('isTT') && this.getter('isLocal'); } }, currentLang: { value: function () { return this.getter('lang'); } }, isWeekDay: { value: function () { var val; if (this.isValid()) { val = weekDayNumber(getCorrectStruct(this, this.getter())).inRange(1, 5); } return val; } }, isWeekend: { value: function () { var val; if (this.isValid()) { val = weekDayNumber(getCorrectStruct(this, this.getter())).inRange(6, 7); } return val; } }, zone: { value: function () { var val; if (this.isValid()) { val = getCorrectStruct(this, this.getter()).offset.toString(); } return val; } }, isValid: { value: function () { return isValid(this.getter()); } }, parse: { value: function (isoString) { var val; if (isString(isoString)) { val = this.setter('struct', isoParse(isoString)); } else { throw new TypeError(isoString); } return val; } }, toString: { value: function (pattern) { var struct, string, isJulian; if (this.isValid()) { isJulian = this.isJulian(); if (isJulian) { struct = jdToJulian(this.julianDay()); } else { struct = this.getter(); } struct = getCorrectStruct(this, struct); string = stripSingleQuotes(formatDateTime(struct, pattern, isJulian, this.currentLang())); } else { string = 'Invalid Date'; } return string; } }, toDateString: { value: function (pattern) { var struct, string, isJulian; if (this.isValid()) { isJulian = this.isJulian(); if (isJulian) { struct = jdToJulian(this.julianDay()); } else { struct = this.getter(); } struct = getCorrectStruct(this, struct); string = stripSingleQuotes(formatDate(struct, pattern, isJulian, this.currentLang())); } else { string = 'Invalid Date'; } return string; } }, toTimeString: { value: function (pattern) { var struct, string, isJulian; if (this.isValid()) { isJulian = this.isJulian(); if (isJulian) { struct = jdToJulian(this.julianDay()); } else { struct = this.getter(); } struct = getCorrectStruct(this, struct); string = stripSingleQuotes(formatTime(struct, pattern, this.currentLang())); } else { string = 'Invalid Date'; } return string; } }, toISOString: { value: function (padding) { var val; if (this.isValid()) { val = toISOString(getCorrectStruct(this, this.getter()), padding); } else { val = 'Invalid Date'; } return val; } }, valueOf: { value: function () { var val; if (this.isJulian()) { val = this.julianDay(); } else { val = this.getTime(); } return val; } }, unix: { value: function () { var struct, val; if (this.isValid()) { if (this.isTT()) { struct = toTT(this.getter()); } else { struct = this.getter(); } val = getTime(toUT(struct)).div(1000).trunc().toString(); } return val; } }, object: { value: function (dateObject) { var struct, val; if (isUndefined(dateObject)) { if (this.isValid()) { struct = getCorrectStruct(this, this.getter()); if (this.isJulian()) { val = structToObject(gregorianToJulian(struct)); } else { val = structToObject(struct); } } } else if (isPlainObject(dateObject)) { val = this.setter('struct', objectToStruct(dateObject, this.isJulian())); } else { throw new TypeError(dateObject); } return val; } }, clone: { value: function () { return new AstroDate(this); } }, array: { value: function (dateArray) { var struct, val; if (isUndefined(dateArray)) { if (this.isValid()) { struct = getCorrectStruct(this, this.getter()); if (this.isJulian()) { val = structToArrayOfString(gregorianToJulian(struct)); } else { val = structToArrayOfString(struct); } } } else if (arrayIsArray(dateArray)) { val = this.setter('struct', arrayToStruct(dateArray, this.isJulian())); } else { throw new TypeError(dateArray); } return val; } }, date: { value: function (date) { var val; if (isUndefined(date)) { if (this.isValid()) { val = new Date(parseInt(this.getTime(), 10)); } else { val = new Date(NaN); } } else if (isDate(date)) { val = this.setter(date); } else { throw new TypeError(date); } return val; } }, getTime: { value: function () { var struct, val; if (this.isValid()) { if (this.isTT()) { struct = toTT(this.getter()); } else { struct = this.getter(); } val = getTime(toUT(struct)).toString(); } return val; } }, deltaTime: { value: function () { var val; if (this.isValid()) { val = deltaTime(getCorrectStruct(this, this.getter())).toString(); } return val; } }, timeTo: { value: function (unit) { var val; if (this.isValid()) { val = timeTo(getCorrectStruct(this, this.getter()), normaliseUnits(unit)).toString(); } return val; } }, julianDay: { value: function (julianDay) { var struct, val; if (isUndefined(julianDay)) { if (this.isValid()) { if (this.isTT()) { struct = toTT(this.getter()); } else { struct = this.getter(); } val = gregorianToJd(toUT(struct)).toString(); } } else if (isNumber(julianDay) || isString(julianDay) || BigNumber.isBigNumber(julianDay)) { val = this.setter('struct', jdToGregorian(julianDay)); } else { throw new TypeError(julianDay); } return val; } }, easter: { value: function () { var struct, val; if (this.isValid()) { struct = getCorrectStruct(this, this.getter()); if (this.isJulian()) { val = julianEaster(gregorianToJulian(struct)); } else { val = gregorianEaster(struct); } } return val; } }, monthOfYear: { value: function (type) { var val, struct; if (this.isValid()) { struct = getCorrectStruct(this, this.getter()); if (this.isJulian()) { val = monthName(gregorianToJulian(struct), type, this.currentLang()); } else { val = monthName(struct, type); } } return val; } }, dayOfWeek: { value: function (type) { var val; if (this.isValid()) { val = dayOfWeek(getCorrectStruct(this, this.getter()), type, this.currentLang()); } return val; } }, isLeapYear: { value: function () { var struct, val; if (this.isValid()) { struct = getCorrectStruct(this, this.getter()); if (this.isJulian()) { val = isJulianLeapYear(gregorianToJulian(struct)); } else { val = isGregorianLeapYear(struct); } } return val; } }, daysInYear: { value: function () { var struct, val; if (this.isValid()) { struct = getCorrectStruct(this, this.getter()); if (this.isJulian()) { val = daysInJulianYear(gregorianToJulian(struct)).toString(); } else { val = daysInGregorianYear(struct).toString(); } } return val; } }, daysInMonth: { value: function () { var struct, val; if (this.isValid()) { struct = getCorrectStruct(this, this.getter()); if (this.isJulian()) { val = daysInJulianMonth(gregorianToJulian(struct)).toString(); } else { val = daysInGregorianMonth(struct).toString(); } } return val; } }, dayOfYear: { value: function () { var struct, val; if (this.isValid()) { struct = getCorrectStruct(this, this.getter()); if (this.isJulian()) { val = dayOfJulianYear(gregorianToJulian(struct)).toString(); } else { val = dayOfGregorianYear(struct).toString(); } } return val; } }, json: { value: function (jsonString) { var struct, propArray, val; if (isUndefined(jsonString)) { if (isFunction(JSON.stringify)) { val = JSON.stringify(this.object()); } else { struct = this.object(); propArray = arrayMap(objectKeys(struct), function (key) { return '"' + key + '":"' + struct[key] + '"'; }); val = '{' + propArray.join(',') + '}'; } } else if (isString(jsonString)) { if (isFunction(JSON.parse)) { struct = objectToStruct(JSON.parse(jsonString), this.isJulian()); } else { /*jslint evil: true */ struct = objectToStruct(new Function('return' + jsonString)(), this.isJulian()); /*jslint evil: false */ } if (!isValid(struct)) { throw new SyntaxError(struct); } val = this.setter('struct', struct); } else { throw new TypeError(jsonString); } return val; } }, toJSON: { value: function (padding) { return this.toISOString(padding); } }, calendarToWeekDate: { value: function () { var val; if (this.isValid()) { val = structToObject(calendarToWeekDate(getCorrectStruct(this, this.getter()))); } return val; } }, lang: { value: function (id) { if (isString(id) && !isEmptyString(id) && isPlainObject(languages[id])) { this.setter('lang', id); } return this; } } }); objectDefineProperties(AstroDate, { version: { value: VERSION }, lang: { value: function (id, object, freeze) { var val; if (isString(id) && !isEmptyString(id)) { if (isPlainObject(object)) { languages[id] = object; if (!strictEqual(freeze, false)) { deepFreeze(languages[id]); } } if (isPlainObject(languages[id])) { val = languages[id]; defaultLanguage = id; } } return val; } }, leapSeconds: { value: function (object, freeze) { if (isPlainObject(object)) { leapSeconds = object; if (!strictEqual(freeze, false)) { deepFreeze(leapSeconds); } } return leapSeconds; } }, BigNumber: { value: BigNumber }, normaliseUnits: { value: function (unitString) { return normaliseUnits(unitString); } }, isAstroDate: { value: function (inputArg) { return isObject(inputArg) && objectInstanceOf(inputArg, AstroDate); } }, now: { value: function () { return new AstroDate().getTime(); } }, julianDay: { value: function () { return new AstroDate().julianDay(); } }, unix: { value: function () { return new AstroDate().unix(); } }, months: { value: function (type, size, lang) { return makeNamesArray('months', type, size, lang, monthKeys); } }, weekDays: { value: function (type, size, lang) { return makeNamesArray('days', type, size, lang, dayKeys); } } }); defaultProperties = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; deepFreeze(defaultProperties); fullKeys = [{ full: 'year', alias: 'y', local: 'getFullYear' }, { full: 'month', alias: 'M', local: 'getMonth' }, { full: 'day', alias: 'd', local: 'getDate' }, { full: 'hour', alias: 'h', local: 'getHours' }, { full: 'minute', alias: 'm', local: 'getMinutes' }, { full: 'second', alias: 's', local: 'getSeconds' }, { full: 'millisecond', alias: 'ms', local: 'getMilliseconds' }, { full: 'offset', alias: 'z', local: 'getTimezoneOffset' }]; /* , { full: 'week', alias: 'W', local: null }, { full: 'weekDay', alias: 'E', local: null } */ deepFreeze(fullKeys); monthKeys = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']; deepFreeze(monthKeys); dayKeys = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']; deepFreeze(dayKeys); arrayForEach([BigNumber, BigNumber.prototype], function (element) { arrayForEach(objectKeys(element), function (key) { objectDefineProperty(element, key, { enumerable: false, configurable: false, writeable: false }); }); }); AstroDate.lang('root', { 'codePatterns': { 'language': '{0}', 'script': '{0}', 'territory': '{0}' }, 'types': { 'calendar': { 'japanese': 'japanese', 'iso8601': 'iso8601', 'coptic': 'coptic', 'dangi': 'dangi', 'ethiopic': 'ethiopic', 'ethiopic-amete-alem': 'ethiopic-amete-alem', 'gregorian': 'gregorian', 'hebrew': 'hebrew', 'persian': 'persian', 'roc': 'roc', 'chinese': 'chinese', 'buddhist': 'buddhist', 'indian': 'indian', 'islamic': 'islamic', 'islamic-civil': 'islamic-civil', 'islamic-rgsa': 'islamic-rgsa', 'islamic-tbla': 'islamic-tbla', 'islamic-umalqura': 'islamic-umalqura' }, 'collation': { 'phonebook': 'phonebook', 'gb2312han': 'gb2312han', 'eor': 'eor', 'ducet': 'ducet', 'dictionary': 'dictionary', 'big5han': 'big5han', 'traditional': 'traditional', 'zhuyin': 'zhuyin', 'unihan': 'unihan', 'stroke': 'stroke', 'searchjl': 'searchjl', 'search': 'search', 'reformed': 'reformed', 'pinyin': 'pinyin', 'standard': 'standard' }, 'numbers': { 'laoo': 'laoo', 'lanatham': 'lanatham', 'lana': 'lana', 'knda': 'knda', 'khmr': 'khmr', 'kali': 'kali', 'jpanfin': 'jpanfin', 'jpan': 'jpan', 'java': 'java', 'hebr': 'hebr', 'hantfin': 'hantfin', 'hant': 'hant', 'hansfin': 'hansfin', 'hans': 'hans', 'hanidec': 'hanidec', 'guru': 'guru', 'cakm': 'cakm', 'brah': 'brah', 'beng': 'beng', 'bali': 'bali', 'armnlow': 'armnlow', 'armn': 'armn', 'arabext': 'arabext', 'arab': 'arab', 'cham': 'cham', 'deva': 'deva', 'orya': 'orya', 'osma': 'osma', 'roman': 'roman', 'romanlow': 'romanlow', 'saur': 'saur', 'shrd': 'shrd', 'sora': 'sora', 'sund': 'sund', 'vaii': 'vaii', 'tibt': 'tibt', 'thai': 'thai', 'telu': 'telu', 'tamldec': 'tamldec', 'taml': 'taml', 'talu': 'talu', 'takr': 'takr', 'olck': 'olck', 'nkoo': 'nkoo', 'mymrshan': 'mymrshan', 'mymr': 'mymr', 'mtei': 'mtei', 'mong': 'mong', 'mlym': 'mlym', 'limb': 'limb', 'lepc': 'lepc', 'latn': 'latn', 'gujr': 'gujr', 'greklow': 'greklow', 'grek': 'grek', 'geor': 'geor', 'fullwide': 'fullwide', 'ethi': 'ethi' } }, 'keys': { 'calendar': 'calendar', 'collation': 'collation', 'currency': 'currency', 'numbers': 'numbers' }, 'localeDisplayPattern': { 'localePattern': '{0} ({1})', 'localeSeparator': '{0}, {1}', 'localeKeyTypePattern': '{0}: {1}' }, 'timeZoneNames': { 'hourFormat': '+HH:mm;-HH:mm', 'gmtFormat': 'GMT{0}', 'gmtZeroFormat': 'GMT', 'regionFormat': '{0}', 'regionFormat-type-daylight': '{0} (+1)', 'regionFormat-type-standard': '{0} (+0)', 'fallbackFormat': '{1} ({0})', 'zone': { 'Pacific': { 'Saipan': { 'exemplarCity': 'Saipan' }, 'Rarotonga': { 'exemplarCity': 'Rarotonga' }, 'Port_Moresby': { 'exemplarCity': 'Port Moresby' }, 'Ponape': { 'exemplarCity': 'Pohnpei' }, 'Pitcairn': { 'exemplarCity': 'Pitcairn' }, 'Palau': { 'exemplarCity': 'Palau' }, 'Auckland': { 'exemplarCity': 'Auckland' }, 'Apia': { 'exemplarCity': 'Apia' }, 'Funafuti': { 'exemplarCity': 'Funafuti' }, 'Galapagos': { 'exemplarCity': 'Galapagos' }, 'Gambier': { 'exemplarCity': 'Gambier' }, 'Guadalcanal': { 'exemplarCity': 'Guadalcanal' }, 'Guam': { 'exemplarCity': 'Guam' }, 'Honolulu': { 'exemplarCity': 'Honolulu' }, 'Wallis': { 'exemplarCity': 'Wallis' }, 'Wake': { 'exemplarCity': 'Wake' }, 'Truk': { 'exemplarCity': 'Chuuk' }, 'Tongatapu': { 'exemplarCity': 'Tongatapu' }, 'Tarawa': { 'exemplarCity': 'Tarawa' }, 'Tahiti': { 'exemplarCity': 'Tahiti' }, 'Kiritimati': { 'exemplarCity': 'Kiritimati' }, 'Johnston': { 'exemplarCity': 'Johnston' }, 'Chatham': { 'exemplarCity': 'Chatham' }, 'Easter': { 'exemplarCity': 'Easter' }, 'Efate': { 'exemplarCity': 'Efate' }, 'Enderbury': { 'exemplarCity': 'Enderbury' }, 'Fakaofo': { 'exemplarCity': 'Fakaofo' }, 'Fiji': { 'exemplarCity': 'Fiji' }, 'Kosrae': { 'exemplarCity': 'Kosrae' }, 'Kwajalein': { 'exemplarCity': 'Kwajalein' }, 'Majuro': { 'exemplarCity': 'Majuro' }, 'Marquesas': { 'exemplarCity': 'Marquesas' }, 'Midway': { 'exemplarCity': 'Midway' }, 'Nauru': { 'exemplarCity': 'Nauru' }, 'Niue': { 'exemplarCity': 'Niue' }, 'Norfolk': { 'exemplarCity': 'Norfolk' }, 'Noumea': { 'exemplarCity': 'Noumea' }, 'Pago_Pago': { 'exemplarCity': 'Pago Pago' } }, 'Australia': { 'Lindeman': { 'exemplarCity': 'Lindeman' }, 'Hobart': { 'exemplarCity': 'Hobart' }, 'Eucla': { 'exemplarCity': 'Eucla' }, 'Darwin': { 'exemplarCity': 'Darwin' }, 'Sydney': { 'exemplarCity': 'Sydney' }, 'Perth': { 'exemplarCity': 'Perth' }, 'Melbourne': { 'exemplarCity': 'Melbourne' }, 'Lord_Howe': { 'exemplarCity': 'Lord Howe' }, 'Adelaide': { 'exemplarCity': 'Adelaide' }, 'Brisbane': { 'exemplarCity': 'Brisbane' }, 'Broken_Hill': { 'exemplarCity': 'Broken Hill' }, 'Currie': { 'exemplarCity': 'Currie' } }, 'Indian': { 'Maldives': { 'exemplarCity': 'Maldives' }, 'Mahe': { 'exemplarCity': 'Mahe' }, 'Kerguelen': { 'exemplarCity': 'Kerguelen' }, 'Reunion': { 'exemplarCity': 'Reunion' }, 'Mayotte': { 'exemplarCity': 'Mayotte' }, 'Mauritius': { 'exemplarCity': 'Mauritius' }, 'Antananarivo': { 'exemplarCity': 'Antananarivo' }, 'Chagos': { 'exemplarCity': 'Chagos' }, 'Christmas': { 'exemplarCity': 'Christmas' }, 'Cocos': { 'exemplarCity': 'Cocos' }, 'Comoro': { 'exemplarCity': 'Comoro' } }, 'Etc': { 'GMT-11': { 'exemplarCity': 'GMT-11' }, 'GMT-10': { 'exemplarCity': 'GMT-10' }, 'GMT-1': { 'exemplarCity': 'GMT-1' }, 'GMT9': { 'exemplarCity': 'GMT+9' }, 'GMT8': { 'exemplarCity': 'GMT+8' }, 'GMT7': { 'exemplarCity': 'GMT+7' }, 'GMT6': { 'exemplarCity': 'GMT+6' }, 'GMT5': { 'exemplarCity': 'GMT+5' }, 'GMT': { 'exemplarCity': 'GMT' }, 'GMT1': { 'exemplarCity': 'GMT+1' }, 'GMT10': { 'exemplarCity': 'GMT+10' }, 'GMT11': { 'exemplarCity': 'GMT+11' }, 'GMT-3': { 'exemplarCity': 'GMT-3' }, 'GMT-4': { 'exemplarCity': 'GMT-4' }, 'GMT-5': { 'exemplarCity': 'GMT-5' }, 'GMT-6': { 'exemplarCity': 'GMT-6' }, 'GMT-7': { 'exemplarCity': 'GMT-7' }, 'GMT-8': { 'exemplarCity': 'GMT-8' }, 'GMT-9': { 'exemplarCity': 'GMT-9' }, 'Unknown': { 'exemplarCity': 'Unknown' }, 'GMT-2': { 'exemplarCity': 'GMT-2' }, 'GMT-14': { 'exemplarCity': 'GMT-14' }, 'GMT-13': { 'exemplarCity': 'GMT-13' }, 'GMT-12': { 'exemplarCity': 'GMT-12' }, 'GMT4': { 'exemplarCity': 'GMT+4' }, 'GMT3': { 'exemplarCity': 'GMT+3' }, 'GMT2': { 'exemplarCity': 'GMT+2' }, 'GMT12': { 'exemplarCity': 'GMT+12' } }, 'Antarctica': { 'Rothera': { 'exemplarCity': 'Rothera' }, 'Palmer': { 'exemplarCity': 'Palmer' }, 'McMurdo': { 'exemplarCity': 'McMurdo' }, 'Vostok': { 'exemplarCity': 'Vostok' }, 'Syowa': { 'exemplarCity': 'Syowa' }, 'South_Pole': { 'exemplarCity': 'South Pole' }, 'Casey': { 'exemplarCity': 'Casey' }, 'Davis': { 'exemplarCity': 'Davis' }, 'DumontDUrville': { 'exemplarCity': 'Dumont d\u02BCUrville' }, 'Macquarie': { 'exemplarCity': 'Macquarie' }, 'Mawson': { 'exemplarCity': 'Mawson' } }, 'Arctic': { 'Longyearbyen': { 'exemplarCity': 'Longyearbyen' } }, 'America': { 'Toronto': { 'exemplarCity': 'Toronto' }, 'Tijuana': { 'exemplarCity': 'Tijuana' }, 'Thunder_Bay': { 'exemplarCity': 'Thunder Bay' }, 'Thule': { 'exemplarCity': 'Thule' }, 'Tegucigalpa': { 'exemplarCity': 'Tegucigalpa' }, 'Swift_Current': { 'exemplarCity': 'Swift Current' }, 'Chicago': { 'exemplarCity': 'Chicago' }, 'Cayman': { 'exemplarCity': 'Cayman' }, 'Cayenne': { 'exemplarCity': 'Cayenne' }, 'Catamarca': { 'exemplarCity': 'Catamarca' }, 'Caracas': { 'exemplarCity': 'Caracas' }, 'Cancun': { 'exemplarCity': 'Cancun' }, 'Campo_Grande': { 'exemplarCity': 'Campo Grande' }, 'Cambridge_Bay': { 'exemplarCity': 'Cambridge Bay' }, 'Buenos_Aires': { 'exemplarCity': 'Buenos Aires' }, 'Boise': { 'exemplarCity': 'Boise' }, 'Asuncion': { 'exemplarCity': 'Asuncion' }, 'Aruba': { 'exemplarCity': 'Aruba' }, 'Argentina': { 'Rio_Gallegos': { 'exemplarCity': 'Rio Gallegos' }, 'San_Juan': { 'exemplarCity': 'San Juan' }, 'Ushuaia': { 'exemplarCity': 'Ushuaia' }, 'La_Rioja': { 'exemplarCity': 'La Rioja' }, 'San_Luis': { 'exemplarCity': 'San Luis' }, 'Salta': { 'exemplarCity': 'Salta' }, 'Tucuman': { 'exemplarCity': 'Tucuman' } }, 'Araguaina': { 'exemplarCity': 'Araguaina' }, 'Antigua': { 'exemplarCity': 'Antigua' }, 'Anguilla': { 'exemplarCity': 'Anguilla' }, 'Anchorage': { 'exemplarCity': 'Anchorage' }, 'Adak': { 'exemplarCity': 'Adak' }, 'Bahia': { 'exemplarCity': 'Bahia' }, 'Bahia_Banderas': { 'exemplarCity': 'Bahia Banderas' }, 'Barbados': { 'exemplarCity': 'Barbados' }, 'Belem': { 'exemplarCity': 'Belem' }, 'Belize': { 'exemplarCity': 'Belize' }, 'Blanc-Sablon': { 'exemplarCity': 'Blanc-Sablon' }, 'Boa_Vista': { 'exemplarCity': 'Boa Vista' }, 'Bogota': { 'exemplarCity': 'Bogota' }, 'Curacao': { 'exemplarCity': 'Curacao' }, 'Danmarkshavn': { 'exemplarCity': 'Danmarkshavn' }, 'Dawson': { 'exemplarCity': 'Dawson' }, 'Dawson_Creek': { 'exemplarCity': 'Dawson Creek' }, 'Denver': { 'exemplarCity': 'Denver' }, 'Detroit': { 'exemplarCity': 'Detroit' }, 'Hermosillo': { 'exemplarCity': 'Hermosillo' }, 'Indiana': { 'Vincennes': { 'exemplarCity': 'Vincennes, Indiana' }, 'Petersburg': { 'exemplarCity': 'Petersburg, Indiana' }, 'Tell_City': { 'exemplarCity': 'Tell City, Indiana' }, 'Knox': { 'exemplarCity': 'Knox, Indiana' }, 'Winamac': { 'exemplarCity': 'Winamac, Indiana' }, 'Marengo': { 'exemplarCity': 'Marengo, Indiana' }, 'Vevay': { 'exemplarCity': 'Vevay, Indiana' } }, 'Indianapolis': { 'exemplarCity': 'Indianapolis' }, 'Inuvik': { 'exemplarCity': 'Inuvik' }, 'Iqaluit': { 'exemplarCity': 'Iqaluit' }, 'Jamaica': { 'exemplarCity': 'Jamaica' }, 'Jujuy': { 'exemplarCity': 'Jujuy' }, 'Juneau': { 'exemplarCity': 'Juneau' }, 'Yellowknife': { 'exemplarCity': 'Yellowknife' }, 'Yakutat': { 'exemplarCity': 'Yakutat' }, 'Winnipeg': { 'exemplarCity': 'Winnipeg' }, 'Whitehorse': { 'exemplarCity': 'Whitehorse' }, 'Vancouver': { 'exemplarCity': 'Vancouver' }, 'Tortola': { 'exemplarCity': 'Tortola' }, 'Kralendijk': { 'exemplarCity': 'Kralendijk' }, 'Kentucky': { 'Monticello': { 'exemplarCity': 'Monticello, Kentucky' } }, 'Havana': { 'exemplarCity': 'Havana' }, 'Halifax': { 'exemplarCity': 'Halifax' }, 'Guyana': { 'exemplarCity': 'Guyana' }, 'Guayaquil': { 'exemplarCity': 'Guayaquil' }, 'Guatemala': { 'exemplarCity': 'Guatemala' }, 'Guadeloupe': { 'exemplarCity': 'Guadeloupe' }, 'Grenada': { 'exemplarCity': 'Grenada' }, 'Grand_Turk': { 'exemplarCity': 'Grand Turk' }, 'Goose_Bay': { 'exemplarCity': 'Goose Bay' }, 'Godthab': { 'exemplarCity': 'Nuuk' }, 'Glace_Bay': { 'exemplarCity': 'Glace Bay' }, 'Fortaleza': { 'exemplarCity': 'Fortaleza' }, 'El_Salvador': { 'exemplarCity': 'El Salvador' }, 'Eirunepe': { 'exemplarCity': 'Eirunepe' }, 'Edmonton': { 'exemplarCity': 'Edmonton' }, 'Dominica': { 'exemplarCity': 'Dominica' }, 'Chihuahua': { 'exemplarCity': 'Chihuahua' }, 'Coral_Harbour': { 'exemplarCity': 'Atikokan' }, 'Cordoba': { 'exemplarCity': 'Cordoba' }, 'Costa_Rica': { 'exemplarCity': 'Costa Rica' }, 'Creston': { 'exemplarCity': 'Creston' }, 'Cuiaba': { 'exemplarCity': 'Cuiaba' }, 'La_Paz': { 'exemplarCity': 'La Paz' }, 'Lima': { 'exemplarCity': 'Lima' }, 'Los_Angeles': { 'exemplarCity': 'Los Angeles' }, 'Louisville': { 'exemplarCity': 'Louisville' }, 'Lower_Princes': { 'exemplarCity': 'Lower Prince\'s Quarter' }, 'Maceio': { 'exemplarCity': 'Maceio' }, 'Managua': { 'exemplarCity': 'Managua' }, 'Manaus': { 'exemplarCity': 'Manaus' }, 'Marigot': { 'exemplarCity': 'Marigot' }, 'Martinique': { 'exemplarCity': 'Martinique' }, 'Matamoros': { 'exemplarCity': 'Matamoros' }, 'Mazatlan': { 'exemplarCity': 'Mazatlan' }, 'Mendoza': { 'exemplarCity': 'Mendoza' }, 'Menominee': { 'exemplarCity': 'Menominee' }, 'Merida': { 'exemplarCity': 'Merida' }, 'Metlakatla': { 'exemplarCity': 'Metlakatla' }, 'Mexico_City': { 'exemplarCity': 'Mexico City' }, 'Miquelon': { 'exemplarCity': 'Miquelon' }, 'Moncton': { 'exemplarCity': 'Moncton' }, 'Monterrey': { 'exemplarCity': 'Monterrey' }, 'Montevideo': { 'exemplarCity': 'Montevideo' }, 'Montreal': { 'exemplarCity': 'Montreal' }, 'Montserrat': { 'exemplarCity': 'Montserrat' }, 'Nassau': { 'exemplarCity': 'Nassau' }, 'New_York': { 'exemplarCity': 'New York' }, 'Nipigon': { 'exemplarCity': 'Nipigon' }, 'Nome': { 'exemplarCity': 'Nome' }, 'Noronha': { 'exemplarCity': 'Noronha' }, 'North_Dakota': { 'Beulah': { 'exemplarCity': 'Beulah, North Dakota' }, 'New_Salem': { 'exemplarCity': 'New Salem, North Dakota' }, 'Center': { 'exemplarCity': 'Center, North Dakota' } }, 'Ojinaga': { 'exemplarCity': 'Ojinaga' }, 'Panama': { 'exemplarCity': 'Panama' }, 'Pangnirtung': { 'exemplarCity': 'Pangnirtung' }, 'Paramaribo': { 'exemplarCity': 'Paramaribo' }, 'Phoenix': { 'exemplarCity': 'Phoenix' }, 'Port-au-Prince': { 'exemplarCity': 'Port-au-Prince' }, 'Port_of_Spain': { 'exemplarCity': 'Port of Spain' }, 'Porto_Velho': { 'exemplarCity': 'Porto Velho' }, 'Puerto_Rico': { 'exemplarCity': 'Puerto Rico' }, 'Rainy_River': { 'exemplarCity': 'Rainy River' }, 'Rankin_Inlet': { 'exemplarCity': 'Rankin Inlet' }, 'Recife': { 'exemplarCity': 'Recife' }, 'Regina': { 'exemplarCity': 'Regina' }, 'Resolute': { 'exemplarCity': 'Resolute' }, 'Rio_Branco': { 'exemplarCity': 'Rio Branco' }, 'Santa_Isabel': { 'exemplarCity': 'Santa Isabel' }, 'Santarem': { 'exemplarCity': 'Santarem' }, 'Santiago': { 'exemplarCity': 'Santiago' }, 'Santo_Domingo': { 'exemplarCity': 'Santo Domingo' }, 'Sao_Paulo': { 'exemplarCity': 'Sao Paulo' }, 'Scoresbysund': { 'exemplarCity': 'Ittoqqortoormiit' }, 'Shiprock': { 'exemplarCity': 'Shiprock' }, 'Sitka': { 'exemplarCity': 'Sitka' }, 'St_Barthelemy': { 'exemplarCity': 'St. Barthelemy' }, 'St_Johns': { 'exemplarCity': 'St. John\u02BCs' }, 'St_Kitts': { 'exemplarCity': 'St. Kitts' }, 'St_Lucia': { 'exemplarCity': 'St. Lucia' }, 'St_Thomas': { 'exemplarCity': 'St. Thomas' }, 'St_Vincent': { 'exemplarCity': 'St. Vincent' } }, 'Atlantic': { 'South_Georgia': { 'exemplarCity': 'South Georgia' }, 'Reykjavik': { 'exemplarCity': 'Reykjavik' }, 'Stanley': { 'exemplarCity': 'Stanley' }, 'St_Helena': { 'exemplarCity': 'St. Helena' }, 'Azores': { 'exemplarCity': 'Azores' }, 'Bermuda': { 'exemplarCity': 'Bermuda' }, 'Canary': { 'exemplarCity': 'Canary' }, 'Cape_Verde': { 'exemplarCity': 'Cape Verde' }, 'Faeroe': { 'exemplarCity': 'Faroe' }, 'Madeira': { 'exemplarCity': 'Madeira' } }, 'Europe': { 'Oslo': { 'exemplarCity': 'Oslo' }, 'Moscow': { 'exemplarCity': 'Moscow' }, 'Monaco': { 'exemplarCity': 'Monaco' }, 'Minsk': { 'exemplarCity': 'Minsk' }, 'Mariehamn': { 'exemplarCity': 'Mariehamn' }, 'Malta': { 'exemplarCity': 'Malta' }, 'Madrid': { 'exemplarCity': 'Madrid' }, 'Luxembourg': { 'exemplarCity': 'Luxembourg' }, 'London': { 'exemplarCity': 'London' }, 'Ljubljana': { 'exemplarCity': 'Ljubljana' }, 'Lisbon': { 'exemplarCity': 'Lisbon' }, 'Kiev': { 'exemplarCity': 'Kiev' }, 'Kaliningrad': { 'exemplarCity': 'Kaliningrad' }, 'Jersey': { 'exemplarCity': 'Jersey' }, 'Istanbul': { 'exemplarCity': 'Istanbul' }, 'Isle_of_Man': { 'exemplarCity': 'Isle of Man' }, 'Bucharest': { 'exemplarCity': 'Bucharest' }, 'Brussels': { 'exemplarCity': 'Brussels' }, 'Bratislava': { 'exemplarCity': 'Bratislava' }, 'Berlin': { 'exemplarCity': 'Berlin' }, 'Belgrade': { 'exemplarCity': 'Belgrade' }, 'Athens': { 'exemplarCity': 'Athens' }, 'Andorra': { 'exemplarCity': 'Andorra' }, 'Amsterdam': { 'exemplarCity': 'Amsterdam' }, 'Simferopol': { 'exemplarCity': 'Simferopol' }, 'Skopje': { 'exemplarCity': 'Skopje' }, 'Sofia': { 'exemplarCity': 'Sofia' }, 'Stockholm': { 'exemplarCity': 'Stockholm' }, 'Tallinn': { 'exemplarCity': 'Tallinn' }, 'Tirane': { 'exemplarCity': 'Tirane' }, 'Uzhgorod': { 'exemplarCity': 'Uzhgorod' }, 'Vaduz': { 'exemplarCity': 'Vaduz' }, 'Zurich': { 'exemplarCity': 'Zurich' }, 'Zaporozhye': { 'exemplarCity': 'Zaporozhye' }, 'Zagreb': { 'exemplarCity': 'Zagreb' }, 'Warsaw': { 'exemplarCity': 'Warsaw' }, 'Volgograd': { 'exemplarCity': 'Volgograd' }, 'Vilnius': { 'exemplarCity': 'Vilnius' }, 'Vienna': { 'exemplarCity': 'Vienna' }, 'Vatican': { 'exemplarCity': 'Vatican' }, 'Sarajevo': { 'exemplarCity': 'Sarajevo' }, 'San_Marino': { 'exemplarCity': 'San Marino' }, 'Samara': { 'exemplarCity': 'Samara' }, 'Rome': { 'exemplarCity': 'Rome' }, 'Riga': { 'exemplarCity': 'Riga' }, 'Prague': { 'exemplarCity': 'Prague' }, 'Podgorica': { 'exemplarCity': 'Podgorica' }, 'Paris': { 'exemplarCity': 'Paris' }, 'Helsinki': { 'exemplarCity': 'Helsinki' }, 'Guernsey': { 'exemplarCity': 'Guernsey' }, 'Gibraltar': { 'exemplarCity': 'Gibraltar' }, 'Dublin': { 'exemplarCity': 'Dublin' }, 'Copenhagen': { 'exemplarCity': 'Copenhagen' }, 'Chisinau': { 'exemplarCity': 'Chisinau' }, 'Busingen': { 'exemplarCity': 'Busingen' }, 'Budapest': { 'exemplarCity': 'Budapest' } }, 'Africa': { 'Libreville': { 'exemplarCity': 'Libreville' }, 'Lagos': { 'exemplarCity': 'Lagos' }, 'Kinshasa': { 'exemplarCity': 'Kinshasa' }, 'Kigali': { 'exemplarCity': 'Kigali' }, 'Khartoum': { 'exemplarCity': 'Khartoum' }, 'Kampala': { 'exemplarCity': 'Kampala' }, 'Juba': { 'exemplarCity': 'Juba' }, 'Johannesburg': { 'exemplarCity': 'Johannesburg' }, 'Harare': { 'exemplarCity': 'Harare' }, 'Gaborone': { 'exemplarCity': 'Gaborone' }, 'Freetown': { 'exemplarCity': 'Freetown' }, 'El_Aaiun': { 'exemplarCity': 'El Aaiun' }, 'Douala': { 'exemplarCity': 'Douala' }, 'Djibouti': { 'exemplarCity': 'Djibouti' }, 'Dar_es_Salaam': { 'exemplarCity': 'Dar es Salaam' }, 'Dakar': { 'exemplarCity': 'Dakar' }, 'Banjul': { 'exemplarCity': 'Banjul' }, 'Bangui': { 'exemplarCity': 'Bangui' }, 'Bamako': { 'exemplarCity': 'Bamako' }, 'Asmera': { 'exemplarCity': 'Asmara' }, 'Malabo': { 'exemplarCity': 'Malabo' }, 'Maputo': { 'exemplarCity': 'Maputo' }, 'Maseru': { 'exemplarCity': 'Maseru' }, 'Mbabane': { 'exemplarCity': 'Mbabane' }, 'Mogadishu': { 'exemplarCity': 'Mogadishu' }, 'Monrovia': { 'exemplarCity': 'Monrovia' }, 'Nairobi': { 'exemplarCity': 'Nairobi' }, 'Ndjamena': { 'exemplarCity': 'Ndjamena' }, 'Windhoek': { 'exemplarCity': 'Windhoek' }, 'Tunis': { 'exemplarCity': 'Tunis' }, 'Tripoli': { 'exemplarCity': 'Tripoli' }, 'Sao_Tome': { 'exemplarCity': 'Sao Tome' }, 'Porto-Novo': { 'exemplarCity': 'Porto-Novo' }, 'Ouagadougou': { 'exemplarCity': 'Ouagadougou' }, 'Nouakchott': { 'exemplarCity': 'Nouakchott' }, 'Niamey': { 'exemplarCity': 'Niamey' }, 'Lusaka': { 'exemplarCity': 'Lusaka' }, 'Lubumbashi': { 'exemplarCity': 'Lubumbashi' }, 'Luanda': { 'exemplarCity': 'Luanda' }, 'Lome': { 'exemplarCity': 'Lome' }, 'Conakry': { 'exemplarCity': 'Conakry' }, 'Ceuta': { 'exemplarCity': 'Ceuta' }, 'Casablanca': { 'exemplarCity': 'Casablanca' }, 'Cairo': { 'exemplarCity': 'Cairo' }, 'Bujumbura': { 'exemplarCity': 'Bujumbura' }, 'Brazzaville': { 'exemplarCity': 'Brazzaville' }, 'Blantyre': { 'exemplarCity': 'Blantyre' }, 'Bissau': { 'exemplarCity': 'Bissau' }, 'Abidjan': { 'exemplarCity': 'Abidjan' }, 'Accra': { 'exemplarCity': 'Accra' }, 'Addis_Ababa': { 'exemplarCity': 'Addis Ababa' }, 'Algiers': { 'exemplarCity': 'Algiers' } }, 'Asia': { 'Shanghai': { 'exemplarCity': 'Shanghai' }, 'Seoul': { 'exemplarCity': 'Seoul' }, 'Samarkand': { 'exemplarCity': 'Samarkand' }, 'Sakhalin': { 'exemplarCity': 'Sakhalin' }, 'Saigon': { 'exemplarCity': 'Ho Chi Minh' }, 'Riyadh': { 'exemplarCity': 'Riyadh' }, 'Rangoon': { 'exemplarCity': 'Rangoon' }, 'Qyzylorda': { 'exemplarCity': 'Qyzylorda' }, 'Qatar': { 'exemplarCity': 'Qatar' }, 'Pyongyang': { 'exemplarCity': 'Pyongyang' }, 'Pontianak': { 'exemplarCity': 'Pontianak' }, 'Phnom_Penh': { 'exemplarCity': 'Phnom Penh' }, 'Oral': { 'exemplarCity': 'Oral' }, 'Omsk': { 'exemplarCity': 'Omsk' }, 'Novosibirsk': { 'exemplarCity': 'Novosibirsk' }, 'Baghdad': { 'exemplarCity': 'Baghdad' }, 'Chongqing': { 'exemplarCity': 'Chongqing' }, 'Colombo': { 'exemplarCity': 'Colombo' }, 'Damascus': { 'exemplarCity': 'Damascus' }, 'Dhaka': { 'exemplarCity': 'Dhaka' }, 'Dili': { 'exemplarCity': 'Dili' }, 'Dubai': { 'exemplarCity': 'Dubai' }, 'Dushanbe': { 'exemplarCity': 'Dushanbe' }, 'Gaza': { 'exemplarCity': 'Gaza' }, 'Harbin': { 'exemplarCity': 'Harbin' }, 'Hebron': { 'exemplarCity': 'Hebron' }, 'Hong_Kong': { 'exemplarCity': 'Hong Kong' }, 'Hovd': { 'exemplarCity': 'Hovd' }, 'Irkutsk': { 'exemplarCity': 'Irkutsk' }, 'Jakarta': { 'exemplarCity': 'Jakarta' }, 'Jayapura': { 'exemplarCity': 'Jayapura' }, 'Ulaanbaatar': { 'exemplarCity': 'Ulaanbaatar' }, 'Urumqi': { 'exemplarCity': 'Urumqi' }, 'Ust-Nera': { 'exemplarCity': 'Ust-Nera' }, 'Vientiane': { 'exemplarCity': 'Vientiane' }, 'Vladivostok': { 'exemplarCity': 'Vladivostok' }, 'Yakutsk': { 'exemplarCity': 'Yakutsk' }, 'Yekaterinburg': { 'exemplarCity': 'Yekaterinburg' }, 'Yerevan': { 'exemplarCity': 'Yerevan' }, 'Tokyo': { 'exemplarCity': 'Tokyo' }, 'Thimphu': { 'exemplarCity': 'Thimphu' }, 'Tehran': { 'exemplarCity': 'Tehran' }, 'Tbilisi': { 'exemplarCity': 'Tbilisi' }, 'Tashkent': { 'exemplarCity': 'Tashkent' }, 'Taipei': { 'exemplarCity': 'Taipei' }, 'Singapore': { 'exemplarCity': 'Singapore' }, 'Jerusalem': { 'exemplarCity': 'Jerusalem' }, 'Ashgabat': { 'exemplarCity': 'Ashgabat' }, 'Aqtobe': { 'exemplarCity': 'Aqtobe' }, 'Aqtau': { 'exemplarCity': 'Aqtau' }, 'Anadyr': { 'exemplarCity': 'Anadyr' }, 'Amman': { 'exemplarCity': 'Amman' }, 'Almaty': { 'exemplarCity': 'Almaty' }, 'Aden': { 'exemplarCity': 'Aden' }, 'Bahrain': { 'exemplarCity': 'Bahrain' }, 'Baku': { 'exemplarCity': 'Baku' }, 'Bangkok': { 'exemplarCity': 'Bangkok' }, 'Beirut': { 'exemplarCity': 'Beirut' }, 'Bishkek': { 'exemplarCity': 'Bishkek' }, 'Brunei': { 'exemplarCity': 'Brunei' }, 'Calcutta': { 'exemplarCity': 'Kolkata' }, 'Choibalsan': { 'exemplarCity': 'Choibalsan' }, 'Kabul': { 'exemplarCity': 'Kabul' }, 'Kamchatka': { 'exemplarCity': 'Kamchatka' }, 'Karachi': { 'exemplarCity': 'Karachi' }, 'Kashgar': { 'exemplarCity': 'Kashgar' }, 'Katmandu': { 'exemplarCity': 'Kathmandu' }, 'Khandyga': { 'exemplarCity': 'Khandyga' }, 'Krasnoyarsk': { 'exemplarCity': 'Krasnoyarsk' }, 'Kuala_Lumpur': { 'exemplarCity': 'Kuala Lumpur' }, 'Kuching': { 'exemplarCity': 'Kuching' }, 'Kuwait': { 'exemplarCity': 'Kuwait' }, 'Macau': { 'exemplarCity': 'Macau' }, 'Magadan': { 'exemplarCity': 'Magadan' }, 'Makassar': { 'exemplarCity': 'Makassar' }, 'Manila': { 'exemplarCity': 'Manila' }, 'Muscat': { 'exemplarCity': 'Muscat' }, 'Nicosia': { 'exemplarCity': 'Nicosia' }, 'Novokuznetsk': { 'exemplarCity': 'Novokuznetsk' } } } }, 'calendars': { 'gregorian': { 'months': { 'format': { 'abbreviated': { '8': 'M08', '7': 'M07', '6': 'M06', '5': 'M05', '12': 'M12', '11': 'M11', '10': 'M10', '9': 'M09', '1': 'M01', '2': 'M02', '3': 'M03', '4': 'M04' }, 'narrow': { '8': '8', '7': '7', '6': '6', '5': '5', '12': '12', '11': '11', '10': '10', '9': '9', '1': '1', '2': '2', '3': '3', '4': '4' }, 'wide': { '8': 'M08', '7': 'M07', '6': 'M06', '5': 'M05', '12': 'M12', '11': 'M11', '10': 'M10', '9': 'M09', '1': 'M01', '2': 'M02', '3': 'M03', '4': 'M04' } }, 'stand-alone': { 'abbreviated': { '8': 'M08', '7': 'M07', '6': 'M06', '5': 'M05', '12': 'M12', '11': 'M11', '10': 'M10', '9': 'M09', '1': 'M01', '2': 'M02', '3': 'M03', '4': 'M04' }, 'narrow': { '8': '8', '7': '7', '6': '6', '5': '5', '12': '12', '11': '11', '10': '10', '9': '9', '1': '1', '2': '2', '3': '3', '4': '4' }, 'wide': { '8': 'M08', '7': 'M07', '6': 'M06', '5': 'M05', '12': 'M12', '11': 'M11', '10': 'M10', '9': 'M09', '1': 'M01', '2': 'M02', '3': 'M03', '4': 'M04' } } }, 'days': { 'format': { 'abbreviated': { 'sun': 'Sun', 'mon': 'Mon', 'tue': 'Tue', 'wed': 'Wed', 'thu': 'Thu', 'fri': 'Fri', 'sat': 'Sat' }, 'narrow': { 'sun': 'S', 'mon': 'M', 'tue': 'T', 'wed': 'W', 'thu': 'T', 'fri': 'F', 'sat': 'S' }, 'short': { 'sun': 'Sun', 'mon': 'Mon', 'tue': 'Tue', 'wed': 'Wed', 'thu': 'Thu', 'fri': 'Fri', 'sat': 'Sat' }, 'wide': { 'sun': 'Sun', 'mon': 'Mon', 'tue': 'Tue', 'wed': 'Wed', 'thu': 'Thu', 'fri': 'Fri', 'sat': 'Sat' } }, 'stand-alone': { 'abbreviated': { 'sun': 'Sun', 'mon': 'Mon', 'tue': 'Tue', 'wed': 'Wed', 'thu': 'Thu', 'fri': 'Fri', 'sat': 'Sat' }, 'narrow': { 'sun': 'S', 'mon': 'M', 'tue': 'T', 'wed': 'W', 'thu': 'T', 'fri': 'F', 'sat': 'S' }, 'short': { 'sun': 'Sun', 'mon': 'Mon', 'tue': 'Tue', 'wed': 'Wed', 'thu': 'Thu', 'fri': 'Fri', 'sat': 'Sat' }, 'wide': { 'sun': 'Sun', 'mon': 'Mon', 'tue': 'Tue', 'wed': 'Wed', 'thu': 'Thu', 'fri': 'Fri', 'sat': 'Sat' } } }, 'quarters': { 'format': { 'abbreviated': { '1': 'Q1', '2': 'Q2', '3': 'Q3', '4': 'Q4' }, 'narrow': { '1': '1', '2': '2', '3': '3', '4': '4' }, 'wide': { '1': 'Q1', '2': 'Q2', '3': 'Q3', '4': 'Q4' } }, 'stand-alone': { 'abbreviated': { '1': 'Q1', '2': 'Q2', '3': 'Q3', '4': 'Q4' }, 'narrow': { '1': '1', '2': '2', '3': '3', '4': '4' }, 'wide': { '1': 'Q1', '2': 'Q2', '3': 'Q3', '4': 'Q4' } } }, 'dayPeriods': { 'format': { 'abbreviated': { 'am': 'AM', 'pm': 'PM' }, 'narrow': { 'am': 'AM', 'pm': 'PM' }, 'wide': { 'am': 'AM', 'pm': 'PM' } }, 'stand-alone': { 'abbreviated': { 'am': 'AM', 'pm': 'PM' }, 'narrow': { 'am': 'AM', 'pm': 'PM' }, 'wide': { 'am': 'AM', 'pm': 'PM' } } }, 'eras': { 'eraNames': { '0': 'BCE', '0-alt-variant': 'BCE', '1': 'CE', '1-alt-variant': 'CE' }, 'eraAbbr': { '0': 'BCE', '0-alt-variant': 'BCE', '1': 'CE', '1-alt-variant': 'CE' }, 'eraNarrow': { '0': 'BCE', '0-alt-variant': 'BCE', '1': 'CE', '1-alt-variant': 'CE' } }, 'dateFormats': { 'full': 'y MMMM d, EEEE', 'long': 'y MMMM d', 'medium': 'y MMM d', 'short': 'y-MM-dd' }, 'timeFormats': { 'full': 'HH:mm:ss zzzz', 'long': 'HH:mm:ss z', 'medium': 'HH:mm:ss', 'short': 'HH:mm' }, 'dateTimeFormats': { 'full': '{1} {0}', 'long': '{1} {0}', 'medium': '{1} {0}', 'short': '{1} {0}', 'availableFormats': { 'Hms': 'HH:mm:ss', 'hms': 'h:mm:ss a', 'Hm': 'HH:mm', 'hm': 'h:mm a', 'H': 'HH', 'h': 'h a', 'GyMMMEd': 'G y MMM d, E', 'GyMMMd': 'G y MMM d', 'd': 'd', 'Ed': 'd, E', 'Ehm': 'E h:mm a', 'EHm': 'E HH:mm', 'Ehms': 'E h:mm:ss a', 'EHms': 'E HH:mm:ss', 'Gy': 'G y', 'GyMMM': 'G y MMM', 'yM': 'y-MM', 'yMd': 'y-MM-dd', 'yMEd': 'y-MM-dd, E', 'yMMM': 'y MMM', 'yMMMd': 'y MMM d', 'yMMMEd': 'y MMM d, E', 'yQQQ': 'y QQQ', 'yQQQQ': 'y QQQQ', 'y': 'y', 'ms': 'mm:ss', 'MMMEd': 'MMM d, E', 'MMMd': 'MMM d', 'MMM': 'LLL', 'MEd': 'MM-dd, E', 'Md': 'MM-dd', 'M': 'L' }, 'appendItems': { 'Second': '{0} ({2}: {1})', 'Quarter': '{0} ({2}: {1})', 'Month': '{0} ({2}: {1})', 'Year': '{1} {0}', 'Week': '{0} ({2}: {1})', 'Timezone': '{0} {1}', 'Day': '{0} ({2}: {1})', 'Day-Of-Week': '{0} {1}', 'Era': '{1} {0}', 'Hour': '{0} ({2}: {1})', 'Minute': '{0} ({2}: {1})' }, 'intervalFormats': { 'MMMEd': { 'd': 'MMM d, E \u2013 MMM d, E', 'M': 'MMM d, E \u2013 MMM d, E' }, 'MMMd': { 'd': 'MMM d\u2013d', 'M': 'MMM d \u2013 MMM d' }, 'MMM': { 'M': 'LLL\u2013LLL' }, 'MEd': { 'd': 'MM-dd, E \u2013 MM-dd, E', 'M': 'MM-dd, E \u2013 MM-dd, E' }, 'Md': { 'd': 'MM-dd \u2013 MM-dd', 'M': 'MM-dd \u2013 MM-dd' }, 'M': { 'M': 'MM\u2013MM' }, 'Hv': { 'H': 'HH\u2013HH v' }, 'hv': { 'a': 'h a \u2013 h a v', 'h': 'h\u2013h a v' }, 'y': { 'y': 'y\u2013y' }, 'yM': { 'M': 'y-MM \u2013 y-MM', 'y': 'y-MM \u2013 y-MM' }, 'yMd': { 'd': 'y-MM-dd \u2013 y-MM-dd', 'M': 'y-MM-dd \u2013 y-MM-dd', 'y': 'y-MM-dd \u2013 y-MM-dd' }, 'yMEd': { 'd': 'y-MM-dd, E \u2013 y-MM-dd, E', 'M': 'y-MM-dd, E \u2013 y-MM-dd, E', 'y': 'y-MM-dd, E \u2013 y-MM-dd, E' }, 'yMMM': { 'M': 'y MMM\u2013MMM', 'y': 'y MMM \u2013 y MMM' }, 'yMMMd': { 'd': 'y MMM d\u2013d', 'M': 'y MMM d \u2013 MMM d', 'y': 'y MMM d \u2013 y MMM d' }, 'yMMMEd': { 'd': 'y MMM d, E \u2013 MMM d, E', 'M': 'y MMM d, E \u2013 MMM d, E', 'y': 'y MMM d, E \u2013 y MMM d, E' }, 'yMMMM': { 'M': 'y MMMM\u2013MMMM', 'y': 'y MMMM \u2013 y MMMM' }, 'Hmv': { 'H': 'HH:mm\u2013HH:mm v', 'm': 'HH:mm\u2013HH:mm v' }, 'hmv': { 'a': 'h:mm a \u2013 h:mm a v', 'h': 'h:mm\u2013h:mm a v', 'm': 'h:mm\u2013h:mm a v' }, 'Hm': { 'H': 'HH:mm\u2013HH:mm', 'm': 'HH:mm\u2013HH:mm' }, 'hm': { 'a': 'h:mm a \u2013 h:mm a', 'h': 'h:mm\u2013h:mm a', 'm': 'h:mm\u2013h:mm a' }, 'H': { 'H': 'HH\u2013HH' }, 'h': { 'a': 'h a \u2013 h a', 'h': 'h\u2013h a' }, 'd': { 'd': 'd\u2013d' }, 'intervalFormatFallback': '{0} \u2013 {1}' } } } } }, false); AstroDate.leapSeconds({ '1972': { '6': { '30': 1 }, '12': { '31': 1 } }, '1973': { '12': { '31': 1 } }, '1974': { '12': { '31': 1 } }, '1975': { '12': { '31': 1 } }, '1976': { '12': { '31': 1 } }, '1977': { '12': { '31': 1 } }, '1978': { '12': { '31': 1 } }, '1979': { '12': { '31': 1 } }, '1981': { '6': { '30': 1 } }, '1982': { '6': { '30': 1 } }, '1983': { '6': { '30': 1 } }, '1985': { '6': { '30': 1 } }, '1987': { '12': { '31': 1 } }, '1989': { '12': { '31': 1 } }, '1990': { '12': { '31': 1 } }, '1992': { '6': { '30': 1 } }, '1993': { '6': { '30': 1 } }, '1994': { '6': { '30': 1 } }, '1995': { '12': { '31': 1 } }, '1997': { '6': { '30': 1 } }, '1998': { '12': { '31': 1 } }, '2005': { '12': { '31': 1 } }, '2008': { '12': { '31': 1 } }, '2012': { '6': { '30': 1 } }, 'total': { '6': { '30': 10 }, '12': { '31': 15 }, 'sum': 35 } }, false); return AstroDate; }; nfeDefinition = null; return tempSafariNFE; }()))); tempSafariNFE = null; }((function (thisContext) { 'use strict'; /*global window, global, self */ // detect the global context of the environment if ('object' === typeof window && null !== window && window.window === window) { thisContext = window; } else if ('object' === typeof global && null !== global && global.global === global) { thisContext = global; } else if ('object' === typeof self && null !== self && self.self === self) { thisContext = self; } if ('object' !== typeof thisContext || null === thisContext) { throw new TypeError('Invalid global context'); } /*global */ return thisContext; }(this)), (function () { 'use strict'; // return undefined for privateUndefined return; }())));
Added missing argument for month to name
astrodate.js
Added missing argument for month to name
<ide><path>strodate.js <ide> if (this.isJulian()) { <ide> val = monthName(gregorianToJulian(struct), type, this.currentLang()); <ide> } else { <del> val = monthName(struct, type); <add> val = monthName(struct, type, this.currentLang()); <ide> } <ide> } <ide>
Java
mit
630972364fedba6e6c0474fca9ce60cf5a231767
0
gfneto/Hive2Hive,Hive2Hive/Hive2Hive
package org.hive2hive.core.processes.implementations.share.pkupdate; import org.apache.log4j.Logger; import org.hive2hive.core.log.H2HLoggerFactory; import org.hive2hive.core.model.FileVersion; import org.hive2hive.core.model.MetaFile; import org.hive2hive.core.network.data.IDataManager; import org.hive2hive.core.processes.framework.abstracts.ProcessStep; import org.hive2hive.core.processes.framework.decorators.AsyncComponent; import org.hive2hive.core.processes.framework.exceptions.InvalidProcessStateException; import org.hive2hive.core.processes.framework.exceptions.ProcessExecutionException; import org.hive2hive.core.processes.implementations.context.ChunkPKUpdateContext; import org.hive2hive.core.processes.implementations.context.MetaDocumentPKUpdateContext; public class InitializeChunkUpdateStep extends ProcessStep { private final static Logger logger = H2HLoggerFactory.getLogger(InitializeChunkUpdateStep.class); private final MetaDocumentPKUpdateContext context; private final IDataManager dataManager; public InitializeChunkUpdateStep(MetaDocumentPKUpdateContext context, IDataManager dataManager) { this.context = context; this.dataManager = dataManager; } @Override protected void doExecute() throws InvalidProcessStateException, ProcessExecutionException { MetaFile metaFile = context.consumeMetaFile(); if (metaFile == null) { throw new ProcessExecutionException("Meta File not found"); } logger.debug("Initialize updating all chunks for a file in a shared folder..."); int counter = 0; for (FileVersion version : metaFile.getVersions()) { for (String chunkId : version.getChunkIds()) { // each chunk gets an own context ChunkPKUpdateContext chunkContext = new ChunkPKUpdateContext( context.consumeOldProtectionKeys(), context.consumeNewProtectionKeys(), chunkId); // create the step and wrap it to run asynchronous, attach it to the parent process ChangeProtectionKeyStep changeStep = new ChangeProtectionKeyStep(chunkContext, dataManager); getParent().add(new AsyncComponent(changeStep)); counter++; } } logger.debug(counter + " chunks need to update their protection key"); } }
org.hive2hive.core/src/org/hive2hive/core/processes/implementations/share/pkupdate/InitializeChunkUpdateStep.java
package org.hive2hive.core.processes.implementations.share.pkupdate; import org.apache.log4j.Logger; import org.hive2hive.core.log.H2HLoggerFactory; import org.hive2hive.core.model.FileVersion; import org.hive2hive.core.model.MetaFile; import org.hive2hive.core.network.data.IDataManager; import org.hive2hive.core.processes.framework.abstracts.ProcessStep; import org.hive2hive.core.processes.framework.decorators.AsyncComponent; import org.hive2hive.core.processes.framework.exceptions.InvalidProcessStateException; import org.hive2hive.core.processes.framework.exceptions.ProcessExecutionException; import org.hive2hive.core.processes.implementations.context.ChunkPKUpdateContext; import org.hive2hive.core.processes.implementations.context.MetaDocumentPKUpdateContext; public class InitializeChunkUpdateStep extends ProcessStep { private final static Logger logger = H2HLoggerFactory.getLogger(InitializeChunkUpdateStep.class); private final MetaDocumentPKUpdateContext context; private final IDataManager dataManager; public InitializeChunkUpdateStep(MetaDocumentPKUpdateContext context, IDataManager dataManager) { this.context = context; this.dataManager = dataManager; } @Override protected void doExecute() throws InvalidProcessStateException, ProcessExecutionException { MetaFile metaFile = context.consumeMetaFile(); if (metaFile == null) { throw new ProcessExecutionException("Meta File not found"); } logger.debug("Initialize updating all chunks for a file in a shared folder..."); for (FileVersion version : metaFile.getVersions()) { for (String chunkId : version.getChunkIds()) { // each chunk gets an own context ChunkPKUpdateContext chunkContext = new ChunkPKUpdateContext( context.consumeOldProtectionKeys(), context.consumeNewProtectionKeys(), chunkId); // create the step and wrap it to run asynchronous, attach it to the parent process ChangeProtectionKeyStep changeStep = new ChangeProtectionKeyStep(chunkContext, dataManager); getParent().add(new AsyncComponent(changeStep)); } } } }
minor addition of log entry Signed-off-by: Nico Rutishauser <[email protected]>
org.hive2hive.core/src/org/hive2hive/core/processes/implementations/share/pkupdate/InitializeChunkUpdateStep.java
minor addition of log entry
<ide><path>rg.hive2hive.core/src/org/hive2hive/core/processes/implementations/share/pkupdate/InitializeChunkUpdateStep.java <ide> } <ide> <ide> logger.debug("Initialize updating all chunks for a file in a shared folder..."); <add> int counter = 0; <ide> for (FileVersion version : metaFile.getVersions()) { <ide> for (String chunkId : version.getChunkIds()) { <ide> // each chunk gets an own context <ide> // create the step and wrap it to run asynchronous, attach it to the parent process <ide> ChangeProtectionKeyStep changeStep = new ChangeProtectionKeyStep(chunkContext, dataManager); <ide> getParent().add(new AsyncComponent(changeStep)); <add> counter++; <ide> } <ide> } <add> <add> logger.debug(counter + " chunks need to update their protection key"); <ide> } <ide> }
Java
apache-2.0
a66a56b108c04f05efcb9b965361d692435acc59
0
perezd/bazel,twitter-forks/bazel,katre/bazel,perezd/bazel,Asana/bazel,cushon/bazel,mrdomino/bazel,kchodorow/bazel-1,juhalindfors/bazel-patches,kchodorow/bazel,iamthearm/bazel,mikelikespie/bazel,dslomov/bazel,damienmg/bazel,akira-baruah/bazel,kchodorow/bazel,mbrukman/bazel,mikelikespie/bazel,ulfjack/bazel,UrbanCompass/bazel,mikelalcon/bazel,UrbanCompass/bazel,werkt/bazel,hermione521/bazel,katre/bazel,ulfjack/bazel,aehlig/bazel,spxtr/bazel,LuminateWireless/bazel,aehlig/bazel,perezd/bazel,mbrukman/bazel,safarmer/bazel,variac/bazel,bazelbuild/bazel,LuminateWireless/bazel,meteorcloudy/bazel,Asana/bazel,spxtr/bazel,katre/bazel,perezd/bazel,katre/bazel,mbrukman/bazel,davidzchen/bazel,iamthearm/bazel,variac/bazel,safarmer/bazel,ButterflyNetwork/bazel,mikelalcon/bazel,mikelikespie/bazel,werkt/bazel,perezd/bazel,twitter-forks/bazel,mrdomino/bazel,katre/bazel,ButterflyNetwork/bazel,snnn/bazel,hermione521/bazel,dslomov/bazel-windows,cushon/bazel,mrdomino/bazel,meteorcloudy/bazel,variac/bazel,dropbox/bazel,Asana/bazel,variac/bazel,twitter-forks/bazel,snnn/bazel,snnn/bazel,juhalindfors/bazel-patches,LuminateWireless/bazel,variac/bazel,bazelbuild/bazel,hermione521/bazel,damienmg/bazel,juhalindfors/bazel-patches,mrdomino/bazel,aehlig/bazel,mikelalcon/bazel,kchodorow/bazel-1,mikelikespie/bazel,ulfjack/bazel,meteorcloudy/bazel,bazelbuild/bazel,LuminateWireless/bazel,dslomov/bazel,dslomov/bazel-windows,juhalindfors/bazel-patches,hermione521/bazel,zhexuany/bazel,twitter-forks/bazel,ulfjack/bazel,damienmg/bazel,kchodorow/bazel-1,UrbanCompass/bazel,safarmer/bazel,iamthearm/bazel,akira-baruah/bazel,aehlig/bazel,LuminateWireless/bazel,mbrukman/bazel,iamthearm/bazel,twitter-forks/bazel,snnn/bazel,werkt/bazel,werkt/bazel,bazelbuild/bazel,akira-baruah/bazel,iamthearm/bazel,davidzchen/bazel,dropbox/bazel,meteorcloudy/bazel,snnn/bazel,safarmer/bazel,cushon/bazel,kchodorow/bazel,kchodorow/bazel-1,damienmg/bazel,zhexuany/bazel,spxtr/bazel,kchodorow/bazel-1,juhalindfors/bazel-patches,ulfjack/bazel,dslomov/bazel-windows,katre/bazel,bazelbuild/bazel,aehlig/bazel,kchodorow/bazel,ButterflyNetwork/bazel,akira-baruah/bazel,spxtr/bazel,dropbox/bazel,kchodorow/bazel-1,perezd/bazel,cushon/bazel,hermione521/bazel,Asana/bazel,zhexuany/bazel,safarmer/bazel,aehlig/bazel,meteorcloudy/bazel,mrdomino/bazel,dropbox/bazel,Asana/bazel,kchodorow/bazel,mikelikespie/bazel,perezd/bazel,mrdomino/bazel,mikelalcon/bazel,mbrukman/bazel,ulfjack/bazel,dslomov/bazel,damienmg/bazel,meteorcloudy/bazel,bazelbuild/bazel,UrbanCompass/bazel,ButterflyNetwork/bazel,cushon/bazel,twitter-forks/bazel,hermione521/bazel,juhalindfors/bazel-patches,kchodorow/bazel,zhexuany/bazel,spxtr/bazel,davidzchen/bazel,iamthearm/bazel,Asana/bazel,UrbanCompass/bazel,mikelalcon/bazel,dslomov/bazel,mbrukman/bazel,werkt/bazel,mikelikespie/bazel,cushon/bazel,davidzchen/bazel,ButterflyNetwork/bazel,dslomov/bazel-windows,damienmg/bazel,davidzchen/bazel,safarmer/bazel,akira-baruah/bazel,spxtr/bazel,kchodorow/bazel,zhexuany/bazel,akira-baruah/bazel,zhexuany/bazel,dslomov/bazel,werkt/bazel,variac/bazel,twitter-forks/bazel,variac/bazel,dslomov/bazel,snnn/bazel,dslomov/bazel-windows,mikelalcon/bazel,juhalindfors/bazel-patches,spxtr/bazel,davidzchen/bazel,damienmg/bazel,dropbox/bazel,LuminateWireless/bazel,dslomov/bazel,davidzchen/bazel,dslomov/bazel-windows,snnn/bazel,UrbanCompass/bazel,aehlig/bazel,dropbox/bazel,ulfjack/bazel,Asana/bazel,meteorcloudy/bazel,ButterflyNetwork/bazel
// Copyright 2015 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.java.bazel; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Writer; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Set; import javax.lang.model.SourceVersion; import javax.tools.DiagnosticListener; import javax.tools.JavaCompiler; import javax.tools.JavaFileManager; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.StandardLocation; /** * Provides a {@link JavaCompiler} that has behavior as similar as possible * to the java compiler provided by default by Bazel. * Replace calls to {@link javax.tools.ToolProvider#getSystemJavaCompiler} * with calls to {@link BazelJavaCompiler#newInstance}. * * <p>This class is typically used only from a host build tool or in tests. * When using this in production, langtools.jar and the bootclasspath jars * are deployed as separate jar files within the runfiles directory. */ public class BazelJavaCompiler { // The default blessed javac options. private static final String DEFAULT_BOOTCLASSPATH = JavacBootclasspath.asString(); private static final String[] DEFAULT_JAVACOPTS; static { List<String> defaultJavacopts = new ArrayList<>(); for (String javacopt : JavaBuilderConfig.defaultJavacOpts()) { if (javacopt.startsWith("-Xep")) { // ignore Error Prone-specific flags accepted by JavaBuilder continue; } defaultJavacopts.add(javacopt); } // The bootclasspath must be specified both via an invocation option and // via fileManager.setLocation(PLATFORM_CLASS_PATH), to work around what // appears to be a bug in jdk[6,8] javac. defaultJavacopts.addAll(Arrays.asList("-bootclasspath", DEFAULT_BOOTCLASSPATH)); DEFAULT_JAVACOPTS = defaultJavacopts.toArray(new String[defaultJavacopts.size()]); } private static final Class<? extends JavaCompiler> JAVA_COMPILER_CLASS = getJavaCompilerClass(); private static class LangtoolsClassLoader extends URLClassLoader { public LangtoolsClassLoader() throws MalformedURLException { super(new URL[] { getLangtoolsJar().toURI().toURL() }, // We use the bootstrap classloader (null) as the parent classloader // instead of the default "system" class loader; we intentionally do // not consult the classpath. This way the class path is not // polluted, we reduce the risk of having multiple langtools on the // classpath, and langtools.jar is only opened if this method is // called. And this will reduce problems for automated java // dependency analysis, which other teams are trying to do. null); } } private static Class<? extends JavaCompiler> getJavaCompilerClass() { try { ClassLoader cl = new LangtoolsClassLoader(); return getJavaCompilerClass(cl); } catch (Exception e) { throw new RuntimeException("Cannot get java compiler", e); } } private static Class<? extends JavaCompiler> getJavaCompilerClass(ClassLoader cl) throws Exception { return Class.forName("com.sun.tools.javac.api.JavacTool", true, cl) .asSubclass(JavaCompiler.class); } /** * Returns the langtools jar. */ public static File getLangtoolsJar() { return JavaLangtools.file(); } /** * Returns the default javacopts, including the blessed bootclasspath. */ public static List<String> getDefaultJavacopts() { return new ArrayList<>(Arrays.asList(DEFAULT_JAVACOPTS)); } /** * Returns a new {@link JavaCompiler} that has behavior as similar as * possible to the java compiler provided by default by the bazel build * system, independent of the user-specified {@code JAVABASE}. * * <p>More precisely, this method works analogously to {@link * javax.tools.ToolProvider#getSystemJavaCompiler}, but returns a {@code * JavaCompiler} that differs in these details: * * <ul> * * <li> uses the blessed javac implementation: {@code //tools/defaults:java_langtools}, * as defined by bazel's --java_langtools flag. * * <li> uses the blessed boot class path: {@code //tools/defaults:javac_bootclasspath}, * as defined by bazel's --javac_bootclasspath flag. * * <li> uses the blessed default values for javac options such as {@code -source} * * </ul> * * <p>This class ensures that (by default) the {@code -source}, {@code * -target} and {@code -bootclasspath} flags all agree and specify the same * (blessed) JDK version, for language and API compatibility. * * <p>This method finds the javac implementation using a custom classloader * that does not consult the user's classpath. This works well, unless the * return value is cast to a javac-implementation class like {@code * JavacTask}, in which case the dreaded classloader error "can't cast * JavacTaskImpl to JavacTask" raises its ugly head, in which case you should * use {@link #newInstance(ClassLoader)} instead. */ public static JavaCompiler newInstance() { try { return newInstance(JAVA_COMPILER_CLASS.getConstructor().newInstance()); } catch (Exception e) { throw new RuntimeException("Cannot get java compiler", e); } } /** * Returns a new {@link JavaCompiler} that has behavior as similar as * possible to the java compiler provided by default by bazel, * independent of the user-specified {@code JAVABASE}. * * <p>This method has effect identical to {@link #newInstance()} (and that * method is generally preferred to this one), except that the javac * implementation is found via the provided classloader instead of defining a * custom classloader that knows the standard location of the blessed javac * implementation. * * <p>This method is needed when the return value is cast to a * javac-implementation class like {@code JavacTask}, to avoid the dreaded * multiple classloader error "can't cast JavacTaskImpl to JavacTask". * * <p>Typically, users should pass {@code ClassLoader.getSystemClassLoader()} * as the argument to this method. */ public static JavaCompiler newInstance(ClassLoader cl) { try { return newInstance(getJavaCompilerClass(cl).getConstructor().newInstance()); } catch (Exception e) { throw new RuntimeException("Cannot get java compiler", e); } } private static JavaCompiler newInstance(final JavaCompiler delegate) { // We forward most operations to the JavaCompiler implementation in langtools.jar. return new JavaCompiler() { @Override public CompilationTask getTask( Writer out, JavaFileManager fileManager, DiagnosticListener<? super JavaFileObject> diagnosticListener, Iterable<String> options, Iterable<String> classes, Iterable<? extends JavaFileObject> compilationUnits) { // We prepend bazel's default javacopts to user javacopts, // so that the user can override them. javac supports this // "last option wins" style of option override. List<String> fullOptions = getDefaultJavacopts(); if (options != null) { for (String option : options) { fullOptions.add(option); } } return delegate.getTask(out, fileManager, diagnosticListener, fullOptions, classes, compilationUnits); } @Override public StandardJavaFileManager getStandardFileManager( DiagnosticListener<? super JavaFileObject> diagnosticListener, Locale locale, Charset charset) { StandardJavaFileManager fileManager = delegate.getStandardFileManager( diagnosticListener, locale, charset); try { fileManager.setLocation( StandardLocation.PLATFORM_CLASS_PATH, // bootclasspath JavacBootclasspath.asFiles()); } catch (IOException e) { // Should never happen, according to javadocs for setLocation throw new RuntimeException(e); } return fileManager; } @Override public int run(InputStream in, OutputStream out, OutputStream err, String... arguments) { // prepend bazel's default javacopts to user arguments List<String> args = getDefaultJavacopts(); args.addAll(Arrays.asList(arguments)); return delegate.run(in, out, err, args.toArray(new String[0])); } @Override public Set<SourceVersion> getSourceVersions() { return delegate.getSourceVersions(); } @Override public int isSupportedOption(String option) { return delegate.isSupportedOption(option); } }; } }
src/java_tools/buildjar/java/com/google/devtools/build/java/bazel/BazelJavaCompiler.java
// Copyright 2015 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.java.bazel; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Writer; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Set; import javax.lang.model.SourceVersion; import javax.tools.DiagnosticListener; import javax.tools.JavaCompiler; import javax.tools.JavaFileManager; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.StandardLocation; /** * Provides a {@link JavaCompiler} that has behavior as similar as possible * to the java compiler provided by default by Bazel. * Replace calls to {@link javax.tools.ToolProvider#getSystemJavaCompiler} * with calls to {@link BazelJavaCompiler#newInstance}. * * <p>This class is typically used only from a host build tool or in tests. * When using this in production, langtools.jar and the bootclasspath jars * are deployed as separate jar files within the runfiles directory. */ public class BazelJavaCompiler { // The default blessed javac options. private static final String DEFAULT_BOOTCLASSPATH = JavacBootclasspath.asString(); private static final String[] DEFAULT_JAVACOPTS; static { List<String> defaultJavacopts = new ArrayList<>(JavaBuilderConfig.defaultJavacOpts()); // The bootclasspath must be specified both via an invocation option and // via fileManager.setLocation(PLATFORM_CLASS_PATH), to work around what // appears to be a bug in jdk[6,8] javac. defaultJavacopts.addAll(Arrays.asList("-bootclasspath", DEFAULT_BOOTCLASSPATH)); DEFAULT_JAVACOPTS = defaultJavacopts.toArray(new String[defaultJavacopts.size()]); } private static final Class<? extends JavaCompiler> JAVA_COMPILER_CLASS = getJavaCompilerClass(); private static class LangtoolsClassLoader extends URLClassLoader { public LangtoolsClassLoader() throws MalformedURLException { super(new URL[] { getLangtoolsJar().toURI().toURL() }, // We use the bootstrap classloader (null) as the parent classloader // instead of the default "system" class loader; we intentionally do // not consult the classpath. This way the class path is not // polluted, we reduce the risk of having multiple langtools on the // classpath, and langtools.jar is only opened if this method is // called. And this will reduce problems for automated java // dependency analysis, which other teams are trying to do. null); } } private static Class<? extends JavaCompiler> getJavaCompilerClass() { try { ClassLoader cl = new LangtoolsClassLoader(); return getJavaCompilerClass(cl); } catch (Exception e) { throw new RuntimeException("Cannot get java compiler", e); } } private static Class<? extends JavaCompiler> getJavaCompilerClass(ClassLoader cl) throws Exception { return Class.forName("com.sun.tools.javac.api.JavacTool", true, cl) .asSubclass(JavaCompiler.class); } /** * Returns the langtools jar. */ public static File getLangtoolsJar() { return JavaLangtools.file(); } /** * Returns the default javacopts, including the blessed bootclasspath. */ public static List<String> getDefaultJavacopts() { return new ArrayList<>(Arrays.asList(DEFAULT_JAVACOPTS)); } /** * Returns a new {@link JavaCompiler} that has behavior as similar as * possible to the java compiler provided by default by the bazel build * system, independent of the user-specified {@code JAVABASE}. * * <p>More precisely, this method works analogously to {@link * javax.tools.ToolProvider#getSystemJavaCompiler}, but returns a {@code * JavaCompiler} that differs in these details: * * <ul> * * <li> uses the blessed javac implementation: {@code //tools/defaults:java_langtools}, * as defined by bazel's --java_langtools flag. * * <li> uses the blessed boot class path: {@code //tools/defaults:javac_bootclasspath}, * as defined by bazel's --javac_bootclasspath flag. * * <li> uses the blessed default values for javac options such as {@code -source} * * </ul> * * <p>This class ensures that (by default) the {@code -source}, {@code * -target} and {@code -bootclasspath} flags all agree and specify the same * (blessed) JDK version, for language and API compatibility. * * <p>This method finds the javac implementation using a custom classloader * that does not consult the user's classpath. This works well, unless the * return value is cast to a javac-implementation class like {@code * JavacTask}, in which case the dreaded classloader error "can't cast * JavacTaskImpl to JavacTask" raises its ugly head, in which case you should * use {@link #newInstance(ClassLoader)} instead. */ public static JavaCompiler newInstance() { try { return newInstance(JAVA_COMPILER_CLASS.newInstance()); } catch (Exception e) { throw new RuntimeException("Cannot get java compiler", e); } } /** * Returns a new {@link JavaCompiler} that has behavior as similar as * possible to the java compiler provided by default by bazel, * independent of the user-specified {@code JAVABASE}. * * <p>This method has effect identical to {@link #newInstance()} (and that * method is generally preferred to this one), except that the javac * implementation is found via the provided classloader instead of defining a * custom classloader that knows the standard location of the blessed javac * implementation. * * <p>This method is needed when the return value is cast to a * javac-implementation class like {@code JavacTask}, to avoid the dreaded * multiple classloader error "can't cast JavacTaskImpl to JavacTask". * * <p>Typically, users should pass {@code ClassLoader.getSystemClassLoader()} * as the argument to this method. */ public static JavaCompiler newInstance(ClassLoader cl) { try { return newInstance(getJavaCompilerClass(cl).newInstance()); } catch (Exception e) { throw new RuntimeException("Cannot get java compiler", e); } } private static JavaCompiler newInstance(final JavaCompiler delegate) { // We forward most operations to the JavaCompiler implementation in langtools.jar. return new JavaCompiler() { @Override public CompilationTask getTask( Writer out, JavaFileManager fileManager, DiagnosticListener<? super JavaFileObject> diagnosticListener, Iterable<String> options, Iterable<String> classes, Iterable<? extends JavaFileObject> compilationUnits) { // We prepend bazel's default javacopts to user javacopts, // so that the user can override them. javac supports this // "last option wins" style of option override. List<String> fullOptions = getDefaultJavacopts(); if (options != null) { for (String option : options) { fullOptions.add(option); } } return delegate.getTask(out, fileManager, diagnosticListener, fullOptions, classes, compilationUnits); } @Override public StandardJavaFileManager getStandardFileManager( DiagnosticListener<? super JavaFileObject> diagnosticListener, Locale locale, Charset charset) { StandardJavaFileManager fileManager = delegate.getStandardFileManager( diagnosticListener, locale, charset); try { fileManager.setLocation( StandardLocation.PLATFORM_CLASS_PATH, // bootclasspath JavacBootclasspath.asFiles()); } catch (IOException e) { // Should never happen, according to javadocs for setLocation throw new RuntimeException(e); } return fileManager; } @Override public int run(InputStream in, OutputStream out, OutputStream err, String... arguments) { // prepend bazel's default javacopts to user arguments List<String> args = getDefaultJavacopts(); args.addAll(Arrays.asList(arguments)); return delegate.run(in, out, err, args.toArray(new String[0])); } @Override public Set<SourceVersion> getSourceVersions() { return delegate.getSourceVersions(); } @Override public int isSupportedOption(String option) { return delegate.isSupportedOption(option); } }; } }
Drop Error Prone-specific javacopts -- MOS_MIGRATED_REVID=127576227
src/java_tools/buildjar/java/com/google/devtools/build/java/bazel/BazelJavaCompiler.java
Drop Error Prone-specific javacopts
<ide><path>rc/java_tools/buildjar/java/com/google/devtools/build/java/bazel/BazelJavaCompiler.java <ide> import java.util.List; <ide> import java.util.Locale; <ide> import java.util.Set; <del> <ide> import javax.lang.model.SourceVersion; <ide> import javax.tools.DiagnosticListener; <ide> import javax.tools.JavaCompiler; <ide> <ide> private static final String[] DEFAULT_JAVACOPTS; <ide> static { <del> List<String> defaultJavacopts = new ArrayList<>(JavaBuilderConfig.defaultJavacOpts()); <del> <add> List<String> defaultJavacopts = new ArrayList<>(); <add> for (String javacopt : JavaBuilderConfig.defaultJavacOpts()) { <add> if (javacopt.startsWith("-Xep")) { <add> // ignore Error Prone-specific flags accepted by JavaBuilder <add> continue; <add> } <add> defaultJavacopts.add(javacopt); <add> } <add> <ide> // The bootclasspath must be specified both via an invocation option and <ide> // via fileManager.setLocation(PLATFORM_CLASS_PATH), to work around what <ide> // appears to be a bug in jdk[6,8] javac. <ide> */ <ide> public static JavaCompiler newInstance() { <ide> try { <del> return newInstance(JAVA_COMPILER_CLASS.newInstance()); <add> return newInstance(JAVA_COMPILER_CLASS.getConstructor().newInstance()); <ide> } catch (Exception e) { <ide> throw new RuntimeException("Cannot get java compiler", e); <ide> } <ide> */ <ide> public static JavaCompiler newInstance(ClassLoader cl) { <ide> try { <del> return newInstance(getJavaCompilerClass(cl).newInstance()); <add> return newInstance(getJavaCompilerClass(cl).getConstructor().newInstance()); <ide> } catch (Exception e) { <ide> throw new RuntimeException("Cannot get java compiler", e); <ide> }
Java
agpl-3.0
14e3fb0f7efa2a8d051979fb0dfac4b6051c004a
0
animotron/core,animotron/core
/* * Copyright (C) 2011-2012 The Animo Project * http://animotron.org * * This file is part of Animotron. * * Animotron is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * Animotron is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of * the GNU Affero General Public License along with Animotron. * If not, see <http://www.gnu.org/licenses/>. */ package org.animotron.synchro; import org.animotron.graph.Properties; import org.animotron.graph.handler.GraphHandler; import org.animotron.graph.serializer.DigestSerializer; import org.animotron.manipulator.Controller; import org.animotron.statement.Statement; import org.neo4j.graphdb.Relationship; import java.io.*; import java.nio.ByteBuffer; /** * @author <a href="mailto:[email protected]">Evgeny Gazdovsky</a> * */ public class BinaryGraphHandler implements GraphHandler { public final static byte START_GRAPH = 1; public final static byte START_RELATIONSHIP = 2; public final static byte END_RELATIONSHIP = 0; public final static byte FS = 3; public final static byte END_GRAPH = -1; public final static byte STRING = 0; public final static byte LONG = 1; public final static byte DOUBLE = 2; public final static byte BOOLEAN = 3; private OutputStream os; private String fs = null; public BinaryGraphHandler(OutputStream os) { this.os = os; } private void write(byte[] b) throws IOException { os.write(b.length); os.write(b); } private void write(String d) throws IOException { os.write(STRING); write(d.getBytes()); } private void write(Long d) throws IOException { os.write(LONG); byte[] b = new byte[8]; ByteBuffer.wrap(b).putLong(d); os.write(b); } private void write(Double d) throws IOException { os.write(DOUBLE); byte[] b = new byte[8]; ByteBuffer.wrap(b).putDouble(d); os.write(b); } private void write(Boolean d) throws IOException { os.write(BOOLEAN); byte b; if (d) { b = 1; } else { b = 0; } os.write(b); } @Override public void start(Statement statement, Statement parent, Relationship r, int level, boolean isOne, int pos, boolean isLast) throws IOException { if (level == 0) { if (Properties.FS.has(r)) { fs = (String) Properties.FS.get(r); } byte[] hash = DigestSerializer._.serialize(r); write(hash); } os.write(START_RELATIONSHIP); write(statement.name().getBytes()); if (r != null) { Object o = statement.reference(r); if (o != null) { os.write(3); if (o instanceof String) { write((String) o); } else if (o instanceof Long) { write((Long) o); } else if (o instanceof Double) { write((Double) o); } else if (o instanceof Boolean) { write((Boolean) o); } } } } @Override public void end(Statement statement, Statement parent, Relationship r, int level, boolean isOne, int pos, boolean isLast) throws IOException { os.write(END_RELATIONSHIP); } @Override public void startGraph() throws IOException { os.write(START_GRAPH); } @Override public void endGraph() throws IOException { if (fs != null) { os.write(FS); write(fs.getBytes()); File file = new File(fs); byte[] size = new byte[8]; ByteBuffer.wrap(size).putLong(file.length()); os.write(size); InputStream is = new FileInputStream(file); byte buf[] = new byte[1024 * 4]; int len; while((len=is.read(buf))>0) { os.write(buf, 0, len); } is.close(); } os.write(END_GRAPH); } @Override public Controller getController() { return null; } }
src/main/java/org/animotron/synchro/BinaryGraphHandler.java
package org.animotron.synchro; import org.animotron.graph.Properties; import org.animotron.graph.handler.GraphHandler; import org.animotron.graph.serializer.DigestSerializer; import org.animotron.manipulator.Controller; import org.animotron.statement.Statement; import org.neo4j.graphdb.Relationship; import java.io.*; import java.nio.ByteBuffer; /** * Created with IntelliJ IDEA. * User: evgeny * Date: 14.12.12 * Time: 19:00 * To change this template use File | Settings | File Templates. */ public class BinaryGraphHandler implements GraphHandler { public final static byte START_GRAPH = 1; public final static byte START_RELATIONSHIP = 2; public final static byte END_RELATIONSHIP = 0; public final static byte FS = 3; public final static byte END_GRAPH = -1; public final static byte STRING = 0; public final static byte LONG = 1; public final static byte DOUBLE = 2; public final static byte BOOLEAN = 3; private OutputStream os; private String fs = null; public BinaryGraphHandler(OutputStream os) { this.os = os; } private void write(byte[] b) throws IOException { os.write(b.length); os.write(b); } private void write(String d) throws IOException { os.write(STRING); write(d.getBytes()); } private void write(Long d) throws IOException { os.write(LONG); byte[] b = new byte[8]; ByteBuffer.wrap(b).putLong(d); os.write(b); } private void write(Double d) throws IOException { os.write(DOUBLE); byte[] b = new byte[8]; ByteBuffer.wrap(b).putDouble(d); os.write(b); } private void write(Boolean d) throws IOException { os.write(BOOLEAN); byte b; if (d) { b = 1; } else { b = 0; } os.write(b); } @Override public void start(Statement statement, Statement parent, Relationship r, int level, boolean isOne, int pos, boolean isLast) throws IOException { if (level == 0) { if (Properties.FS.has(r)) { fs = (String) Properties.FS.get(r); } byte[] hash = DigestSerializer._.serialize(r); write(hash); } os.write(START_RELATIONSHIP); write(statement.name().getBytes()); if (r != null) { Object o = statement.reference(r); if (o != null) { os.write(3); if (o instanceof String) { write((String) o); } else if (o instanceof Long) { write((Long) o); } else if (o instanceof Double) { write((Double) o); } else if (o instanceof Boolean) { write((Boolean) o); } } } } @Override public void end(Statement statement, Statement parent, Relationship r, int level, boolean isOne, int pos, boolean isLast) throws IOException { os.write(END_RELATIONSHIP); } @Override public void startGraph() throws IOException { os.write(START_GRAPH); } @Override public void endGraph() throws IOException { if (fs != null) { os.write(FS); write(fs.getBytes()); File file = new File(fs); byte[] size = new byte[8]; ByteBuffer.wrap(size).putLong(file.length()); os.write(size); InputStream is = new FileInputStream(file); byte buf[] = new byte[1024 * 4]; int len; while((len=is.read(buf))>0) { os.write(buf, 0, len); } is.close(); } os.write(END_GRAPH); } @Override public Controller getController() { return null; } }
binary serializer of the animo expression
src/main/java/org/animotron/synchro/BinaryGraphHandler.java
binary serializer of the animo expression
<ide><path>rc/main/java/org/animotron/synchro/BinaryGraphHandler.java <add>/* <add> * Copyright (C) 2011-2012 The Animo Project <add> * http://animotron.org <add> * <add> * This file is part of Animotron. <add> * <add> * Animotron is free software: you can redistribute it and/or modify <add> * it under the terms of the GNU Affero General Public License as <add> * published by the Free Software Foundation, either version 3 of <add> * the License, or (at your option) any later version. <add> * <add> * Animotron is distributed in the hope that it will be useful, <add> * but WITHOUT ANY WARRANTY; without even the implied warranty of <add> * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the <add> * GNU Affero General Public License for more details. <add> * <add> * You should have received a copy of <add> * the GNU Affero General Public License along with Animotron. <add> * If not, see <http://www.gnu.org/licenses/>. <add> */ <ide> package org.animotron.synchro; <ide> <ide> import org.animotron.graph.Properties; <ide> import java.nio.ByteBuffer; <ide> <ide> /** <del> * Created with IntelliJ IDEA. <del> * User: evgeny <del> * Date: 14.12.12 <del> * Time: 19:00 <del> * To change this template use File | Settings | File Templates. <add> * @author <a href="mailto:[email protected]">Evgeny Gazdovsky</a> <add> * <ide> */ <ide> public class BinaryGraphHandler implements GraphHandler { <ide>
Java
mit
61b3ce96a5bb92ec21901500def24e6a35e22de6
0
elBukkit/MagicPlugin,elBukkit/MagicPlugin,elBukkit/MagicLib,elBukkit/MagicPlugin
package com.elmakers.mine.bukkit.action; import com.elmakers.mine.bukkit.api.action.CastContext; import com.elmakers.mine.bukkit.api.action.GUIAction; import com.elmakers.mine.bukkit.api.block.CurrencyItem; import com.elmakers.mine.bukkit.api.magic.Mage; import com.elmakers.mine.bukkit.api.magic.MageController; import com.elmakers.mine.bukkit.api.magic.Messages; import com.elmakers.mine.bukkit.api.spell.Spell; import com.elmakers.mine.bukkit.api.spell.SpellResult; import com.elmakers.mine.bukkit.api.wand.Wand; import com.elmakers.mine.bukkit.api.wand.WandUpgradePath; import com.elmakers.mine.bukkit.block.MaterialAndData; import com.elmakers.mine.bukkit.integration.VaultController; import com.elmakers.mine.bukkit.spell.BaseSpell; import com.elmakers.mine.bukkit.utility.CompatibilityUtils; import com.elmakers.mine.bukkit.utility.ConfigurationUtils; import com.elmakers.mine.bukkit.utility.InventoryUtils; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; public abstract class BaseShopAction extends BaseSpellAction implements GUIAction { protected boolean requireWand = false; private String requiredPath = null; private String requiresCompletedPath = null; private String exactPath = null; protected boolean autoUpgrade = false; protected boolean useXP = false; protected boolean sell = false; protected boolean useItems = false; protected boolean showConfirmation = true; protected MaterialAndData confirmFillMaterial; protected CastContext context; private Map<Integer, ShopItem> showingItems; protected class ShopItem { private final ItemStack item; private final double worth; public ShopItem(ItemStack item, double worth) { this.item = item; this.worth = worth; } public double getWorth() { return worth; } public ItemStack getItem() { return item; } } @Override public void deactivated() { } public SpellResult checkContext(CastContext context) { Mage mage = context.getMage(); MageController controller = mage.getController(); Player player = mage.getPlayer(); if (player == null) { return SpellResult.PLAYER_REQUIRED; } if (!requireWand) { return SpellResult.CAST; } Wand wand = mage.getActiveWand(); if (wand == null) { context.sendMessage("no_wand"); return SpellResult.FAIL; } WandUpgradePath path = wand.getPath(); // Check path requirements if (requiredPath != null || exactPath != null) { if (path == null) { context.sendMessage(context.getMessage("no_path").replace("$wand", wand.getName())); return SpellResult.FAIL; } if ((requiredPath != null && !path.hasPath(requiredPath)) || (exactPath != null && !exactPath.equals(path.getKey()))) { WandUpgradePath requiresPath = controller.getPath(requiredPath); if (requiresPath != null) { context.sendMessage(context.getMessage("no_required_path").replace("$path", requiresPath.getName())); } else { context.getLogger().warning("Invalid path specified in AddSpell action: " + requiredPath); } return SpellResult.FAIL; } if (requiresCompletedPath != null) { WandUpgradePath pathUpgrade = path.getUpgrade(); if (pathUpgrade == null) { context.sendMessage(context.getMessage("no_upgrade").replace("$wand", wand.getName())); return SpellResult.FAIL; } if (path.canEnchant(wand)) { context.sendMessage(context.getMessage("no_path_end").replace("$path", pathUpgrade.getName())); return SpellResult.FAIL; } } } return SpellResult.CAST; } @Override public void clicked(InventoryClickEvent event) { event.setCancelled(true); ItemStack item = event.getCurrentItem(); if (context == null || item == null || !InventoryUtils.hasMeta(item, "shop")) { return; } int slotIndex = Integer.parseInt(InventoryUtils.getMeta(item, "shop")); MageController controller = context.getController(); Messages messages = controller.getMessages(); Mage mage = context.getMage(); Wand wand = mage.getActiveWand(); boolean isItems = (useItems || !VaultController.hasEconomy()) && controller.getWorthItem() != null; boolean isXP = (useXP || (!VaultController.hasEconomy() && controller.getWorthItem() == null)); ShopItem shopItem = showingItems.get(slotIndex); if (shopItem == null) { return; } double worth = shopItem.getWorth(); boolean hasCosts = true; if (worth > 0) { if (isXP) { worth = worth * controller.getWorthXP(); hasCosts = mage.getExperience() > (int)(double)worth; } else if (isItems) { worth = worth * controller.getWorthBase() / controller.getWorthItemAmount(); int hasAmount = getItemAmount(controller, mage); hasCosts = hasAmount >= worth; } else { worth = worth * controller.getWorthBase(); hasCosts = VaultController.getInstance().has(mage.getPlayer(), worth); } } if (sell) { hasCosts = getItemAmount(controller, item, mage) > 0; } if (!hasCosts) { String costString = context.getMessage("insufficient_resources"); if (sell) { String amountString = formatItemAmount(controller, item, 1); costString = costString.replace("$cost", amountString); } else if (isXP) { String xpAmount = Integer.toString((int)(double)worth); xpAmount = messages.get("costs.xp_amount").replace("$amount", xpAmount); costString = costString.replace("$cost", xpAmount); } else if (isItems) { String amountString = formatItemAmount(controller, worth); costString = costString.replace("$cost", amountString); } else { costString = costString.replace("$cost", VaultController.getInstance().format(worth)); } context.sendMessage(costString); } else { String itemName = controller.describeItem(item); if (InventoryUtils.hasMeta(item, "confirm")) { String inventoryTitle = context.getMessage("confirm_title", "Buy $item").replace("$item", itemName); Inventory confirmInventory = CompatibilityUtils.createInventory(null, 9, inventoryTitle); InventoryUtils.removeMeta(item, "confirm"); for (int i = 0; i < 9; i++) { if (i != 4) { ItemStack filler = confirmFillMaterial.getItemStack(1); ItemMeta meta = filler.getItemMeta(); if (meta != null) { meta.setDisplayName(ChatColor.DARK_GRAY + (i < 4 ? "-->" : "<--")); filler.setItemMeta(meta); } confirmInventory.setItem(i, filler); } else { confirmInventory.setItem(i, item); } } mage.deactivateGUI(); mage.activateGUI(this); mage.getPlayer().openInventory(confirmInventory); return; } String costString = context.getMessage("deducted"); if (sell) { String amountString = formatItemAmount(controller, worth); costString = costString.replace("$cost", amountString); } else if (isXP) { String xpAmount = Integer.toString((int)(double)worth); xpAmount = messages.get("costs.xp_amount").replace("$amount", xpAmount); costString = costString.replace("$cost", xpAmount); } else if (isItems) { String amountString = formatItemAmount(controller, worth); costString = costString.replace("$cost", amountString); } else { costString = costString.replace("$cost", VaultController.getInstance().format(worth)); } costString = costString.replace("$item", itemName); context.sendMessage(costString); if (sell) { removeItems(controller, mage, item, 1); if (isXP) { mage.giveExperience((int) (double) worth); } else if (isItems) { int amount = (int)Math.ceil(worth); ItemStack worthItem = controller.getWorthItem(); while (amount > 0) { worthItem = InventoryUtils.getCopy(worthItem); worthItem.setAmount(Math.min(amount, 64)); amount -= worthItem.getAmount(); mage.giveItem(worthItem); } } else { VaultController.getInstance().depositPlayer(mage.getPlayer(), worth); } } else { if (requireWand) { if (wand == null) { context.sendMessage("no_wand"); mage.deactivateGUI(); return; } if (!wand.addItem(item)) { String inapplicable = context.getMessage("not_applicable", "You can't buy $item").replace("$item", itemName); context.sendMessage(inapplicable); mage.deactivateGUI(); return; } } if (isXP) { mage.removeExperience((int)(double)worth); } else if (isItems) { removeItems(controller, mage, (int)Math.ceil(worth)); } else { VaultController.getInstance().withdrawPlayer(mage.getPlayer(), worth); } if (!requireWand) { context.getController().giveItemToPlayer(mage.getPlayer(), item); } if (wand != null && autoUpgrade) { com.elmakers.mine.bukkit.api.wand.WandUpgradePath path = wand.getPath(); WandUpgradePath nextPath = path != null ? path.getUpgrade(): null; if (nextPath != null && path.checkUpgradeRequirements(wand, null) && !path.canEnchant(wand)) { path.upgrade(wand, mage); } } } onPurchase(context); } mage.deactivateGUI(); } protected void onPurchase(CastContext context) { } public void prepare(CastContext context, ConfigurationSection parameters) { super.prepare(context, parameters); useXP = parameters.getBoolean("use_xp", false); sell = parameters.getBoolean("sell", false); useItems = parameters.getBoolean("use_items", false); showConfirmation = parameters.getBoolean("confirm", true); confirmFillMaterial = ConfigurationUtils.getMaterialAndData(parameters, "confirm_filler", new MaterialAndData(Material.AIR)); requiredPath = parameters.getString("path", null); exactPath = parameters.getString("path_exact", null); requiresCompletedPath = parameters.getString("path_end", null); autoUpgrade = parameters.getBoolean("auto_upgrade", false); requireWand = parameters.getBoolean("require_wand", false); if (requiresCompletedPath != null) { requiredPath = requiresCompletedPath; } if (requiredPath != null || exactPath != null) { requireWand = true; } } public SpellResult showItems(CastContext context, List<ShopItem> items) { Mage mage = context.getMage(); this.context = context; Player player = mage.getPlayer(); if (player == null) { return SpellResult.PLAYER_REQUIRED; } this.showingItems = new HashMap<Integer, ShopItem>(); MageController controller = context.getController(); Messages messages = controller.getMessages(); // Load items List<ItemStack> itemStacks = new ArrayList<ItemStack>(); boolean isItems = (useItems || !VaultController.hasEconomy()) && controller.getWorthItem() != null; boolean isXP = (useXP || (!VaultController.hasEconomy() && controller.getWorthItem() == null)); String costString = context.getMessage("cost_lore"); for (ShopItem shopItem : items) { double worth = shopItem.getWorth(); ItemStack item = shopItem.getItem(); if (item == null) continue; ItemMeta meta = item.getItemMeta(); if (meta == null) { itemStacks.add(item); continue; } List<String> lore = meta.getLore(); if (lore == null) { lore = new ArrayList<String>(); } String costs; if (isXP) { worth = worth * controller.getWorthXP(); String xpAmount = Integer.toString((int)(double)worth); xpAmount = messages.get("costs.xp_amount").replace("$amount", xpAmount); costs = costString.replace("$cost", xpAmount); } else if (isItems) { worth = worth * controller.getWorthBase() / controller.getWorthItemAmount(); String itemWorth = formatItemAmount(controller, worth); costs = costString.replace("$cost", itemWorth); } else { worth = worth * controller.getWorthBase(); costs = costString.replace("$cost", VaultController.getInstance().format(worth)); } lore.add(ChatColor.GOLD + costs); meta.setLore(lore); item.setItemMeta(meta); item = InventoryUtils.makeReal(item); int currentSlot = itemStacks.size(); InventoryUtils.setMeta(item, "shop", Integer.toString(currentSlot)); if (showConfirmation) { InventoryUtils.setMeta(item, "confirm", "true"); } this.showingItems.put(currentSlot, shopItem); itemStacks.add(item); } if (itemStacks.size() == 0) { context.sendMessage("no_items"); return SpellResult.FAIL; } String inventoryTitle = context.getMessage("title", "Shop ($balance)"); if (isXP) { String xpAmount = Integer.toString(mage.getExperience()); xpAmount = messages.get("costs.xp_amount").replace("$amount", xpAmount); inventoryTitle = inventoryTitle.replace("$balance", xpAmount); } else if (isItems) { int itemAmount = getItemAmount(controller, mage); inventoryTitle = inventoryTitle.replace("$balance", formatItemAmount(controller, itemAmount)); } else { double balance = VaultController.getInstance().getBalance(player); inventoryTitle = inventoryTitle.replace("$balance", VaultController.getInstance().format(balance)); } int invSize = (itemStacks.size() / 10 + 1) * 9; Inventory displayInventory = CompatibilityUtils.createInventory(null, invSize, inventoryTitle); for (ItemStack item : itemStacks) { displayInventory.addItem(item); } mage.activateGUI(this); mage.getPlayer().openInventory(displayInventory); return SpellResult.CAST; } protected String formatItemAmount(MageController controller, double amount) { CurrencyItem currency = controller.getCurrency(); if (currency != null) { int evenAmount = (int)Math.ceil(amount); String currencyName = currency.getName(); if (currencyName != null && !currencyName.isEmpty()) { if (evenAmount == 1) { return Integer.toString(evenAmount) + " " + currencyName; } String pluralName = currency.getPluralName(); if (pluralName == null || pluralName.isEmpty()) { pluralName = currencyName; } return Integer.toString(evenAmount) + " " + pluralName; } } return formatItemAmount(controller, controller.getWorthItem(), amount); } protected String formatItemAmount(MageController controller, ItemStack item, double amount) { return Integer.toString((int)Math.ceil(amount)) + " " + controller.describeItem(item); } protected int getItemAmount(MageController controller, Mage mage) { return getItemAmount(controller, controller.getWorthItem(), mage); } protected int getItemAmount(MageController controller, ItemStack worthItem, Mage mage) { int itemAmount = 0; ItemStack[] contents = mage.getInventory().getContents(); for (int i = 0; i < contents.length; i++) { if (contents[i] != null && controller.itemsAreEqual(contents[i], worthItem)) { itemAmount += contents[i].getAmount(); } } return itemAmount; } protected void removeItems(MageController controller, Mage mage, int amount) { removeItems(controller, mage, controller.getWorthItem(), amount); } protected void removeItems(MageController controller, Mage mage, ItemStack worthItem, int amount) { int remainingAmount = amount; Inventory inventory = mage.getInventory(); ItemStack[] contents = inventory.getContents(); for (int i = 0; i < contents.length; i++) { if (contents[i] != null && controller.itemsAreEqual(contents[i], worthItem)) { if (contents[i].getAmount() <= remainingAmount) { remainingAmount -= contents[i].getAmount(); contents[i] = null; } else { contents[i].setAmount(contents[i].getAmount() - remainingAmount); remainingAmount = 0; } } if (remainingAmount <= 0) { break; } } inventory.setContents(contents); } @Override public void getParameterNames(Spell spell, Collection<String> parameters) { super.getParameterNames(spell, parameters); parameters.add("confirm"); parameters.add("path"); parameters.add("path_end"); parameters.add("path_exact"); parameters.add("auto_upgrade"); parameters.add("require_wand"); } @Override public void getParameterOptions(Spell spell, String parameterKey, Collection<String> examples) { MageController controller = spell.getController(); if (parameterKey.equals("path") || parameterKey.equals("path_exact") || parameterKey.equals("path_end")) { examples.addAll(controller.getWandPathKeys()); } else if (parameterKey.equals("require_wand") || parameterKey.equals("confirm") || parameterKey.equals("auto_upgrade")) { examples.addAll(Arrays.asList((BaseSpell.EXAMPLE_BOOLEANS))); } else { super.getParameterOptions(spell, parameterKey, examples); } } }
src/main/java/com/elmakers/mine/bukkit/action/BaseShopAction.java
package com.elmakers.mine.bukkit.action; import com.elmakers.mine.bukkit.api.action.CastContext; import com.elmakers.mine.bukkit.api.action.GUIAction; import com.elmakers.mine.bukkit.api.block.CurrencyItem; import com.elmakers.mine.bukkit.api.magic.Mage; import com.elmakers.mine.bukkit.api.magic.MageController; import com.elmakers.mine.bukkit.api.magic.Messages; import com.elmakers.mine.bukkit.api.spell.Spell; import com.elmakers.mine.bukkit.api.spell.SpellResult; import com.elmakers.mine.bukkit.api.wand.Wand; import com.elmakers.mine.bukkit.api.wand.WandUpgradePath; import com.elmakers.mine.bukkit.block.MaterialAndData; import com.elmakers.mine.bukkit.integration.VaultController; import com.elmakers.mine.bukkit.spell.BaseSpell; import com.elmakers.mine.bukkit.utility.CompatibilityUtils; import com.elmakers.mine.bukkit.utility.ConfigurationUtils; import com.elmakers.mine.bukkit.utility.InventoryUtils; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; public abstract class BaseShopAction extends BaseSpellAction implements GUIAction { protected boolean requireWand = false; private String requiredPath = null; private String requiresCompletedPath = null; private String exactPath = null; protected boolean autoUpgrade = false; protected boolean useXP = false; protected boolean sell = false; protected boolean useItems = false; protected boolean showConfirmation = true; protected MaterialAndData confirmFillMaterial; protected CastContext context; private Map<Integer, ShopItem> showingItems; protected class ShopItem { private final ItemStack item; private final double worth; public ShopItem(ItemStack item, double worth) { this.item = item; this.worth = worth; } public double getWorth() { return worth; } public ItemStack getItem() { return item; } } @Override public void deactivated() { } public SpellResult checkContext(CastContext context) { Mage mage = context.getMage(); MageController controller = mage.getController(); Player player = mage.getPlayer(); if (player == null) { return SpellResult.PLAYER_REQUIRED; } if (!requireWand) { return SpellResult.CAST; } Wand wand = mage.getActiveWand(); if (wand == null) { context.sendMessage("no_wand"); return SpellResult.FAIL; } WandUpgradePath path = wand.getPath(); // Check path requirements if (requiredPath != null || exactPath != null) { if (path == null) { context.sendMessage(context.getMessage("no_path").replace("$wand", wand.getName())); return SpellResult.FAIL; } if ((requiredPath != null && !path.hasPath(requiredPath)) || (exactPath != null && !exactPath.equals(path.getKey()))) { WandUpgradePath requiresPath = controller.getPath(requiredPath); if (requiresPath != null) { context.sendMessage(context.getMessage("no_required_path").replace("$path", requiresPath.getName())); } else { context.getLogger().warning("Invalid path specified in AddSpell action: " + requiredPath); } return SpellResult.FAIL; } if (requiresCompletedPath != null) { WandUpgradePath pathUpgrade = path.getUpgrade(); if (pathUpgrade == null) { context.sendMessage(context.getMessage("no_upgrade").replace("$wand", wand.getName())); return SpellResult.FAIL; } if (path.canEnchant(wand)) { context.sendMessage(context.getMessage("no_path_end").replace("$path", pathUpgrade.getName())); return SpellResult.FAIL; } } } return SpellResult.CAST; } @Override public void clicked(InventoryClickEvent event) { event.setCancelled(true); ItemStack item = event.getCurrentItem(); if (context == null || item == null || !InventoryUtils.hasMeta(item, "shop")) { return; } int slotIndex = Integer.parseInt(InventoryUtils.getMeta(item, "shop")); MageController controller = context.getController(); Messages messages = controller.getMessages(); Mage mage = context.getMage(); Wand wand = mage.getActiveWand(); boolean isItems = (useItems || !VaultController.hasEconomy()) && controller.getWorthItem() != null; boolean isXP = (useXP || (!VaultController.hasEconomy() && controller.getWorthItem() == null)); ShopItem shopItem = showingItems.get(slotIndex); if (shopItem == null) { return; } double worth = shopItem.getWorth(); boolean hasCosts = true; if (worth > 0) { if (isXP) { worth = worth * controller.getWorthXP(); hasCosts = mage.getExperience() > (int)(double)worth; } else if (isItems) { worth = worth * controller.getWorthBase() / controller.getWorthItemAmount(); int hasAmount = getItemAmount(controller, mage); hasCosts = hasAmount >= worth; } else { worth = worth * controller.getWorthBase(); hasCosts = VaultController.getInstance().has(mage.getPlayer(), worth); } } if (sell) { hasCosts = getItemAmount(controller, item, mage) > 0; } if (!hasCosts) { String costString = context.getMessage("insufficient_resources"); if (sell) { String amountString = formatItemAmount(controller, item, 1); costString = costString.replace("$cost", amountString); } else if (isXP) { String xpAmount = Integer.toString((int)(double)worth); xpAmount = messages.get("costs.xp_amount").replace("$amount", xpAmount); costString = costString.replace("$cost", xpAmount); } else if (isItems) { String amountString = formatItemAmount(controller, worth); costString = costString.replace("$cost", amountString); } else { costString = costString.replace("$cost", VaultController.getInstance().format(worth)); } context.sendMessage(costString); } else { String itemName = controller.describeItem(item); if (InventoryUtils.hasMeta(item, "confirm")) { String inventoryTitle = context.getMessage("confirm_title", "Buy $item").replace("$item", itemName); Inventory confirmInventory = CompatibilityUtils.createInventory(null, 9, inventoryTitle); InventoryUtils.removeMeta(item, "confirm"); for (int i = 0; i < 9; i++) { if (i != 4) { ItemStack filler = confirmFillMaterial.getItemStack(1); ItemMeta meta = filler.getItemMeta(); if (meta != null) { meta.setDisplayName(ChatColor.DARK_GRAY + (i < 4 ? "-->" : "<--")); filler.setItemMeta(meta); } confirmInventory.setItem(i, filler); } else { confirmInventory.setItem(i, item); } } mage.deactivateGUI(); mage.activateGUI(this); mage.getPlayer().openInventory(confirmInventory); return; } String costString = context.getMessage("deducted"); if (sell) { String amountString = formatItemAmount(controller, worth); costString = costString.replace("$cost", amountString); } else if (isXP) { String xpAmount = Integer.toString((int)(double)worth); xpAmount = messages.get("costs.xp_amount").replace("$amount", xpAmount); costString = costString.replace("$cost", xpAmount); } else if (isItems) { String amountString = formatItemAmount(controller, worth); costString = costString.replace("$cost", amountString); } else { costString = costString.replace("$cost", VaultController.getInstance().format(worth)); } costString = costString.replace("$item", itemName); context.sendMessage(costString); if (sell) { removeItems(controller, mage, item, 1); if (isXP) { mage.giveExperience((int) (double) worth); } else if (isItems) { int amount = (int)Math.ceil(worth); ItemStack worthItem = controller.getWorthItem(); while (amount > 0) { worthItem = InventoryUtils.getCopy(worthItem); worthItem.setAmount(Math.min(amount, 64)); amount -= worthItem.getAmount(); mage.giveItem(worthItem); } } else { VaultController.getInstance().depositPlayer(mage.getPlayer(), worth); } } else { if (requireWand) { if (wand == null) { context.sendMessage("no_wand"); mage.deactivateGUI(); return; } if (!wand.addItem(item)) { String inapplicable = context.getMessage("not_applicable", "You can't buy $item").replace("$item", itemName); context.sendMessage(inapplicable); mage.deactivateGUI(); return; } } if (isXP) { mage.removeExperience((int)(double)worth); } else if (isItems) { removeItems(controller, mage, (int)Math.ceil(worth)); } else { VaultController.getInstance().withdrawPlayer(mage.getPlayer(), worth); } if (!requireWand) { context.getController().giveItemToPlayer(mage.getPlayer(), item); } if (wand != null && autoUpgrade) { com.elmakers.mine.bukkit.api.wand.WandUpgradePath path = wand.getPath(); WandUpgradePath nextPath = path != null ? path.getUpgrade(): null; if (nextPath != null && path.checkUpgradeRequirements(wand, null) && !path.canEnchant(wand)) { path.upgrade(wand, mage); } } } onPurchase(context); } mage.deactivateGUI(); } protected void onPurchase(CastContext context) { } public void prepare(CastContext context, ConfigurationSection parameters) { super.prepare(context, parameters); useXP = parameters.getBoolean("use_xp", false); sell = parameters.getBoolean("sell", false); useItems = parameters.getBoolean("use_items", false); showConfirmation = parameters.getBoolean("confirm", true); confirmFillMaterial = ConfigurationUtils.getMaterialAndData(parameters, "confirm_filler", new MaterialAndData(Material.AIR)); requiredPath = parameters.getString("path", null); exactPath = parameters.getString("path_exact", null); requiresCompletedPath = parameters.getString("path_end", null); autoUpgrade = parameters.getBoolean("auto_upgrade", false); requireWand = parameters.getBoolean("require_wand", false); if (requiresCompletedPath != null) { requiredPath = requiresCompletedPath; } if (requiredPath != null || exactPath != null) { requireWand = true; } } public SpellResult showItems(CastContext context, List<ShopItem> items) { Mage mage = context.getMage(); this.context = context; Player player = mage.getPlayer(); if (player == null) { return SpellResult.PLAYER_REQUIRED; } this.showingItems = new HashMap<Integer, ShopItem>(); MageController controller = context.getController(); Messages messages = controller.getMessages(); // Load items List<ItemStack> itemStacks = new ArrayList<ItemStack>(); boolean isItems = (useItems || !VaultController.hasEconomy()) && controller.getWorthItem() != null; boolean isXP = (useXP || (!VaultController.hasEconomy() && controller.getWorthItem() == null)); String costString = context.getMessage("cost_lore"); for (ShopItem shopItem : items) { double worth = shopItem.getWorth(); ItemStack item = shopItem.getItem(); if (item == null) continue; ItemMeta meta = item.getItemMeta(); List<String> lore = meta.getLore(); if (lore == null) { lore = new ArrayList<String>(); } String costs; if (isXP) { worth = worth * controller.getWorthXP(); String xpAmount = Integer.toString((int)(double)worth); xpAmount = messages.get("costs.xp_amount").replace("$amount", xpAmount); costs = costString.replace("$cost", xpAmount); } else if (isItems) { worth = worth * controller.getWorthBase() / controller.getWorthItemAmount(); String itemWorth = formatItemAmount(controller, worth); costs = costString.replace("$cost", itemWorth); } else { worth = worth * controller.getWorthBase(); costs = costString.replace("$cost", VaultController.getInstance().format(worth)); } lore.add(ChatColor.GOLD + costs); meta.setLore(lore); item.setItemMeta(meta); item = InventoryUtils.makeReal(item); int currentSlot = itemStacks.size(); InventoryUtils.setMeta(item, "shop", Integer.toString(currentSlot)); this.showingItems.put(currentSlot, shopItem); if (showConfirmation) { InventoryUtils.setMeta(item, "confirm", "true"); } itemStacks.add(item); } if (itemStacks.size() == 0) { context.sendMessage("no_items"); return SpellResult.FAIL; } String inventoryTitle = context.getMessage("title", "Shop ($balance)"); if (isXP) { String xpAmount = Integer.toString(mage.getExperience()); xpAmount = messages.get("costs.xp_amount").replace("$amount", xpAmount); inventoryTitle = inventoryTitle.replace("$balance", xpAmount); } else if (isItems) { int itemAmount = getItemAmount(controller, mage); inventoryTitle = inventoryTitle.replace("$balance", formatItemAmount(controller, itemAmount)); } else { double balance = VaultController.getInstance().getBalance(player); inventoryTitle = inventoryTitle.replace("$balance", VaultController.getInstance().format(balance)); } int invSize = (itemStacks.size() / 10 + 1) * 9; Inventory displayInventory = CompatibilityUtils.createInventory(null, invSize, inventoryTitle); for (ItemStack item : itemStacks) { displayInventory.addItem(item); } mage.activateGUI(this); mage.getPlayer().openInventory(displayInventory); return SpellResult.CAST; } protected String formatItemAmount(MageController controller, double amount) { CurrencyItem currency = controller.getCurrency(); if (currency != null) { int evenAmount = (int)Math.ceil(amount); String currencyName = currency.getName(); if (currencyName != null && !currencyName.isEmpty()) { if (evenAmount == 1) { return Integer.toString(evenAmount) + " " + currencyName; } String pluralName = currency.getPluralName(); if (pluralName == null || pluralName.isEmpty()) { pluralName = currencyName; } return Integer.toString(evenAmount) + " " + pluralName; } } return formatItemAmount(controller, controller.getWorthItem(), amount); } protected String formatItemAmount(MageController controller, ItemStack item, double amount) { return Integer.toString((int)Math.ceil(amount)) + " " + controller.describeItem(item); } protected int getItemAmount(MageController controller, Mage mage) { return getItemAmount(controller, controller.getWorthItem(), mage); } protected int getItemAmount(MageController controller, ItemStack worthItem, Mage mage) { int itemAmount = 0; ItemStack[] contents = mage.getInventory().getContents(); for (int i = 0; i < contents.length; i++) { if (contents[i] != null && controller.itemsAreEqual(contents[i], worthItem)) { itemAmount += contents[i].getAmount(); } } return itemAmount; } protected void removeItems(MageController controller, Mage mage, int amount) { removeItems(controller, mage, controller.getWorthItem(), amount); } protected void removeItems(MageController controller, Mage mage, ItemStack worthItem, int amount) { int remainingAmount = amount; Inventory inventory = mage.getInventory(); ItemStack[] contents = inventory.getContents(); for (int i = 0; i < contents.length; i++) { if (contents[i] != null && controller.itemsAreEqual(contents[i], worthItem)) { if (contents[i].getAmount() <= remainingAmount) { remainingAmount -= contents[i].getAmount(); contents[i] = null; } else { contents[i].setAmount(contents[i].getAmount() - remainingAmount); remainingAmount = 0; } } if (remainingAmount <= 0) { break; } } inventory.setContents(contents); } @Override public void getParameterNames(Spell spell, Collection<String> parameters) { super.getParameterNames(spell, parameters); parameters.add("confirm"); parameters.add("path"); parameters.add("path_end"); parameters.add("path_exact"); parameters.add("auto_upgrade"); parameters.add("require_wand"); } @Override public void getParameterOptions(Spell spell, String parameterKey, Collection<String> examples) { MageController controller = spell.getController(); if (parameterKey.equals("path") || parameterKey.equals("path_exact") || parameterKey.equals("path_end")) { examples.addAll(controller.getWandPathKeys()); } else if (parameterKey.equals("require_wand") || parameterKey.equals("confirm") || parameterKey.equals("auto_upgrade")) { examples.addAll(Arrays.asList((BaseSpell.EXAMPLE_BOOLEANS))); } else { super.getParameterOptions(spell, parameterKey, examples); } } }
Add some protection for items with no meta. (Failure to add air)
src/main/java/com/elmakers/mine/bukkit/action/BaseShopAction.java
Add some protection for items with no meta. (Failure to add air)
<ide><path>rc/main/java/com/elmakers/mine/bukkit/action/BaseShopAction.java <ide> if (item == null) continue; <ide> <ide> ItemMeta meta = item.getItemMeta(); <add> if (meta == null) { <add> itemStacks.add(item); <add> continue; <add> } <ide> List<String> lore = meta.getLore(); <ide> if (lore == null) { <ide> lore = new ArrayList<String>(); <ide> item = InventoryUtils.makeReal(item); <ide> int currentSlot = itemStacks.size(); <ide> InventoryUtils.setMeta(item, "shop", Integer.toString(currentSlot)); <del> this.showingItems.put(currentSlot, shopItem); <ide> if (showConfirmation) { <ide> InventoryUtils.setMeta(item, "confirm", "true"); <ide> } <add> this.showingItems.put(currentSlot, shopItem); <ide> itemStacks.add(item); <ide> } <ide>
Java
agpl-3.0
1ba3a8d0c497de644bbab24ec4cac7ec59182754
0
exomiser/Exomiser,exomiser/Exomiser
/* * The Exomiser - A tool to annotate and prioritize genomic variants * * Copyright (c) 2016-2017 Queen Mary University of London. * Copyright (c) 2012-2016 Charité Universitätsmedizin Berlin and Genome Research Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.monarchinitiative.exomiser.core.phenotype; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; /** * Class implementing the Phenodigm (PHENOtype comparisons for DIsease Genes and Models) algorithm for scoring the * semantic similarity of a model against the best theoretical model for a set of phenotypes in a given organism. * See original publication here - https://doi.org/10.1093/database/bat025 * * @since 8.0.0 * @author Jules Jacobsen <[email protected]> */ public class PhenodigmModelScorer<T extends Model> implements ModelScorer<T> { private static final Logger logger = LoggerFactory.getLogger(PhenodigmModelScorer.class); private final double theoreticalMaxMatchScore; private final double theoreticalBestAvgScore; private final PhenotypeMatcher organismPhenotypeMatcher; private final int numQueryPhenotypes; /** * Use this constructor when running a single (HP-HP) or single cross-species (e.g. HP-MP) comparisons. * For multi cross-species comparisons use the constructor which requires the {@link QueryPhenotypeMatch} against which * all models are compared. * * @param organismPhenotypeMatcher the best phenotype matches for this organism e.g. HP-HP, HP-MP or HP-MP * @param numQueryPhenotypes */ private PhenodigmModelScorer(PhenotypeMatcher organismPhenotypeMatcher, int numQueryPhenotypes) { this(organismPhenotypeMatcher.getQueryPhenotypeMatch(), organismPhenotypeMatcher, numQueryPhenotypes); } /** * Use this constructor when running multi cross-species comparisons. For single or single cross-species comparisons, * use the alternate constructor. * * @param queryPhenotypeMatch against which all models are compared. * @param organismPhenotypeMatcher the best phenotype matches for this organism e.g. HP-HP, HP-MP or HP-MP * @param numQueryPhenotypes */ private PhenodigmModelScorer(QueryPhenotypeMatch queryPhenotypeMatch, PhenotypeMatcher organismPhenotypeMatcher, int numQueryPhenotypes) { this.theoreticalMaxMatchScore = queryPhenotypeMatch.getMaxMatchScore(); this.theoreticalBestAvgScore = queryPhenotypeMatch.getBestAvgScore(); this.organismPhenotypeMatcher = organismPhenotypeMatcher; this.numQueryPhenotypes = numQueryPhenotypes; logOrganismPhenotypeMatches(); } /** * Produces a {@link ModelScorer} which will score human models only, e.g. disease models or individuals where * their phenotypes are encoded using HPO terms. * * @param phenotypeMatcher The HP to HP PhenotypeMatches for the query Phenotypes. */ public static <T extends Model> PhenodigmModelScorer<T> forSameSpecies(PhenotypeMatcher phenotypeMatcher) { int numQueryPhenotypes = phenotypeMatcher.getQueryTerms().size(); return new PhenodigmModelScorer<>(phenotypeMatcher, numQueryPhenotypes); } /** * Produces a {@link ModelScorer} which will score models between human and a single other species. Requires an * {@link PhenotypeMatcher} for the relevant organism i.e. mouse or fish. * * @param phenotypeMatcher The HP to MP/ZP PhenotypeMatches for the query Phenotypes. */ public static <T extends Model> PhenodigmModelScorer<T> forSingleCrossSpecies(PhenotypeMatcher phenotypeMatcher) { int numQueryPhenotypes = phenotypeMatcher.getBestPhenotypeMatches().size(); return new PhenodigmModelScorer<>(phenotypeMatcher, numQueryPhenotypes); } /** * Produces a {@link ModelScorer} which will score models across multiple species. This requires a reference * species (human) so that the scores are scaled correctly across the species. * * @param referenceOrganismQueryPhenotypeMatch {@link QueryPhenotypeMatch} for the reference organism - this should be for the HP-HP hits. * @param phenotypeMatcher the {@link PhenotypeMatcher} for the relevant organism i.e. HP-HP, HP-MP or HP-ZP matches. */ public static <T extends Model> PhenodigmModelScorer<T> forMultiCrossSpecies(QueryPhenotypeMatch referenceOrganismQueryPhenotypeMatch, PhenotypeMatcher phenotypeMatcher) { int numQueryPhenotypes = referenceOrganismQueryPhenotypeMatch.getQueryTerms().size(); return new PhenodigmModelScorer<>(referenceOrganismQueryPhenotypeMatch, phenotypeMatcher, numQueryPhenotypes); } private void logOrganismPhenotypeMatches() { logger.info("Best {} phenotype matches:", organismPhenotypeMatcher.getOrganism()); Map<PhenotypeTerm, Set<PhenotypeMatch>> termPhenotypeMatches = organismPhenotypeMatcher.getTermPhenotypeMatches(); for (Map.Entry<PhenotypeTerm, Set<PhenotypeMatch>> entry : termPhenotypeMatches.entrySet()) { PhenotypeTerm queryTerm = entry.getKey(); Set<PhenotypeMatch> matches = entry.getValue(); if (matches.isEmpty()) { logger.info("{}-NOT MATCHED", queryTerm.getId()); } else { matches.stream() .max(Comparator.comparingDouble(PhenotypeMatch::getScore)) .ifPresent(bestMatch -> logger.info("{}-{}={}", queryTerm.getId(), bestMatch.getMatchPhenotypeId(), bestMatch.getScore())); } } QueryPhenotypeMatch organismQueryPhenotypeMatch = organismPhenotypeMatcher.getQueryPhenotypeMatch(); logger.info("bestMaxScore={} bestAvgScore={}", organismQueryPhenotypeMatch.getMaxMatchScore(), organismQueryPhenotypeMatch .getBestAvgScore()); } @Override public ModelPhenotypeMatch<T> scoreModel(T model) { PhenodigmMatchRawScore rawModelScore = organismPhenotypeMatcher.matchPhenotypeIds(model.getPhenotypeIds()); double score = calculateCombinedScore(rawModelScore); return ModelPhenotypeMatch.of(score, model, rawModelScore.getBestPhenotypeMatches()); } private double calculateCombinedScore(PhenodigmMatchRawScore rawModelScore) { double maxModelMatchScore = rawModelScore.getMaxModelMatchScore(); double sumModelBestMatchScores = rawModelScore.getSumModelBestMatchScores(); int numMatchingPhenotypesForModel = rawModelScore.getMatchingPhenotypes().size(); /* * hpIdsWithPhenotypeMatch.size() = no. of HPO disease annotations for human and the no. of annotations with an entry in hp_*_mappings table for other species * matchedPhenotypeIDsForModel.size() = no. of annotations for model with a match in hp_*_mappings table for at least one of the disease annotations * Aug 2015 - changed calculation to take into account all HPO terms for averaging after DDD benchmarking - keeps consistent across species then */ //int rowColumnCount = hpIdsWithPhenotypeMatch.size() + matchedPhenotypeIdsForModel.size(); /* * In order to have a strict symmetrical comparison all the query and model phenotypes in the HP-MP table should be taken into account (these are the significant matches) * so we should be using something close to totalPhenotypes = numQueryPhenotypes + numModelPhenotypes, however in the benchmarking it became apparent that * models with large numbers of phenotypes (e.g. 40+) performed badly compared to models with smaller number when matched against a small query. So we have * implemented a sort of semi-symmetrical comparison which only takes into account the model terms matching those in the query HP-MP subsets. */ int totalPhenotypesWithMatch = numQueryPhenotypes + numMatchingPhenotypesForModel; if (sumModelBestMatchScores > 0) { double modelBestAvgScore = sumModelBestMatchScores / totalPhenotypesWithMatch; // calculate combined score double combinedScore = 50 * (maxModelMatchScore / theoreticalMaxMatchScore + modelBestAvgScore / theoreticalBestAvgScore); if (combinedScore > 100) { combinedScore = 100; } return combinedScore / 100; } return 0; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PhenodigmModelScorer that = (PhenodigmModelScorer) o; return Double.compare(that.theoreticalMaxMatchScore, theoreticalMaxMatchScore) == 0 && Double.compare(that.theoreticalBestAvgScore, theoreticalBestAvgScore) == 0 && numQueryPhenotypes == that.numQueryPhenotypes && Objects.equals(organismPhenotypeMatcher, that.organismPhenotypeMatcher); } @Override public int hashCode() { return Objects.hash(theoreticalMaxMatchScore, theoreticalBestAvgScore, organismPhenotypeMatcher, numQueryPhenotypes); } @Override public String toString() { return "PhenodigmModelScorer{" + "theoreticalMaxMatchScore=" + theoreticalMaxMatchScore + ", theoreticalBestAvgScore=" + theoreticalBestAvgScore + ", organismPhenotypeMatcher=" + organismPhenotypeMatcher + ", numQueryPhenotypes=" + numQueryPhenotypes + '}'; } }
exomiser-core/src/main/java/org/monarchinitiative/exomiser/core/phenotype/PhenodigmModelScorer.java
/* * The Exomiser - A tool to annotate and prioritize genomic variants * * Copyright (c) 2016-2017 Queen Mary University of London. * Copyright (c) 2012-2016 Charité Universitätsmedizin Berlin and Genome Research Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.monarchinitiative.exomiser.core.phenotype; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Comparator; import java.util.Map; import java.util.Objects; import java.util.Set; /** * Class implementing the Phenodigm (PHENOtype comparisons for DIsease Genes and Models) algorithm for scoring the * semantic similarity of a model against the best theoretical model for a set of phenotypes in a given organism. * See original publication here - https://doi.org/10.1093/database/bat025 * * @since 8.0.0 * @author Jules Jacobsen <[email protected]> */ public class PhenodigmModelScorer<T extends Model> implements ModelScorer<T> { private static final Logger logger = LoggerFactory.getLogger(PhenodigmModelScorer.class); private final double theoreticalMaxMatchScore; private final double theoreticalBestAvgScore; private final PhenotypeMatcher organismPhenotypeMatcher; private final int numQueryPhenotypes; /** * Use this constructor when running a single (HP-HP) or single cross-species (e.g. HP-MP) comparisons. * For multi cross-species comparisons use the constructor which requires the {@link QueryPhenotypeMatch} against which * all models are compared. * * @param organismPhenotypeMatcher the best phenotype matches for this organism e.g. HP-HP, HP-MP or HP-MP * @param numQueryPhenotypes */ private PhenodigmModelScorer(PhenotypeMatcher organismPhenotypeMatcher, int numQueryPhenotypes) { this(organismPhenotypeMatcher.getQueryPhenotypeMatch(), organismPhenotypeMatcher, numQueryPhenotypes); } /** * Use this constructor when running multi cross-species comparisons. For single or single cross-species comparisons, * use the alternate constructor. * * @param queryPhenotypeMatch against which all models are compared. * @param organismPhenotypeMatcher the best phenotype matches for this organism e.g. HP-HP, HP-MP or HP-MP * @param numQueryPhenotypes */ private PhenodigmModelScorer(QueryPhenotypeMatch queryPhenotypeMatch, PhenotypeMatcher organismPhenotypeMatcher, int numQueryPhenotypes) { this.theoreticalMaxMatchScore = queryPhenotypeMatch.getMaxMatchScore(); this.theoreticalBestAvgScore = queryPhenotypeMatch.getBestAvgScore(); this.organismPhenotypeMatcher = organismPhenotypeMatcher; this.numQueryPhenotypes = numQueryPhenotypes; logOrganismPhenotypeMatches(); } /** * Produces a {@link ModelScorer} which will score human models only, e.g. disease models or individuals where * their phenotypes are encoded using HPO terms. * * @param phenotypeMatcher The HP to HP PhenotypeMatches for the query Phenotypes. */ public static <T extends Model> PhenodigmModelScorer<T> forSameSpecies(PhenotypeMatcher phenotypeMatcher) { int numQueryPhenotypes = phenotypeMatcher.getQueryTerms().size(); return new PhenodigmModelScorer<>(phenotypeMatcher, numQueryPhenotypes); } /** * Produces a {@link ModelScorer} which will score models between human and a single other species. Requires an * {@link PhenotypeMatcher} for the relevant organism i.e. mouse or fish. * * @param phenotypeMatcher The HP to MP/ZP PhenotypeMatches for the query Phenotypes. */ public static <T extends Model> PhenodigmModelScorer<T> forSingleCrossSpecies(PhenotypeMatcher phenotypeMatcher) { int numQueryPhenotypes = phenotypeMatcher.getBestPhenotypeMatches().size(); return new PhenodigmModelScorer<>(phenotypeMatcher, numQueryPhenotypes); } /** * Produces a {@link ModelScorer} which will score models across multiple species. This requires a reference * species (human) so that the scores are scaled correctly across the species. * * @param referenceOrganismQueryPhenotypeMatch {@link QueryPhenotypeMatch} for the reference organism - this should be for the HP-HP hits. * @param phenotypeMatcher the {@link PhenotypeMatcher} for the relevant organism i.e. HP-HP, HP-MP or HP-ZP matches. */ public static <T extends Model> PhenodigmModelScorer<T> forMultiCrossSpecies(QueryPhenotypeMatch referenceOrganismQueryPhenotypeMatch, PhenotypeMatcher phenotypeMatcher) { int numQueryPhenotypes = referenceOrganismQueryPhenotypeMatch.getQueryTerms().size(); return new PhenodigmModelScorer<>(referenceOrganismQueryPhenotypeMatch, phenotypeMatcher, numQueryPhenotypes); } private void logOrganismPhenotypeMatches() { logger.info("Best {} phenotype matches:", organismPhenotypeMatcher.getOrganism()); Map<PhenotypeTerm, Set<PhenotypeMatch>> termPhenotypeMatches = organismPhenotypeMatcher.getTermPhenotypeMatches(); for (Map.Entry<PhenotypeTerm, Set<PhenotypeMatch>> entry : termPhenotypeMatches.entrySet()) { PhenotypeTerm queryTerm = entry.getKey(); Set<PhenotypeMatch> matches = entry.getValue(); if (matches.isEmpty()) { logger.info("{}-NOT MATCHED", queryTerm.getId()); } else { PhenotypeMatch bestMatch = matches.stream() .max(Comparator.comparingDouble(PhenotypeMatch::getScore)) .get(); logger.info("{}-{}={}", queryTerm.getId(), bestMatch.getMatchPhenotypeId(), bestMatch.getScore()); } } QueryPhenotypeMatch organismQueryPhenotypeMatch = organismPhenotypeMatcher.getQueryPhenotypeMatch(); logger.info("bestMaxScore={} bestAvgScore={}", organismQueryPhenotypeMatch.getMaxMatchScore(), organismQueryPhenotypeMatch .getBestAvgScore()); } @Override public ModelPhenotypeMatch<T> scoreModel(T model) { PhenodigmMatchRawScore rawModelScore = organismPhenotypeMatcher.matchPhenotypeIds(model.getPhenotypeIds()); double score = calculateCombinedScore(rawModelScore); return ModelPhenotypeMatch.of(score, model, rawModelScore.getBestPhenotypeMatches()); } private double calculateCombinedScore(PhenodigmMatchRawScore rawModelScore) { double maxModelMatchScore = rawModelScore.getMaxModelMatchScore(); double sumModelBestMatchScores = rawModelScore.getSumModelBestMatchScores(); int numMatchingPhenotypesForModel = rawModelScore.getMatchingPhenotypes().size(); /* * hpIdsWithPhenotypeMatch.size() = no. of HPO disease annotations for human and the no. of annotations with an entry in hp_*_mappings table for other species * matchedPhenotypeIDsForModel.size() = no. of annotations for model with a match in hp_*_mappings table for at least one of the disease annotations * Aug 2015 - changed calculation to take into account all HPO terms for averaging after DDD benchmarking - keeps consistent across species then */ //int rowColumnCount = hpIdsWithPhenotypeMatch.size() + matchedPhenotypeIdsForModel.size(); /* * In order to have a strict symmetrical comparison all the query and model phenotypes in the HP-MP table should be taken into account (these are the significant matches) * so we should be using something close to totalPhenotypes = numQueryPhenotypes + numModelPhenotypes, however in the benchmarking it became apparent that * models with large numbers of phenotypes (e.g. 40+) performed badly compared to models with smaller number when matched against a small query. So we have * implemented a sort of semi-symmetrical comparison which only takes into account the model terms matching those in the query HP-MP subsets. */ int totalPhenotypesWithMatch = numQueryPhenotypes + numMatchingPhenotypesForModel; if (sumModelBestMatchScores > 0) { double modelBestAvgScore = sumModelBestMatchScores / totalPhenotypesWithMatch; // calculate combined score double combinedScore = 50 * (maxModelMatchScore / theoreticalMaxMatchScore + modelBestAvgScore / theoreticalBestAvgScore); if (combinedScore > 100) { combinedScore = 100; } return combinedScore / 100; } return 0; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PhenodigmModelScorer that = (PhenodigmModelScorer) o; return Double.compare(that.theoreticalMaxMatchScore, theoreticalMaxMatchScore) == 0 && Double.compare(that.theoreticalBestAvgScore, theoreticalBestAvgScore) == 0 && numQueryPhenotypes == that.numQueryPhenotypes && Objects.equals(organismPhenotypeMatcher, that.organismPhenotypeMatcher); } @Override public int hashCode() { return Objects.hash(theoreticalMaxMatchScore, theoreticalBestAvgScore, organismPhenotypeMatcher, numQueryPhenotypes); } @Override public String toString() { return "PhenodigmModelScorer{" + "theoreticalMaxMatchScore=" + theoreticalMaxMatchScore + ", theoreticalBestAvgScore=" + theoreticalBestAvgScore + ", organismPhenotypeMatcher=" + organismPhenotypeMatcher + ", numQueryPhenotypes=" + numQueryPhenotypes + '}'; } }
Use Stream.ifPresent() to prevent null pointer dereference in PhenodigmModelScorer
exomiser-core/src/main/java/org/monarchinitiative/exomiser/core/phenotype/PhenodigmModelScorer.java
Use Stream.ifPresent() to prevent null pointer dereference in PhenodigmModelScorer
<ide><path>xomiser-core/src/main/java/org/monarchinitiative/exomiser/core/phenotype/PhenodigmModelScorer.java <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <ide> <del>import java.util.Comparator; <del>import java.util.Map; <del>import java.util.Objects; <del>import java.util.Set; <add>import java.util.*; <ide> <ide> /** <ide> * Class implementing the Phenodigm (PHENOtype comparisons for DIsease Genes and Models) algorithm for scoring the <ide> if (matches.isEmpty()) { <ide> logger.info("{}-NOT MATCHED", queryTerm.getId()); <ide> } else { <del> PhenotypeMatch bestMatch = matches.stream() <add> matches.stream() <ide> .max(Comparator.comparingDouble(PhenotypeMatch::getScore)) <del> .get(); <del> logger.info("{}-{}={}", queryTerm.getId(), bestMatch.getMatchPhenotypeId(), bestMatch.getScore()); <add> .ifPresent(bestMatch -> logger.info("{}-{}={}", queryTerm.getId(), bestMatch.getMatchPhenotypeId(), bestMatch.getScore())); <ide> } <ide> } <ide> QueryPhenotypeMatch organismQueryPhenotypeMatch = organismPhenotypeMatcher.getQueryPhenotypeMatch();
Java
mit
195386e726184babcb724159125772294a470e23
0
CyclopsMC/EverlastingAbilities
package org.cyclops.everlastingabilities; import org.apache.logging.log4j.Level; import org.cyclops.cyclopscore.config.ConfigurableProperty; import org.cyclops.cyclopscore.config.ConfigurableType; import org.cyclops.cyclopscore.config.ConfigurableTypeCategory; import org.cyclops.cyclopscore.config.extendedconfig.DummyConfig; import org.cyclops.cyclopscore.init.ModBase; import org.cyclops.cyclopscore.tracking.Analytics; import org.cyclops.cyclopscore.tracking.Versions; /** * A config with general options for this mod. * @author rubensworks * */ public class GeneralConfig extends DummyConfig { /** * The current mod version, will be used to check if the player's config isn't out of date and * warn the player accordingly. */ @ConfigurableProperty(category = ConfigurableTypeCategory.CORE, comment = "Config version for " + Reference.MOD_NAME +".\nDO NOT EDIT MANUALLY!") public static String version = Reference.MOD_VERSION; /** * If the debug mode should be enabled. @see Debug */ @ConfigurableProperty(category = ConfigurableTypeCategory.CORE, comment = "Set 'true' to enable development debug mode. This will result in a lower performance!", requiresMcRestart = true) public static boolean debug = false; /** * If the recipe loader should crash when finding invalid recipes. */ @ConfigurableProperty(category = ConfigurableTypeCategory.CORE, comment = "If the recipe loader should crash when finding invalid recipes.", requiresMcRestart = true) public static boolean crashOnInvalidRecipe = false; /** * If mod compatibility loader should crash hard if errors occur in that process. */ @ConfigurableProperty(category = ConfigurableTypeCategory.CORE, comment = "If mod compatibility loader should crash hard if errors occur in that process.", requiresMcRestart = true) public static boolean crashOnModCompatCrash = false; /** * If an anonymous mod startup analytics request may be sent to our analytics service. */ @ConfigurableProperty(category = ConfigurableTypeCategory.CORE, comment = "If an anonymous mod startup analytics request may be sent to our analytics service.") public static boolean analytics = true; /** * If the version checker should be enabled. */ @ConfigurableProperty(category = ConfigurableTypeCategory.CORE, comment = "If the version checker should be enabled.") public static boolean versionChecker = true; /** * The maximum rarity of totems to spawn when a player first logs in. [0-3], -1 disables totem spawning. */ @ConfigurableProperty(category = ConfigurableTypeCategory.GENERAL, comment = "The maximum rarity of totems to spawn when a player first logs in. [0-3], -1 disables totem spawning.") public static int totemMaximumSpawnRarity = 1; /** * How many abilities should be dropped on player death. */ @ConfigurableProperty(category = ConfigurableTypeCategory.GENERAL, comment = "How many abilities should be dropped on player death.", isCommandable = true) public static int dropAbilitiesOnPlayerDeath = 1; /** * true: Abilities drop when players die; false: Abilities drop when players die by the hand of other players. */ @ConfigurableProperty(category = ConfigurableTypeCategory.GENERAL, comment = "true: Abilities drop when players die; false: Abilities drop when players die by the hand of other players.", isCommandable = true) public static boolean alwaysDropAbilities = false; /** * 1/x chance for mobs to have abilities. */ @ConfigurableProperty(category = ConfigurableTypeCategory.GENERAL, comment = "1/x chance for mobs to have abilities", isCommandable = true) public static int mobAbilityChance = 50; /** * If the magnetize ability should move xp. */ @ConfigurableProperty(category = ConfigurableTypeCategory.GENERAL, comment = "If the magnetize ability should move xp.", isCommandable = true) public static boolean magnetizeMoveXp = true; /** * The type of this config. */ public static ConfigurableType TYPE = ConfigurableType.DUMMY; /** * Create a new instance. */ public GeneralConfig() { super(EverlastingAbilities._instance, true, "general", null, GeneralConfig.class); } @Override public void onRegistered() { // Check version of config file if(!version.equals(Reference.MOD_VERSION)) { getMod().log(Level.WARN, "The config file of " + Reference.MOD_NAME + " is out of date and might cause problems, please remove it so it can be regenerated."); } getMod().putGenericReference(ModBase.REFKEY_CRASH_ON_INVALID_RECIPE, GeneralConfig.crashOnInvalidRecipe); getMod().putGenericReference(ModBase.REFKEY_DEBUGCONFIG, GeneralConfig.debug); getMod().putGenericReference(ModBase.REFKEY_CRASH_ON_MODCOMPAT_CRASH, GeneralConfig.crashOnModCompatCrash); if(analytics) { Analytics.registerMod(getMod(), Reference.GA_TRACKING_ID); } if(versionChecker) { Versions.registerMod(getMod(), EverlastingAbilities._instance, Reference.VERSION_URL); } } @Override public boolean isEnabled() { return true; } }
src/main/java/org/cyclops/everlastingabilities/GeneralConfig.java
package org.cyclops.everlastingabilities; import org.apache.logging.log4j.Level; import org.cyclops.cyclopscore.config.ConfigurableProperty; import org.cyclops.cyclopscore.config.ConfigurableType; import org.cyclops.cyclopscore.config.ConfigurableTypeCategory; import org.cyclops.cyclopscore.config.extendedconfig.DummyConfig; import org.cyclops.cyclopscore.init.ModBase; import org.cyclops.cyclopscore.tracking.Analytics; import org.cyclops.cyclopscore.tracking.Versions; /** * A config with general options for this mod. * @author rubensworks * */ public class GeneralConfig extends DummyConfig { /** * The current mod version, will be used to check if the player's config isn't out of date and * warn the player accordingly. */ @ConfigurableProperty(category = ConfigurableTypeCategory.CORE, comment = "Config version for " + Reference.MOD_NAME +".\nDO NOT EDIT MANUALLY!") public static String version = Reference.MOD_VERSION; /** * If the debug mode should be enabled. @see Debug */ @ConfigurableProperty(category = ConfigurableTypeCategory.CORE, comment = "Set 'true' to enable development debug mode. This will result in a lower performance!", requiresMcRestart = true) public static boolean debug = false; /** * If the recipe loader should crash when finding invalid recipes. */ @ConfigurableProperty(category = ConfigurableTypeCategory.CORE, comment = "If the recipe loader should crash when finding invalid recipes.", requiresMcRestart = true) public static boolean crashOnInvalidRecipe = false; /** * If mod compatibility loader should crash hard if errors occur in that process. */ @ConfigurableProperty(category = ConfigurableTypeCategory.CORE, comment = "If mod compatibility loader should crash hard if errors occur in that process.", requiresMcRestart = true) public static boolean crashOnModCompatCrash = false; /** * If an anonymous mod startup analytics request may be sent to our analytics service. */ @ConfigurableProperty(category = ConfigurableTypeCategory.CORE, comment = "If an anonymous mod startup analytics request may be sent to our analytics service.") public static boolean analytics = true; /** * If the version checker should be enabled. */ @ConfigurableProperty(category = ConfigurableTypeCategory.CORE, comment = "If the version checker should be enabled.") public static boolean versionChecker = true; /** * The maximum rarity of totems to spawn when a player first logs in. [0-3], -1 disables totem spawning. */ @ConfigurableProperty(category = ConfigurableTypeCategory.GENERAL, comment = "The maximum rarity of totems to spawn when a player first logs in. [0-3], -1 disables totem spawning.") public static int totemMaximumSpawnRarity = 1; /** * How many abilities should be dropped on player death. */ @ConfigurableProperty(category = ConfigurableTypeCategory.GENERAL, comment = "How many abilities should be dropped on player death.", isCommandable = true) public static int dropAbilitiesOnPlayerDeath = 1; /** * true: Abilities drop when players die; false: Abilities drop when players die by the hand of other players. */ @ConfigurableProperty(category = ConfigurableTypeCategory.GENERAL, comment = "true: Abilities drop when players die; false: Abilities drop when players die by the hand of other players.", isCommandable = true) public static boolean alwaysDropAbilities = false; /** * 1/x chance for mobs to have abilities. */ @ConfigurableProperty(category = ConfigurableTypeCategory.GENERAL, comment = "1/x chance for mobs to have abilities", isCommandable = true) public static int mobAbilityChance = 10; /** * If the magnetize ability should move xp. */ @ConfigurableProperty(category = ConfigurableTypeCategory.GENERAL, comment = "If the magnetize ability should move xp.", isCommandable = true) public static boolean magnetizeMoveXp = true; /** * The type of this config. */ public static ConfigurableType TYPE = ConfigurableType.DUMMY; /** * Create a new instance. */ public GeneralConfig() { super(EverlastingAbilities._instance, true, "general", null, GeneralConfig.class); } @Override public void onRegistered() { // Check version of config file if(!version.equals(Reference.MOD_VERSION)) { getMod().log(Level.WARN, "The config file of " + Reference.MOD_NAME + " is out of date and might cause problems, please remove it so it can be regenerated."); } getMod().putGenericReference(ModBase.REFKEY_CRASH_ON_INVALID_RECIPE, GeneralConfig.crashOnInvalidRecipe); getMod().putGenericReference(ModBase.REFKEY_DEBUGCONFIG, GeneralConfig.debug); getMod().putGenericReference(ModBase.REFKEY_CRASH_ON_MODCOMPAT_CRASH, GeneralConfig.crashOnModCompatCrash); if(analytics) { Analytics.registerMod(getMod(), Reference.GA_TRACKING_ID); } if(versionChecker) { Versions.registerMod(getMod(), EverlastingAbilities._instance, Reference.VERSION_URL); } } @Override public boolean isEnabled() { return true; } }
Lower mob totem drop chance from 1/10 to 1/50
src/main/java/org/cyclops/everlastingabilities/GeneralConfig.java
Lower mob totem drop chance from 1/10 to 1/50
<ide><path>rc/main/java/org/cyclops/everlastingabilities/GeneralConfig.java <ide> * 1/x chance for mobs to have abilities. <ide> */ <ide> @ConfigurableProperty(category = ConfigurableTypeCategory.GENERAL, comment = "1/x chance for mobs to have abilities", isCommandable = true) <del> public static int mobAbilityChance = 10; <add> public static int mobAbilityChance = 50; <ide> <ide> /** <ide> * If the magnetize ability should move xp.
Java
apache-2.0
82516721fdb63828b509a9fbbce127929ed3372f
0
ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma
/* * The Gemma project * * Copyright (c) 2006 University of British Columbia * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package ubic.gemma.web.taglib.expression.experiment; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport; import org.apache.commons.lang.StringUtils; import ubic.gemma.model.expression.arrayDesign.ArrayDesign; import ubic.gemma.model.expression.bioAssay.BioAssay; import ubic.gemma.model.expression.biomaterial.BioMaterial; import ubic.gemma.model.expression.experiment.ExpressionExperiment; import com.sdicons.json.mapper.JSONMapper; import com.sdicons.json.mapper.MapperException; /** * Used to display table of biomaterials and bioassays. In edit mode this displays allows dragging bioassays around to * match up across platforms. * * @author joseph * @version $Id$ */ public class AssayViewTag extends TagSupport { /** * */ private static final long serialVersionUID = 8754490187937841260L; /** * How many 'extra' biomaterials to add to the editing table, so the user can assing bioassays to new biomaterials. */ private static final int NUM_EXTRA_BIOMATERIALS = 12; private ExpressionExperiment expressionExperiment; private boolean edit = false; /** * @param expressionExperiment */ public void setExpressionExperiment( ExpressionExperiment expressionExperiment ) { this.expressionExperiment = expressionExperiment; } /** * @param edit */ public void setEdit( String edit ) { if ( edit.equalsIgnoreCase( "true" ) ) { this.edit = true; } else { this.edit = false; } } /* * (non-Javadoc) * * @see javax.servlet.jsp.tagext.TagSupport#doEndTag() */ @Override public int doEndTag() { return EVAL_PAGE; } /* * (non-Javadoc) * * @see javax.servlet.jsp.tagext.TagSupport#doStartTag() */ @SuppressWarnings("unchecked") @Override public int doStartTag() throws JspException { StringBuilder buf = new StringBuilder(); buf.append( "<div>" ); // create table Collection<BioAssay> bioAssays = expressionExperiment.getBioAssays(); Map<BioMaterial, Map<ArrayDesign, Collection<BioAssay>>> bioAssayMap = new HashMap<BioMaterial, Map<ArrayDesign, Collection<BioAssay>>>(); Set<ArrayDesign> designs = new HashSet<ArrayDesign>(); Map<ArrayDesign, Long> arrayMaterialCount = new HashMap<ArrayDesign, Long>(); // package all of this information into JSON for javascript dynamic retrieval Map<String, Collection<String>> assayToMaterial = new HashMap<String, Collection<String>>(); for ( BioAssay assay : bioAssays ) { // map for bioassays linked to a specific arraydesign // map for the bioassays linked to a specific biomaterial Collection<BioMaterial> materials = assay.getSamplesUsed(); ArrayDesign design = assay.getArrayDesignUsed(); designs.add( design ); for ( BioMaterial material : materials ) { // check if the assay list is initialized yet Map<ArrayDesign, Collection<BioAssay>> assayMap; if ( bioAssayMap.containsKey( material ) ) { assayMap = bioAssayMap.get( material ); } else { assayMap = new HashMap<ArrayDesign, Collection<BioAssay>>(); bioAssayMap.put( material, assayMap ); } if ( assayMap.containsKey( design ) ) { assayMap.get( design ).add( assay ); } else { Collection<BioAssay> assayList = new ArrayList<BioAssay>(); assayList.add( assay ); assayMap.put( design, assayList ); } // count the number of materials per array if ( arrayMaterialCount.containsKey( design ) ) { Long count = arrayMaterialCount.get( design ); count++; arrayMaterialCount.put( design, count ); } else { Long count = new Long( 1 ); arrayMaterialCount.put( design, count ); } } } int materialCount = bioAssayMap.keySet().size(); buf.append( "<table class='list'><tr>" ); buf.append( "<th>" + materialCount + " BioMaterials</th>" ); // display arraydesigns for ( ArrayDesign design : designs ) { Long count = arrayMaterialCount.get( design ); buf.append( "<th>" + count + " BioAssays on<br /><a target='_blank' href=\"/Gemma/arrays/showArrayDesign.html?id=" + design.getId() + "\" title=\"" + design.getName() + "\" >" + ( design.getShortName() == null ? design.getName() : design.getShortName() ) + "</a></th>" ); } buf.append( "</tr>" ); // display bioMaterials and the corresponding bioAssays int count = 1; Iterator iter = bioAssayMap.keySet().iterator(); ArrayList<BioMaterial> materials = new ArrayList<BioMaterial>(); while ( iter.hasNext() ) { materials.add( ( BioMaterial ) iter.next() ); } Comparator<BioMaterial> comparator = new BioMaterialComparator(); Collections.sort( materials, comparator ); int elementCount = 1; int emptyCount = 0; for ( BioMaterial material : materials ) { if ( count % 2 == 0 ) { buf.append( "<tr class='even' align=justify>" ); } else { buf.append( "<tr class='odd' align=justify>" ); } String bmLink = "<a href='/Gemma/bioMaterial/showBioMaterial.html?id=" + material.getId() + "'> " + material.getName() + "</a>"; buf.append( "<td>" + bmLink + "</td>" ); Map<ArrayDesign, Collection<BioAssay>> assayMap = bioAssayMap.get( material ); String image = "&nbsp;&nbsp;&nbsp;<img height=16 width=16 src='/Gemma/images/icons/arrow_switch.png' />&nbsp;&nbsp;&nbsp;"; for ( ArrayDesign design : designs ) { if ( assayMap.containsKey( design ) ) { Collection<BioAssay> assays = assayMap.get( design ); Collection<Long> ids = new ArrayList<Long>(); Collection<String> tooltips = new ArrayList<String>(); for ( BioAssay assay : assays ) { ids.add( assay.getId() ); tooltips.add( StringUtils.abbreviate( assay.getName() + assay.getDescription(), 120 ) ); this.addMaterial( assayToMaterial, assay.getId(), material.getId() ); } if ( assayMap.get( design ).size() > 1 ) { String link = "<a title='" + StringUtils.join( tooltips.toArray(), "\n" ) + "' href='/Gemma/bioAssay/showAllBioAssays.html?id=" + StringUtils.join( ids.toArray(), "," ) + "'> (list) </a>"; buf .append( "<td>" + assayMap.get( design ).size() + link + "&nbsp;" + elementCount + "</td>\n" ); } else { /* * Each bioassay has a unique id; the div it sits in is identified by the class 'dragitem'. See * expressionExperiment.edit.jsp. */ BioAssay assay = ( ( ArrayList<BioAssay> ) assayMap.get( design ) ).get( 0 ); String shortDesc = StringUtils.abbreviate( assay.getDescription(), 60 ); String link = "<a target=\"_blank\" title='" + shortDesc + "' href='/Gemma/bioAssay/showBioAssay.html?id=" + assay.getId() + "'>" + assay.getName() + "</a>"; String editAttributes = " align='left' class='dragItem' id='bioassay." + assay.getId() + "' material='" + material.getId() + "' assay='" + assay.getId() + "' arrayDesign='" + design.getId() + "'"; if ( edit && designs.size() > 1 ) { buf.append( "\n<td><div " + editAttributes + ">" + image + link ); } else { buf.append( "\n<td ><div>" + link + "&nbsp;" ); } buf.append( "</div></td>\n" ); } } else { emptyCount = addEmpty( buf, assayToMaterial, emptyCount, material, image, design ); } } buf.append( "</tr>" ); count++; elementCount++; } // add a few blanks, but only if we are editing. if ( edit ) { addNovelBiomaterialSlots( buf, designs, assayToMaterial, count, emptyCount ); } buf.append( "</table>" ); if ( edit ) { // append JSON serialization try { String jsonSerialization = JSONMapper.toJSON( assayToMaterial ).render( false ); buf.append( "<input type='hidden' id='assayToMaterialMap' name='assayToMaterialMap' value='" + jsonSerialization + "'/>" ); } catch ( MapperException e ) { // cannot serialize } } buf.append( "</div>" ); try { pageContext.getOut().print( buf.toString() ); } catch ( Exception ex ) { throw new JspException( "assayViewTag: " + ex.getMessage() ); } return SKIP_BODY; } /** * Add places for completely new biomaterials to be added. * * @param buf * @param designs * @param assayToMaterial * @param count * @param emptyCount */ private void addNovelBiomaterialSlots( StringBuilder buf, Set<ArrayDesign> designs, Map<String, Collection<String>> assayToMaterial, int count, int emptyCount ) { if ( designs.size() == 1 ) { return; } for ( int i = 1; i <= NUM_EXTRA_BIOMATERIALS; i++ ) { if ( count % 2 == 0 ) { buf.append( "<tr class='even' align=justify>" ); } else { buf.append( "<tr class='odd' align=justify>" ); } BioMaterial material = BioMaterial.Factory.newInstance(); // FIXME this is a kludge: use negative ids to distinguish the new biomaterials. material.setId( 0L - i ); material.setName( "[New biomaterial " + i + "]" ); buf.append( "<td>" + material.getName() + "</td>" ); String image = "<img height=10 width=10 src='/Gemma/images/arrow_out.png' />"; for ( ArrayDesign design : designs ) { emptyCount = addEmpty( buf, assayToMaterial, emptyCount, material, image, design ); } buf.append( "</tr>" ); count++; } } /** * Add a 'unused' biomaterial/bioassay combination to the table. * * @param buf * @param assayToMaterial * @param emptyCount * @param material * @param image * @param design * @return revised count of number of empty items. */ private int addEmpty( StringBuilder buf, Map<String, Collection<String>> assayToMaterial, int emptyCount, BioMaterial material, String image, ArrayDesign design ) { // put empty space in table if the bioMaterial does not // use this array design emptyCount++; String editAttributes = "class='dragItem' id='bioassay.empty." + emptyCount + "' material='" + material.getId() + "' assay='nullElement' arrayDesign='" + design.getId() + "'"; if ( edit ) { buf.append( "\n<td><div " + editAttributes + ">" + image ); } else { buf.append( "\n<td><div>&nbsp;" ); } this.addMaterial( assayToMaterial, null, material.getId() ); buf.append( "</div></td>\n" ); return emptyCount; } /** * @param assayToMaterial * @param bioAssayId * @param bioMaterialId */ private void addMaterial( Map<String, Collection<String>> assayToMaterial, Long bioAssayId, Long bioMaterialId ) { String bioAssayStr = ""; if ( bioAssayId == null ) { bioAssayStr = "nullElement"; } else { bioAssayStr = bioAssayId.toString(); } // if bioAssayId is not in the map, create it and initialize the bioMaterial collection // if bioAssayId is in the map, add to the bioMaterial collection if ( assayToMaterial.containsKey( bioAssayStr ) ) { Collection<String> bioMaterials = assayToMaterial.get( bioAssayStr ); bioMaterials.add( bioMaterialId.toString() ); } else { Collection<String> bioMaterials = new ArrayList<String>(); bioMaterials.add( bioMaterialId.toString() ); assayToMaterial.put( bioAssayStr, bioMaterials ); } } /** * @author pavlidis * @version $Id$ */ static class BioMaterialComparator implements Comparator<BioMaterial> { public int compare( BioMaterial arg0, BioMaterial arg1 ) { BioMaterial obj0 = arg0; BioMaterial obj1 = arg1; return obj0.getName().compareTo( obj1.getName() ); } } }
gemma-web/src/main/java/ubic/gemma/web/taglib/expression/experiment/AssayViewTag.java
/* * The Gemma project * * Copyright (c) 2006 University of British Columbia * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package ubic.gemma.web.taglib.expression.experiment; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ubic.gemma.model.expression.arrayDesign.ArrayDesign; import ubic.gemma.model.expression.bioAssay.BioAssay; import ubic.gemma.model.expression.biomaterial.BioMaterial; import ubic.gemma.model.expression.experiment.ExpressionExperiment; import com.sdicons.json.mapper.JSONMapper; import com.sdicons.json.mapper.MapperException; /** * Used to display table of biomaterials and bioassays. In edit mode this displays allows dragging bioassays around to * match up across platforms. * * @jsp.tag name="assayView" body-content="empty" * @author joseph * @version $Id$ */ public class AssayViewTag extends TagSupport { /** * */ private static final long serialVersionUID = 8754490187937841260L; /** * How many 'extra' biomaterials to add to the editing table, so the user can assing bioassays to new biomaterials. */ private static final int NUM_EXTRA_BIOMATERIALS = 12; private Log log = LogFactory.getLog( this.getClass() ); private ExpressionExperiment expressionExperiment; private boolean edit = false; /** * @param expressionExperiment * @jsp.attribute required="true" rtexprvalue="true" */ public void setExpressionExperiment( ExpressionExperiment expressionExperiment ) { this.expressionExperiment = expressionExperiment; } /** * @param edit * @jsp.attribute required="false" rtexprvalue="true" */ public void setEdit( String edit ) { if ( edit.equalsIgnoreCase( "true" ) ) { this.edit = true; } else { this.edit = false; } } /* * (non-Javadoc) * * @see javax.servlet.jsp.tagext.TagSupport#doEndTag() */ @Override public int doEndTag() { return EVAL_PAGE; } /* * (non-Javadoc) * * @see javax.servlet.jsp.tagext.TagSupport#doStartTag() */ @SuppressWarnings("unchecked") @Override public int doStartTag() throws JspException { log.debug( "in Start Tag" ); StringBuilder buf = new StringBuilder(); buf.append( "<div>" ); // create table Collection<BioAssay> bioAssays = expressionExperiment.getBioAssays(); Map<BioMaterial, Map<ArrayDesign, Collection<BioAssay>>> bioAssayMap = new HashMap<BioMaterial, Map<ArrayDesign, Collection<BioAssay>>>(); Set<ArrayDesign> designs = new HashSet<ArrayDesign>(); Map<ArrayDesign, Long> arrayMaterialCount = new HashMap<ArrayDesign, Long>(); // package all of this information into JSON for javascript dynamic retrieval Map<String, Collection<String>> assayToMaterial = new HashMap<String, Collection<String>>(); for ( BioAssay assay : bioAssays ) { // map for bioassays linked to a specific arraydesign // map for the bioassays linked to a specific biomaterial Collection<BioMaterial> materials = assay.getSamplesUsed(); ArrayDesign design = assay.getArrayDesignUsed(); designs.add( design ); for ( BioMaterial material : materials ) { // check if the assay list is initialized yet Map<ArrayDesign, Collection<BioAssay>> assayMap; if ( bioAssayMap.containsKey( material ) ) { assayMap = bioAssayMap.get( material ); } else { assayMap = new HashMap<ArrayDesign, Collection<BioAssay>>(); bioAssayMap.put( material, assayMap ); } if ( assayMap.containsKey( design ) ) { assayMap.get( design ).add( assay ); } else { Collection<BioAssay> assayList = new ArrayList<BioAssay>(); assayList.add( assay ); assayMap.put( design, assayList ); } // count the number of materials per array if ( arrayMaterialCount.containsKey( design ) ) { Long count = arrayMaterialCount.get( design ); count++; arrayMaterialCount.put( design, count ); } else { Long count = new Long( 1 ); arrayMaterialCount.put( design, count ); } } } int materialCount = bioAssayMap.keySet().size(); buf.append( "<table class='list'><tr>" ); buf.append( "<th>" + materialCount + " BioMaterials</th>" ); // display arraydesigns for ( ArrayDesign design : designs ) { Long count = arrayMaterialCount.get( design ); buf.append( "<th>" + count + " BioAssays on<br />" + "<a href='' title='" + design.getName() + "' onclick='return false;'>" + ( design.getShortName() == null ? design.getName() : design.getShortName() ) + "</a></th>" ); } buf.append( "</tr>" ); // display bioMaterials and the corresponding bioAssays int count = 1; Iterator iter = bioAssayMap.keySet().iterator(); ArrayList<BioMaterial> materials = new ArrayList<BioMaterial>(); while ( iter.hasNext() ) { materials.add( ( BioMaterial ) iter.next() ); } Comparator<BioMaterial> comparator = new BioMaterialComparator(); Collections.sort( materials, comparator ); int elementCount = 1; int emptyCount = 0; for ( BioMaterial material : materials ) { if ( count % 2 == 0 ) { buf.append( "<tr class='even' align=justify>" ); } else { buf.append( "<tr class='odd' align=justify>" ); } String bmLink = "<a href='/Gemma/bioMaterial/showBioMaterial.html?id=" + material.getId() + "'> " + material.getName() + "</a>"; buf.append( "<td>" + bmLink + "</td>" ); Map<ArrayDesign, Collection<BioAssay>> assayMap = bioAssayMap.get( material ); String image = "&nbsp;&nbsp;&nbsp;<img height=16 width=16 src='/Gemma/images/icons/arrow_switch.png' />&nbsp;&nbsp;&nbsp;"; for ( ArrayDesign design : designs ) { if ( assayMap.containsKey( design ) ) { Collection<BioAssay> assays = assayMap.get( design ); Collection<Long> ids = new ArrayList<Long>(); Collection<String> tooltips = new ArrayList<String>(); for ( BioAssay assay : assays ) { ids.add( assay.getId() ); tooltips.add( StringUtils.abbreviate( assay.getName() + assay.getDescription(), 120 ) ); this.addMaterial( assayToMaterial, assay.getId(), material.getId() ); } if ( assayMap.get( design ).size() > 1 ) { String link = "<a title='" + StringUtils.join( tooltips.toArray(), "\n" ) + "' href='/Gemma/bioAssay/showAllBioAssays.html?id=" + StringUtils.join( ids.toArray(), "," ) + "'> (list) </a>"; buf .append( "<td>" + assayMap.get( design ).size() + link + "&nbsp;" + elementCount + "</td>\n" ); } else { /* * Each bioassay has a unique id; the div it sits in is identified by the class 'dragitem'. See * expressionExperiment.edit.jsp. */ BioAssay assay = ( ( ArrayList<BioAssay> ) assayMap.get( design ) ).get( 0 ); String shortDesc = StringUtils.abbreviate( assay.getDescription(), 60 ); String link = "<a target=\"_blank\" title='" + shortDesc + "' href='/Gemma/bioAssay/showBioAssay.html?id=" + assay.getId() + "'>" + assay.getName() + "</a>"; String editAttributes = " align='left' class='dragItem' id='bioassay." + assay.getId() + "' material='" + material.getId() + "' assay='" + assay.getId() + "' arrayDesign='" + design.getId() + "'"; if ( edit && designs.size() > 1 ) { buf.append( "\n<td><div " + editAttributes + ">" + image + link ); } else { buf.append( "\n<td ><div>" + link + "&nbsp;" ); } buf.append( "</div></td>\n" ); } } else { emptyCount = addEmpty( buf, assayToMaterial, emptyCount, material, image, design ); } } buf.append( "</tr>" ); count++; elementCount++; } // add a few blanks, but only if we are editing. if ( edit ) { addNovelBiomaterialSlots( buf, designs, assayToMaterial, count, emptyCount ); } buf.append( "</table>" ); if ( edit ) { // append JSON serialization String jsonSerialization = ""; try { jsonSerialization = JSONMapper.toJSON( assayToMaterial ).render( false ); } catch ( MapperException e ) { // cannot serialize log.error( "cannot serialize materialMap object!" ); } buf.append( "<input type='hidden' id='assayToMaterialMap' name='assayToMaterialMap' value='" + jsonSerialization + "'/>" ); } buf.append( "</div>" ); try { pageContext.getOut().print( buf.toString() ); } catch ( Exception ex ) { throw new JspException( "assayViewTag: " + ex.getMessage() ); } return SKIP_BODY; } /** * Add places for completely new biomaterials to be added. * * @param buf * @param designs * @param assayToMaterial * @param count * @param emptyCount */ private void addNovelBiomaterialSlots( StringBuilder buf, Set<ArrayDesign> designs, Map<String, Collection<String>> assayToMaterial, int count, int emptyCount ) { if ( designs.size() == 1 ) { return; } for ( int i = 1; i <= NUM_EXTRA_BIOMATERIALS; i++ ) { if ( count % 2 == 0 ) { buf.append( "<tr class='even' align=justify>" ); } else { buf.append( "<tr class='odd' align=justify>" ); } BioMaterial material = BioMaterial.Factory.newInstance(); // FIXME this is a kludge: use negative ids to distinguish the new biomaterials. material.setId( 0L - i ); material.setName( "[New biomaterial " + i + "]" ); buf.append( "<td>" + material.getName() + "</td>" ); String image = "<img height=10 width=10 src='/Gemma/images/arrow_out.png' />"; for ( ArrayDesign design : designs ) { emptyCount = addEmpty( buf, assayToMaterial, emptyCount, material, image, design ); } buf.append( "</tr>" ); count++; } } /** * Add a 'unused' biomaterial/bioassay combination to the table. * * @param buf * @param assayToMaterial * @param emptyCount * @param material * @param image * @param design * @return revised count of number of empty items. */ private int addEmpty( StringBuilder buf, Map<String, Collection<String>> assayToMaterial, int emptyCount, BioMaterial material, String image, ArrayDesign design ) { // put empty space in table if the bioMaterial does not // use this array design emptyCount++; String editAttributes = "class='dragItem' id='bioassay.empty." + emptyCount + "' material='" + material.getId() + "' assay='nullElement' arrayDesign='" + design.getId() + "'"; if ( edit ) { buf.append( "\n<td><div " + editAttributes + ">" + image ); } else { buf.append( "\n<td><div>&nbsp;" ); } this.addMaterial( assayToMaterial, null, material.getId() ); buf.append( "</div></td>\n" ); return emptyCount; } /** * @param assayToMaterial * @param bioAssayId * @param bioMaterialId */ private void addMaterial( Map<String, Collection<String>> assayToMaterial, Long bioAssayId, Long bioMaterialId ) { String bioAssayStr = ""; if ( bioAssayId == null ) { bioAssayStr = "nullElement"; } else { bioAssayStr = bioAssayId.toString(); } // if bioAssayId is not in the map, create it and initialize the bioMaterial collection // if bioAssayId is in the map, add to the bioMaterial collection if ( assayToMaterial.containsKey( bioAssayStr ) ) { Collection<String> bioMaterials = assayToMaterial.get( bioAssayStr ); bioMaterials.add( bioMaterialId.toString() ); } else { Collection<String> bioMaterials = new ArrayList<String>(); bioMaterials.add( bioMaterialId.toString() ); assayToMaterial.put( bioAssayStr, bioMaterials ); } } /** * @author pavlidis * @version $Id$ */ static class BioMaterialComparator implements Comparator<BioMaterial> { public int compare( BioMaterial arg0, BioMaterial arg1 ) { BioMaterial obj0 = arg0; BioMaterial obj1 = arg1; return obj0.getName().compareTo( obj1.getName() ); } } }
fix 1947
gemma-web/src/main/java/ubic/gemma/web/taglib/expression/experiment/AssayViewTag.java
fix 1947
<ide><path>emma-web/src/main/java/ubic/gemma/web/taglib/expression/experiment/AssayViewTag.java <ide> import javax.servlet.jsp.tagext.TagSupport; <ide> <ide> import org.apache.commons.lang.StringUtils; <del>import org.apache.commons.logging.Log; <del>import org.apache.commons.logging.LogFactory; <ide> <ide> import ubic.gemma.model.expression.arrayDesign.ArrayDesign; <ide> import ubic.gemma.model.expression.bioAssay.BioAssay; <ide> * Used to display table of biomaterials and bioassays. In edit mode this displays allows dragging bioassays around to <ide> * match up across platforms. <ide> * <del> * @jsp.tag name="assayView" body-content="empty" <ide> * @author joseph <ide> * @version $Id$ <ide> */ <ide> */ <ide> private static final int NUM_EXTRA_BIOMATERIALS = 12; <ide> <del> private Log log = LogFactory.getLog( this.getClass() ); <del> <ide> private ExpressionExperiment expressionExperiment; <ide> private boolean edit = false; <ide> <ide> /** <ide> * @param expressionExperiment <del> * @jsp.attribute required="true" rtexprvalue="true" <ide> */ <ide> public void setExpressionExperiment( ExpressionExperiment expressionExperiment ) { <ide> this.expressionExperiment = expressionExperiment; <ide> <ide> /** <ide> * @param edit <del> * @jsp.attribute required="false" rtexprvalue="true" <ide> */ <ide> public void setEdit( String edit ) { <ide> if ( edit.equalsIgnoreCase( "true" ) ) { <ide> @SuppressWarnings("unchecked") <ide> @Override <ide> public int doStartTag() throws JspException { <del> log.debug( "in Start Tag" ); <ide> <ide> StringBuilder buf = new StringBuilder(); <ide> <ide> // display arraydesigns <ide> for ( ArrayDesign design : designs ) { <ide> Long count = arrayMaterialCount.get( design ); <del> buf.append( "<th>" + count + " BioAssays on<br />" + "<a href='' title='" + design.getName() <del> + "' onclick='return false;'>" <add> buf.append( "<th>" + count + " BioAssays on<br /><a target='_blank' href=\"/Gemma/arrays/showArrayDesign.html?id=" <add> + design.getId() + "\" title=\"" + design.getName() + "\" >" <ide> + ( design.getShortName() == null ? design.getName() : design.getShortName() ) + "</a></th>" ); <ide> } <ide> buf.append( "</tr>" ); <ide> <ide> if ( edit ) { <ide> // append JSON serialization <del> String jsonSerialization = ""; <ide> try { <del> jsonSerialization = JSONMapper.toJSON( assayToMaterial ).render( false ); <add> String jsonSerialization = JSONMapper.toJSON( assayToMaterial ).render( false ); <add> buf.append( "<input type='hidden' id='assayToMaterialMap' name='assayToMaterialMap' value='" <add> + jsonSerialization + "'/>" ); <ide> } catch ( MapperException e ) { <ide> // cannot serialize <del> log.error( "cannot serialize materialMap object!" ); <del> } <del> buf.append( "<input type='hidden' id='assayToMaterialMap' name='assayToMaterialMap' value='" <del> + jsonSerialization + "'/>" ); <add> } <add> <ide> } <ide> <ide> buf.append( "</div>" );
Java
apache-2.0
3eda519a662f04e1f9b98b5d1680bfc3cd319616
0
gentics/mesh,gentics/mesh,gentics/mesh,gentics/mesh
package com.gentics.mesh.core.schema; import static com.gentics.mesh.assertj.MeshAssertions.assertThat; import static com.gentics.mesh.core.rest.schema.change.impl.SchemaChangeOperation.ADDFIELD; import static com.gentics.mesh.core.rest.schema.change.impl.SchemaChangeOperation.REMOVEFIELD; import static com.gentics.mesh.core.rest.schema.change.impl.SchemaChangeOperation.UPDATEMICROSCHEMA; import static com.gentics.mesh.test.ClientHelper.call; import static com.gentics.mesh.test.TestSize.FULL; import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertNotNull; import org.junit.Test; import com.gentics.madl.tx.Tx; import com.gentics.mesh.FieldUtil; import com.gentics.mesh.core.data.container.impl.MicroschemaContainerImpl; import com.gentics.mesh.core.data.schema.MicroschemaContainer; import com.gentics.mesh.core.data.schema.MicroschemaContainerVersion; import com.gentics.mesh.core.rest.microschema.MicroschemaModel; import com.gentics.mesh.core.rest.microschema.impl.MicroschemaModelImpl; import com.gentics.mesh.core.rest.schema.BinaryFieldSchema; import com.gentics.mesh.core.rest.schema.Microschema; import com.gentics.mesh.core.rest.schema.StringFieldSchema; import com.gentics.mesh.core.rest.schema.change.impl.SchemaChangesListModel; import com.gentics.mesh.core.rest.schema.impl.StringFieldSchemaImpl; import com.gentics.mesh.test.context.AbstractMeshTest; import com.gentics.mesh.test.context.MeshTestSetting; @MeshTestSetting(testSize = FULL, startServer = true) public class MicroschemaDiffEndpointTest extends AbstractMeshTest { private Microschema getMicroschema() { Microschema vcardMicroschema = new MicroschemaModelImpl(); vcardMicroschema.setName("vcard"); vcardMicroschema.setDescription("Microschema for a vcard"); // firstname field StringFieldSchema firstNameFieldSchema = new StringFieldSchemaImpl(); firstNameFieldSchema.setName("firstName"); firstNameFieldSchema.setLabel("First Name"); firstNameFieldSchema.setRequired(true); vcardMicroschema.addField(firstNameFieldSchema); // lastname field StringFieldSchema lastNameFieldSchema = new StringFieldSchemaImpl(); lastNameFieldSchema.setName("lastName"); lastNameFieldSchema.setLabel("Last Name"); lastNameFieldSchema.setRequired(true); vcardMicroschema.addField(lastNameFieldSchema); // address field StringFieldSchema addressFieldSchema = new StringFieldSchemaImpl(); addressFieldSchema.setName("address"); addressFieldSchema.setLabel("Address"); vcardMicroschema.addField(addressFieldSchema); // postcode field StringFieldSchema postcodeFieldSchema = new StringFieldSchemaImpl(); postcodeFieldSchema.setName("postcode"); postcodeFieldSchema.setLabel("Post Code"); vcardMicroschema.addField(postcodeFieldSchema); return vcardMicroschema; } @Test public void testDiffEmptyDescription() { // Set the description to empty string String microschemaUuid = tx(() -> microschemaContainer("vcard").getUuid()); tx(() -> { MicroschemaContainer microschema = tx(() -> microschemaContainer("vcard")); MicroschemaContainerVersion microschemaVersion = microschema.getLatestVersion(); MicroschemaModel schemaModel = microschemaVersion.getSchema(); schemaModel.setDescription(""); microschemaVersion.setJson(schemaModel.toJson()); }); // Diff the schema with no description in the JSON Microschema request = getMicroschema(); request.setDescription(null); SchemaChangesListModel changes = call(() -> client().diffMicroschema(microschemaUuid, request)); assertThat(changes.getChanges()).isEmpty(); } @Test public void testNoDiff() { try (Tx tx = tx()) { MicroschemaContainer microschema = microschemaContainer("vcard"); Microschema request = getMicroschema(); SchemaChangesListModel changes = call(() -> client().diffMicroschema(microschema.getUuid(), request)); assertThat(changes.getChanges()).isEmpty(); } } @Test public void testAddField() { String uuid = tx(() -> microschemaContainer("vcard").getUuid()); Microschema request = getMicroschema(); StringFieldSchema stringField = FieldUtil.createStringFieldSchema("someField"); stringField.setAllowedValues("one", "two"); request.addField(stringField); SchemaChangesListModel changes = call(() -> client().diffMicroschema(uuid, request)); assertNotNull(changes); assertThat(changes.getChanges()).hasSize(2); assertThat(changes.getChanges().get(0)).is(ADDFIELD).forField("someField"); assertThat(changes.getChanges().get(1)).is(UPDATEMICROSCHEMA).hasProperty("order", new String[] { "firstName", "lastName", "address", "postcode", "someField" }); call(() -> client().applyChangesToMicroschema(uuid, changes)); } @Test public void testApplyChanges() { String uuid = tx(() -> microschemaContainer("vcard").getUuid()); Microschema request = getMicroschema(); StringFieldSchema stringField = FieldUtil .createStringFieldSchema("someField"); stringField.setAllowedValues("one", "two"); request.addField(stringField); // 1. Diff the schema SchemaChangesListModel changes = call(() -> client().diffMicroschema(uuid, request)); // 2. Apply the changes call(() -> client().applyChangesToMicroschema(uuid, changes)); } @Test public void testAddUnsupportedField() { try (Tx tx = tx()) { MicroschemaContainer microschema = microschemaContainer("vcard"); Microschema request = getMicroschema(); BinaryFieldSchema binaryField = FieldUtil.createBinaryFieldSchema("binaryField"); request.addField(binaryField); call(() -> client().diffMicroschema(microschema.getUuid(), request), BAD_REQUEST, "microschema_error_field_type_not_allowed", "binaryField", "binary"); } } @Test public void testRemoveField() { try (Tx tx = tx()) { MicroschemaContainer microschema = microschemaContainer("vcard"); Microschema request = getMicroschema(); request.removeField("postcode"); SchemaChangesListModel changes = call(() -> client().diffMicroschema(microschema.getUuid(), request)); assertNotNull(changes); assertThat(changes.getChanges()).hasSize(2); assertThat(changes.getChanges().get(0)).is(REMOVEFIELD).forField("postcode"); assertThat(changes.getChanges().get(1)).is(UPDATEMICROSCHEMA).hasProperty("order", new String[] { "firstName", "lastName", "address" }); } } }
core/src/test/java/com/gentics/mesh/core/schema/MicroschemaDiffEndpointTest.java
package com.gentics.mesh.core.schema; import com.gentics.madl.tx.Tx; import com.gentics.mesh.FieldUtil; import com.gentics.mesh.core.data.schema.MicroschemaContainer; import com.gentics.mesh.core.rest.microschema.impl.MicroschemaModelImpl; import com.gentics.mesh.core.rest.schema.BinaryFieldSchema; import com.gentics.mesh.core.rest.schema.Microschema; import com.gentics.mesh.core.rest.schema.StringFieldSchema; import com.gentics.mesh.core.rest.schema.change.impl.SchemaChangesListModel; import com.gentics.mesh.core.rest.schema.impl.StringFieldSchemaImpl; import com.gentics.mesh.test.context.AbstractMeshTest; import com.gentics.mesh.test.context.MeshTestSetting; import org.junit.Test; import static com.gentics.mesh.assertj.MeshAssertions.assertThat; import static com.gentics.mesh.core.rest.schema.change.impl.SchemaChangeOperation.ADDFIELD; import static com.gentics.mesh.core.rest.schema.change.impl.SchemaChangeOperation.REMOVEFIELD; import static com.gentics.mesh.core.rest.schema.change.impl.SchemaChangeOperation.UPDATEMICROSCHEMA; import static com.gentics.mesh.test.ClientHelper.call; import static com.gentics.mesh.test.TestSize.FULL; import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST; import static org.junit.Assert.assertNotNull; @MeshTestSetting(testSize = FULL, startServer = true) public class MicroschemaDiffEndpointTest extends AbstractMeshTest { private Microschema getMicroschema() { Microschema vcardMicroschema = new MicroschemaModelImpl(); vcardMicroschema.setName("vcard"); vcardMicroschema.setDescription("Microschema for a vcard"); // firstname field StringFieldSchema firstNameFieldSchema = new StringFieldSchemaImpl(); firstNameFieldSchema.setName("firstName"); firstNameFieldSchema.setLabel("First Name"); firstNameFieldSchema.setRequired(true); vcardMicroschema.addField(firstNameFieldSchema); // lastname field StringFieldSchema lastNameFieldSchema = new StringFieldSchemaImpl(); lastNameFieldSchema.setName("lastName"); lastNameFieldSchema.setLabel("Last Name"); lastNameFieldSchema.setRequired(true); vcardMicroschema.addField(lastNameFieldSchema); // address field StringFieldSchema addressFieldSchema = new StringFieldSchemaImpl(); addressFieldSchema.setName("address"); addressFieldSchema.setLabel("Address"); vcardMicroschema.addField(addressFieldSchema); // postcode field StringFieldSchema postcodeFieldSchema = new StringFieldSchemaImpl(); postcodeFieldSchema.setName("postcode"); postcodeFieldSchema.setLabel("Post Code"); vcardMicroschema.addField(postcodeFieldSchema); return vcardMicroschema; } @Test public void testNoDiff() { try (Tx tx = tx()) { MicroschemaContainer microschema = microschemaContainer("vcard"); Microschema request = getMicroschema(); SchemaChangesListModel changes = call(() -> client().diffMicroschema(microschema.getUuid(), request)); assertNotNull(changes); assertThat(changes.getChanges()).isEmpty(); } } @Test public void testAddField() { String uuid = tx(() -> microschemaContainer("vcard").getUuid()); Microschema request = getMicroschema(); StringFieldSchema stringField = FieldUtil.createStringFieldSchema("someField"); stringField.setAllowedValues("one", "two"); request.addField(stringField); SchemaChangesListModel changes = call(() -> client().diffMicroschema(uuid, request)); assertNotNull(changes); assertThat(changes.getChanges()).hasSize(2); assertThat(changes.getChanges().get(0)).is(ADDFIELD).forField("someField"); assertThat(changes.getChanges().get(1)).is(UPDATEMICROSCHEMA).hasProperty("order", new String[] { "firstName", "lastName", "address", "postcode", "someField" }); call(() -> client().applyChangesToMicroschema(uuid, changes)); } @Test public void testApplyChanges() { String uuid = tx(() -> microschemaContainer("vcard").getUuid()); Microschema request = getMicroschema(); StringFieldSchema stringField = FieldUtil .createStringFieldSchema("someField"); stringField.setAllowedValues("one", "two"); request.addField(stringField); // 1. Diff the schema SchemaChangesListModel changes = call(() -> client().diffMicroschema(uuid, request)); // 2. Apply the changes call(() -> client().applyChangesToMicroschema(uuid, changes)); } @Test public void testAddUnsupportedField() { try (Tx tx = tx()) { MicroschemaContainer microschema = microschemaContainer("vcard"); Microschema request = getMicroschema(); BinaryFieldSchema binaryField = FieldUtil.createBinaryFieldSchema("binaryField"); request.addField(binaryField); call(() -> client().diffMicroschema(microschema.getUuid(), request), BAD_REQUEST, "microschema_error_field_type_not_allowed", "binaryField", "binary"); } } @Test public void testRemoveField() { try (Tx tx = tx()) { MicroschemaContainer microschema = microschemaContainer("vcard"); Microschema request = getMicroschema(); request.removeField("postcode"); SchemaChangesListModel changes = call(() -> client().diffMicroschema(microschema.getUuid(), request)); assertNotNull(changes); assertThat(changes.getChanges()).hasSize(2); assertThat(changes.getChanges().get(0)).is(REMOVEFIELD).forField("postcode"); assertThat(changes.getChanges().get(1)).is(UPDATEMICROSCHEMA).hasProperty("order", new String[] { "firstName", "lastName", "address" }); } } }
Add schema diff test
core/src/test/java/com/gentics/mesh/core/schema/MicroschemaDiffEndpointTest.java
Add schema diff test
<ide><path>ore/src/test/java/com/gentics/mesh/core/schema/MicroschemaDiffEndpointTest.java <ide> package com.gentics.mesh.core.schema; <add> <add>import static com.gentics.mesh.assertj.MeshAssertions.assertThat; <add>import static com.gentics.mesh.core.rest.schema.change.impl.SchemaChangeOperation.ADDFIELD; <add>import static com.gentics.mesh.core.rest.schema.change.impl.SchemaChangeOperation.REMOVEFIELD; <add>import static com.gentics.mesh.core.rest.schema.change.impl.SchemaChangeOperation.UPDATEMICROSCHEMA; <add>import static com.gentics.mesh.test.ClientHelper.call; <add>import static com.gentics.mesh.test.TestSize.FULL; <add>import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST; <add>import static org.assertj.core.api.Assertions.assertThat; <add>import static org.junit.Assert.assertNotNull; <add> <add>import org.junit.Test; <ide> <ide> import com.gentics.madl.tx.Tx; <ide> import com.gentics.mesh.FieldUtil; <add>import com.gentics.mesh.core.data.container.impl.MicroschemaContainerImpl; <ide> import com.gentics.mesh.core.data.schema.MicroschemaContainer; <add>import com.gentics.mesh.core.data.schema.MicroschemaContainerVersion; <add>import com.gentics.mesh.core.rest.microschema.MicroschemaModel; <ide> import com.gentics.mesh.core.rest.microschema.impl.MicroschemaModelImpl; <ide> import com.gentics.mesh.core.rest.schema.BinaryFieldSchema; <ide> import com.gentics.mesh.core.rest.schema.Microschema; <ide> import com.gentics.mesh.core.rest.schema.impl.StringFieldSchemaImpl; <ide> import com.gentics.mesh.test.context.AbstractMeshTest; <ide> import com.gentics.mesh.test.context.MeshTestSetting; <del> <del>import org.junit.Test; <del> <del>import static com.gentics.mesh.assertj.MeshAssertions.assertThat; <del>import static com.gentics.mesh.core.rest.schema.change.impl.SchemaChangeOperation.ADDFIELD; <del>import static com.gentics.mesh.core.rest.schema.change.impl.SchemaChangeOperation.REMOVEFIELD; <del>import static com.gentics.mesh.core.rest.schema.change.impl.SchemaChangeOperation.UPDATEMICROSCHEMA; <del>import static com.gentics.mesh.test.ClientHelper.call; <del>import static com.gentics.mesh.test.TestSize.FULL; <del>import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST; <del>import static org.junit.Assert.assertNotNull; <ide> <ide> @MeshTestSetting(testSize = FULL, startServer = true) <ide> public class MicroschemaDiffEndpointTest extends AbstractMeshTest { <ide> } <ide> <ide> @Test <add> public void testDiffEmptyDescription() { <add> // Set the description to empty string <add> String microschemaUuid = tx(() -> microschemaContainer("vcard").getUuid()); <add> tx(() -> { <add> MicroschemaContainer microschema = tx(() -> microschemaContainer("vcard")); <add> MicroschemaContainerVersion microschemaVersion = microschema.getLatestVersion(); <add> MicroschemaModel schemaModel = microschemaVersion.getSchema(); <add> schemaModel.setDescription(""); <add> microschemaVersion.setJson(schemaModel.toJson()); <add> }); <add> <add> // Diff the schema with no description in the JSON <add> Microschema request = getMicroschema(); <add> request.setDescription(null); <add> SchemaChangesListModel changes = call(() -> client().diffMicroschema(microschemaUuid, request)); <add> assertThat(changes.getChanges()).isEmpty(); <add> } <add> <add> @Test <ide> public void testNoDiff() { <ide> try (Tx tx = tx()) { <ide> MicroschemaContainer microschema = microschemaContainer("vcard"); <ide> Microschema request = getMicroschema(); <ide> <ide> SchemaChangesListModel changes = call(() -> client().diffMicroschema(microschema.getUuid(), request)); <del> assertNotNull(changes); <ide> assertThat(changes.getChanges()).isEmpty(); <ide> } <ide> } <ide> assertThat(changes.getChanges()).hasSize(2); <ide> assertThat(changes.getChanges().get(0)).is(ADDFIELD).forField("someField"); <ide> assertThat(changes.getChanges().get(1)).is(UPDATEMICROSCHEMA).hasProperty("order", <del> new String[] { "firstName", "lastName", "address", "postcode", "someField" }); <add> new String[] { "firstName", "lastName", "address", "postcode", "someField" }); <ide> call(() -> client().applyChangesToMicroschema(uuid, changes)); <ide> } <ide> <ide> request.addField(binaryField); <ide> <ide> call(() -> client().diffMicroschema(microschema.getUuid(), request), BAD_REQUEST, "microschema_error_field_type_not_allowed", <del> "binaryField", "binary"); <add> "binaryField", "binary"); <ide> } <ide> } <ide>
Java
apache-2.0
9c40b4e59cd83027bdaaea047c01e47f08546e27
0
OpenVidu/openvidu,OpenVidu/openvidu,OpenVidu/openvidu,OpenVidu/openvidu,OpenVidu/openvidu,OpenVidu/openvidu
/* * (C) Copyright 2017-2019 OpenVidu (https://openvidu.io/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.openvidu.test.e2e; import static org.junit.Assert.fail; import static org.openqa.selenium.OutputType.BASE64; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.math.RoundingMode; import java.nio.file.Path; import java.nio.file.Paths; import java.text.DecimalFormat; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.imageio.ImageIO; import org.apache.commons.io.FileUtils; import org.jcodec.api.FrameGrab; import org.jcodec.api.JCodecException; import org.jcodec.common.model.Picture; import org.jcodec.scale.AWTUtil; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.junit.Assert; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import org.openqa.selenium.By; import org.openqa.selenium.Dimension; import org.openqa.selenium.Keys; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.stream.JsonReader; import io.github.bonigarcia.SeleniumExtension; import io.github.bonigarcia.wdm.WebDriverManager; import io.openvidu.java.client.OpenVidu; import io.openvidu.java.client.Recording; import io.openvidu.test.e2e.browser.BrowserUser; import io.openvidu.test.e2e.browser.ChromeAndroidUser; import io.openvidu.test.e2e.browser.ChromeUser; import io.openvidu.test.e2e.browser.FirefoxUser; import io.openvidu.test.e2e.browser.OperaUser; import io.openvidu.test.e2e.utils.CommandLineExecuter; import io.openvidu.test.e2e.utils.MultimediaFileMetadata; import io.openvidu.test.e2e.utils.Unzipper; /** * E2E tests for openvidu-testapp. * * @author Pablo Fuente ([email protected]) * @since 1.1.1 */ @Tag("e2e") @DisplayName("E2E tests for OpenVidu TestApp") @ExtendWith(SeleniumExtension.class) @RunWith(JUnitPlatform.class) public class OpenViduTestAppE2eTest { static String OPENVIDU_SECRET = "MY_SECRET"; static String OPENVIDU_URL = "https://localhost:4443/"; static String APP_URL = "http://localhost:4200/"; static Exception ex = null; private final Object lock = new Object(); private static final Logger log = LoggerFactory.getLogger(OpenViduTestAppE2eTest.class); BrowserUser user; volatile static boolean isRecordingTest; @BeforeAll() static void setupAll() { String ffmpegOutput = new CommandLineExecuter().executeCommand("which ffmpeg"); if (ffmpegOutput == null || ffmpegOutput.isEmpty()) { log.error("ffmpeg package is not installed in the host machine"); Assert.fail(); return; } else { log.info("ffmpeg is installed and accesible"); } WebDriverManager.chromedriver().setup(); WebDriverManager.firefoxdriver().setup(); String appUrl = System.getProperty("APP_URL"); if (appUrl != null) { APP_URL = appUrl; } log.info("Using URL {} to connect to openvidu-testapp", APP_URL); String openviduUrl = System.getProperty("OPENVIDU_URL"); if (openviduUrl != null) { OPENVIDU_URL = openviduUrl; } log.info("Using URL {} to connect to openvidu-server", OPENVIDU_URL); String openvidusecret = System.getProperty("OPENVIDU_SECRET"); if (openvidusecret != null) { OPENVIDU_SECRET = openvidusecret; } log.info("Using secret {} to connect to openvidu-server", OPENVIDU_SECRET); try { log.info("Cleaning folder /opt/openvidu/recordings"); FileUtils.cleanDirectory(new File("/opt/openvidu/recordings")); } catch (IOException e) { log.error(e.getMessage()); } } void setupBrowser(String browser) { switch (browser) { case "chrome": this.user = new ChromeUser("TestUser", 50); break; case "firefox": this.user = new FirefoxUser("TestUser", 50); break; case "opera": this.user = new OperaUser("TestUser", 50); break; case "chromeAndroid": this.user = new ChromeAndroidUser("TestUser", 50); break; case "chromeAlternateScreenShare": this.user = new ChromeUser("TestUser", 50, "OpenVidu TestApp"); break; default: this.user = new ChromeUser("TestUser", 50); } user.getDriver().get(APP_URL); WebElement urlInput = user.getDriver().findElement(By.id("openvidu-url")); urlInput.clear(); urlInput.sendKeys(OPENVIDU_URL); WebElement secretInput = user.getDriver().findElement(By.id("openvidu-secret")); secretInput.clear(); secretInput.sendKeys(OPENVIDU_SECRET); user.getEventManager().startPolling(); } void setupChromeWithFakeVideo(Path videoFileLocation) { this.user = new ChromeUser("TestUser", 50, videoFileLocation); user.getDriver().get(APP_URL); WebElement urlInput = user.getDriver().findElement(By.id("openvidu-url")); urlInput.clear(); urlInput.sendKeys(OPENVIDU_URL); WebElement secretInput = user.getDriver().findElement(By.id("openvidu-secret")); secretInput.clear(); secretInput.sendKeys(OPENVIDU_SECRET); user.getEventManager().startPolling(); } @AfterEach void dispose() { user.dispose(); if (isRecordingTest) { try { FileUtils.cleanDirectory(new File("/opt/openvidu/recordings")); } catch (IOException e) { log.error(e.getMessage()); } isRecordingTest = false; } } @Test @DisplayName("One2One Chrome [Video + Audio]") void oneToOneVideoAudioSessionChrome() throws Exception { setupBrowser("chrome"); log.info("One2One Chrome [Video + Audio]"); user.getDriver().findElement(By.id("auto-join-checkbox")).click(); user.getDriver().findElement(By.id("one2one-btn")).click(); user.getEventManager().waitUntilEventReaches("connectionCreated", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 2); user.getEventManager().waitUntilEventReaches("streamCreated", 4); user.getEventManager().waitUntilEventReaches("streamPlaying", 4); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 4); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); gracefullyLeaveParticipants(2); } @Test @DisplayName("One2One [Audio]") void oneToOneAudioSession() throws Exception { setupBrowser("chrome"); log.info("One2One [Audio]"); user.getDriver().findElement(By.id("one2one-btn")).click(); user.getDriver().findElements(By.className("send-video-checkbox")).forEach(el -> el.click()); user.getDriver().findElements(By.className("join-btn")).forEach(el -> el.sendKeys(Keys.ENTER)); user.getEventManager().waitUntilEventReaches("connectionCreated", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 2); user.getEventManager().waitUntilEventReaches("streamCreated", 4); user.getEventManager().waitUntilEventReaches("streamPlaying", 4); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 4); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, false)); gracefullyLeaveParticipants(2); } @Test @DisplayName("One2One [Video]") void oneToOneVideoSession() throws Exception { setupBrowser("chrome"); log.info("One2One [Video]"); user.getDriver().findElement(By.id("one2one-btn")).click(); user.getDriver().findElements(By.className("send-audio-checkbox")).forEach(el -> el.click()); user.getDriver().findElements(By.className("join-btn")).forEach(el -> el.sendKeys(Keys.ENTER)); user.getEventManager().waitUntilEventReaches("connectionCreated", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 2); user.getEventManager().waitUntilEventReaches("streamCreated", 4); user.getEventManager().waitUntilEventReaches("streamPlaying", 4); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 4); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), false, true)); gracefullyLeaveParticipants(2); } @Test @DisplayName("One2Many [Video + Audio]") void oneToManyVideoAudioSession() throws Exception { setupBrowser("chrome"); log.info("One2Many [Video + Audio]"); user.getDriver().findElement(By.id("auto-join-checkbox")).click(); user.getDriver().findElement(By.id("one2many-btn")).click(); user.getEventManager().waitUntilEventReaches("connectionCreated", 16); user.getEventManager().waitUntilEventReaches("accessAllowed", 1); user.getEventManager().waitUntilEventReaches("streamCreated", 4); user.getEventManager().waitUntilEventReaches("streamPlaying", 4); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 4); user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true); gracefullyLeaveParticipants(4); } @Test @DisplayName("Unique user remote subscription [Video + Audio]") void oneRemoteSubscription() throws Exception { setupBrowser("chrome"); log.info("Unique user remote subscription [Video + Audio]"); user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.className("subscribe-remote-check")).click(); user.getDriver().findElement(By.className("join-btn")).click(); user.getEventManager().waitUntilEventReaches("connectionCreated", 1); user.getEventManager().waitUntilEventReaches("accessAllowed", 1); user.getEventManager().waitUntilEventReaches("streamCreated", 1); user.getEventManager().waitUntilEventReaches("streamPlaying", 1); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 1); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); gracefullyLeaveParticipants(1); } @Test @DisplayName("Unique user remote subscription Firefox [Video + Audio]") void oneRemoteSubscriptionFirefox() throws Exception { setupBrowser("firefox"); log.info("Unique user remote subscription Firefox [Video + Audio]"); user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.className("subscribe-remote-check")).click(); user.getDriver().findElement(By.className("join-btn")).click(); user.getEventManager().waitUntilEventReaches("connectionCreated", 1); user.getEventManager().waitUntilEventReaches("accessAllowed", 1); Thread.sleep(3000); gracefullyLeaveParticipants(1); } @Test @DisplayName("Unique user remote subscription [ScreenShare + Audio]") void oneRemoteSubscriptionScreen() throws Exception { setupBrowser("chrome"); log.info("Unique user remote subscription [ScreenShare + Audio]"); user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.className("screen-radio")).click(); user.getDriver().findElement(By.className("subscribe-remote-check")).click(); user.getDriver().findElement(By.className("join-btn")).click(); user.getEventManager().waitUntilEventReaches("connectionCreated", 1); user.getEventManager().waitUntilEventReaches("accessAllowed", 1); user.getEventManager().waitUntilEventReaches("streamCreated", 1); user.getEventManager().waitUntilEventReaches("streamPlaying", 1); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 1); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); gracefullyLeaveParticipants(1); } @Test @DisplayName("Many2Many [Video + Audio]") void manyToManyVideoAudioSession() throws Exception { setupBrowser("chrome"); log.info("Many2Many [Video + Audio]"); WebElement addUser = user.getDriver().findElement(By.id("add-user-btn")); for (int i = 0; i < 4; i++) { addUser.click(); } user.getDriver().findElements(By.className("join-btn")).forEach(el -> el.sendKeys(Keys.ENTER)); user.getEventManager().waitUntilEventReaches("connectionCreated", 16); user.getEventManager().waitUntilEventReaches("accessAllowed", 4); user.getEventManager().waitUntilEventReaches("streamCreated", 16); user.getEventManager().waitUntilEventReaches("streamPlaying", 16); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 16); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); gracefullyLeaveParticipants(4); } @Test @DisplayName("One2One Firefox [Video + Audio]") void oneToOneVideoAudioSessionFirefox() throws Exception { setupBrowser("firefox"); log.info("One2One Firefox [Video + Audio]"); user.getDriver().findElement(By.id("auto-join-checkbox")).click(); user.getDriver().findElement(By.id("one2one-btn")).click(); user.getEventManager().waitUntilEventReaches("connectionCreated", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 2); user.getEventManager().waitUntilEventReaches("streamCreated", 4); user.getEventManager().waitUntilEventReaches("streamPlaying", 4); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 4); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); gracefullyLeaveParticipants(2); } @Test @DisplayName("Cross-Browser test") void crossBrowserTest() throws Exception { setupBrowser("chrome"); log.info("Cross-Browser test"); Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread th, Throwable ex) { System.out.println("Uncaught exception: " + ex); synchronized (lock) { OpenViduTestAppE2eTest.ex = new Exception(ex); } } }; Thread t = new Thread(() -> { BrowserUser user2 = new FirefoxUser("TestUser", 30); user2.getDriver().get(APP_URL); WebElement urlInput = user2.getDriver().findElement(By.id("openvidu-url")); urlInput.clear(); urlInput.sendKeys(OPENVIDU_URL); WebElement secretInput = user2.getDriver().findElement(By.id("openvidu-secret")); secretInput.clear(); secretInput.sendKeys(OPENVIDU_SECRET); user2.getEventManager().startPolling(); user2.getDriver().findElement(By.id("add-user-btn")).click(); user2.getDriver().findElement(By.className("join-btn")).click(); try { user2.getEventManager().waitUntilEventReaches("connectionCreated", 2); user2.getEventManager().waitUntilEventReaches("accessAllowed", 1); user2.getEventManager().waitUntilEventReaches("streamCreated", 2); user2.getEventManager().waitUntilEventReaches("streamPlaying", 2); Assert.assertEquals(user2.getDriver().findElements(By.tagName("video")).size(), 2); Assert.assertTrue(user2.getEventManager() .assertMediaTracks(user2.getDriver().findElements(By.tagName("video")), true, true)); user2.getEventManager().waitUntilEventReaches("streamDestroyed", 1); user2.getEventManager().waitUntilEventReaches("connectionDestroyed", 1); user2.getDriver().findElement(By.id("remove-user-btn")).click(); user2.getEventManager().waitUntilEventReaches("sessionDisconnected", 1); } catch (Exception e) { e.printStackTrace(); user2.dispose(); Thread.currentThread().interrupt(); } user2.dispose(); }); t.setUncaughtExceptionHandler(h); t.start(); user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.className("join-btn")).click(); user.getEventManager().waitUntilEventReaches("connectionCreated", 2); user.getEventManager().waitUntilEventReaches("accessAllowed", 1); user.getEventManager().waitUntilEventReaches("streamCreated", 2); user.getEventManager().waitUntilEventReaches("streamPlaying", 2); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 2); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); gracefullyLeaveParticipants(1); t.join(); synchronized (lock) { if (OpenViduTestAppE2eTest.ex != null) { throw OpenViduTestAppE2eTest.ex; } } } @Test @DisplayName("Signal message") void oneToManySignalMessage() throws Exception { setupBrowser("chrome"); log.info("Signal message"); WebElement addUser = user.getDriver().findElement(By.id("add-user-btn")); for (int i = 0; i < 4; i++) { addUser.click(); } user.getDriver().findElements(By.className("publish-checkbox")).forEach(el -> el.click()); user.getDriver().findElements(By.className("join-btn")).forEach(el -> el.sendKeys(Keys.ENTER)); user.getEventManager().waitUntilEventReaches("connectionCreated", 16); user.getDriver().findElements(By.className(("message-btn"))).get(0).click(); user.getEventManager().waitUntilEventReaches("signal", 4); gracefullyLeaveParticipants(4); } @Test @DisplayName("Subscribe Unsubscribe") void subscribeUnsubscribeTest() throws Exception { setupBrowser("chrome"); log.info("Subscribe Unsubscribe"); user.getDriver().findElement(By.id("one2one-btn")).click(); user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .publish-checkbox")).click(); user.getDriver().findElements(By.className("join-btn")).forEach(el -> el.sendKeys(Keys.ENTER)); user.getEventManager().waitUntilEventReaches("connectionCreated", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 1); user.getEventManager().waitUntilEventReaches("streamCreated", 2); user.getEventManager().waitUntilEventReaches("streamPlaying", 2); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 2); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); // Global unsubscribe-subscribe WebElement subscriberVideo = user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 video")); WebElement subBtn = user.getDriver().findElement(By.cssSelector(("#openvidu-instance-0 .sub-btn"))); subBtn.click(); user.getWaiter() .until(ExpectedConditions.not(ExpectedConditions.attributeToBeNotEmpty(subscriberVideo, "srcObject"))); Assert.assertFalse(user.getEventManager().hasMediaStream(subscriberVideo)); subBtn.click(); user.getEventManager().waitUntilEventReaches("streamPlaying", 3); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 2); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); // Video unsubscribe subscriberVideo = user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 video")); Iterable<WebElement> firstVideo = Arrays.asList(subscriberVideo); user.getDriver().findElement(By.cssSelector(("#openvidu-instance-0 .sub-video-btn"))).click(); Thread.sleep(1000); Assert.assertTrue(user.getEventManager().assertMediaTracks(firstVideo, true, false)); // Audio unsubscribe user.getDriver().findElement(By.cssSelector(("#openvidu-instance-0 .sub-audio-btn"))).click(); Thread.sleep(1000); Assert.assertTrue(user.getEventManager().assertMediaTracks(firstVideo, false, false)); // Video and audio subscribe user.getDriver().findElement(By.cssSelector(("#openvidu-instance-0 .sub-video-btn"))).click(); Thread.sleep(1000); Assert.assertTrue(user.getEventManager().assertMediaTracks(firstVideo, false, true)); user.getDriver().findElement(By.cssSelector(("#openvidu-instance-0 .sub-audio-btn"))).click(); Thread.sleep(1000); Assert.assertTrue(user.getEventManager().assertMediaTracks(firstVideo, true, true)); gracefullyLeaveParticipants(2); } @Test @DisplayName("Publish Unpublish") void publishUnpublishTest() throws Exception { setupBrowser("chrome"); log.info("Signal message"); user.getDriver().findElement(By.id("auto-join-checkbox")).click(); user.getDriver().findElement(By.id("one2one-btn")).click(); user.getEventManager().waitUntilEventReaches("connectionCreated", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 2); user.getEventManager().waitUntilEventReaches("streamCreated", 4); user.getEventManager().waitUntilEventReaches("streamPlaying", 4); user.getWaiter().until(ExpectedConditions.numberOfElementsToBe(By.tagName("video"), 4)); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); Thread.sleep(2000); List<WebElement> publishButtons = user.getDriver().findElements(By.className("pub-btn")); for (WebElement el : publishButtons) { el.click(); } user.getEventManager().waitUntilEventReaches("streamDestroyed", 4); for (WebElement video : user.getDriver().findElements(By.tagName("video"))) { user.getWaiter() .until(ExpectedConditions.not(ExpectedConditions.attributeToBeNotEmpty(video, "srcObject"))); Assert.assertFalse(user.getEventManager().hasMediaStream(video)); } for (WebElement el : publishButtons) { el.click(); Thread.sleep(1000); } user.getEventManager().waitUntilEventReaches("streamCreated", 8); user.getEventManager().waitUntilEventReaches("streamPlaying", 8); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); gracefullyLeaveParticipants(2); } @Test @DisplayName("Change publisher dynamically") void changePublisherTest() throws Exception { Queue<Boolean> threadAssertions = new ConcurrentLinkedQueue<Boolean>(); setupBrowser("chrome"); log.info("Change publisher dynamically"); WebElement oneToManyInput = user.getDriver().findElement(By.id("one2many-input")); oneToManyInput.clear(); oneToManyInput.sendKeys("1"); user.getDriver().findElement(By.id("auto-join-checkbox")).click(); final CountDownLatch latch1 = new CountDownLatch(2); // First publication (audio + video [CAMERA]) user.getEventManager().on("streamPlaying", (event) -> { if (event.get("eventContent") != null) { threadAssertions.add(((String) event.get("eventContent")).contains("CAMERA")); } latch1.countDown(); }); user.getDriver().findElement(By.id("one2many-btn")).click(); Thread.sleep(2000); user.getEventManager().waitUntilEventReaches("connectionCreated", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 1); user.getEventManager().waitUntilEventReaches("streamCreated", 2); user.getEventManager().waitUntilEventReaches("streamPlaying", 2); if (!latch1.await(8000, TimeUnit.MILLISECONDS)) { gracefullyLeaveParticipants(2); fail(); return; } user.getEventManager().off("streamPlaying"); for (Iterator<Boolean> iter = threadAssertions.iterator(); iter.hasNext();) { Assert.assertTrue(iter.next()); iter.remove(); } user.getWaiter().until(ExpectedConditions.numberOfElementsToBe(By.tagName("video"), 2)); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); Thread.sleep(2000); final CountDownLatch latch2 = new CountDownLatch(2); // Second publication (only video (SCREEN)) user.getEventManager().on("streamPlaying", (event) -> { if (event.get("eventContent") != null) { threadAssertions.add(((String) event.get("eventContent")).contains("SCREEN")); } latch2.countDown(); }); user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .change-publisher-btn")).click(); user.getEventManager().waitUntilEventReaches("streamDestroyed", 2); user.getEventManager().waitUntilEventReaches("accessAllowed", 2); user.getEventManager().waitUntilEventReaches("streamCreated", 4); user.getEventManager().waitUntilEventReaches("streamPlaying", 4); if (!latch2.await(8000, TimeUnit.MILLISECONDS)) { gracefullyLeaveParticipants(2); fail(); return; } user.getEventManager().off("streamPlaying"); for (Iterator<Boolean> iter = threadAssertions.iterator(); iter.hasNext();) { Assert.assertTrue(iter.next()); iter.remove(); } Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), false, true)); Thread.sleep(2000); final CountDownLatch latch3 = new CountDownLatch(2); // Third publication (audio + video [CAMERA]) user.getEventManager().on("streamPlaying", (event) -> { if (event.get("eventContent") != null) { threadAssertions.add(((String) event.get("eventContent")).contains("CAMERA")); } latch3.countDown(); }); user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .change-publisher-btn")).click(); user.getEventManager().waitUntilEventReaches("streamDestroyed", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 3); user.getEventManager().waitUntilEventReaches("streamCreated", 6); user.getEventManager().waitUntilEventReaches("streamPlaying", 6); if (!latch3.await(8000, TimeUnit.MILLISECONDS)) { gracefullyLeaveParticipants(2); fail(); return; } user.getEventManager().off("streamPlaying"); for (Iterator<Boolean> iter = threadAssertions.iterator(); iter.hasNext();) { Assert.assertTrue(iter.next()); iter.remove(); } Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); gracefullyLeaveParticipants(2); } @Test @DisplayName("Moderator capabilities") void moderatorCapabilitiesTest() throws Exception { setupBrowser("chrome"); log.info("Moderator capabilities"); // Add publisher user.getDriver().findElement(By.id("add-user-btn")).click(); // Add subscriber user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.cssSelector("#openvidu-instance-1 .publish-checkbox")).click(); // Add and configure moderator (only subscribe) user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.cssSelector("#openvidu-instance-2 .publish-checkbox")).click(); user.getDriver().findElement(By.id("session-settings-btn-2")).click(); Thread.sleep(1000); user.getDriver().findElement(By.id("radio-btn-mod")).click(); user.getDriver().findElement(By.id("save-btn")).click(); Thread.sleep(1000); user.getDriver().findElements(By.className("join-btn")).forEach(el -> el.sendKeys(Keys.ENTER)); user.getEventManager().waitUntilEventReaches("connectionCreated", 9); user.getEventManager().waitUntilEventReaches("accessAllowed", 1); user.getEventManager().waitUntilEventReaches("streamCreated", 3); user.getEventManager().waitUntilEventReaches("streamPlaying", 3); user.getWaiter().until(ExpectedConditions.numberOfElementsToBe(By.tagName("video"), 3)); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); // Moderator forces unpublish user.getDriver().findElement(By.cssSelector("#openvidu-instance-2 .force-unpub-btn")).click(); user.getEventManager().waitUntilEventReaches("streamDestroyed", 3); user.getWaiter().until(ExpectedConditions.numberOfElementsToBe(By.tagName("video"), 1)); // Publisher publishes again user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .pub-btn")).click(); user.getEventManager().waitUntilEventReaches("streamCreated", 6); user.getEventManager().waitUntilEventReaches("streamPlaying", 6); user.getWaiter().until(ExpectedConditions.numberOfElementsToBe(By.tagName("video"), 3)); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); // Moderator forces disconnect of publisher user.getDriver().findElement(By.cssSelector("#openvidu-instance-2 .force-disconnect-btn")).click(); user.getEventManager().waitUntilEventReaches("streamDestroyed", 6); user.getEventManager().waitUntilEventReaches("connectionDestroyed", 2); user.getEventManager().waitUntilEventReaches("sessionDisconnected", 1); user.getWaiter().until(ExpectedConditions.numberOfElementsToBe(By.tagName("video"), 0)); gracefullyLeaveParticipants(3); } @Test @DisplayName("Stream property changed event") void streamPropertyChangedEventTest() throws Exception { Queue<Boolean> threadAssertions = new ConcurrentLinkedQueue<Boolean>(); setupBrowser("chromeAlternateScreenShare"); log.info("Stream property changed event"); WebElement oneToManyInput = user.getDriver().findElement(By.id("one2many-input")); oneToManyInput.clear(); oneToManyInput.sendKeys("1"); user.getDriver().findElement(By.id("one2many-btn")).click(); user.getDriver().findElement(By.className("screen-radio")).click(); List<WebElement> joinButtons = user.getDriver().findElements(By.className("join-btn")); for (WebElement el : joinButtons) { el.sendKeys(Keys.ENTER); } user.getEventManager().waitUntilEventReaches("connectionCreated", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 1); user.getEventManager().waitUntilEventReaches("streamCreated", 2); user.getEventManager().waitUntilEventReaches("streamPlaying", 2); // Unpublish video final CountDownLatch latch1 = new CountDownLatch(2); user.getEventManager().on("streamPropertyChanged", (event) -> { threadAssertions.add(((String) event.get("eventContent")).contains("videoActive [false]")); latch1.countDown(); }); user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .pub-video-btn")).click(); user.getEventManager().waitUntilEventReaches("streamPropertyChanged", 2); if (!latch1.await(5000, TimeUnit.MILLISECONDS)) { gracefullyLeaveParticipants(2); fail(); return; } user.getEventManager().off("streamPropertyChanged"); for (Iterator<Boolean> iter = threadAssertions.iterator(); iter.hasNext();) { Assert.assertTrue(iter.next()); iter.remove(); } // Unpublish audio final CountDownLatch latch2 = new CountDownLatch(2); user.getEventManager().on("streamPropertyChanged", (event) -> { threadAssertions.add(((String) event.get("eventContent")).contains("audioActive [false]")); latch2.countDown(); }); user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .pub-audio-btn")).click(); user.getEventManager().waitUntilEventReaches("streamPropertyChanged", 4); if (!latch2.await(5000, TimeUnit.MILLISECONDS)) { gracefullyLeaveParticipants(2); fail(); return; } user.getEventManager().off("streamPropertyChanged"); for (Iterator<Boolean> iter = threadAssertions.iterator(); iter.hasNext();) { Assert.assertTrue(iter.next()); iter.remove(); } // Resize captured window final CountDownLatch latch3 = new CountDownLatch(2); int newWidth = 1500; int newHeight = 500; final long[] expectedWidthHeight = new long[2]; user.getEventManager().on("streamPropertyChanged", (event) -> { threadAssertions.add(((String) event.get("eventContent")).contains("videoDimensions [{\"width\":" + expectedWidthHeight[0] + ",\"height\":" + expectedWidthHeight[1] + "}]")); latch3.countDown(); }); user.getDriver().manage().window().setSize(new Dimension(newWidth, newHeight)); String widthAndHeight = user.getEventManager().getDimensionOfViewport(); JSONObject obj = (JSONObject) new JSONParser().parse(widthAndHeight); expectedWidthHeight[0] = (long) obj.get("width"); expectedWidthHeight[1] = (long) obj.get("height") - 1; System.out.println("New viewport dimension: " + obj.toJSONString()); user.getEventManager().waitUntilEventReaches("streamPropertyChanged", 6); if (!latch3.await(5000, TimeUnit.MILLISECONDS)) { gracefullyLeaveParticipants(2); fail(); return; } user.getEventManager().off("streamPropertyChanged"); for (Iterator<Boolean> iter = threadAssertions.iterator(); iter.hasNext();) { Assert.assertTrue(iter.next()); iter.remove(); } gracefullyLeaveParticipants(2); } @Test @DisplayName("Local record") void localRecordTest() throws Exception { setupBrowser("chrome"); log.info("Local record"); user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.className("join-btn")).click(); user.getEventManager().waitUntilEventReaches("connectionCreated", 1); user.getEventManager().waitUntilEventReaches("accessAllowed", 1); user.getEventManager().waitUntilEventReaches("streamCreated", 1); user.getEventManager().waitUntilEventReaches("streamPlaying", 1); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); WebElement recordBtn = user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .publisher-rec-btn")); recordBtn.click(); Thread.sleep(2000); WebElement pauseRecordBtn = user.getDriver() .findElement(By.cssSelector("#openvidu-instance-0 .publisher-rec-pause-btn")); pauseRecordBtn.click(); Thread.sleep(2000); pauseRecordBtn.click(); Thread.sleep(2000); recordBtn.click(); user.getWaiter().until(ExpectedConditions.elementToBeClickable(By.cssSelector("#recorder-preview video"))); user.getWaiter().until( waitForVideoDuration(user.getDriver().findElement(By.cssSelector("#recorder-preview video")), 4)); user.getDriver().findElement(By.id("close-record-btn")).click(); user.getWaiter().until(ExpectedConditions.numberOfElementsToBe(By.cssSelector("#recorder-preview video"), 0)); gracefullyLeaveParticipants(1); } @Test @DisplayName("Remote composed record") void remoteComposedRecordTest() throws Exception { isRecordingTest = true; setupBrowser("chrome"); log.info("Remote composed record"); final String sessionName = "COMPOSED_RECORDED_SESSION"; final String resolution = "1280x720"; user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.id("session-name-input-0")).clear(); user.getDriver().findElement(By.id("session-name-input-0")).sendKeys(sessionName); // API REST test user.getDriver().findElement(By.id("session-api-btn-0")).click(); Thread.sleep(1000); // Try to record a non-existing session user.getDriver().findElement(By.id("start-recording-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Error [404]")); listEmptyRecordings(); // Try to stop a non-existing recording user.getDriver().findElement(By.id("recording-id-field")).sendKeys("FAIL"); user.getDriver().findElement(By.id("stop-recording-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Error [404]")); listEmptyRecordings(); // Try to get a non-existing recording user.getDriver().findElement(By.id("get-recording-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Error [404]")); listEmptyRecordings(); // Try to delete a non-existing recording user.getDriver().findElement(By.id("get-recording-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Error [404]")); user.getDriver().findElement(By.id("close-dialog-btn")).click(); Thread.sleep(1000); // Join the user to the session user.getDriver().findElement(By.className("join-btn")).click(); user.getEventManager().waitUntilEventReaches("connectionCreated", 1); user.getEventManager().waitUntilEventReaches("accessAllowed", 1); user.getEventManager().waitUntilEventReaches("streamCreated", 1); user.getEventManager().waitUntilEventReaches("streamPlaying", 1); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); user.getDriver().findElement(By.id("session-api-btn-0")).click(); Thread.sleep(1000); user.getDriver().findElement(By.id("rec-properties-btn")).click(); Thread.sleep(500); WebElement resolutionField = user.getDriver().findElement(By.id("recording-resolution-field")); resolutionField.clear(); resolutionField.sendKeys(resolution); user.getDriver().findElement(By.id("start-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording started [" + sessionName + "]")); user.getEventManager().waitUntilEventReaches("recordingStarted", 1); Thread.sleep(5000); user.getDriver().findElement(By.id("recording-id-field")).clear(); user.getDriver().findElement(By.id("recording-id-field")).sendKeys(sessionName); // Try to start an ongoing recording user.getDriver().findElement(By.id("start-recording-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Error [409]")); // Try to get an existing recording user.getDriver().findElement(By.id("get-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording got [" + sessionName + "]")); // Try to delete an ongoing recording user.getDriver().findElement(By.id("delete-recording-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Error [409]")); // List existing recordings (one) user.getDriver().findElement(By.id("list-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording list [" + sessionName + "]")); // Stop ongoing recording user.getDriver().findElement(By.id("stop-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording stopped [" + sessionName + "]")); user.getEventManager().waitUntilEventReaches("recordingStopped", 1); String recordingsPath = "/opt/openvidu/recordings/"; File file1 = new File(recordingsPath + sessionName + "/" + sessionName + ".mp4"); File file2 = new File(recordingsPath + sessionName + "/" + ".recording." + sessionName); File file3 = new File(recordingsPath + sessionName + "/" + sessionName + ".jpg"); Assert.assertTrue(file1.exists() && file1.length() > 0); Assert.assertTrue(file2.exists() && file2.length() > 0); Assert.assertTrue(file3.exists() && file3.length() > 0); Assert.assertTrue( this.recordedFileFine(file1, new OpenVidu(OPENVIDU_URL, OPENVIDU_SECRET).getRecording(sessionName))); Assert.assertTrue(this.thumbnailIsFine(file3)); // Try to get the stopped recording user.getDriver().findElement(By.id("get-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording got [" + sessionName + "]")); // Try to list the stopped recording user.getDriver().findElement(By.id("list-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording list [" + sessionName + "]")); // Delete the recording user.getDriver().findElement(By.id("delete-recording-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording deleted")); Assert.assertFalse(file1.exists()); Assert.assertFalse(file2.exists()); Assert.assertFalse(file3.exists()); user.getDriver().findElement(By.id("close-dialog-btn")).click(); Thread.sleep(500); gracefullyLeaveParticipants(1); } @Test @DisplayName("Remote individual record") void remoteIndividualRecordTest() throws Exception { isRecordingTest = true; setupBrowser("chrome"); log.info("Remote individual record"); final String sessionName = "TestSession"; final String recordingName = "CUSTOM_NAME"; user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.id("session-name-input-0")).clear(); user.getDriver().findElement(By.id("session-name-input-0")).sendKeys(sessionName); user.getDriver().findElement(By.id("auto-join-checkbox")).click(); user.getDriver().findElement(By.id("one2one-btn")).click(); user.getEventManager().waitUntilEventReaches("connectionCreated", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 2); user.getEventManager().waitUntilEventReaches("streamCreated", 4); user.getEventManager().waitUntilEventReaches("streamPlaying", 4); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); user.getDriver().findElement(By.id("session-api-btn-0")).click(); Thread.sleep(1000); user.getDriver().findElement(By.id("rec-properties-btn")).click(); Thread.sleep(500); // Set recording name user.getDriver().findElement(By.id("recording-name-field")).sendKeys(recordingName); // Set OutputMode to INDIVIDUAL user.getDriver().findElement(By.id("rec-outputmode-select")).click(); Thread.sleep(500); user.getDriver().findElement(By.id("option-INDIVIDUAL")).click(); Thread.sleep(500); user.getDriver().findElement(By.id("start-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording started [" + sessionName + "]")); user.getEventManager().waitUntilEventReaches("recordingStarted", 2); Thread.sleep(5000); user.getDriver().findElement(By.id("recording-id-field")).clear(); user.getDriver().findElement(By.id("recording-id-field")).sendKeys(sessionName); // Try to start an ongoing recording user.getDriver().findElement(By.id("start-recording-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Error [409]")); // Try to get an existing recording user.getDriver().findElement(By.id("get-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording got [" + sessionName + "]")); // Try to delete an ongoing recording user.getDriver().findElement(By.id("delete-recording-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Error [409]")); // List existing recordings (one) user.getDriver().findElement(By.id("list-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording list [" + sessionName + "]")); // Stop ongoing recording user.getDriver().findElement(By.id("stop-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording stopped [" + sessionName + "]")); user.getEventManager().waitUntilEventReaches("recordingStopped", 2); String recordingsPath = "/opt/openvidu/recordings/"; String recPath = recordingsPath + sessionName + "/"; Recording recording = new OpenVidu(OPENVIDU_URL, OPENVIDU_SECRET).getRecording(sessionName); this.checkIndividualRecording(recPath, recording, "opus", "vp8"); // Try to get the stopped recording user.getDriver().findElement(By.id("get-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording got [" + sessionName + "]")); // Try to list the stopped recording user.getDriver().findElement(By.id("list-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording list [" + sessionName + "]")); // Delete the recording user.getDriver().findElement(By.id("delete-recording-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording deleted")); Assert.assertFalse(new File(recPath).exists()); user.getDriver().findElement(By.id("close-dialog-btn")).click(); Thread.sleep(500); gracefullyLeaveParticipants(2); } @Test @DisplayName("Remote record cross-browser audio-only and video-only") void remoteRecordAudioOnlyVideoOnlyTest() throws Exception { isRecordingTest = true; setupBrowser("chromeAlternateScreenShare"); log.info("Remote record cross-browser audio-only and video-only"); final String SESSION_NAME = "TestSession"; final String RECORDING_COMPOSED_VIDEO = "COMPOSED_VIDEO_ONLY"; final String RECORDING_COMPOSED_AUDIO = "COMPOSED_AUDIO_ONLY"; final String RECORDING_INDIVIDUAL_VIDEO = "INDIVIDUAL_VIDEO_ONLY"; final String RECORDING_INDIVIDUAL_AUDIO = "INDIVIDUAL_AUDIO_ONLY"; final int RECORDING_DURATION = 5000; Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread th, Throwable ex) { System.out.println("Uncaught exception: " + ex); synchronized (lock) { OpenViduTestAppE2eTest.ex = new Exception(ex); } } }; Thread t = new Thread(() -> { BrowserUser user2 = new FirefoxUser("FirefoxUser", 30); user2.getDriver().get(APP_URL); WebElement urlInput = user2.getDriver().findElement(By.id("openvidu-url")); urlInput.clear(); urlInput.sendKeys(OPENVIDU_URL); WebElement secretInput = user2.getDriver().findElement(By.id("openvidu-secret")); secretInput.clear(); secretInput.sendKeys(OPENVIDU_SECRET); user2.getEventManager().startPolling(); // Firefox user audio + video user2.getDriver().findElement(By.id("add-user-btn")).click(); // Firefox user video-only user2.getDriver().findElement(By.id("add-user-btn")).click(); user2.getDriver().findElement(By.cssSelector("#openvidu-instance-1 .send-audio-checkbox")).click(); // Join Firefox users user2.getDriver().findElements(By.className("join-btn")).forEach(el -> el.sendKeys(Keys.ENTER)); try { user2.getEventManager().waitUntilEventReaches("connectionCreated", 4); user2.getEventManager().waitUntilEventReaches("accessAllowed", 2); user2.getEventManager().waitUntilEventReaches("streamCreated", 8); user2.getEventManager().waitUntilEventReaches("streamPlaying", 8); Assert.assertEquals(user2.getDriver().findElements(By.tagName("video")).size(), 8); user2.getEventManager().waitUntilEventReaches("recordingStarted", 2); user2.getEventManager().waitUntilEventReaches("recordingStopped", 2); user2.getEventManager().waitUntilEventReaches("recordingStarted", 4); user2.getEventManager().waitUntilEventReaches("recordingStopped", 4); user2.getEventManager().waitUntilEventReaches("recordingStarted", 6); user2.getEventManager().waitUntilEventReaches("recordingStopped", 6); user2.getEventManager().waitUntilEventReaches("recordingStarted", 8); user2.getEventManager().waitUntilEventReaches("recordingStopped", 8); user2.getEventManager().waitUntilEventReaches("streamDestroyed", 4); user2.getEventManager().waitUntilEventReaches("connectionDestroyed", 4); user2.getDriver().findElement(By.id("remove-user-btn")).click(); user2.getDriver().findElement(By.id("remove-user-btn")).click(); user2.getEventManager().waitUntilEventReaches("sessionDisconnected", 2); } catch (Exception e) { e.printStackTrace(); user2.dispose(); Thread.currentThread().interrupt(); } user2.dispose(); }); t.setUncaughtExceptionHandler(h); t.start(); // Chrome user screen share only-video user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .screen-radio")).click(); user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .send-audio-checkbox")).click(); // Chrome user audio-only user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.cssSelector("#openvidu-instance-1 .send-video-checkbox")).click(); // Join Chrome users user.getDriver().findElements(By.className("join-btn")).forEach(el -> el.sendKeys(Keys.ENTER)); user.getEventManager().waitUntilEventReaches("connectionCreated", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 2); user.getEventManager().waitUntilEventReaches("streamCreated", 8); user.getEventManager().waitUntilEventReaches("streamPlaying", 8); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 8); user.getDriver().findElement(By.id("session-api-btn-0")).click(); Thread.sleep(1000); user.getDriver().findElement(By.id("rec-properties-btn")).click(); Thread.sleep(500); WebElement recordingNameField = user.getDriver().findElement(By.id("recording-name-field")); // Video-only COMPOSED recording recordingNameField.clear(); recordingNameField.sendKeys(RECORDING_COMPOSED_VIDEO); user.getDriver().findElement(By.id("rec-hasaudio-checkbox")).click(); Thread.sleep(500); user.getDriver().findElement(By.id("start-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording started [" + SESSION_NAME + "]")); user.getEventManager().waitUntilEventReaches("recordingStarted", 2); Thread.sleep(RECORDING_DURATION); user.getDriver().findElement(By.id("recording-id-field")).clear(); user.getDriver().findElement(By.id("recording-id-field")).sendKeys(SESSION_NAME); user.getDriver().findElement(By.id("stop-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording stopped [" + SESSION_NAME + "]")); user.getEventManager().waitUntilEventReaches("recordingStopped", 2); // Audio-only COMPOSED recording recordingNameField.clear(); recordingNameField.sendKeys(RECORDING_COMPOSED_AUDIO); user.getDriver().findElement(By.id("rec-hasaudio-checkbox")).click(); user.getDriver().findElement(By.id("rec-hasvideo-checkbox")).click(); Thread.sleep(500); user.getDriver().findElement(By.id("start-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording started [" + SESSION_NAME + "-1]")); user.getEventManager().waitUntilEventReaches("recordingStarted", 4); Thread.sleep(RECORDING_DURATION); user.getDriver().findElement(By.id("recording-id-field")).clear(); user.getDriver().findElement(By.id("recording-id-field")).sendKeys(SESSION_NAME + "-1"); user.getDriver().findElement(By.id("stop-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording stopped [" + SESSION_NAME + "-1]")); user.getEventManager().waitUntilEventReaches("recordingStopped", 4); // Video-only INDIVIDUAL recording recordingNameField.clear(); recordingNameField.sendKeys(RECORDING_INDIVIDUAL_VIDEO); user.getDriver().findElement(By.id("rec-hasaudio-checkbox")).click(); user.getDriver().findElement(By.id("rec-hasvideo-checkbox")).click(); Thread.sleep(500); user.getDriver().findElement(By.id("rec-outputmode-select")).click(); Thread.sleep(500); user.getDriver().findElement(By.id("option-INDIVIDUAL")).click(); Thread.sleep(500); user.getDriver().findElement(By.id("start-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording started [" + SESSION_NAME + "-2]")); user.getEventManager().waitUntilEventReaches("recordingStarted", 6); Thread.sleep(RECORDING_DURATION); user.getDriver().findElement(By.id("recording-id-field")).clear(); user.getDriver().findElement(By.id("recording-id-field")).sendKeys(SESSION_NAME + "-2"); user.getDriver().findElement(By.id("stop-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording stopped [" + SESSION_NAME + "-2]")); user.getEventManager().waitUntilEventReaches("recordingStopped", 6); // Audio-only INDIVIDUAL recording recordingNameField.clear(); recordingNameField.sendKeys(RECORDING_INDIVIDUAL_AUDIO); user.getDriver().findElement(By.id("rec-hasaudio-checkbox")).click(); user.getDriver().findElement(By.id("rec-hasvideo-checkbox")).click(); Thread.sleep(500); user.getDriver().findElement(By.id("start-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording started [" + SESSION_NAME + "-3]")); user.getEventManager().waitUntilEventReaches("recordingStarted", 8); Thread.sleep(RECORDING_DURATION); user.getDriver().findElement(By.id("recording-id-field")).clear(); user.getDriver().findElement(By.id("recording-id-field")).sendKeys(SESSION_NAME + "-3"); user.getDriver().findElement(By.id("stop-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording stopped [" + SESSION_NAME + "-3]")); user.getEventManager().waitUntilEventReaches("recordingStopped", 8); String recordingsPath = "/opt/openvidu/recordings/"; // Check video-only COMPOSED recording String recPath = recordingsPath + SESSION_NAME + "/"; Recording recording = new OpenVidu(OPENVIDU_URL, OPENVIDU_SECRET).getRecording(SESSION_NAME); this.checkMultimediaFile(new File(recPath + recording.getName() + ".mp4"), false, true, recording.getDuration(), recording.getResolution(), null, "h264"); // Check audio-only COMPOSED recording recPath = recordingsPath + SESSION_NAME + "-1/"; recording = new OpenVidu(OPENVIDU_URL, OPENVIDU_SECRET).getRecording(SESSION_NAME + "-1"); this.checkMultimediaFile(new File(recPath + recording.getName() + ".webm"), true, false, recording.getDuration(), null, "opus", null); // Check video-only INDIVIDUAL recording recPath = recordingsPath + SESSION_NAME + "-2/"; recording = new OpenVidu(OPENVIDU_URL, OPENVIDU_SECRET).getRecording(SESSION_NAME + "-2"); this.checkIndividualRecording(recPath, recording, "opus", "vp8"); // Check audio-only INDIVIDUAL recording recPath = recordingsPath + SESSION_NAME + "-3/"; recording = new OpenVidu(OPENVIDU_URL, OPENVIDU_SECRET).getRecording(SESSION_NAME + "-3"); this.checkIndividualRecording(recPath, recording, "opus", "vp8"); user.getDriver().findElement(By.id("close-dialog-btn")).click(); Thread.sleep(500); gracefullyLeaveParticipants(2); t.join(); synchronized (lock) { if (OpenViduTestAppE2eTest.ex != null) { throw OpenViduTestAppE2eTest.ex; } } } @Test @DisplayName("REST API: Fetch all, fetch one, force disconnect, force unpublish, close session") void restApiFetchForce() throws Exception { setupBrowser("chrome"); log.info("REST API: Fetch all, fetch one, force disconnect, force unpublish, close session"); user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.id("add-user-btn")).click(); // API REST test user.getDriver().findElement(By.id("session-api-btn-0")).click(); Thread.sleep(1000); // Close session (undefined) user.getDriver().findElement(By.id("close-session-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Error [Session undefined]")); // Fetch one (undefined) user.getDriver().findElement(By.id("get-session-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Error [Session undefined]")); // Fetch all (no active sessions) user.getDriver().findElement(By.id("list-sessions-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeContains(By.id("api-response-text-area"), "value", "Number: 0. Changes: false")); user.getDriver().findElement(By.id("close-dialog-btn")).click(); Thread.sleep(1000); user.getDriver().findElement(By.id("auto-join-checkbox")).click(); user.getDriver().findElement(By.id("one2one-btn")).click(); user.getEventManager().waitUntilEventReaches("connectionCreated", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 2); user.getEventManager().waitUntilEventReaches("streamCreated", 4); user.getEventManager().waitUntilEventReaches("streamPlaying", 4); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); // Fetch existing session (change) user.getDriver().findElement(By.id("session-api-btn-0")).click(); Thread.sleep(1000); user.getDriver().findElement(By.id("get-session-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeContains(By.id("api-response-text-area"), "value", "Changes: true")); // Store connectionId and streamId String response = user.getDriver().findElement(By.id("api-response-text-area")).getAttribute("value"); JSONObject json = (JSONObject) ((JSONArray) new JSONParser().parse(response.split("%")[1])).get(0); String connectionId = (String) json.keySet().iterator().next(); String streamId = (String) ((JSONObject) ((JSONArray) json.get(connectionId)).get(0)).get("streamId"); // Fetch all sessions (no change) user.getDriver().findElement(By.id("list-sessions-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeContains(By.id("api-response-text-area"), "value", "Number: 1. Changes: false")); // Force unpublish wrong user.getDriver().findElement(By.id("resource-id-field")).clear(); user.getDriver().findElement(By.id("resource-id-field")).sendKeys("FAIL"); user.getDriver().findElement(By.id("force-unpublish-api-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Error [404]")); // Force unpublish right user.getDriver().findElement(By.id("resource-id-field")).clear(); user.getDriver().findElement(By.id("resource-id-field")).sendKeys(streamId); user.getDriver().findElement(By.id("force-unpublish-api-btn")).click(); user.getWaiter().until( ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Stream unpublished")); user.getEventManager().waitUntilEventReaches("streamDestroyed", 2); // Force disconnect wrong user.getDriver().findElement(By.id("resource-id-field")).clear(); user.getDriver().findElement(By.id("resource-id-field")).sendKeys("FAIL"); user.getDriver().findElement(By.id("force-disconnect-api-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Error [404]")); // Force disconnect right user.getDriver().findElement(By.id("resource-id-field")).clear(); user.getDriver().findElement(By.id("resource-id-field")).sendKeys(connectionId); user.getDriver().findElement(By.id("force-disconnect-api-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "User disconnected")); user.getEventManager().waitUntilEventReaches("connectionDestroyed", 1); // Close session user.getDriver().findElement(By.id("close-session-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Session closed")); user.getWaiter().until(ExpectedConditions.numberOfElementsToBe(By.tagName("video"), 0)); user.getDriver().findElement(By.id("close-dialog-btn")).click(); Thread.sleep(500); gracefullyLeaveParticipants(1); } @Test @DisplayName("Video filter test") void videoFilterTest() throws Exception { setupBrowser("chrome"); log.info("Video filter test"); // Configure publisher user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElements(By.cssSelector("#openvidu-instance-0 .subscribe-checkbox")).get(0).click(); user.getDriver().findElements(By.cssSelector("#openvidu-instance-0 .send-audio-checkbox")).get(0).click(); user.getDriver().findElement(By.id("session-settings-btn-0")).click(); Thread.sleep(1000); user.getDriver().findElement(By.id("add-allowed-filter-btn")).click(); user.getDriver().findElement(By.id("save-btn")).click(); Thread.sleep(1000); // Configure subscriber user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.cssSelector("#openvidu-instance-1 .publish-checkbox")).click(); user.getDriver().findElements(By.className("join-btn")).forEach(el -> el.sendKeys(Keys.ENTER)); user.getEventManager().waitUntilEventReaches("connectionCreated", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 1); user.getEventManager().waitUntilEventReaches("streamCreated", 2); user.getEventManager().waitUntilEventReaches("streamPlaying", 2); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 2); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), false, true)); WebElement subscriberVideo = user.getDriver().findElement(By.cssSelector("#openvidu-instance-1 video")); // Analyze Chrome fake video stream without gray filter (GREEN color) Map<String, Long> rgb = user.getEventManager().getAverageRgbFromVideo(subscriberVideo); System.out.println(rgb.toString()); Assert.assertTrue(checkVideoAverageRgbGreen(rgb)); // Try to apply none allowed filter user.getDriver().findElement(By.cssSelector(".filter-btn")).click(); WebElement filterTypeInput = user.getDriver().findElement(By.id("filter-type-field")); filterTypeInput.clear(); filterTypeInput.sendKeys("NotAllowedFilter"); user.getDriver().findElement(By.id("apply-filter-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeContains(By.id("filter-response-text-area"), "value", "Error [You don't have permissions to apply a filter]")); // Try to execute method over not applied filter user.getDriver().findElement(By.id("exec-filter-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeContains(By.id("filter-response-text-area"), "value", "has no filter applied in session")); // Apply allowed video filter filterTypeInput.clear(); filterTypeInput.sendKeys("GStreamerFilter"); WebElement filterOptionsInput = user.getDriver().findElement(By.id("filter-options-field")); filterOptionsInput.clear(); filterOptionsInput.sendKeys("{\"command\": \"videobalance saturation=0.0\"}"); user.getDriver().findElement(By.id("apply-filter-btn")).click(); user.getWaiter().until( ExpectedConditions.attributeContains(By.id("filter-response-text-area"), "value", "Filter applied")); // Try to apply another filter user.getDriver().findElement(By.id("apply-filter-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeContains(By.id("filter-response-text-area"), "value", "already has a filter applied in session")); // Analyze Chrome fake video stream with gray filter (GRAY color) user.getEventManager().waitUntilEventReaches("streamPropertyChanged", 2); Thread.sleep(500); rgb = user.getEventManager().getAverageRgbFromVideo(subscriberVideo); System.out.println(rgb.toString()); Assert.assertTrue(checkVideoAverageRgbGray(rgb)); // Execute filter method WebElement filterMethodInput = user.getDriver().findElement(By.id("filter-method-field")); filterMethodInput.clear(); filterMethodInput.sendKeys("setElementProperty"); WebElement filterParamsInput = user.getDriver().findElement(By.id("filter-params-field")); filterParamsInput.clear(); filterParamsInput.sendKeys("{\"propertyName\":\"saturation\",\"propertyValue\":\"1.0\"}"); user.getDriver().findElement(By.id("exec-filter-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeContains(By.id("filter-response-text-area"), "value", "Filter method executed")); // Analyze Chrome fake video stream without gray filter (GREEN color) user.getEventManager().waitUntilEventReaches("streamPropertyChanged", 4); Thread.sleep(500); rgb = user.getEventManager().getAverageRgbFromVideo(subscriberVideo); System.out.println(rgb.toString()); Assert.assertTrue(checkVideoAverageRgbGreen(rgb)); user.getDriver().findElement(By.id("close-dialog-btn")).click(); Thread.sleep(500); // Publisher leaves and connects with active filter user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .leave-btn")).click(); user.getEventManager().waitUntilEventReaches("streamDestroyed", 2); user.getEventManager().waitUntilEventReaches("connectionDestroyed", 1); user.getEventManager().waitUntilEventReaches("sessionDisconnected", 1); user.getDriver().findElement(By.id("publisher-settings-btn-0")).click(); Thread.sleep(500); user.getDriver().findElement(By.id("save-btn")).click(); Thread.sleep(500); user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .join-btn")).click(); user.getEventManager().waitUntilEventReaches("connectionCreated", 7); user.getEventManager().waitUntilEventReaches("accessAllowed", 2); user.getEventManager().waitUntilEventReaches("streamCreated", 4); user.getEventManager().waitUntilEventReaches("streamPlaying", 4); // Analyze Chrome fake video stream with gray filter (GRAY color) subscriberVideo = user.getDriver().findElement(By.cssSelector("#openvidu-instance-1 video")); rgb = user.getEventManager().getAverageRgbFromVideo(subscriberVideo); System.out.println(rgb.toString()); Assert.assertTrue(checkVideoAverageRgbGray(rgb)); // Remove filter user.getDriver().findElement(By.cssSelector(".filter-btn")).click(); Thread.sleep(500); user.getDriver().findElement(By.id("remove-filter-btn")).click(); user.getWaiter().until( ExpectedConditions.attributeContains(By.id("filter-response-text-area"), "value", "Filter removed")); user.getEventManager().waitUntilEventReaches("streamPropertyChanged", 6); Thread.sleep(1000); // Analyze Chrome fake video stream with gray filter (GREEN color) rgb = user.getEventManager().getAverageRgbFromVideo(subscriberVideo); System.out.println(rgb.toString()); Assert.assertTrue(checkVideoAverageRgbGreen(rgb)); user.getDriver().findElement(By.id("close-dialog-btn")).click(); Thread.sleep(500); gracefullyLeaveParticipants(2); } @Test @DisplayName("Video filter events test") void videoFilterEventsTest() throws Exception { setupChromeWithFakeVideo(Paths.get("/opt/openvidu/barcode.y4m")); log.info("Video filter events test"); // Configure publisher user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElements(By.cssSelector("#openvidu-instance-0 .subscribe-checkbox")).get(0).click(); user.getDriver().findElements(By.cssSelector("#openvidu-instance-0 .send-audio-checkbox")).get(0).click(); user.getDriver().findElement(By.id("session-settings-btn-0")).click(); Thread.sleep(1000); WebElement allowedFilterInput = user.getDriver().findElement(By.id("allowed-filter-input")); allowedFilterInput.clear(); allowedFilterInput.sendKeys("ZBarFilter"); user.getDriver().findElement(By.id("add-allowed-filter-btn")).click(); user.getDriver().findElement(By.id("save-btn")).click(); Thread.sleep(1000); // Configure moderator (only subscribe) user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.cssSelector("#openvidu-instance-1 .publish-checkbox")).click(); user.getDriver().findElement(By.id("session-settings-btn-1")).click(); Thread.sleep(1000); user.getDriver().findElement(By.id("radio-btn-mod")).click(); user.getDriver().findElement(By.id("save-btn")).click(); Thread.sleep(1000); user.getDriver().findElements(By.className("join-btn")).forEach(el -> el.sendKeys(Keys.ENTER)); user.getEventManager().waitUntilEventReaches("connectionCreated", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 1); user.getEventManager().waitUntilEventReaches("streamCreated", 2); user.getEventManager().waitUntilEventReaches("streamPlaying", 2); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 2); // Assert no audio track only for the moderator incoming video Assert.assertTrue(user.getEventManager().assertMediaTracks( user.getDriver().findElements(By.cssSelector("#openvidu-instance-1 video")), false, true)); // Publisher applies ZBarCode filter to itself user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .filter-btn")).click(); Thread.sleep(500); WebElement input = user.getDriver().findElement(By.id("filter-type-field")); input.clear(); input.sendKeys("ZBarFilter"); input = user.getDriver().findElement(By.id("filter-options-field")); input.clear(); input.sendKeys("{}"); user.getDriver().findElement(By.id("apply-filter-btn")).click(); user.getWaiter().until( ExpectedConditions.attributeContains(By.id("filter-response-text-area"), "value", "Filter applied")); user.getEventManager().waitUntilEventReaches("streamPropertyChanged", 2); // Publisher subscribes to CodeFound event for his own stream input = user.getDriver().findElement(By.id("filter-event-type-field")); input.clear(); input.sendKeys("CodeFound"); user.getDriver().findElement(By.id("sub-filter-event-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeContains(By.id("filter-response-text-area"), "value", "Filter event listener added")); user.getEventManager().waitUntilEventReaches("filterEvent", 2); // Publisher unsubscribes from "CodeFound" filter event user.getDriver().findElement(By.id("unsub-filter-event-btn")).click(); try { // If this active wait finishes successfully, then the removal of the event // listener has not worked fine user.getEventManager().waitUntilEventReaches("filterEvent", 3, 3, false); Assert.fail("'filterEvent' was received. Filter.removeEventListener() failed"); } catch (Exception e) { System.out.println("Filter event removal worked fine"); } user.getDriver().findElement(By.id("close-dialog-btn")).click(); Thread.sleep(500); // Moderator subscribes to CodeFound event for the Publisher's stream user.getDriver().findElement(By.cssSelector("#openvidu-instance-1 .filter-btn")).click(); Thread.sleep(500); input = user.getDriver().findElement(By.id("filter-event-type-field")); input.clear(); input.sendKeys("CodeFound"); user.getDriver().findElement(By.id("sub-filter-event-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeContains(By.id("filter-response-text-area"), "value", "Filter event listener added")); user.getEventManager().waitUntilEventReaches("filterEvent", 4); // Moderator removes the Publisher's filter user.getDriver().findElement(By.id("remove-filter-btn")).click(); user.getWaiter().until( ExpectedConditions.attributeContains(By.id("filter-response-text-area"), "value", "Filter removed")); user.getEventManager().waitUntilEventReaches("streamPropertyChanged", 4); try { // If this active wait finishes successfully, then the removal of the filter has // not worked fine user.getEventManager().waitUntilEventReaches("filterEvent", 5, 3, false); Assert.fail("'filterEvent' was received. Stream.removeFilter() failed"); } catch (Exception e) { System.out.println("Filter removal worked fine"); } gracefullyLeaveParticipants(2); } private void listEmptyRecordings() { // List existing recordings (empty) user.getDriver().findElement(By.id("list-recording-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording list []")); } private ExpectedCondition<Boolean> waitForVideoDuration(WebElement element, int durationInSeconds) { return new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver input) { return element.getAttribute("duration").matches( durationInSeconds - 1 + "\\.[8-9][0-9]{0,5}|" + durationInSeconds + "\\.[0-2][0-9]{0,5}"); } }; } private boolean checkVideoAverageRgbGreen(Map<String, Long> rgb) { // GREEN color: {r < 15, g > 130, b <15} return (rgb.get("r") < 15) && (rgb.get("g") > 130) && (rgb.get("b") < 15); } private boolean checkVideoAverageRgbGray(Map<String, Long> rgb) { // GRAY color: {r < 50, g < 50, b < 50} and the absolute difference between them // not greater than 2 return (rgb.get("r") < 50) && (rgb.get("g") < 50) && (rgb.get("b") < 50) && (Math.abs(rgb.get("r") - rgb.get("g")) <= 2) && (Math.abs(rgb.get("r") - rgb.get("b")) <= 2) && (Math.abs(rgb.get("b") - rgb.get("g")) <= 2); } private void gracefullyLeaveParticipants(int numberOfParticipants) throws Exception { int accumulatedConnectionDestroyed = 0; for (int j = 1; j <= numberOfParticipants; j++) { user.getDriver().findElement(By.id("remove-user-btn")).sendKeys(Keys.ENTER); user.getEventManager().waitUntilEventReaches("sessionDisconnected", j); accumulatedConnectionDestroyed = (j != numberOfParticipants) ? (accumulatedConnectionDestroyed + numberOfParticipants - j) : (accumulatedConnectionDestroyed); user.getEventManager().waitUntilEventReaches("connectionDestroyed", accumulatedConnectionDestroyed); } } private String getBase64Screenshot(BrowserUser user) throws Exception { String screenshotBase64 = ((TakesScreenshot) user.getDriver()).getScreenshotAs(BASE64); return "data:image/png;base64," + screenshotBase64; } private boolean recordedFileFine(File file, Recording recording) { this.checkMultimediaFile(file, true, true, recording.getDuration(), recording.getResolution(), "aac", "h264"); boolean isFine = false; Picture frame; try { // Get a frame at 75% duration and check that it has the expected color frame = FrameGrab.getFrameAtSec(file, (double) (recording.getDuration() * 0.75)); BufferedImage image = AWTUtil.toBufferedImage(frame); Map<String, Long> colorMap = this.averageColor(image); Assert.assertEquals(image.getWidth() + "x" + image.getHeight(), recording.getResolution()); log.info("Recording map color: {}", colorMap.toString()); isFine = this.checkVideoAverageRgbGreen(colorMap); } catch (IOException | JCodecException e) { log.warn("Error getting frame from video recording: {}", e.getMessage()); isFine = false; } return isFine; } private void checkIndividualRecording(String recPath, Recording recording, String audioDecoder, String videoDecoder) { // Should be only 2 files: zip and metadata File folder = new File(recPath); Assert.assertEquals(folder.listFiles().length, 2); File file1 = new File(recPath + recording.getName() + ".zip"); File file2 = new File(recPath + ".recording." + recording.getId()); Assert.assertTrue(file1.exists() && file1.length() > 0); Assert.assertTrue(file2.exists() && file2.length() > 0); List<File> unzippedWebmFiles = new Unzipper().unzipFile(recPath, recording.getName() + ".zip"); File jsonSyncFile = new File(recPath + recording.getName() + ".json"); Assert.assertTrue(jsonSyncFile.exists() && jsonSyncFile.length() > 0); JsonObject jsonSyncMetadata; try { Gson gson = new Gson(); JsonReader reader = new JsonReader(new FileReader(jsonSyncFile)); jsonSyncMetadata = gson.fromJson(reader, JsonObject.class); } catch (Exception e) { log.error("Cannot read JSON sync metadata file from {}. Error: {}", jsonSyncFile.getAbsolutePath(), e.getMessage()); Assert.fail(); return; } long totalFileSize = 0; JsonArray syncArray = jsonSyncMetadata.get("files").getAsJsonArray(); for (File webmFile : unzippedWebmFiles) { totalFileSize += webmFile.length(); Assert.assertTrue(webmFile.exists() && webmFile.length() > 0); double durationInSeconds = 0; boolean found = false; for (int i = 0; i < syncArray.size(); i++) { JsonObject j = syncArray.get(i).getAsJsonObject(); if (webmFile.getName().contains(j.get("streamId").getAsString())) { durationInSeconds = (double) (j.get("endTimeOffset").getAsDouble() - j.get("startTimeOffset").getAsDouble()) / 1000; found = true; break; } } Assert.assertTrue(found); log.info("Duration of {} according to sync metadata json file: {} s", webmFile.getName(), durationInSeconds); this.checkMultimediaFile(webmFile, recording.hasAudio(), recording.hasVideo(), durationInSeconds, recording.getResolution(), audioDecoder, videoDecoder); webmFile.delete(); } Assert.assertEquals(recording.getSize(), totalFileSize); jsonSyncFile.delete(); } private void checkMultimediaFile(File file, boolean hasAudio, boolean hasVideo, double duration, String resolution, String audioDecoder, String videoDecoder) { // Check tracks, duration, resolution, framerate and decoders MultimediaFileMetadata metadata = new MultimediaFileMetadata(file.getAbsolutePath()); if (hasVideo) { if (hasAudio) { Assert.assertTrue(metadata.hasAudio() && metadata.hasVideo()); Assert.assertTrue(metadata.getAudioDecoder().toLowerCase().contains(audioDecoder)); } else { Assert.assertTrue(metadata.hasVideo()); Assert.assertFalse(metadata.hasAudio()); } if (resolution != null) { Assert.assertEquals(resolution, metadata.getVideoWidth() + "x" + metadata.getVideoHeight()); } Assert.assertTrue(metadata.getVideoDecoder().toLowerCase().contains(videoDecoder)); } else if (hasAudio) { Assert.assertTrue(metadata.hasAudio()); Assert.assertFalse(metadata.hasVideo()); Assert.assertTrue(metadata.getAudioDecoder().toLowerCase().contains(audioDecoder)); } else { Assert.fail("Cannot check a file witho no audio and no video"); } // Check duration with 1 decimal precision DecimalFormat df = new DecimalFormat("#0.0"); df.setRoundingMode(RoundingMode.UP); log.info("Duration of {} according to ffmpeg: {} s", file.getName(), metadata.getDuration()); log.info("Duration of {} according to 'duration' property: {} s", file.getName(), duration); log.info("Difference in s duration: {}", Math.abs(metadata.getDuration() - duration)); Assert.assertTrue(Math.abs((metadata.getDuration() - duration)) < 0.25); } private boolean thumbnailIsFine(File file) { boolean isFine = false; BufferedImage image = null; try { image = ImageIO.read(file); } catch (IOException e) { log.error(e.getMessage()); return false; } log.info("Recording thumbnail dimensions: {}x{}", image.getWidth(), image.getHeight()); Map<String, Long> colorMap = this.averageColor(image); log.info("Thumbnail map color: {}", colorMap.toString()); isFine = this.checkVideoAverageRgbGreen(colorMap); return isFine; } private Map<String, Long> averageColor(BufferedImage bi) { int x0 = 0; int y0 = 0; int w = bi.getWidth(); int h = bi.getHeight(); int x1 = x0 + w; int y1 = y0 + h; long sumr = 0, sumg = 0, sumb = 0; for (int x = x0; x < x1; x++) { for (int y = y0; y < y1; y++) { Color pixel = new Color(bi.getRGB(x, y)); sumr += pixel.getRed(); sumg += pixel.getGreen(); sumb += pixel.getBlue(); } } int num = w * h; Map<String, Long> colorMap = new HashMap<>(); colorMap.put("r", (long) (sumr / num)); colorMap.put("g", (long) (sumg / num)); colorMap.put("b", (long) (sumb / num)); return colorMap; } }
openvidu-test-e2e/src/test/java/io/openvidu/test/e2e/OpenViduTestAppE2eTest.java
/* * (C) Copyright 2017-2019 OpenVidu (https://openvidu.io/) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.openvidu.test.e2e; import static org.junit.Assert.fail; import static org.openqa.selenium.OutputType.BASE64; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.math.RoundingMode; import java.nio.file.Path; import java.nio.file.Paths; import java.text.DecimalFormat; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.imageio.ImageIO; import org.apache.commons.io.FileUtils; import org.jcodec.api.FrameGrab; import org.jcodec.api.JCodecException; import org.jcodec.common.model.Picture; import org.jcodec.scale.AWTUtil; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.junit.Assert; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.platform.runner.JUnitPlatform; import org.junit.runner.RunWith; import org.openqa.selenium.By; import org.openqa.selenium.Dimension; import org.openqa.selenium.Keys; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.stream.JsonReader; import io.github.bonigarcia.SeleniumExtension; import io.github.bonigarcia.wdm.WebDriverManager; import io.openvidu.java.client.OpenVidu; import io.openvidu.java.client.Recording; import io.openvidu.test.e2e.browser.BrowserUser; import io.openvidu.test.e2e.browser.ChromeAndroidUser; import io.openvidu.test.e2e.browser.ChromeUser; import io.openvidu.test.e2e.browser.FirefoxUser; import io.openvidu.test.e2e.browser.OperaUser; import io.openvidu.test.e2e.utils.CommandLineExecuter; import io.openvidu.test.e2e.utils.MultimediaFileMetadata; import io.openvidu.test.e2e.utils.Unzipper; /** * E2E tests for openvidu-testapp. * * @author Pablo Fuente ([email protected]) * @since 1.1.1 */ @Tag("e2e") @DisplayName("E2E tests for OpenVidu TestApp") @ExtendWith(SeleniumExtension.class) @RunWith(JUnitPlatform.class) public class OpenViduTestAppE2eTest { static String OPENVIDU_SECRET = "MY_SECRET"; static String OPENVIDU_URL = "https://localhost:4443/"; static String APP_URL = "http://localhost:4200/"; static Exception ex = null; private final Object lock = new Object(); private static final Logger log = LoggerFactory.getLogger(OpenViduTestAppE2eTest.class); BrowserUser user; volatile static boolean isRecordingTest; @BeforeAll() static void setupAll() { String ffmpegOutput = new CommandLineExecuter().executeCommand("which ffmpeg"); if (ffmpegOutput == null || ffmpegOutput.isEmpty()) { log.error("ffmpeg package is not installed in the host machine"); Assert.fail(); return; } else { log.info("ffmpeg is installed and accesible"); } WebDriverManager.chromedriver().setup(); WebDriverManager.firefoxdriver().setup(); String appUrl = System.getProperty("APP_URL"); if (appUrl != null) { APP_URL = appUrl; } log.info("Using URL {} to connect to openvidu-testapp", APP_URL); String openviduUrl = System.getProperty("OPENVIDU_URL"); if (openviduUrl != null) { OPENVIDU_URL = openviduUrl; } log.info("Using URL {} to connect to openvidu-server", OPENVIDU_URL); String openvidusecret = System.getProperty("OPENVIDU_SECRET"); if (openvidusecret != null) { OPENVIDU_SECRET = openvidusecret; } log.info("Using secret {} to connect to openvidu-server", OPENVIDU_SECRET); try { log.info("Cleaning folder /opt/openvidu/recordings"); FileUtils.cleanDirectory(new File("/opt/openvidu/recordings")); } catch (IOException e) { log.error(e.getMessage()); } } void setupBrowser(String browser) { switch (browser) { case "chrome": this.user = new ChromeUser("TestUser", 50); break; case "firefox": this.user = new FirefoxUser("TestUser", 50); break; case "opera": this.user = new OperaUser("TestUser", 50); break; case "chromeAndroid": this.user = new ChromeAndroidUser("TestUser", 50); break; case "chromeAlternateScreenShare": this.user = new ChromeUser("TestUser", 50, "OpenVidu TestApp"); break; default: this.user = new ChromeUser("TestUser", 50); } user.getDriver().get(APP_URL); WebElement urlInput = user.getDriver().findElement(By.id("openvidu-url")); urlInput.clear(); urlInput.sendKeys(OPENVIDU_URL); WebElement secretInput = user.getDriver().findElement(By.id("openvidu-secret")); secretInput.clear(); secretInput.sendKeys(OPENVIDU_SECRET); user.getEventManager().startPolling(); } void setupChromeWithFakeVideo(Path videoFileLocation) { this.user = new ChromeUser("TestUser", 50, videoFileLocation); user.getDriver().get(APP_URL); WebElement urlInput = user.getDriver().findElement(By.id("openvidu-url")); urlInput.clear(); urlInput.sendKeys(OPENVIDU_URL); WebElement secretInput = user.getDriver().findElement(By.id("openvidu-secret")); secretInput.clear(); secretInput.sendKeys(OPENVIDU_SECRET); user.getEventManager().startPolling(); } @AfterEach void dispose() { user.dispose(); if (isRecordingTest) { try { FileUtils.cleanDirectory(new File("/opt/openvidu/recordings")); } catch (IOException e) { log.error(e.getMessage()); } isRecordingTest = false; } } @Test @DisplayName("One2One Chrome [Video + Audio]") void oneToOneVideoAudioSessionChrome() throws Exception { setupBrowser("chrome"); log.info("One2One Chrome [Video + Audio]"); user.getDriver().findElement(By.id("auto-join-checkbox")).click(); user.getDriver().findElement(By.id("one2one-btn")).click(); user.getEventManager().waitUntilEventReaches("connectionCreated", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 2); user.getEventManager().waitUntilEventReaches("streamCreated", 4); user.getEventManager().waitUntilEventReaches("streamPlaying", 4); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 4); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); gracefullyLeaveParticipants(2); } @Test @DisplayName("One2One [Audio]") void oneToOneAudioSession() throws Exception { setupBrowser("chrome"); log.info("One2One [Audio]"); user.getDriver().findElement(By.id("one2one-btn")).click(); user.getDriver().findElements(By.className("send-video-checkbox")).forEach(el -> el.click()); user.getDriver().findElements(By.className("join-btn")).forEach(el -> el.sendKeys(Keys.ENTER)); user.getEventManager().waitUntilEventReaches("connectionCreated", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 2); user.getEventManager().waitUntilEventReaches("streamCreated", 4); user.getEventManager().waitUntilEventReaches("streamPlaying", 4); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 4); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, false)); gracefullyLeaveParticipants(2); } @Test @DisplayName("One2One [Video]") void oneToOneVideoSession() throws Exception { setupBrowser("chrome"); log.info("One2One [Video]"); user.getDriver().findElement(By.id("one2one-btn")).click(); user.getDriver().findElements(By.className("send-audio-checkbox")).forEach(el -> el.click()); user.getDriver().findElements(By.className("join-btn")).forEach(el -> el.sendKeys(Keys.ENTER)); user.getEventManager().waitUntilEventReaches("connectionCreated", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 2); user.getEventManager().waitUntilEventReaches("streamCreated", 4); user.getEventManager().waitUntilEventReaches("streamPlaying", 4); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 4); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), false, true)); gracefullyLeaveParticipants(2); } @Test @DisplayName("One2Many [Video + Audio]") void oneToManyVideoAudioSession() throws Exception { setupBrowser("chrome"); log.info("One2Many [Video + Audio]"); user.getDriver().findElement(By.id("auto-join-checkbox")).click(); user.getDriver().findElement(By.id("one2many-btn")).click(); user.getEventManager().waitUntilEventReaches("connectionCreated", 16); user.getEventManager().waitUntilEventReaches("accessAllowed", 1); user.getEventManager().waitUntilEventReaches("streamCreated", 4); user.getEventManager().waitUntilEventReaches("streamPlaying", 4); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 4); user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true); gracefullyLeaveParticipants(4); } @Test @DisplayName("Unique user remote subscription [Video + Audio]") void oneRemoteSubscription() throws Exception { setupBrowser("chrome"); log.info("Unique user remote subscription [Video + Audio]"); user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.className("subscribe-remote-check")).click(); user.getDriver().findElement(By.className("join-btn")).click(); user.getEventManager().waitUntilEventReaches("connectionCreated", 1); user.getEventManager().waitUntilEventReaches("accessAllowed", 1); user.getEventManager().waitUntilEventReaches("streamCreated", 1); user.getEventManager().waitUntilEventReaches("streamPlaying", 1); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 1); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); gracefullyLeaveParticipants(1); } @Test @DisplayName("Unique user remote subscription Firefox [Video + Audio]") void oneRemoteSubscriptionFirefox() throws Exception { setupBrowser("firefox"); log.info("Unique user remote subscription Firefox [Video + Audio]"); user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.className("subscribe-remote-check")).click(); user.getDriver().findElement(By.className("join-btn")).click(); user.getEventManager().waitUntilEventReaches("connectionCreated", 1); user.getEventManager().waitUntilEventReaches("accessAllowed", 1); Thread.sleep(3000); gracefullyLeaveParticipants(1); } @Test @DisplayName("Unique user remote subscription [ScreenShare + Audio]") void oneRemoteSubscriptionScreen() throws Exception { setupBrowser("chrome"); log.info("Unique user remote subscription [ScreenShare + Audio]"); user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.className("screen-radio")).click(); user.getDriver().findElement(By.className("subscribe-remote-check")).click(); user.getDriver().findElement(By.className("join-btn")).click(); user.getEventManager().waitUntilEventReaches("connectionCreated", 1); user.getEventManager().waitUntilEventReaches("accessAllowed", 1); user.getEventManager().waitUntilEventReaches("streamCreated", 1); user.getEventManager().waitUntilEventReaches("streamPlaying", 1); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 1); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); gracefullyLeaveParticipants(1); } @Test @DisplayName("Many2Many [Video + Audio]") void manyToManyVideoAudioSession() throws Exception { setupBrowser("chrome"); log.info("Many2Many [Video + Audio]"); WebElement addUser = user.getDriver().findElement(By.id("add-user-btn")); for (int i = 0; i < 4; i++) { addUser.click(); } user.getDriver().findElements(By.className("join-btn")).forEach(el -> el.sendKeys(Keys.ENTER)); user.getEventManager().waitUntilEventReaches("connectionCreated", 16); user.getEventManager().waitUntilEventReaches("accessAllowed", 4); user.getEventManager().waitUntilEventReaches("streamCreated", 16); user.getEventManager().waitUntilEventReaches("streamPlaying", 16); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 16); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); gracefullyLeaveParticipants(4); } @Test @DisplayName("One2One Firefox [Video + Audio]") void oneToOneVideoAudioSessionFirefox() throws Exception { setupBrowser("firefox"); log.info("One2One Firefox [Video + Audio]"); user.getDriver().findElement(By.id("auto-join-checkbox")).click(); user.getDriver().findElement(By.id("one2one-btn")).click(); user.getEventManager().waitUntilEventReaches("connectionCreated", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 2); user.getEventManager().waitUntilEventReaches("streamCreated", 4); user.getEventManager().waitUntilEventReaches("streamPlaying", 4); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 4); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); gracefullyLeaveParticipants(2); } @Test @DisplayName("Cross-Browser test") void crossBrowserTest() throws Exception { setupBrowser("chrome"); log.info("Cross-Browser test"); Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread th, Throwable ex) { System.out.println("Uncaught exception: " + ex); synchronized (lock) { OpenViduTestAppE2eTest.ex = new Exception(ex); } } }; Thread t = new Thread(() -> { BrowserUser user2 = new FirefoxUser("TestUser", 30); user2.getDriver().get(APP_URL); WebElement urlInput = user2.getDriver().findElement(By.id("openvidu-url")); urlInput.clear(); urlInput.sendKeys(OPENVIDU_URL); WebElement secretInput = user2.getDriver().findElement(By.id("openvidu-secret")); secretInput.clear(); secretInput.sendKeys(OPENVIDU_SECRET); user2.getEventManager().startPolling(); user2.getDriver().findElement(By.id("add-user-btn")).click(); user2.getDriver().findElement(By.className("join-btn")).click(); try { user2.getEventManager().waitUntilEventReaches("connectionCreated", 2); user2.getEventManager().waitUntilEventReaches("accessAllowed", 1); user2.getEventManager().waitUntilEventReaches("streamCreated", 2); user2.getEventManager().waitUntilEventReaches("streamPlaying", 2); Assert.assertEquals(user2.getDriver().findElements(By.tagName("video")).size(), 2); Assert.assertTrue(user2.getEventManager() .assertMediaTracks(user2.getDriver().findElements(By.tagName("video")), true, true)); user2.getEventManager().waitUntilEventReaches("streamDestroyed", 1); user2.getEventManager().waitUntilEventReaches("connectionDestroyed", 1); user2.getDriver().findElement(By.id("remove-user-btn")).click(); user2.getEventManager().waitUntilEventReaches("sessionDisconnected", 1); } catch (Exception e) { e.printStackTrace(); user2.dispose(); Thread.currentThread().interrupt(); } user2.dispose(); }); t.setUncaughtExceptionHandler(h); t.start(); user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.className("join-btn")).click(); user.getEventManager().waitUntilEventReaches("connectionCreated", 2); user.getEventManager().waitUntilEventReaches("accessAllowed", 1); user.getEventManager().waitUntilEventReaches("streamCreated", 2); user.getEventManager().waitUntilEventReaches("streamPlaying", 2); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 2); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); gracefullyLeaveParticipants(1); t.join(); synchronized (lock) { if (OpenViduTestAppE2eTest.ex != null) { throw OpenViduTestAppE2eTest.ex; } } } @Test @DisplayName("Signal message") void oneToManySignalMessage() throws Exception { setupBrowser("chrome"); log.info("Signal message"); WebElement addUser = user.getDriver().findElement(By.id("add-user-btn")); for (int i = 0; i < 4; i++) { addUser.click(); } user.getDriver().findElements(By.className("publish-checkbox")).forEach(el -> el.click()); user.getDriver().findElements(By.className("join-btn")).forEach(el -> el.sendKeys(Keys.ENTER)); user.getEventManager().waitUntilEventReaches("connectionCreated", 16); user.getDriver().findElements(By.className(("message-btn"))).get(0).click(); user.getEventManager().waitUntilEventReaches("signal", 4); gracefullyLeaveParticipants(4); } @Test @DisplayName("Subscribe Unsubscribe") void subscribeUnsubscribeTest() throws Exception { setupBrowser("chrome"); log.info("Subscribe Unsubscribe"); user.getDriver().findElement(By.id("one2one-btn")).click(); user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .publish-checkbox")).click(); user.getDriver().findElements(By.className("join-btn")).forEach(el -> el.sendKeys(Keys.ENTER)); user.getEventManager().waitUntilEventReaches("connectionCreated", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 1); user.getEventManager().waitUntilEventReaches("streamCreated", 2); user.getEventManager().waitUntilEventReaches("streamPlaying", 2); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 2); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); // Global unsubscribe-subscribe WebElement subscriberVideo = user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 video")); WebElement subBtn = user.getDriver().findElement(By.cssSelector(("#openvidu-instance-0 .sub-btn"))); subBtn.click(); user.getWaiter() .until(ExpectedConditions.not(ExpectedConditions.attributeToBeNotEmpty(subscriberVideo, "srcObject"))); Assert.assertFalse(user.getEventManager().hasMediaStream(subscriberVideo)); subBtn.click(); user.getEventManager().waitUntilEventReaches("streamPlaying", 3); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 2); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); // Video unsubscribe subscriberVideo = user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 video")); Iterable<WebElement> firstVideo = Arrays.asList(subscriberVideo); user.getDriver().findElement(By.cssSelector(("#openvidu-instance-0 .sub-video-btn"))).click(); Thread.sleep(1000); Assert.assertTrue(user.getEventManager().assertMediaTracks(firstVideo, true, false)); // Audio unsubscribe user.getDriver().findElement(By.cssSelector(("#openvidu-instance-0 .sub-audio-btn"))).click(); Thread.sleep(1000); Assert.assertTrue(user.getEventManager().assertMediaTracks(firstVideo, false, false)); // Video and audio subscribe user.getDriver().findElement(By.cssSelector(("#openvidu-instance-0 .sub-video-btn"))).click(); Thread.sleep(1000); Assert.assertTrue(user.getEventManager().assertMediaTracks(firstVideo, false, true)); user.getDriver().findElement(By.cssSelector(("#openvidu-instance-0 .sub-audio-btn"))).click(); Thread.sleep(1000); Assert.assertTrue(user.getEventManager().assertMediaTracks(firstVideo, true, true)); gracefullyLeaveParticipants(2); } @Test @DisplayName("Publish Unpublish") void publishUnpublishTest() throws Exception { setupBrowser("chrome"); log.info("Signal message"); user.getDriver().findElement(By.id("auto-join-checkbox")).click(); user.getDriver().findElement(By.id("one2one-btn")).click(); user.getEventManager().waitUntilEventReaches("connectionCreated", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 2); user.getEventManager().waitUntilEventReaches("streamCreated", 4); user.getEventManager().waitUntilEventReaches("streamPlaying", 4); user.getWaiter().until(ExpectedConditions.numberOfElementsToBe(By.tagName("video"), 4)); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); Thread.sleep(2000); List<WebElement> publishButtons = user.getDriver().findElements(By.className("pub-btn")); for (WebElement el : publishButtons) { el.click(); } user.getEventManager().waitUntilEventReaches("streamDestroyed", 4); for (WebElement video : user.getDriver().findElements(By.tagName("video"))) { user.getWaiter() .until(ExpectedConditions.not(ExpectedConditions.attributeToBeNotEmpty(video, "srcObject"))); Assert.assertFalse(user.getEventManager().hasMediaStream(video)); } for (WebElement el : publishButtons) { el.click(); Thread.sleep(1000); } user.getEventManager().waitUntilEventReaches("streamCreated", 8); user.getEventManager().waitUntilEventReaches("streamPlaying", 8); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); gracefullyLeaveParticipants(2); } @Test @DisplayName("Change publisher dynamically") void changePublisherTest() throws Exception { Queue<Boolean> threadAssertions = new ConcurrentLinkedQueue<Boolean>(); setupBrowser("chrome"); log.info("Change publisher dynamically"); WebElement oneToManyInput = user.getDriver().findElement(By.id("one2many-input")); oneToManyInput.clear(); oneToManyInput.sendKeys("1"); user.getDriver().findElement(By.id("auto-join-checkbox")).click(); final CountDownLatch latch1 = new CountDownLatch(2); // First publication (audio + video [CAMERA]) user.getEventManager().on("streamPlaying", (event) -> { if (event.get("eventContent") != null) { threadAssertions.add(((String) event.get("eventContent")).contains("CAMERA")); } latch1.countDown(); }); user.getDriver().findElement(By.id("one2many-btn")).click(); Thread.sleep(2000); user.getEventManager().waitUntilEventReaches("connectionCreated", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 1); user.getEventManager().waitUntilEventReaches("streamCreated", 2); user.getEventManager().waitUntilEventReaches("streamPlaying", 2); if (!latch1.await(8000, TimeUnit.MILLISECONDS)) { gracefullyLeaveParticipants(2); fail(); return; } user.getEventManager().off("streamPlaying"); for (Iterator<Boolean> iter = threadAssertions.iterator(); iter.hasNext();) { Assert.assertTrue(iter.next()); iter.remove(); } user.getWaiter().until(ExpectedConditions.numberOfElementsToBe(By.tagName("video"), 2)); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); Thread.sleep(2000); final CountDownLatch latch2 = new CountDownLatch(2); // Second publication (only video (SCREEN)) user.getEventManager().on("streamPlaying", (event) -> { if (event.get("eventContent") != null) { threadAssertions.add(((String) event.get("eventContent")).contains("SCREEN")); } latch2.countDown(); }); user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .change-publisher-btn")).click(); user.getEventManager().waitUntilEventReaches("streamDestroyed", 2); user.getEventManager().waitUntilEventReaches("accessAllowed", 2); user.getEventManager().waitUntilEventReaches("streamCreated", 4); user.getEventManager().waitUntilEventReaches("streamPlaying", 4); if (!latch2.await(8000, TimeUnit.MILLISECONDS)) { gracefullyLeaveParticipants(2); fail(); return; } user.getEventManager().off("streamPlaying"); for (Iterator<Boolean> iter = threadAssertions.iterator(); iter.hasNext();) { Assert.assertTrue(iter.next()); iter.remove(); } Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), false, true)); Thread.sleep(2000); final CountDownLatch latch3 = new CountDownLatch(2); // Third publication (audio + video [CAMERA]) user.getEventManager().on("streamPlaying", (event) -> { if (event.get("eventContent") != null) { threadAssertions.add(((String) event.get("eventContent")).contains("CAMERA")); } latch3.countDown(); }); user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .change-publisher-btn")).click(); user.getEventManager().waitUntilEventReaches("streamDestroyed", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 3); user.getEventManager().waitUntilEventReaches("streamCreated", 6); user.getEventManager().waitUntilEventReaches("streamPlaying", 6); if (!latch3.await(8000, TimeUnit.MILLISECONDS)) { gracefullyLeaveParticipants(2); fail(); return; } user.getEventManager().off("streamPlaying"); for (Iterator<Boolean> iter = threadAssertions.iterator(); iter.hasNext();) { Assert.assertTrue(iter.next()); iter.remove(); } Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); gracefullyLeaveParticipants(2); } @Test @DisplayName("Moderator capabilities") void moderatorCapabilitiesTest() throws Exception { setupBrowser("chrome"); log.info("Moderator capabilities"); // Add publisher user.getDriver().findElement(By.id("add-user-btn")).click(); // Add subscriber user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.cssSelector("#openvidu-instance-1 .publish-checkbox")).click(); // Add and configure moderator (only subscribe) user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.cssSelector("#openvidu-instance-2 .publish-checkbox")).click(); user.getDriver().findElement(By.id("session-settings-btn-2")).click(); Thread.sleep(1000); user.getDriver().findElement(By.id("radio-btn-mod")).click(); user.getDriver().findElement(By.id("save-btn")).click(); Thread.sleep(1000); user.getDriver().findElements(By.className("join-btn")).forEach(el -> el.sendKeys(Keys.ENTER)); user.getEventManager().waitUntilEventReaches("connectionCreated", 9); user.getEventManager().waitUntilEventReaches("accessAllowed", 1); user.getEventManager().waitUntilEventReaches("streamCreated", 3); user.getEventManager().waitUntilEventReaches("streamPlaying", 3); user.getWaiter().until(ExpectedConditions.numberOfElementsToBe(By.tagName("video"), 3)); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); // Moderator forces unpublish user.getDriver().findElement(By.cssSelector("#openvidu-instance-2 .force-unpub-btn")).click(); user.getEventManager().waitUntilEventReaches("streamDestroyed", 3); user.getWaiter().until(ExpectedConditions.numberOfElementsToBe(By.tagName("video"), 1)); // Publisher publishes again user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .pub-btn")).click(); user.getEventManager().waitUntilEventReaches("streamCreated", 6); user.getEventManager().waitUntilEventReaches("streamPlaying", 6); user.getWaiter().until(ExpectedConditions.numberOfElementsToBe(By.tagName("video"), 3)); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); // Moderator forces disconnect of publisher user.getDriver().findElement(By.cssSelector("#openvidu-instance-2 .force-disconnect-btn")).click(); user.getEventManager().waitUntilEventReaches("streamDestroyed", 6); user.getEventManager().waitUntilEventReaches("connectionDestroyed", 2); user.getEventManager().waitUntilEventReaches("sessionDisconnected", 1); user.getWaiter().until(ExpectedConditions.numberOfElementsToBe(By.tagName("video"), 0)); gracefullyLeaveParticipants(3); } @Test @DisplayName("Stream property changed event") void streamPropertyChangedEventTest() throws Exception { Queue<Boolean> threadAssertions = new ConcurrentLinkedQueue<Boolean>(); setupBrowser("chromeAlternateScreenShare"); log.info("Stream property changed event"); WebElement oneToManyInput = user.getDriver().findElement(By.id("one2many-input")); oneToManyInput.clear(); oneToManyInput.sendKeys("1"); user.getDriver().findElement(By.id("one2many-btn")).click(); user.getDriver().findElement(By.className("screen-radio")).click(); List<WebElement> joinButtons = user.getDriver().findElements(By.className("join-btn")); for (WebElement el : joinButtons) { el.sendKeys(Keys.ENTER); } user.getEventManager().waitUntilEventReaches("connectionCreated", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 1); user.getEventManager().waitUntilEventReaches("streamCreated", 2); user.getEventManager().waitUntilEventReaches("streamPlaying", 2); // Unpublish video final CountDownLatch latch1 = new CountDownLatch(2); user.getEventManager().on("streamPropertyChanged", (event) -> { threadAssertions.add(((String) event.get("eventContent")).contains("videoActive [false]")); latch1.countDown(); }); user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .pub-video-btn")).click(); user.getEventManager().waitUntilEventReaches("streamPropertyChanged", 2); if (!latch1.await(5000, TimeUnit.MILLISECONDS)) { gracefullyLeaveParticipants(2); fail(); return; } user.getEventManager().off("streamPropertyChanged"); for (Iterator<Boolean> iter = threadAssertions.iterator(); iter.hasNext();) { Assert.assertTrue(iter.next()); iter.remove(); } // Unpublish audio final CountDownLatch latch2 = new CountDownLatch(2); user.getEventManager().on("streamPropertyChanged", (event) -> { threadAssertions.add(((String) event.get("eventContent")).contains("audioActive [false]")); latch2.countDown(); }); user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .pub-audio-btn")).click(); user.getEventManager().waitUntilEventReaches("streamPropertyChanged", 4); if (!latch2.await(5000, TimeUnit.MILLISECONDS)) { gracefullyLeaveParticipants(2); fail(); return; } user.getEventManager().off("streamPropertyChanged"); for (Iterator<Boolean> iter = threadAssertions.iterator(); iter.hasNext();) { Assert.assertTrue(iter.next()); iter.remove(); } // Resize captured window final CountDownLatch latch3 = new CountDownLatch(2); int newWidth = 1500; int newHeight = 500; final long[] expectedWidthHeight = new long[2]; user.getEventManager().on("streamPropertyChanged", (event) -> { threadAssertions.add(((String) event.get("eventContent")).contains("videoDimensions [{\"width\":" + expectedWidthHeight[0] + ",\"height\":" + expectedWidthHeight[1] + "}]")); latch3.countDown(); }); user.getDriver().manage().window().setSize(new Dimension(newWidth, newHeight)); String widthAndHeight = user.getEventManager().getDimensionOfViewport(); JSONObject obj = (JSONObject) new JSONParser().parse(widthAndHeight); expectedWidthHeight[0] = (long) obj.get("width"); expectedWidthHeight[1] = (long) obj.get("height") - 1; System.out.println("New viewport dimension: " + obj.toJSONString()); user.getEventManager().waitUntilEventReaches("streamPropertyChanged", 6); if (!latch3.await(5000, TimeUnit.MILLISECONDS)) { gracefullyLeaveParticipants(2); fail(); return; } user.getEventManager().off("streamPropertyChanged"); for (Iterator<Boolean> iter = threadAssertions.iterator(); iter.hasNext();) { Assert.assertTrue(iter.next()); iter.remove(); } gracefullyLeaveParticipants(2); } @Test @DisplayName("Local record") void localRecordTest() throws Exception { setupBrowser("chrome"); log.info("Local record"); user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.className("join-btn")).click(); user.getEventManager().waitUntilEventReaches("connectionCreated", 1); user.getEventManager().waitUntilEventReaches("accessAllowed", 1); user.getEventManager().waitUntilEventReaches("streamCreated", 1); user.getEventManager().waitUntilEventReaches("streamPlaying", 1); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); WebElement recordBtn = user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .publisher-rec-btn")); recordBtn.click(); Thread.sleep(2000); WebElement pauseRecordBtn = user.getDriver() .findElement(By.cssSelector("#openvidu-instance-0 .publisher-rec-pause-btn")); pauseRecordBtn.click(); Thread.sleep(2000); pauseRecordBtn.click(); Thread.sleep(2000); recordBtn.click(); user.getWaiter().until(ExpectedConditions.elementToBeClickable(By.cssSelector("#recorder-preview video"))); user.getWaiter().until( waitForVideoDuration(user.getDriver().findElement(By.cssSelector("#recorder-preview video")), 4)); user.getDriver().findElement(By.id("close-record-btn")).click(); user.getWaiter().until(ExpectedConditions.numberOfElementsToBe(By.cssSelector("#recorder-preview video"), 0)); gracefullyLeaveParticipants(1); } @Test @DisplayName("Remote composed record") void remoteComposedRecordTest() throws Exception { isRecordingTest = true; setupBrowser("chrome"); log.info("Remote composed record"); final String sessionName = "COMPOSED_RECORDED_SESSION"; final String resolution = "1280x720"; user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.id("session-name-input-0")).clear(); user.getDriver().findElement(By.id("session-name-input-0")).sendKeys(sessionName); // API REST test user.getDriver().findElement(By.id("session-api-btn-0")).click(); Thread.sleep(1000); // Try to record a non-existing session user.getDriver().findElement(By.id("start-recording-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Error [404]")); listEmptyRecordings(); // Try to stop a non-existing recording user.getDriver().findElement(By.id("recording-id-field")).sendKeys("FAIL"); user.getDriver().findElement(By.id("stop-recording-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Error [404]")); listEmptyRecordings(); // Try to get a non-existing recording user.getDriver().findElement(By.id("get-recording-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Error [404]")); listEmptyRecordings(); // Try to delete a non-existing recording user.getDriver().findElement(By.id("get-recording-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Error [404]")); user.getDriver().findElement(By.id("close-dialog-btn")).click(); Thread.sleep(1000); // Join the user to the session user.getDriver().findElement(By.className("join-btn")).click(); user.getEventManager().waitUntilEventReaches("connectionCreated", 1); user.getEventManager().waitUntilEventReaches("accessAllowed", 1); user.getEventManager().waitUntilEventReaches("streamCreated", 1); user.getEventManager().waitUntilEventReaches("streamPlaying", 1); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); user.getDriver().findElement(By.id("session-api-btn-0")).click(); Thread.sleep(1000); user.getDriver().findElement(By.id("rec-properties-btn")).click(); Thread.sleep(500); WebElement resolutionField = user.getDriver().findElement(By.id("recording-resolution-field")); resolutionField.clear(); resolutionField.sendKeys(resolution); user.getDriver().findElement(By.id("start-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording started [" + sessionName + "]")); user.getEventManager().waitUntilEventReaches("recordingStarted", 1); Thread.sleep(5000); user.getDriver().findElement(By.id("recording-id-field")).clear(); user.getDriver().findElement(By.id("recording-id-field")).sendKeys(sessionName); // Try to start an ongoing recording user.getDriver().findElement(By.id("start-recording-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Error [409]")); // Try to get an existing recording user.getDriver().findElement(By.id("get-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording got [" + sessionName + "]")); // Try to delete an ongoing recording user.getDriver().findElement(By.id("delete-recording-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Error [409]")); // List existing recordings (one) user.getDriver().findElement(By.id("list-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording list [" + sessionName + "]")); // Stop ongoing recording user.getDriver().findElement(By.id("stop-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording stopped [" + sessionName + "]")); user.getEventManager().waitUntilEventReaches("recordingStopped", 1); String recordingsPath = "/opt/openvidu/recordings/"; File file1 = new File(recordingsPath + sessionName + "/" + sessionName + ".mp4"); File file2 = new File(recordingsPath + sessionName + "/" + ".recording." + sessionName); File file3 = new File(recordingsPath + sessionName + "/" + sessionName + ".jpg"); Assert.assertTrue(file1.exists() && file1.length() > 0); Assert.assertTrue(file2.exists() && file2.length() > 0); Assert.assertTrue(file3.exists() && file3.length() > 0); Assert.assertTrue( this.recordedFileFine(file1, new OpenVidu(OPENVIDU_URL, OPENVIDU_SECRET).getRecording(sessionName))); Assert.assertTrue(this.thumbnailIsFine(file3)); // Try to get the stopped recording user.getDriver().findElement(By.id("get-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording got [" + sessionName + "]")); // Try to list the stopped recording user.getDriver().findElement(By.id("list-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording list [" + sessionName + "]")); // Delete the recording user.getDriver().findElement(By.id("delete-recording-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording deleted")); Assert.assertFalse(file1.exists()); Assert.assertFalse(file2.exists()); Assert.assertFalse(file3.exists()); user.getDriver().findElement(By.id("close-dialog-btn")).click(); Thread.sleep(500); gracefullyLeaveParticipants(1); } @Test @DisplayName("Remote individual record") void remoteIndividualRecordTest() throws Exception { isRecordingTest = true; setupBrowser("chrome"); log.info("Remote individual record"); final String sessionName = "TestSession"; final String recordingName = "CUSTOM_NAME"; user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.id("session-name-input-0")).clear(); user.getDriver().findElement(By.id("session-name-input-0")).sendKeys(sessionName); user.getDriver().findElement(By.id("auto-join-checkbox")).click(); user.getDriver().findElement(By.id("one2one-btn")).click(); user.getEventManager().waitUntilEventReaches("connectionCreated", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 2); user.getEventManager().waitUntilEventReaches("streamCreated", 4); user.getEventManager().waitUntilEventReaches("streamPlaying", 4); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); user.getDriver().findElement(By.id("session-api-btn-0")).click(); Thread.sleep(1000); user.getDriver().findElement(By.id("rec-properties-btn")).click(); Thread.sleep(500); // Set recording name user.getDriver().findElement(By.id("recording-name-field")).sendKeys(recordingName); // Set OutputMode to INDIVIDUAL user.getDriver().findElement(By.id("rec-outputmode-select")).click(); Thread.sleep(500); user.getDriver().findElement(By.id("option-INDIVIDUAL")).click(); Thread.sleep(500); user.getDriver().findElement(By.id("start-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording started [" + sessionName + "]")); user.getEventManager().waitUntilEventReaches("recordingStarted", 2); Thread.sleep(5000); user.getDriver().findElement(By.id("recording-id-field")).clear(); user.getDriver().findElement(By.id("recording-id-field")).sendKeys(sessionName); // Try to start an ongoing recording user.getDriver().findElement(By.id("start-recording-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Error [409]")); // Try to get an existing recording user.getDriver().findElement(By.id("get-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording got [" + sessionName + "]")); // Try to delete an ongoing recording user.getDriver().findElement(By.id("delete-recording-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Error [409]")); // List existing recordings (one) user.getDriver().findElement(By.id("list-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording list [" + sessionName + "]")); // Stop ongoing recording user.getDriver().findElement(By.id("stop-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording stopped [" + sessionName + "]")); user.getEventManager().waitUntilEventReaches("recordingStopped", 2); String recordingsPath = "/opt/openvidu/recordings/"; String recPath = recordingsPath + sessionName + "/"; Recording recording = new OpenVidu(OPENVIDU_URL, OPENVIDU_SECRET).getRecording(sessionName); this.checkIndividualRecording(recPath, recording, "opus", "vp8"); // Try to get the stopped recording user.getDriver().findElement(By.id("get-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording got [" + sessionName + "]")); // Try to list the stopped recording user.getDriver().findElement(By.id("list-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording list [" + sessionName + "]")); // Delete the recording user.getDriver().findElement(By.id("delete-recording-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording deleted")); Assert.assertFalse(new File(recPath).exists()); user.getDriver().findElement(By.id("close-dialog-btn")).click(); Thread.sleep(500); gracefullyLeaveParticipants(2); } @Test @DisplayName("Remote record cross-browser audio-only and video-only") void remoteRecordAudioOnlyVideoOnlyTest() throws Exception { isRecordingTest = true; setupBrowser("chromeAlternateScreenShare"); log.info("Remote record cross-browser audio-only and video-only"); final String SESSION_NAME = "TestSession"; final String RECORDING_COMPOSED_VIDEO = "COMPOSED_VIDEO_ONLY"; final String RECORDING_COMPOSED_AUDIO = "COMPOSED_AUDIO_ONLY"; final String RECORDING_INDIVIDUAL_VIDEO = "INDIVIDUAL_VIDEO_ONLY"; final String RECORDING_INDIVIDUAL_AUDIO = "INDIVIDUAL_AUDIO_ONLY"; final int RECORDING_DURATION = 5000; Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread th, Throwable ex) { System.out.println("Uncaught exception: " + ex); synchronized (lock) { OpenViduTestAppE2eTest.ex = new Exception(ex); } } }; Thread t = new Thread(() -> { BrowserUser user2 = new FirefoxUser("FirefoxUser", 30); user2.getDriver().get(APP_URL); WebElement urlInput = user2.getDriver().findElement(By.id("openvidu-url")); urlInput.clear(); urlInput.sendKeys(OPENVIDU_URL); WebElement secretInput = user2.getDriver().findElement(By.id("openvidu-secret")); secretInput.clear(); secretInput.sendKeys(OPENVIDU_SECRET); user2.getEventManager().startPolling(); // Firefox user audio + video user2.getDriver().findElement(By.id("add-user-btn")).click(); // Firefox user video-only user2.getDriver().findElement(By.id("add-user-btn")).click(); user2.getDriver().findElement(By.cssSelector("#openvidu-instance-1 .send-audio-checkbox")).click(); // Join Firefox users user2.getDriver().findElements(By.className("join-btn")).forEach(el -> el.sendKeys(Keys.ENTER)); try { user2.getEventManager().waitUntilEventReaches("connectionCreated", 4); user2.getEventManager().waitUntilEventReaches("accessAllowed", 2); user2.getEventManager().waitUntilEventReaches("streamCreated", 8); user2.getEventManager().waitUntilEventReaches("streamPlaying", 8); Assert.assertEquals(user2.getDriver().findElements(By.tagName("video")).size(), 8); user2.getEventManager().waitUntilEventReaches("recordingStarted", 2); user2.getEventManager().waitUntilEventReaches("recordingStopped", 2); user2.getEventManager().waitUntilEventReaches("recordingStarted", 4); user2.getEventManager().waitUntilEventReaches("recordingStopped", 4); user2.getEventManager().waitUntilEventReaches("recordingStarted", 6); user2.getEventManager().waitUntilEventReaches("recordingStopped", 6); user2.getEventManager().waitUntilEventReaches("recordingStarted", 8); user2.getEventManager().waitUntilEventReaches("recordingStopped", 8); user2.getEventManager().waitUntilEventReaches("streamDestroyed", 4); user2.getEventManager().waitUntilEventReaches("connectionDestroyed", 4); user2.getDriver().findElement(By.id("remove-user-btn")).click(); user2.getDriver().findElement(By.id("remove-user-btn")).click(); user2.getEventManager().waitUntilEventReaches("sessionDisconnected", 2); } catch (Exception e) { e.printStackTrace(); user2.dispose(); Thread.currentThread().interrupt(); } user2.dispose(); }); t.setUncaughtExceptionHandler(h); t.start(); // Chrome user screen share only-video user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .screen-radio")).click(); user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .send-audio-checkbox")).click(); // Chrome user audio-only user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.cssSelector("#openvidu-instance-1 .send-video-checkbox")).click(); // Join Chrome users user.getDriver().findElements(By.className("join-btn")).forEach(el -> el.sendKeys(Keys.ENTER)); user.getEventManager().waitUntilEventReaches("connectionCreated", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 2); user.getEventManager().waitUntilEventReaches("streamCreated", 8); user.getEventManager().waitUntilEventReaches("streamPlaying", 8); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 8); user.getDriver().findElement(By.id("session-api-btn-0")).click(); Thread.sleep(1000); user.getDriver().findElement(By.id("rec-properties-btn")).click(); Thread.sleep(500); WebElement recordingNameField = user.getDriver().findElement(By.id("recording-name-field")); // Video-only COMPOSED recording recordingNameField.clear(); recordingNameField.sendKeys(RECORDING_COMPOSED_VIDEO); user.getDriver().findElement(By.id("rec-hasaudio-checkbox")).click(); Thread.sleep(500); user.getDriver().findElement(By.id("start-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording started [" + SESSION_NAME + "]")); user.getEventManager().waitUntilEventReaches("recordingStarted", 2); Thread.sleep(RECORDING_DURATION); user.getDriver().findElement(By.id("recording-id-field")).clear(); user.getDriver().findElement(By.id("recording-id-field")).sendKeys(SESSION_NAME); user.getDriver().findElement(By.id("stop-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording stopped [" + SESSION_NAME + "]")); user.getEventManager().waitUntilEventReaches("recordingStopped", 2); // Audio-only COMPOSED recording recordingNameField.clear(); recordingNameField.sendKeys(RECORDING_COMPOSED_AUDIO); user.getDriver().findElement(By.id("rec-hasaudio-checkbox")).click(); user.getDriver().findElement(By.id("rec-hasvideo-checkbox")).click(); Thread.sleep(500); user.getDriver().findElement(By.id("start-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording started [" + SESSION_NAME + "-1]")); user.getEventManager().waitUntilEventReaches("recordingStarted", 4); Thread.sleep(RECORDING_DURATION); user.getDriver().findElement(By.id("recording-id-field")).clear(); user.getDriver().findElement(By.id("recording-id-field")).sendKeys(SESSION_NAME + "-1"); user.getDriver().findElement(By.id("stop-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording stopped [" + SESSION_NAME + "-1]")); user.getEventManager().waitUntilEventReaches("recordingStopped", 4); // Video-only INDIVIDUAL recording recordingNameField.clear(); recordingNameField.sendKeys(RECORDING_INDIVIDUAL_VIDEO); user.getDriver().findElement(By.id("rec-hasaudio-checkbox")).click(); user.getDriver().findElement(By.id("rec-hasvideo-checkbox")).click(); Thread.sleep(500); user.getDriver().findElement(By.id("rec-outputmode-select")).click(); Thread.sleep(500); user.getDriver().findElement(By.id("option-INDIVIDUAL")).click(); Thread.sleep(500); user.getDriver().findElement(By.id("start-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording started [" + SESSION_NAME + "-2]")); user.getEventManager().waitUntilEventReaches("recordingStarted", 6); Thread.sleep(RECORDING_DURATION); user.getDriver().findElement(By.id("recording-id-field")).clear(); user.getDriver().findElement(By.id("recording-id-field")).sendKeys(SESSION_NAME + "-2"); user.getDriver().findElement(By.id("stop-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording stopped [" + SESSION_NAME + "-2]")); user.getEventManager().waitUntilEventReaches("recordingStopped", 6); // Audio-only INDIVIDUAL recording recordingNameField.clear(); recordingNameField.sendKeys(RECORDING_INDIVIDUAL_AUDIO); user.getDriver().findElement(By.id("rec-hasaudio-checkbox")).click(); user.getDriver().findElement(By.id("rec-hasvideo-checkbox")).click(); Thread.sleep(500); user.getDriver().findElement(By.id("start-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording started [" + SESSION_NAME + "-3]")); user.getEventManager().waitUntilEventReaches("recordingStarted", 8); Thread.sleep(RECORDING_DURATION); user.getDriver().findElement(By.id("recording-id-field")).clear(); user.getDriver().findElement(By.id("recording-id-field")).sendKeys(SESSION_NAME + "-3"); user.getDriver().findElement(By.id("stop-recording-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording stopped [" + SESSION_NAME + "-3]")); user.getEventManager().waitUntilEventReaches("recordingStopped", 8); String recordingsPath = "/opt/openvidu/recordings/"; // Check video-only COMPOSED recording String recPath = recordingsPath + SESSION_NAME + "/"; Recording recording = new OpenVidu(OPENVIDU_URL, OPENVIDU_SECRET).getRecording(SESSION_NAME); this.checkMultimediaFile(new File(recPath + recording.getName() + ".mp4"), false, true, recording.getDuration(), recording.getResolution(), null, "h264"); // Check audio-only COMPOSED recording recPath = recordingsPath + SESSION_NAME + "-1/"; recording = new OpenVidu(OPENVIDU_URL, OPENVIDU_SECRET).getRecording(SESSION_NAME + "-1"); this.checkMultimediaFile(new File(recPath + recording.getName() + ".webm"), true, false, recording.getDuration() * 1000, null, "opus", null); // Check video-only INDIVIDUAL recording recPath = recordingsPath + SESSION_NAME + "-2/"; recording = new OpenVidu(OPENVIDU_URL, OPENVIDU_SECRET).getRecording(SESSION_NAME + "-2"); this.checkIndividualRecording(recPath, recording, "opus", "vp8"); // Check audio-only INDIVIDUAL recording recPath = recordingsPath + SESSION_NAME + "-3/"; recording = new OpenVidu(OPENVIDU_URL, OPENVIDU_SECRET).getRecording(SESSION_NAME + "-3"); this.checkIndividualRecording(recPath, recording, "opus", "vp8"); user.getDriver().findElement(By.id("close-dialog-btn")).click(); Thread.sleep(500); gracefullyLeaveParticipants(2); t.join(); synchronized (lock) { if (OpenViduTestAppE2eTest.ex != null) { throw OpenViduTestAppE2eTest.ex; } } } @Test @DisplayName("REST API: Fetch all, fetch one, force disconnect, force unpublish, close session") void restApiFetchForce() throws Exception { setupBrowser("chrome"); log.info("REST API: Fetch all, fetch one, force disconnect, force unpublish, close session"); user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.id("add-user-btn")).click(); // API REST test user.getDriver().findElement(By.id("session-api-btn-0")).click(); Thread.sleep(1000); // Close session (undefined) user.getDriver().findElement(By.id("close-session-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Error [Session undefined]")); // Fetch one (undefined) user.getDriver().findElement(By.id("get-session-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Error [Session undefined]")); // Fetch all (no active sessions) user.getDriver().findElement(By.id("list-sessions-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeContains(By.id("api-response-text-area"), "value", "Number: 0. Changes: false")); user.getDriver().findElement(By.id("close-dialog-btn")).click(); Thread.sleep(1000); user.getDriver().findElement(By.id("auto-join-checkbox")).click(); user.getDriver().findElement(By.id("one2one-btn")).click(); user.getEventManager().waitUntilEventReaches("connectionCreated", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 2); user.getEventManager().waitUntilEventReaches("streamCreated", 4); user.getEventManager().waitUntilEventReaches("streamPlaying", 4); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true)); // Fetch existing session (change) user.getDriver().findElement(By.id("session-api-btn-0")).click(); Thread.sleep(1000); user.getDriver().findElement(By.id("get-session-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeContains(By.id("api-response-text-area"), "value", "Changes: true")); // Store connectionId and streamId String response = user.getDriver().findElement(By.id("api-response-text-area")).getAttribute("value"); JSONObject json = (JSONObject) ((JSONArray) new JSONParser().parse(response.split("%")[1])).get(0); String connectionId = (String) json.keySet().iterator().next(); String streamId = (String) ((JSONObject) ((JSONArray) json.get(connectionId)).get(0)).get("streamId"); // Fetch all sessions (no change) user.getDriver().findElement(By.id("list-sessions-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeContains(By.id("api-response-text-area"), "value", "Number: 1. Changes: false")); // Force unpublish wrong user.getDriver().findElement(By.id("resource-id-field")).clear(); user.getDriver().findElement(By.id("resource-id-field")).sendKeys("FAIL"); user.getDriver().findElement(By.id("force-unpublish-api-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Error [404]")); // Force unpublish right user.getDriver().findElement(By.id("resource-id-field")).clear(); user.getDriver().findElement(By.id("resource-id-field")).sendKeys(streamId); user.getDriver().findElement(By.id("force-unpublish-api-btn")).click(); user.getWaiter().until( ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Stream unpublished")); user.getEventManager().waitUntilEventReaches("streamDestroyed", 2); // Force disconnect wrong user.getDriver().findElement(By.id("resource-id-field")).clear(); user.getDriver().findElement(By.id("resource-id-field")).sendKeys("FAIL"); user.getDriver().findElement(By.id("force-disconnect-api-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Error [404]")); // Force disconnect right user.getDriver().findElement(By.id("resource-id-field")).clear(); user.getDriver().findElement(By.id("resource-id-field")).sendKeys(connectionId); user.getDriver().findElement(By.id("force-disconnect-api-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "User disconnected")); user.getEventManager().waitUntilEventReaches("connectionDestroyed", 1); // Close session user.getDriver().findElement(By.id("close-session-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Session closed")); user.getWaiter().until(ExpectedConditions.numberOfElementsToBe(By.tagName("video"), 0)); user.getDriver().findElement(By.id("close-dialog-btn")).click(); Thread.sleep(500); gracefullyLeaveParticipants(1); } @Test @DisplayName("Video filter test") void videoFilterTest() throws Exception { setupBrowser("chrome"); log.info("Video filter test"); // Configure publisher user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElements(By.cssSelector("#openvidu-instance-0 .subscribe-checkbox")).get(0).click(); user.getDriver().findElements(By.cssSelector("#openvidu-instance-0 .send-audio-checkbox")).get(0).click(); user.getDriver().findElement(By.id("session-settings-btn-0")).click(); Thread.sleep(1000); user.getDriver().findElement(By.id("add-allowed-filter-btn")).click(); user.getDriver().findElement(By.id("save-btn")).click(); Thread.sleep(1000); // Configure subscriber user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.cssSelector("#openvidu-instance-1 .publish-checkbox")).click(); user.getDriver().findElements(By.className("join-btn")).forEach(el -> el.sendKeys(Keys.ENTER)); user.getEventManager().waitUntilEventReaches("connectionCreated", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 1); user.getEventManager().waitUntilEventReaches("streamCreated", 2); user.getEventManager().waitUntilEventReaches("streamPlaying", 2); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 2); Assert.assertTrue(user.getEventManager().assertMediaTracks(user.getDriver().findElements(By.tagName("video")), false, true)); WebElement subscriberVideo = user.getDriver().findElement(By.cssSelector("#openvidu-instance-1 video")); // Analyze Chrome fake video stream without gray filter (GREEN color) Map<String, Long> rgb = user.getEventManager().getAverageRgbFromVideo(subscriberVideo); System.out.println(rgb.toString()); Assert.assertTrue(checkVideoAverageRgbGreen(rgb)); // Try to apply none allowed filter user.getDriver().findElement(By.cssSelector(".filter-btn")).click(); WebElement filterTypeInput = user.getDriver().findElement(By.id("filter-type-field")); filterTypeInput.clear(); filterTypeInput.sendKeys("NotAllowedFilter"); user.getDriver().findElement(By.id("apply-filter-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeContains(By.id("filter-response-text-area"), "value", "Error [You don't have permissions to apply a filter]")); // Try to execute method over not applied filter user.getDriver().findElement(By.id("exec-filter-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeContains(By.id("filter-response-text-area"), "value", "has no filter applied in session")); // Apply allowed video filter filterTypeInput.clear(); filterTypeInput.sendKeys("GStreamerFilter"); WebElement filterOptionsInput = user.getDriver().findElement(By.id("filter-options-field")); filterOptionsInput.clear(); filterOptionsInput.sendKeys("{\"command\": \"videobalance saturation=0.0\"}"); user.getDriver().findElement(By.id("apply-filter-btn")).click(); user.getWaiter().until( ExpectedConditions.attributeContains(By.id("filter-response-text-area"), "value", "Filter applied")); // Try to apply another filter user.getDriver().findElement(By.id("apply-filter-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeContains(By.id("filter-response-text-area"), "value", "already has a filter applied in session")); // Analyze Chrome fake video stream with gray filter (GRAY color) user.getEventManager().waitUntilEventReaches("streamPropertyChanged", 2); Thread.sleep(500); rgb = user.getEventManager().getAverageRgbFromVideo(subscriberVideo); System.out.println(rgb.toString()); Assert.assertTrue(checkVideoAverageRgbGray(rgb)); // Execute filter method WebElement filterMethodInput = user.getDriver().findElement(By.id("filter-method-field")); filterMethodInput.clear(); filterMethodInput.sendKeys("setElementProperty"); WebElement filterParamsInput = user.getDriver().findElement(By.id("filter-params-field")); filterParamsInput.clear(); filterParamsInput.sendKeys("{\"propertyName\":\"saturation\",\"propertyValue\":\"1.0\"}"); user.getDriver().findElement(By.id("exec-filter-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeContains(By.id("filter-response-text-area"), "value", "Filter method executed")); // Analyze Chrome fake video stream without gray filter (GREEN color) user.getEventManager().waitUntilEventReaches("streamPropertyChanged", 4); Thread.sleep(500); rgb = user.getEventManager().getAverageRgbFromVideo(subscriberVideo); System.out.println(rgb.toString()); Assert.assertTrue(checkVideoAverageRgbGreen(rgb)); user.getDriver().findElement(By.id("close-dialog-btn")).click(); Thread.sleep(500); // Publisher leaves and connects with active filter user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .leave-btn")).click(); user.getEventManager().waitUntilEventReaches("streamDestroyed", 2); user.getEventManager().waitUntilEventReaches("connectionDestroyed", 1); user.getEventManager().waitUntilEventReaches("sessionDisconnected", 1); user.getDriver().findElement(By.id("publisher-settings-btn-0")).click(); Thread.sleep(500); user.getDriver().findElement(By.id("save-btn")).click(); Thread.sleep(500); user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .join-btn")).click(); user.getEventManager().waitUntilEventReaches("connectionCreated", 7); user.getEventManager().waitUntilEventReaches("accessAllowed", 2); user.getEventManager().waitUntilEventReaches("streamCreated", 4); user.getEventManager().waitUntilEventReaches("streamPlaying", 4); // Analyze Chrome fake video stream with gray filter (GRAY color) subscriberVideo = user.getDriver().findElement(By.cssSelector("#openvidu-instance-1 video")); rgb = user.getEventManager().getAverageRgbFromVideo(subscriberVideo); System.out.println(rgb.toString()); Assert.assertTrue(checkVideoAverageRgbGray(rgb)); // Remove filter user.getDriver().findElement(By.cssSelector(".filter-btn")).click(); Thread.sleep(500); user.getDriver().findElement(By.id("remove-filter-btn")).click(); user.getWaiter().until( ExpectedConditions.attributeContains(By.id("filter-response-text-area"), "value", "Filter removed")); user.getEventManager().waitUntilEventReaches("streamPropertyChanged", 6); Thread.sleep(1000); // Analyze Chrome fake video stream with gray filter (GREEN color) rgb = user.getEventManager().getAverageRgbFromVideo(subscriberVideo); System.out.println(rgb.toString()); Assert.assertTrue(checkVideoAverageRgbGreen(rgb)); user.getDriver().findElement(By.id("close-dialog-btn")).click(); Thread.sleep(500); gracefullyLeaveParticipants(2); } @Test @DisplayName("Video filter events test") void videoFilterEventsTest() throws Exception { setupChromeWithFakeVideo(Paths.get("/opt/openvidu/barcode.y4m")); log.info("Video filter events test"); // Configure publisher user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElements(By.cssSelector("#openvidu-instance-0 .subscribe-checkbox")).get(0).click(); user.getDriver().findElements(By.cssSelector("#openvidu-instance-0 .send-audio-checkbox")).get(0).click(); user.getDriver().findElement(By.id("session-settings-btn-0")).click(); Thread.sleep(1000); WebElement allowedFilterInput = user.getDriver().findElement(By.id("allowed-filter-input")); allowedFilterInput.clear(); allowedFilterInput.sendKeys("ZBarFilter"); user.getDriver().findElement(By.id("add-allowed-filter-btn")).click(); user.getDriver().findElement(By.id("save-btn")).click(); Thread.sleep(1000); // Configure moderator (only subscribe) user.getDriver().findElement(By.id("add-user-btn")).click(); user.getDriver().findElement(By.cssSelector("#openvidu-instance-1 .publish-checkbox")).click(); user.getDriver().findElement(By.id("session-settings-btn-1")).click(); Thread.sleep(1000); user.getDriver().findElement(By.id("radio-btn-mod")).click(); user.getDriver().findElement(By.id("save-btn")).click(); Thread.sleep(1000); user.getDriver().findElements(By.className("join-btn")).forEach(el -> el.sendKeys(Keys.ENTER)); user.getEventManager().waitUntilEventReaches("connectionCreated", 4); user.getEventManager().waitUntilEventReaches("accessAllowed", 1); user.getEventManager().waitUntilEventReaches("streamCreated", 2); user.getEventManager().waitUntilEventReaches("streamPlaying", 2); Assert.assertEquals(user.getDriver().findElements(By.tagName("video")).size(), 2); // Assert no audio track only for the moderator incoming video Assert.assertTrue(user.getEventManager().assertMediaTracks( user.getDriver().findElements(By.cssSelector("#openvidu-instance-1 video")), false, true)); // Publisher applies ZBarCode filter to itself user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .filter-btn")).click(); Thread.sleep(500); WebElement input = user.getDriver().findElement(By.id("filter-type-field")); input.clear(); input.sendKeys("ZBarFilter"); input = user.getDriver().findElement(By.id("filter-options-field")); input.clear(); input.sendKeys("{}"); user.getDriver().findElement(By.id("apply-filter-btn")).click(); user.getWaiter().until( ExpectedConditions.attributeContains(By.id("filter-response-text-area"), "value", "Filter applied")); user.getEventManager().waitUntilEventReaches("streamPropertyChanged", 2); // Publisher subscribes to CodeFound event for his own stream input = user.getDriver().findElement(By.id("filter-event-type-field")); input.clear(); input.sendKeys("CodeFound"); user.getDriver().findElement(By.id("sub-filter-event-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeContains(By.id("filter-response-text-area"), "value", "Filter event listener added")); user.getEventManager().waitUntilEventReaches("filterEvent", 2); // Publisher unsubscribes from "CodeFound" filter event user.getDriver().findElement(By.id("unsub-filter-event-btn")).click(); try { // If this active wait finishes successfully, then the removal of the event // listener has not worked fine user.getEventManager().waitUntilEventReaches("filterEvent", 3, 3, false); Assert.fail("'filterEvent' was received. Filter.removeEventListener() failed"); } catch (Exception e) { System.out.println("Filter event removal worked fine"); } user.getDriver().findElement(By.id("close-dialog-btn")).click(); Thread.sleep(500); // Moderator subscribes to CodeFound event for the Publisher's stream user.getDriver().findElement(By.cssSelector("#openvidu-instance-1 .filter-btn")).click(); Thread.sleep(500); input = user.getDriver().findElement(By.id("filter-event-type-field")); input.clear(); input.sendKeys("CodeFound"); user.getDriver().findElement(By.id("sub-filter-event-btn")).click(); user.getWaiter().until(ExpectedConditions.attributeContains(By.id("filter-response-text-area"), "value", "Filter event listener added")); user.getEventManager().waitUntilEventReaches("filterEvent", 4); // Moderator removes the Publisher's filter user.getDriver().findElement(By.id("remove-filter-btn")).click(); user.getWaiter().until( ExpectedConditions.attributeContains(By.id("filter-response-text-area"), "value", "Filter removed")); user.getEventManager().waitUntilEventReaches("streamPropertyChanged", 4); try { // If this active wait finishes successfully, then the removal of the filter has // not worked fine user.getEventManager().waitUntilEventReaches("filterEvent", 5, 3, false); Assert.fail("'filterEvent' was received. Stream.removeFilter() failed"); } catch (Exception e) { System.out.println("Filter removal worked fine"); } gracefullyLeaveParticipants(2); } private void listEmptyRecordings() { // List existing recordings (empty) user.getDriver().findElement(By.id("list-recording-btn")).click(); user.getWaiter() .until(ExpectedConditions.attributeToBe(By.id("api-response-text-area"), "value", "Recording list []")); } private ExpectedCondition<Boolean> waitForVideoDuration(WebElement element, int durationInSeconds) { return new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver input) { return element.getAttribute("duration").matches( durationInSeconds - 1 + "\\.[8-9][0-9]{0,5}|" + durationInSeconds + "\\.[0-2][0-9]{0,5}"); } }; } private boolean checkVideoAverageRgbGreen(Map<String, Long> rgb) { // GREEN color: {r < 15, g > 130, b <15} return (rgb.get("r") < 15) && (rgb.get("g") > 130) && (rgb.get("b") < 15); } private boolean checkVideoAverageRgbGray(Map<String, Long> rgb) { // GRAY color: {r < 50, g < 50, b < 50} and the absolute difference between them // not greater than 2 return (rgb.get("r") < 50) && (rgb.get("g") < 50) && (rgb.get("b") < 50) && (Math.abs(rgb.get("r") - rgb.get("g")) <= 2) && (Math.abs(rgb.get("r") - rgb.get("b")) <= 2) && (Math.abs(rgb.get("b") - rgb.get("g")) <= 2); } private void gracefullyLeaveParticipants(int numberOfParticipants) throws Exception { int accumulatedConnectionDestroyed = 0; for (int j = 1; j <= numberOfParticipants; j++) { user.getDriver().findElement(By.id("remove-user-btn")).sendKeys(Keys.ENTER); user.getEventManager().waitUntilEventReaches("sessionDisconnected", j); accumulatedConnectionDestroyed = (j != numberOfParticipants) ? (accumulatedConnectionDestroyed + numberOfParticipants - j) : (accumulatedConnectionDestroyed); user.getEventManager().waitUntilEventReaches("connectionDestroyed", accumulatedConnectionDestroyed); } } private String getBase64Screenshot(BrowserUser user) throws Exception { String screenshotBase64 = ((TakesScreenshot) user.getDriver()).getScreenshotAs(BASE64); return "data:image/png;base64," + screenshotBase64; } private boolean recordedFileFine(File file, Recording recording) { this.checkMultimediaFile(file, true, true, recording.getDuration(), recording.getResolution(), "aac", "h264"); boolean isFine = false; Picture frame; try { // Get a frame at 75% duration and check that it has the expected color frame = FrameGrab.getFrameAtSec(file, (double) (recording.getDuration() * 0.75)); BufferedImage image = AWTUtil.toBufferedImage(frame); Map<String, Long> colorMap = this.averageColor(image); Assert.assertEquals(image.getWidth() + "x" + image.getHeight(), recording.getResolution()); log.info("Recording map color: {}", colorMap.toString()); isFine = this.checkVideoAverageRgbGreen(colorMap); } catch (IOException | JCodecException e) { log.warn("Error getting frame from video recording: {}", e.getMessage()); isFine = false; } return isFine; } private void checkIndividualRecording(String recPath, Recording recording, String audioDecoder, String videoDecoder) { // Should be only 2 files: zip and metadata File folder = new File(recPath); Assert.assertEquals(folder.listFiles().length, 2); File file1 = new File(recPath + recording.getName() + ".zip"); File file2 = new File(recPath + ".recording." + recording.getId()); Assert.assertTrue(file1.exists() && file1.length() > 0); Assert.assertTrue(file2.exists() && file2.length() > 0); List<File> unzippedWebmFiles = new Unzipper().unzipFile(recPath, recording.getName() + ".zip"); File jsonSyncFile = new File(recPath + recording.getName() + ".json"); Assert.assertTrue(jsonSyncFile.exists() && jsonSyncFile.length() > 0); JsonObject jsonSyncMetadata; try { Gson gson = new Gson(); JsonReader reader = new JsonReader(new FileReader(jsonSyncFile)); jsonSyncMetadata = gson.fromJson(reader, JsonObject.class); } catch (Exception e) { log.error("Cannot read JSON sync metadata file from {}. Error: {}", jsonSyncFile.getAbsolutePath(), e.getMessage()); Assert.fail(); return; } long totalFileSize = 0; JsonArray syncArray = jsonSyncMetadata.get("files").getAsJsonArray(); for (File webmFile : unzippedWebmFiles) { totalFileSize += webmFile.length(); Assert.assertTrue(webmFile.exists() && webmFile.length() > 0); double durationInSeconds = 0; boolean found = false; for (int i = 0; i < syncArray.size(); i++) { JsonObject j = syncArray.get(i).getAsJsonObject(); if (webmFile.getName().contains(j.get("streamId").getAsString())) { durationInSeconds = (double) (j.get("endTimeOffset").getAsDouble() - j.get("startTimeOffset").getAsDouble()) / 1000; found = true; break; } } Assert.assertTrue(found); log.info("Duration of {} according to sync metadata json file: {} s", webmFile.getName(), durationInSeconds); this.checkMultimediaFile(webmFile, recording.hasAudio(), recording.hasVideo(), durationInSeconds, recording.getResolution(), audioDecoder, videoDecoder); webmFile.delete(); } Assert.assertEquals(recording.getSize(), totalFileSize); jsonSyncFile.delete(); } private void checkMultimediaFile(File file, boolean hasAudio, boolean hasVideo, double duration, String resolution, String audioDecoder, String videoDecoder) { // Check tracks, duration, resolution, framerate and decoders MultimediaFileMetadata metadata = new MultimediaFileMetadata(file.getAbsolutePath()); if (hasVideo) { if (hasAudio) { Assert.assertTrue(metadata.hasAudio() && metadata.hasVideo()); Assert.assertTrue(metadata.getAudioDecoder().toLowerCase().contains(audioDecoder)); } else { Assert.assertTrue(metadata.hasVideo()); Assert.assertFalse(metadata.hasAudio()); } if (resolution != null) { Assert.assertEquals(resolution, metadata.getVideoWidth() + "x" + metadata.getVideoHeight()); } Assert.assertTrue(metadata.getVideoDecoder().toLowerCase().contains(videoDecoder)); } else if (hasAudio) { Assert.assertTrue(metadata.hasAudio()); Assert.assertFalse(metadata.hasVideo()); Assert.assertTrue(metadata.getAudioDecoder().toLowerCase().contains(audioDecoder)); } else { Assert.fail("Cannot check a file witho no audio and no video"); } // Check duration with 1 decimal precision DecimalFormat df = new DecimalFormat("#0.0"); df.setRoundingMode(RoundingMode.UP); log.info("Duration of {} according to ffmpeg: {} s", file.getName(), metadata.getDuration()); log.info("Duration of {} according to 'duration' property: {} s", file.getName(), duration); log.info("Difference in s duration: {}", Math.abs(metadata.getDuration() - duration)); Assert.assertTrue(Math.abs((metadata.getDuration() - duration)) < 0.25); } private boolean thumbnailIsFine(File file) { boolean isFine = false; BufferedImage image = null; try { image = ImageIO.read(file); } catch (IOException e) { log.error(e.getMessage()); return false; } log.info("Recording thumbnail dimensions: {}x{}", image.getWidth(), image.getHeight()); Map<String, Long> colorMap = this.averageColor(image); log.info("Thumbnail map color: {}", colorMap.toString()); isFine = this.checkVideoAverageRgbGreen(colorMap); return isFine; } private Map<String, Long> averageColor(BufferedImage bi) { int x0 = 0; int y0 = 0; int w = bi.getWidth(); int h = bi.getHeight(); int x1 = x0 + w; int y1 = y0 + h; long sumr = 0, sumg = 0, sumb = 0; for (int x = x0; x < x1; x++) { for (int y = y0; y < y1; y++) { Color pixel = new Color(bi.getRGB(x, y)); sumr += pixel.getRed(); sumg += pixel.getGreen(); sumb += pixel.getBlue(); } } int num = w * h; Map<String, Long> colorMap = new HashMap<>(); colorMap.put("r", (long) (sumr / num)); colorMap.put("g", (long) (sumg / num)); colorMap.put("b", (long) (sumb / num)); return colorMap; } }
openvidu-test-e2e: check composed audio-only duration fix
openvidu-test-e2e/src/test/java/io/openvidu/test/e2e/OpenViduTestAppE2eTest.java
openvidu-test-e2e: check composed audio-only duration fix
<ide><path>penvidu-test-e2e/src/test/java/io/openvidu/test/e2e/OpenViduTestAppE2eTest.java <ide> recPath = recordingsPath + SESSION_NAME + "-1/"; <ide> recording = new OpenVidu(OPENVIDU_URL, OPENVIDU_SECRET).getRecording(SESSION_NAME + "-1"); <ide> this.checkMultimediaFile(new File(recPath + recording.getName() + ".webm"), true, false, <del> recording.getDuration() * 1000, null, "opus", null); <add> recording.getDuration(), null, "opus", null); <ide> <ide> // Check video-only INDIVIDUAL recording <ide> recPath = recordingsPath + SESSION_NAME + "-2/";
Java
mit
e2fd6338d827bf571d53e273ce2e943c00a05672
0
opentdc/rates-service-opencrx
/** * The MIT License (MIT) * * Copyright (c) 2015 Arbalo AG * * 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. */ package org.opentdc.rates.opencrx; import java.util.List; import javax.naming.NamingException; import javax.servlet.ServletContext; import org.openmdx.base.exception.ServiceException; import org.opentdc.opencrx.AbstractOpencrxServiceProvider; import org.opentdc.rates.RatesModel; import org.opentdc.rates.ServiceProvider; import org.opentdc.service.exception.DuplicateException; import org.opentdc.service.exception.NotFoundException; public class OpencrxServiceProvider extends AbstractOpencrxServiceProvider implements ServiceProvider { public static final short ACTIVITY_GROUP_TYPE_PROJECT = 40; public static final short ACCOUNT_ROLE_CUSTOMER = 100; public static final short ACTIVITY_CLASS_INCIDENT = 2; public static final short ICAL_TYPE_NA = 0; public static final short ICAL_CLASS_NA = 0; public static final short ICAL_TYPE_VEVENT = 1; // instance variables // private static final Logger logger = Logger.getLogger(OpencrxServiceProvider.class.getName()); public OpencrxServiceProvider( ServletContext context, String prefix ) throws ServiceException, NamingException { super(context, prefix); } @Override public List<RatesModel> list(String queryType, String query, long position, long size) { // TODO Auto-generated method stub return null; } @Override public RatesModel create(RatesModel rate) throws DuplicateException { // TODO Auto-generated method stub return null; } @Override public RatesModel read(String id) throws NotFoundException { // TODO Auto-generated method stub return null; } @Override public RatesModel update(String id, RatesModel rate) throws NotFoundException { // TODO Auto-generated method stub return null; } @Override public void delete(String id) throws NotFoundException { // TODO Auto-generated method stub } }
src/java/org/opentdc/rates/opencrx/OpencrxServiceProvider.java
/** * The MIT License (MIT) * * Copyright (c) 2015 Arbalo AG * * 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. */ package org.opentdc.rates.opencrx; import java.util.List; import java.util.logging.Logger; import javax.naming.NamingException; import javax.servlet.ServletContext; import org.openmdx.base.exception.ServiceException; import org.opentdc.opencrx.AbstractOpencrxServiceProvider; import org.opentdc.rates.RatesModel; import org.opentdc.rates.ServiceProvider; import org.opentdc.service.exception.DuplicateException; import org.opentdc.service.exception.NotFoundException; public class OpencrxServiceProvider extends AbstractOpencrxServiceProvider implements ServiceProvider { public static final short ACTIVITY_GROUP_TYPE_PROJECT = 40; public static final short ACCOUNT_ROLE_CUSTOMER = 100; public static final short ACTIVITY_CLASS_INCIDENT = 2; public static final short ICAL_TYPE_NA = 0; public static final short ICAL_CLASS_NA = 0; public static final short ICAL_TYPE_VEVENT = 1; // instance variables // private static final Logger logger = Logger.getLogger(OpencrxServiceProvider.class.getName()); public OpencrxServiceProvider( ServletContext context, String prefix ) throws ServiceException, NamingException { super(context, prefix); } @Override public List<RatesModel> list(String queryType, String query, long position, long size) { // TODO Auto-generated method stub return null; } @Override public RatesModel create(RatesModel rate) throws DuplicateException { // TODO Auto-generated method stub return null; } @Override public RatesModel read(String id) throws NotFoundException { // TODO Auto-generated method stub return null; } @Override public RatesModel update(String id, RatesModel rate) throws NotFoundException { // TODO Auto-generated method stub return null; } @Override public void delete(String id) throws NotFoundException { // TODO Auto-generated method stub } }
remove some unused dependencies
src/java/org/opentdc/rates/opencrx/OpencrxServiceProvider.java
remove some unused dependencies
<ide><path>rc/java/org/opentdc/rates/opencrx/OpencrxServiceProvider.java <ide> package org.opentdc.rates.opencrx; <ide> <ide> import java.util.List; <del>import java.util.logging.Logger; <ide> <ide> import javax.naming.NamingException; <ide> import javax.servlet.ServletContext;
Java
apache-2.0
6b43b628adf411f6a7e472f78a90d13b656e597c
0
apache/juddi,apache/juddi,apache/juddi,apache/juddi,apache/juddi
/* * Copyright 2001-2009 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.juddi.v3.tck; import java.io.File; import java.io.FileInputStream; import java.net.URL; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertTrue; import java.rmi.RemoteException; import java.security.KeyStore; import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.Certificate; import java.util.Arrays; import java.util.List; import javax.xml.bind.JAXB; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.juddi.jaxb.EntityCreator; import org.junit.Assert; import org.uddi.api_v3.BusinessDetail; import org.uddi.api_v3.BusinessEntity; import org.uddi.api_v3.CategoryBag; import org.uddi.api_v3.DeleteBusiness; import org.uddi.api_v3.Description; import org.uddi.api_v3.GetBusinessDetail; import org.uddi.api_v3.KeyedReference; import org.uddi.api_v3.KeyedReferenceGroup; import org.uddi.api_v3.SaveBusiness; import org.uddi.v3_service.UDDIInquiryPortType; import org.uddi.v3_service.UDDIPublicationPortType; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * @author <a href="mailto:[email protected]">Kurt T Stam</a> * @author <a href="mailto:[email protected]">Jeff Faath</a> */ public class TckBusiness { final static String JOE_BUSINESS_XML = "uddi_data/joepublisher/businessEntity.xml"; final static String JOE_BUSINESS_KEY = "uddi:uddi.joepublisher.com:businessone"; final static String JOE_BUSINESS3_XML = "uddi_data/joepublisher/businessEntity3.xml"; final static String JOE_BUSINESS3_KEY = "uddi:uddi.joepublisher.com:businessthree.com"; final static String JOE_BUSINESS_MOVE_XML = "uddi_data/joepublisher/moveBusinessService1to3.xml"; final static String MARY_BUSINESS_XML = "uddi_data/marypublisher/businessEntity.xml"; final static String MARY_BUSINESS_KEY = "uddi:uddi.marypublisher.com:marybusinessone"; final static String SAM_BUSINESS_XML = "uddi_data/samsyndicator/businessEntity.xml"; final static String SAM_BUSINESS_WITHPROJECTION_XML = "uddi_data/samsyndicator/businessEntity_withProjection.xml"; final static String SAM_BUSINESS_KEY = "uddi:www.samco.com:samco"; final static String COMBINE_CATBAGS_BIZ_XML = "uddi_data/joepublisher/combineCatBagsBusinessServices.xml"; final static String COMBINE_CATBAGS_BIZ_KEY = "uddi:uddi.joepublisher.com:business01"; public final static String RIFTSAW_BUSINESS_KEY = "uddi:riftsaw.jboss.org:business_redhat-jboss"; public final static String RIFTSAW_BUSINESS_XML = "uddi_data/bpel/riftsaw/businessEntity.xml"; final static String SIGNATURE_KEYSTORE = "uddi_data/signature/signature.jks"; final static String SIGNATURE_KEYSTORE_TYPE = "JKS"; final static String SIGNATURE_KEYSTORE_PASSWORD = "changeit"; final static String SIGNATURE_KEYSTORE_ALIAS = "mykey"; private Log logger = LogFactory.getLog(this.getClass()); private UDDIPublicationPortType publication = null; private UDDIInquiryPortType inquiry = null; public TckBusiness(UDDIPublicationPortType publication, UDDIInquiryPortType inquiry) { super(); this.publication = publication; this.inquiry = inquiry; } public void saveSamSyndicatorBusiness(String authInfoSam) { saveBusiness(authInfoSam, SAM_BUSINESS_XML, SAM_BUSINESS_KEY); } public void saveSamSyndicatorBusinesses(String authInfoSam, int numberOfCopies) { saveBusinesses(authInfoSam, SAM_BUSINESS_XML, SAM_BUSINESS_KEY, numberOfCopies); } public void saveSamSyndicatorBusinessWithProjection(String authInfoSam) { saveBusiness(authInfoSam, SAM_BUSINESS_WITHPROJECTION_XML, SAM_BUSINESS_KEY); } public void deleteSamSyndicatorBusiness(String authInfoSam) { deleteBusiness(authInfoSam, SAM_BUSINESS_XML, SAM_BUSINESS_KEY); } public void deleteSamSyndicatorBusinesses(String authInfoSam, int numberOfCopies) { deleteBusinesses(authInfoSam, SAM_BUSINESS_XML, SAM_BUSINESS_KEY, numberOfCopies); } public void saveJoePublisherBusinessX509Signature(String authInfoJoe) { saveBusiness(authInfoJoe, JOE_BUSINESS_XML, JOE_BUSINESS_KEY); signBusiness(authInfoJoe, JOE_BUSINESS_KEY); verifyBusinessSignature(authInfoJoe, JOE_BUSINESS_KEY); } public void saveJoePublisherBusiness(String authInfoJoe) { saveBusiness(authInfoJoe, JOE_BUSINESS_XML, JOE_BUSINESS_KEY, true); } public void saveCombineCatBagsPublisherBusiness(String authInfoJoe) { saveBusiness(authInfoJoe, COMBINE_CATBAGS_BIZ_XML, COMBINE_CATBAGS_BIZ_KEY); } public void saveJoePublisherBusiness3(String authInfoJoe) { saveBusiness(authInfoJoe, JOE_BUSINESS3_XML, JOE_BUSINESS3_KEY); } public void saveJoePublisherBusiness1to3(String authInfoJoe) { saveBusiness(authInfoJoe, JOE_BUSINESS_MOVE_XML, JOE_BUSINESS3_KEY); } public void saveMaryPublisherBusiness(String authInfoMary) { saveBusiness(authInfoMary, MARY_BUSINESS_XML, MARY_BUSINESS_KEY); } public void updateJoePublisherBusiness(String authInfoJoe) { updateBusiness(authInfoJoe, JOE_BUSINESS_XML, JOE_BUSINESS_KEY); } public void saveJoePublisherBusinesses(String authInfoJoe, int numberOfCopies) { saveBusinesses(authInfoJoe, JOE_BUSINESS_XML, JOE_BUSINESS_KEY, numberOfCopies); } public void deleteJoePublisherBusiness(String authInfoJoe) { deleteBusiness(authInfoJoe, JOE_BUSINESS_XML, JOE_BUSINESS_KEY); } public void deleteJoePublisherBusiness3(String authInfoJoe) { deleteBusiness(authInfoJoe, JOE_BUSINESS3_XML, JOE_BUSINESS3_KEY); } public void deleteMaryPublisherBusiness(String authInfoMary) { deleteBusiness(authInfoMary, MARY_BUSINESS_XML, MARY_BUSINESS_KEY); } public void deleteJoePublisherBusinesses(String authInfoJoe, int numberOfCopies) { deleteBusinesses(authInfoJoe, JOE_BUSINESS_XML, JOE_BUSINESS_KEY, numberOfCopies); } public void checkServicesBusinessOne(int expectedNumberOfServices) { checkNumberOfServices(JOE_BUSINESS_KEY,expectedNumberOfServices); } public void checkServicesBusinessThree(int expectedNumberOfServices) { checkNumberOfServices(JOE_BUSINESS3_KEY,expectedNumberOfServices); } public void saveBusinesses(String authInfo, String businessXML, String businessKey, int numberOfCopies) { try { BusinessEntity beIn = (BusinessEntity)EntityCreator.buildFromDoc(businessXML, "org.uddi.api_v3"); String businessName = beIn.getName().get(0).getValue(); for (int i=0; i<numberOfCopies; i++) { SaveBusiness sb = new SaveBusiness(); sb.setAuthInfo(authInfo); beIn.getName().get(0).setValue(businessName + "-" + i); beIn.setBusinessKey(businessKey + "-" + i); sb.getBusinessEntity().add(beIn); publication.saveBusiness(sb); logger.debug("Saved business with key " + businessName + "-" + i); } } catch(Throwable e) { logger.error(e.getMessage(),e); Assert.fail("No exception should be thrown"); } } public void checkNumberOfServices(String businessKey, int expectedServices) { try { GetBusinessDetail gb = new GetBusinessDetail(); gb.getBusinessKey().add(businessKey); BusinessDetail bd; bd = inquiry.getBusinessDetail(gb); List<BusinessEntity> beOutList = bd.getBusinessEntity(); BusinessEntity beOut = beOutList.get(0); if (expectedServices > 0) { assertEquals(expectedServices, beOut.getBusinessServices().getBusinessService().size()); } else { Assert.assertNull(beOut.getBusinessServices()); } } catch (RemoteException e) { logger.error(e.getMessage(),e); Assert.fail("No exception should be thrown"); } } public void signBusiness(String authInfo, String businessKey) { try { GetBusinessDetail gb = new GetBusinessDetail(); gb.getBusinessKey().add(businessKey); BusinessDetail bd = inquiry.getBusinessDetail(gb); List<BusinessEntity> beOutList = bd.getBusinessEntity(); BusinessEntity bizEntity = beOutList.get(0); bizEntity.getSignature().clear(); BusinessEntity bizEntitySigned = signJAXBObject(bizEntity); SaveBusiness sb = new SaveBusiness(); sb.setAuthInfo(authInfo); sb.getBusinessEntity().add(bizEntitySigned); publication.saveBusiness(sb); } catch(Throwable e) { logger.error(e.getMessage(),e); Assert.fail("No exception should be thrown"); } } public void verifyBusinessSignature(String authInfo, String businessKey) { try { GetBusinessDetail gb = new GetBusinessDetail(); gb.getBusinessKey().add(businessKey); BusinessDetail bd = inquiry.getBusinessDetail(gb); List<BusinessEntity> beOutList = bd.getBusinessEntity(); BusinessEntity bizEntity = beOutList.get(0); boolean sigOk = verifySignedJAXBObject(bizEntity); assertTrue("Signature invalid!", sigOk); } catch(Throwable e) { logger.error(e.getMessage(),e); Assert.fail("No exception should be thrown"); } } private <T> T signJAXBObject(T jaxbObj) { DOMResult domResult = new DOMResult(); JAXB.marshal(jaxbObj, domResult); Document doc = ((Document)domResult.getNode()); Element docElement = doc.getDocumentElement(); try { KeyStore ks = KeyStore.getInstance(SIGNATURE_KEYSTORE_TYPE); URL url = Thread.currentThread().getContextClassLoader().getResource(SIGNATURE_KEYSTORE); ks.load(url.openStream(), SIGNATURE_KEYSTORE_PASSWORD.toCharArray()); KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry)ks.getEntry(SIGNATURE_KEYSTORE_ALIAS, new KeyStore.PasswordProtection(SIGNATURE_KEYSTORE_PASSWORD.toCharArray())); PrivateKey privateKey = keyEntry.getPrivateKey(); Certificate origCert = keyEntry.getCertificate(); PublicKey validatingKey = origCert.getPublicKey(); TckSigningUtil.signDOM(docElement, privateKey, origCert); DOMSource domSource = new DOMSource(doc); T result = (T)JAXB.unmarshal(domSource, jaxbObj.getClass()); return result; } catch (Exception e) { throw new RuntimeException("Signature failure due to: " + e.getMessage(), e); } } private boolean verifySignedJAXBObject(Object obj) { try { DOMResult domResult = new DOMResult(); JAXB.marshal(obj, domResult); Document doc = ((Document)domResult.getNode()); Element docElement = doc.getDocumentElement(); KeyStore ks = KeyStore.getInstance(SIGNATURE_KEYSTORE_TYPE); URL url = Thread.currentThread().getContextClassLoader().getResource(SIGNATURE_KEYSTORE); ks.load(url.openStream(), SIGNATURE_KEYSTORE_PASSWORD.toCharArray()); KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry)ks.getEntry(SIGNATURE_KEYSTORE_ALIAS, new KeyStore.PasswordProtection(SIGNATURE_KEYSTORE_PASSWORD.toCharArray())); PrivateKey privateKey = keyEntry.getPrivateKey(); Certificate origCert = keyEntry.getCertificate(); PublicKey validatingKey = origCert.getPublicKey(); return TckSigningUtil.verifySignature(docElement, validatingKey); } catch (Exception e) { throw new RuntimeException (e); } } public void saveBusiness(String authInfo, String businessXML, String businessKey) { saveBusiness(authInfo, businessXML, businessKey, true); } public void saveBusiness(String authInfo, String businessXML, String businessKey, boolean serialize) { try { SaveBusiness sb = new SaveBusiness(); sb.setAuthInfo(authInfo); BusinessEntity beIn = (BusinessEntity)EntityCreator.buildFromDoc(businessXML, "org.uddi.api_v3"); sb.getBusinessEntity().add(beIn); BusinessDetail saveBusiness = publication.saveBusiness(sb); logger.info("Business saved with key " + saveBusiness.getBusinessEntity().get(0).getBusinessKey()); // Now get the entity and check the values GetBusinessDetail gb = new GetBusinessDetail(); gb.getBusinessKey().add(businessKey); BusinessDetail bd = inquiry.getBusinessDetail(gb); List<BusinessEntity> beOutList = bd.getBusinessEntity(); BusinessEntity beOut = beOutList.get(0); if (serialize) { JAXB.marshal(beOut, new File("target/aftersave.xml")); } assertEquals(beIn.getBusinessKey(), beOut.getBusinessKey()); TckValidator.checkNames(beIn.getName(), beOut.getName()); TckValidator.checkDescriptions(beIn.getDescription(), beOut.getDescription()); TckValidator.checkDiscoveryUrls(beIn.getDiscoveryURLs(), beOut.getDiscoveryURLs()); TckValidator.checkContacts(beIn.getContacts(), beOut.getContacts()); TckValidator.checkCategories(beIn.getCategoryBag(), beOut.getCategoryBag()); TckValidator.checkSignatures(beIn.getSignature(), beOut.getSignature()); } catch(Throwable e) { logger.error(e.getMessage(),e); Assert.fail("No exception should be thrown"); } } public void updateBusiness(String authInfo, String businessXML, String businessKey) { try { // Now get the entity and check the values GetBusinessDetail gb = new GetBusinessDetail(); gb.getBusinessKey().add(businessKey); BusinessDetail bd = inquiry.getBusinessDetail(gb); List<BusinessEntity> beOutList = bd.getBusinessEntity(); BusinessEntity beOut = beOutList.get(0); //We are expecting 2 services assertEquals(2,beOut.getBusinessServices().getBusinessService().size()); //Now updating the business by adding another description SaveBusiness sb = new SaveBusiness(); sb.setAuthInfo(authInfo); BusinessEntity beIn = beOut; Description desc2= new Description(); desc2.setLang("nl"); desc2.setValue("Omschrijving"); beIn.getDescription().add(desc2); sb.getBusinessEntity().add(beIn); publication.saveBusiness(sb); // Now get the entity and check the values BusinessDetail bdnew = inquiry.getBusinessDetail(gb); List<BusinessEntity> beOutListNew = bdnew.getBusinessEntity(); BusinessEntity beOutNew = beOutListNew.get(0); assertEquals(beIn.getBusinessKey(), beOutNew.getBusinessKey()); // After the update we still are supposed to see two services. assertNotNull(beOutNew.getBusinessServices()); assertEquals(2,beOutNew.getBusinessServices().getBusinessService().size()); } catch(Throwable e) { logger.error(e.getMessage(),e); Assert.fail("No exception should be thrown"); } } public void deleteBusinesses(String authInfo, String businessXML, String businessKey, int numberOfCopies) { try { for (int i=0; i<numberOfCopies; i++) { // Delete the entity and make sure it is removed String key = businessKey + "-" + i; DeleteBusiness db = new DeleteBusiness(); db.setAuthInfo(authInfo); db.getBusinessKey().add(key); publication.deleteBusiness(db); logger.debug("Deleted business with key " + key); } } catch(Exception e) { logger.error(e.getMessage(),e); Assert.fail("No exception should be thrown"); } } public void deleteBusiness(String authInfo, String businessXML, String businessKey) { try { // Delete the entity and make sure it is removed DeleteBusiness db = new DeleteBusiness(); db.setAuthInfo(authInfo); db.getBusinessKey().add(businessKey); publication.deleteBusiness(db); } catch(Exception e) { logger.error(e.getMessage(),e); Assert.fail("No exception should be thrown"); } } }
uddi-tck-base/src/main/java/org/apache/juddi/v3/tck/TckBusiness.java
/* * Copyright 2001-2009 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.juddi.v3.tck; import java.io.File; import java.io.FileInputStream; import java.net.URL; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertTrue; import java.rmi.RemoteException; import java.security.KeyStore; import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.Certificate; import java.util.Arrays; import java.util.List; import javax.xml.bind.JAXB; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.juddi.jaxb.EntityCreator; import org.junit.Assert; import org.uddi.api_v3.BusinessDetail; import org.uddi.api_v3.BusinessEntity; import org.uddi.api_v3.CategoryBag; import org.uddi.api_v3.DeleteBusiness; import org.uddi.api_v3.Description; import org.uddi.api_v3.GetBusinessDetail; import org.uddi.api_v3.KeyedReference; import org.uddi.api_v3.KeyedReferenceGroup; import org.uddi.api_v3.SaveBusiness; import org.uddi.v3_service.UDDIInquiryPortType; import org.uddi.v3_service.UDDIPublicationPortType; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * @author <a href="mailto:[email protected]">Kurt T Stam</a> * @author <a href="mailto:[email protected]">Jeff Faath</a> */ public class TckBusiness { final static String JOE_BUSINESS_XML = "uddi_data/joepublisher/businessEntity.xml"; final static String JOE_BUSINESS_KEY = "uddi:uddi.joepublisher.com:businessone"; final static String JOE_BUSINESS3_XML = "uddi_data/joepublisher/businessEntity3.xml"; final static String JOE_BUSINESS3_KEY = "uddi:uddi.joepublisher.com:businessthree.com"; final static String JOE_BUSINESS_MOVE_XML = "uddi_data/joepublisher/moveBusinessService1to3.xml"; final static String MARY_BUSINESS_XML = "uddi_data/marypublisher/businessEntity.xml"; final static String MARY_BUSINESS_KEY = "uddi:uddi.marypublisher.com:marybusinessone"; final static String SAM_BUSINESS_XML = "uddi_data/samsyndicator/businessEntity.xml"; final static String SAM_BUSINESS_WITHPROJECTION_XML = "uddi_data/samsyndicator/businessEntity_withProjection.xml"; final static String SAM_BUSINESS_KEY = "uddi:www.samco.com:samco"; final static String COMBINE_CATBAGS_BIZ_XML = "uddi_data/joepublisher/combineCatBagsBusinessServices.xml"; final static String COMBINE_CATBAGS_BIZ_KEY = "uddi:uddi.joepublisher.com:business01"; public final static String RIFTSAW_BUSINESS_KEY = "uddi:riftsaw.jboss.org:business_redhat-jboss"; public final static String RIFTSAW_BUSINESS_XML = "uddi_data/bpel/riftsaw/businessEntity.xml"; final static String SIGNATURE_KEYSTORE = "uddi_data/signature/signature.jks"; final static String SIGNATURE_KEYSTORE_TYPE = "JKS"; final static String SIGNATURE_KEYSTORE_PASSWORD = "changeit"; final static String SIGNATURE_KEYSTORE_ALIAS = "mykey"; private Log logger = LogFactory.getLog(this.getClass()); private UDDIPublicationPortType publication = null; private UDDIInquiryPortType inquiry = null; public TckBusiness(UDDIPublicationPortType publication, UDDIInquiryPortType inquiry) { super(); this.publication = publication; this.inquiry = inquiry; } public void saveSamSyndicatorBusiness(String authInfoSam) { saveBusiness(authInfoSam, SAM_BUSINESS_XML, SAM_BUSINESS_KEY); } public void saveSamSyndicatorBusinesses(String authInfoSam, int numberOfCopies) { saveBusinesses(authInfoSam, SAM_BUSINESS_XML, SAM_BUSINESS_KEY, numberOfCopies); } public void saveSamSyndicatorBusinessWithProjection(String authInfoSam) { saveBusiness(authInfoSam, SAM_BUSINESS_WITHPROJECTION_XML, SAM_BUSINESS_KEY); } public void deleteSamSyndicatorBusiness(String authInfoSam) { deleteBusiness(authInfoSam, SAM_BUSINESS_XML, SAM_BUSINESS_KEY); } public void deleteSamSyndicatorBusinesses(String authInfoSam, int numberOfCopies) { deleteBusinesses(authInfoSam, SAM_BUSINESS_XML, SAM_BUSINESS_KEY, numberOfCopies); } public void saveJoePublisherBusinessX509Signature(String authInfoJoe) { saveBusiness(authInfoJoe, JOE_BUSINESS_XML, JOE_BUSINESS_KEY); signBusiness(authInfoJoe, JOE_BUSINESS_KEY); verifyBusinessSignature(authInfoJoe, JOE_BUSINESS_KEY); } public void saveJoePublisherBusiness(String authInfoJoe) { saveBusiness(authInfoJoe, JOE_BUSINESS_XML, JOE_BUSINESS_KEY, true); } public void saveCombineCatBagsPublisherBusiness(String authInfoJoe) { saveBusiness(authInfoJoe, COMBINE_CATBAGS_BIZ_XML, COMBINE_CATBAGS_BIZ_KEY); } public void saveJoePublisherBusiness3(String authInfoJoe) { saveBusiness(authInfoJoe, JOE_BUSINESS3_XML, JOE_BUSINESS3_KEY); } public void saveJoePublisherBusiness1to3(String authInfoJoe) { saveBusiness(authInfoJoe, JOE_BUSINESS_MOVE_XML, JOE_BUSINESS3_KEY); } public void saveMaryPublisherBusiness(String authInfoMary) { saveBusiness(authInfoMary, MARY_BUSINESS_XML, MARY_BUSINESS_KEY); } public void updateJoePublisherBusiness(String authInfoJoe) { updateBusiness(authInfoJoe, JOE_BUSINESS_XML, JOE_BUSINESS_KEY); } public void saveJoePublisherBusinesses(String authInfoJoe, int numberOfCopies) { saveBusinesses(authInfoJoe, JOE_BUSINESS_XML, JOE_BUSINESS_KEY, numberOfCopies); } public void deleteJoePublisherBusiness(String authInfoJoe) { deleteBusiness(authInfoJoe, JOE_BUSINESS_XML, JOE_BUSINESS_KEY); } public void deleteJoePublisherBusiness3(String authInfoJoe) { deleteBusiness(authInfoJoe, JOE_BUSINESS3_XML, JOE_BUSINESS3_KEY); } public void deleteMaryPublisherBusiness(String authInfoMary) { deleteBusiness(authInfoMary, MARY_BUSINESS_XML, MARY_BUSINESS_KEY); } public void deleteJoePublisherBusinesses(String authInfoJoe, int numberOfCopies) { deleteBusinesses(authInfoJoe, JOE_BUSINESS_XML, JOE_BUSINESS_KEY, numberOfCopies); } public void checkServicesBusinessOne(int expectedNumberOfServices) { checkNumberOfServices(JOE_BUSINESS_KEY,expectedNumberOfServices); } public void checkServicesBusinessThree(int expectedNumberOfServices) { checkNumberOfServices(JOE_BUSINESS3_KEY,expectedNumberOfServices); } public void saveBusinesses(String authInfo, String businessXML, String businessKey, int numberOfCopies) { try { BusinessEntity beIn = (BusinessEntity)EntityCreator.buildFromDoc(businessXML, "org.uddi.api_v3"); String businessName = beIn.getName().get(0).getValue(); for (int i=0; i<numberOfCopies; i++) { SaveBusiness sb = new SaveBusiness(); sb.setAuthInfo(authInfo); beIn.getName().get(0).setValue(businessName + "-" + i); beIn.setBusinessKey(businessKey + "-" + i); sb.getBusinessEntity().add(beIn); publication.saveBusiness(sb); logger.debug("Saved business with key " + businessName + "-" + i); } } catch(Throwable e) { logger.error(e.getMessage(),e); Assert.fail("No exception should be thrown"); } } public void checkNumberOfServices(String businessKey, int expectedServices) { try { GetBusinessDetail gb = new GetBusinessDetail(); gb.getBusinessKey().add(businessKey); BusinessDetail bd; bd = inquiry.getBusinessDetail(gb); List<BusinessEntity> beOutList = bd.getBusinessEntity(); BusinessEntity beOut = beOutList.get(0); if (expectedServices > 0) { assertEquals(expectedServices, beOut.getBusinessServices().getBusinessService().size()); } else { Assert.assertNull(beOut.getBusinessServices()); } } catch (RemoteException e) { logger.error(e.getMessage(),e); Assert.fail("No exception should be thrown"); } } public void signBusiness(String authInfo, String businessKey) { try { GetBusinessDetail gb = new GetBusinessDetail(); gb.getBusinessKey().add(businessKey); BusinessDetail bd = inquiry.getBusinessDetail(gb); List<BusinessEntity> beOutList = bd.getBusinessEntity(); BusinessEntity bizEntity = beOutList.get(0); bizEntity.getSignature().clear(); BusinessEntity bizEntitySigned = signJAXBObject(bizEntity); SaveBusiness sb = new SaveBusiness(); sb.setAuthInfo(authInfo); sb.getBusinessEntity().add(bizEntitySigned); publication.saveBusiness(sb); } catch(Throwable e) { logger.error(e.getMessage(),e); Assert.fail("No exception should be thrown"); } } public void verifyBusinessSignature(String authInfo, String businessKey) { try { GetBusinessDetail gb = new GetBusinessDetail(); gb.getBusinessKey().add(businessKey); BusinessDetail bd = inquiry.getBusinessDetail(gb); List<BusinessEntity> beOutList = bd.getBusinessEntity(); BusinessEntity bizEntity = beOutList.get(0); boolean sigOk = verifySignedJAXBObject(bizEntity); assertTrue("Signature invalid!", sigOk); } catch(Throwable e) { logger.error(e.getMessage(),e); Assert.fail("No exception should be thrown"); } } private <T> T signJAXBObject(T jaxbObj) { DOMResult domResult = new DOMResult(); JAXB.marshal(jaxbObj, domResult); Document doc = ((Document)domResult.getNode()); Element docElement = doc.getDocumentElement(); try { KeyStore ks = KeyStore.getInstance(SIGNATURE_KEYSTORE_TYPE); URL url = Thread.currentThread().getContextClassLoader().getResource(SIGNATURE_KEYSTORE); ks.load(url.openStream(), SIGNATURE_KEYSTORE_PASSWORD.toCharArray()); KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry)ks.getEntry(SIGNATURE_KEYSTORE_ALIAS, new KeyStore.PasswordProtection(SIGNATURE_KEYSTORE_PASSWORD.toCharArray())); PrivateKey privateKey = keyEntry.getPrivateKey(); Certificate origCert = keyEntry.getCertificate(); PublicKey validatingKey = origCert.getPublicKey(); TckSigningUtil.signDOM(docElement, privateKey, origCert); DOMSource domSource = new DOMSource(doc); T result = (T)JAXB.unmarshal(domSource, jaxbObj.getClass()); return result; } catch (Exception e) { throw new RuntimeException("Signature failure due to: " + e.getMessage(), e); } } private boolean verifySignedJAXBObject(Object obj) { try { DOMResult domResult = new DOMResult(); JAXB.marshal(obj, domResult); Document doc = ((Document)domResult.getNode()); Element docElement = doc.getDocumentElement(); KeyStore ks = KeyStore.getInstance(SIGNATURE_KEYSTORE_TYPE); URL url = Thread.currentThread().getContextClassLoader().getResource(SIGNATURE_KEYSTORE); ks.load(url.openStream(), SIGNATURE_KEYSTORE_PASSWORD.toCharArray()); KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry)ks.getEntry(SIGNATURE_KEYSTORE_ALIAS, new KeyStore.PasswordProtection(SIGNATURE_KEYSTORE_PASSWORD.toCharArray())); PrivateKey privateKey = keyEntry.getPrivateKey(); Certificate origCert = keyEntry.getCertificate(); PublicKey validatingKey = origCert.getPublicKey(); return TckSigningUtil.verifySignature(docElement, validatingKey); } catch (Exception e) { throw new RuntimeException (e); } } public void saveBusiness(String authInfo, String businessXML, String businessKey) { saveBusiness(authInfo, businessXML, businessKey, false); } public void saveBusiness(String authInfo, String businessXML, String businessKey, boolean serialize) { try { SaveBusiness sb = new SaveBusiness(); sb.setAuthInfo(authInfo); BusinessEntity beIn = (BusinessEntity)EntityCreator.buildFromDoc(businessXML, "org.uddi.api_v3"); sb.getBusinessEntity().add(beIn); publication.saveBusiness(sb); // Now get the entity and check the values GetBusinessDetail gb = new GetBusinessDetail(); gb.getBusinessKey().add(businessKey); BusinessDetail bd = inquiry.getBusinessDetail(gb); List<BusinessEntity> beOutList = bd.getBusinessEntity(); BusinessEntity beOut = beOutList.get(0); if (serialize) { JAXB.marshal(beOut, new File("target/aftersave.xml")); } assertEquals(beIn.getBusinessKey(), beOut.getBusinessKey()); TckValidator.checkNames(beIn.getName(), beOut.getName()); TckValidator.checkDescriptions(beIn.getDescription(), beOut.getDescription()); TckValidator.checkDiscoveryUrls(beIn.getDiscoveryURLs(), beOut.getDiscoveryURLs()); TckValidator.checkContacts(beIn.getContacts(), beOut.getContacts()); TckValidator.checkCategories(beIn.getCategoryBag(), beOut.getCategoryBag()); TckValidator.checkSignatures(beIn.getSignature(), beOut.getSignature()); } catch(Throwable e) { logger.error(e.getMessage(),e); Assert.fail("No exception should be thrown"); } } public void updateBusiness(String authInfo, String businessXML, String businessKey) { try { // Now get the entity and check the values GetBusinessDetail gb = new GetBusinessDetail(); gb.getBusinessKey().add(businessKey); BusinessDetail bd = inquiry.getBusinessDetail(gb); List<BusinessEntity> beOutList = bd.getBusinessEntity(); BusinessEntity beOut = beOutList.get(0); //We are expecting 2 services assertEquals(2,beOut.getBusinessServices().getBusinessService().size()); //Now updating the business by adding another description SaveBusiness sb = new SaveBusiness(); sb.setAuthInfo(authInfo); BusinessEntity beIn = beOut; Description desc2= new Description(); desc2.setLang("nl"); desc2.setValue("Omschrijving"); beIn.getDescription().add(desc2); sb.getBusinessEntity().add(beIn); publication.saveBusiness(sb); // Now get the entity and check the values BusinessDetail bdnew = inquiry.getBusinessDetail(gb); List<BusinessEntity> beOutListNew = bdnew.getBusinessEntity(); BusinessEntity beOutNew = beOutListNew.get(0); assertEquals(beIn.getBusinessKey(), beOutNew.getBusinessKey()); // After the update we still are supposed to see two services. assertNotNull(beOutNew.getBusinessServices()); assertEquals(2,beOutNew.getBusinessServices().getBusinessService().size()); } catch(Throwable e) { logger.error(e.getMessage(),e); Assert.fail("No exception should be thrown"); } } public void deleteBusinesses(String authInfo, String businessXML, String businessKey, int numberOfCopies) { try { for (int i=0; i<numberOfCopies; i++) { // Delete the entity and make sure it is removed String key = businessKey + "-" + i; DeleteBusiness db = new DeleteBusiness(); db.setAuthInfo(authInfo); db.getBusinessKey().add(key); publication.deleteBusiness(db); logger.debug("Deleted business with key " + key); } } catch(Exception e) { logger.error(e.getMessage(),e); Assert.fail("No exception should be thrown"); } } public void deleteBusiness(String authInfo, String businessXML, String businessKey) { try { // Delete the entity and make sure it is removed DeleteBusiness db = new DeleteBusiness(); db.setAuthInfo(authInfo); db.getBusinessKey().add(businessKey); publication.deleteBusiness(db); } catch(Exception e) { logger.error(e.getMessage(),e); Assert.fail("No exception should be thrown"); } } }
JUDDI-644 adding additional debug info git-svn-id: 78f1a4f4f5508b22b762fadacf3de42e47fdef3b@1526850 13f79535-47bb-0310-9956-ffa450edef68
uddi-tck-base/src/main/java/org/apache/juddi/v3/tck/TckBusiness.java
JUDDI-644 adding additional debug info
<ide><path>ddi-tck-base/src/main/java/org/apache/juddi/v3/tck/TckBusiness.java <ide> } <ide> <ide> public void saveBusiness(String authInfo, String businessXML, String businessKey) { <del> saveBusiness(authInfo, businessXML, businessKey, false); <add> saveBusiness(authInfo, businessXML, businessKey, true); <ide> } <ide> public void saveBusiness(String authInfo, String businessXML, String businessKey, boolean serialize) { <ide> try { <ide> <ide> BusinessEntity beIn = (BusinessEntity)EntityCreator.buildFromDoc(businessXML, "org.uddi.api_v3"); <ide> sb.getBusinessEntity().add(beIn); <del> <del> publication.saveBusiness(sb); <add> BusinessDetail saveBusiness = publication.saveBusiness(sb); <add> logger.info("Business saved with key " + saveBusiness.getBusinessEntity().get(0).getBusinessKey()); <ide> <ide> // Now get the entity and check the values <ide> GetBusinessDetail gb = new GetBusinessDetail();
Java
apache-2.0
7eda33c2a070d37ffb16b088a2f71c0cd73c221d
0
grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation
package com.navigation.reactnative; import android.app.Activity; import android.app.ActivityOptions; import android.app.SharedElementCallback; import android.content.Intent; import android.content.res.TypedArray; import android.os.Build; import android.os.Bundle; import android.util.Pair; import android.view.View; import android.view.ViewGroup; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.views.image.ReactImageView; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; public class NavigationModule extends ReactContextBaseJavaModule { private HashMap<Integer, Intent> mIntents = new HashMap<>(); private int activityOpenEnterAnimationId; private int activityOpenExitAnimationId; private int activityCloseEnterAnimationId; private int activityCloseExitAnimationId; public NavigationModule(ReactApplicationContext reactContext) { super(reactContext); TypedArray activityStyle = getReactApplicationContext().getTheme().obtainStyledAttributes(new int[] {android.R.attr.windowAnimationStyle}); int windowAnimationStyleResId = activityStyle.getResourceId(0, 0); activityStyle.recycle(); activityStyle = getReactApplicationContext().getTheme().obtainStyledAttributes(windowAnimationStyleResId, new int[] { android.R.attr.activityOpenEnterAnimation, android.R.attr.activityOpenExitAnimation, android.R.attr.activityCloseEnterAnimation, android.R.attr.activityCloseExitAnimation }); activityOpenEnterAnimationId = activityStyle.getResourceId(0, 0); activityOpenExitAnimationId = activityStyle.getResourceId(1, 0); activityCloseEnterAnimationId = activityStyle.getResourceId(2, 0); activityCloseExitAnimationId = activityStyle.getResourceId(3, 0); activityStyle.recycle(); } @Override public String getName() { return "NavigationModule"; } @ReactMethod public void render(int crumb, int tab, ReadableArray titles, String appKey, ReadableArray sharedElementNames, final ReadableArray oldSharedElementNames, String enterAnim, String exitAnim) { final Activity currentActivity = getCurrentActivity(); if (mIntents.size() == 0) { mIntents.put(0, currentActivity.getIntent()); } int currentCrumb = mIntents.size() - 1; if (crumb < currentCrumb) { final Intent intent = mIntents.get(crumb); for(int i = crumb + 1; i <= currentCrumb; i++) { mIntents.remove(i); } final int enter = this.getAnimationResourceId(enterAnim, this.activityCloseEnterAnimationId); final int exit = this.getAnimationResourceId(exitAnim, this.activityCloseExitAnimationId); final HashMap<String, View> oldSharedElementsMap = getSharedElementsMap(); final Pair[] oldSharedElements = currentCrumb - crumb == 1 ? getSharedElements(oldSharedElementsMap, oldSharedElementNames) : null; currentActivity.runOnUiThread(new Runnable() { @Override public void run() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && oldSharedElements != null && oldSharedElements.length != 0) { currentActivity.setEnterSharedElementCallback(new SharedElementCallback() { @Override public void onMapSharedElements(List<String> names, Map<String, View> elements) { names.clear(); elements.clear(); for(int i = 0; i < oldSharedElementNames.size(); i++) { String name = oldSharedElementNames.getString(i); names.add(name); if (oldSharedElementsMap.containsKey(name)) elements.put(name, oldSharedElementsMap.get(name)); } } }); currentActivity.finishAfterTransition(); } else { currentActivity.navigateUpTo(intent); } currentActivity.overridePendingTransition(enter, exit); } }); } if (crumb > currentCrumb) { final Intent[] intents = new Intent[crumb - currentCrumb]; for(int i = 0; i < crumb - currentCrumb; i++) { int nextCrumb = currentCrumb + i + 1; Class scene = nextCrumb % 2 == 0 ? SceneActivity.class : AlternateSceneActivity.class; Intent intent = new Intent(getReactApplicationContext(), scene); intent.putExtra(SceneActivity.CRUMB, nextCrumb); intent.putExtra(SceneActivity.APP_KEY, appKey); mIntents.put(nextCrumb, intent); intents[i] = intent; } final int enter = this.getAnimationResourceId(enterAnim, this.activityOpenEnterAnimationId); final int exit = this.getAnimationResourceId(exitAnim, this.activityOpenExitAnimationId); final HashMap<String, View> sharedElementsMap = getSharedElementsMap(); final Pair[] sharedElements = crumb - currentCrumb == 1 ? getSharedElements(sharedElementsMap, sharedElementNames) : null; currentActivity.runOnUiThread(new Runnable() { @Override public void run() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && sharedElements != null && sharedElements.length != 0) { currentActivity.setExitSharedElementCallback(new SharedElementCallback() { @Override public void onSharedElementEnd(List<String> names, List<View> elements, List<View> snapshots) { for (View view : elements) { if (view instanceof ReactImageView) ((ReactImageView) view).getDrawable().setVisible(true, true); } } @Override public void onMapSharedElements(List<String> names, Map<String, View> elements) { elements.clear(); for(String name : names) { if (sharedElementsMap.containsKey(name)) elements.put(name, sharedElementsMap.get(name)); } } }); @SuppressWarnings("unchecked") Bundle bundle = ActivityOptions.makeSceneTransitionAnimation(currentActivity, sharedElements).toBundle(); currentActivity.startActivity(intents[0], bundle); } else { currentActivity.startActivities(intents); } currentActivity.overridePendingTransition(enter, exit); } }); } } private int getAnimationResourceId(String animationName, int defaultId) { if (animationName == null) return defaultId; String packageName = getReactApplicationContext().getPackageName(); return getReactApplicationContext().getResources().getIdentifier(animationName, "anim", packageName); } private HashMap<String, View> getSharedElementsMap() { View contentView = getCurrentActivity().findViewById(android.R.id.content); HashSet<View> sharedElements = SharedElementManager.getSharedElements(contentView.getRootView()); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP || sharedElements == null) return null; HashMap<String, View> sharedElementMap = new HashMap<>(); for(View sharedElement : sharedElements) { sharedElementMap.put(sharedElement.getTransitionName(), sharedElement); } return sharedElementMap; } private Pair[] getSharedElements(HashMap<String, View> sharedElementMap, ReadableArray sharedElementNames) { if (sharedElementMap == null || sharedElementNames == null) return null; ArrayList<Pair> sharedElementPairs = new ArrayList<>(); for(int i = 0; i < sharedElementNames.size(); i++) { String name = sharedElementNames.getString(i); if (sharedElementMap.containsKey(name)) sharedElementPairs.add(Pair.create(sharedElementMap.get(name), name)); } return sharedElementPairs.toArray(new Pair[sharedElementPairs.size()]); } }
NavigationReactNative/src/android/app/src/main/java/com/navigation/reactnative/NavigationModule.java
package com.navigation.reactnative; import android.app.Activity; import android.app.ActivityOptions; import android.app.SharedElementCallback; import android.content.Intent; import android.content.res.TypedArray; import android.os.Build; import android.os.Bundle; import android.util.Pair; import android.view.View; import android.view.ViewGroup; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.views.image.ReactImageView; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; public class NavigationModule extends ReactContextBaseJavaModule { private HashMap<Integer, Intent> mIntents = new HashMap<>(); private int activityOpenEnterAnimationId; private int activityOpenExitAnimationId; private int activityCloseEnterAnimationId; private int activityCloseExitAnimationId; public NavigationModule(ReactApplicationContext reactContext) { super(reactContext); TypedArray activityStyle = getReactApplicationContext().getTheme().obtainStyledAttributes(new int[] {android.R.attr.windowAnimationStyle}); int windowAnimationStyleResId = activityStyle.getResourceId(0, 0); activityStyle.recycle(); activityStyle = getReactApplicationContext().getTheme().obtainStyledAttributes(windowAnimationStyleResId, new int[] { android.R.attr.activityOpenEnterAnimation, android.R.attr.activityOpenExitAnimation, android.R.attr.activityCloseEnterAnimation, android.R.attr.activityCloseExitAnimation }); activityOpenEnterAnimationId = activityStyle.getResourceId(0, 0); activityOpenExitAnimationId = activityStyle.getResourceId(1, 0); activityCloseEnterAnimationId = activityStyle.getResourceId(2, 0); activityCloseExitAnimationId = activityStyle.getResourceId(3, 0); activityStyle.recycle(); } @Override public String getName() { return "NavigationModule"; } @ReactMethod public void render(int crumb, int tab, ReadableArray titles, String appKey, ReadableArray sharedElementNames, final ReadableArray oldSharedElementNames, String enterAnim, String exitAnim) { final Activity currentActivity = getCurrentActivity(); if (mIntents.size() == 0) { mIntents.put(0, currentActivity.getIntent()); } int currentCrumb = mIntents.size() - 1; if (crumb < currentCrumb) { final Intent intent = mIntents.get(crumb); for(int i = crumb + 1; i <= currentCrumb; i++) { mIntents.remove(i); } final int enter = this.getAnimationResourceId(enterAnim, this.activityCloseEnterAnimationId); final int exit = this.getAnimationResourceId(exitAnim, this.activityCloseExitAnimationId); final HashMap<String, View> oldSharedElementsMap = getSharedElementsMap(); final Pair[] oldSharedElements = currentCrumb - crumb == 1 ? getSharedElements(oldSharedElementsMap, oldSharedElementNames) : null; currentActivity.runOnUiThread(new Runnable() { @Override public void run() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && oldSharedElements != null && oldSharedElements.length != 0) { currentActivity.setEnterSharedElementCallback(new SharedElementCallback() { @Override public void onMapSharedElements(List<String> names, Map<String, View> elements) { names.clear(); elements.clear(); for(int i = 0; i < oldSharedElementNames.size(); i++) { String name = oldSharedElementNames.getString(i); names.add(name); if (oldSharedElementsMap.containsKey(name)) elements.put(name, oldSharedElementsMap.get(name)); } } }); currentActivity.finishAfterTransition(); } else { currentActivity.navigateUpTo(intent); } currentActivity.overridePendingTransition(enter, exit); } }); } if (crumb > currentCrumb) { final Intent[] intents = new Intent[crumb - currentCrumb]; for(int i = 0; i < crumb - currentCrumb; i++) { int nextCrumb = currentCrumb + i + 1; Class scene = nextCrumb % 2 == 0 ? SceneActivity.class : AlternateSceneActivity.class; Intent intent = new Intent(getReactApplicationContext(), scene); intent.putExtra(SceneActivity.CRUMB, nextCrumb); intent.putExtra(SceneActivity.APP_KEY, appKey); mIntents.put(nextCrumb, intent); intents[i] = intent; } final int enter = this.getAnimationResourceId(enterAnim, this.activityOpenEnterAnimationId); final int exit = this.getAnimationResourceId(exitAnim, this.activityOpenExitAnimationId); final HashMap<String, View> sharedElementsMap = getSharedElementsMap(); final Pair[] sharedElements = crumb - currentCrumb == 1 ? getSharedElements(sharedElementsMap, sharedElementNames) : null; currentActivity.runOnUiThread(new Runnable() { @Override public void run() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && sharedElements != null && sharedElements.length != 0) { currentActivity.setExitSharedElementCallback(new SharedElementCallback() { @Override public void onSharedElementEnd(List<String> names, List<View> elements, List<View> snapshots) { for (View view : elements) { View childView = ((ViewGroup) view).getChildAt(0); if (childView instanceof ReactImageView) ((ReactImageView) childView).getDrawable().setVisible(true, true); } } @Override public void onMapSharedElements(List<String> names, Map<String, View> elements) { elements.clear(); for(String name : names) { if (sharedElementsMap.containsKey(name)) elements.put(name, sharedElementsMap.get(name)); } } }); @SuppressWarnings("unchecked") Bundle bundle = ActivityOptions.makeSceneTransitionAnimation(currentActivity, sharedElements).toBundle(); currentActivity.startActivity(intents[0], bundle); } else { currentActivity.startActivities(intents); } currentActivity.overridePendingTransition(enter, exit); } }); } } private int getAnimationResourceId(String animationName, int defaultId) { if (animationName == null) return defaultId; String packageName = getReactApplicationContext().getPackageName(); return getReactApplicationContext().getResources().getIdentifier(animationName, "anim", packageName); } private HashMap<String, View> getSharedElementsMap() { View contentView = getCurrentActivity().findViewById(android.R.id.content); HashSet<View> sharedElements = SharedElementManager.getSharedElements(contentView.getRootView()); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP || sharedElements == null) return null; HashMap<String, View> sharedElementMap = new HashMap<>(); for(View sharedElement : sharedElements) { sharedElementMap.put(sharedElement.getTransitionName(), sharedElement); } return sharedElementMap; } private Pair[] getSharedElements(HashMap<String, View> sharedElementMap, ReadableArray sharedElementNames) { if (sharedElementMap == null || sharedElementNames == null) return null; ArrayList<Pair> sharedElementPairs = new ArrayList<>(); for(int i = 0; i < sharedElementNames.size(); i++) { String name = sharedElementNames.getString(i); if (sharedElementMap.containsKey(name)) sharedElementPairs.add(Pair.create(sharedElementMap.get(name), name)); } return sharedElementPairs.toArray(new Pair[sharedElementPairs.size()]); } }
Checked the shared element directly
NavigationReactNative/src/android/app/src/main/java/com/navigation/reactnative/NavigationModule.java
Checked the shared element directly
<ide><path>avigationReactNative/src/android/app/src/main/java/com/navigation/reactnative/NavigationModule.java <ide> @Override <ide> public void onSharedElementEnd(List<String> names, List<View> elements, List<View> snapshots) { <ide> for (View view : elements) { <del> View childView = ((ViewGroup) view).getChildAt(0); <del> if (childView instanceof ReactImageView) <del> ((ReactImageView) childView).getDrawable().setVisible(true, true); <add> if (view instanceof ReactImageView) <add> ((ReactImageView) view).getDrawable().setVisible(true, true); <ide> } <ide> } <ide> @Override
Java
mit
c38bbc5a67772d8ca6fc3445461cb47b6556050b
0
hermanbanken/RxFiddle,hermanbanken/RxFiddle,hermanbanken/RxFiddle,hermanbanken/RxFiddle,hermanbanken/RxFiddle
package nl.hermanbanken.rxfiddle; import jdk.internal.org.objectweb.asm.Type; import nl.hermanbanken.rxfiddle.data.Invoke; import nl.hermanbanken.rxfiddle.data.InvokeResult; import nl.hermanbanken.rxfiddle.data.Label; import nl.hermanbanken.rxfiddle.data.RuntimeEvent; import nl.hermanbanken.rxfiddle.visualiser.StdOutVisualizer; import nl.hermanbanken.rxfiddle.visualiser.Visualizer; import java.util.*; import java.util.concurrent.ArrayBlockingQueue; /** * Hook for instrumented classes * * @see <a href="https://www.youtube.com/watch?v=y4Ex6bsTv3k">ScalaDays 2015 Amsterdam presentation by Tal Weiss</a> * @see <a href="http://www.slideshare.net/Takipi/advanced-production-debugging#33">Relevant slide from presentation</a> * */ @SuppressWarnings({"WeakerAccess", "unused"}) public class Hook { public static Visualizer visualizer = new StdOutVisualizer(); public static final Stack<Label> labels = new Stack<>(); public static final Queue<Label> labelsForGrab = new ArrayBlockingQueue<>(1000); public static final Stack<Invoke> invokes = new Stack<>(); public static volatile Label currentLabel = null; public static volatile Invoke currentInvoke = null; public static HashMap<Label, ArrayList<Invoke>> results = new HashMap<>(); public static HashSet<Object> followed = new HashSet<>(); static { visualizer.logRun(System.nanoTime()); } public static class Constants { public static final String CLASS_NAME = Type.getInternalName(Hook.class); public static final String HOOK_METHOD_NAME = "libraryHook"; public static final String HOOK_METHOD_DESC = "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;Z)V"; public static final String LEAVE_METHOD_NAME = "leave"; public static final String LEAVE_METHOD_DESC = "(Ljava/lang/Object;)V"; public static final String ENTER_METHOD_NAME = "enter"; public static final String ENTER_METHOD_DESC = "(Ljava/lang/String;Ljava/lang/String;I)V"; } /** Usage of Rx **/ public static void libraryHook( Object subject, String className, String methodName, boolean fromLambda) { if (className.startsWith("rx/plugins") || className.startsWith("rx/internal")) return; // Runtime events if (followed.contains(subject) && (methodName.equals("request") || methodName.startsWith("subscribe") || methodName.startsWith("on"))) { System.out.printf("On followed subject %s: %s\n", subject, methodName); visualizer.logRuntime(new RuntimeEvent(subject, className, methodName)); } else if (methodName.startsWith("subscribe") || methodName.startsWith("on") || methodName.startsWith("unsubscribe")) { System.err.printf("Ignored runtime event %s %s %s\n", subject, className, methodName); } // Setup events if (labelsForGrab.isEmpty()) return; if (subject != null) follow(subject); Invoke invoke = new Invoke(subject, className, methodName, labelsForGrab.poll()); invokes.push(invoke); visualizer.logInvoke(invoke); } /** Tracing **/ public static void enter(String className, String methodName, int lineNumber) { Label label = new Label(className, methodName, lineNumber); labels.add(label); labelsForGrab.offer(label); } public static void leave(Object result) { labels.pop(); visualizer.logResult(new InvokeResult(invokes.isEmpty() ? null : invokes.pop(), result)); follow(result); } public static void follow(Object obj) { if (obj == null) return; if (obj.getClass().getName().startsWith("rx/internal") || obj.getClass().getName().startsWith("rx.internal")) { // System.out.printf("Not following %s", obj.getClass().getName()); } else if (followed.add(obj)) { System.out.printf("Following %s\n", obj); } } }
rxfiddle-jvm-collector/src/main/java/nl/hermanbanken/RxFiddle/Hook.java
package nl.hermanbanken.rxfiddle; import jdk.internal.org.objectweb.asm.Type; import nl.hermanbanken.rxfiddle.data.Invoke; import nl.hermanbanken.rxfiddle.data.InvokeResult; import nl.hermanbanken.rxfiddle.data.Label; import nl.hermanbanken.rxfiddle.data.RuntimeEvent; import nl.hermanbanken.rxfiddle.visualiser.StdOutVisualizer; import nl.hermanbanken.rxfiddle.visualiser.Visualizer; import java.util.*; import java.util.concurrent.ArrayBlockingQueue; /** * Hook for instrumented classes * * @see <a href="https://www.youtube.com/watch?v=y4Ex6bsTv3k">ScalaDays 2015 Amsterdam presentation by Tal Weiss</a> * @see <a href="http://www.slideshare.net/Takipi/advanced-production-debugging#33">Relevant slide from presentation</a> * */ @SuppressWarnings({"WeakerAccess", "unused"}) public class Hook { public static Visualizer visualizer = new StdOutVisualizer(); public static final Stack<Label> labels = new Stack<>(); public static final Queue<Label> labelsForGrab = new ArrayBlockingQueue<>(1000); public static final Stack<Invoke> invokes = new Stack<>(); public static volatile Label currentLabel = null; public static volatile Invoke currentInvoke = null; public static HashMap<Label, ArrayList<Invoke>> results = new HashMap<>(); public static HashSet<Object> followed = new HashSet<>(); static { visualizer.logRun(System.nanoTime()); } public static class Constants { public static final String CLASS_NAME = Type.getInternalName(Hook.class); public static final String HOOK_METHOD_NAME = "libraryHook"; public static final String HOOK_METHOD_DESC = "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;Z)V"; public static final String LEAVE_METHOD_NAME = "leave"; public static final String LEAVE_METHOD_DESC = "(Ljava/lang/Object;)V"; public static final String ENTER_METHOD_NAME = "enter"; public static final String ENTER_METHOD_DESC = "(Ljava/lang/String;Ljava/lang/String;I)V"; } /** Usage of Rx **/ public static void libraryHook( Object subject, String className, String methodName, boolean fromLambda) { if (className.startsWith("rx/plugins")) return; // Runtime events if (followed.contains(subject) && (methodName.equals("request") || methodName.startsWith("subscribe") || methodName.startsWith("on"))) { System.out.printf("On followed subject %s: %s\n", subject, methodName); visualizer.logRuntime(new RuntimeEvent(subject, className, methodName)); } else if (methodName.startsWith("subscribe") || methodName.startsWith("on") || methodName.startsWith("unsubscribe")) { System.err.printf("Ignored runtime event %s %s %s\n", subject, className, methodName); } // Setup events if (labelsForGrab.isEmpty()) return; if (subject != null) follow(subject); Invoke invoke = new Invoke(subject, className, methodName, labelsForGrab.poll()); invokes.push(invoke); visualizer.logInvoke(invoke); } /** Tracing **/ public static void enter(String className, String methodName, int lineNumber) { Label label = new Label(className, methodName, lineNumber); labels.add(label); labelsForGrab.offer(label); } public static void leave(Object result) { labels.pop(); visualizer.logResult(new InvokeResult(invokes.isEmpty() ? null : invokes.pop(), result)); follow(result); } public static void follow(Object obj) { if (obj != null && followed.add(obj)) { System.out.printf("Following %s\n", obj); } } }
Prevent rx.internal logging
rxfiddle-jvm-collector/src/main/java/nl/hermanbanken/RxFiddle/Hook.java
Prevent rx.internal logging
<ide><path>xfiddle-jvm-collector/src/main/java/nl/hermanbanken/RxFiddle/Hook.java <ide> /** Usage of Rx **/ <ide> public static void libraryHook( <ide> Object subject, String className, String methodName, boolean fromLambda) { <del> if (className.startsWith("rx/plugins")) return; <add> if (className.startsWith("rx/plugins") || className.startsWith("rx/internal")) return; <ide> <ide> // Runtime events <ide> if (followed.contains(subject) <ide> } <ide> <ide> public static void follow(Object obj) { <del> if (obj != null && followed.add(obj)) { <add> if (obj == null) return; <add> if (obj.getClass().getName().startsWith("rx/internal") <add> || obj.getClass().getName().startsWith("rx.internal")) { <add> // System.out.printf("Not following %s", obj.getClass().getName()); <add> } else if (followed.add(obj)) { <ide> System.out.printf("Following %s\n", obj); <ide> } <ide> }
Java
apache-2.0
6165bf23f562a360ba2f15a0c7afa2d258fa3165
0
vector-im/riot-android,vector-im/vector-android,vector-im/riot-android,vector-im/vector-android,vector-im/riot-android,vector-im/vector-android,vector-im/riot-android,vector-im/riot-android,vector-im/vector-android
/* * Copyright 2015 OpenMarket Ltd * Copyright 2017 Vector Creations Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.services; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.os.Build; import android.os.Handler; import android.os.IBinder; import android.os.PowerManager; import android.support.v4.app.TaskStackBuilder; import android.support.v4.content.ContextCompat; import android.support.v4.content.res.ResourcesCompat; import android.support.v4.util.Pair; import android.support.v7.app.NotificationCompat; import android.support.v4.app.NotificationManagerCompat; import android.text.TextUtils; import org.matrix.androidsdk.crypto.data.MXDeviceInfo; import org.matrix.androidsdk.crypto.data.MXUsersDevicesMap; import org.matrix.androidsdk.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.Toast; import org.matrix.androidsdk.MXSession; import org.matrix.androidsdk.call.IMXCall; import org.matrix.androidsdk.call.MXCallsManager; import org.matrix.androidsdk.data.store.IMXStore; import org.matrix.androidsdk.data.Room; import org.matrix.androidsdk.data.RoomState; import org.matrix.androidsdk.data.store.MXStoreListener; import org.matrix.androidsdk.listeners.MXEventListener; import org.matrix.androidsdk.rest.model.Event; import org.matrix.androidsdk.rest.model.RoomMember; import org.matrix.androidsdk.rest.model.User; import org.matrix.androidsdk.rest.model.bingrules.BingRule; import org.matrix.androidsdk.util.EventDisplay; import im.vector.VectorApp; import im.vector.Matrix; import im.vector.R; import im.vector.ViewedRoomTracker; import im.vector.activity.VectorCallViewActivity; import im.vector.activity.CommonActivityUtils; import im.vector.activity.VectorHomeActivity; import im.vector.activity.VectorRoomActivity; import im.vector.gcm.GcmRegistrationManager; import im.vector.util.NotificationUtils; import im.vector.util.VectorCallSoundManager; import im.vector.util.VectorUtils; import java.io.File; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Random; /** * A foreground service in charge of controlling whether the event stream is running or not. */ public class EventStreamService extends Service { private static final String LOG_TAG = "EventStreamService"; /** * static instance */ private static EventStreamService mActiveEventStreamService = null; /** * Service action */ public enum StreamAction { IDLE, STOP, START, PAUSE, RESUME, CATCHUP, GCM_STATUS_UPDATE } // notification sub title, when sync polling thread is enabled: /** * foreground notification description. * This permanent notification is displayed when * 1- the client uses GCM but the third party server registration fails * 2- the client does not use GCM. */ private static final String NOTIFICATION_SUB_TITLE = "Listening for events"; /** * Parameters to the service */ public static final String EXTRA_STREAM_ACTION = "EventStreamService.EXTRA_STREAM_ACTION"; public static final String EXTRA_MATRIX_IDS = "EventStreamService.EXTRA_MATRIX_IDS"; /** * Notification identifiers */ private static final int NOTIF_ID_MESSAGE = 60; private static final int NOTIF_ID_FOREGROUND_SERVICE = 61; private static final int FOREGROUND_LISTENING_FOR_EVENTS = 42; private static final int FOREGROUND_NOTIF_ID_PENDING_CALL = 44; private static final int FOREGROUND_ID_INCOMING_CALL = 45; private int mForegroundServiceIdentifier = -1; /** * Default bing rule */ private static final BingRule mDefaultBingRule = new BingRule("ruleKind", "aPattern" , true, true, false); /** * Managed sessions */ private ArrayList<MXSession> mSessions; /** * Session identifiers */ private ArrayList<String> mMatrixIds; /** * The current state. */ private StreamAction mServiceState = StreamAction.IDLE; /** * store the notifications description */ private LinkedHashMap<String, Pair<BingRule, Event>> mPendingNotifications = new LinkedHashMap<>(); private Map<String, List<Pair<BingRule, String>>> mNotifiedMessagesByRoomId = null; /** * call in progress (foreground notification) */ private String mCallIdInProgress = null; /** * incoming (foreground notification) */ private String mIncomingCallId = null; /** * true when the service is in foreground ie the GCM registration failed or is disabled. */ private boolean mIsForeground = false; /** * GCM manager */ private GcmRegistrationManager mGcmRegistrationManager; /** * @return the event stream instance */ public static EventStreamService getInstance() { return mActiveEventStreamService; } /** * Calls events listener. */ private final MXCallsManager.MXCallsManagerListener mCallsManagerListener = new MXCallsManager.MXCallsManagerListener() { /** * Manage hangup event. * The ringing sound is disabled and pending incoming call is dismissed. * @param callId the callId */ private void manageHangUpEvent(String callId) { if (null != callId) { Log.d(LOG_TAG, "manageHangUpEvent : hide call notification and stopRinging for call " + callId); hideCallNotifications(); } else { Log.d(LOG_TAG, "manageHangUpEvent : stopRinging"); } VectorCallSoundManager.stopRinging(); } @Override public void onIncomingCall(final IMXCall call, MXUsersDevicesMap<MXDeviceInfo> unknownDevices) { Log.d(LOG_TAG, "onIncomingCall " + call.getCallId()); IMXCall.MXCallListener callListener = new IMXCall.MXCallListener() { @Override public void onStateDidChange(String state) { Log.d(LOG_TAG, "dispatchOnStateDidChange " + call.getCallId() + " : " + state); // if there is no call push rule // display the incoming call notification but with no sound if (TextUtils.equals(state, IMXCall.CALL_STATE_CREATED) || TextUtils.equals(state, IMXCall.CALL_STATE_CREATING_CALL_VIEW)) { displayIncomingCallNotification(call.getSession(), call.getRoom(), null, call.getCallId(), null); } } @Override public void onCallError(String error) { Log.d(LOG_TAG, "dispatchOnCallError " + call.getCallId() + " : " + error); manageHangUpEvent(call.getCallId()); } @Override public void onViewLoading(View callView) { } @Override public void onViewReady() { } @Override public void onCallAnsweredElsewhere() { Log.d(LOG_TAG, "onCallAnsweredElsewhere " + call.getCallId()); manageHangUpEvent(call.getCallId()); } @Override public void onCallEnd(final int aReasonId) { Log.d(LOG_TAG, "dispatchOnCallEnd " + call.getCallId()); manageHangUpEvent(call.getCallId()); } @Override public void onPreviewSizeChanged(int width, int height) { } }; call.addListener(callListener); } @Override public void onCallHangUp(final IMXCall call) { Log.d(LOG_TAG, "onCallHangUp " + call.getCallId()); manageHangUpEvent(call.getCallId()); } @Override public void onVoipConferenceStarted(String roomId) { } @Override public void onVoipConferenceFinished(String roomId) { } }; /** * Live events listener */ private final MXEventListener mEventsListener = new MXEventListener() { @Override public void onBingEvent(Event event, RoomState roomState, BingRule bingRule) { // privacy //Log.d(LOG_TAG, "onBingEvent : the event " + event); //Log.d(LOG_TAG, "onBingEvent : the bingRule " + bingRule); Log.d(LOG_TAG, "prepareNotification : " + event.eventId + " in " + roomState.roomId); prepareNotification(event, roomState, bingRule); } @Override public void onLiveEventsChunkProcessed(String fromToken, String toToken) { triggerPreparedNotification(true); mPendingNotifications.clear(); // do not suspend the application if there is some active calls if ((StreamAction.CATCHUP == mServiceState) || (StreamAction.PAUSE == mServiceState)) { boolean hasActiveCalls = false; for (MXSession session : mSessions) { hasActiveCalls |= session.mCallsManager.hasActiveCalls(); } // if there are some active calls, the catchup should not be stopped. // because an user could answer to a call from another device. // there will no push because it is his own message. // so, the client has no choice to catchup until the ring is shutdown if (hasActiveCalls) { Log.d(LOG_TAG, "onLiveEventsChunkProcessed : Catchup again because there are active calls"); catchup(false); } else if (StreamAction.CATCHUP == mServiceState) { Log.d(LOG_TAG, "onLiveEventsChunkProcessed : no Active call"); // in some race conditions // the call listener does not dispatch the call end // for example when the call is stopped while the incoming call activity is creating // the call is not initialized so the answerelsewhere / stop don't make sense. if (VectorCallSoundManager.isRinging()) { Log.d(LOG_TAG, "onLiveEventsChunkProcessed : there is no more call but the device is still ringing"); hideCallNotifications(); VectorCallSoundManager.stopRinging(); } setServiceState(StreamAction.PAUSE); } } } }; /** * Add some accounts to the current service. * @param matrixIds the account identifiers to add. */ public void startAccounts(List<String> matrixIds) { for(String matrixId : matrixIds) { // not yet started if (mMatrixIds.indexOf(matrixId) < 0) { MXSession session = Matrix.getInstance(getApplicationContext()).getSession(matrixId); mSessions.add(session); mMatrixIds.add(matrixId); session.getDataHandler().addListener(mEventsListener); session.getDataHandler().getCallsManager().addListener(mCallsManagerListener); // perform a full sync session.startEventStream(null); } } } /** * Stop some accounts of the current service. * @param matrixIds the account identifiers to add. */ public void stopAccounts(List<String> matrixIds) { for(String matrixId : matrixIds) { // not yet started if (mMatrixIds.indexOf(matrixId) >= 0) { MXSession session = Matrix.getInstance(getApplicationContext()).getSession(matrixId); if (null != session) { session.stopEventStream(); session.getDataHandler().removeListener(mEventsListener); session.getDataHandler().getCallsManager().removeListener(mCallsManagerListener); mSessions.remove(session); mMatrixIds.remove(matrixId); } } } } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (null == intent) { Log.e(LOG_TAG, "onStartCommand : null intent"); if (null != mActiveEventStreamService) { Log.e(LOG_TAG, "onStartCommand : null intent with an active events stream service"); } else { Log.e(LOG_TAG, "onStartCommand : null intent with no events stream service"); } return START_NOT_STICKY; } StreamAction action = StreamAction.values()[intent.getIntExtra(EXTRA_STREAM_ACTION, StreamAction.IDLE.ordinal())]; Log.d(LOG_TAG, "onStartCommand with action : " + action); if (intent.hasExtra(EXTRA_MATRIX_IDS)) { if (null == mMatrixIds) { mMatrixIds = new ArrayList<>(Arrays.asList(intent.getStringArrayExtra(EXTRA_MATRIX_IDS))); mSessions = new ArrayList<>(); for(String matrixId : mMatrixIds) { mSessions.add(Matrix.getInstance(getApplicationContext()).getSession(matrixId)); } Log.d(LOG_TAG, "onStartCommand : update the matrix ids list to " + mMatrixIds); } } switch (action) { case START: case RESUME: start(); break; case STOP: Log.d(LOG_TAG, "## onStartCommand(): service stopped"); stopSelf(); break; case PAUSE: pause(); break; case CATCHUP: catchup(true); break; case GCM_STATUS_UPDATE: gcmStatusUpdate(); default: break; } return START_STICKY; } @Override public void onDestroy() { Log.d(LOG_TAG, "the service is destroyed"); stop(); } @Override public IBinder onBind(Intent intent) { return null; } /** * Start the even stream. * @param session the session * @param store the store */ private void startEventStream(final MXSession session, final IMXStore store) { session.getDataHandler().checkPermanentStorageData(); session.startEventStream(store.getEventStreamToken()); session.getDataHandler().onStoreReady(); } /** * @return the current state */ private StreamAction getServiceState() { Log.d(LOG_TAG, "getState " + mServiceState); return mServiceState; } /** * Update the current thread state. * @param newState the new state. */ private void setServiceState(StreamAction newState) { Log.d(LOG_TAG, "setState from " + mServiceState + " to " + newState); mServiceState = newState; } /** * internal start. */ private void start() { StreamAction state = getServiceState(); if (state == StreamAction.START) { Log.e(LOG_TAG, "start : Already started."); return; } else if ((state == StreamAction.PAUSE) || (state == StreamAction.CATCHUP)) { Log.e(LOG_TAG, "start : Resuming active stream."); resume(); return; } if (mSessions == null) { Log.e(LOG_TAG, "start : No valid MXSession."); return; } Log.d(LOG_TAG, "## start : start the service"); mActiveEventStreamService = this; for(MXSession session : mSessions) { if (null == session.getDataHandler()) { Log.e(LOG_TAG, "start : the session is not anymore valid."); return; } session.getDataHandler().addListener(mEventsListener); session.getDataHandler().getCallsManager().addListener(mCallsManagerListener); final IMXStore store = session.getDataHandler().getStore(); // the store is ready (no data loading in progress...) if (store.isReady()) { startEventStream(session, store); } else { final MXSession fSession = session; // wait that the store is ready before starting the events listener store.addMXStoreListener(new MXStoreListener() { @Override public void onStoreReady(String accountId) { startEventStream(fSession, store); } @Override public void onStoreCorrupted(String accountId, String description) { // start a new initial sync if (null == store.getEventStreamToken()) { startEventStream(fSession, store); } else { // the data are out of sync Matrix.getInstance(getApplicationContext()).reloadSessions(getApplicationContext()); } } @Override public void onStoreOOM(final String accountId, final String description) { Handler uiHandler = new Handler(getMainLooper()); uiHandler.post(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), accountId + " : " + description, Toast.LENGTH_LONG).show(); Matrix.getInstance(getApplicationContext()).reloadSessions(getApplicationContext()); } }); } }); } } mGcmRegistrationManager = Matrix.getInstance(getApplicationContext()).getSharedGCMRegistrationManager(); if (!mGcmRegistrationManager.useGCM()) { updateServiceForegroundState(); } setServiceState(StreamAction.START); } /** * internal stop. */ private void stop() { Log.d(LOG_TAG, "## stop(): the service is stopped"); if (mIsForeground) { stopForeground(true); } if (mSessions != null) { for(MXSession session : mSessions) { if (session.isAlive()) { session.stopEventStream(); session.getDataHandler().removeListener(mEventsListener); session.getDataHandler().getCallsManager().removeListener(mCallsManagerListener); } } } mMatrixIds = null; mSessions = null; setServiceState(StreamAction.STOP); mActiveEventStreamService = null; } /** * internal pause method. */ private void pause() { StreamAction state = getServiceState(); if ((StreamAction.START == state) || (StreamAction.RESUME == state)) { Log.d(LOG_TAG, "onStartCommand pause from state " + state); if (mSessions != null) { for(MXSession session : mSessions) { session.pauseEventStream(); } setServiceState(StreamAction.PAUSE); } } else { Log.e(LOG_TAG, "onStartCommand invalid state pause " + state); } } /** * internal catchup method. * @param checkState true to check if the current state allow to perform a catchup */ private void catchup(boolean checkState) { StreamAction state = getServiceState(); boolean canCatchup = true; if (!checkState) { Log.d(LOG_TAG, "catchup without checking state "); } else { Log.d(LOG_TAG, "catchup with state " + state + " CurrentActivity " + VectorApp.getCurrentActivity()); // the catchup should only be done // 1- the state is in catchup : the event stream might have gone to sleep between two catchups // 2- the thread is suspended // 3- the application has been launched by a push so there is no displayed activity canCatchup = (state == StreamAction.CATCHUP) || (state == StreamAction.PAUSE) || ((StreamAction.START == state) && (null == VectorApp.getCurrentActivity())); } if (canCatchup) { if (mSessions != null) { for (MXSession session : mSessions) { session.catchupEventStream(); } } else { Log.e(LOG_TAG, "catchup no session"); } setServiceState(StreamAction.CATCHUP); } else { Log.d(LOG_TAG, "No catchup is triggered because there is already a running event thread"); } } /** * internal resume method. */ private void resume() { Log.d(LOG_TAG, "## resume : resume the service"); if (mSessions != null) { for(MXSession session : mSessions) { session.resumeEventStream(); } } setServiceState(StreamAction.START); } /** * The GCM status has been updated (i.e disabled or enabled). */ private void gcmStatusUpdate() { Log.d(LOG_TAG, "## gcmStatusUpdate"); if (mIsForeground) { Log.d(LOG_TAG, "## gcmStatusUpdate : gcm status succeeds so stopForeground"); if (FOREGROUND_LISTENING_FOR_EVENTS == mForegroundServiceIdentifier) { stopForeground(true); mForegroundServiceIdentifier = -1; } mIsForeground = false; } updateServiceForegroundState(); } /** * Enable/disable the service foreground status. * The service is put in foreground ("Foreground process priority") when a sync polling is used, * to strongly reduce the likelihood of the App being killed. */ private void updateServiceForegroundState() { Log.d(LOG_TAG, "## updateServiceForegroundState"); MXSession session = Matrix.getInstance(getApplicationContext()).getDefaultSession(); if (null == session) { Log.e(LOG_TAG, "## updateServiceForegroundState(): no session"); return; } // GA issue if (null == mGcmRegistrationManager) { return; } if ((!mGcmRegistrationManager.useGCM() || !mGcmRegistrationManager.isServerRegistred()) && mGcmRegistrationManager.isBackgroundSyncAllowed() && mGcmRegistrationManager.areDeviceNotificationsAllowed()) { Log.d(LOG_TAG, "## updateServiceForegroundState : put the service in foreground"); if (-1 == mForegroundServiceIdentifier) { Notification notification = buildForegroundServiceNotification(); startForeground(NOTIF_ID_FOREGROUND_SERVICE, notification); mForegroundServiceIdentifier = FOREGROUND_LISTENING_FOR_EVENTS; } mIsForeground = true; } else { Log.d(LOG_TAG, "## updateServiceForegroundState : put the service in background"); if (FOREGROUND_LISTENING_FOR_EVENTS == mForegroundServiceIdentifier) { stopForeground(true); mForegroundServiceIdentifier = -1; } mIsForeground = false; } } //================================================================================ // notification management //================================================================================ /** * @return the polling thread listener notification */ @SuppressLint("NewApi") private Notification buildForegroundServiceNotification() { // build the pending intent go to the home screen if this is clicked. Intent i = new Intent(this, VectorHomeActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0); // build the notification builder NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this); notifBuilder.setSmallIcon(R.drawable.permanent_notification_transparent); notifBuilder.setWhen(System.currentTimeMillis()); notifBuilder.setContentTitle(getString(R.string.app_name)); notifBuilder.setContentText(NOTIFICATION_SUB_TITLE); notifBuilder.setContentIntent(pi); // hide the notification from the status bar if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { notifBuilder.setPriority(NotificationCompat.PRIORITY_MIN); } Notification notification = notifBuilder.build(); notification.flags |= Notification.FLAG_NO_CLEAR; if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { // some devices crash if this field is not set // even if it is deprecated // setLatestEventInfo() is deprecated on Android M, so we try to use // reflection at runtime, to avoid compiler error: "Cannot resolve method.." try { Method deprecatedMethod = notification.getClass().getMethod("setLatestEventInfo", Context.class, CharSequence.class, CharSequence.class, PendingIntent.class); deprecatedMethod.invoke(notification, this, getString(R.string.app_name), NOTIFICATION_SUB_TITLE, pi); } catch (Exception ex) { Log.e(LOG_TAG, "## buildNotification(): Exception - setLatestEventInfo() Msg="+ex.getMessage()); } } return notification; } /** * Retrieve the room name. * @param session the session * @param room the room * @param event the event * @return the room name */ private String getRoomName(MXSession session, Room room, Event event) { String roomName = VectorUtils.getRoomDisplayName(EventStreamService.this, session, room); // avoid displaying the room Id // try to find the sender display name if (TextUtils.equals(roomName, room.getRoomId())) { roomName = room.getName(session.getMyUserId()); // avoid room Id as name if (TextUtils.equals(roomName, room.getRoomId()) && (null != event)) { User user = session.getDataHandler().getStore().getUser(event.sender); if (null != user) { roomName = user.displayname; } else { roomName = event.sender; } } } return roomName; } /** * Prepare a call notification. * Only the incoming calls are managed by now and have a dedicated notification. * @param event the event * @param bingRule the bing rule */ private void prepareCallNotification(Event event, BingRule bingRule) { // display only the invitation messages by now // because the other ones are not displayed. if (!event.getType().equals(Event.EVENT_TYPE_CALL_INVITE)) { Log.d(LOG_TAG, "prepareCallNotification : don't bing - Call invite"); return; } MXSession session = Matrix.getMXSession(getApplicationContext(), event.getMatrixId()); // invalid session ? // should never happen. // But it could be triggered because of multi accounts management. // The dedicated account is removing but some pushes are still received. if ((null == session) || !session.isAlive()) { Log.d(LOG_TAG, "prepareCallNotification : don't bing - no session"); return; } Room room = session.getDataHandler().getRoom(event.roomId); // invalid room ? if (null == room) { Log.d(LOG_TAG, "prepareCallNotification : don't bing - the room does not exist"); return; } String callId = null; try { callId = event.getContentAsJsonObject().get("call_id").getAsString(); } catch (Exception e) { Log.e(LOG_TAG, "prepareNotification : getContentAsJsonObject " + e.getMessage()); } if (!TextUtils.isEmpty(callId)) { displayIncomingCallNotification(session, room, event, callId, bingRule); } } /** * Prepare a notification for the expected event. * @param event the event * @param roomState the room state * @param bingRule the bing rule */ public void prepareNotification(Event event, RoomState roomState, BingRule bingRule) { if (mPendingNotifications.containsKey(event.eventId)) { Log.d(LOG_TAG, "prepareNotification : don't bing - the event was already binged"); return; } if (!mGcmRegistrationManager.areDeviceNotificationsAllowed()) { Log.d(LOG_TAG, "prepareNotification : the push has been disable on this device"); return; } if (event.isCallEvent()) { prepareCallNotification(event, bingRule); return; } final String roomId = event.roomId; // Just don't bing for the room the user's currently in if (!VectorApp.isAppInBackground() && (roomId != null) && event.roomId.equals(ViewedRoomTracker.getInstance().getViewedRoomId())) { Log.d(LOG_TAG, "prepareNotification : don't bing because it is the currently opened room"); return; } // FIXME: Support event contents with no body if (!event.getContent().getAsJsonObject().has("body")) { // only the membership events are supported if (!Event.EVENT_TYPE_STATE_ROOM_MEMBER.equals(event.getType()) && !event.isCallEvent()) { Log.d(LOG_TAG, "onBingEvent : don't bing - no body and not a call event"); return; } } MXSession session = Matrix.getMXSession(getApplicationContext(), event.getMatrixId()); // invalid session ? // should never happen. // But it could be triggered because of multi accounts management. // The dedicated account is removing but some pushes are still received. if ((null == session) || !session.isAlive()) { Log.d(LOG_TAG, "prepareNotification : don't bing - no session"); return; } Room room = session.getDataHandler().getRoom(roomId); // invalid room ? if (null == room) { Log.d(LOG_TAG, "prepareNotification : don't bing - the room does not exist"); return; } mPendingNotifications.put(event.eventId, new Pair<>(bingRule, event)); } /** * Cancel the push notifications for a dedicated roomId. * If the roomId is null, cancel all the push notification. * @param accountId the account id * @param roomId the room id. */ public static void cancelNotificationsForRoomId(String accountId, String roomId) { Log.d(LOG_TAG, "cancelNotificationsForRoomId " + accountId + " - " + roomId); if (null != mActiveEventStreamService) { mActiveEventStreamService.cancelNotifications(accountId ,roomId); } } /** * Clear any displayed notification. */ private void clearNotification() { NotificationManager nm = (NotificationManager) EventStreamService.this.getSystemService(Context.NOTIFICATION_SERVICE); try { nm.cancelAll(); } catch (Exception e) { Log.e(LOG_TAG, "## clearNotification() failed " + e.getMessage()); } // reset the identifiers mPendingNotifications.clear(); mNotifiedMessagesByRoomId.clear(); } /** * Remove any pending notification. * It should be called when the application is logged out. */ public static void removeNotification() { if (null != mActiveEventStreamService) { mActiveEventStreamService.clearNotification(); } } /** * Check if a notification must be cleared because the linked event has been read, deleted ... */ public static void checkDisplayedNotifications() { if (null != mActiveEventStreamService) { mActiveEventStreamService.triggerPreparedNotification(false); } } private void cancelNotifications(String accountId, String roomId) { if (mNotifiedMessagesByRoomId.containsKey(roomId)) { mNotifiedMessagesByRoomId = null; triggerPreparedNotification(false); } } /** * Trigger the latest prepared notification * @param checkNotification true to check if the prepared notification still makes sense. */ public void triggerPreparedNotification(boolean checkNotification) { Pair<BingRule, Event> eventToNotify = getEventToNotify(); if (null != eventToNotify) { mNotifiedMessagesByRoomId = null; } boolean isNotifUpdated = refreshNotifiedMessagesList(); if (isNotifUpdated) { // TODO add multi sessions MXSession session = Matrix.getInstance(getBaseContext()).getDefaultSession(); NotificationManagerCompat nm = NotificationManagerCompat.from(EventStreamService.this); // no more notifications if (mNotifiedMessagesByRoomId.size() == 0) { nm.cancel(NOTIF_ID_MESSAGE); } else { boolean isBackgroundNotif = (null == eventToNotify); Event event; Room room; BingRule bingRule; // use the first notified event to refresh the notification if (isBackgroundNotif) { String roomId = mNotifiedMessagesByRoomId.keySet().iterator().next(); Pair<BingRule, String> pair = mNotifiedMessagesByRoomId.get(roomId).get(0); room = session.getDataHandler().getStore().getRoom(roomId); event = session.getDataHandler().getStore().getEvent(pair.second, roomId); bingRule = pair.first; } else { event = eventToNotify.second; room = session.getDataHandler().getStore().getRoom(event.roomId); bingRule = eventToNotify.first; } boolean isInvitationEvent = false; EventDisplay eventDisplay = new EventDisplay(getApplicationContext(), event, room.getLiveState()); eventDisplay.setPrependMessagesWithAuthor(true); String body = eventDisplay.getTextualDisplay().toString(); if (Event.EVENT_TYPE_STATE_ROOM_MEMBER.equals(event.getType())) { try { isInvitationEvent = "invite".equals(event.getContentAsJsonObject().getAsJsonPrimitive("membership").getAsString()); } catch (Exception e) { Log.e(LOG_TAG, "prepareNotification : invitation parsing failed"); } } Bitmap largeBitmap = null; // when the event is an invitation one // don't check if the sender ID is known because the members list are not yet downloaded if (!isInvitationEvent) { // is there any avatar url if (!TextUtils.isEmpty(room.getAvatarUrl())) { int size = getApplicationContext().getResources().getDimensionPixelSize(R.dimen.profile_avatar_size); // check if the thumbnail is already downloaded File f = session.getMediasCache().thumbnailCacheFile(room.getAvatarUrl(), size); if (null != f) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; try { largeBitmap = BitmapFactory.decodeFile(f.getPath(), options); } catch (OutOfMemoryError oom) { Log.e(LOG_TAG, "decodeFile failed with an oom"); } } else { session.getMediasCache().loadAvatarThumbnail(session.getHomeserverConfig(), new ImageView(getApplicationContext()), room.getAvatarUrl(), size); } } } //mNotificationSessionId = session.getCredentials().userId; Log.d(LOG_TAG, "prepareNotification : with sound " + bingRule.isDefaultNotificationSound(bingRule.notificationSound())); String roomName = getRoomName(session, room, event); NotificationCompat.Builder builder = new NotificationCompat.Builder(EventStreamService.this); builder.setWhen(event.getOriginServerTs()); builder.setContentTitle(roomName); builder.setContentText(body); builder.setGroup("riot"); builder.setGroupSummary(true); NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); int sum = 0; // TODO manage order for(String roomId : mNotifiedMessagesByRoomId.keySet()) { room = session.getDataHandler().getRoom(roomId); roomName = getRoomName(session, room, null); inboxStyle.addLine(roomName + " : " + session.getDataHandler().getStore().unreadEvents(roomId, null).size() + " unread events"); sum += session.getDataHandler().getStore().unreadEvents(roomId, null).size(); } inboxStyle.setBigContentTitle("Riot"); inboxStyle.setSummaryText(sum + " unread messages in " + mNotifiedMessagesByRoomId.keySet().size() + " rooms"); builder.setStyle(inboxStyle); if (mNotifiedMessagesByRoomId.keySet().size() == 1) { if (null != largeBitmap) { largeBitmap = NotificationUtils.createSquareBitmap(largeBitmap); builder.setLargeIcon(largeBitmap); } } else { } builder.setSmallIcon(R.drawable.message_notification_transparent); int highlightCount = room.getHighlightCount(); boolean is_bing = bingRule.isDefaultNotificationSound(bingRule.notificationSound()); if (isBackgroundNotif) { builder.setPriority(NotificationCompat.PRIORITY_MIN); } else if (is_bing) { // So that it pops up on screen. builder.setPriority(NotificationCompat.PRIORITY_HIGH); builder.setColor(ContextCompat.getColor(getApplicationContext(), R.color.vector_fuchsia_color)); } else if (highlightCount > 0) { builder.setPriority(NotificationCompat.PRIORITY_DEFAULT); builder.setColor(ContextCompat.getColor(getApplicationContext(), R.color.vector_fuchsia_color)); } else { builder.setPriority(NotificationCompat.PRIORITY_MIN); builder.setColor(Color.TRANSPARENT); } // TODO add quick reply Notification n = builder.build(); n.flags |= Notification.FLAG_SHOW_LIGHTS; n.defaults |= Notification.DEFAULT_LIGHTS; if (is_bing && !isBackgroundNotif) { n.defaults |= Notification.DEFAULT_SOUND; } nm.notify(NOTIF_ID_MESSAGE, n); } } } /** * Check if the current displayed notification must be cleared * because it doesn't make sense anymore. */ private Pair<BingRule, Event> getEventToNotify() { // TODO add multi sessions MXSession session = Matrix.getInstance(getBaseContext()).getDefaultSession(); // notified only the latest unread message List<Pair<BingRule, Event>> pairs = new ArrayList<>(mPendingNotifications.values()); Collections.reverse(pairs); for(Pair<BingRule, Event> pair : pairs) { Event event = pair.second; Room room = session.getDataHandler().getRoom(event.roomId); // test if the message has not been read if ((null != room) && !room.isEventRead(event.eventId)) { // test if the message is displayable EventDisplay eventDisplay = new EventDisplay(getApplicationContext(), event, room.getLiveState()); eventDisplay.setPrependMessagesWithAuthor(false); String body = eventDisplay.getTextualDisplay().toString(); if (!TextUtils.isEmpty(body)) { mPendingNotifications.clear(); return pair; } } } mPendingNotifications.clear(); return null; } //private LinkedHashMap<String, Event> mPendingNotifications = new LinkedHashMap<>(); //private Map<String, List<Pair<BingRule, String>>> mNotifiedMessagesByRoomId = null; /** * Refresh the notified messages list if it was not yet done. * @return true if there is an update */ private boolean refreshNotifiedMessagesList() { // TODO add multi sessions MXSession session = Matrix.getInstance(getBaseContext()).getDefaultSession(); IMXStore store = session.getDataHandler().getStore(); if (null == mNotifiedMessagesByRoomId) { mNotifiedMessagesByRoomId = new HashMap<>(); Collection<Room> rooms = store.getRooms(); for(Room room : rooms) { // invitation : add the dedicated event if (room.isInvited()) { Collection<Event> events = store.getRoomMessages(room.getRoomId()); if (null != events) { for (Event event : events) { if (Event.EVENT_TYPE_STATE_ROOM_MEMBER.equals(event.getType())) { try { if ("invite".equals(event.getContentAsJsonObject().getAsJsonPrimitive("membership").getAsString())) { BingRule rule = session.fulfillRule(event); if (null != rule) { List<Pair<BingRule, String>> list = new ArrayList<>(); list.add(new Pair<>(rule, event.eventId)); mNotifiedMessagesByRoomId.put(room.getRoomId(), list); } } } catch (Exception e) { Log.e(LOG_TAG, "initNotifiedMessagesList : invitation parsing failed"); } } } } } else { List<Event> unreadEvents = session.getDataHandler().getStore().unreadEvents(room.getRoomId(), null); if ((null != unreadEvents) && unreadEvents.size() > 0) { List<Pair<BingRule, String>> list = new ArrayList<>(); for (Event event : unreadEvents) { BingRule rule = session.fulfillRule(event); if (null != rule) { list.add(new Pair<>(rule, event.eventId)); } } if (list.size() > 0) { mNotifiedMessagesByRoomId.put(room.getRoomId(), list); } } } } return true; } else { boolean isUpdated = false; List<String> roomIds = new ArrayList<>(mNotifiedMessagesByRoomId.keySet()); for(String roomId : roomIds) { Room room = store.getRoom(roomId); // the room does not exist anymore if (null == room) { mNotifiedMessagesByRoomId.remove(roomId); isUpdated = true; } else { List<Pair<BingRule, String>> events = mNotifiedMessagesByRoomId.get(roomId); // search for the read messages for(int i = 0; i < events.size(); ) { Pair<BingRule, String> pair = events.get(i); if (room.isEventRead(pair.second)) { events.remove(i); isUpdated = true; } else { i++; } } if (0 == events.size()) { mNotifiedMessagesByRoomId.remove(roomId); isUpdated = true; } } } return isUpdated; } } /** * Display a permanent notification when there is an incoming call. * @param session the session * @param room the room * @param event the event * @param callId the callId * @param bingRule the bing rule. */ private void displayIncomingCallNotification(MXSession session, Room room, Event event, String callId, BingRule bingRule) { Log.d(LOG_TAG, "displayIncomingCallNotification : " + callId + " in " + room.getRoomId()); // the incoming call in progress is already displayed if (!TextUtils.isEmpty(mIncomingCallId)) { Log.d(LOG_TAG, "displayIncomingCallNotification : the incoming call in progress is already displayed"); } else if (!TextUtils.isEmpty(mCallIdInProgress)) { Log.d(LOG_TAG, "displayIncomingCallNotification : a 'call in progress' notification is displayed"); } // test if there is no active call else if (null == VectorCallViewActivity.getActiveCall()) { Log.d(LOG_TAG, "displayIncomingCallNotification : display the dedicated notification"); if ((null != bingRule) && bingRule.isCallRingNotificationSound(bingRule.notificationSound())) { VectorCallSoundManager.startRinging(); } Notification notification = NotificationUtils.buildIncomingCallNotification( EventStreamService.this, getRoomName(session, room, event), session.getMyUserId(), callId); if ((null != bingRule) && bingRule.isDefaultNotificationSound(bingRule.notificationSound())) { notification.defaults |= Notification.DEFAULT_SOUND; } startForeground(NOTIF_ID_FOREGROUND_SERVICE, notification); mForegroundServiceIdentifier = FOREGROUND_ID_INCOMING_CALL; mIncomingCallId = callId; // turn the screen on for 3 seconds PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "MXEventListener"); wl.acquire(3000); wl.release(); } else { Log.d(LOG_TAG, "displayIncomingCallNotification : do not display the incoming call notification because there is a pending call"); } } /** * Display a call in progress notificatin. * @param session the session * @param callId the callId */ public void displayCallInProgressNotification(MXSession session, Room room, String callId) { if (null != callId) { Notification notification = NotificationUtils.buildPendingCallNotification(getApplicationContext(), room.getName(session.getCredentials().userId), room.getRoomId(), session.getCredentials().userId, callId); startForeground(NOTIF_ID_FOREGROUND_SERVICE, notification); mForegroundServiceIdentifier = FOREGROUND_NOTIF_ID_PENDING_CALL; mCallIdInProgress = callId; } } /** * Hide the permanent call notifications */ public void hideCallNotifications() { NotificationManager nm = (NotificationManager) EventStreamService.this.getSystemService(Context.NOTIFICATION_SERVICE); // hide the call if ((FOREGROUND_NOTIF_ID_PENDING_CALL == mForegroundServiceIdentifier) || (FOREGROUND_ID_INCOMING_CALL == mForegroundServiceIdentifier)) { if (FOREGROUND_NOTIF_ID_PENDING_CALL == mForegroundServiceIdentifier) { mCallIdInProgress = null; } else { mIncomingCallId = null; } nm.cancel(NOTIF_ID_FOREGROUND_SERVICE); mForegroundServiceIdentifier = -1; stopForeground(true); updateServiceForegroundState(); } } }
vector/src/main/java/im/vector/services/EventStreamService.java
/* * Copyright 2015 OpenMarket Ltd * Copyright 2017 Vector Creations Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.services; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.os.Build; import android.os.Handler; import android.os.IBinder; import android.os.PowerManager; import android.support.v4.app.TaskStackBuilder; import android.support.v4.content.ContextCompat; import android.support.v4.content.res.ResourcesCompat; import android.support.v7.app.NotificationCompat; import android.support.v4.app.NotificationManagerCompat; import android.text.TextUtils; import org.matrix.androidsdk.crypto.data.MXDeviceInfo; import org.matrix.androidsdk.crypto.data.MXUsersDevicesMap; import org.matrix.androidsdk.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.Toast; import org.matrix.androidsdk.MXSession; import org.matrix.androidsdk.call.IMXCall; import org.matrix.androidsdk.call.MXCallsManager; import org.matrix.androidsdk.data.store.IMXStore; import org.matrix.androidsdk.data.Room; import org.matrix.androidsdk.data.RoomState; import org.matrix.androidsdk.data.store.MXStoreListener; import org.matrix.androidsdk.listeners.MXEventListener; import org.matrix.androidsdk.rest.model.Event; import org.matrix.androidsdk.rest.model.RoomMember; import org.matrix.androidsdk.rest.model.User; import org.matrix.androidsdk.rest.model.bingrules.BingRule; import org.matrix.androidsdk.util.EventDisplay; import im.vector.VectorApp; import im.vector.Matrix; import im.vector.R; import im.vector.ViewedRoomTracker; import im.vector.activity.VectorCallViewActivity; import im.vector.activity.CommonActivityUtils; import im.vector.activity.VectorHomeActivity; import im.vector.activity.VectorRoomActivity; import im.vector.gcm.GcmRegistrationManager; import im.vector.util.NotificationUtils; import im.vector.util.VectorCallSoundManager; import im.vector.util.VectorUtils; import java.io.File; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; /** * A foreground service in charge of controlling whether the event stream is running or not. */ public class EventStreamService extends Service { private static final String LOG_TAG = "EventStreamService"; /** * static instance */ private static EventStreamService mActiveEventStreamService = null; /** * Service action */ public enum StreamAction { IDLE, STOP, START, PAUSE, RESUME, CATCHUP, GCM_STATUS_UPDATE } // notification sub title, when sync polling thread is enabled: /** * foreground notification description. * This permanent notification is displayed when * 1- the client uses GCM but the third party server registration fails * 2- the client does not use GCM. */ private static final String NOTIFICATION_SUB_TITLE = "Listening for events"; /** * Parameters to the service */ public static final String EXTRA_STREAM_ACTION = "EventStreamService.EXTRA_STREAM_ACTION"; public static final String EXTRA_MATRIX_IDS = "EventStreamService.EXTRA_MATRIX_IDS"; /** * Notification identifiers */ private static final int NOTIF_ID_MESSAGE = 60; private static final int NOTIF_ID_FOREGROUND_SERVICE = 61; private static final int FOREGROUND_LISTENING_FOR_EVENTS = 42; private static final int FOREGROUND_NOTIF_ID_PENDING_CALL = 44; private static final int FOREGROUND_ID_INCOMING_CALL = 45; private int mForegroundServiceIdentifier = -1; /** * Default bing rule */ private static final BingRule mDefaultBingRule = new BingRule("ruleKind", "aPattern" , true, true, false); /** * Managed sessions */ private ArrayList<MXSession> mSessions; /** * Session identifiers */ private ArrayList<String> mMatrixIds; /** * The current state. */ private StreamAction mServiceState = StreamAction.IDLE; /** * store the notifications description */ private String mNotificationSessionId = null; private Map<String, NotificationCompat.MessagingStyle> mNotificationMessagesListByRoomId = new HashMap<>(); private Map<String, String> mLatestEventIdByRoomId = new HashMap<>(); /** * call in progress (foreground notification) */ private String mCallIdInProgress = null; /** * incoming (foreground notification) */ private String mIncomingCallId = null; /** * true when the service is in foreground ie the GCM registration failed or is disabled. */ private boolean mIsForeground = false; /** * the latest built notification */ private Notification mLatestNotification = null; /** * list the notifications found between two onLiveEventsChunkProcessed() */ private final ArrayList<String> mPendingNotifications = new ArrayList<>(); /** * GCM manager */ private GcmRegistrationManager mGcmRegistrationManager; /** * @return the event stream instance */ public static EventStreamService getInstance() { return mActiveEventStreamService; } /** * Calls events listener. */ private final MXCallsManager.MXCallsManagerListener mCallsManagerListener = new MXCallsManager.MXCallsManagerListener() { /** * Manage hangup event. * The ringing sound is disabled and pending incoming call is dismissed. * @param callId the callId */ private void manageHangUpEvent(String callId) { if (null != callId) { Log.d(LOG_TAG, "manageHangUpEvent : hide call notification and stopRinging for call " + callId); hideCallNotifications(); } else { Log.d(LOG_TAG, "manageHangUpEvent : stopRinging"); } VectorCallSoundManager.stopRinging(); } @Override public void onIncomingCall(final IMXCall call, MXUsersDevicesMap<MXDeviceInfo> unknownDevices) { Log.d(LOG_TAG, "onIncomingCall " + call.getCallId()); IMXCall.MXCallListener callListener = new IMXCall.MXCallListener() { @Override public void onStateDidChange(String state) { Log.d(LOG_TAG, "dispatchOnStateDidChange " + call.getCallId() + " : " + state); // if there is no call push rule // display the incoming call notification but with no sound if (TextUtils.equals(state, IMXCall.CALL_STATE_CREATED) || TextUtils.equals(state, IMXCall.CALL_STATE_CREATING_CALL_VIEW)) { displayIncomingCallNotification(call.getSession(), call.getRoom(), null, call.getCallId(), null); } } @Override public void onCallError(String error) { Log.d(LOG_TAG, "dispatchOnCallError " + call.getCallId() + " : " + error); manageHangUpEvent(call.getCallId()); } @Override public void onViewLoading(View callView) { } @Override public void onViewReady() { } @Override public void onCallAnsweredElsewhere() { Log.d(LOG_TAG, "onCallAnsweredElsewhere " + call.getCallId()); manageHangUpEvent(call.getCallId()); } @Override public void onCallEnd(final int aReasonId) { Log.d(LOG_TAG, "dispatchOnCallEnd " + call.getCallId()); manageHangUpEvent(call.getCallId()); } @Override public void onPreviewSizeChanged(int width, int height) { } }; call.addListener(callListener); } @Override public void onCallHangUp(final IMXCall call) { Log.d(LOG_TAG, "onCallHangUp " + call.getCallId()); manageHangUpEvent(call.getCallId()); } @Override public void onVoipConferenceStarted(String roomId) { } @Override public void onVoipConferenceFinished(String roomId) { } }; /** * Live events listener */ private final MXEventListener mEventsListener = new MXEventListener() { @Override public void onBingEvent(Event event, RoomState roomState, BingRule bingRule) { // privacy //Log.d(LOG_TAG, "onBingEvent : the event " + event); //Log.d(LOG_TAG, "onBingEvent : the bingRule " + bingRule); Log.d(LOG_TAG, "prepareNotification : " + event.eventId + " in " + roomState.roomId); prepareNotification(event, roomState, bingRule); } @Override public void onLiveEventsChunkProcessed(String fromToken, String toToken) { triggerPreparedNotification(true); mPendingNotifications.clear(); // do not suspend the application if there is some active calls if ((StreamAction.CATCHUP == mServiceState) || (StreamAction.PAUSE == mServiceState)) { boolean hasActiveCalls = false; for (MXSession session : mSessions) { hasActiveCalls |= session.mCallsManager.hasActiveCalls(); } // if there are some active calls, the catchup should not be stopped. // because an user could answer to a call from another device. // there will no push because it is his own message. // so, the client has no choice to catchup until the ring is shutdown if (hasActiveCalls) { Log.d(LOG_TAG, "onLiveEventsChunkProcessed : Catchup again because there are active calls"); catchup(false); } else if (StreamAction.CATCHUP == mServiceState) { Log.d(LOG_TAG, "onLiveEventsChunkProcessed : no Active call"); // in some race conditions // the call listener does not dispatch the call end // for example when the call is stopped while the incoming call activity is creating // the call is not initialized so the answerelsewhere / stop don't make sense. if (VectorCallSoundManager.isRinging()) { Log.d(LOG_TAG, "onLiveEventsChunkProcessed : there is no more call but the device is still ringing"); hideCallNotifications(); VectorCallSoundManager.stopRinging(); } setServiceState(StreamAction.PAUSE); } } } }; /** * Add some accounts to the current service. * @param matrixIds the account identifiers to add. */ public void startAccounts(List<String> matrixIds) { for(String matrixId : matrixIds) { // not yet started if (mMatrixIds.indexOf(matrixId) < 0) { MXSession session = Matrix.getInstance(getApplicationContext()).getSession(matrixId); mSessions.add(session); mMatrixIds.add(matrixId); session.getDataHandler().addListener(mEventsListener); session.getDataHandler().getCallsManager().addListener(mCallsManagerListener); // perform a full sync session.startEventStream(null); } } } /** * Stop some accounts of the current service. * @param matrixIds the account identifiers to add. */ public void stopAccounts(List<String> matrixIds) { for(String matrixId : matrixIds) { // not yet started if (mMatrixIds.indexOf(matrixId) >= 0) { MXSession session = Matrix.getInstance(getApplicationContext()).getSession(matrixId); if (null != session) { session.stopEventStream(); session.getDataHandler().removeListener(mEventsListener); session.getDataHandler().getCallsManager().removeListener(mCallsManagerListener); mSessions.remove(session); mMatrixIds.remove(matrixId); } } } } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (null == intent) { Log.e(LOG_TAG, "onStartCommand : null intent"); if (null != mActiveEventStreamService) { Log.e(LOG_TAG, "onStartCommand : null intent with an active events stream service"); } else { Log.e(LOG_TAG, "onStartCommand : null intent with no events stream service"); } return START_NOT_STICKY; } StreamAction action = StreamAction.values()[intent.getIntExtra(EXTRA_STREAM_ACTION, StreamAction.IDLE.ordinal())]; Log.d(LOG_TAG, "onStartCommand with action : " + action); if (intent.hasExtra(EXTRA_MATRIX_IDS)) { if (null == mMatrixIds) { mMatrixIds = new ArrayList<>(Arrays.asList(intent.getStringArrayExtra(EXTRA_MATRIX_IDS))); mSessions = new ArrayList<>(); for(String matrixId : mMatrixIds) { mSessions.add(Matrix.getInstance(getApplicationContext()).getSession(matrixId)); } Log.d(LOG_TAG, "onStartCommand : update the matrix ids list to " + mMatrixIds); } } switch (action) { case START: case RESUME: start(); break; case STOP: Log.d(LOG_TAG, "## onStartCommand(): service stopped"); stopSelf(); break; case PAUSE: pause(); break; case CATCHUP: catchup(true); break; case GCM_STATUS_UPDATE: gcmStatusUpdate(); default: break; } return START_STICKY; } @Override public void onDestroy() { Log.d(LOG_TAG, "the service is destroyed"); stop(); } @Override public IBinder onBind(Intent intent) { return null; } /** * Start the even stream. * @param session the session * @param store the store */ private void startEventStream(final MXSession session, final IMXStore store) { session.getDataHandler().checkPermanentStorageData(); session.startEventStream(store.getEventStreamToken()); session.getDataHandler().onStoreReady(); } /** * @return the current state */ private StreamAction getServiceState() { Log.d(LOG_TAG, "getState " + mServiceState); return mServiceState; } /** * Update the current thread state. * @param newState the new state. */ private void setServiceState(StreamAction newState) { Log.d(LOG_TAG, "setState from " + mServiceState + " to " + newState); mServiceState = newState; } /** * internal start. */ private void start() { StreamAction state = getServiceState(); if (state == StreamAction.START) { Log.e(LOG_TAG, "start : Already started."); return; } else if ((state == StreamAction.PAUSE) || (state == StreamAction.CATCHUP)) { Log.e(LOG_TAG, "start : Resuming active stream."); resume(); return; } if (mSessions == null) { Log.e(LOG_TAG, "start : No valid MXSession."); return; } Log.d(LOG_TAG, "## start : start the service"); mActiveEventStreamService = this; for(MXSession session : mSessions) { if (null == session.getDataHandler()) { Log.e(LOG_TAG, "start : the session is not anymore valid."); return; } session.getDataHandler().addListener(mEventsListener); session.getDataHandler().getCallsManager().addListener(mCallsManagerListener); final IMXStore store = session.getDataHandler().getStore(); // the store is ready (no data loading in progress...) if (store.isReady()) { startEventStream(session, store); } else { final MXSession fSession = session; // wait that the store is ready before starting the events listener store.addMXStoreListener(new MXStoreListener() { @Override public void onStoreReady(String accountId) { startEventStream(fSession, store); } @Override public void onStoreCorrupted(String accountId, String description) { // start a new initial sync if (null == store.getEventStreamToken()) { startEventStream(fSession, store); } else { // the data are out of sync Matrix.getInstance(getApplicationContext()).reloadSessions(getApplicationContext()); } } @Override public void onStoreOOM(final String accountId, final String description) { Handler uiHandler = new Handler(getMainLooper()); uiHandler.post(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), accountId + " : " + description, Toast.LENGTH_LONG).show(); Matrix.getInstance(getApplicationContext()).reloadSessions(getApplicationContext()); } }); } }); } } mGcmRegistrationManager = Matrix.getInstance(getApplicationContext()).getSharedGCMRegistrationManager(); if (!mGcmRegistrationManager.useGCM()) { updateServiceForegroundState(); } setServiceState(StreamAction.START); } /** * internal stop. */ private void stop() { Log.d(LOG_TAG, "## stop(): the service is stopped"); if (mIsForeground) { stopForeground(true); } if (mSessions != null) { for(MXSession session : mSessions) { if (session.isAlive()) { session.stopEventStream(); session.getDataHandler().removeListener(mEventsListener); session.getDataHandler().getCallsManager().removeListener(mCallsManagerListener); } } } mMatrixIds = null; mSessions = null; setServiceState(StreamAction.STOP); mActiveEventStreamService = null; } /** * internal pause method. */ private void pause() { StreamAction state = getServiceState(); if ((StreamAction.START == state) || (StreamAction.RESUME == state)) { Log.d(LOG_TAG, "onStartCommand pause from state " + state); if (mSessions != null) { for(MXSession session : mSessions) { session.pauseEventStream(); } setServiceState(StreamAction.PAUSE); } } else { Log.e(LOG_TAG, "onStartCommand invalid state pause " + state); } } /** * internal catchup method. * @param checkState true to check if the current state allow to perform a catchup */ private void catchup(boolean checkState) { StreamAction state = getServiceState(); boolean canCatchup = true; if (!checkState) { Log.d(LOG_TAG, "catchup without checking state "); } else { Log.d(LOG_TAG, "catchup with state " + state + " CurrentActivity " + VectorApp.getCurrentActivity()); // the catchup should only be done // 1- the state is in catchup : the event stream might have gone to sleep between two catchups // 2- the thread is suspended // 3- the application has been launched by a push so there is no displayed activity canCatchup = (state == StreamAction.CATCHUP) || (state == StreamAction.PAUSE) || ((StreamAction.START == state) && (null == VectorApp.getCurrentActivity())); } if (canCatchup) { if (mSessions != null) { for (MXSession session : mSessions) { session.catchupEventStream(); } } else { Log.e(LOG_TAG, "catchup no session"); } setServiceState(StreamAction.CATCHUP); } else { Log.d(LOG_TAG, "No catchup is triggered because there is already a running event thread"); } } /** * internal resume method. */ private void resume() { Log.d(LOG_TAG, "## resume : resume the service"); if (mSessions != null) { for(MXSession session : mSessions) { session.resumeEventStream(); } } setServiceState(StreamAction.START); } /** * The GCM status has been updated (i.e disabled or enabled). */ private void gcmStatusUpdate() { Log.d(LOG_TAG, "## gcmStatusUpdate"); if (mIsForeground) { Log.d(LOG_TAG, "## gcmStatusUpdate : gcm status succeeds so stopForeground"); if (FOREGROUND_LISTENING_FOR_EVENTS == mForegroundServiceIdentifier) { stopForeground(true); mForegroundServiceIdentifier = -1; } mIsForeground = false; } updateServiceForegroundState(); } /** * Enable/disable the service foreground status. * The service is put in foreground ("Foreground process priority") when a sync polling is used, * to strongly reduce the likelihood of the App being killed. */ private void updateServiceForegroundState() { Log.d(LOG_TAG, "## updateServiceForegroundState"); MXSession session = Matrix.getInstance(getApplicationContext()).getDefaultSession(); if (null == session) { Log.e(LOG_TAG, "## updateServiceForegroundState(): no session"); return; } // GA issue if (null == mGcmRegistrationManager) { return; } if ((!mGcmRegistrationManager.useGCM() || !mGcmRegistrationManager.isServerRegistred()) && mGcmRegistrationManager.isBackgroundSyncAllowed() && mGcmRegistrationManager.areDeviceNotificationsAllowed()) { Log.d(LOG_TAG, "## updateServiceForegroundState : put the service in foreground"); if (-1 == mForegroundServiceIdentifier) { Notification notification = buildForegroundServiceNotification(); startForeground(NOTIF_ID_FOREGROUND_SERVICE, notification); mForegroundServiceIdentifier = FOREGROUND_LISTENING_FOR_EVENTS; } mIsForeground = true; } else { Log.d(LOG_TAG, "## updateServiceForegroundState : put the service in background"); if (FOREGROUND_LISTENING_FOR_EVENTS == mForegroundServiceIdentifier) { stopForeground(true); mForegroundServiceIdentifier = -1; } mIsForeground = false; } } //================================================================================ // notification management //================================================================================ /** * Compute an event unique identifier. * @param event the event * @return the uid identifier */ private static String computeEventUID(Event event) { if (null != event) { return (event.roomId + "-" + event.eventId); } else { return "invalid"; } } /** * @return the polling thread listener notification */ @SuppressLint("NewApi") private Notification buildForegroundServiceNotification() { // build the pending intent go to the home screen if this is clicked. Intent i = new Intent(this, VectorHomeActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0); // build the notification builder NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this); notifBuilder.setSmallIcon(R.drawable.permanent_notification_transparent); notifBuilder.setWhen(System.currentTimeMillis()); notifBuilder.setContentTitle(getString(R.string.app_name)); notifBuilder.setContentText(NOTIFICATION_SUB_TITLE); notifBuilder.setContentIntent(pi); // hide the notification from the status bar if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { notifBuilder.setPriority(NotificationCompat.PRIORITY_MIN); } Notification notification = notifBuilder.build(); notification.flags |= Notification.FLAG_NO_CLEAR; if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { // some devices crash if this field is not set // even if it is deprecated // setLatestEventInfo() is deprecated on Android M, so we try to use // reflection at runtime, to avoid compiler error: "Cannot resolve method.." try { Method deprecatedMethod = notification.getClass().getMethod("setLatestEventInfo", Context.class, CharSequence.class, CharSequence.class, PendingIntent.class); deprecatedMethod.invoke(notification, this, getString(R.string.app_name), NOTIFICATION_SUB_TITLE, pi); } catch (Exception ex) { Log.e(LOG_TAG, "## buildNotification(): Exception - setLatestEventInfo() Msg="+ex.getMessage()); } } return notification; } /** * Retrieve the room name. * @param session the session * @param room the room * @param event the event * @return the room name */ private String getRoomName(MXSession session, Room room, Event event) { String roomName = VectorUtils.getRoomDisplayName(EventStreamService.this, session, room); // avoid displaying the room Id // try to find the sender display name if (TextUtils.equals(roomName, room.getRoomId())) { roomName = room.getName(session.getMyUserId()); // avoid room Id as name if (TextUtils.equals(roomName, room.getRoomId()) && (null != event)) { User user = session.getDataHandler().getStore().getUser(event.sender); if (null != user) { roomName = user.displayname; } else { roomName = event.sender; } } } return roomName; } /** * Prepare a call notification. * Only the incoming calls are managed by now and have a dedicated notification. * @param event the event * @param bingRule the bing rule */ private void prepareCallNotification(Event event, BingRule bingRule) { // display only the invitation messages by now // because the other ones are not displayed. if (!event.getType().equals(Event.EVENT_TYPE_CALL_INVITE)) { Log.d(LOG_TAG, "prepareCallNotification : don't bing - Call invite"); return; } MXSession session = Matrix.getMXSession(getApplicationContext(), event.getMatrixId()); // invalid session ? // should never happen. // But it could be triggered because of multi accounts management. // The dedicated account is removing but some pushes are still received. if ((null == session) || !session.isAlive()) { Log.d(LOG_TAG, "prepareCallNotification : don't bing - no session"); return; } Room room = session.getDataHandler().getRoom(event.roomId); // invalid room ? if (null == room) { Log.d(LOG_TAG, "prepareCallNotification : don't bing - the room does not exist"); return; } String callId = null; try { callId = event.getContentAsJsonObject().get("call_id").getAsString(); } catch (Exception e) { Log.e(LOG_TAG, "prepareNotification : getContentAsJsonObject " + e.getMessage()); } if (!TextUtils.isEmpty(callId)) { displayIncomingCallNotification(session, room, event, callId, bingRule); } } /** * Prepare a notification for the expected event. * @param event the event * @param roomState the room state * @param bingRule the bing rule */ public void prepareNotification(Event event, RoomState roomState, BingRule bingRule) { String uid = computeEventUID(event); if (mPendingNotifications.indexOf(uid) >= 0) { Log.d(LOG_TAG, "prepareNotification : don't bing - the event was already binged"); checkNotification(); return; } mPendingNotifications.add(uid); // define a bing rule if it is not provided if (null == bingRule) { bingRule = mDefaultBingRule; } if (!mGcmRegistrationManager.areDeviceNotificationsAllowed()) { Log.d(LOG_TAG, "prepareNotification : the push has been disable on this device"); return; } if (event.isCallEvent()) { prepareCallNotification(event, bingRule); return; } final String roomId = event.roomId; // Just don't bing for the room the user's currently in if (!VectorApp.isAppInBackground() && (roomId != null) && event.roomId.equals(ViewedRoomTracker.getInstance().getViewedRoomId())) { Log.d(LOG_TAG, "prepareNotification : don't bing because it is the currently opened room"); return; } String senderID = event.getSender(); // FIXME: Support event contents with no body if (!event.getContent().getAsJsonObject().has("body")) { // only the membership events are supported if (!Event.EVENT_TYPE_STATE_ROOM_MEMBER.equals(event.getType()) && !event.isCallEvent()) { Log.d(LOG_TAG, "onBingEvent : don't bing - no body and not a call event"); return; } } MXSession session = Matrix.getMXSession(getApplicationContext(), event.getMatrixId()); // invalid session ? // should never happen. // But it could be triggered because of multi accounts management. // The dedicated account is removing but some pushes are still received. if ((null == session) || !session.isAlive()) { Log.d(LOG_TAG, "prepareNotification : don't bing - no session"); return; } Room room = session.getDataHandler().getRoom(roomId); // invalid room ? if (null == room) { Log.d(LOG_TAG, "prepareNotification : don't bing - the room does not exist"); return; } boolean isInvitationEvent = false; EventDisplay eventDisplay = new EventDisplay(getApplicationContext(), event, roomState); eventDisplay.setPrependMessagesWithAuthor(false); String body = eventDisplay.getTextualDisplay().toString(); if (TextUtils.isEmpty(body)) { Log.e(LOG_TAG, "prepareNotification : the event " + event.eventId + " cannot be displayed"); return; } if (Event.EVENT_TYPE_STATE_ROOM_MEMBER.equals(event.getType())) { try { isInvitationEvent = "invite".equals(event.getContentAsJsonObject().getAsJsonPrimitive("membership").getAsString()); } catch (Exception e) { Log.e(LOG_TAG, "prepareNotification : invitation parsing failed"); } } Bitmap largeBitmap = null; // when the event is an invitation one // don't check if the sender ID is known because the members list are not yet downloaded if (!isInvitationEvent) { // is there any avatar url if (!TextUtils.isEmpty(room.getAvatarUrl())) { int size = getApplicationContext().getResources().getDimensionPixelSize(R.dimen.profile_avatar_size); // check if the thumbnail is already downloaded File f = session.getMediasCache().thumbnailCacheFile(room.getAvatarUrl(), size); if (null != f) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = Bitmap.Config.ARGB_8888; try { largeBitmap = BitmapFactory.decodeFile(f.getPath(), options); } catch (OutOfMemoryError oom) { Log.e(LOG_TAG, "decodeFile failed with an oom"); } } else { session.getMediasCache().loadAvatarThumbnail(session.getHomeserverConfig(), new ImageView(getApplicationContext()), room.getAvatarUrl(), size); } } } mNotificationSessionId = session.getCredentials().userId; Log.d(LOG_TAG, "prepareNotification : with sound " + bingRule.isDefaultNotificationSound(bingRule.notificationSound())); String roomName = getRoomName(session, room, event); NotificationManagerCompat nm = NotificationManagerCompat.from(EventStreamService.this); NotificationCompat.Builder builder = new NotificationCompat.Builder(EventStreamService.this); builder.setWhen(event.getOriginServerTs()); builder.setContentTitle(roomName); builder.setContentText(body); builder.setSmallIcon(R.drawable.message_notification_transparent); builder.setGroup("riot"); builder.setGroupSummary(true); if (!isInvitationEvent) { NotificationCompat.MessagingStyle textStyle = new NotificationCompat.MessagingStyle("foo"); textStyle.setConversationTitle(roomName); // Append unread events from oldest to latest List<Event> unreadEvents = session.getDataHandler().getStore().unreadEvents(roomId, null); for (Event ev : unreadEvents) { EventDisplay evDisplay = new EventDisplay(getApplicationContext(), ev, roomState); String bd = evDisplay.getTextualDisplay().toString(); if (TextUtils.isEmpty(bd)) { continue; } String sender = ev.getSender(); String senderName = null; if (!session.getCredentials().userId.equals(sender)) { senderName = room.getMember(sender).getName(); } textStyle.addMessage(bd, ev.getOriginServerTs(), senderName); } mNotificationMessagesListByRoomId.put(roomId, textStyle); mLatestEventIdByRoomId.put(roomId, event.eventId); builder.setStyle(textStyle); } if (null != largeBitmap) { largeBitmap = NotificationUtils.createSquareBitmap(largeBitmap); builder.setLargeIcon(largeBitmap); } int highlightCount = room.getHighlightCount(); int notificationCount = room.getNotificationCount(); boolean is_bing = bingRule.isDefaultNotificationSound(bingRule.notificationSound()); if (is_bing) { // So that it pops up on screen. builder.setPriority(NotificationCompat.PRIORITY_HIGH); builder.setColor(ContextCompat.getColor(getApplicationContext(), R.color.vector_fuchsia_color)); } else if (highlightCount > 0) { builder.setPriority(NotificationCompat.PRIORITY_DEFAULT); builder.setColor(ContextCompat.getColor(getApplicationContext(), R.color.vector_fuchsia_color)); } else { builder.setPriority(NotificationCompat.PRIORITY_MIN); builder.setColor(Color.TRANSPARENT); } TaskStackBuilder stackBuilder; Intent intent; intent = new Intent(getBaseContext(), VectorRoomActivity.class); intent.putExtra(VectorRoomActivity.EXTRA_ROOM_ID, roomId); intent.putExtra(VectorRoomActivity.EXTRA_MATRIX_ID, session.getMyUserId()); stackBuilder = TaskStackBuilder.create(getBaseContext()) .addParentStack(VectorRoomActivity.class) .addNextIntent(intent); // android 4.3 issue // use a generator for the private requestCode. // When using 0, the intent is not created/launched when the user taps on the notification. // PendingIntent pendingIntent = stackBuilder.getPendingIntent((new Random()).nextInt(1000), PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(pendingIntent); Notification n = builder.build(); n.flags |= Notification.FLAG_SHOW_LIGHTS; n.defaults |= Notification.DEFAULT_LIGHTS; if (is_bing) { n.defaults |= Notification.DEFAULT_SOUND; } nm.notify(roomId, NOTIF_ID_MESSAGE, n); } /** * Trigger the latest prepared notification * @param checkNotification true to check if the prepared notification still makes sense. */ public void triggerPreparedNotification(boolean checkNotification) { if (null != mLatestNotification) { if (checkNotification) { // check first if the message has not been read checkNotification(); } // if it is still defined. if (null != mLatestNotification) { try { NotificationManagerCompat nm = NotificationManagerCompat.from(EventStreamService.this); // nm.cancelAll(); nm.notify((int)System.currentTimeMillis(), mLatestNotification); // turn the screen on if (mGcmRegistrationManager.isScreenTurnedOn()) { // turn the screen on for 3 seconds PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "MXEventListener"); wl.acquire(3000); wl.release(); } } catch (Exception e) { Log.e(LOG_TAG, "onLiveEventsChunkProcessed crashed " + e.getLocalizedMessage()); } mLatestNotification = null; } } } /** * Cancel the push notifications for a dedicated roomId. * If the roomId is null, cancel all the push notification. * @param accountId the account id * @param roomId the room id. */ public static void cancelNotificationsForRoomId(String accountId, String roomId) { Log.d(LOG_TAG, "cancelNotificationsForRoomId " + accountId + " - " + roomId); if (null != mActiveEventStreamService) { mActiveEventStreamService.cancelNotifications(accountId ,roomId); } } /** * Clear any displayed notification. */ private void clearNotification() { NotificationManager nm = (NotificationManager) EventStreamService.this.getSystemService(Context.NOTIFICATION_SERVICE); try { nm.cancelAll(); } catch (Exception e) { Log.e(LOG_TAG, "## clearNotification() failed " + e.getMessage()); } // reset the identifiers mNotificationSessionId = null; mNotificationMessagesListByRoomId.clear(); mLatestEventIdByRoomId.clear(); mLatestNotification = null; } /** * Clear any displayed notification for a dedicated room and session id. * @param accountId the account id. * @param roomId the room id. */ private void cancelNotifications(String accountId, String roomId) { Log.d(LOG_TAG, "cancelNotifications " + accountId + " - " + roomId); // sanity checks if ((null != accountId) && (null != roomId) && mNotificationMessagesListByRoomId.containsKey(roomId)) { NotificationManager nm = (NotificationManager) EventStreamService.this.getSystemService(Context.NOTIFICATION_SERVICE); try { nm.cancel(roomId, NOTIF_ID_MESSAGE); } catch (Exception e) { Log.e(LOG_TAG, "## cancelNotifications() failed " + e.getMessage()); } mNotificationMessagesListByRoomId.remove(roomId); mLatestEventIdByRoomId.remove(roomId); } } /** * Remove any pending notification. * It should be called when the application is logged out. */ public static void removeNotification() { if (null != mActiveEventStreamService) { mActiveEventStreamService.clearNotification(); } } /** * Check if a notification must be cleared because the linked event has been read, deleted ... */ public static void checkDisplayedNotifications() { if (null != mActiveEventStreamService) { mActiveEventStreamService.checkNotification(); } } /** * Check if the current displayed notification must be cleared * because it doesn't make sense anymore. */ private void checkNotification() { //Log.d(LOG_TAG, "checkNotification : session ID" + mNotificationSessionId + " - Notif ID " + mNotificationRoomId + " - Event id " + mNotificationEventId); for(String roomId : mNotificationMessagesListByRoomId.keySet()) { boolean clearNotification = true; MXSession session = Matrix.getInstance(this).getSession(mNotificationSessionId); if (null != session) { Room room = session.getDataHandler().getRoom(roomId); if (null != room) { Log.d(LOG_TAG, "checkNotification : the room exists"); // invitation notification if (!mLatestEventIdByRoomId.containsKey(roomId)) { Log.d(LOG_TAG, "checkNotification : room invitation case"); clearNotification = !room.isInvited(); } else { Log.d(LOG_TAG, "checkNotification : event case"); clearNotification = room.isEventRead(mLatestEventIdByRoomId.get(roomId)); if (!clearNotification) { NotificationCompat.MessagingStyle messagingStyle = mNotificationMessagesListByRoomId.get(roomId); List<Event> unreadEvents = session.getDataHandler().getStore().unreadEvents(roomId, null); // update the unread messages list // if ((null != messagingStyle) && (null != unreadEvents) && (messagingStyle.getMessages().size() != unreadEvents.size())) { messagingStyle.getMessages().clear(); for (Event ev: unreadEvents) { EventDisplay evDisplay = new EventDisplay(getApplicationContext(), ev, room.getLiveState()); String bd = evDisplay.getTextualDisplay().toString(); if (TextUtils.isEmpty(bd)) { continue; } String sender = ev.getSender(); String senderName = null; if (!session.getCredentials().userId.equals(sender)) { senderName = room.getMember(sender).getName(); } messagingStyle.addMessage(bd, ev.getOriginServerTs(), senderName); } } } } } else { Log.d(LOG_TAG, "checkNotification : the room does not exist"); } } if (clearNotification) { cancelNotifications(mNotificationSessionId, roomId); } } } /** * Display a permanent notification when there is an incoming call. * @param session the session * @param room the room * @param event the event * @param callId the callId * @param bingRule the bing rule. */ private void displayIncomingCallNotification(MXSession session, Room room, Event event, String callId, BingRule bingRule) { Log.d(LOG_TAG, "displayIncomingCallNotification : " + callId + " in " + room.getRoomId()); // the incoming call in progress is already displayed if (!TextUtils.isEmpty(mIncomingCallId)) { Log.d(LOG_TAG, "displayIncomingCallNotification : the incoming call in progress is already displayed"); } else if (!TextUtils.isEmpty(mCallIdInProgress)) { Log.d(LOG_TAG, "displayIncomingCallNotification : a 'call in progress' notification is displayed"); } // test if there is no active call else if (null == VectorCallViewActivity.getActiveCall()) { Log.d(LOG_TAG, "displayIncomingCallNotification : display the dedicated notification"); if ((null != bingRule) && bingRule.isCallRingNotificationSound(bingRule.notificationSound())) { VectorCallSoundManager.startRinging(); } Notification notification = NotificationUtils.buildIncomingCallNotification( EventStreamService.this, getRoomName(session, room, event), session.getMyUserId(), callId); if ((null != bingRule) && bingRule.isDefaultNotificationSound(bingRule.notificationSound())) { notification.defaults |= Notification.DEFAULT_SOUND; } startForeground(NOTIF_ID_FOREGROUND_SERVICE, notification); mForegroundServiceIdentifier = FOREGROUND_ID_INCOMING_CALL; mIncomingCallId = callId; // turn the screen on for 3 seconds PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "MXEventListener"); wl.acquire(3000); wl.release(); } else { Log.d(LOG_TAG, "displayIncomingCallNotification : do not display the incoming call notification because there is a pending call"); } } /** * Display a call in progress notificatin. * @param session the session * @param callId the callId */ public void displayCallInProgressNotification(MXSession session, Room room, String callId) { if (null != callId) { Notification notification = NotificationUtils.buildPendingCallNotification(getApplicationContext(), room.getName(session.getCredentials().userId), room.getRoomId(), session.getCredentials().userId, callId); startForeground(NOTIF_ID_FOREGROUND_SERVICE, notification); mForegroundServiceIdentifier = FOREGROUND_NOTIF_ID_PENDING_CALL; mCallIdInProgress = callId; } } /** * Hide the permanent call notifications */ public void hideCallNotifications() { NotificationManager nm = (NotificationManager) EventStreamService.this.getSystemService(Context.NOTIFICATION_SERVICE); // hide the call if ((FOREGROUND_NOTIF_ID_PENDING_CALL == mForegroundServiceIdentifier) || (FOREGROUND_ID_INCOMING_CALL == mForegroundServiceIdentifier)) { if (FOREGROUND_NOTIF_ID_PENDING_CALL == mForegroundServiceIdentifier) { mCallIdInProgress = null; } else { mIncomingCallId = null; } nm.cancel(NOTIF_ID_FOREGROUND_SERVICE); mForegroundServiceIdentifier = -1; stopForeground(true); updateServiceForegroundState(); } } }
notification_improvements First implementation
vector/src/main/java/im/vector/services/EventStreamService.java
notification_improvements First implementation
<ide><path>ector/src/main/java/im/vector/services/EventStreamService.java <ide> import android.support.v4.app.TaskStackBuilder; <ide> import android.support.v4.content.ContextCompat; <ide> import android.support.v4.content.res.ResourcesCompat; <add>import android.support.v4.util.Pair; <ide> import android.support.v7.app.NotificationCompat; <ide> import android.support.v4.app.NotificationManagerCompat; <ide> import android.text.TextUtils; <ide> import java.util.ArrayList; <ide> import java.util.Arrays; <ide> <add>import java.util.Collection; <add>import java.util.Collections; <ide> import java.util.HashMap; <add>import java.util.LinkedHashMap; <ide> import java.util.List; <ide> import java.util.Map; <ide> import java.util.Random; <ide> /** <ide> * store the notifications description <ide> */ <del> private String mNotificationSessionId = null; <del> private Map<String, NotificationCompat.MessagingStyle> mNotificationMessagesListByRoomId = new HashMap<>(); <del> private Map<String, String> mLatestEventIdByRoomId = new HashMap<>(); <del> <add> private LinkedHashMap<String, Pair<BingRule, Event>> mPendingNotifications = new LinkedHashMap<>(); <add> private Map<String, List<Pair<BingRule, String>>> mNotifiedMessagesByRoomId = null; <ide> <ide> /** <ide> * call in progress (foreground notification) <ide> * true when the service is in foreground ie the GCM registration failed or is disabled. <ide> */ <ide> private boolean mIsForeground = false; <del> <del> /** <del> * the latest built notification <del> */ <del> private Notification mLatestNotification = null; <del> <del> /** <del> * list the notifications found between two onLiveEventsChunkProcessed() <del> */ <del> private final ArrayList<String> mPendingNotifications = new ArrayList<>(); <ide> <ide> /** <ide> * GCM manager <ide> //================================================================================ <ide> <ide> /** <del> * Compute an event unique identifier. <del> * @param event the event <del> * @return the uid identifier <del> */ <del> private static String computeEventUID(Event event) { <del> if (null != event) { <del> return (event.roomId + "-" + event.eventId); <del> } else { <del> return "invalid"; <del> } <del> } <del> <del> /** <ide> * @return the polling thread listener notification <ide> */ <ide> @SuppressLint("NewApi") <ide> * @param bingRule the bing rule <ide> */ <ide> private void prepareCallNotification(Event event, BingRule bingRule) { <del> <ide> // display only the invitation messages by now <ide> // because the other ones are not displayed. <ide> if (!event.getType().equals(Event.EVENT_TYPE_CALL_INVITE)) { <ide> * @param bingRule the bing rule <ide> */ <ide> public void prepareNotification(Event event, RoomState roomState, BingRule bingRule) { <del> String uid = computeEventUID(event); <del> <del> if (mPendingNotifications.indexOf(uid) >= 0) { <add> if (mPendingNotifications.containsKey(event.eventId)) { <ide> Log.d(LOG_TAG, "prepareNotification : don't bing - the event was already binged"); <del> checkNotification(); <ide> return; <del> } <del> <del> mPendingNotifications.add(uid); <del> <del> // define a bing rule if it is not provided <del> if (null == bingRule) { <del> bingRule = mDefaultBingRule; <ide> } <ide> <ide> if (!mGcmRegistrationManager.areDeviceNotificationsAllowed()) { <ide> return; <ide> } <ide> <del> String senderID = event.getSender(); <ide> // FIXME: Support event contents with no body <ide> if (!event.getContent().getAsJsonObject().has("body")) { <ide> // only the membership events are supported <ide> return; <ide> } <ide> <del> boolean isInvitationEvent = false; <del> <del> EventDisplay eventDisplay = new EventDisplay(getApplicationContext(), event, roomState); <del> eventDisplay.setPrependMessagesWithAuthor(false); <del> String body = eventDisplay.getTextualDisplay().toString(); <del> <del> if (TextUtils.isEmpty(body)) { <del> Log.e(LOG_TAG, "prepareNotification : the event " + event.eventId + " cannot be displayed"); <del> return; <del> } <del> <del> if (Event.EVENT_TYPE_STATE_ROOM_MEMBER.equals(event.getType())) { <del> try { <del> isInvitationEvent = "invite".equals(event.getContentAsJsonObject().getAsJsonPrimitive("membership").getAsString()); <del> } catch (Exception e) { <del> Log.e(LOG_TAG, "prepareNotification : invitation parsing failed"); <del> } <del> } <del> <del> Bitmap largeBitmap = null; <del> <del> // when the event is an invitation one <del> // don't check if the sender ID is known because the members list are not yet downloaded <del> if (!isInvitationEvent) { <del> // is there any avatar url <del> if (!TextUtils.isEmpty(room.getAvatarUrl())) { <del> int size = getApplicationContext().getResources().getDimensionPixelSize(R.dimen.profile_avatar_size); <del> <del> // check if the thumbnail is already downloaded <del> File f = session.getMediasCache().thumbnailCacheFile(room.getAvatarUrl(), size); <del> <del> if (null != f) { <del> BitmapFactory.Options options = new BitmapFactory.Options(); <del> options.inPreferredConfig = Bitmap.Config.ARGB_8888; <del> try { <del> largeBitmap = BitmapFactory.decodeFile(f.getPath(), options); <del> } catch (OutOfMemoryError oom) { <del> Log.e(LOG_TAG, "decodeFile failed with an oom"); <del> } <del> } else { <del> session.getMediasCache().loadAvatarThumbnail(session.getHomeserverConfig(), new ImageView(getApplicationContext()), room.getAvatarUrl(), size); <del> } <del> } <del> } <del> <del> mNotificationSessionId = session.getCredentials().userId; <del> <del> Log.d(LOG_TAG, "prepareNotification : with sound " + bingRule.isDefaultNotificationSound(bingRule.notificationSound())); <del> <del> String roomName = getRoomName(session, room, event); <del> <del> NotificationManagerCompat nm = NotificationManagerCompat.from(EventStreamService.this); <del> <del> NotificationCompat.Builder builder = new NotificationCompat.Builder(EventStreamService.this); <del> builder.setWhen(event.getOriginServerTs()); <del> builder.setContentTitle(roomName); <del> builder.setContentText(body); <del> builder.setSmallIcon(R.drawable.message_notification_transparent); <del> <del> builder.setGroup("riot"); <del> builder.setGroupSummary(true); <del> <del> if (!isInvitationEvent) { <del> NotificationCompat.MessagingStyle textStyle = new NotificationCompat.MessagingStyle("foo"); <del> textStyle.setConversationTitle(roomName); <del> <del> // Append unread events from oldest to latest <del> List<Event> unreadEvents = session.getDataHandler().getStore().unreadEvents(roomId, null); <del> for (Event ev : unreadEvents) { <del> EventDisplay evDisplay = new EventDisplay(getApplicationContext(), ev, roomState); <del> String bd = evDisplay.getTextualDisplay().toString(); <del> if (TextUtils.isEmpty(bd)) { <del> continue; <del> } <del> <del> String sender = ev.getSender(); <del> String senderName = null; <del> if (!session.getCredentials().userId.equals(sender)) { <del> senderName = room.getMember(sender).getName(); <del> } <del> textStyle.addMessage(bd, ev.getOriginServerTs(), senderName); <del> } <del> <del> mNotificationMessagesListByRoomId.put(roomId, textStyle); <del> mLatestEventIdByRoomId.put(roomId, event.eventId); <del> builder.setStyle(textStyle); <del> } <del> <del> if (null != largeBitmap) { <del> largeBitmap = NotificationUtils.createSquareBitmap(largeBitmap); <del> builder.setLargeIcon(largeBitmap); <del> } <del> <del> int highlightCount = room.getHighlightCount(); <del> int notificationCount = room.getNotificationCount(); <del> <del> boolean is_bing = bingRule.isDefaultNotificationSound(bingRule.notificationSound()); <del> <del> if (is_bing) { <del> // So that it pops up on screen. <del> builder.setPriority(NotificationCompat.PRIORITY_HIGH); <del> builder.setColor(ContextCompat.getColor(getApplicationContext(), R.color.vector_fuchsia_color)); <del> } else if (highlightCount > 0) { <del> builder.setPriority(NotificationCompat.PRIORITY_DEFAULT); <del> builder.setColor(ContextCompat.getColor(getApplicationContext(), R.color.vector_fuchsia_color)); <del> } else { <del> builder.setPriority(NotificationCompat.PRIORITY_MIN); <del> builder.setColor(Color.TRANSPARENT); <del> } <del> <del> TaskStackBuilder stackBuilder; <del> Intent intent; <del> <del> intent = new Intent(getBaseContext(), VectorRoomActivity.class); <del> intent.putExtra(VectorRoomActivity.EXTRA_ROOM_ID, roomId); <del> intent.putExtra(VectorRoomActivity.EXTRA_MATRIX_ID, session.getMyUserId()); <del> <del> stackBuilder = TaskStackBuilder.create(getBaseContext()) <del> .addParentStack(VectorRoomActivity.class) <del> .addNextIntent(intent); <del> <del> <del> // android 4.3 issue <del> // use a generator for the private requestCode. <del> // When using 0, the intent is not created/launched when the user taps on the notification. <del> // <del> PendingIntent pendingIntent = stackBuilder.getPendingIntent((new Random()).nextInt(1000), PendingIntent.FLAG_UPDATE_CURRENT); <del> builder.setContentIntent(pendingIntent); <del> <del> Notification n = builder.build(); <del> n.flags |= Notification.FLAG_SHOW_LIGHTS; <del> n.defaults |= Notification.DEFAULT_LIGHTS; <del> <del> <del> <del> if (is_bing) { <del> n.defaults |= Notification.DEFAULT_SOUND; <del> } <del> <del> nm.notify(roomId, NOTIF_ID_MESSAGE, n); <del> } <del> <del> /** <del> * Trigger the latest prepared notification <del> * @param checkNotification true to check if the prepared notification still makes sense. <del> */ <del> public void triggerPreparedNotification(boolean checkNotification) { <del> if (null != mLatestNotification) { <del> if (checkNotification) { <del> // check first if the message has not been read <del> checkNotification(); <del> } <del> <del> // if it is still defined. <del> if (null != mLatestNotification) { <del> try { <del> NotificationManagerCompat nm = NotificationManagerCompat.from(EventStreamService.this); <del>// nm.cancelAll(); <del> nm.notify((int)System.currentTimeMillis(), mLatestNotification); <del> <del> // turn the screen on <del> if (mGcmRegistrationManager.isScreenTurnedOn()) { <del> // turn the screen on for 3 seconds <del> PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); <del> PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "MXEventListener"); <del> wl.acquire(3000); <del> wl.release(); <del> } <del> <del> <del> } catch (Exception e) { <del> Log.e(LOG_TAG, "onLiveEventsChunkProcessed crashed " + e.getLocalizedMessage()); <del> } <del> <del> mLatestNotification = null; <del> } <del> } <del> } <del> <add> mPendingNotifications.put(event.eventId, new Pair<>(bingRule, event)); <add> } <ide> <ide> /** <ide> * Cancel the push notifications for a dedicated roomId. <ide> } <ide> <ide> // reset the identifiers <del> mNotificationSessionId = null; <del> mNotificationMessagesListByRoomId.clear(); <del> mLatestEventIdByRoomId.clear(); <del> mLatestNotification = null; <del> } <del> <del> /** <del> * Clear any displayed notification for a dedicated room and session id. <del> * @param accountId the account id. <del> * @param roomId the room id. <del> */ <del> private void cancelNotifications(String accountId, String roomId) { <del> Log.d(LOG_TAG, "cancelNotifications " + accountId + " - " + roomId); <del> <del> // sanity checks <del> if ((null != accountId) && (null != roomId) && mNotificationMessagesListByRoomId.containsKey(roomId)) { <del> <del> NotificationManager nm = (NotificationManager) EventStreamService.this.getSystemService(Context.NOTIFICATION_SERVICE); <del> try { <del> nm.cancel(roomId, NOTIF_ID_MESSAGE); <del> } catch (Exception e) { <del> Log.e(LOG_TAG, "## cancelNotifications() failed " + e.getMessage()); <del> } <del> <del> mNotificationMessagesListByRoomId.remove(roomId); <del> mLatestEventIdByRoomId.remove(roomId); <del> } <add> mPendingNotifications.clear(); <add> mNotifiedMessagesByRoomId.clear(); <ide> } <ide> <ide> /** <ide> */ <ide> public static void checkDisplayedNotifications() { <ide> if (null != mActiveEventStreamService) { <del> mActiveEventStreamService.checkNotification(); <add> mActiveEventStreamService.triggerPreparedNotification(false); <add> } <add> } <add> <add> private void cancelNotifications(String accountId, String roomId) { <add> if (mNotifiedMessagesByRoomId.containsKey(roomId)) { <add> mNotifiedMessagesByRoomId = null; <add> triggerPreparedNotification(false); <add> } <add> } <add> <add> /** <add> * Trigger the latest prepared notification <add> * @param checkNotification true to check if the prepared notification still makes sense. <add> */ <add> public void triggerPreparedNotification(boolean checkNotification) { <add> Pair<BingRule, Event> eventToNotify = getEventToNotify(); <add> <add> if (null != eventToNotify) { <add> mNotifiedMessagesByRoomId = null; <add> } <add> <add> boolean isNotifUpdated = refreshNotifiedMessagesList(); <add> <add> if (isNotifUpdated) { <add> // TODO add multi sessions <add> MXSession session = Matrix.getInstance(getBaseContext()).getDefaultSession(); <add> <add> NotificationManagerCompat nm = NotificationManagerCompat.from(EventStreamService.this); <add> <add> // no more notifications <add> if (mNotifiedMessagesByRoomId.size() == 0) { <add> nm.cancel(NOTIF_ID_MESSAGE); <add> } else { <add> boolean isBackgroundNotif = (null == eventToNotify); <add> Event event; <add> Room room; <add> BingRule bingRule; <add> <add> // use the first notified event to refresh the notification <add> if (isBackgroundNotif) { <add> String roomId = mNotifiedMessagesByRoomId.keySet().iterator().next(); <add> Pair<BingRule, String> pair = mNotifiedMessagesByRoomId.get(roomId).get(0); <add> <add> room = session.getDataHandler().getStore().getRoom(roomId); <add> event = session.getDataHandler().getStore().getEvent(pair.second, roomId); <add> bingRule = pair.first; <add> } else { <add> event = eventToNotify.second; <add> room = session.getDataHandler().getStore().getRoom(event.roomId); <add> bingRule = eventToNotify.first; <add> } <add> <add> boolean isInvitationEvent = false; <add> <add> EventDisplay eventDisplay = new EventDisplay(getApplicationContext(), event, room.getLiveState()); <add> eventDisplay.setPrependMessagesWithAuthor(true); <add> String body = eventDisplay.getTextualDisplay().toString(); <add> <add> if (Event.EVENT_TYPE_STATE_ROOM_MEMBER.equals(event.getType())) { <add> try { <add> isInvitationEvent = "invite".equals(event.getContentAsJsonObject().getAsJsonPrimitive("membership").getAsString()); <add> } catch (Exception e) { <add> Log.e(LOG_TAG, "prepareNotification : invitation parsing failed"); <add> } <add> } <add> <add> Bitmap largeBitmap = null; <add> <add> // when the event is an invitation one <add> // don't check if the sender ID is known because the members list are not yet downloaded <add> if (!isInvitationEvent) { <add> // is there any avatar url <add> if (!TextUtils.isEmpty(room.getAvatarUrl())) { <add> int size = getApplicationContext().getResources().getDimensionPixelSize(R.dimen.profile_avatar_size); <add> <add> // check if the thumbnail is already downloaded <add> File f = session.getMediasCache().thumbnailCacheFile(room.getAvatarUrl(), size); <add> <add> if (null != f) { <add> BitmapFactory.Options options = new BitmapFactory.Options(); <add> options.inPreferredConfig = Bitmap.Config.ARGB_8888; <add> try { <add> largeBitmap = BitmapFactory.decodeFile(f.getPath(), options); <add> } catch (OutOfMemoryError oom) { <add> Log.e(LOG_TAG, "decodeFile failed with an oom"); <add> } <add> } else { <add> session.getMediasCache().loadAvatarThumbnail(session.getHomeserverConfig(), new ImageView(getApplicationContext()), room.getAvatarUrl(), size); <add> } <add> } <add> } <add> <add> //mNotificationSessionId = session.getCredentials().userId; <add> <add> Log.d(LOG_TAG, "prepareNotification : with sound " + bingRule.isDefaultNotificationSound(bingRule.notificationSound())); <add> <add> String roomName = getRoomName(session, room, event); <add> <add> NotificationCompat.Builder builder = new NotificationCompat.Builder(EventStreamService.this); <add> builder.setWhen(event.getOriginServerTs()); <add> builder.setContentTitle(roomName); <add> builder.setContentText(body); <add> <add> builder.setGroup("riot"); <add> builder.setGroupSummary(true); <add> <add> NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); <add> <add> int sum = 0; <add> <add> // TODO manage order <add> for(String roomId : mNotifiedMessagesByRoomId.keySet()) { <add> room = session.getDataHandler().getRoom(roomId); <add> roomName = getRoomName(session, room, null); <add> <add> inboxStyle.addLine(roomName + " : " + session.getDataHandler().getStore().unreadEvents(roomId, null).size() + " unread events"); <add> sum += session.getDataHandler().getStore().unreadEvents(roomId, null).size(); <add> } <add> <add> inboxStyle.setBigContentTitle("Riot"); <add> inboxStyle.setSummaryText(sum + " unread messages in " + mNotifiedMessagesByRoomId.keySet().size() + " rooms"); <add> builder.setStyle(inboxStyle); <add> <add> if (mNotifiedMessagesByRoomId.keySet().size() == 1) { <add> if (null != largeBitmap) { <add> largeBitmap = NotificationUtils.createSquareBitmap(largeBitmap); <add> builder.setLargeIcon(largeBitmap); <add> } <add> } else { <add> <add> } <add> <add> builder.setSmallIcon(R.drawable.message_notification_transparent); <add> <add> int highlightCount = room.getHighlightCount(); <add> <add> boolean is_bing = bingRule.isDefaultNotificationSound(bingRule.notificationSound()); <add> <add> if (isBackgroundNotif) { <add> builder.setPriority(NotificationCompat.PRIORITY_MIN); <add> } else if (is_bing) { <add> // So that it pops up on screen. <add> builder.setPriority(NotificationCompat.PRIORITY_HIGH); <add> builder.setColor(ContextCompat.getColor(getApplicationContext(), R.color.vector_fuchsia_color)); <add> } else if (highlightCount > 0) { <add> builder.setPriority(NotificationCompat.PRIORITY_DEFAULT); <add> builder.setColor(ContextCompat.getColor(getApplicationContext(), R.color.vector_fuchsia_color)); <add> } else { <add> builder.setPriority(NotificationCompat.PRIORITY_MIN); <add> builder.setColor(Color.TRANSPARENT); <add> } <add> <add> // TODO add quick reply <add> <add> Notification n = builder.build(); <add> n.flags |= Notification.FLAG_SHOW_LIGHTS; <add> n.defaults |= Notification.DEFAULT_LIGHTS; <add> <add> if (is_bing && !isBackgroundNotif) { <add> n.defaults |= Notification.DEFAULT_SOUND; <add> } <add> <add> nm.notify(NOTIF_ID_MESSAGE, n); <add> } <ide> } <ide> } <ide> <ide> * Check if the current displayed notification must be cleared <ide> * because it doesn't make sense anymore. <ide> */ <del> private void checkNotification() { <del> //Log.d(LOG_TAG, "checkNotification : session ID" + mNotificationSessionId + " - Notif ID " + mNotificationRoomId + " - Event id " + mNotificationEventId); <del> <del> for(String roomId : mNotificationMessagesListByRoomId.keySet()) { <del> boolean clearNotification = true; <del> <del> MXSession session = Matrix.getInstance(this).getSession(mNotificationSessionId); <del> <del> if (null != session) { <del> Room room = session.getDataHandler().getRoom(roomId); <del> <del> if (null != room) { <del> Log.d(LOG_TAG, "checkNotification : the room exists"); <del> <del> // invitation notification <del> if (!mLatestEventIdByRoomId.containsKey(roomId)) { <del> Log.d(LOG_TAG, "checkNotification : room invitation case"); <del> clearNotification = !room.isInvited(); <del> } else { <del> Log.d(LOG_TAG, "checkNotification : event case"); <del> clearNotification = room.isEventRead(mLatestEventIdByRoomId.get(roomId)); <del> <del> if (!clearNotification) { <del> NotificationCompat.MessagingStyle messagingStyle = mNotificationMessagesListByRoomId.get(roomId); <del> List<Event> unreadEvents = session.getDataHandler().getStore().unreadEvents(roomId, null); <del> <del> // update the unread messages list <del> // <del> if ((null != messagingStyle) && <del> (null != unreadEvents) && <del> (messagingStyle.getMessages().size() != unreadEvents.size())) { <del> messagingStyle.getMessages().clear(); <del> <del> for (Event ev: unreadEvents) { <del> EventDisplay evDisplay = new EventDisplay(getApplicationContext(), ev, room.getLiveState()); <del> String bd = evDisplay.getTextualDisplay().toString(); <del> if (TextUtils.isEmpty(bd)) { <del> continue; <add> private Pair<BingRule, Event> getEventToNotify() { <add> // TODO add multi sessions <add> MXSession session = Matrix.getInstance(getBaseContext()).getDefaultSession(); <add> // notified only the latest unread message <add> List<Pair<BingRule, Event>> pairs = new ArrayList<>(mPendingNotifications.values()); <add> <add> Collections.reverse(pairs); <add> <add> for(Pair<BingRule, Event> pair : pairs) { <add> Event event = pair.second; <add> Room room = session.getDataHandler().getRoom(event.roomId); <add> <add> // test if the message has not been read <add> if ((null != room) && !room.isEventRead(event.eventId)) { <add> // test if the message is displayable <add> EventDisplay eventDisplay = new EventDisplay(getApplicationContext(), event, room.getLiveState()); <add> eventDisplay.setPrependMessagesWithAuthor(false); <add> String body = eventDisplay.getTextualDisplay().toString(); <add> <add> if (!TextUtils.isEmpty(body)) { <add> mPendingNotifications.clear(); <add> return pair; <add> } <add> } <add> } <add> <add> mPendingNotifications.clear(); <add> return null; <add> } <add> <add> //private LinkedHashMap<String, Event> mPendingNotifications = new LinkedHashMap<>(); <add> //private Map<String, List<Pair<BingRule, String>>> mNotifiedMessagesByRoomId = null; <add> /** <add> * Refresh the notified messages list if it was not yet done. <add> * @return true if there is an update <add> */ <add> private boolean refreshNotifiedMessagesList() { <add> // TODO add multi sessions <add> MXSession session = Matrix.getInstance(getBaseContext()).getDefaultSession(); <add> IMXStore store = session.getDataHandler().getStore(); <add> <add> if (null == mNotifiedMessagesByRoomId) { <add> mNotifiedMessagesByRoomId = new HashMap<>(); <add> Collection<Room> rooms = store.getRooms(); <add> <add> for(Room room : rooms) { <add> // invitation : add the dedicated event <add> if (room.isInvited()) { <add> Collection<Event> events = store.getRoomMessages(room.getRoomId()); <add> <add> if (null != events) { <add> for (Event event : events) { <add> if (Event.EVENT_TYPE_STATE_ROOM_MEMBER.equals(event.getType())) { <add> try { <add> if ("invite".equals(event.getContentAsJsonObject().getAsJsonPrimitive("membership").getAsString())) { <add> BingRule rule = session.fulfillRule(event); <add> <add> if (null != rule) { <add> List<Pair<BingRule, String>> list = new ArrayList<>(); <add> list.add(new Pair<>(rule, event.eventId)); <add> <add> mNotifiedMessagesByRoomId.put(room.getRoomId(), list); <add> } <ide> } <del> <del> String sender = ev.getSender(); <del> String senderName = null; <del> if (!session.getCredentials().userId.equals(sender)) { <del> senderName = room.getMember(sender).getName(); <del> } <del> messagingStyle.addMessage(bd, ev.getOriginServerTs(), senderName); <add> } catch (Exception e) { <add> Log.e(LOG_TAG, "initNotifiedMessagesList : invitation parsing failed"); <ide> } <ide> } <ide> } <ide> } <ide> } else { <del> Log.d(LOG_TAG, "checkNotification : the room does not exist"); <del> } <del> } <del> <del> if (clearNotification) { <del> cancelNotifications(mNotificationSessionId, roomId); <del> } <add> List<Event> unreadEvents = session.getDataHandler().getStore().unreadEvents(room.getRoomId(), null); <add> <add> if ((null != unreadEvents) && unreadEvents.size() > 0) { <add> List<Pair<BingRule, String>> list = new ArrayList<>(); <add> <add> for (Event event : unreadEvents) { <add> BingRule rule = session.fulfillRule(event); <add> if (null != rule) { <add> list.add(new Pair<>(rule, event.eventId)); <add> } <add> } <add> <add> if (list.size() > 0) { <add> mNotifiedMessagesByRoomId.put(room.getRoomId(), list); <add> } <add> } <add> } <add> } <add> <add> return true; <add> } else { <add> boolean isUpdated = false; <add> List<String> roomIds = new ArrayList<>(mNotifiedMessagesByRoomId.keySet()); <add> <add> for(String roomId : roomIds) { <add> Room room = store.getRoom(roomId); <add> <add> // the room does not exist anymore <add> if (null == room) { <add> mNotifiedMessagesByRoomId.remove(roomId); <add> isUpdated = true; <add> } else { <add> List<Pair<BingRule, String>> events = mNotifiedMessagesByRoomId.get(roomId); <add> <add> // search for the read messages <add> for(int i = 0; i < events.size(); ) { <add> Pair<BingRule, String> pair = events.get(i); <add> <add> if (room.isEventRead(pair.second)) { <add> events.remove(i); <add> isUpdated = true; <add> } else { <add> i++; <add> } <add> } <add> <add> if (0 == events.size()) { <add> mNotifiedMessagesByRoomId.remove(roomId); <add> isUpdated = true; <add> } <add> } <add> } <add> <add> return isUpdated; <ide> } <ide> } <ide>
Java
bsd-3-clause
3ee8511d07fa6889a60ccbd3904195266cdd4476
0
hypery2k/tracee,Hippoom/tracee,SvenBunge/tracee,danielwegener/tracee,tracee/tracee
package io.tracee; import javax.xml.namespace.QName; public final class TraceeConstants { private TraceeConstants() { } // TPIC = TracEE propagated invocation context public static final String HTTP_HEADER_NAME = "TPIC"; public static final String JMS_HEADER_NAME = "TPIC"; public static final String SESSION_ID_KEY = "traceeSessionId"; public static final String REQUEST_ID_KEY = "traceeRequestId"; public static final String SOAP_HEADER_NAME = "tpic"; public static final String SOAP_HEADER_NAMESPACE = "http://tracee.io/tpic/1.0"; public static final QName SOAP_HEADER_QNAME = new QName(SOAP_HEADER_NAMESPACE,SOAP_HEADER_NAME); }
api/src/main/java/io/tracee/TraceeConstants.java
package io.tracee; import javax.xml.namespace.QName; public final class TraceeConstants { private TraceeConstants() { } // TPIC = TracEE propagated invocation context public static final String HTTP_HEADER_NAME = "TPIC"; public static final String JMS_HEADER_NAME = "TPIC"; public static final String SESSION_ID_KEY = "traceeSessionId"; public static final String REQUEST_ID_KEY = "traceeRequestId"; public static final String PROFILE_HIDE_INBOUND = "HideInbound"; public static final String PROFILE_HIDE_OUTBOUND = "HideOutbound"; public static final String SOAP_HEADER_NAMESPACE = "http://tracee.io/tpic/1.0"; public static final String SOAP_HEADER_NAME = "tpic"; public static final QName SOAP_HEADER_QNAME = new QName(SOAP_HEADER_NAMESPACE,SOAP_HEADER_NAME); }
Remove unused constants
api/src/main/java/io/tracee/TraceeConstants.java
Remove unused constants
<ide><path>pi/src/main/java/io/tracee/TraceeConstants.java <ide> public static final String SESSION_ID_KEY = "traceeSessionId"; <ide> public static final String REQUEST_ID_KEY = "traceeRequestId"; <ide> <del> public static final String PROFILE_HIDE_INBOUND = "HideInbound"; <del> public static final String PROFILE_HIDE_OUTBOUND = "HideOutbound"; <del> <add> public static final String SOAP_HEADER_NAME = "tpic"; <ide> public static final String SOAP_HEADER_NAMESPACE = "http://tracee.io/tpic/1.0"; <del> public static final String SOAP_HEADER_NAME = "tpic"; <ide> public static final QName SOAP_HEADER_QNAME = new QName(SOAP_HEADER_NAMESPACE,SOAP_HEADER_NAME); <ide> }
JavaScript
apache-2.0
871f7c7396998c5c22af348aa71fe0557e78b676
0
chtyim/cdap,mpouttuclarke/cdap,anthcp/cdap,hsaputra/cdap,caskdata/cdap,mpouttuclarke/cdap,anthcp/cdap,caskdata/cdap,mpouttuclarke/cdap,chtyim/cdap,chtyim/cdap,hsaputra/cdap,caskdata/cdap,hsaputra/cdap,mpouttuclarke/cdap,anthcp/cdap,caskdata/cdap,hsaputra/cdap,caskdata/cdap,anthcp/cdap,caskdata/cdap,chtyim/cdap,chtyim/cdap,hsaputra/cdap,chtyim/cdap,mpouttuclarke/cdap,anthcp/cdap
/** * Operation 2.8 */ angular.module(PKG.name+'.feature.dashboard') /* ------------------------------------------------------ */ .controller('OpsCdapCtrl', function ($scope, opshelper, $rootScope) { var panels = [ // Format: // [ Widget Title, context, [metricNames], line-type (options are in addwdgt-ctrl.js ] [ 'Router requests', '', ['system.request.received','system.response.client-error', 'system.response.successful'], 'c3-scatter', { sizeX: 4, sizeY: 2, row: 0, col: 0 } ], [ 'Dataset Service', 'component.dataset~service', ['system.request.received','system.response.client-error','system.response.successful'], 'c3-scatter', { sizeX: 2, sizeY: 2, row: 0, col: 4 } ], [ 'Transaction Commit', '', ['system.canCommit', 'system.commit', 'system.start.long', 'system.start.short'], 'c3-area-spline', { sizeX: 2, sizeY: 1, row: 2, col: 0 } ], [ 'Transaction Latency', '', ['system.commit.latency', 'system.start.short.latency'], 'c3-area-spline', { sizeX: 2, sizeY: 1, row: 2, col: 2 } ], [ 'System Error and Warnings', '', ['system.services.log.error', 'system.services.log.warn'], 'c3-area-step', { sizeX: 2, sizeY: 1, row: 2, col: 4 } ], [ 'Explore Service', 'component.explore~service', ['system.request.received','system.response.successful'], 'c3-area-spline', { sizeX: 2, sizeY: 1, row: 3, col: 0 } ], [ 'Events Processed', 'namespace.*', ['system.process.events.processed'], 'c3-line', { sizeX: 4, sizeY: 1, row: 3, col: 2 } ], [ 'Bytes Store', 'namespace.*', ['system.dataset.store.bytes'], 'c3-line', { sizeX: 2, sizeY: 1, row: 4, col: 0 } ], [ 'Dataset Read/Writes', 'namespace.*', ['system.dataset.store.writes' ,'system.dataset.store.reads'], 'c3-area-spline', { sizeX: 2, sizeY: 1, row: 4, col: 2 } ], [ 'Containers Used', 'namespace.*', ['system.resources.used.containers', 'system.process.instance'], 'c3-area-step', { sizeX: 2, sizeY: 1, row: 4, col: 4 } ] ]; $scope.currentBoard = opshelper.createBoardFromPanels(panels); $scope.gridsterOpts = { rowHeight: '280', columns: 6, mobileBreakPoint: 600, resizable: { enabled: true, start: function(event, uiWidget, $element) {}, // optional callback fired when resize is started, resize: function(event, uiWidget, $element) {}, // optional callback fired when item is resized, stop: function(event, uiWidget, $element) { var resizedHeight = parseInt(uiWidget[0].style.height, 10), resizedWidth = parseInt(uiWidget[0].style.width, 10); $element.height = (resizedHeight < 300 ? 200: resizedHeight - 70); $element.width = (resizedWidth < 450? 370: resizedWidth - 32); } // optional callback fired when item is finished resizing } }; }) .controller('OpsAppsCtrl', function ($scope, $state, myHelpers, MyDataSource) { var dataSrc = new MyDataSource($scope); $scope.apps = []; dataSrc .request({ _cdapNsPath: '/apps' }, function (apps) { $scope.apps = apps; var m = ['vcores', 'containers', 'memory']; for (var i = 0; i < m.length; i++) { dataSrc .poll({ _cdapPath: '/metrics/query' + '?tag=namespace:system' + '&metric=system.resources.used.' + m[i] + '&groupBy=app', method: 'POST' }, setMetric); } }); function setMetric(r) { angular.forEach($scope.apps, function (app) { angular.forEach(r.series, function (s) { if(app.id === s.grouping.app) { myHelpers.deepSet( app, 'metric.' + s.metricName.split('.').pop(), s.data[0].value ); } }); }); } }) /* ------------------------------------------------------ */ .factory('opshelper', function (Widget, $timeout) { function createWidget(title, context, metricNames, type) { return new Widget({title: title, type: type, isLive: true, metric: { context: context, names: metricNames, startTime: 'now-3600s', endTime: 'now', resolution: '1m' }, interval: 15000 }); } function createBoardFromPanels(panels) { var widgets = []; panels.forEach(function(panel) { var widget = createWidget(panel[0], panel[1], panel[2], panel[3]); angular.extend(widget, panel[4]); widgets.push(widget); }); // Note: title is not currently used in the view return {title : "System metrics", columns : widgets}; } return { createBoardFromPanels: createBoardFromPanels }; }) ;
cdap-ui/app/features/operations/ops-ctrl.js
/** * Operation 2.8 */ angular.module(PKG.name+'.feature.dashboard') /* ------------------------------------------------------ */ .controller('OpsCdapCtrl', function ($scope, opshelper, $rootScope) { var panels = [ // Format: // [ Widget Title, context, [metricNames], line-type (options are in addwdgt-ctrl.js ] [ 'Router requests', '', ['system.request.received','system.response.client-error', 'system.response.successful'], 'c3-scatter', { sizeX: 4, sizeY: 2, row: 0, col: 0 } ], [ 'Dataset Service', 'component.dataset~service', ['system.request.received','system.response.client-error','system.response.successful'], 'c3-scatter', { sizeX: 2, sizeY: 2, row: 0, col: 4 } ], [ 'Transaction Commit', '', ['system.canCommit', 'system.commit', 'system.start.long', 'system.start.short'], 'c3-area-spline', { sizeX: 2, sizeY: 1, row: 2, col: 0 } ], [ 'Transaction Latency', '', ['system.commit.latency', 'system.start.short.latency'], 'c3-area-spline', { sizeX: 2, sizeY: 1, row: 2, col: 2 } ], [ 'System Error and Warnings', '', ['system.services.log.error', 'system.services.log.warn'], 'c3-area-step', { sizeX: 2, sizeY: 1, row: 2, col: 4 } ], [ 'Explore Service', 'component.explore~service', ['system.request.received','system.response.successful'], 'c3-area-spline', { sizeX: 2, sizeY: 1, row: 3, col: 0 } ], [ 'Events Processed', 'namespace.*', ['system.process.events.processed'], 'c3-line', { sizeX: 4, sizeY: 1, row: 3, col: 2 } ], [ 'Bytes Store', 'namespace.*', ['system.dataset.store.bytes'], 'c3-line', { sizeX: 2, sizeY: 1, row: 4, col: 0 } ], [ 'Dataset Read/Writes', 'namespace.*', ['system.dataset.store.writes' ,'system.dataset.store.reads'], 'c3-area-spline', { sizeX: 2, sizeY: 1, row: 4, col: 2 } ], [ 'Containers Used', 'namespace.*', ['system.resources.used.containers', 'system.process.instance'], 'c3-area-step', { sizeX: 2, sizeY: 1, row: 4, col: 4 } ] ]; $scope.currentBoard = opshelper.createBoardFromPanels(panels); $scope.gridsterOpts = { rowHeight: '280', columns: 6, mobileBreakPoint: 600, resizable: { enabled: true, start: function(event, uiWidget, $element) {}, // optional callback fired when resize is started, resize: function(event, uiWidget, $element) {}, // optional callback fired when item is resized, stop: function(event, uiWidget, $element) { var resizedHeight = parseInt(uiWidget[0].style.height, 10); if (resizedHeight < 300) { $element.height = 200; } else { $element.height = resizedHeight - 70; } console.info("Resized"); } // optional callback fired when item is finished resizing }, }; }) .controller('OpsAppsCtrl', function ($scope, $state, myHelpers, MyDataSource) { var dataSrc = new MyDataSource($scope); $scope.apps = []; dataSrc .request({ _cdapNsPath: '/apps' }, function (apps) { $scope.apps = apps; var m = ['vcores', 'containers', 'memory']; for (var i = 0; i < m.length; i++) { dataSrc .poll({ _cdapPath: '/metrics/query' + '?tag=namespace:system' + '&metric=system.resources.used.' + m[i] + '&groupBy=app', method: 'POST' }, setMetric); } }); function setMetric(r) { angular.forEach($scope.apps, function (app) { angular.forEach(r.series, function (s) { if(app.id === s.grouping.app) { myHelpers.deepSet( app, 'metric.' + s.metricName.split('.').pop(), s.data[0].value ); } }); }); } }) /* ------------------------------------------------------ */ .factory('opshelper', function (Widget, $timeout) { function createWidget(title, context, metricNames, type) { return new Widget({title: title, type: type, isLive: true, metric: { context: context, names: metricNames, startTime: 'now-3600s', endTime: 'now', resolution: '1m' }, interval: 15000 }); } function createBoardFromPanels(panels) { var widgets = []; panels.forEach(function(panel) { var widget = createWidget(panel[0], panel[1], panel[2], panel[3]); angular.extend(widget, panel[4]); widgets.push(widget); }); console.info(angular.copy(widgets)); // Note: title is not currently used in the view return {title : "System metrics", columns : widgets}; } return { createBoardFromPanels: createBoardFromPanels }; }) ;
Minor cleaup on standard dashboard (ops-ctrl.js)
cdap-ui/app/features/operations/ops-ctrl.js
Minor cleaup on standard dashboard (ops-ctrl.js)
<ide><path>dap-ui/app/features/operations/ops-ctrl.js <ide> start: function(event, uiWidget, $element) {}, // optional callback fired when resize is started, <ide> resize: function(event, uiWidget, $element) {}, // optional callback fired when item is resized, <ide> stop: function(event, uiWidget, $element) { <del> var resizedHeight = parseInt(uiWidget[0].style.height, 10); <del> if (resizedHeight < 300) { <del> $element.height = 200; <del> } else { <del> $element.height = resizedHeight - 70; <del> } <del> console.info("Resized"); <add> var resizedHeight = parseInt(uiWidget[0].style.height, 10), <add> resizedWidth = parseInt(uiWidget[0].style.width, 10); <add> <add> $element.height = (resizedHeight < 300 ? 200: resizedHeight - 70); <add> $element.width = (resizedWidth < 450? 370: resizedWidth - 32); <ide> } // optional callback fired when item is finished resizing <del> }, <add> } <ide> }; <ide> <ide> }) <ide> angular.extend(widget, panel[4]); <ide> widgets.push(widget); <ide> }); <del> console.info(angular.copy(widgets)); <ide> // Note: title is not currently used in the view <ide> return {title : "System metrics", columns : widgets}; <ide> }
Java
epl-1.0
d2d66d4095a9cc3f16126931820a5275868c291f
0
ELTE-Soft/xUML-RT-Executor
package hu.eltesoft.modelexecution.cli; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.InputStream; import java.nio.file.Paths; import java.util.AbstractMap.SimpleEntry; import java.util.Arrays; import java.util.Collection; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Before; import org.junit.runners.Parameterized.Parameters; import com.google.common.collect.ImmutableSet; import com.google.common.io.ByteStreams; import com.google.common.io.Files; public class SystemModelTests extends ModelBasedTests { // TODO: maintain this list according to system tests private static final Set<String> EXCLUDED_TESTS = ImmutableSet.<String> builder().add("AssociationClass").build(); private static final String TESTER_UML_FILE_NAME = "Tester.uml"; private static final File SYSTEM_MODELS_DIR = Paths.get("..", "..", "test-models").toFile(); @Before @Override public void before() throws Throwable { super.before(); // copy Tester.uml to source folder File targetFile = srcFolder.toPath().resolve(TESTER_UML_FILE_NAME).toFile(); File testerFile = SYSTEM_MODELS_DIR.toPath().resolve(TESTER_UML_FILE_NAME).toFile(); Files.copy(testerFile, targetFile); // copy external entity implementation to build folder try (InputStream eeStream = getClass().getClassLoader().getResourceAsStream("TesterImpl.class")) { byte[] eeBytes = ByteStreams.toByteArray(eeStream); targetFile = buildFolder.toPath().resolve("TesterImpl.class").toFile(); Files.write(eeBytes, targetFile); } } @Override protected void validateRunnerOutput(SimpleEntry<String, String> output) { assertNotEquals("Standard error after compilation must not be empty", "", output.getValue()); assertFalse("Explicit model test failure", output.getKey().startsWith("failure")); assertTrue("Implicit model test failure", output.getKey().startsWith("success")); } @Parameters(name = "{0}") public static Collection<Object[]> getParameters() { Stream<File> umlFiles = Arrays.stream(SYSTEM_MODELS_DIR.listFiles()).filter(file -> { String name = file.getName(); if (TESTER_UML_FILE_NAME.equals(name)) { return false; } if (name.endsWith(".uml")) { // drop extension String testName = name.substring(0, name.length() - 4); if (!EXCLUDED_TESTS.contains(testName)) { return true; } } return false; }); return umlFiles.map(file -> { Object[] params = new Object[4]; params[0] = file; params[1] = "Test"; params[2] = "run"; params[3] = true; return params; }).collect(Collectors.toList()); } }
tests/hu.eltesoft.modelexecution.cli.tests/src/hu/eltesoft/modelexecution/cli/SystemModelTests.java
package hu.eltesoft.modelexecution.cli; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.InputStream; import java.nio.file.Path; import java.nio.file.Paths; import java.util.AbstractMap.SimpleEntry; import java.util.Arrays; import java.util.Collection; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Before; import org.junit.runners.Parameterized.Parameters; import com.google.common.collect.ImmutableSet; import com.google.common.io.ByteStreams; import com.google.common.io.Files; public class SystemModelTests extends ModelBasedTests { // TODO: maintain this list according to system tests private static final Set<String> EXCLUDED_TESTS = ImmutableSet.<String> builder().add("AssociationClass").build(); private static final String TESTER_UML_FILE_NAME = "Tester.uml"; private static final File SYSTEM_MODELS_DIR = Paths.get("..", "..", "test-models").toFile(); @Before @Override public void before() throws Throwable { super.before(); // copy Tester.uml to source folder File targetFile = srcFolder.toPath().resolve(TESTER_UML_FILE_NAME).toFile(); File testerFile = SYSTEM_MODELS_DIR.toPath().resolve(TESTER_UML_FILE_NAME).toFile(); Files.copy(testerFile, targetFile); // copy external entity implementation to build folder try (InputStream eeStream = getClass().getClassLoader().getResourceAsStream("TesterImpl.class")) { byte[] eeBytes = ByteStreams.toByteArray(eeStream); targetFile = buildFolder.toPath().resolve("TesterImpl.class").toFile(); Files.write(eeBytes, targetFile); } } @Override protected void validateRunnerOutput(SimpleEntry<String, String> output) { assertNotEquals("Standard error after compilation must not be empty", "", output.getValue()); assertFalse("Explicit model test failure", output.getKey().startsWith("failure")); assertTrue("Implicit model test failure", output.getKey().startsWith("success")); } @Parameters(name = "{0}") public static Collection<Object[]> getParameters() { Stream<File> umlFiles = Arrays.stream(SYSTEM_MODELS_DIR.listFiles()).filter(file -> { String name = file.getName(); if (TESTER_UML_FILE_NAME.equals(name)) { return false; } if (name.endsWith(".uml")) { // drop extension String testName = name.substring(0, name.length() - 4); if (!EXCLUDED_TESTS.contains(testName)) { return true; } } return false; }); return umlFiles.map(file -> { Object[] params = new Object[4]; params[0] = file; params[1] = "Test"; params[2] = "run"; params[3] = true; return params; }).collect(Collectors.toList()); } }
Removing unused import
tests/hu.eltesoft.modelexecution.cli.tests/src/hu/eltesoft/modelexecution/cli/SystemModelTests.java
Removing unused import
<ide><path>ests/hu.eltesoft.modelexecution.cli.tests/src/hu/eltesoft/modelexecution/cli/SystemModelTests.java <ide> <ide> import java.io.File; <ide> import java.io.InputStream; <del>import java.nio.file.Path; <ide> import java.nio.file.Paths; <ide> import java.util.AbstractMap.SimpleEntry; <ide> import java.util.Arrays;
Java
apache-2.0
5202a2690fe80a359a2467ce27c268bf8aa0469b
0
VicMikhailau/MaskedEditText
package com.vicmikhailau.maskededittextsample; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.vicmikhailau.maskededittext.MaskedEditText; import com.vicmikhailau.maskededittext.MaskedFormatter; import com.vicmikhailau.maskededittext.MaskedWatcher; public class MainActivity extends AppCompatActivity { /** * Use specific values for create your own mask (see example below or in xml): * ANYTHING_KEY = '*' * DIGIT_KEY = '#' * UPPERCASE_KEY = 'U'; * LOWERCASE_KEY = 'L'; * ALPHA_NUMERIC_KEY = 'A'; * LITERAL_KEY = '\''; * CHARACTER_KEY = '?'; * HEX_KEY = 'H'; */ /** * For getting unmasked text for MaskedEditText mEdtMaskedCustom just use mEdtMaskedCustom.getUnMaskedString(). * For getting unmasked text for default EditText with MaskedWatcher mMaskedWatcher just use mMaskedWatcher.getUnMaskedString(). */ // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private EditText mEdtMasked; private MaskedFormatter formatter; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass // =========================================================== @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViews(); setMask("##/##/####"); } // =========================================================== // Listeners, methods for/from Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== private void findViews() { mEdtMasked = (EditText) findViewById(R.id.edt_masked); } /** * You cas use MaskedEditText declared in xml with attribute named mask * or * set mask in code for default EdiText * * @param mask your mask */ private void setMask(String mask) { formatter = new MaskedFormatter(mask); mEdtMasked.addTextChangedListener(new MaskedWatcher(formatter, mEdtMasked)); String s = formatter.formatString(mEdtMasked.getText().toString()).getUnMaskedString(); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
app/src/main/java/com/vicmikhailau/maskededittextsample/MainActivity.java
package com.vicmikhailau.maskededittextsample; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.vicmikhailau.maskededittext.MaskedEditText; import com.vicmikhailau.maskededittext.MaskedFormatter; import com.vicmikhailau.maskededittext.MaskedWatcher; public class MainActivity extends AppCompatActivity { /** * Use specific values for create your own mask (see example below or in xml): * ANYTHING_KEY = '*' * DIGIT_KEY = '#' * UPPERCASE_KEY = 'U'; * LOWERCASE_KEY = 'L'; * ALPHA_NUMERIC_KEY = 'A'; * LITERAL_KEY = '\''; * CHARACTER_KEY = '?'; * HEX_KEY = 'H'; */ /** * For getting unmasked text for MaskedEditText mEdtMaskedCustom just use mEdtMaskedCustom.getUnMaskedString(). * For getting unmasked text for default EditText with MaskedWatcher mMaskedWatcher just use mMaskedWatcher.getUnMaskedString(). */ // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private EditText mEdtMasked; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass // =========================================================== @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViews(); setMask("##/##/####"); } // =========================================================== // Listeners, methods for/from Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== private void findViews() { mEdtMasked = (EditText) findViewById(R.id.edt_masked); } /** * You cas use MaskedEditText declared in xml with attribute named mask * or * set mask in code for default EdiText * * @param mask your mask */ private void setMask(String mask) { MaskedFormatter formatter = new MaskedFormatter(mask); mEdtMasked.addTextChangedListener(new MaskedWatcher(formatter, mEdtMasked)); // Example how to get unmasked string in this case. String s = formatter.formatString(mEdtMasked.getText().toString()).getUnMaskedString(); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Fix: we use weakref in watcher, and we need to store formatter as a class member (because, if gc was called, formatter will be destroyed).
app/src/main/java/com/vicmikhailau/maskededittextsample/MainActivity.java
Fix: we use weakref in watcher, and we need to store formatter as a class member (because, if gc was called, formatter will be destroyed).
<ide><path>pp/src/main/java/com/vicmikhailau/maskededittextsample/MainActivity.java <ide> // =========================================================== <ide> <ide> private EditText mEdtMasked; <add> private MaskedFormatter formatter; <ide> <ide> // =========================================================== <ide> // Constructors <ide> * @param mask your mask <ide> */ <ide> private void setMask(String mask) { <del> MaskedFormatter formatter = new MaskedFormatter(mask); <add> formatter = new MaskedFormatter(mask); <ide> mEdtMasked.addTextChangedListener(new MaskedWatcher(formatter, mEdtMasked)); <del> // Example how to get unmasked string in this case. <ide> String s = formatter.formatString(mEdtMasked.getText().toString()).getUnMaskedString(); <ide> } <ide>
JavaScript
mit
30dd4ca09e24a6c5435040bccb55d60e1fc6d015
0
sebastian-software/core,sebastian-software/core,zynga/core,zynga/core,zynga/core,sebastian-software/core
/** * #require(jquery) #require(qunit) #asset(qunit.css) */ var global = this; $(function() { /* --------------------------------------------------------------------------- EXT :: FIX --------------------------------------------------------------------------- */ module("Ext :: Fixes"); asyncTest("setTimeout with arguments", 1, function() { /** #require(ext.TimeoutArgs) */ setTimeout(function(arg) { equals(arg, "hello"); start(); }, 10, "hello"); }); asyncTest("setImmediate", 1, function() { /** #require(ext.Immediate) */ setImmediate(function() { ok(true, "always fine"); start(); }); }); asyncTest("requestAnimationFrame", 1, function() { /** #require(ext.RequestAnimationFrame) */ requestAnimationFrame(function() { ok(true, "always fine"); start(); }); }); test("Object.keys", function() { // Basic first var keys = Object.keys({hello:null, foo:1}).sort().join(","); equals(keys, "foo,hello"); // toString etc. are special in IE because these are built-in keys var keys = Object.keys({toString:null, hello:null, foo:1}).sort().join(","); equals(keys, "foo,hello,toString"); }); /* --------------------------------------------------------------------------- EXT :: SUGAR --------------------------------------------------------------------------- */ module("Ext :: Sugar"); /** #require(ext.sugar.Object) */ test("Object.empty", function() { // toString etc. are special in IE because these are built-in keys ok(Object.isEmpty({})); ok(!Object.isEmpty({toString:null})); ok(!Object.isEmpty({toString:null, hello:null, foo:1})); }); test("Object.values", function() { var values = Object.values({x:1, y:2, z:3}).sort().join(","); equals(values, "1,2,3"); }); test("Object.fromArray", function() { equals(Object.keys(Object.fromArray(["foo","bar","baz"])).join(","), "foo,bar,baz"); equals(Object.values(Object.fromArray(["foo","bar","baz"])).join(","), "true,true,true"); equals(Object.keys(Object.fromArray(["foo","bar","baz"], "hello")).join(","), "foo,bar,baz"); equals(Object.values(Object.fromArray(["foo","bar","baz"], "hello")).join(","), "hello,hello,hello"); }); /** #require(ext.sugar.Array) */ test("Array.prototype.max", function() { equals([1,4,23,3].max(), 23); equals([10,10,10].max(), 10); equals([].max(), -Infinity); }); test("Array.prototype.min", function() { equals([1,4,23,3].min(), 1); equals([10,10,10].min(), 10); equals([].min(), Infinity); }); test("Array.prototype.sum", function() { equals([1,4,23,3].sum(), 31); equals([1,4,23,,,3].sum(), 31); equals([].sum(), 0); }); test("Array.prototype.insertAt", function() { var arr1 = [1,2,3,4,5,6,7]; equals(arr1.insertAt("end"), "end"); equals(arr1.join(","), "1,2,3,4,5,6,7,end"); var arr1 = [1,2,3,4,5,6,7]; equals(arr1.insertAt("begin", 0), "begin"); equals(arr1.join(","), "begin,1,2,3,4,5,6,7"); var arr1 = [1,2,3,4,5,6,7]; equals(arr1.insertAt("fromBegin", 3), "fromBegin"); equals(arr1.join(","), "1,2,3,fromBegin,4,5,6,7"); var arr1 = [1,2,3,4,5,6,7]; equals(arr1.insertAt("fromEnd", -3), "fromEnd"); equals(arr1.join(","), "1,2,3,4,fromEnd,5,6,7"); }); test("Array.prototype.contains", function() { var arr1 = [1,2,3,5,6,7]; ok(arr1.contains(3)); ok(!arr1.contains(4)); ok(arr1.contains(5)); var arr2 = ["true","1",3,false]; ok(!arr2.contains(true)); ok(!arr2.contains(1)); ok(!arr2.contains("3")); ok(!arr2.contains("false")); ok(arr2.contains("true")); ok(arr2.contains("1")); ok(arr2.contains(3)); ok(arr2.contains(false)); }); test("Array.prototype.clone", function() { var orig = [1,2,3]; var clone = orig.clone(); equals(orig.length, clone.length); equals(orig.join(","), clone.join(",")); var orig = [1,2,,,5]; var clone = orig.clone(); equals(orig.length, clone.length); equals(orig.join(","), clone.join(",")); }); test("Array.prototype.remove", function() { var arr = [1,2,3,4,5,6]; equals(arr.remove(4), 4); equals(arr.length, 5); equals(arr.remove(4)); equals(arr.length, 5); var arr = [1,2,3,1,2,3]; equals(arr.remove(3), 3); equals(arr.join(","), "1,2,1,2,3"); }); test("Array.prototype.removeAt", function() { var arr = [1,2,3,4,5,6]; equals(arr.removeAt(2), 3); equals(arr.removeAt(12)); equals(arr.join(","), "1,2,4,5,6"); }); test("Array.prototype.removeRange", function() { var arr = [1,2,3,4,5,6,7,8,9]; arr.removeRange(1, 1); equals(arr.join(","), "1,3,4,5,6,7,8,9"); var arr = [1,2,3,4,5,6,7,8,9]; arr.removeRange(1, 3); equals(arr.join(","), "1,5,6,7,8,9"); var arr = [1,2,3,4,5,6,7,8,9]; arr.removeRange(1, -3); equals(arr.join(","), "1,8,9"); var arr = [1,2,3,4,5,6,7,8,9]; arr.removeRange(-3, -1); equals(arr.join(","), "1,2,3,4,5,6"); }); test("Array.prototype.unique", function() { var arr = [1,2,3,1,2,3]; equals(arr.unique().join(","), "1,2,3"); // sparse arrays supported var arr = [1,2,,,2,3]; equals(arr.unique().join(","), "1,2,3"); // null values are treated special var arr = [1,2,null,null,2,3]; equals(arr.unique().join(","), "1,2,,3"); // selection test var arr = [1,"2",3,"1",2,"3"]; var unique = arr.unique(); equals(unique.join(","), "1,2,3"); equals(typeof unique[0], "number"); equals(typeof unique[1], "string"); equals(typeof unique[2], "number"); // does not support objects var arr = [{},{},{}]; equals(arr.unique().join(","), "[object Object]"); // but can work with special objects var hashCode = 0; var Special = function() { this.hashCode = hashCode++; } Special.prototype.toString = function() { return "[object Special#" + this.hashCode + "]"; } arr = [new Special, new Special, new Special]; equals(arr.unique().join(","), "[object Special#0],[object Special#1],[object Special#2]"); }); test("Array.prototype.at", function() { var arr = [1,2,3,4,5]; equals(arr.at(0), 1); equals(arr.at(-1), 5); equals(arr.at(20)); equals(arr.at(-20)); }); test("Array.prototype.compact", function() { var sparse = [1,2,3,,5,,,8]; equals(sparse.compact().length, 5); var undef; var sparse = [1,2,3,null,5,,undef,8]; equals(sparse.compact().length, 7); equals(sparse.compact(true).length, 5); }); test("Array.prototype.flatten", function() { equals([[1], 2, [3]].flatten().toString(), [1,2,3].toString()); equals([["a"],[],"b","c"].flatten().toString(), ["a","b","c"].toString()); }); /** #require(ext.sugar.Function) */ asyncTest("Function.prototype.debounce - END", 1, function() { var counter = 0; var callback = function() { counter++; }; var debounced = callback.debounce(); debounced(); debounced(); debounced(); debounced(); debounced(); window.setTimeout(function() { equals(counter, 1); start(); }, 200) }); test("Function.prototype.debounce - ASAP", function() { var counter = 0; var callback = function() { counter++; }; var debounced = callback.debounce(100, true); debounced(); debounced(); debounced(); debounced(); debounced(); equals(counter, 1); }); /** #require(ext.sugar.Number) */ test("Number.prototype.pad", function() { equals((23).pad(2), "23"); equals((23).pad(4), "0023"); equals((23).pad(6), "000023"); equals((0).pad(6), "000000"); }); /** #require(ext.sugar.String) */ test("String.prototype.contains", function() { ok("hello world".contains("hello")); ok("hello world".contains("")); ok("hello world".contains(" ")); ok(!"hello world".contains(12)); ok(!"hello world".contains("dlrow")); }); test("String.prototype.hyphenate", function() { equals("backgroundColor".hyphenate(), "background-color"); equals("WebkitTransform".hyphenate(), "-webkit-transform"); equals("ISOString".hyphenate(), "-i-s-o-string"); }); test("String.prototype.repeat", function() { equals("x".repeat(3), "xxx"); equals("xyz".repeat(3), "xyzxyzxyz"); equals("xyz".repeat(0), ""); }); /* --------------------------------------------------------------------------- CORE :: ASSET --------------------------------------------------------------------------- */ module("Core :: Asset"); test("Adding Source Data", function() { raises(function() { core.io.Asset.resetData(); core.io.Asset.toUri("my.png") }); core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "my.png" : {"u":"asset/my.png","p":0} }, "profiles" : [{name:"source"}] }); equals(core.io.Asset.toUri("my.png"), "asset/my.png"); core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "my.png" : {"u":"asset/my.png","p":0} }, "profiles" : [{name:"source", "root":"xxx/yyy/"}] }); equals(core.io.Asset.toUri("my.png"), "xxx/yyy/asset/my.png"); core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "my.png" : {"u":"asset/my.png","p":0} }, "profiles" : [{name:"source", "root":"http://mycdn.com/xxx/yyy/"}] }); equals(core.io.Asset.toUri("my.png"), "http://mycdn.com/xxx/yyy/asset/my.png"); core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "lib2" : { "my.png" : {"u":"../../lib2/asset/my.png","p":0} } }, "profiles" : [{name:"source", "root":"http://mycdn.com/app/source/"}] }); equals(core.io.Asset.toUri("lib2/my.png"), "http://mycdn.com/app/source/../../lib2/asset/my.png"); }); test("Adding Build Data", function() { raises(function() { core.io.Asset.resetData(); core.io.Asset.toUri("my.png") }); core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "my.png" : {"p":0} }, "profiles" : [{name:"build", "root":"asset/"}] }); equals(core.io.Asset.toUri("my.png"), "asset/my.png"); core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "my.png" : {"p":0} }, "profiles" : [{name:"build", "root":"xxx/yyy/asset/"}] }); equals(core.io.Asset.toUri("my.png"), "xxx/yyy/asset/my.png"); core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "my.png" : {"p":0} }, "profiles" : [{name:"build", "root":"http://mycdn.com/xxx/yyy/asset/"}] }); equals(core.io.Asset.toUri("my.png"), "http://mycdn.com/xxx/yyy/asset/my.png"); }); test("Image Sizes", function() { core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "myapp" : { "icons" : { "app.png" : {"d":[48, 48], "p":0} } } }, "profiles" : [{name:"build", "root":"asset/"}] }); equals(core.io.Asset.toUri("myapp/icons/app.png"), "asset/myapp/icons/app.png"); equals(core.io.Asset.getImageSize("myapp/icons/app.png")+"", [48, 48]+""); equals(core.io.Asset.getFrameNumber("myapp/icons/app.png"), 1); }); test("Image Sprite - None", function() { core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "myapp" : { "icons" : { "app.png" : {"d":[48, 48], "p":0} } } }, "profiles" : [{name:"build", "root":"asset/"}] }); equals(core.io.Asset.toUri("myapp/icons/app.png"), "asset/myapp/icons/app.png"); var imgData = core.io.Asset.getImage("myapp/icons/app.png"); strictEqual(imgData.left, 0); strictEqual(imgData.top, 0); strictEqual(imgData.src, "asset/myapp/icons/app.png"); }); test("Image Sprite - Same Folder", function() { core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "myapp" : { "icons" : { "app.png" : {"d":[48, 48, [0, 96, 240]], "p":0}, "icons.png" : {"d":[288, 288], "p":0} } } }, "profiles" : [{name:"build", "root":"asset/"}], "sprites" : ["icons.png"] }); equals(core.io.Asset.toUri("myapp/icons/app.png"), "asset/myapp/icons/app.png"); var imgData = core.io.Asset.getImage("myapp/icons/app.png"); strictEqual(imgData.width, 48); strictEqual(imgData.height, 48); strictEqual(imgData.left, 96); strictEqual(imgData.top, 240); strictEqual(imgData.src, "asset/myapp/icons/icons.png"); }); test("Image Sprite - Absolute ID", function() { core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "myapp" : { "icons.png" : {"d":[288, 288], "p":0}, "icons" : { "app.png" : {"d":[48, 48, [0, 96, 240]], "p":0} } } }, "profiles" : [{name:"build", "root":"asset/"}], "sprites" : ["myapp/icons.png"] }); equals(core.io.Asset.toUri("myapp/icons/app.png"), "asset/myapp/icons/app.png"); var imgData = core.io.Asset.getImage("myapp/icons/app.png"); strictEqual(imgData.width, 48); strictEqual(imgData.height, 48); strictEqual(imgData.left, 96); strictEqual(imgData.top, 240); strictEqual(imgData.src, "asset/myapp/icons.png"); }); test("Image Sprite - Root ID", function() { core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "icons.png" : {"d":[288, 288], "p":0}, "myapp" : { "icons" : { "app.png" : {"d":[48, 48, [0, 96, 240]], "p":0} } } }, "profiles" : [{name:"build", "root":"asset/"}], "sprites" : ["/icons.png"] }); equals(core.io.Asset.toUri("myapp/icons/app.png"), "asset/myapp/icons/app.png"); var imgData = core.io.Asset.getImage("myapp/icons/app.png"); strictEqual(imgData.width, 48); strictEqual(imgData.height, 48); strictEqual(imgData.left, 96); strictEqual(imgData.top, 240); strictEqual(imgData.src, "asset/icons.png"); }); test("Frames - Rows/Columns", function() { core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "myapp" : { "anim" : { "loading.png" : {"d":[16*16, 16, 0, [16, 1]], "p":0}, "explode.png" : {"d":[32*30, 32*3, 0, [30, 3]], "p":0}, "collapse.png" : {"d":[12*2, 12*20, 0, [2, 20, 86]], "p":0}, } } }, "profiles" : [{name:"build", "root":"asset/"}] }); strictEqual(core.io.Asset.getFrameNumber("myapp/anim/loading.png"), 16, "number of frames I"); strictEqual(core.io.Asset.getFrameNumber("myapp/anim/explode.png"), 90, "number of frames II"); strictEqual(core.io.Asset.getFrameNumber("myapp/anim/collapse.png"), 86, "number of frames III"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 0).left, 0, "left position first"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 1).left, 16, "left position second"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 13).left, 208, "left position inner"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 15).left, 240, "left position last"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 0).top, 0, "top position first"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 1).top, 0, "top position second"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 13).top, 0, "top position inner"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 15).top, 0, "top position last"); strictEqual(core.io.Asset.getFrame("myapp/anim/collapse.png", 2).left, 0, "left other image"); strictEqual(core.io.Asset.getFrame("myapp/anim/collapse.png", 2).top, 12, "top other image"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 13).width, 16, "corrected width"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 13).height, 16, "corrected height"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 13).src, "asset/myapp/anim/loading.png", "normal source handling I"); strictEqual(core.io.Asset.getImage("myapp/anim/loading.png").width, 256, "full image width"); strictEqual(core.io.Asset.getImage("myapp/anim/loading.png").height, 16, "full image height"); strictEqual(core.io.Asset.getImage("myapp/anim/loading.png").src, "asset/myapp/anim/loading.png", "normal source handling II"); }); test("Frames - Rows/Columns in Image Sprite", function() { core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "myapp" : { "sprite.png" : {"d":[960, 352], "p":0}, "anim" : { "loading.png" : {"d":[16*16, 16, [0, 20, 0], [16, 1]], "p":0}, "explode.png" : {"d":[32*30, 32*3, [0, 40, 16], [30, 3]], "p":0}, "collapse.png" : {"d":[12*2, 12*20, [0, 60, 112], [2, 20, 86]], "p":0} } } }, "profiles" : [{name:"build", "root":"asset/"}], "sprites" : ["myapp/sprite.png"] }); strictEqual(core.io.Asset.getFrameNumber("myapp/anim/loading.png"), 16, "number of frames I"); strictEqual(core.io.Asset.getFrameNumber("myapp/anim/explode.png"), 90, "number of frames II"); strictEqual(core.io.Asset.getFrameNumber("myapp/anim/collapse.png"), 86, "number of frames III"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 0).left, 20, "left position first"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 1).left, 36, "left position second"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 13).left, 228, "left position inner"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 15).left, 260, "left position last"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 0).top, 0, "top position first"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 1).top, 0, "top position second"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 13).top, 0, "top position inner"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 15).top, 0, "top position last"); strictEqual(core.io.Asset.getFrame("myapp/anim/collapse.png", 2).left, 60, "left other image"); strictEqual(core.io.Asset.getFrame("myapp/anim/collapse.png", 2).top, 124, "top other image"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 13).width, 16, "corrected width"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 13).height, 16, "corrected height"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 13).src, "asset/myapp/sprite.png", "normal source sprite handling I"); strictEqual(core.io.Asset.getImage("myapp/anim/loading.png").width, 256, "full image width"); strictEqual(core.io.Asset.getImage("myapp/anim/loading.png").height, 16, "full image height"); strictEqual(core.io.Asset.getImage("myapp/anim/loading.png").src, "asset/myapp/sprite.png", "normal source sprite handling II"); }); test("Frames - Custom", function() { core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "myapp" : { "anim" : { "guy.png" : {"d":[200, 16, 0, [ [ // Format: left, top, width, height, offsetLeft?, offsetTop?, rotation? [ 0, 0, 20, 20], [30, 50, 10, 30, 20, 50], [70, 20, 14, 40, 0, 30, 90] ] ]], "p":0} } }, }, "profiles" : [{name:"build", "root":"asset/"}] }); strictEqual(core.io.Asset.getFrameNumber("myapp/anim/guy.png"), 3, "number of frames"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).left, 0, "left position I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).top, 0, "top position I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).width, 20, "width I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).height, 20, "height I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).offsetLeft, 0, "offsetLeft I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).offsetTop, 0, "offsetTop I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).rotation, 0, "rotation I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).left, 30, "left position II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).top, 50, "top position II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).width, 10, "width II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).height, 30, "height II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).offsetLeft, 20, "offsetLeft II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).offsetTop, 50, "offsetTop II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).rotation, 0, "rotation II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).left, 70, "left position III"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).top, 20, "top position III"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).width, 14, "width III"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).height, 40, "height III"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).offsetLeft, 0, "offsetLeft III"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).offsetTop, 30, "offsetTop III"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).rotation, 90, "rotation III"); }); test("Frames - Custom in Image Sprite", function() { core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "myapp" : { "sprite.png" : {"d":[960, 352], "p":0}, "anim" : { "guy.png" : {"d":[200, 16, [0, 20, 40], [ [ // Format: left, top, width, height, offsetLeft?, offsetTop?, rotation? [ 0, 0, 20, 20], [30, 50, 10, 30, 20, 50], [70, 20, 14, 40, 0, 30, 90] ] ]], "p":0}, } }, }, "sprites" : ["myapp/sprite.png"], "profiles" : [{name:"build", "root":"asset/"}] }); strictEqual(core.io.Asset.getFrameNumber("myapp/anim/guy.png"), 3, "number of frames"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).left, 20, "left position I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).top, 40, "top position I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).width, 20, "width I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).height, 20, "height I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).offsetLeft, 0, "offsetLeft I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).offsetTop, 0, "offsetTop I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).rotation, 0, "rotation I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).src, "asset/myapp/sprite.png", "source I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).left, 50, "left position II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).top, 90, "top position II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).width, 10, "width II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).height, 30, "height II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).offsetLeft, 20, "offsetLeft II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).offsetTop, 50, "offsetTop II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).rotation, 0, "rotation II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).src, "asset/myapp/sprite.png", "source II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).left, 90, "left position III"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).top, 60, "top position III"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).width, 14, "width III"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).height, 40, "height III"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).offsetLeft, 0, "offsetLeft III"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).offsetTop, 30, "offsetTop III"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).rotation, 90, "rotation III"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).src, "asset/myapp/sprite.png", "source III"); }); /* --------------------------------------------------------------------------- CORE :: UTIL --------------------------------------------------------------------------- */ module("Core :: Util"); test("Id", function() { var myFunc = new Function; strictEqual(core.util.Id.get(myFunc), 1); strictEqual(core.util.Id.get(myFunc), 1); strictEqual(core.util.Id.get(document.body), 2); strictEqual(core.util.Id.get(document.body), 2); }); /* --------------------------------------------------------------------------- CORE :: BOM --------------------------------------------------------------------------- */ module("Core :: BOM"); test("Text", function() { strictEqual(typeof core.bom.Text.measure("hello world"), "object"); strictEqual(typeof core.bom.Text.measure("hello world").width, "number"); strictEqual(typeof core.bom.Text.measure("hello world").height, "number"); strictEqual(typeof core.bom.Text.measure("hello world foo bar baz", null, 40), "object"); strictEqual(core.bom.Text.measure("hello world foo bar baz", null, 40).width, 40); }); /* --------------------------------------------------------------------------- CORE :: TEMPLATE --------------------------------------------------------------------------- */ module("Core :: Template"); test("Basic", function() { var template = core.template.Compiler.compile("Follow @{{screenName}}."); ok(template instanceof core.template.Template); var output = template.render({ screenName: "dhg" }); equal(output, "Follow @dhg."); var output = template.render({ screenName: "wpbasti" }); equal(output, "Follow @wpbasti."); }); test("Line Breaks", function() { var template = core.template.Compiler.compile("Break\nHere {{value}}."); ok(template instanceof core.template.Template); var output = template.render({ value: "xxx" }); equal(output, "Break\nHere xxx."); }); test("Lists", function() { var template = core.template.Compiler.compile("{{#repo}}<b>{{name}}</b>{{/repo}}"); ok(template instanceof core.template.Template); var output = template.render({ "repo": [ { "name": "resque" }, { "name": "hub" }, { "name": "rip" } ] }); equal(output, "<b>resque</b><b>hub</b><b>rip</b>"); }); test("Conditional Lists", function() { var template = core.template.Compiler.compile("{{?repo}}Repos<br/>{{#repo}}<b>{{name}}</b>{{/repo}}{{/repo}}"); ok(template instanceof core.template.Template); var output = template.render({ "repo": [ { "name": "resque" }, { "name": "hub" }, { "name": "rip" } ] }); equal(output, "Repos<br/><b>resque</b><b>hub</b><b>rip</b>"); var output = template.render({ "repo": [] }); equal(output, ""); var template = core.template.Compiler.compile("{{#other}}<em>{{name}}</em>{{/other}}{{?repo}}Repos<br/>{{#repo}}<b>{{name}}</b>{{/repo}}{{/repo}}"); var output = template.render({ "repo": [], "other": [ { "name": "resque" }, { "name": "hub" }, { "name": "rip" } ] }); equal(output, "<em>resque</em><em>hub</em><em>rip</em>"); var template = core.template.Compiler.compile("{{#other}}<em>{{foo}}</em>{{/other}}{{?repo}}Repos<br/>{{#repo}}<b>{{name}}</b>{{/repo}}{{/repo}}"); var output = template.render({ "repo": [ { "name": "resque" }, { "name": "hub" }, { "name": "rip" } ], "other": { "foo" : "bar" } }); equal(output, "<em>bar</em>Repos<br/><b>resque</b><b>hub</b><b>rip</b>"); }); test("Non False", function() { var template = core.template.Compiler.compile("{{#person?}}Hi {{name}}!{{/person?}}"); ok(template instanceof core.template.Template); var output = template.render({ "person?": { "name": "Jon" } }); equal(output, "Hi Jon!"); }); test("Inverted Sections", function() { var template = core.template.Compiler.compile("{{#repo}}<b>{{.}}</b>{{/repo}}{{^repo}}No repos :({{/repo}}"); ok(template instanceof core.template.Template); var output = template.render({ "repo": [] }); equal(output, "No repos :("); var output = template.render({ "repo": [1,2,3] }); equal(output, "<b>1</b><b>2</b><b>3</b>"); }); test("Comments", function() { var template = core.template.Compiler.compile("<h1>Today{{! ignore me }}.</h1>"); ok(template instanceof core.template.Template); var output = template.render({ "repo": [] }); equal(output, "<h1>Today.</h1>"); }); test("Unescaped", function() { var template = core.template.Compiler.compile("{{code}}"); ok(template instanceof core.template.Template); var output = template.render({ "code": "<b>Foo</b>" }); equal(output, "&lt;b&gt;Foo&lt;/b&gt;"); var output = template.render({ "code": "Bert & Ernie" }); equal(output, "Bert &amp; Ernie"); var template = core.template.Compiler.compile("{{&code}}"); ok(template instanceof core.template.Template); var output = template.render({ "code": "<b>Foo</b>" }); equal(output, "<b>Foo</b>"); }); test("Partials", function() { var template = core.template.Compiler.compile("{{#tweets}}{{> tweet}}{{/tweets}}"); ok(template instanceof core.template.Template); var tweetTemplate = core.template.Compiler.compile('<p data-id="{{id}}">{{text}}</p>'); ok(tweetTemplate instanceof core.template.Template); var output = template.render({ "tweets": [{ text: "hello world", id: 1 }, { text: "this is a test tweet", id: 2 }, { text: "to impress you", id: 3 }] }, { tweet: tweetTemplate }); equal(output, "<p data-id=\"1\">hello world</p><p data-id=\"2\">this is a test tweet</p><p data-id=\"3\">to impress you</p>"); }); test("Parser", function() { var text = "{{^check}}No{{/check}}{{#check}}Yes{{/check}}"; var tree = core.template.Parser.parse(text); equals(tree[0].tag, "^"); equals(tree[0].name, "check"); equals(tree[1].tag, "#"); equals(tree[1].name, "check"); }); test("Dots", function() { var template = core.template.Compiler.compile("{{#tweets}}{{author.name}}[{{author.id}}]{{/tweets}}"); var output = template.render({ "tweets": [{ author: { name : "Sascha", id : 0 } }, { author: { name : "Christoph", id : 1 } }, { author: { name : "Ivo", id : 2 } }] }); equals(output, "Sascha[0]Christoph[1]Ivo[2]"); }); /* --------------------------------------------------------------------------- CORE :: CRYPT --------------------------------------------------------------------------- */ module("Core :: Crypt"); test("Adler32", function() { strictEqual(core.crypt.Adler32.checksum("hello world"), 436929629); strictEqual(core.crypt.Adler32.checksum("hello world!"), 512296062); strictEqual(core.crypt.Adler32.checksum("günthér falit°@"), 1479674097); }); test("CRC32", function() { strictEqual(core.crypt.CRC32.checksum("hello world"), 222957957); strictEqual(core.crypt.CRC32.checksum("hello world!"), 62177901); strictEqual(core.crypt.CRC32.checksum("günthér falit°@"), 1047403603); }); test("MD5", function() { strictEqual(core.crypt.MD5.checksum("hello world").toHex(), "5eb63bbbe01eeed093cb22bb8f5acdc3"); strictEqual(core.crypt.MD5.checksum("hello karl").toHex(), "967f3d167631b54ea74b380e439ec2d5"); strictEqual(core.crypt.MD5.checksum("günthér falit°@").toHex(), "c901b2c94c101e0c2fdb2c96a041ceda"); strictEqual(core.crypt.MD5.hmac("secret", "hello world").toHex(), "78d6997b1230f38e59b6d1642dfaa3a4"); strictEqual(core.crypt.MD5.hmac("secret", "hello karl").toHex(), "1df06dd6ad23a62de80b713bdfc5f59f"); strictEqual(core.crypt.MD5.hmac("other secret", "hello world").toHex(), "614ff83602727ee68fba3e9500856fad"); strictEqual(core.crypt.MD5.hmac("other secret", "hello karl").toHex(), "71b406e27e5184663c0c01448b57c5a7"); }); test("SHA1", function() { strictEqual(core.crypt.SHA1.checksum("hello world").toHex(), "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed"); strictEqual(core.crypt.SHA1.checksum("hello karl").toHex(), "1665bcf30c12443dbb332b84590123f7d544500b"); strictEqual(core.crypt.SHA1.checksum("günthér falit°@").toHex(), "01695e64d0f83e453281f385209884e94784c7bf"); strictEqual(core.crypt.SHA1.hmac("secret", "hello world").toHex(), "03376ee7ad7bbfceee98660439a4d8b125122a5a"); strictEqual(core.crypt.SHA1.hmac("secret", "hello karl").toHex(), "1de9256cf6805f714a59b69806647b34315ae6ad"); strictEqual(core.crypt.SHA1.hmac("other secret", "hello world").toHex(), "2b7dd1114abb301c6a3879612c040db1dc76efe7"); strictEqual(core.crypt.SHA1.hmac("other secret", "hello karl").toHex(), "1005fc78d9e3c525c72c3dcaef4ec2d1ae2d638d"); }); test("SHA256", function() { strictEqual(core.crypt.SHA256.checksum("hello world").toHex(), "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"); strictEqual(core.crypt.SHA256.checksum("hello karl").toHex(), "710e9c35558708b24698b55e5e890b506fc946558b3aaa4b356ba008e4edc860"); strictEqual(core.crypt.SHA256.checksum("günthér falit°@").toHex(), "2b62c8f744680ed05d50246db24cdbc491532f185a736c72e7cd94a7bbd41e77"); strictEqual(core.crypt.SHA256.hmac("secret", "hello world").toHex(), "734cc62f32841568f45715aeb9f4d7891324e6d948e4c6c60c0621cdac48623a"); strictEqual(core.crypt.SHA256.hmac("secret", "hello karl").toHex(), "22585ec85d81b38049d3446dd109507bd6d72478b07ef35efb4767260fe09715"); strictEqual(core.crypt.SHA256.hmac("other secret", "hello world").toHex(), "02113759509b1c7ae0deaee8f022d84f828e7d46ae9255044c3d801ad2b09a39"); strictEqual(core.crypt.SHA256.hmac("other secret", "hello karl").toHex(), "17f71ee9084ade98ed82ee4153ceb47707381e5852b473fb77eb8632e06e8bb8"); }); /* --------------------------------------------------------------------------- CORE :: COLLECTION :: LINKED LIST --------------------------------------------------------------------------- */ module("Core :: Collection :: LinkedList"); test("Create", function() { var ll = new core.collection.LinkedList; ok(ll instanceof core.collection.LinkedList); }); test("Import/Export", function() { var Cls = function(i) { this.id = i; }; var array = [new Cls(1), new Cls(2), new Cls(3), new Cls(4), new Cls(5)]; var ll = new core.collection.LinkedList(array); ok(ll instanceof core.collection.LinkedList); equal(ll.getLength(), array.length); var exported = ll.toArray(); ok(exported instanceof Array); equal(exported.length, array.length); equal(array[0], exported[0]); equal(array[1], exported[1]); equal(array[2], exported[2]); equal(array[3], exported[3]); equal(array[4], exported[4]); }); test("Add/Remove Sorted", function() { var Cls = function(i) { this.id = i; }; var ll = new core.collection.LinkedList; ok(ll instanceof core.collection.LinkedList); equal(ll.getLength(), 0); var first = new Cls(1); var second = new Cls(2); var third = new Cls(3); strictEqual(ll.add(first), ll); equal(ll.getLength(), 1); strictEqual(ll.add(second), ll); equal(ll.getLength(), 2); strictEqual(ll.add(third), ll); equal(ll.getLength(), 3); var exported = ll.toArray(); strictEqual(ll.remove(first), ll); equal(ll.getLength(), 2); strictEqual(ll.remove(second), ll); equal(ll.getLength(), 1); strictEqual(ll.remove(third), ll); equal(ll.getLength(), 0); // Exported not modified by changes equal(exported.length, 3); }); test("Add/Remove Random", function() { var Cls = function(i) { this.id = i; }; var ll = new core.collection.LinkedList; ok(ll instanceof core.collection.LinkedList); equal(ll.getLength(), 0); var first = new Cls(1); var second = new Cls(2); var third = new Cls(3); strictEqual(ll.add(first), ll); equal(ll.getLength(), 1); var exported = ll.toArray(); strictEqual(exported[0], first); strictEqual(ll.add(second), ll); equal(ll.getLength(), 2); var exported = ll.toArray(); equal(exported.length, 2); strictEqual(exported[0], first); strictEqual(exported[1], second); strictEqual(ll.remove(first), ll); equal(ll.getLength(), 1); var exported = ll.toArray(); equal(exported.length, 1); strictEqual(exported[0], second); strictEqual(ll.add(third), ll); equal(ll.getLength(), 2); strictEqual(ll.remove(third), ll); equal(ll.getLength(), 1); strictEqual(ll.remove(second), ll); equal(ll.getLength(), 0); }); test("Add/Remove Random", function() { var Cls = function(i) { this.id = i; }; var ll = new core.collection.LinkedList; ok(ll instanceof core.collection.LinkedList); equal(ll.getLength(), 0); }); /* --------------------------------------------------------------------------- CORE :: NAMESPACES --------------------------------------------------------------------------- */ module("Core :: Namespaces", { teardown : function() { delete global.foo; delete global.abc; delete global.a; } }); test("Creating global", function() { core.Main.declareNamespace("foo", 3); equals(global.foo, 3); }); test("Creating namespace", function() { core.Main.declareNamespace("abc.def", 5); equals(global.abc.def, 5); }); /* --------------------------------------------------------------------------- CORE :: MODULES --------------------------------------------------------------------------- */ module("Core :: Modules", { teardown : function() { delete global.abc; delete global.x; } }); test("Creating empty module", function() { core.Module("abc.Module1", {}); equals(core.Module.isModule(abc.Module1), true); equals(abc.Module1.moduleName, "abc.Module1"); equals(abc.Module1.toString(), "[module abc.Module1]"); }); test("Creating module with short namespace", function() { core.Module("x.Module1", {}); equals(core.Module.isModule(x.Module1), true); equals(x.Module1.moduleName, "x.Module1"); equals(x.Module1.toString(), "[module x.Module1]"); }); test("Module false validation", function() { ok(!core.Module.isModule({})); ok(!core.Module.isModule(3)); ok(!core.Module.isModule(null)); }); test("Creating method module", function() { core.Module("abc.Module2", { method1 : function() {}, method2 : function() {}, method3 : function() {} }); equals(core.Module.isModule(abc.Module2), true); ok(abc.Module2.method1 instanceof Function); ok(abc.Module2.method2 instanceof Function); ok(abc.Module2.method3 instanceof Function); equals(abc.Module2.method1.displayName, "abc.Module2.method1"); equals(abc.Module2.method2.displayName, "abc.Module2.method2"); equals(abc.Module2.method3.displayName, "abc.Module2.method3"); }); test("Checking module name", function() { raises(function() { core.Module("", {}); }); raises(function() { Module(true, {}); }); raises(function() { core.Module(" SpaceVoodoo ", {}); }); raises(function() { core.Module("has space", {}); }); raises(function() { core.Module("firstLow", {}); }); raises(function() { core.Module("two..Dots", {}); }); }); /* --------------------------------------------------------------------------- CORE :: CLASSES :: BASICS --------------------------------------------------------------------------- */ module("Core :: Classes :: Basics", { teardown : function() { core.Main.clearNamespace("abc.Class1"); core.Main.clearNamespace("abc.Class2"); core.Main.clearNamespace("abc.Class3"); } }); test("Invalid config", function() { raises(function() { core.Class("abc.Class1"); }); raises(function() { core.Class("abc.Class2", 42); }) raises(function() { core.Class("abc.Class3", { unallowedKey : "foo" }); }); }); test("Creating empty class", function() { core.Class("abc.Class1", {}); equals(core.Class.isClass(abc.Class1), true); equals(abc.Class1.className, "abc.Class1"); equals(abc.Class1.toString(), "[class abc.Class1]"); }); test("Class false validation", function() { ok(!core.Class.isClass({})); ok(!core.Class.isClass(3)); ok(!core.Class.isClass(null)); }); /* --------------------------------------------------------------------------- CORE :: CLASSES :: MEMBERS --------------------------------------------------------------------------- */ module("Core :: Classes :: Members", { teardown : function() { core.Main.clearNamespace("members.Class1"); core.Main.clearNamespace("members.Include1"); core.Main.clearNamespace("members.Include2"); } }); /** * Two classes which should be mixed into another one define the same member. * A conflict arises, as both could not be merged into the target class. */ test("Conflicting member functions", function() { core.Class("members.Include1", { members : { foo : function() {} } }); core.Class("members.Include2", { members : { foo : function() {} } }); raises(function() { core.Class("members.Join", { include : [members.Include1, members.Include2] }); }); }); /** * Two classes which should be mixed into another one define the same member. * A conflict arises, as both could not be merged into the target class. */ test("Conflicting member data", function() { core.Class("members.Include1", { members : { foo : 1 } }); core.Class("members.Include2", { members : { foo : 2 } }); raises(function() { core.Class("members.Join", { include : [members.Include1, members.Include2] }); }); }); /** * Two classes which should be mixed into another one define the same member. * The conflict is prevented as the affected member is also defined locally. So * the author of the including class is aware of the conflict and could call the * original methods if that makes sense. */ test("Conflicting member functions, correctly merged", function() { core.Class("members.Include1", { members : { foo : function() {} } }); core.Class("members.Include2", { members : { foo : function() {} } }); core.Class("members.Join", { include : [members.Include1, members.Include2], members : { // Merge manually foo : function() { members.Include1.prototype.foo.call(this); members.Include2.prototype.foo.call(this); doSomethingElse(); } } }); ok(true); }); /** * Two classes which should be mixed into another one define the same member. * The conflict is tried being prevented as the affected member is also defined locally. But as * it is not a function this is not regarded as solved. The individual included classes might * require that this member is a function! */ test("Conflicting member functions, not merged correctly", function() { core.Class("members.Include1", { members : { foo : function() {} } }); core.Class("members.Include2", { members : { foo : function() {} } }); raises(function() { core.Class("members.Join", { include : [members.Include1, members.Include2], members : { // Invalid merge foo : null } }); }); }); /** * Two classes which should be mixed into another one define the same member. * The conflict is tried to being prevented as the affected member is also defined locally. * But this is not allowed for private members. */ test("Conflicting member functions with failed private merge", function() { core.Class("members.Include1", { members : { __foo : function() {} } }); core.Class("members.Include2", { members : { __foo : function() {} } }); raises(function() { core.Class("members.Join", { include : [members.Include1, members.Include2], members : { // Private merge... not allowed __foo : function() { members.Include1.prototype.foo.call(this); members.Include2.prototype.foo.call(this); doSomethingElse(); } } }); }); }); /* --------------------------------------------------------------------------- CORE :: CLASSES :: EVENTS --------------------------------------------------------------------------- */ module("Core :: Classes :: Events", { teardown : function() { core.Main.clearNamespace("events.Keyboard"); core.Main.clearNamespace("events.Mouse"); core.Main.clearNamespace("events.Widget"); core.Main.clearNamespace("events.Widget2"); } }); /** * Basic event declaration with additional test to mixin classes. */ // Prepare event classes core.Class("MouseEvent", {}); core.Class("KeyEvent", {}); core.Class("TouchEvent", {}); core.Class("DataEvent", {}); core.Class("FocusEvent", {}); test("Events", function() { core.Class("events.Mouse", { events : { click : MouseEvent, mousedown : MouseEvent, mouseup : MouseEvent } }); var eventMap = core.Class.getEvents(events.Mouse); ok((function() { core.Assert.isType(eventMap, "Map"); return true; })(), "Events should be a returned as a map"); equals(eventMap.click, MouseEvent, "No click event found"); core.Class("events.Keyboard", { events : { keydown : KeyEvent, keyup : KeyEvent } }); core.Class("events.Widget", { include : [events.Mouse, events.Keyboard] }); var full = Object.keys(core.Class.getEvents(events.Widget)).join(","); equals(full, "click,mousedown,mouseup,keydown,keyup", "Merge of events failed"); core.Class("events.Widget2", { include : [events.Mouse, events.Keyboard], events : { custom : DataEvent } }); var full = Object.keys(core.Class.getEvents(events.Widget2)).join(","); equals(full, "custom,click,mousedown,mouseup,keydown,keyup", "Merge of events with own events failed"); }); test("Event Conflicts", function() { core.Class("events.Mouse", { events : { click : MouseEvent, mousedown : MouseEvent, mouseup : MouseEvent } }); core.Class("events.Keyboard", { events : { keydown : KeyEvent, keyup : KeyEvent } }); core.Class("events.Widget", { include : [events.Mouse, events.Keyboard], events : { // This override should be okay click : MouseEvent } }); core.Class("events.Touch", { events : { click : TouchEvent, tap : TouchEvent } }); var full = Object.keys(core.Class.getEvents(events.Widget)).join(","); equals(full, "click,mousedown,mouseup,keydown,keyup", "Merge of events failed"); raises(function() { core.Class("events.Widget2", { // This should fail, two click events in include list include : [events.Mouse, events.Keyboard, events.Touch] }); }) }); test("Event Interfaces", function() { core.Interface("events.UserActions", { events : { click : MouseEvent, mousedown : MouseEvent, mouseup : MouseEvent, focus : FocusEvent, blur : FocusEvent, keydown : KeyEvent, keyup : KeyEvent } }); raises(function() { var MouseEvent = true; core.Class("events.Mouse", { implement : [events.UserActions], events : { click : MouseEvent, mousedown : MouseEvent, mouseup : MouseEvent } }); }); }); /* --------------------------------------------------------------------------- CLASSES :: PROPERTIES --------------------------------------------------------------------------- */ module("Core :: Classes :: Properties", { teardown : function() { core.Main.clearNamespace("properties.Text"); core.Main.clearNamespace("properties.Dimension"); core.Main.clearNamespace("properties.Label"); core.Main.clearNamespace("properties.Simple"); core.Main.clearNamespace("properties.IColor"); core.Main.clearNamespace("properties.IFontSize"); core.Main.clearNamespace("properties.ColorImplementer"); core.Main.clearNamespace("properties.ColorWrongImplementer"); core.Main.clearNamespace("properties.FontSizeImplementer"); core.Main.clearNamespace("properties.FontSizeMissing"); core.Main.clearNamespace("properties.FontSizeWrongImplementer"); core.Main.clearNamespace("properties.Parent"); core.Main.clearNamespace("properties.Child1"); core.Main.clearNamespace("properties.Child2"); } }); test("Creating Properties", function() { core.Class("properties.Simple", { properties : { color : { type : "String", apply : function(value, old) { // pass } }, backgroundColor : { type : "String", apply : function(value, old) { // pass }, fire : "changeBackgroundColor" } }, members : { // Interface implementation fireEvent : function(type, value, old) { // pass } } }); ok((function() { core.Class.assertIsClass(properties.Simple); return true; })()); equals(Object.keys(core.Class.getProperties(properties.Simple)).join(","), "color,backgroundColor"); equals(core.Class.getProperties(properties.Simple).color.type, "String"); equals(typeof core.Class.getProperties(properties.Simple).color.apply, "function"); ok(properties.Simple.prototype.getColor instanceof Function); ok(properties.Simple.prototype.getBackgroundColor instanceof Function); ok(properties.Simple.prototype.setColor instanceof Function); ok(properties.Simple.prototype.setBackgroundColor instanceof Function); equals(properties.Simple.prototype.getColor.displayName, "properties.Simple.getColor"); equals(properties.Simple.prototype.getBackgroundColor.displayName, "properties.Simple.getBackgroundColor"); equals(properties.Simple.prototype.setColor.displayName, "properties.Simple.setColor"); equals(properties.Simple.prototype.setBackgroundColor.displayName, "properties.Simple.setBackgroundColor"); equals(properties.Simple.prototype.getColor.length, 0); equals(properties.Simple.prototype.getBackgroundColor.length, 0); equals(properties.Simple.prototype.setColor.length, 1); equals(properties.Simple.prototype.setBackgroundColor.length, 1); var obj1 = new properties.Simple; equals(obj1.setColor("red"), "red"); equals(obj1.setBackgroundColor("black"), "black"); equals(obj1.getColor(), "red"); equals(obj1.getBackgroundColor(), "black"); }); test("Property Interfaces", function() { core.Interface("properties.IColor", { properties : { color : { type : "String", fire : "changeColor" } } }); core.Class("properties.ColorImplementer", { implement : [properties.IColor], properties : { color : { type : "String", fire : "changeColor" } }, members : { // Interface implementation fireEvent : function(type, value, old) { // pass } } }); raises(function() { core.Class("properties.ColorImplementer", { implement : [properties.IColor], properties : { color : { type : "String" } } }); }); core.Interface("properties.IFontSize", { properties : { /** #require(core.property.Multi) */ fontSize : { type : "Integer", inheritable : true } } }); core.Class("properties.FontSizeImplementer", { implement : [properties.IFontSize], properties : { fontSize : { type : "Integer", inheritable : true } }, members : { // Interface implementation getInheritedValue : function(property) { // pass } } }); raises(function() { core.Class("properties.FontSizeMissing", { implement : [properties.IFontSize] }); }) raises(function() { core.Class("properties.FontSizeWrongImplementer", { implement : [properties.IFontSize], properties : { fontSize : { type : "String", inheritable : true } }, members : { // Interface implementation getInheritedValue : function(property) { // pass } } }); }); }); test("Creating specific properties in classes without matching interfaces", function() { raises(function() { core.Class("properties.NoFireEvent", { properties : { size : { fire : "changeSize" } } }); }); raises(function() { core.Class("properties.NoGetThemed", { properties : { size : { themeable : true } } }); }); raises(function() { core.Class("properties.NoGetInherited", { properties : { size : { inheritable : true } } }); }); }); test("Inheriting Properties", function() { core.Class("properties.Text", { construct : function(element) { this.__textElement = element; }, properties : { wrap : { type : "Boolean", apply : function(value, old) { this.__textElement.style.whiteSpace = value ? "" : "no-wrap" } }, color : { type : "String", apply : function(value, old) { this.__textElement.style.color = value; } }, fontFamily : { type : ["sans-serif", "serif", "monospace"], apply : function(value, old) { this.__textElement.style.fontFamily = value; } }, lineHeight : { type : "Integer", apply : function(value, old) { this.__textElement.style.lineHeight = value; } } }, members : { destruct : function() { this.__textElement = null; } } }); ok(core.Class.isClass(properties.Text)); equals(Object.keys(core.Class.getProperties(properties.Text)).join(","), "wrap,color,fontFamily,lineHeight"); core.Class("properties.Dimension", { properties : { width : { type : "Integer" }, height : { type : "Integer" } } }); ok(core.Class.isClass(properties.Dimension)); equals(Object.keys(core.Class.getProperties(properties.Dimension)).join(","), "width,height"); core.Class("properties.Label", { include : [properties.Text, properties.Dimension], construct : function() { this.__labelElement = document.createElement("label"); properties.Text.call(this, this.__labelElement); this.setLineHeight(2); }, members : { destruct : function() { properties.Text.prototype.destruct.call(this); this.__labelElement = null; } } }); ok(core.Class.isClass(properties.Label)); equals(Object.keys(core.Class.getProperties(properties.Label)).join(","), "wrap,color,fontFamily,lineHeight,width,height"); var ll = new properties.Label; equals(ll.getLineHeight(), 2); }); test("Overwrite properties", function() { core.Class("properties.Parent", { properties : { prop : { init: "Parent" } } }); core.Class("properties.Child1", { include : [properties.Parent], properties : { prop : { init: "Child1" } } }); core.Class("properties.Child2", { include : [properties.Parent] }); var child1 = new properties.Child1(); var child2 = new properties.Child2(); equals("Child1", child1.getProp()); equals("Parent", child2.getProp()); }); });
test/source/class/tests.js
/** * #require(jquery) #require(qunit) #asset(qunit.css) */ var global = this; $(function() { /* --------------------------------------------------------------------------- EXT :: FIX --------------------------------------------------------------------------- */ module("Ext :: Fixes"); asyncTest("setTimeout with arguments", 1, function() { /** #require(ext.TimeoutArgs) */ setTimeout(function(arg) { equals(arg, "hello"); start(); }, 10, "hello"); }); asyncTest("setImmediate", 1, function() { /** #require(ext.Immediate) */ setImmediate(function() { ok(true, "always fine"); start(); }); }); asyncTest("requestAnimationFrame", 1, function() { /** #require(ext.RequestAnimationFrame) */ requestAnimationFrame(function() { ok(true, "always fine"); start(); }); }); test("Object.keys", function() { // Basic first var keys = Object.keys({hello:null, foo:1}).sort().join(","); equals(keys, "foo,hello"); // toString etc. are special in IE because these are built-in keys var keys = Object.keys({toString:null, hello:null, foo:1}).sort().join(","); equals(keys, "foo,hello,toString"); }); /* --------------------------------------------------------------------------- EXT :: SUGAR --------------------------------------------------------------------------- */ module("Ext :: Sugar"); /** #require(ext.sugar.Object) */ test("Object.empty", function() { // toString etc. are special in IE because these are built-in keys ok(Object.isEmpty({})); ok(!Object.isEmpty({toString:null})); ok(!Object.isEmpty({toString:null, hello:null, foo:1})); }); test("Object.values", function() { var values = Object.values({x:1, y:2, z:3}).sort().join(","); equals(values, "1,2,3"); }); test("Object.fromArray", function() { equals(Object.keys(Object.fromArray(["foo","bar","baz"])).join(","), "foo,bar,baz"); equals(Object.values(Object.fromArray(["foo","bar","baz"])).join(","), "true,true,true"); equals(Object.keys(Object.fromArray(["foo","bar","baz"], "hello")).join(","), "foo,bar,baz"); equals(Object.values(Object.fromArray(["foo","bar","baz"], "hello")).join(","), "hello,hello,hello"); }); /** #require(ext.sugar.Array) */ test("Array.prototype.max", function() { equals([1,4,23,3].max(), 23); equals([10,10,10].max(), 10); equals([].max(), -Infinity); }); test("Array.prototype.min", function() { equals([1,4,23,3].min(), 1); equals([10,10,10].min(), 10); equals([].min(), Infinity); }); test("Array.prototype.sum", function() { equals([1,4,23,3].sum(), 31); equals([1,4,23,,,3].sum(), 31); equals([].sum(), 0); }); test("Array.prototype.insertAt", function() { var arr1 = [1,2,3,4,5,6,7]; equals(arr1.insertAt("end"), "end"); equals(arr1.join(","), "1,2,3,4,5,6,7,end"); var arr1 = [1,2,3,4,5,6,7]; equals(arr1.insertAt("begin", 0), "begin"); equals(arr1.join(","), "begin,1,2,3,4,5,6,7"); var arr1 = [1,2,3,4,5,6,7]; equals(arr1.insertAt("fromBegin", 3), "fromBegin"); equals(arr1.join(","), "1,2,3,fromBegin,4,5,6,7"); var arr1 = [1,2,3,4,5,6,7]; equals(arr1.insertAt("fromEnd", -3), "fromEnd"); equals(arr1.join(","), "1,2,3,4,fromEnd,5,6,7"); }); test("Array.prototype.contains", function() { var arr1 = [1,2,3,5,6,7]; ok(arr1.contains(3)); ok(!arr1.contains(4)); ok(arr1.contains(5)); var arr2 = ["true","1",3,false]; ok(!arr2.contains(true)); ok(!arr2.contains(1)); ok(!arr2.contains("3")); ok(!arr2.contains("false")); ok(arr2.contains("true")); ok(arr2.contains("1")); ok(arr2.contains(3)); ok(arr2.contains(false)); }); test("Array.prototype.clone", function() { var orig = [1,2,3]; var clone = orig.clone(); equals(orig.length, clone.length); equals(orig.join(","), clone.join(",")); var orig = [1,2,,,5]; var clone = orig.clone(); equals(orig.length, clone.length); equals(orig.join(","), clone.join(",")); }); test("Array.prototype.remove", function() { var arr = [1,2,3,4,5,6]; equals(arr.remove(4), 4); equals(arr.length, 5); equals(arr.remove(4)); equals(arr.length, 5); var arr = [1,2,3,1,2,3]; equals(arr.remove(3), 3); equals(arr.join(","), "1,2,1,2,3"); }); test("Array.prototype.removeAt", function() { var arr = [1,2,3,4,5,6]; equals(arr.removeAt(2), 3); equals(arr.removeAt(12)); equals(arr.join(","), "1,2,4,5,6"); }); test("Array.prototype.removeRange", function() { var arr = [1,2,3,4,5,6,7,8,9]; arr.removeRange(1, 1); equals(arr.join(","), "1,3,4,5,6,7,8,9"); var arr = [1,2,3,4,5,6,7,8,9]; arr.removeRange(1, 3); equals(arr.join(","), "1,5,6,7,8,9"); var arr = [1,2,3,4,5,6,7,8,9]; arr.removeRange(1, -3); equals(arr.join(","), "1,8,9"); var arr = [1,2,3,4,5,6,7,8,9]; arr.removeRange(-3, -1); equals(arr.join(","), "1,2,3,4,5,6"); }); test("Array.prototype.unique", function() { var arr = [1,2,3,1,2,3]; equals(arr.unique().join(","), "1,2,3"); // sparse arrays supported var arr = [1,2,,,2,3]; equals(arr.unique().join(","), "1,2,3"); // null values are treated special var arr = [1,2,null,null,2,3]; equals(arr.unique().join(","), "1,2,,3"); // selection test var arr = [1,"2",3,"1",2,"3"]; var unique = arr.unique(); equals(unique.join(","), "1,2,3"); equals(typeof unique[0], "number"); equals(typeof unique[1], "string"); equals(typeof unique[2], "number"); // does not support objects var arr = [{},{},{}]; equals(arr.unique().join(","), "[object Object]"); // but can work with special objects var hashCode = 0; var Special = function() { this.hashCode = hashCode++; } Special.prototype.toString = function() { return "[object Special#" + this.hashCode + "]"; } arr = [new Special, new Special, new Special]; equals(arr.unique().join(","), "[object Special#0],[object Special#1],[object Special#2]"); }); test("Array.prototype.at", function() { var arr = [1,2,3,4,5]; equals(arr.at(0), 1); equals(arr.at(-1), 5); equals(arr.at(20)); equals(arr.at(-20)); }); test("Array.prototype.compact", function() { var sparse = [1,2,3,,5,,,8]; equals(sparse.compact().length, 5); var undef; var sparse = [1,2,3,null,5,,undef,8]; equals(sparse.compact().length, 7); equals(sparse.compact(true).length, 5); }); test("Array.prototype.flatten", function() { equals([[1], 2, [3]].flatten().toString(), [1,2,3].toString()); equals([["a"],[],"b","c"].flatten().toString(), ["a","b","c"].toString()); }); /** #require(ext.sugar.Function) */ asyncTest("Function.prototype.debounce - END", 1, function() { var counter = 0; var callback = function() { counter++; }; var debounced = callback.debounce(); debounced(); debounced(); debounced(); debounced(); debounced(); window.setTimeout(function() { equals(counter, 1); start(); }, 200) }); test("Function.prototype.debounce - ASAP", function() { var counter = 0; var callback = function() { counter++; }; var debounced = callback.debounce(100, true); debounced(); debounced(); debounced(); debounced(); debounced(); equals(counter, 1); }); /** #require(ext.sugar.Number) */ test("Number.prototype.pad", function() { equals((23).pad(2), "23"); equals((23).pad(4), "0023"); equals((23).pad(6), "000023"); equals((0).pad(6), "000000"); }); /** #require(ext.sugar.String) */ test("String.prototype.contains", function() { ok("hello world".contains("hello")); ok("hello world".contains("")); ok("hello world".contains(" ")); ok(!"hello world".contains(12)); ok(!"hello world".contains("dlrow")); }); test("String.prototype.hyphenate", function() { equals("backgroundColor".hyphenate(), "background-color"); equals("WebkitTransform".hyphenate(), "-webkit-transform"); equals("ISOString".hyphenate(), "-i-s-o-string"); }); test("String.prototype.repeat", function() { equals("x".repeat(3), "xxx"); equals("xyz".repeat(3), "xyzxyzxyz"); equals("xyz".repeat(0), ""); }); /* --------------------------------------------------------------------------- CORE :: ASSET --------------------------------------------------------------------------- */ module("Core :: Asset"); test("Adding Source Data", function() { raises(function() { core.io.Asset.resetData(); core.io.Asset.toUri("my.png") }); core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "my.png" : {"u":"asset/my.png","p":0} }, "profiles" : [{name:"source"}] }); equals(core.io.Asset.toUri("my.png"), "asset/my.png"); core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "my.png" : {"u":"asset/my.png","p":0} }, "profiles" : [{name:"source", "root":"xxx/yyy/"}] }); equals(core.io.Asset.toUri("my.png"), "xxx/yyy/asset/my.png"); core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "my.png" : {"u":"asset/my.png","p":0} }, "profiles" : [{name:"source", "root":"http://mycdn.com/xxx/yyy/"}] }); equals(core.io.Asset.toUri("my.png"), "http://mycdn.com/xxx/yyy/asset/my.png"); core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "lib2" : { "my.png" : {"u":"../../lib2/asset/my.png","p":0} } }, "profiles" : [{name:"source", "root":"http://mycdn.com/app/source/"}] }); equals(core.io.Asset.toUri("lib2/my.png"), "http://mycdn.com/app/source/../../lib2/asset/my.png"); }); test("Adding Build Data", function() { raises(function() { core.io.Asset.resetData(); core.io.Asset.toUri("my.png") }); core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "my.png" : {"p":0} }, "profiles" : [{name:"build", "root":"asset/"}] }); equals(core.io.Asset.toUri("my.png"), "asset/my.png"); core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "my.png" : {"p":0} }, "profiles" : [{name:"build", "root":"xxx/yyy/asset/"}] }); equals(core.io.Asset.toUri("my.png"), "xxx/yyy/asset/my.png"); core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "my.png" : {"p":0} }, "profiles" : [{name:"build", "root":"http://mycdn.com/xxx/yyy/asset/"}] }); equals(core.io.Asset.toUri("my.png"), "http://mycdn.com/xxx/yyy/asset/my.png"); }); test("Image Sizes", function() { core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "myapp" : { "icons" : { "app.png" : {"d":[48, 48], "p":0} } } }, "profiles" : [{name:"build", "root":"asset/"}] }); equals(core.io.Asset.toUri("myapp/icons/app.png"), "asset/myapp/icons/app.png"); equals(core.io.Asset.getImageSize("myapp/icons/app.png")+"", [48, 48]+""); equals(core.io.Asset.getFrameNumber("myapp/icons/app.png"), 1); }); test("Image Sprite - None", function() { core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "myapp" : { "icons" : { "app.png" : {"d":[48, 48], "p":0} } } }, "profiles" : [{name:"build", "root":"asset/"}] }); equals(core.io.Asset.toUri("myapp/icons/app.png"), "asset/myapp/icons/app.png"); var imgData = core.io.Asset.getImage("myapp/icons/app.png"); strictEqual(imgData.left, 0); strictEqual(imgData.top, 0); strictEqual(imgData.src, "asset/myapp/icons/app.png"); }); test("Image Sprite - Same Folder", function() { core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "myapp" : { "icons" : { "app.png" : {"d":[48, 48, [0, 96, 240]], "p":0}, "icons.png" : {"d":[288, 288], "p":0} } } }, "profiles" : [{name:"build", "root":"asset/"}], "sprites" : ["icons.png"] }); equals(core.io.Asset.toUri("myapp/icons/app.png"), "asset/myapp/icons/app.png"); var imgData = core.io.Asset.getImage("myapp/icons/app.png"); strictEqual(imgData.width, 48); strictEqual(imgData.height, 48); strictEqual(imgData.left, 96); strictEqual(imgData.top, 240); strictEqual(imgData.src, "asset/myapp/icons/icons.png"); }); test("Image Sprite - Absolute ID", function() { core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "myapp" : { "icons.png" : {"d":[288, 288], "p":0}, "icons" : { "app.png" : {"d":[48, 48, [0, 96, 240]], "p":0} } } }, "profiles" : [{name:"build", "root":"asset/"}], "sprites" : ["myapp/icons.png"] }); equals(core.io.Asset.toUri("myapp/icons/app.png"), "asset/myapp/icons/app.png"); var imgData = core.io.Asset.getImage("myapp/icons/app.png"); strictEqual(imgData.width, 48); strictEqual(imgData.height, 48); strictEqual(imgData.left, 96); strictEqual(imgData.top, 240); strictEqual(imgData.src, "asset/myapp/icons.png"); }); test("Image Sprite - Root ID", function() { core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "icons.png" : {"d":[288, 288], "p":0}, "myapp" : { "icons" : { "app.png" : {"d":[48, 48, [0, 96, 240]], "p":0} } } }, "profiles" : [{name:"build", "root":"asset/"}], "sprites" : ["/icons.png"] }); equals(core.io.Asset.toUri("myapp/icons/app.png"), "asset/myapp/icons/app.png"); var imgData = core.io.Asset.getImage("myapp/icons/app.png"); strictEqual(imgData.width, 48); strictEqual(imgData.height, 48); strictEqual(imgData.left, 96); strictEqual(imgData.top, 240); strictEqual(imgData.src, "asset/icons.png"); }); test("Frames - Rows/Columns", function() { core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "myapp" : { "anim" : { "loading.png" : [16*16, 16, 16, 1], "explode.png" : [32*30, 32*3, 30, 3], "collapse.png" : [12*2, 12*20, 2, 20, 86] } } }, "profiles" : [{name:"build", "root":"asset/"}] }); strictEqual(core.io.Asset.getFrameNumber("myapp/anim/loading.png"), 16, "number of frames I"); strictEqual(core.io.Asset.getFrameNumber("myapp/anim/explode.png"), 90, "number of frames II"); strictEqual(core.io.Asset.getFrameNumber("myapp/anim/collapse.png"), 86, "number of frames III"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 0).left, 0, "left position first"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 1).left, 16, "left position second"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 13).left, 208, "left position inner"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 15).left, 240, "left position last"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 0).top, 0, "top position first"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 1).top, 0, "top position second"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 13).top, 0, "top position inner"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 15).top, 0, "top position last"); strictEqual(core.io.Asset.getFrame("myapp/anim/collapse.png", 2).left, 0, "left other image"); strictEqual(core.io.Asset.getFrame("myapp/anim/collapse.png", 2).top, 12, "top other image"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 13).width, 16, "corrected width"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 13).height, 16, "corrected height"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 13).src, "asset/myapp/anim/loading.png", "normal source handling I"); strictEqual(core.io.Asset.getImage("myapp/anim/loading.png").width, 256, "full image width"); strictEqual(core.io.Asset.getImage("myapp/anim/loading.png").height, 16, "full image height"); strictEqual(core.io.Asset.getImage("myapp/anim/loading.png").src, "asset/myapp/anim/loading.png", "normal source handling II"); }); test("Frames - Rows/Columns in Image Sprite", function() { core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "myapp" : { "sprite.png" : [960, 352, "asset/myapp/sprite.png"], "anim" : { "loading.png" : [16*16, 16, "myapp/sprite.png", 20, 0, 16, 1], "explode.png" : [32*30, 32*3, "myapp/sprite.png", 40, 16, 30, 3], "collapse.png" : [12*2, 12*20, "myapp/sprite.png", 60, 112, 2, 20, 86] } } }, "profiles" : [{name:"build", "root":"asset/"}] }); strictEqual(core.io.Asset.getFrameNumber("myapp/anim/loading.png"), 16, "number of frames I"); strictEqual(core.io.Asset.getFrameNumber("myapp/anim/explode.png"), 90, "number of frames II"); strictEqual(core.io.Asset.getFrameNumber("myapp/anim/collapse.png"), 86, "number of frames III"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 0).left, 20, "left position first"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 1).left, 36, "left position second"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 13).left, 228, "left position inner"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 15).left, 260, "left position last"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 0).top, 0, "top position first"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 1).top, 0, "top position second"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 13).top, 0, "top position inner"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 15).top, 0, "top position last"); strictEqual(core.io.Asset.getFrame("myapp/anim/collapse.png", 2).left, 60, "left other image"); strictEqual(core.io.Asset.getFrame("myapp/anim/collapse.png", 2).top, 124, "top other image"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 13).width, 16, "corrected width"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 13).height, 16, "corrected height"); strictEqual(core.io.Asset.getFrame("myapp/anim/loading.png", 13).src, "asset/myapp/sprite.png", "normal source sprite handling I"); strictEqual(core.io.Asset.getImage("myapp/anim/loading.png").width, 256, "full image width"); strictEqual(core.io.Asset.getImage("myapp/anim/loading.png").height, 16, "full image height"); strictEqual(core.io.Asset.getImage("myapp/anim/loading.png").src, "asset/myapp/sprite.png", "normal source sprite handling II"); }); test("Frames - Custom", function() { core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "myapp" : { "anim" : { "guy.png" : [200, 16, [ // Format: left, top, width, height, offsetLeft?, offsetTop?, rotation? [ 0, 0, 20, 20], [30, 50, 10, 30, 20, 50], [70, 20, 14, 40, 0, 30, 90] ]] } }, }, "profiles" : [{name:"build", "root":"asset/"}] }); strictEqual(core.io.Asset.getFrameNumber("myapp/anim/guy.png"), 3, "number of frames"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).left, 0, "left position I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).top, 0, "top position I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).width, 20, "width I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).height, 20, "height I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).offsetLeft, 0, "offsetLeft I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).offsetTop, 0, "offsetTop I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).rotation, 0, "rotation I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).left, 30, "left position II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).top, 50, "top position II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).width, 10, "width II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).height, 30, "height II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).offsetLeft, 20, "offsetLeft II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).offsetTop, 50, "offsetTop II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).rotation, 0, "rotation II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).left, 70, "left position III"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).top, 20, "top position III"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).width, 14, "width III"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).height, 40, "height III"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).offsetLeft, 0, "offsetLeft III"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).offsetTop, 30, "offsetTop III"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).rotation, 90, "rotation III"); }); test("Frames - Custom in Image Sprite", function() { core.io.Asset.resetData(); core.io.Asset.addData( { "assets" : { "myapp" : { "sprite.png" : [960, 352], "anim" : { "guy.png" : [200, 16, "myapp/sprite.png", 20, 40, [ // Format: left, top, width, height, offsetLeft?, offsetTop?, rotation? [ 0, 0, 20, 20], [30, 50, 10, 30, 20, 50], [70, 20, 14, 40, 0, 30, 90] ]] } }, }, "profiles" : [{name:"build", "root":"asset/"}] }); strictEqual(core.io.Asset.getFrameNumber("myapp/anim/guy.png"), 3, "number of frames"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).left, 20, "left position I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).top, 40, "top position I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).width, 20, "width I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).height, 20, "height I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).offsetLeft, 0, "offsetLeft I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).offsetTop, 0, "offsetTop I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).rotation, 0, "rotation I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 0).src, "asset/myapp/sprite.png", "source I"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).left, 50, "left position II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).top, 90, "top position II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).width, 10, "width II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).height, 30, "height II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).offsetLeft, 20, "offsetLeft II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).offsetTop, 50, "offsetTop II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).rotation, 0, "rotation II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 1).src, "asset/myapp/sprite.png", "source II"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).left, 90, "left position III"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).top, 60, "top position III"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).width, 14, "width III"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).height, 40, "height III"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).offsetLeft, 0, "offsetLeft III"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).offsetTop, 30, "offsetTop III"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).rotation, 90, "rotation III"); strictEqual(core.io.Asset.getFrame("myapp/anim/guy.png", 2).src, "asset/myapp/sprite.png", "source III"); }); /* --------------------------------------------------------------------------- CORE :: UTIL --------------------------------------------------------------------------- */ module("Core :: Util"); test("Id", function() { var myFunc = new Function; strictEqual(core.util.Id.get(myFunc), 1); strictEqual(core.util.Id.get(myFunc), 1); strictEqual(core.util.Id.get(document.body), 2); strictEqual(core.util.Id.get(document.body), 2); }); /* --------------------------------------------------------------------------- CORE :: BOM --------------------------------------------------------------------------- */ module("Core :: BOM"); test("Text", function() { strictEqual(typeof core.bom.Text.measure("hello world"), "object"); strictEqual(typeof core.bom.Text.measure("hello world").width, "number"); strictEqual(typeof core.bom.Text.measure("hello world").height, "number"); strictEqual(typeof core.bom.Text.measure("hello world foo bar baz", null, 40), "object"); strictEqual(core.bom.Text.measure("hello world foo bar baz", null, 40).width, 40); }); /* --------------------------------------------------------------------------- CORE :: TEMPLATE --------------------------------------------------------------------------- */ module("Core :: Template"); test("Basic", function() { var template = core.template.Compiler.compile("Follow @{{screenName}}."); ok(template instanceof core.template.Template); var output = template.render({ screenName: "dhg" }); equal(output, "Follow @dhg."); var output = template.render({ screenName: "wpbasti" }); equal(output, "Follow @wpbasti."); }); test("Line Breaks", function() { var template = core.template.Compiler.compile("Break\nHere {{value}}."); ok(template instanceof core.template.Template); var output = template.render({ value: "xxx" }); equal(output, "Break\nHere xxx."); }); test("Lists", function() { var template = core.template.Compiler.compile("{{#repo}}<b>{{name}}</b>{{/repo}}"); ok(template instanceof core.template.Template); var output = template.render({ "repo": [ { "name": "resque" }, { "name": "hub" }, { "name": "rip" } ] }); equal(output, "<b>resque</b><b>hub</b><b>rip</b>"); }); test("Conditional Lists", function() { var template = core.template.Compiler.compile("{{?repo}}Repos<br/>{{#repo}}<b>{{name}}</b>{{/repo}}{{/repo}}"); ok(template instanceof core.template.Template); var output = template.render({ "repo": [ { "name": "resque" }, { "name": "hub" }, { "name": "rip" } ] }); equal(output, "Repos<br/><b>resque</b><b>hub</b><b>rip</b>"); var output = template.render({ "repo": [] }); equal(output, ""); var template = core.template.Compiler.compile("{{#other}}<em>{{name}}</em>{{/other}}{{?repo}}Repos<br/>{{#repo}}<b>{{name}}</b>{{/repo}}{{/repo}}"); var output = template.render({ "repo": [], "other": [ { "name": "resque" }, { "name": "hub" }, { "name": "rip" } ] }); equal(output, "<em>resque</em><em>hub</em><em>rip</em>"); var template = core.template.Compiler.compile("{{#other}}<em>{{foo}}</em>{{/other}}{{?repo}}Repos<br/>{{#repo}}<b>{{name}}</b>{{/repo}}{{/repo}}"); var output = template.render({ "repo": [ { "name": "resque" }, { "name": "hub" }, { "name": "rip" } ], "other": { "foo" : "bar" } }); equal(output, "<em>bar</em>Repos<br/><b>resque</b><b>hub</b><b>rip</b>"); }); test("Non False", function() { var template = core.template.Compiler.compile("{{#person?}}Hi {{name}}!{{/person?}}"); ok(template instanceof core.template.Template); var output = template.render({ "person?": { "name": "Jon" } }); equal(output, "Hi Jon!"); }); test("Inverted Sections", function() { var template = core.template.Compiler.compile("{{#repo}}<b>{{.}}</b>{{/repo}}{{^repo}}No repos :({{/repo}}"); ok(template instanceof core.template.Template); var output = template.render({ "repo": [] }); equal(output, "No repos :("); var output = template.render({ "repo": [1,2,3] }); equal(output, "<b>1</b><b>2</b><b>3</b>"); }); test("Comments", function() { var template = core.template.Compiler.compile("<h1>Today{{! ignore me }}.</h1>"); ok(template instanceof core.template.Template); var output = template.render({ "repo": [] }); equal(output, "<h1>Today.</h1>"); }); test("Unescaped", function() { var template = core.template.Compiler.compile("{{code}}"); ok(template instanceof core.template.Template); var output = template.render({ "code": "<b>Foo</b>" }); equal(output, "&lt;b&gt;Foo&lt;/b&gt;"); var output = template.render({ "code": "Bert & Ernie" }); equal(output, "Bert &amp; Ernie"); var template = core.template.Compiler.compile("{{&code}}"); ok(template instanceof core.template.Template); var output = template.render({ "code": "<b>Foo</b>" }); equal(output, "<b>Foo</b>"); }); test("Partials", function() { var template = core.template.Compiler.compile("{{#tweets}}{{> tweet}}{{/tweets}}"); ok(template instanceof core.template.Template); var tweetTemplate = core.template.Compiler.compile('<p data-id="{{id}}">{{text}}</p>'); ok(tweetTemplate instanceof core.template.Template); var output = template.render({ "tweets": [{ text: "hello world", id: 1 }, { text: "this is a test tweet", id: 2 }, { text: "to impress you", id: 3 }] }, { tweet: tweetTemplate }); equal(output, "<p data-id=\"1\">hello world</p><p data-id=\"2\">this is a test tweet</p><p data-id=\"3\">to impress you</p>"); }); test("Parser", function() { var text = "{{^check}}No{{/check}}{{#check}}Yes{{/check}}"; var tree = core.template.Parser.parse(text); equals(tree[0].tag, "^"); equals(tree[0].name, "check"); equals(tree[1].tag, "#"); equals(tree[1].name, "check"); }); test("Dots", function() { var template = core.template.Compiler.compile("{{#tweets}}{{author.name}}[{{author.id}}]{{/tweets}}"); var output = template.render({ "tweets": [{ author: { name : "Sascha", id : 0 } }, { author: { name : "Christoph", id : 1 } }, { author: { name : "Ivo", id : 2 } }] }); equals(output, "Sascha[0]Christoph[1]Ivo[2]"); }); /* --------------------------------------------------------------------------- CORE :: CRYPT --------------------------------------------------------------------------- */ module("Core :: Crypt"); test("Adler32", function() { strictEqual(core.crypt.Adler32.checksum("hello world"), 436929629); strictEqual(core.crypt.Adler32.checksum("hello world!"), 512296062); strictEqual(core.crypt.Adler32.checksum("günthér falit°@"), 1479674097); }); test("CRC32", function() { strictEqual(core.crypt.CRC32.checksum("hello world"), 222957957); strictEqual(core.crypt.CRC32.checksum("hello world!"), 62177901); strictEqual(core.crypt.CRC32.checksum("günthér falit°@"), 1047403603); }); test("MD5", function() { strictEqual(core.crypt.MD5.checksum("hello world").toHex(), "5eb63bbbe01eeed093cb22bb8f5acdc3"); strictEqual(core.crypt.MD5.checksum("hello karl").toHex(), "967f3d167631b54ea74b380e439ec2d5"); strictEqual(core.crypt.MD5.checksum("günthér falit°@").toHex(), "c901b2c94c101e0c2fdb2c96a041ceda"); strictEqual(core.crypt.MD5.hmac("secret", "hello world").toHex(), "78d6997b1230f38e59b6d1642dfaa3a4"); strictEqual(core.crypt.MD5.hmac("secret", "hello karl").toHex(), "1df06dd6ad23a62de80b713bdfc5f59f"); strictEqual(core.crypt.MD5.hmac("other secret", "hello world").toHex(), "614ff83602727ee68fba3e9500856fad"); strictEqual(core.crypt.MD5.hmac("other secret", "hello karl").toHex(), "71b406e27e5184663c0c01448b57c5a7"); }); test("SHA1", function() { strictEqual(core.crypt.SHA1.checksum("hello world").toHex(), "2aae6c35c94fcfb415dbe95f408b9ce91ee846ed"); strictEqual(core.crypt.SHA1.checksum("hello karl").toHex(), "1665bcf30c12443dbb332b84590123f7d544500b"); strictEqual(core.crypt.SHA1.checksum("günthér falit°@").toHex(), "01695e64d0f83e453281f385209884e94784c7bf"); strictEqual(core.crypt.SHA1.hmac("secret", "hello world").toHex(), "03376ee7ad7bbfceee98660439a4d8b125122a5a"); strictEqual(core.crypt.SHA1.hmac("secret", "hello karl").toHex(), "1de9256cf6805f714a59b69806647b34315ae6ad"); strictEqual(core.crypt.SHA1.hmac("other secret", "hello world").toHex(), "2b7dd1114abb301c6a3879612c040db1dc76efe7"); strictEqual(core.crypt.SHA1.hmac("other secret", "hello karl").toHex(), "1005fc78d9e3c525c72c3dcaef4ec2d1ae2d638d"); }); test("SHA256", function() { strictEqual(core.crypt.SHA256.checksum("hello world").toHex(), "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"); strictEqual(core.crypt.SHA256.checksum("hello karl").toHex(), "710e9c35558708b24698b55e5e890b506fc946558b3aaa4b356ba008e4edc860"); strictEqual(core.crypt.SHA256.checksum("günthér falit°@").toHex(), "2b62c8f744680ed05d50246db24cdbc491532f185a736c72e7cd94a7bbd41e77"); strictEqual(core.crypt.SHA256.hmac("secret", "hello world").toHex(), "734cc62f32841568f45715aeb9f4d7891324e6d948e4c6c60c0621cdac48623a"); strictEqual(core.crypt.SHA256.hmac("secret", "hello karl").toHex(), "22585ec85d81b38049d3446dd109507bd6d72478b07ef35efb4767260fe09715"); strictEqual(core.crypt.SHA256.hmac("other secret", "hello world").toHex(), "02113759509b1c7ae0deaee8f022d84f828e7d46ae9255044c3d801ad2b09a39"); strictEqual(core.crypt.SHA256.hmac("other secret", "hello karl").toHex(), "17f71ee9084ade98ed82ee4153ceb47707381e5852b473fb77eb8632e06e8bb8"); }); /* --------------------------------------------------------------------------- CORE :: COLLECTION :: LINKED LIST --------------------------------------------------------------------------- */ module("Core :: Collection :: LinkedList"); test("Create", function() { var ll = new core.collection.LinkedList; ok(ll instanceof core.collection.LinkedList); }); test("Import/Export", function() { var Cls = function(i) { this.id = i; }; var array = [new Cls(1), new Cls(2), new Cls(3), new Cls(4), new Cls(5)]; var ll = new core.collection.LinkedList(array); ok(ll instanceof core.collection.LinkedList); equal(ll.getLength(), array.length); var exported = ll.toArray(); ok(exported instanceof Array); equal(exported.length, array.length); equal(array[0], exported[0]); equal(array[1], exported[1]); equal(array[2], exported[2]); equal(array[3], exported[3]); equal(array[4], exported[4]); }); test("Add/Remove Sorted", function() { var Cls = function(i) { this.id = i; }; var ll = new core.collection.LinkedList; ok(ll instanceof core.collection.LinkedList); equal(ll.getLength(), 0); var first = new Cls(1); var second = new Cls(2); var third = new Cls(3); strictEqual(ll.add(first), ll); equal(ll.getLength(), 1); strictEqual(ll.add(second), ll); equal(ll.getLength(), 2); strictEqual(ll.add(third), ll); equal(ll.getLength(), 3); var exported = ll.toArray(); strictEqual(ll.remove(first), ll); equal(ll.getLength(), 2); strictEqual(ll.remove(second), ll); equal(ll.getLength(), 1); strictEqual(ll.remove(third), ll); equal(ll.getLength(), 0); // Exported not modified by changes equal(exported.length, 3); }); test("Add/Remove Random", function() { var Cls = function(i) { this.id = i; }; var ll = new core.collection.LinkedList; ok(ll instanceof core.collection.LinkedList); equal(ll.getLength(), 0); var first = new Cls(1); var second = new Cls(2); var third = new Cls(3); strictEqual(ll.add(first), ll); equal(ll.getLength(), 1); var exported = ll.toArray(); strictEqual(exported[0], first); strictEqual(ll.add(second), ll); equal(ll.getLength(), 2); var exported = ll.toArray(); equal(exported.length, 2); strictEqual(exported[0], first); strictEqual(exported[1], second); strictEqual(ll.remove(first), ll); equal(ll.getLength(), 1); var exported = ll.toArray(); equal(exported.length, 1); strictEqual(exported[0], second); strictEqual(ll.add(third), ll); equal(ll.getLength(), 2); strictEqual(ll.remove(third), ll); equal(ll.getLength(), 1); strictEqual(ll.remove(second), ll); equal(ll.getLength(), 0); }); test("Add/Remove Random", function() { var Cls = function(i) { this.id = i; }; var ll = new core.collection.LinkedList; ok(ll instanceof core.collection.LinkedList); equal(ll.getLength(), 0); }); /* --------------------------------------------------------------------------- CORE :: NAMESPACES --------------------------------------------------------------------------- */ module("Core :: Namespaces", { teardown : function() { delete global.foo; delete global.abc; delete global.a; } }); test("Creating global", function() { core.Main.declareNamespace("foo", 3); equals(global.foo, 3); }); test("Creating namespace", function() { core.Main.declareNamespace("abc.def", 5); equals(global.abc.def, 5); }); /* --------------------------------------------------------------------------- CORE :: MODULES --------------------------------------------------------------------------- */ module("Core :: Modules", { teardown : function() { delete global.abc; delete global.x; } }); test("Creating empty module", function() { core.Module("abc.Module1", {}); equals(core.Module.isModule(abc.Module1), true); equals(abc.Module1.moduleName, "abc.Module1"); equals(abc.Module1.toString(), "[module abc.Module1]"); }); test("Creating module with short namespace", function() { core.Module("x.Module1", {}); equals(core.Module.isModule(x.Module1), true); equals(x.Module1.moduleName, "x.Module1"); equals(x.Module1.toString(), "[module x.Module1]"); }); test("Module false validation", function() { ok(!core.Module.isModule({})); ok(!core.Module.isModule(3)); ok(!core.Module.isModule(null)); }); test("Creating method module", function() { core.Module("abc.Module2", { method1 : function() {}, method2 : function() {}, method3 : function() {} }); equals(core.Module.isModule(abc.Module2), true); ok(abc.Module2.method1 instanceof Function); ok(abc.Module2.method2 instanceof Function); ok(abc.Module2.method3 instanceof Function); equals(abc.Module2.method1.displayName, "abc.Module2.method1"); equals(abc.Module2.method2.displayName, "abc.Module2.method2"); equals(abc.Module2.method3.displayName, "abc.Module2.method3"); }); test("Checking module name", function() { raises(function() { core.Module("", {}); }); raises(function() { Module(true, {}); }); raises(function() { core.Module(" SpaceVoodoo ", {}); }); raises(function() { core.Module("has space", {}); }); raises(function() { core.Module("firstLow", {}); }); raises(function() { core.Module("two..Dots", {}); }); }); /* --------------------------------------------------------------------------- CORE :: CLASSES :: BASICS --------------------------------------------------------------------------- */ module("Core :: Classes :: Basics", { teardown : function() { core.Main.clearNamespace("abc.Class1"); core.Main.clearNamespace("abc.Class2"); core.Main.clearNamespace("abc.Class3"); } }); test("Invalid config", function() { raises(function() { core.Class("abc.Class1"); }); raises(function() { core.Class("abc.Class2", 42); }) raises(function() { core.Class("abc.Class3", { unallowedKey : "foo" }); }); }); test("Creating empty class", function() { core.Class("abc.Class1", {}); equals(core.Class.isClass(abc.Class1), true); equals(abc.Class1.className, "abc.Class1"); equals(abc.Class1.toString(), "[class abc.Class1]"); }); test("Class false validation", function() { ok(!core.Class.isClass({})); ok(!core.Class.isClass(3)); ok(!core.Class.isClass(null)); }); /* --------------------------------------------------------------------------- CORE :: CLASSES :: MEMBERS --------------------------------------------------------------------------- */ module("Core :: Classes :: Members", { teardown : function() { core.Main.clearNamespace("members.Class1"); core.Main.clearNamespace("members.Include1"); core.Main.clearNamespace("members.Include2"); } }); /** * Two classes which should be mixed into another one define the same member. * A conflict arises, as both could not be merged into the target class. */ test("Conflicting member functions", function() { core.Class("members.Include1", { members : { foo : function() {} } }); core.Class("members.Include2", { members : { foo : function() {} } }); raises(function() { core.Class("members.Join", { include : [members.Include1, members.Include2] }); }); }); /** * Two classes which should be mixed into another one define the same member. * A conflict arises, as both could not be merged into the target class. */ test("Conflicting member data", function() { core.Class("members.Include1", { members : { foo : 1 } }); core.Class("members.Include2", { members : { foo : 2 } }); raises(function() { core.Class("members.Join", { include : [members.Include1, members.Include2] }); }); }); /** * Two classes which should be mixed into another one define the same member. * The conflict is prevented as the affected member is also defined locally. So * the author of the including class is aware of the conflict and could call the * original methods if that makes sense. */ test("Conflicting member functions, correctly merged", function() { core.Class("members.Include1", { members : { foo : function() {} } }); core.Class("members.Include2", { members : { foo : function() {} } }); core.Class("members.Join", { include : [members.Include1, members.Include2], members : { // Merge manually foo : function() { members.Include1.prototype.foo.call(this); members.Include2.prototype.foo.call(this); doSomethingElse(); } } }); ok(true); }); /** * Two classes which should be mixed into another one define the same member. * The conflict is tried being prevented as the affected member is also defined locally. But as * it is not a function this is not regarded as solved. The individual included classes might * require that this member is a function! */ test("Conflicting member functions, not merged correctly", function() { core.Class("members.Include1", { members : { foo : function() {} } }); core.Class("members.Include2", { members : { foo : function() {} } }); raises(function() { core.Class("members.Join", { include : [members.Include1, members.Include2], members : { // Invalid merge foo : null } }); }); }); /** * Two classes which should be mixed into another one define the same member. * The conflict is tried to being prevented as the affected member is also defined locally. * But this is not allowed for private members. */ test("Conflicting member functions with failed private merge", function() { core.Class("members.Include1", { members : { __foo : function() {} } }); core.Class("members.Include2", { members : { __foo : function() {} } }); raises(function() { core.Class("members.Join", { include : [members.Include1, members.Include2], members : { // Private merge... not allowed __foo : function() { members.Include1.prototype.foo.call(this); members.Include2.prototype.foo.call(this); doSomethingElse(); } } }); }); }); /* --------------------------------------------------------------------------- CORE :: CLASSES :: EVENTS --------------------------------------------------------------------------- */ module("Core :: Classes :: Events", { teardown : function() { core.Main.clearNamespace("events.Keyboard"); core.Main.clearNamespace("events.Mouse"); core.Main.clearNamespace("events.Widget"); core.Main.clearNamespace("events.Widget2"); } }); /** * Basic event declaration with additional test to mixin classes. */ // Prepare event classes core.Class("MouseEvent", {}); core.Class("KeyEvent", {}); core.Class("TouchEvent", {}); core.Class("DataEvent", {}); core.Class("FocusEvent", {}); test("Events", function() { core.Class("events.Mouse", { events : { click : MouseEvent, mousedown : MouseEvent, mouseup : MouseEvent } }); var eventMap = core.Class.getEvents(events.Mouse); ok((function() { core.Assert.isType(eventMap, "Map"); return true; })(), "Events should be a returned as a map"); equals(eventMap.click, MouseEvent, "No click event found"); core.Class("events.Keyboard", { events : { keydown : KeyEvent, keyup : KeyEvent } }); core.Class("events.Widget", { include : [events.Mouse, events.Keyboard] }); var full = Object.keys(core.Class.getEvents(events.Widget)).join(","); equals(full, "click,mousedown,mouseup,keydown,keyup", "Merge of events failed"); core.Class("events.Widget2", { include : [events.Mouse, events.Keyboard], events : { custom : DataEvent } }); var full = Object.keys(core.Class.getEvents(events.Widget2)).join(","); equals(full, "custom,click,mousedown,mouseup,keydown,keyup", "Merge of events with own events failed"); }); test("Event Conflicts", function() { core.Class("events.Mouse", { events : { click : MouseEvent, mousedown : MouseEvent, mouseup : MouseEvent } }); core.Class("events.Keyboard", { events : { keydown : KeyEvent, keyup : KeyEvent } }); core.Class("events.Widget", { include : [events.Mouse, events.Keyboard], events : { // This override should be okay click : MouseEvent } }); core.Class("events.Touch", { events : { click : TouchEvent, tap : TouchEvent } }); var full = Object.keys(core.Class.getEvents(events.Widget)).join(","); equals(full, "click,mousedown,mouseup,keydown,keyup", "Merge of events failed"); raises(function() { core.Class("events.Widget2", { // This should fail, two click events in include list include : [events.Mouse, events.Keyboard, events.Touch] }); }) }); test("Event Interfaces", function() { core.Interface("events.UserActions", { events : { click : MouseEvent, mousedown : MouseEvent, mouseup : MouseEvent, focus : FocusEvent, blur : FocusEvent, keydown : KeyEvent, keyup : KeyEvent } }); raises(function() { var MouseEvent = true; core.Class("events.Mouse", { implement : [events.UserActions], events : { click : MouseEvent, mousedown : MouseEvent, mouseup : MouseEvent } }); }); }); /* --------------------------------------------------------------------------- CLASSES :: PROPERTIES --------------------------------------------------------------------------- */ module("Core :: Classes :: Properties", { teardown : function() { core.Main.clearNamespace("properties.Text"); core.Main.clearNamespace("properties.Dimension"); core.Main.clearNamespace("properties.Label"); core.Main.clearNamespace("properties.Simple"); core.Main.clearNamespace("properties.IColor"); core.Main.clearNamespace("properties.IFontSize"); core.Main.clearNamespace("properties.ColorImplementer"); core.Main.clearNamespace("properties.ColorWrongImplementer"); core.Main.clearNamespace("properties.FontSizeImplementer"); core.Main.clearNamespace("properties.FontSizeMissing"); core.Main.clearNamespace("properties.FontSizeWrongImplementer"); core.Main.clearNamespace("properties.Parent"); core.Main.clearNamespace("properties.Child1"); core.Main.clearNamespace("properties.Child2"); } }); test("Creating Properties", function() { core.Class("properties.Simple", { properties : { color : { type : "String", apply : function(value, old) { // pass } }, backgroundColor : { type : "String", apply : function(value, old) { // pass }, fire : "changeBackgroundColor" } }, members : { // Interface implementation fireEvent : function(type, value, old) { // pass } } }); ok((function() { core.Class.assertIsClass(properties.Simple); return true; })()); equals(Object.keys(core.Class.getProperties(properties.Simple)).join(","), "color,backgroundColor"); equals(core.Class.getProperties(properties.Simple).color.type, "String"); equals(typeof core.Class.getProperties(properties.Simple).color.apply, "function"); ok(properties.Simple.prototype.getColor instanceof Function); ok(properties.Simple.prototype.getBackgroundColor instanceof Function); ok(properties.Simple.prototype.setColor instanceof Function); ok(properties.Simple.prototype.setBackgroundColor instanceof Function); equals(properties.Simple.prototype.getColor.displayName, "properties.Simple.getColor"); equals(properties.Simple.prototype.getBackgroundColor.displayName, "properties.Simple.getBackgroundColor"); equals(properties.Simple.prototype.setColor.displayName, "properties.Simple.setColor"); equals(properties.Simple.prototype.setBackgroundColor.displayName, "properties.Simple.setBackgroundColor"); equals(properties.Simple.prototype.getColor.length, 0); equals(properties.Simple.prototype.getBackgroundColor.length, 0); equals(properties.Simple.prototype.setColor.length, 1); equals(properties.Simple.prototype.setBackgroundColor.length, 1); var obj1 = new properties.Simple; equals(obj1.setColor("red"), "red"); equals(obj1.setBackgroundColor("black"), "black"); equals(obj1.getColor(), "red"); equals(obj1.getBackgroundColor(), "black"); }); test("Property Interfaces", function() { core.Interface("properties.IColor", { properties : { color : { type : "String", fire : "changeColor" } } }); core.Class("properties.ColorImplementer", { implement : [properties.IColor], properties : { color : { type : "String", fire : "changeColor" } }, members : { // Interface implementation fireEvent : function(type, value, old) { // pass } } }); raises(function() { core.Class("properties.ColorImplementer", { implement : [properties.IColor], properties : { color : { type : "String" } } }); }); core.Interface("properties.IFontSize", { properties : { /** #require(core.property.Multi) */ fontSize : { type : "Integer", inheritable : true } } }); core.Class("properties.FontSizeImplementer", { implement : [properties.IFontSize], properties : { fontSize : { type : "Integer", inheritable : true } }, members : { // Interface implementation getInheritedValue : function(property) { // pass } } }); raises(function() { core.Class("properties.FontSizeMissing", { implement : [properties.IFontSize] }); }) raises(function() { core.Class("properties.FontSizeWrongImplementer", { implement : [properties.IFontSize], properties : { fontSize : { type : "String", inheritable : true } }, members : { // Interface implementation getInheritedValue : function(property) { // pass } } }); }); }); test("Creating specific properties in classes without matching interfaces", function() { raises(function() { core.Class("properties.NoFireEvent", { properties : { size : { fire : "changeSize" } } }); }); raises(function() { core.Class("properties.NoGetThemed", { properties : { size : { themeable : true } } }); }); raises(function() { core.Class("properties.NoGetInherited", { properties : { size : { inheritable : true } } }); }); }); test("Inheriting Properties", function() { core.Class("properties.Text", { construct : function(element) { this.__textElement = element; }, properties : { wrap : { type : "Boolean", apply : function(value, old) { this.__textElement.style.whiteSpace = value ? "" : "no-wrap" } }, color : { type : "String", apply : function(value, old) { this.__textElement.style.color = value; } }, fontFamily : { type : ["sans-serif", "serif", "monospace"], apply : function(value, old) { this.__textElement.style.fontFamily = value; } }, lineHeight : { type : "Integer", apply : function(value, old) { this.__textElement.style.lineHeight = value; } } }, members : { destruct : function() { this.__textElement = null; } } }); ok(core.Class.isClass(properties.Text)); equals(Object.keys(core.Class.getProperties(properties.Text)).join(","), "wrap,color,fontFamily,lineHeight"); core.Class("properties.Dimension", { properties : { width : { type : "Integer" }, height : { type : "Integer" } } }); ok(core.Class.isClass(properties.Dimension)); equals(Object.keys(core.Class.getProperties(properties.Dimension)).join(","), "width,height"); core.Class("properties.Label", { include : [properties.Text, properties.Dimension], construct : function() { this.__labelElement = document.createElement("label"); properties.Text.call(this, this.__labelElement); this.setLineHeight(2); }, members : { destruct : function() { properties.Text.prototype.destruct.call(this); this.__labelElement = null; } } }); ok(core.Class.isClass(properties.Label)); equals(Object.keys(core.Class.getProperties(properties.Label)).join(","), "wrap,color,fontFamily,lineHeight,width,height"); var ll = new properties.Label; equals(ll.getLineHeight(), 2); }); test("Overwrite properties", function() { core.Class("properties.Parent", { properties : { prop : { init: "Parent" } } }); core.Class("properties.Child1", { include : [properties.Parent], properties : { prop : { init: "Child1" } } }); core.Class("properties.Child2", { include : [properties.Parent] }); var child1 = new properties.Child1(); var child2 = new properties.Child2(); equals("Child1", child1.getProp()); equals("Parent", child2.getProp()); }); });
Fixed frame tests
test/source/class/tests.js
Fixed frame tests
<ide><path>est/source/class/tests.js <ide> { <ide> "anim" : <ide> { <del> "loading.png" : [16*16, 16, 16, 1], <del> "explode.png" : [32*30, 32*3, 30, 3], <del> "collapse.png" : [12*2, 12*20, 2, 20, 86] <add> "loading.png" : {"d":[16*16, 16, 0, [16, 1]], "p":0}, <add> "explode.png" : {"d":[32*30, 32*3, 0, [30, 3]], "p":0}, <add> "collapse.png" : {"d":[12*2, 12*20, 0, [2, 20, 86]], "p":0}, <ide> } <ide> } <ide> }, <ide> strictEqual(core.io.Asset.getImage("myapp/anim/loading.png").height, 16, "full image height"); <ide> strictEqual(core.io.Asset.getImage("myapp/anim/loading.png").src, "asset/myapp/anim/loading.png", "normal source handling II"); <ide> <del> <ide> }); <ide> <ide> <ide> { <ide> "myapp" : <ide> { <del> "sprite.png" : [960, 352, "asset/myapp/sprite.png"], <add> "sprite.png" : {"d":[960, 352], "p":0}, <ide> "anim" : <ide> { <del> "loading.png" : [16*16, 16, "myapp/sprite.png", 20, 0, 16, 1], <del> "explode.png" : [32*30, 32*3, "myapp/sprite.png", 40, 16, 30, 3], <del> "collapse.png" : [12*2, 12*20, "myapp/sprite.png", 60, 112, 2, 20, 86] <add> "loading.png" : {"d":[16*16, 16, [0, 20, 0], [16, 1]], "p":0}, <add> "explode.png" : {"d":[32*30, 32*3, [0, 40, 16], [30, 3]], "p":0}, <add> "collapse.png" : {"d":[12*2, 12*20, [0, 60, 112], [2, 20, 86]], "p":0} <ide> } <ide> } <ide> }, <del> "profiles" : [{name:"build", "root":"asset/"}] <add> "profiles" : [{name:"build", "root":"asset/"}], <add> "sprites" : ["myapp/sprite.png"] <ide> }); <ide> <ide> strictEqual(core.io.Asset.getFrameNumber("myapp/anim/loading.png"), 16, "number of frames I"); <ide> { <ide> "anim" : <ide> { <del> "guy.png" : [200, 16, [ <del> // Format: left, top, width, height, offsetLeft?, offsetTop?, rotation? <del> [ 0, 0, 20, 20], <del> [30, 50, 10, 30, 20, 50], <del> [70, 20, 14, 40, 0, 30, 90] <del> ]] <add> "guy.png" : {"d":[200, 16, 0, [ <add> [ <add> // Format: left, top, width, height, offsetLeft?, offsetTop?, rotation? <add> [ 0, 0, 20, 20], <add> [30, 50, 10, 30, 20, 50], <add> [70, 20, 14, 40, 0, 30, 90] <add> ] <add> ]], "p":0} <ide> } <ide> }, <ide> }, <ide> { <ide> "myapp" : <ide> { <del> "sprite.png" : [960, 352], <add> "sprite.png" : {"d":[960, 352], "p":0}, <ide> "anim" : <ide> { <del> "guy.png" : [200, 16, "myapp/sprite.png", 20, 40, [ <del> // Format: left, top, width, height, offsetLeft?, offsetTop?, rotation? <del> [ 0, 0, 20, 20], <del> [30, 50, 10, 30, 20, 50], <del> [70, 20, 14, 40, 0, 30, 90] <del> ]] <add> "guy.png" : {"d":[200, 16, [0, 20, 40], [ <add> [ <add> // Format: left, top, width, height, offsetLeft?, offsetTop?, rotation? <add> [ 0, 0, 20, 20], <add> [30, 50, 10, 30, 20, 50], <add> [70, 20, 14, 40, 0, 30, 90] <add> ] <add> ]], "p":0}, <ide> } <ide> }, <ide> }, <add> "sprites" : ["myapp/sprite.png"], <ide> "profiles" : [{name:"build", "root":"asset/"}] <ide> }); <ide>
Java
epl-1.0
c541776f7d154efd0049809b7c580b1635037d22
0
MikeJMajor/openhab2-addons-dlinksmarthome,paulianttila/openhab2,MikeJMajor/openhab2-addons-dlinksmarthome,paulianttila/openhab2,paulianttila/openhab2,MikeJMajor/openhab2-addons-dlinksmarthome
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.deconz.internal.discovery; import static org.openhab.binding.deconz.internal.BindingConstants.*; import java.net.URI; import java.net.URL; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.jupnp.model.meta.DeviceDetails; import org.jupnp.model.meta.ManufacturerDetails; import org.jupnp.model.meta.RemoteDevice; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.upnp.UpnpDiscoveryParticipant; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; import org.osgi.service.component.annotations.Component; /** * Discover deCONZ software instances. They announce themselves as HUE bridges, * and their REST API is compatible to HUE bridges. But they also provide a websocket * real-time channel for sensors. * * We check for the manufacturer string of "dresden elektronik". * * @author David Graeff - Initial contribution */ @NonNullByDefault @Component(service = UpnpDiscoveryParticipant.class) public class BridgeDiscoveryParticipant implements UpnpDiscoveryParticipant { @Override public Set<ThingTypeUID> getSupportedThingTypeUIDs() { return Collections.singleton(BRIDGE_TYPE); } @Override public @Nullable DiscoveryResult createResult(RemoteDevice device) { ThingUID uid = getThingUID(device); if (uid == null) { return null; } URL descriptorURL = device.getIdentity().getDescriptorURL(); String UDN = device.getIdentity().getUdn().getIdentifierString(); // Friendly name is like "name (host)" String name = device.getDetails().getFriendlyName(); // Cut out the pure name if (name.indexOf('(') - 1 > 0) { name = name.substring(0, name.indexOf('(') - 1); } // Add host+port String host = descriptorURL.getHost(); int port = descriptorURL.getPort(); name = name + " (" + host + ":" + port + ")"; Map<String, Object> properties = new TreeMap<>(); properties.put(CONFIG_HOST, host); properties.put(CONFIG_HTTP_PORT, port); properties.put(PROPERTY_UDN, UDN); return DiscoveryResultBuilder.create(uid).withProperties(properties).withLabel(name) .withRepresentationProperty(PROPERTY_UDN).build(); } @Override public @Nullable ThingUID getThingUID(RemoteDevice device) { DeviceDetails details = device.getDetails(); if (details != null) { ManufacturerDetails manufacturerDetails = details.getManufacturerDetails(); if (manufacturerDetails != null) { URI manufacturerUri = manufacturerDetails.getManufacturerURI(); if ((manufacturerUri != null && manufacturerUri.toString().contains("dresden")) || "dresden elektronik".equals(manufacturerDetails.getManufacturer())) { return new ThingUID(BRIDGE_TYPE, details.getSerialNumber()); } } } return null; } }
bundles/org.openhab.binding.deconz/src/main/java/org/openhab/binding/deconz/internal/discovery/BridgeDiscoveryParticipant.java
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.deconz.internal.discovery; import static org.openhab.binding.deconz.internal.BindingConstants.*; import java.net.URL; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.jupnp.model.meta.DeviceDetails; import org.jupnp.model.meta.RemoteDevice; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.upnp.UpnpDiscoveryParticipant; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; import org.osgi.service.component.annotations.Component; /** * Discover deCONZ software instances. They announce themselves as HUE bridges, * and their REST API is compatible to HUE bridges. But they also provide a websocket * real-time channel for sensors. * * We check for the manufacturer string of "dresden elektronik". * * @author David Graeff - Initial contribution */ @NonNullByDefault @Component(service = UpnpDiscoveryParticipant.class) public class BridgeDiscoveryParticipant implements UpnpDiscoveryParticipant { @Override public Set<ThingTypeUID> getSupportedThingTypeUIDs() { return Collections.singleton(BRIDGE_TYPE); } @Override public @Nullable DiscoveryResult createResult(RemoteDevice device) { ThingUID uid = getThingUID(device); if (uid == null) { return null; } URL descriptorURL = device.getIdentity().getDescriptorURL(); String UDN = device.getIdentity().getUdn().getIdentifierString(); // Friendly name is like "name (host)" String name = device.getDetails().getFriendlyName(); // Cut out the pure name if (name.indexOf('(') - 1 > 0) { name = name.substring(0, name.indexOf('(') - 1); } // Add host+port String host = descriptorURL.getHost(); int port = descriptorURL.getPort(); name = name + " (" + host + ":" + String.valueOf(port) + ")"; Map<String, Object> properties = new TreeMap<>(); properties.put(CONFIG_HOST, host); properties.put(CONFIG_HTTP_PORT, port); properties.put(PROPERTY_UDN, UDN); return DiscoveryResultBuilder.create(uid).withProperties(properties).withLabel(name) .withRepresentationProperty(PROPERTY_UDN).build(); } @Override public @Nullable ThingUID getThingUID(RemoteDevice device) { DeviceDetails details = device.getDetails(); if (details != null && details.getManufacturerDetails() != null && "dresden elektronik".equals(details.getManufacturerDetails().getManufacturer())) { return new ThingUID(BRIDGE_TYPE, details.getSerialNumber()); } return null; } }
[deconz] fix gateway discovery (#9362) Signed-off-by: Jan N. Klug <[email protected]>
bundles/org.openhab.binding.deconz/src/main/java/org/openhab/binding/deconz/internal/discovery/BridgeDiscoveryParticipant.java
[deconz] fix gateway discovery (#9362)
<ide><path>undles/org.openhab.binding.deconz/src/main/java/org/openhab/binding/deconz/internal/discovery/BridgeDiscoveryParticipant.java <ide> <ide> import static org.openhab.binding.deconz.internal.BindingConstants.*; <ide> <add>import java.net.URI; <ide> import java.net.URL; <ide> import java.util.Collections; <ide> import java.util.Map; <ide> import org.eclipse.jdt.annotation.NonNullByDefault; <ide> import org.eclipse.jdt.annotation.Nullable; <ide> import org.jupnp.model.meta.DeviceDetails; <add>import org.jupnp.model.meta.ManufacturerDetails; <ide> import org.jupnp.model.meta.RemoteDevice; <ide> import org.openhab.core.config.discovery.DiscoveryResult; <ide> import org.openhab.core.config.discovery.DiscoveryResultBuilder; <ide> // Add host+port <ide> String host = descriptorURL.getHost(); <ide> int port = descriptorURL.getPort(); <del> name = name + " (" + host + ":" + String.valueOf(port) + ")"; <add> name = name + " (" + host + ":" + port + ")"; <ide> <ide> Map<String, Object> properties = new TreeMap<>(); <ide> <ide> @Override <ide> public @Nullable ThingUID getThingUID(RemoteDevice device) { <ide> DeviceDetails details = device.getDetails(); <del> if (details != null && details.getManufacturerDetails() != null <del> && "dresden elektronik".equals(details.getManufacturerDetails().getManufacturer())) { <del> return new ThingUID(BRIDGE_TYPE, details.getSerialNumber()); <add> if (details != null) { <add> ManufacturerDetails manufacturerDetails = details.getManufacturerDetails(); <add> if (manufacturerDetails != null) { <add> URI manufacturerUri = manufacturerDetails.getManufacturerURI(); <add> if ((manufacturerUri != null && manufacturerUri.toString().contains("dresden")) <add> || "dresden elektronik".equals(manufacturerDetails.getManufacturer())) { <add> return new ThingUID(BRIDGE_TYPE, details.getSerialNumber()); <add> } <add> } <ide> } <ide> return null; <ide> }
Java
mit
error: pathspec 'app/src/test/java/ru/fixapp/fooproject/presentationlayer/resolution/LeftDrawerHelperEmptyTest.java' did not match any file(s) known to git
f4868831de8ab83aba1c550247588417ecd812c2
1
MrVilkaman/AndroidProjectTemplate
package ru.fixapp.fooproject.presentationlayer.resolution; import org.junit.Assert; import org.junit.Test; import ru.fixapp.fooproject.presentationlayer.fragments.core.BaseFragment; import ru.fixapp.fooproject.testsutils.BaseTestCase; public class LeftDrawerHelperEmptyTest extends BaseTestCase { // also for good test coverage @Test public void testAll(){ // Arrange LeftDrawerHelper drawerHelper = new LeftDrawerHelperEmpty(); // Act drawerHelper.open(); drawerHelper.close(); drawerHelper.isOpen(); drawerHelper.close(() -> {}); drawerHelper.getDrawerLayout(); drawerHelper.getDrawerContentFrame(); BaseFragment drawerFragment = drawerHelper.getDrawerFragment(); boolean hasDrawer = drawerHelper.hasDrawer(); // Assert Assert.assertFalse(hasDrawer); Assert.assertNull(drawerFragment); } }
app/src/test/java/ru/fixapp/fooproject/presentationlayer/resolution/LeftDrawerHelperEmptyTest.java
added tests for empty drawer helper
app/src/test/java/ru/fixapp/fooproject/presentationlayer/resolution/LeftDrawerHelperEmptyTest.java
added tests for empty drawer helper
<ide><path>pp/src/test/java/ru/fixapp/fooproject/presentationlayer/resolution/LeftDrawerHelperEmptyTest.java <add>package ru.fixapp.fooproject.presentationlayer.resolution; <add> <add>import org.junit.Assert; <add>import org.junit.Test; <add> <add>import ru.fixapp.fooproject.presentationlayer.fragments.core.BaseFragment; <add>import ru.fixapp.fooproject.testsutils.BaseTestCase; <add> <add> <add>public class LeftDrawerHelperEmptyTest extends BaseTestCase { <add> <add> <add> <add> // also for good test coverage <add> @Test <add> public void testAll(){ <add> // Arrange <add> LeftDrawerHelper drawerHelper = new LeftDrawerHelperEmpty(); <add> <add> // Act <add> drawerHelper.open(); <add> drawerHelper.close(); <add> drawerHelper.isOpen(); <add> drawerHelper.close(() -> {}); <add> drawerHelper.getDrawerLayout(); <add> drawerHelper.getDrawerContentFrame(); <add> BaseFragment drawerFragment = drawerHelper.getDrawerFragment(); <add> boolean hasDrawer = drawerHelper.hasDrawer(); <add> <add> // Assert <add> Assert.assertFalse(hasDrawer); <add> Assert.assertNull(drawerFragment); <add> } <add>}
JavaScript
bsd-3-clause
f29bdf2572655e3e7953407ad2b531f9e804f9aa
0
brython-dev/brython,brython-dev/brython,brython-dev/brython
// Script with function to load scripts and modules, including indexedDB cache (function($B){ var _b_ = $B.builtins if($B.VFS_timestamp && $B.VFS_timestamp > $B.timestamp){ // A VFS created by python -m brython --modules has its own // timestamp. If it is after the one in brython.js, use it $B.timestamp = $B.VFS_timestamp } function idb_load(evt, module){ // Callback function of a request to the indexedDB database with a module // name as key. // If the module is precompiled and its timestamp is the same as in // brython_stdlib, use the precompiled Javascript. // Otherwise, get the source code from brython_stdlib.js. var res = evt.target.result var timestamp = $B.timestamp if(res === undefined || res.timestamp != $B.timestamp || ($B.VFS[module] && res.source_ts !== $B.VFS[module].timestamp)){ // Not found or not with the same date as in brython_stdlib.js: // search in VFS if($B.VFS[module] !== undefined){ var elts = $B.VFS[module], ext = elts[0], source = elts[1] if(ext == ".py"){ var imports = elts[2], is_package = elts.length == 4, source_ts = elts.timestamp, __package__ // Temporarily set $B.imported[module] for relative imports if(is_package){__package__ = module} else{ var parts = module.split(".") parts.pop() __package__ = parts.join(".") } $B.imported[module] = $B.module.$factory(module, "", __package__) try{ var root = $B.py2js(source, module, module), js = root.to_js() }catch(err){ $B.handle_error(err) } // Delete temporary import delete $B.imported[module] if($B.debug > 1){console.log("precompile", module)} // Store Javascript translation in indexedDB var parts = module.split(".") if(parts.length > 1){parts.pop()} if($B.stdlib.hasOwnProperty(parts.join("."))){ var imports = elts[2] imports = imports.join(",") $B.tasks.splice(0, 0, [store_precompiled, module, js, source_ts, imports, is_package]) } }else{ console.log('bizarre', module, ext) } }else{ // Module not found : do nothing } }else{ // Precompiled Javascript found in indexedDB database. if(res.is_package){ $B.precompiled[module] = [res.content] }else{ $B.precompiled[module] = res.content } if(res.imports.length > 0){ // res.imports is a string with the modules imported by the current // modules, separated by commas if($B.debug > 1){ console.log(module, "imports", res.imports) } var subimports = res.imports.split(",") for(var i = 0; i < subimports.length; i++){ var subimport = subimports[i] if(subimport.startsWith(".")){ // Relative imports var url_elts = module.split("."), nb_dots = 0 while(subimport.startsWith(".")){ nb_dots++ subimport = subimport.substr(1) } var elts = url_elts.slice(0, nb_dots) if(subimport){ elts = elts.concat([subimport]) } subimport = elts.join(".") } if(!$B.imported.hasOwnProperty(subimport) && !$B.precompiled.hasOwnProperty(subimport)){ // If the code of the required module is not already // loaded, add a task for this. if($B.VFS.hasOwnProperty(subimport)){ var submodule = $B.VFS[subimport], ext = submodule[0], source = submodule[1] if(submodule[0] == ".py"){ $B.tasks.splice(0, 0, [idb_get, subimport]) }else{ add_jsmodule(subimport, source) } } } } } } loop() } function store_precompiled(module, js, source_ts, imports, is_package){ // Sends a request to store the compiled Javascript for a module. var db = $B.idb_cx.result, tx = db.transaction("modules", "readwrite"), store = tx.objectStore("modules"), cursor = store.openCursor(), data = {"name": module, "content": js, "imports": imports, "origin": origin, "timestamp": __BRYTHON__.timestamp, "source_ts": source_ts, "is_package": is_package }, request = store.put(data) if($B.debug > 1){ console.log("store precompiled", module, "package", is_package) } document.dispatchEvent(new CustomEvent('precompile', {detail: 'cache module ' + module})) var ix = $B.outdated.indexOf(module) if(ix > -1){ $B.outdated.splice(ix, 1) } request.onsuccess = function(evt){ // Restart the task "idb_get", knowing that this time it will use // the compiled version. $B.tasks.splice(0, 0, [idb_get, module]) loop() } } function idb_get(module){ // Sends a request to the indexedDB database for the module name. var db = $B.idb_cx.result, tx = db.transaction("modules", "readonly") try{ var store = tx.objectStore("modules") req = store.get(module) req.onsuccess = function(evt){idb_load(evt, module)} }catch(err){ console.info('error', err) } } $B.idb_open = function(obj){ $B.idb_name = "brython-cache" var idb_cx = $B.idb_cx = indexedDB.open($B.idb_name) idb_cx.onsuccess = function(){ var db = idb_cx.result if(!db.objectStoreNames.contains("modules")){ var version = db.version db.close() console.info('create object store', version) idb_cx = indexedDB.open($B.idb_name, version+1) idb_cx.onupgradeneeded = function(){ console.info("upgrade needed") var db = $B.idb_cx.result, store = db.createObjectStore("modules", {"keyPath": "name"}) store.onsuccess = loop } idb_cx.onversionchanged = function(){ console.log("version changed") } idb_cx.onsuccess = function(){ console.info("db opened", idb_cx) var db = idb_cx.result, store = db.createObjectStore("modules", {"keyPath": "name"}) store.onsuccess = loop } }else{ if($B.debug > 1){ console.info("using indexedDB for stdlib modules cache") } // Preload all compiled modules var tx = db.transaction("modules", "readwrite"), store = tx.objectStore("modules"), record, outdated = [] var openCursor = store.openCursor() openCursor.onerror = function(evt){ console.log("open cursor error", evt) } openCursor.onsuccess = function(evt){ cursor = evt.target.result if(cursor){ record = cursor.value // A record is valid if the Brython engine timestamp is // the same as record.timestamp, and the timestamp of the // VFS file where the file stands is the same as // record.source_ts if(record.timestamp == $B.timestamp){ if(!$B.VFS || !$B.VFS[record.name] || $B.VFS[record.name].timestamp == record.source_ts){ // Load in __BRYTHON__.precompiled if(record.is_package){ $B.precompiled[record.name] = [record.content] }else{ $B.precompiled[record.name] = record.content } if($B.debug > 1){ console.info("load from cache", record.name) } }else{ // If module with name record.name exists in a VFS // and its timestamp is not the VFS timestamp, // remove from cache outdated.push(record.name) } }else{ outdated.push(record.name) } cursor.continue() }else{ if($B.debug > 1){ console.log("done") } $B.outdated = outdated loop() } } } } idb_cx.onupgradeneeded = function(){ console.info("upgrade needed") var db = idb_cx.result, store = db.createObjectStore("modules", {"keyPath": "name"}) store.onsuccess = loop } idb_cx.onerror = function(){ console.info('could not open indexedDB database') // Proceed without indexedDB $B.idb_cx = null $B.idb_name = null $B.$options.indexedDB = false loop() } } $B.ajax_load_script = function(script){ var url = script.url, name = script.name if($B.files && $B.files.hasOwnProperty(name)){ $B.tasks.splice(0, 0, [$B.run_script, $B.files[name], name, true]) }else if($B.protocol != "file"){ var req = new XMLHttpRequest(), qs = $B.$options.cache ? '' : (url.search(/\?/) > -1 ? '&' : '?') + Date.now() req.open("GET", url + qs, true) req.onreadystatechange = function(){ if(this.readyState == 4){ if(this.status == 200){ var src = this.responseText if(script.is_ww){ $B.webworkers[name] = src }else{ $B.tasks.splice(0, 0, [$B.run_script, src, name, true]) } loop() }else if(this.status == 404){ throw Error(url + " not found") } } } req.send() }else{ throw _b_.IOError.$factory("can't load external script at " + script.url + " (Ajax calls not supported with protocol file:///)") } } function add_jsmodule(module, source){ // Use built-in Javascript module source += "\nvar $locals_" + module.replace(/\./g, "_") + " = $module" $B.precompiled[module] = source } var inImported = $B.inImported = function(module){ if($B.imported.hasOwnProperty(module)){ // already imported, do nothing }else if(__BRYTHON__.VFS && __BRYTHON__.VFS.hasOwnProperty(module)){ var elts = __BRYTHON__.VFS[module] if(elts === undefined){console.log('bizarre', module)} var ext = elts[0], source = elts[1], is_package = elts.length == 4 if(ext==".py"){ if($B.idb_cx && !$B.idb_cx.$closed){ $B.tasks.splice(0, 0, [idb_get, module]) } }else{ add_jsmodule(module, source) } }else{ console.log("bizarre", module) } loop() } var loop = $B.loop = function(){ if($B.tasks.length == 0){ // No more task to process. if($B.idb_cx && ! $B.idb_cx.$closed){ var db = $B.idb_cx.result, tx = db.transaction("modules", "readwrite"), store = tx.objectStore("modules") while($B.outdated.length > 0){ var module = $B.outdated.pop(), req = store.delete(module) req.onsuccess = function(event){ if($B.debug > 1){ console.info("delete outdated", module) } document.dispatchEvent(new CustomEvent('precompile', {detail: 'remove outdated ' + module + ' from cache'})) } } document.dispatchEvent(new CustomEvent('precompile', {detail: "close"})) $B.idb_cx.result.close() $B.idb_cx.$closed = true } // dispatch event "brython_done" document.dispatchEvent(new CustomEvent("brython_done", {detail: $B.obj_dict($B.$options)})) return } var task = $B.tasks.shift(), func = task[0], args = task.slice(1) if(func == "execute"){ try{ var script = task[1], script_id = script.__name__.replace(/\./g, "_"), module = $B.module.$factory(script.__name__) module.$src = script.$src module.__file__ = script.__file__ $B.imported[script_id] = module new Function("$locals_" + script_id, script.js)(module) }catch(err){ // If the error was not caught by the Python runtime, build an // instance of a Python exception if(err.__class__ === undefined){ console.log('Javascript error', err) if($B.is_recursion_error(err)){ err = _b_.RecursionError.$factory("too much recursion") }else{ $B.print_stack() err = _b_.RuntimeError.$factory(err + '') } } if($B.debug > 1){ console.log("handle error", err.__class__, err.args, err.$stack) console.log($B.frames_stack.slice()) } $B.handle_error(err) } loop() }else{ // Run function with arguments try{ func.apply(null, args) }catch(err){ $B.handle_error(err) } } } $B.tasks = [] $B.has_indexedDB = self.indexedDB !== undefined $B.handle_error = function(err){ // Print the error traceback on the standard error stream if($B.debug > 1){ console.log("handle error", err.__class__, err.args) } if(err.__class__ !== undefined){ var name = $B.class_name(err), trace = $B.$getattr(err, 'info') if(name == 'SyntaxError' || name == 'IndentationError'){ var offset = err.args[3] trace += '\n ' + ' '.repeat(offset) + '^' + '\n' + name + ': '+err.args[0] }else{ trace += '\n' + name if(err.args[0] && err.args[0] !== _b_.None){ trace += ': ' + _b_.str.$factory(err.args[0]) } } }else{ console.log(err) trace = err + "" } if($B.debug > 1){ try{ $B.$getattr($B.stderr, 'write')(trace) try{ $B.$getattr($B.stderr, 'flush')() }catch(err){ console.log(err) } }catch(print_exc_err){ console.log(trace) } }else{ console.debug(trace) } // Throw the error to stop execution throw err } function required_stdlib_imports(imports, start){ // Returns the list of modules from the standard library needed by // the modules in "imports" var nb_added = 0 start = start || 0 for(var i = start; i < imports.length; i++){ var module = imports[i] if($B.imported.hasOwnProperty(module)){continue} var mod_obj = $B.VFS[module] if(mod_obj === undefined){console.log("undef", module)} if(mod_obj[0] == ".py"){ var subimports = mod_obj[2] // list of modules needed by this mod subimports.forEach(function(subimport){ if(!$B.imported.hasOwnProperty(subimport) && imports.indexOf(subimport) == -1){ if($B.VFS.hasOwnProperty(subimport)){ imports.push(subimport) nb_added++ } } }) } } if(nb_added){ required_stdlib_imports(imports, imports.length - nb_added) } return imports } })(__BRYTHON__)
www/src/loaders.js
// Script with function to load scripts and modules, including indexedDB cache (function($B){ var _b_ = $B.builtins if($B.VFS_timestamp && $B.VFS_timestamp > $B.timestamp){ // A VFS created by python -m brython --modules has its own // timestamp. If it is after the one in brython.js, use it $B.timestamp = $B.VFS_timestamp } function idb_load(evt, module){ // Callback function of a request to the indexedDB database with a module // name as key. // If the module is precompiled and its timestamp is the same as in // brython_stdlib, use the precompiled Javascript. // Otherwise, get the source code from brython_stdlib.js. var res = evt.target.result var timestamp = $B.timestamp if(res === undefined || res.timestamp != $B.timestamp || ($B.VFS[module] && res.source_ts !== $B.VFS[module].timestamp)){ // Not found or not with the same date as in brython_stdlib.js: // search in VFS if($B.VFS[module] !== undefined){ var elts = $B.VFS[module], ext = elts[0], source = elts[1] if(ext == ".py"){ var imports = elts[2], is_package = elts.length == 4, source_ts = elts.timestamp, __package__ // Temporarily set $B.imported[module] for relative imports if(is_package){__package__ = module} else{ var parts = module.split(".") parts.pop() __package__ = parts.join(".") } $B.imported[module] = $B.module.$factory(module, "", __package__) try{ var root = $B.py2js(source, module, module), js = root.to_js() }catch(err){ $B.handle_error(err) } // Delete temporary import delete $B.imported[module] if($B.debug > 1){console.log("precompile", module)} // Store Javascript translation in indexedDB var parts = module.split(".") if(parts.length > 1){parts.pop()} if($B.stdlib.hasOwnProperty(parts.join("."))){ var imports = elts[2] imports = imports.join(",") $B.tasks.splice(0, 0, [store_precompiled, module, js, source_ts, imports, is_package]) } }else{ console.log('bizarre', module, ext) } }else{ // Module not found : do nothing } }else{ // Precompiled Javascript found in indexedDB database. if(res.is_package){ $B.precompiled[module] = [res.content] }else{ $B.precompiled[module] = res.content } if(res.imports.length > 0){ // res.imports is a string with the modules imported by the current // modules, separated by commas if($B.debug > 1){ console.log(module, "imports", res.imports) } var subimports = res.imports.split(",") for(var i = 0; i < subimports.length; i++){ var subimport = subimports[i] if(subimport.startsWith(".")){ // Relative imports var url_elts = module.split("."), nb_dots = 0 while(subimport.startsWith(".")){ nb_dots++ subimport = subimport.substr(1) } var elts = url_elts.slice(0, nb_dots) if(subimport){ elts = elts.concat([subimport]) } subimport = elts.join(".") } if(!$B.imported.hasOwnProperty(subimport) && !$B.precompiled.hasOwnProperty(subimport)){ // If the code of the required module is not already // loaded, add a task for this. if($B.VFS.hasOwnProperty(subimport)){ var submodule = $B.VFS[subimport], ext = submodule[0], source = submodule[1] if(submodule[0] == ".py"){ $B.tasks.splice(0, 0, [idb_get, subimport]) }else{ add_jsmodule(subimport, source) } } } } } } loop() } function store_precompiled(module, js, source_ts, imports, is_package){ // Sends a request to store the compiled Javascript for a module. var db = $B.idb_cx.result, tx = db.transaction("modules", "readwrite"), store = tx.objectStore("modules"), cursor = store.openCursor(), data = {"name": module, "content": js, "imports": imports, "origin": origin, "timestamp": __BRYTHON__.timestamp, "source_ts": source_ts, "is_package": is_package }, request = store.put(data) if($B.debug > 1){ console.log("store precompiled", module, "package", is_package) } document.dispatchEvent(new CustomEvent('precompile', {detail: 'cache module ' + module})) var ix = $B.outdated.indexOf(module) if(ix > -1){ $B.outdated.splice(ix, 1) } request.onsuccess = function(evt){ // Restart the task "idb_get", knowing that this time it will use // the compiled version. $B.tasks.splice(0, 0, [idb_get, module]) loop() } } function idb_get(module){ // Sends a request to the indexedDB database for the module name. var db = $B.idb_cx.result, tx = db.transaction("modules", "readonly") try{ var store = tx.objectStore("modules") req = store.get(module) req.onsuccess = function(evt){idb_load(evt, module)} }catch(err){ console.info('error', err) } } $B.idb_open = function(obj){ $B.idb_name = "brython-cache" var idb_cx = $B.idb_cx = indexedDB.open($B.idb_name) idb_cx.onsuccess = function(){ var db = idb_cx.result if(!db.objectStoreNames.contains("modules")){ var version = db.version db.close() console.info('create object store', version) idb_cx = indexedDB.open($B.idb_name, version+1) idb_cx.onupgradeneeded = function(){ console.info("upgrade needed") var db = $B.idb_cx.result, store = db.createObjectStore("modules", {"keyPath": "name"}) store.onsuccess = loop } idb_cx.onversionchanged = function(){ console.log("version changed") } idb_cx.onsuccess = function(){ console.info("db opened", idb_cx) var db = idb_cx.result, store = db.createObjectStore("modules", {"keyPath": "name"}) store.onsuccess = loop } }else{ if($B.debug > 1){ console.info("using indexedDB for stdlib modules cache") } // Preload all compiled modules var tx = db.transaction("modules", "readwrite"), store = tx.objectStore("modules"), record, outdated = [] var openCursor = store.openCursor() openCursor.onerror = function(evt){ console.log("open cursor error", evt) } openCursor.onsuccess = function(evt){ cursor = evt.target.result if(cursor){ record = cursor.value // A record is valid if the Brython engine timestamp is // the same as record.timestamp, and the timestamp of the // VFS file where the file stands is the same as // record.source_ts if(record.timestamp == $B.timestamp){ if(!$B.VFS || !$B.VFS[record.name] || $B.VFS[record.name].timestamp == record.source_ts){ // Load in __BRYTHON__.precompiled if(record.is_package){ $B.precompiled[record.name] = [record.content] }else{ $B.precompiled[record.name] = record.content } if($B.debug > 1){ console.info("load from cache", record.name) } }else{ // If module with name record.name exists in a VFS // and its timestamp is not the VFS timestamp, // remove from cache outdated.push(record.name) } }else{ outdated.push(record.name) } cursor.continue() }else{ if($B.debug > 1){ console.log("done") } $B.outdated = outdated loop() } } } } idb_cx.onupgradeneeded = function(){ console.info("upgrade needed") var db = idb_cx.result, store = db.createObjectStore("modules", {"keyPath": "name"}) store.onsuccess = loop } idb_cx.onerror = function(){ console.info('could not open indexedDB database') // Proceed without indexedDB $B.idb_cx = null $B.idb_name = null $B.$options.indexedDB = false loop() } } $B.ajax_load_script = function(script){ var url = script.url, name = script.name if($B.files && $B.files.hasOwnProperty(name)){ $B.tasks.splice(0, 0, [$B.run_script, $B.files[name], name, true]) }else if($B.protocol != "file"){ var req = new XMLHttpRequest(), qs = $B.$options.cache ? '' : (url.search(/\?/) > -1 ? '&' : '?') + Date.now() req.open("GET", url + qs, true) req.onreadystatechange = function(){ if(this.readyState == 4){ if(this.status == 200){ var src = this.responseText if(script.is_ww){ $B.webworkers[name] = src }else{ $B.tasks.splice(0, 0, [$B.run_script, src, name, true]) } loop() }else if(this.status == 404){ throw Error(url + " not found") } } } req.send() }else{ throw _b_.IOError.$factory("can't load external script at " + script.url + " (Ajax calls not supported with protocol file:///)") } } function add_jsmodule(module, source){ // Use built-in Javascript module source += "\nvar $locals_" + module.replace(/\./g, "_") + " = $module" $B.precompiled[module] = source } var inImported = $B.inImported = function(module){ if($B.imported.hasOwnProperty(module)){ // already imported, do nothing }else if(__BRYTHON__.VFS && __BRYTHON__.VFS.hasOwnProperty(module)){ var elts = __BRYTHON__.VFS[module] if(elts === undefined){console.log('bizarre', module)} var ext = elts[0], source = elts[1], is_package = elts.length == 4 if(ext==".py"){ if($B.idb_cx && !$B.idb_cx.$closed){ $B.tasks.splice(0, 0, [idb_get, module]) } }else{ add_jsmodule(module, source) } }else{ console.log("bizarre", module) } loop() } var loop = $B.loop = function(){ if($B.tasks.length == 0){ // No more task to process. if($B.idb_cx && ! $B.idb_cx.$closed){ var db = $B.idb_cx.result, tx = db.transaction("modules", "readwrite"), store = tx.objectStore("modules") while($B.outdated.length > 0){ var module = $B.outdated.pop(), req = store.delete(module) req.onsuccess = function(event){ if($B.debug > 1){ console.info("delete outdated", module) } document.dispatchEvent(new CustomEvent('precompile', {detail: 'remove outdated ' + module + ' from cache'})) } } document.dispatchEvent(new CustomEvent('precompile', {detail: "close"})) $B.idb_cx.result.close() $B.idb_cx.$closed = true } return } var task = $B.tasks.shift(), func = task[0], args = task.slice(1) if(func == "execute"){ try{ var script = task[1], script_id = script.__name__.replace(/\./g, "_"), module = $B.module.$factory(script.__name__) module.$src = script.$src module.__file__ = script.__file__ $B.imported[script_id] = module new Function("$locals_" + script_id, script.js)(module) }catch(err){ // If the error was not caught by the Python runtime, build an // instance of a Python exception if(err.__class__ === undefined){ console.log('Javascript error', err) if($B.is_recursion_error(err)){ err = _b_.RecursionError.$factory("too much recursion") }else{ $B.print_stack() err = _b_.RuntimeError.$factory(err + '') } } if($B.debug > 1){ console.log("handle error", err.__class__, err.args, err.$stack) console.log($B.frames_stack.slice()) } $B.handle_error(err) } loop() }else{ // Run function with arguments try{ func.apply(null, args) }catch(err){ $B.handle_error(err) } } } $B.tasks = [] $B.has_indexedDB = self.indexedDB !== undefined $B.handle_error = function(err){ // Print the error traceback on the standard error stream if($B.debug > 1){ console.log("handle error", err.__class__, err.args) } if(err.__class__ !== undefined){ var name = $B.class_name(err), trace = $B.$getattr(err, 'info') if(name == 'SyntaxError' || name == 'IndentationError'){ var offset = err.args[3] trace += '\n ' + ' '.repeat(offset) + '^' + '\n' + name + ': '+err.args[0] }else{ trace += '\n' + name if(err.args[0] && err.args[0] !== _b_.None){ trace += ': ' + _b_.str.$factory(err.args[0]) } } }else{ console.log(err) trace = err + "" } if($B.debug > 1){ try{ $B.$getattr($B.stderr, 'write')(trace) try{ $B.$getattr($B.stderr, 'flush')() }catch(err){ console.log(err) } }catch(print_exc_err){ console.log(trace) } }else{ console.debug(trace) } // Throw the error to stop execution throw err } function required_stdlib_imports(imports, start){ // Returns the list of modules from the standard library needed by // the modules in "imports" var nb_added = 0 start = start || 0 for(var i = start; i < imports.length; i++){ var module = imports[i] if($B.imported.hasOwnProperty(module)){continue} var mod_obj = $B.VFS[module] if(mod_obj === undefined){console.log("undef", module)} if(mod_obj[0] == ".py"){ var subimports = mod_obj[2] // list of modules needed by this mod subimports.forEach(function(subimport){ if(!$B.imported.hasOwnProperty(subimport) && imports.indexOf(subimport) == -1){ if($B.VFS.hasOwnProperty(subimport)){ imports.push(subimport) nb_added++ } } }) } } if(nb_added){ required_stdlib_imports(imports, imports.length - nb_added) } return imports } })(__BRYTHON__)
When all the tasks started by brython(options) are done, dispatch a custom event "brython_done" with attribute "detail" set to options (related to issue #1533)
www/src/loaders.js
When all the tasks started by brython(options) are done, dispatch a custom event "brython_done" with attribute "detail" set to options (related to issue #1533)
<ide><path>ww/src/loaders.js <ide> $B.idb_cx.result.close() <ide> $B.idb_cx.$closed = true <ide> } <add> // dispatch event "brython_done" <add> document.dispatchEvent(new CustomEvent("brython_done", <add> {detail: $B.obj_dict($B.$options)})) <ide> return <ide> } <ide> var task = $B.tasks.shift(),
Java
mit
50c6b6dc0cb298d6e3a5bcdc7135bebcffecfb00
0
phoenixnudt/OWL2VOWL,VisualDataWeb/OWL2VOWL
/* * Test.java * */ package de.uni_stuttgart.vis.vowl.owl2vowl.parser; import de.uni_stuttgart.vis.vowl.owl2vowl.export.JsonExporter; import de.uni_stuttgart.vis.vowl.owl2vowl.model.Constants; import de.uni_stuttgart.vis.vowl.owl2vowl.model.OntologyInfo; import de.uni_stuttgart.vis.vowl.owl2vowl.model.OntologyMetric; import de.uni_stuttgart.vis.vowl.owl2vowl.parser.container.MapData; import de.uni_stuttgart.vis.vowl.owl2vowl.pipes.FormatText; import org.apache.commons.io.FilenameUtils; import org.apache.logging.log4j.LogManager; import org.semanticweb.owlapi.apibinding.OWLManager; import org.semanticweb.owlapi.metrics.*; import org.semanticweb.owlapi.model.*; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Set; /** * @author Eduard Marbach */ public class Main { private static final boolean DEBUG_EXPORT = true; public static org.apache.logging.log4j.Logger logger = LogManager.getRootLogger(); public static OWLOntologyManager manager; private static MapData mapData; private static GeneralParser parser; private static OWLOntology ontology; private static OWLDataFactory factory; public static void main(String[] args) { Main mainO = new Main(); mainO.initializeAPI(); File quickExport = new File(Constants.BENCHMARK1); File nec = new File(Constants.BENCHMARK2); File prov = new File(Constants.PERSONAS); File test = new File(Constants.PATH_VARIABLE); File[] children = test.listFiles(); if(children == null){ throw new IllegalStateException("Directory doesn't contain files."); } for (File curr : children) { if(curr.isDirectory()) { continue; } try { //mainO.loadOntologies(curr); mainO.loadOntologies(new File(Constants.SIOC)); //mainO.loadOntologies(quickExport, Arrays.asList(nec)); //mainO.loadOntologies(Constants.EXT_ONTOVIBE); mainO.startConvertion(); mainO.reset(); break; } catch (OWLOntologyCreationException e) { //e.printStackTrace(); System.out.println("FAILED TO LOAD " + curr.getName()); logger.error("FAILED TO LOAD " + curr.getName()); } } } private static void parseOntoInfo() { OntologyInfo info = mapData.getOntologyInfo(); IRI ontoIri = ontology.getOntologyID().getOntologyIRI(); IRI versionIri = ontology.getOntologyID().getVersionIRI(); if (ontoIri != null) { info.setIri(ontoIri.toString()); } if (versionIri != null) { info.setVersion(versionIri.toString()); } /* Save available annotations */ for (OWLAnnotation i : ontology.getAnnotations()) { if (i.getProperty().toString().equals(Constants.INFO_CREATOR)) { info.setAuthor(FormatText.cutQuote(i.getValue().toString())); } if (i.getProperty().toString().equals(Constants.INFO_DESCRIPTION)) { info.setDescription(FormatText.cutQuote(i.getValue().toString())); } if (i.getProperty().toString().equals(Constants.INFO_ISSUED)) { info.setIssued(FormatText.cutQuote(i.getValue().toString())); } if (i.getProperty().toString().equals(Constants.INFO_LICENSE)) { info.setLicense(FormatText.cutQuote(i.getValue().toString())); } if (i.getProperty().toString().equals(Constants.INFO_RDFS_LABEL)) { info.setRdfsLabel(FormatText.cutQuote(i.getValue().toString())); } if (i.getProperty().toString().equals(Constants.INFO_SEE_ALSO)) { info.setSeeAlso(FormatText.cutQuote(i.getValue().toString())); } if (i.getProperty().toString().equals(Constants.INFO_TITLE)) { info.setTitle(FormatText.cutQuote(i.getValue().toString())); } if (i.getProperty().toString().equals(Constants.INFO_VERSION_INFO)) { info.setVersion(FormatText.cutQuote(i.getValue().toString())); } } } private static void parseDatatypeProperties(Set<OWLDataProperty> dataProperties) { parser.handleDatatypeProperty(dataProperties); } private static void parseObjectProperty(Set<OWLObjectProperty> objectProperties) { parser.handleObjectProperty(objectProperties); } private static void parseDatatypes(Set<OWLDatatype> datatypes) { parser.handleDatatype(datatypes); } private static void parseClasses(Set<OWLClass> classes) { parser.handleClass(classes); } /** * Save the metrics of the current loaded ontology. */ public static void parseMetrics() { OntologyMetric ontologyMetric = mapData.getOntologyMetric(); OWLMetric metric = new ReferencedClassCount(ontology.getOWLOntologyManager()); metric.setOntology(ontology); ontologyMetric.setClassCount(Integer.parseInt(metric.getValue().toString())); metric = new ReferencedObjectPropertyCount(ontology.getOWLOntologyManager()); metric.setOntology(ontology); ontologyMetric.setObjectPropertyCount(Integer.parseInt(metric.getValue().toString())); metric = new ReferencedDataPropertyCount(ontology.getOWLOntologyManager()); metric.setOntology(ontology); ontologyMetric.setDataPropertyCount(Integer.parseInt(metric.getValue().toString())); metric = new ReferencedIndividualCount(ontology.getOWLOntologyManager()); metric.setOntology(ontology); ontologyMetric.setIndividualCount(Integer.parseInt(metric.getValue().toString())); metric = new AxiomCount(ontology.getOWLOntologyManager()); metric.setOntology(ontology); ontologyMetric.setAxiomCount(Integer.parseInt(metric.getValue().toString())); // metric = new DLExpressivity(ontology.getOWLOntologyManager()); // metric.setOntology(ontology); ontologyMetric.calculateSums(); } private void reset() { manager.removeOntology(ontology); } public void initializeAPI() { logger.info("Initializing OWL API ..."); manager = OWLManager.createOWLOntologyManager(); factory = manager.getOWLDataFactory(); logger.info("OWL API initialized!"); } public void loadOntologies(File mainOnto, List<File> necessaryExternals) throws OWLOntologyCreationException { logger.info("Loading ontologies ... [" + mainOnto + ", " + necessaryExternals + "]"); for (File current : necessaryExternals) { manager.loadOntologyFromOntologyDocument(current); } logger.info("External ontologies loaded!"); ontology = manager.loadOntologyFromOntologyDocument(mainOnto); logger.info("Ontologies loaded! Main Ontolgy: " + ontology.getOntologyID().getOntologyIRI()); } public void loadOntologies(File mainOnto) throws OWLOntologyCreationException { logger.info("Loading ontology ... " + mainOnto); ontology = manager.loadOntologyFromOntologyDocument(mainOnto); logger.info("Ontology loaded! Main Ontolgy: " + ontology.getOntologyID().getOntologyIRI()); } public void loadOntologies(String linkToOntology) throws OWLOntologyCreationException { logger.info("Loading ontologies ... " + linkToOntology); ontology = manager.loadOntology(IRI.create(linkToOntology)); logger.info("Ontologies loaded! Main Ontolgy: " + ontology.getOntologyID().getOntologyIRI().getFragment()); } public void startConvertion() { mapData = new MapData(); Set<OWLClass> classes = ontology.getClassesInSignature(); Set<OWLDatatype> datatypes = ontology.getDatatypesInSignature(); Set<OWLObjectProperty> objectProperties = ontology.getObjectPropertiesInSignature(); Set<OWLDataProperty> dataProperties = ontology.getDataPropertiesInSignature(); ProcessUnit processor = new ProcessUnit(ontology, factory, mapData); parser = new GeneralParser(ontology, factory, mapData); /* Parsing of the raw data gained from the OWL API. Will be transformed to useable data for WebVOWL. */ parseOntoInfo(); parseClasses(classes); //parseDatatypes(datatypes); parseObjectProperty(objectProperties); parseDatatypeProperties(dataProperties); parseMetrics(); /* Further processing of the gained data. Eq. IRIs will be transformed to IDs where necessary */ processor.processClasses(); //processor.processDatatypes(); processor.processProperties(); if (DEBUG_EXPORT) { String filePath = System.getProperty("user.dir") + "\\WebVOWL\\src\\js\\data\\"; File exportFile = new File(filePath, FilenameUtils.removeExtension(ontology.getOntologyID().getOntologyIRI().getFragment()) + ".json"); JsonExporter exporter = new JsonExporter(exportFile); try { exporter.execute(mapData); } catch (IOException e) { e.printStackTrace(); } } } }
src/main/java/de/uni_stuttgart/vis/vowl/owl2vowl/parser/Main.java
/* * Test.java * */ package de.uni_stuttgart.vis.vowl.owl2vowl.parser; import de.uni_stuttgart.vis.vowl.owl2vowl.export.JsonExporter; import de.uni_stuttgart.vis.vowl.owl2vowl.model.Constants; import de.uni_stuttgart.vis.vowl.owl2vowl.model.OntologyInfo; import de.uni_stuttgart.vis.vowl.owl2vowl.model.OntologyMetric; import de.uni_stuttgart.vis.vowl.owl2vowl.parser.container.MapData; import de.uni_stuttgart.vis.vowl.owl2vowl.pipes.FormatText; import org.apache.commons.io.FilenameUtils; import org.apache.logging.log4j.LogManager; import org.semanticweb.owlapi.apibinding.OWLManager; import org.semanticweb.owlapi.metrics.*; import org.semanticweb.owlapi.model.*; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Set; /** * @author Eduard Marbach */ public class Main { private static final boolean DEBUG_EXPORT = true; public static org.apache.logging.log4j.Logger logger = LogManager.getRootLogger(); private static MapData mapData; private static GeneralParser parser; public static OWLOntologyManager manager; private static OWLOntology ontology; private static OWLDataFactory factory; public static void main(String[] args) { Main mainO = new Main(); mainO.initializeAPI(); File quickExport = new File(Constants.BENCHMARK1); File nec = new File(Constants.BENCHMARK2); File prov = new File(Constants.PERSONAS); File test = new File(Constants.PATH_VARIABLE); File[] children = test.listFiles(); if(children == null){ throw new IllegalStateException("Directory doesn't contain files."); } for (File curr : children) { if(curr.isDirectory()) { continue; } try { /* mainO.loadOntologies(curr); mainO.startConvertion(); mainO.reset(); */ //mainO.loadOntologies(new File(Constants.MUTO)); //mainO.loadOntologies(quickExport, Arrays.asList(nec)); mainO.loadOntologies(Constants.EXT_ONTOVIBE); mainO.startConvertion(); mainO.reset(); } catch (OWLOntologyCreationException e) { e.printStackTrace(); logger.error("FAILED TO LOAD ONTOLOGIES!"); } break; } } private void reset() { manager.removeOntology(ontology); } private static void parseOntoInfo() { OntologyInfo info = mapData.getOntologyInfo(); IRI ontoIri = ontology.getOntologyID().getOntologyIRI(); IRI versionIri = ontology.getOntologyID().getVersionIRI(); if (ontoIri != null) { info.setIri(ontoIri.toString()); } if (versionIri != null) { info.setVersion(versionIri.toString()); } /* Save available annotations */ for (OWLAnnotation i : ontology.getAnnotations()) { if (i.getProperty().toString().equals(Constants.INFO_CREATOR)) { info.setAuthor(FormatText.cutQuote(i.getValue().toString())); } if (i.getProperty().toString().equals(Constants.INFO_DESCRIPTION)) { info.setDescription(FormatText.cutQuote(i.getValue().toString())); } if (i.getProperty().toString().equals(Constants.INFO_ISSUED)) { info.setIssued(FormatText.cutQuote(i.getValue().toString())); } if (i.getProperty().toString().equals(Constants.INFO_LICENSE)) { info.setLicense(FormatText.cutQuote(i.getValue().toString())); } if (i.getProperty().toString().equals(Constants.INFO_RDFS_LABEL)) { info.setRdfsLabel(FormatText.cutQuote(i.getValue().toString())); } if (i.getProperty().toString().equals(Constants.INFO_SEE_ALSO)) { info.setSeeAlso(FormatText.cutQuote(i.getValue().toString())); } if (i.getProperty().toString().equals(Constants.INFO_TITLE)) { info.setTitle(FormatText.cutQuote(i.getValue().toString())); } if (i.getProperty().toString().equals(Constants.INFO_VERSION_INFO)) { info.setVersion(FormatText.cutQuote(i.getValue().toString())); } } } private static void parseDatatypeProperties(Set<OWLDataProperty> dataProperties) { parser.handleDatatypeProperty(dataProperties); } private static void parseObjectProperty(Set<OWLObjectProperty> objectProperties) { parser.handleObjectProperty(objectProperties); } private static void parseDatatypes(Set<OWLDatatype> datatypes) { parser.handleDatatype(datatypes); } private static void parseClasses(Set<OWLClass> classes) { parser.handleClass(classes); } /** * Save the metrics of the current loaded ontology. */ public static void parseMetrics() { OntologyMetric ontologyMetric = mapData.getOntologyMetric(); OWLMetric metric = new ReferencedClassCount(ontology.getOWLOntologyManager()); metric.setOntology(ontology); ontologyMetric.setClassCount(Integer.parseInt(metric.getValue().toString())); metric = new ReferencedObjectPropertyCount(ontology.getOWLOntologyManager()); metric.setOntology(ontology); ontologyMetric.setObjectPropertyCount(Integer.parseInt(metric.getValue().toString())); metric = new ReferencedDataPropertyCount(ontology.getOWLOntologyManager()); metric.setOntology(ontology); ontologyMetric.setDataPropertyCount(Integer.parseInt(metric.getValue().toString())); metric = new ReferencedIndividualCount(ontology.getOWLOntologyManager()); metric.setOntology(ontology); ontologyMetric.setIndividualCount(Integer.parseInt(metric.getValue().toString())); metric = new AxiomCount(ontology.getOWLOntologyManager()); metric.setOntology(ontology); ontologyMetric.setAxiomCount(Integer.parseInt(metric.getValue().toString())); // metric = new DLExpressivity(ontology.getOWLOntologyManager()); // metric.setOntology(ontology); ontologyMetric.calculateSums(); } public void initializeAPI() { logger.info("Initializing OWL API ..."); manager = OWLManager.createOWLOntologyManager(); factory = manager.getOWLDataFactory(); logger.info("OWL API initialized!"); } public void loadOntologies(File mainOnto, List<File> necessaryExternals) throws OWLOntologyCreationException { logger.info("Loading ontologies ... [" + mainOnto + ", " + necessaryExternals + "]"); for (File current : necessaryExternals) { manager.loadOntologyFromOntologyDocument(current); } logger.info("External ontologies loaded!"); ontology = manager.loadOntologyFromOntologyDocument(mainOnto); logger.info("Ontologies loaded! Main Ontolgy: " + ontology.getOntologyID().getOntologyIRI()); } public void loadOntologies(File mainOnto) throws OWLOntologyCreationException { logger.info("Loading ontology ... " + mainOnto); ontology = manager.loadOntologyFromOntologyDocument(mainOnto); logger.info("Ontology loaded! Main Ontolgy: " + ontology.getOntologyID().getOntologyIRI()); } public void loadOntologies(String linkToOntology) throws OWLOntologyCreationException { logger.info("Loading ontologies ... " + linkToOntology); ontology = manager.loadOntology(IRI.create(linkToOntology)); logger.info("Ontologies loaded! Main Ontolgy: " + ontology.getOntologyID().getOntologyIRI().getFragment()); } public void startConvertion() { mapData = new MapData(); Set<OWLClass> classes = ontology.getClassesInSignature(); Set<OWLDatatype> datatypes = ontology.getDatatypesInSignature(); Set<OWLObjectProperty> objectProperties = ontology.getObjectPropertiesInSignature(); Set<OWLDataProperty> dataProperties = ontology.getDataPropertiesInSignature(); ProcessUnit processor = new ProcessUnit(ontology, factory, mapData); parser = new GeneralParser(ontology, factory, mapData); /* Parsing of the raw data gained from the OWL API. Will be transformed to useable data for WebVOWL. */ parseOntoInfo(); parseClasses(classes); //parseDatatypes(datatypes); parseObjectProperty(objectProperties); parseDatatypeProperties(dataProperties); parseMetrics(); /* Further processing of the gained data. Eq. IRIs will be transformed to IDs where necessary */ processor.processClasses(); //processor.processDatatypes(); processor.processProperties(); if (DEBUG_EXPORT) { String filePath = System.getProperty("user.dir") + "\\WebVOWL\\src\\js\\data\\"; File exportFile = new File(filePath, FilenameUtils.removeExtension(ontology.getOntologyID().getOntologyIRI().getFragment()) + ".json"); JsonExporter exporter = new JsonExporter(exportFile); try { exporter.execute(mapData); } catch (IOException e) { e.printStackTrace(); } } } }
Small improvements.
src/main/java/de/uni_stuttgart/vis/vowl/owl2vowl/parser/Main.java
Small improvements.
<ide><path>rc/main/java/de/uni_stuttgart/vis/vowl/owl2vowl/parser/Main.java <ide> <ide> import java.io.File; <ide> import java.io.IOException; <del>import java.util.Arrays; <ide> import java.util.List; <ide> import java.util.Set; <ide> <ide> public class Main { <ide> private static final boolean DEBUG_EXPORT = true; <ide> public static org.apache.logging.log4j.Logger logger = LogManager.getRootLogger(); <add> public static OWLOntologyManager manager; <ide> private static MapData mapData; <ide> private static GeneralParser parser; <del> <del> public static OWLOntologyManager manager; <ide> private static OWLOntology ontology; <ide> private static OWLDataFactory factory; <ide> <ide> } <ide> <ide> try { <del> /* <del> mainO.loadOntologies(curr); <add> //mainO.loadOntologies(curr); <add> mainO.loadOntologies(new File(Constants.SIOC)); <add> //mainO.loadOntologies(quickExport, Arrays.asList(nec)); <add> //mainO.loadOntologies(Constants.EXT_ONTOVIBE); <ide> mainO.startConvertion(); <ide> mainO.reset(); <del> */ <del> //mainO.loadOntologies(new File(Constants.MUTO)); <del> //mainO.loadOntologies(quickExport, Arrays.asList(nec)); <del> mainO.loadOntologies(Constants.EXT_ONTOVIBE); <del> mainO.startConvertion(); <del> mainO.reset(); <del> <add> break; <ide> } catch (OWLOntologyCreationException e) { <del> e.printStackTrace(); <del> logger.error("FAILED TO LOAD ONTOLOGIES!"); <del> } <del> break; <del> } <del> } <del> <del> private void reset() { <del> manager.removeOntology(ontology); <add> //e.printStackTrace(); <add> System.out.println("FAILED TO LOAD " + curr.getName()); <add> logger.error("FAILED TO LOAD " + curr.getName()); <add> } <add> } <ide> } <ide> <ide> private static void parseOntoInfo() { <ide> // metric.setOntology(ontology); <ide> <ide> ontologyMetric.calculateSums(); <add> } <add> <add> private void reset() { <add> manager.removeOntology(ontology); <ide> } <ide> <ide> public void initializeAPI() {
Java
apache-2.0
9a6938b3dc0c1537c000591a2e683e4b8e9c1c07
0
stevespringett/Alpine,stevespringett/Alpine,stevespringett/Alpine,stevespringett/Alpine
/* * This file is part of Alpine. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright (c) Steve Springett. All Rights Reserved. */ package alpine.persistence; import alpine.resources.AlpineRequest; import alpine.resources.OrderDirection; import alpine.resources.Pagination; import alpine.validation.RegexSequence; import org.datanucleus.api.jdo.JDOQuery; import javax.jdo.FetchPlan; import javax.jdo.PersistenceManager; import javax.jdo.Query; import java.lang.reflect.Field; import java.security.Principal; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.UUID; /** * Base persistence manager that implements AutoCloseable so that the PersistenceManager will * be automatically closed when used in a try-with-resource block. * * @author Steve Springett * @since 1.0.0 */ public abstract class AbstractAlpineQueryManager implements AutoCloseable { protected final Principal principal; protected Pagination pagination; protected final String filter; protected final String orderBy; protected final OrderDirection orderDirection; protected final PersistenceManager pm = PersistenceManagerFactory.createPersistenceManager(); /** * Default constructor */ public AbstractAlpineQueryManager() { principal = null; pagination = new Pagination(Pagination.Strategy.NONE, 0, 0); filter = null; orderBy = null; orderDirection = OrderDirection.UNSPECIFIED; } /** * Constructs a new QueryManager with the following: * @param principal a Principal, or null * @param pagination a Pagination request, or null * @param filter a String filter, or null * @param orderBy the field to order by * @param orderDirection the sorting direction * @since 1.0.0 */ public AbstractAlpineQueryManager(final Principal principal, final Pagination pagination, final String filter, final String orderBy, final OrderDirection orderDirection) { this.principal = principal; this.pagination = pagination; this.filter = filter; this.orderBy = orderBy; this.orderDirection = orderDirection; } /** * Constructs a new QueryManager. Deconstructs the specified AlpineRequest * into its individual components including pagination and ordering. * @param request an AlpineRequest object * @since 1.0.0 */ public AbstractAlpineQueryManager(final AlpineRequest request) { this.principal = request.getPrincipal(); this.pagination = request.getPagination(); this.filter = request.getFilter(); this.orderBy = request.getOrderBy(); this.orderDirection = request.getOrderDirection(); } /** * Wrapper around {@link Query#execute()} that adds transparent support for * pagination and ordering of results via {@link #decorate(Query)}. * @param query the JDO Query object to execute * @return a PaginatedResult object * @since 1.0.0 */ public PaginatedResult execute(final Query query) { final long count = getCount(query); decorate(query); return new PaginatedResult() .objects(query.execute()) .total(count); } /** * Wrapper around {@link Query#execute(Object)} that adds transparent support for * pagination and ordering of results via {@link #decorate(Query)}. * @param query the JDO Query object to execute * @param p1 the value of the first parameter declared. * @return a PaginatedResult object * @since 1.0.0 */ public PaginatedResult execute(final Query query, final Object p1) { final long count = getCount(query, p1); decorate(query); return new PaginatedResult() .objects(query.execute(p1)) .total(count); } /** * Wrapper around {@link Query#execute(Object, Object)} that adds transparent support for * pagination and ordering of results via {@link #decorate(Query)}. * @param query the JDO Query object to execute * @param p1 the value of the first parameter declared. * @param p2 the value of the second parameter declared. * @return a PaginatedResult object * @since 1.0.0 */ public PaginatedResult execute(final Query query, final Object p1, final Object p2) { final long count = getCount(query, p1, p2); decorate(query); return new PaginatedResult() .objects(query.execute(p1, p2)) .total(count); } /** * Wrapper around {@link Query#execute(Object, Object, Object)} that adds transparent support for * pagination and ordering of results via {@link #decorate(Query)}. * @param query the JDO Query object to execute * @param p1 the value of the first parameter declared. * @param p2 the value of the second parameter declared. * @param p3 the value of the third parameter declared. * @return a PaginatedResult object * @since 1.0.0 */ public PaginatedResult execute(final Query query, final Object p1, final Object p2, final Object p3) { final long count = getCount(query, p1, p2, p3); decorate(query); return new PaginatedResult() .objects(query.execute(p1, p2, p3)) .total(count); } /** * Wrapper around {@link Query#executeWithArray(Object...)} that adds transparent support for * pagination and ordering of results via {@link #decorate(Query)}. * @param query the JDO Query object to execute * @param parameters the <code>Object</code> array with all of the parameters * @return a PaginatedResult object * @since 1.0.0 */ public PaginatedResult execute(final Query query, final Object... parameters) { final long count = getCount(query, parameters); decorate(query); return new PaginatedResult() .objects(query.executeWithArray(parameters)) .total(count); } /** * Wrapper around {@link Query#executeWithMap(Map)} that adds transparent support for * pagination and ordering of results via {@link #decorate(Query)}. * @param query the JDO Query object to execute * @param parameters the <code>Map</code> containing all of the parameters. * @return a PaginatedResult object * @since 1.0.0 */ public PaginatedResult execute(final Query query, final Map parameters) { final long count = getCount(query, parameters); decorate(query); return new PaginatedResult() .objects(query.executeWithMap(parameters)) .total(count); } /** * Advances the pagination based on the previous pagination settings. This is purely a * convenience method as the method by itself is not aware of the query being executed, * the result count, etc. * @since 1.0.0 */ public void advancePagination() { if (pagination.isPaginated()) { pagination = new Pagination(pagination.getStrategy(), pagination.getOffset() + pagination.getLimit(), pagination.getLimit()); } } /** * Given a query, this method will decorate that query with pagination, ordering, * and sorting direction. Specific checks are performed to ensure the execution * of the query is capable of being paged and that ordering can be securely performed. * @param query the JDO Query object to execute * @return a Collection of objects * @since 1.0.0 */ public Query decorate(final Query query) { // Clear the result to fetch if previously specified (i.e. by getting count) query.setResult(null); if (pagination != null && pagination.isPaginated()) { final long begin = pagination.getOffset(); final long end = begin + pagination.getLimit(); query.setRange(begin, end); } if (orderBy != null && RegexSequence.Pattern.ALPHA_NUMERIC.matcher(orderBy).matches() && orderDirection != OrderDirection.UNSPECIFIED) { // Check to see if the specified orderBy field is defined in the class being queried. boolean found = false; final org.datanucleus.store.query.Query iq = ((JDOQuery) query).getInternalQuery(); for (Field field: iq.getCandidateClass().getDeclaredFields()) { if (orderBy.equals(field.getName())) { found = true; break; } } if (found) { query.setOrdering(orderBy + " " + orderDirection.name().toLowerCase()); } } return query; } /** * Returns the number of items that would have resulted from returning all object. * This method is performant in that the objects are not actually retrieved, only * the count. * @param query the query to return a count from * @return the number of items * @since 1.0.0 */ public long getCount(final Query query) { //query.addExtension("datanucleus.query.resultSizeMethod", "count"); final String ordering = ((org.datanucleus.api.jdo.JDOQuery) query).getInternalQuery().getOrdering(); query.setResult("count(id)"); query.setOrdering(null); final long count = (Long) query.execute(); query.setOrdering(ordering); return count; } /** * Returns the number of items that would have resulted from returning all object. * This method is performant in that the objects are not actually retrieved, only * the count. * @param query the query to return a count from * @param p1 the value of the first parameter declared. * @return the number of items * @since 1.0.0 */ public long getCount(final Query query, final Object p1) { final String ordering = ((org.datanucleus.api.jdo.JDOQuery) query).getInternalQuery().getOrdering(); query.setResult("count(id)"); query.setOrdering(null); final long count = (Long) query.execute(p1); query.setOrdering(ordering); return count; } /** * Returns the number of items that would have resulted from returning all object. * This method is performant in that the objects are not actually retrieved, only * the count. * @param query the query to return a count from * @param p1 the value of the first parameter declared. * @param p2 the value of the second parameter declared. * @return the number of items * @since 1.0.0 */ public long getCount(final Query query, final Object p1, final Object p2) { final String ordering = ((org.datanucleus.api.jdo.JDOQuery) query).getInternalQuery().getOrdering(); query.setResult("count(id)"); query.setOrdering(null); final long count = (Long) query.execute(p1, p2); query.setOrdering(ordering); return count; } /** * Returns the number of items that would have resulted from returning all object. * This method is performant in that the objects are not actually retrieved, only * the count. * @param query the query to return a count from * @param p1 the value of the first parameter declared. * @param p2 the value of the second parameter declared. * @param p3 the value of the third parameter declared. * @return the number of items * @since 1.0.0 */ public long getCount(final Query query, final Object p1, final Object p2, final Object p3) { final String ordering = ((org.datanucleus.api.jdo.JDOQuery) query).getInternalQuery().getOrdering(); query.setResult("count(id)"); query.setOrdering(null); final long count = (Long) query.execute(p1, p2, p3); query.setOrdering(ordering); return count; } /** * Returns the number of items that would have resulted from returning all object. * This method is performant in that the objects are not actually retrieved, only * the count. * @param query the query to return a count from * @param parameters the <code>Object</code> array with all of the parameters * @return the number of items * @since 1.0.0 */ public long getCount(final Query query, final Object... parameters) { final String ordering = ((org.datanucleus.api.jdo.JDOQuery) query).getInternalQuery().getOrdering(); query.setResult("count(id)"); query.setOrdering(null); final long count = (Long) query.executeWithArray(parameters); query.setOrdering(ordering); return count; } /** * Returns the number of items that would have resulted from returning all object. * This method is performant in that the objects are not actually retrieved, only * the count. * @param query the query to return a count from * @param parameters the <code>Map</code> containing all of the parameters. * @return the number of items * @since 1.0.0 */ public long getCount(final Query query, final Map parameters) { final String ordering = ((org.datanucleus.api.jdo.JDOQuery) query).getInternalQuery().getOrdering(); query.setResult("count(id)"); query.setOrdering(null); final long count = (Long) query.executeWithMap(parameters); query.setOrdering(ordering); return count; } /** * Returns the number of items that would have resulted from returning all object. * This method is performant in that the objects are not actually retrieved, only * the count. * @param cls the persistence-capable class to query * @return the number of items * @param <T> candidate type for the query * @since 1.0.0 */ public <T> long getCount(final Class<T> cls) { final Query query = pm.newQuery(cls); //query.addExtension("datanucleus.query.resultSizeMethod", "count"); query.setResult("count(id)"); return (Long) query.execute(); } /** * Persists the specified PersistenceCapable object. * @param object a PersistenceCapable object * @param <T> the type to return * @return the persisted object */ @SuppressWarnings("unchecked") public <T> T persist(T object) { pm.currentTransaction().begin(); pm.makePersistent(object); pm.currentTransaction().commit(); pm.getFetchPlan().setDetachmentOptions(FetchPlan.DETACH_LOAD_FIELDS); pm.refresh(object); return object; } /** * Persists the specified PersistenceCapable objects. * @param pcs an array of PersistenceCapable objects * @param <T> the type to return * @return the persisted objects */ @SuppressWarnings("unchecked") public <T> T[] persist(T... pcs) { pm.currentTransaction().begin(); pm.makePersistentAll(pcs); pm.currentTransaction().commit(); pm.getFetchPlan().setDetachmentOptions(FetchPlan.DETACH_LOAD_FIELDS); pm.refreshAll(pcs); return pcs; } /** * Persists the specified PersistenceCapable objects. * @param pcs a collection of PersistenceCapable objects * @param <T> the type to return * @return the persisted objects */ @SuppressWarnings("unchecked") public <T> Collection<T> persist(Collection pcs) { pm.currentTransaction().begin(); pm.makePersistentAll(pcs); pm.currentTransaction().commit(); pm.getFetchPlan().setDetachmentOptions(FetchPlan.DETACH_LOAD_FIELDS); pm.refreshAll(pcs); return pcs; } /** * Deletes one or more PersistenceCapable objects. * @param objects an array of one or more objects to delete * @since 1.0.0 */ public void delete(Object... objects) { pm.currentTransaction().begin(); pm.deletePersistentAll(objects); pm.currentTransaction().commit(); } /** * Deletes one or more PersistenceCapable objects. * @param collection a collection of one or more objects to delete * @since 1.0.0 */ public void delete(Collection collection) { pm.currentTransaction().begin(); pm.deletePersistentAll(collection); pm.currentTransaction().commit(); } /** * Retrieves an object by its ID. * @param <T> A type parameter. This type will be returned * @param clazz the persistence class to retrive the ID for * @param id the object id to retrieve * @return an object of the specified type * @since 1.0.0 */ public <T> T getObjectById(Class<T> clazz, Object id) { return pm.getObjectById(clazz, id); } /** * Retrieves an object by its UUID. * @param <T> A type parameter. This type will be returned * @param clazz the persistence class to retrive the ID for * @param uuid the uuid of the object to retrieve * @return an object of the specified type * @since 1.0.0 */ @SuppressWarnings("unchecked") public <T> T getObjectByUuid(Class<T> clazz, UUID uuid) { final Query query = pm.newQuery(clazz, "uuid == :uuid"); final List<T> result = (List<T>) query.execute(uuid); return result.size() == 0 ? null : result.get(0); } /** * Retrieves an object by its UUID. * @param <T> A type parameter. This type will be returned * @param clazz the persistence class to retrive the ID for * @param uuid the uuid of the object to retrieve * @return an object of the specified type * @since 1.0.0 */ @SuppressWarnings("unchecked") public <T> T getObjectByUuid(Class<T> clazz, String uuid) { return getObjectByUuid(clazz, UUID.fromString(uuid)); } /** * Retrieves an object by its UUID. * @param <T> A type parameter. This type will be returned * @param clazz the persistence class to retrive the ID for * @param uuid the uuid of the object to retrieve * @param fetchGroup the JDO fetchgroup to use when making the query * @return an object of the specified type * @since 1.0.0 */ @SuppressWarnings("unchecked") public <T> T getObjectByUuid(Class<T> clazz, UUID uuid, String fetchGroup) { pm.getFetchPlan().addGroup(fetchGroup); return getObjectByUuid(clazz, uuid); } /** * Retrieves an object by its UUID. * @param <T> A type parameter. This type will be returned * @param clazz the persistence class to retrive the ID for * @param uuid the uuid of the object to retrieve * @param fetchGroup the JDO fetchgroup to use when making the query * @return an object of the specified type * @since 1.0.0 */ @SuppressWarnings("unchecked") public <T> T getObjectByUuid(Class<T> clazz, String uuid, String fetchGroup) { return getObjectByUuid(clazz, UUID.fromString(uuid), fetchGroup); } /** * Closes the PersistenceManager instance. * @since 1.0.0 */ public void close() { pm.close(); } /** * Upon finalization, closes the PersistenceManager, if not already closed. * @throws Throwable the {@code Exception} raised by this method * @since 1.0.0 */ protected void finalize() throws Throwable { close(); super.finalize(); } }
alpine/src/main/java/alpine/persistence/AbstractAlpineQueryManager.java
/* * This file is part of Alpine. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright (c) Steve Springett. All Rights Reserved. */ package alpine.persistence; import alpine.resources.AlpineRequest; import alpine.resources.OrderDirection; import alpine.resources.Pagination; import alpine.validation.RegexSequence; import org.datanucleus.api.jdo.JDOQuery; import javax.jdo.FetchPlan; import javax.jdo.PersistenceManager; import javax.jdo.Query; import java.lang.reflect.Field; import java.security.Principal; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.UUID; /** * Base persistence manager that implements AutoCloseable so that the PersistenceManager will * be automatically closed when used in a try-with-resource block. * * @author Steve Springett * @since 1.0.0 */ public abstract class AbstractAlpineQueryManager implements AutoCloseable { protected final Principal principal; protected Pagination pagination; protected final String filter; protected final String orderBy; protected final OrderDirection orderDirection; protected final PersistenceManager pm = PersistenceManagerFactory.createPersistenceManager(); /** * Default constructor */ public AbstractAlpineQueryManager() { principal = null; pagination = new Pagination(Pagination.Strategy.NONE, 0, 0); filter = null; orderBy = null; orderDirection = OrderDirection.UNSPECIFIED; } /** * Constructs a new QueryManager with the following: * @param principal a Principal, or null * @param pagination a Pagination request, or null * @param filter a String filter, or null * @param orderBy the field to order by * @param orderDirection the sorting direction * @since 1.0.0 */ public AbstractAlpineQueryManager(final Principal principal, final Pagination pagination, final String filter, final String orderBy, final OrderDirection orderDirection) { this.principal = principal; this.pagination = pagination; this.filter = filter; this.orderBy = orderBy; this.orderDirection = orderDirection; } /** * Constructs a new QueryManager. Deconstructs the specified AlpineRequest * into its individual components including pagination and ordering. * @param request an AlpineRequest object * @since 1.0.0 */ public AbstractAlpineQueryManager(final AlpineRequest request) { this.principal = request.getPrincipal(); this.pagination = request.getPagination(); this.filter = request.getFilter(); this.orderBy = request.getOrderBy(); this.orderDirection = request.getOrderDirection(); } /** * Wrapper around {@link Query#execute()} that adds transparent support for * pagination and ordering of results via {@link #decorate(Query)}. * @param query the JDO Query object to execute * @return a PaginatedResult object * @since 1.0.0 */ public PaginatedResult execute(final Query query) { final long count = getCount(query); decorate(query); return new PaginatedResult() .objects(query.execute()) .total(count); } /** * Wrapper around {@link Query#execute(Object)} that adds transparent support for * pagination and ordering of results via {@link #decorate(Query)}. * @param query the JDO Query object to execute * @param p1 the value of the first parameter declared. * @return a PaginatedResult object * @since 1.0.0 */ public PaginatedResult execute(final Query query, final Object p1) { final long count = getCount(query, p1); decorate(query); return new PaginatedResult() .objects(query.execute(p1)) .total(count); } /** * Wrapper around {@link Query#execute(Object, Object)} that adds transparent support for * pagination and ordering of results via {@link #decorate(Query)}. * @param query the JDO Query object to execute * @param p1 the value of the first parameter declared. * @param p2 the value of the second parameter declared. * @return a PaginatedResult object * @since 1.0.0 */ public PaginatedResult execute(final Query query, final Object p1, final Object p2) { final long count = getCount(query, p1, p2); decorate(query); return new PaginatedResult() .objects(query.execute(p1, p2)) .total(count); } /** * Wrapper around {@link Query#execute(Object, Object, Object)} that adds transparent support for * pagination and ordering of results via {@link #decorate(Query)}. * @param query the JDO Query object to execute * @param p1 the value of the first parameter declared. * @param p2 the value of the second parameter declared. * @param p3 the value of the third parameter declared. * @return a PaginatedResult object * @since 1.0.0 */ public PaginatedResult execute(final Query query, final Object p1, final Object p2, final Object p3) { final long count = getCount(query, p1, p2, p3); decorate(query); return new PaginatedResult() .objects(query.execute(p1, p2, p3)) .total(count); } /** * Wrapper around {@link Query#executeWithArray(Object...)} that adds transparent support for * pagination and ordering of results via {@link #decorate(Query)}. * @param query the JDO Query object to execute * @param parameters the <code>Object</code> array with all of the parameters * @return a PaginatedResult object * @since 1.0.0 */ public PaginatedResult execute(final Query query, final Object... parameters) { final long count = getCount(query, parameters); decorate(query); return new PaginatedResult() .objects(query.executeWithArray(parameters)) .total(count); } /** * Wrapper around {@link Query#executeWithMap(Map)} that adds transparent support for * pagination and ordering of results via {@link #decorate(Query)}. * @param query the JDO Query object to execute * @param parameters the <code>Map</code> containing all of the parameters. * @return a PaginatedResult object * @since 1.0.0 */ public PaginatedResult execute(final Query query, final Map parameters) { final long count = getCount(query, parameters); decorate(query); return new PaginatedResult() .objects(query.executeWithMap(parameters)) .total(count); } /** * Advances the pagination based on the previous pagination settings. This is purely a * convenience method as the method by itself is not aware of the query being executed, * the result count, etc. * @since 1.0.0 */ public void advancePagination() { if (pagination.isPaginated()) { pagination = new Pagination(pagination.getStrategy(), pagination.getOffset() + pagination.getLimit(), pagination.getLimit()); } } /** * Given a query, this method will decorate that query with pagination, ordering, * and sorting direction. Specific checks are performed to ensure the execution * of the query is capable of being paged and that ordering can be securely performed. * @param query the JDO Query object to execute * @return a Collection of objects * @since 1.0.0 */ public Query decorate(final Query query) { // Clear the result to fetch if previously specified (i.e. by getting count) query.setResult(null); if (pagination != null && pagination.isPaginated()) { final long begin = pagination.getOffset(); final long end = begin + pagination.getLimit(); query.setRange(begin, end); } if (orderBy != null && RegexSequence.Pattern.ALPHA_NUMERIC.matcher(orderBy).matches() && orderDirection != OrderDirection.UNSPECIFIED) { // Check to see if the specified orderBy field is defined in the class being queried. boolean found = false; final org.datanucleus.store.query.Query iq = ((JDOQuery) query).getInternalQuery(); for (Field field: iq.getCandidateClass().getDeclaredFields()) { if (orderBy.equals(field.getName())) { found = true; break; } } if (found) { query.setOrdering(orderBy + " " + orderDirection.name().toLowerCase()); } } return query; } /** * Returns the number of items that would have resulted from returning all object. * This method is performant in that the objects are not actually retrieved, only * the count. * @param query the query to return a count from * @return the number of items * @since 1.0.0 */ public long getCount(final Query query) { //query.addExtension("datanucleus.query.resultSizeMethod", "count"); final String ordering = ((org.datanucleus.api.jdo.JDOQuery) query).getInternalQuery().getOrdering(); query.setResult("count(id)"); query.setOrdering(null); final long count = (Long) query.execute(); query.setOrdering(ordering); return count; } /** * Returns the number of items that would have resulted from returning all object. * This method is performant in that the objects are not actually retrieved, only * the count. * @param query the query to return a count from * @param p1 the value of the first parameter declared. * @return the number of items * @since 1.0.0 */ public long getCount(final Query query, final Object p1) { final String ordering = ((org.datanucleus.api.jdo.JDOQuery) query).getInternalQuery().getOrdering(); query.setResult("count(id)"); query.setOrdering(null); final long count = (Long) query.execute(p1); query.setOrdering(ordering); return count; } /** * Returns the number of items that would have resulted from returning all object. * This method is performant in that the objects are not actually retrieved, only * the count. * @param query the query to return a count from * @param p1 the value of the first parameter declared. * @param p2 the value of the second parameter declared. * @return the number of items * @since 1.0.0 */ public long getCount(final Query query, final Object p1, final Object p2) { final String ordering = ((org.datanucleus.api.jdo.JDOQuery) query).getInternalQuery().getOrdering(); query.setResult("count(id)"); query.setOrdering(null); final long count = (Long) query.execute(p1, p2); query.setOrdering(ordering); return count; } /** * Returns the number of items that would have resulted from returning all object. * This method is performant in that the objects are not actually retrieved, only * the count. * @param query the query to return a count from * @param p1 the value of the first parameter declared. * @param p2 the value of the second parameter declared. * @param p3 the value of the third parameter declared. * @return the number of items * @since 1.0.0 */ public long getCount(final Query query, final Object p1, final Object p2, final Object p3) { final String ordering = ((org.datanucleus.api.jdo.JDOQuery) query).getInternalQuery().getOrdering(); query.setResult("count(id)"); query.setOrdering(null); final long count = (Long) query.execute(p1, p2, p3); query.setOrdering(ordering); return count; } /** * Returns the number of items that would have resulted from returning all object. * This method is performant in that the objects are not actually retrieved, only * the count. * @param query the query to return a count from * @param parameters the <code>Object</code> array with all of the parameters * @return the number of items * @since 1.0.0 */ public long getCount(final Query query, final Object... parameters) { final String ordering = ((org.datanucleus.api.jdo.JDOQuery) query).getInternalQuery().getOrdering(); query.setResult("count(id)"); query.setOrdering(null); final long count = (Long) query.executeWithArray(parameters); query.setOrdering(ordering); return count; } /** * Returns the number of items that would have resulted from returning all object. * This method is performant in that the objects are not actually retrieved, only * the count. * @param query the query to return a count from * @param parameters the <code>Map</code> containing all of the parameters. * @return the number of items * @since 1.0.0 */ public long getCount(final Query query, final Map parameters) { final String ordering = ((org.datanucleus.api.jdo.JDOQuery) query).getInternalQuery().getOrdering(); query.setResult("count(id)"); query.setOrdering(null); final long count = (Long) query.executeWithMap(parameters); query.setOrdering(ordering); return count; } /** * Returns the number of items that would have resulted from returning all object. * This method is performant in that the objects are not actually retrieved, only * the count. * @param cls the persistence-capable class to query * @return the number of items * @param <T> candidate type for the query * @since 1.0.0 */ public <T> long getCount(final Class<T> cls) { final Query query = pm.newQuery(cls); //query.addExtension("datanucleus.query.resultSizeMethod", "count"); query.setResult("count(id)"); return (Long) query.execute(); } /** * Persists the specified PersistenceCapable object. * @param object a PersistenceCapable object * @param <T> the type to return * @return the persisted object */ @SuppressWarnings("unchecked") public <T> T persist(T object) { pm.currentTransaction().begin(); pm.makePersistent(object); pm.currentTransaction().commit(); pm.getFetchPlan().setDetachmentOptions(FetchPlan.DETACH_LOAD_FIELDS); pm.refresh(object); return pm.detachCopy(object); } /** * Persists the specified PersistenceCapable objects. * @param pcs an array of PersistenceCapable objects * @param <T> the type to return * @return the persisted objects */ @SuppressWarnings("unchecked") public <T> T[] persist(T... pcs) { pm.currentTransaction().begin(); pm.makePersistentAll(pcs); pm.currentTransaction().commit(); pm.getFetchPlan().setDetachmentOptions(FetchPlan.DETACH_LOAD_FIELDS); pm.refreshAll(pcs); return pm.detachCopy(pcs); } /** * Persists the specified PersistenceCapable objects. * @param pcs a collection of PersistenceCapable objects * @param <T> the type to return * @return the persisted objects */ @SuppressWarnings("unchecked") public <T> Collection<T> persist(Collection pcs) { pm.currentTransaction().begin(); pm.makePersistentAll(pcs); pm.currentTransaction().commit(); pm.getFetchPlan().setDetachmentOptions(FetchPlan.DETACH_LOAD_FIELDS); pm.refreshAll(pcs); return pm.detachCopy(pcs); } /** * Deletes one or more PersistenceCapable objects. * @param objects an array of one or more objects to delete * @since 1.0.0 */ public void delete(Object... objects) { pm.currentTransaction().begin(); pm.deletePersistentAll(objects); pm.currentTransaction().commit(); } /** * Deletes one or more PersistenceCapable objects. * @param collection a collection of one or more objects to delete * @since 1.0.0 */ public void delete(Collection collection) { pm.currentTransaction().begin(); pm.deletePersistentAll(collection); pm.currentTransaction().commit(); } /** * Retrieves an object by its ID. * @param <T> A type parameter. This type will be returned * @param clazz the persistence class to retrive the ID for * @param id the object id to retrieve * @return an object of the specified type * @since 1.0.0 */ public <T> T getObjectById(Class<T> clazz, Object id) { return pm.getObjectById(clazz, id); } /** * Retrieves an object by its UUID. * @param <T> A type parameter. This type will be returned * @param clazz the persistence class to retrive the ID for * @param uuid the uuid of the object to retrieve * @return an object of the specified type * @since 1.0.0 */ @SuppressWarnings("unchecked") public <T> T getObjectByUuid(Class<T> clazz, UUID uuid) { final Query query = pm.newQuery(clazz, "uuid == :uuid"); final List<T> result = (List<T>) query.execute(uuid); return result.size() == 0 ? null : result.get(0); } /** * Retrieves an object by its UUID. * @param <T> A type parameter. This type will be returned * @param clazz the persistence class to retrive the ID for * @param uuid the uuid of the object to retrieve * @return an object of the specified type * @since 1.0.0 */ @SuppressWarnings("unchecked") public <T> T getObjectByUuid(Class<T> clazz, String uuid) { return getObjectByUuid(clazz, UUID.fromString(uuid)); } /** * Retrieves an object by its UUID. * @param <T> A type parameter. This type will be returned * @param clazz the persistence class to retrive the ID for * @param uuid the uuid of the object to retrieve * @param fetchGroup the JDO fetchgroup to use when making the query * @return an object of the specified type * @since 1.0.0 */ @SuppressWarnings("unchecked") public <T> T getObjectByUuid(Class<T> clazz, UUID uuid, String fetchGroup) { pm.getFetchPlan().addGroup(fetchGroup); return getObjectByUuid(clazz, uuid); } /** * Retrieves an object by its UUID. * @param <T> A type parameter. This type will be returned * @param clazz the persistence class to retrive the ID for * @param uuid the uuid of the object to retrieve * @param fetchGroup the JDO fetchgroup to use when making the query * @return an object of the specified type * @since 1.0.0 */ @SuppressWarnings("unchecked") public <T> T getObjectByUuid(Class<T> clazz, String uuid, String fetchGroup) { return getObjectByUuid(clazz, UUID.fromString(uuid), fetchGroup); } /** * Closes the PersistenceManager instance. * @since 1.0.0 */ public void close() { pm.close(); } /** * Upon finalization, closes the PersistenceManager, if not already closed. * @throws Throwable the {@code Exception} raised by this method * @since 1.0.0 */ protected void finalize() throws Throwable { close(); super.finalize(); } }
Removing detachment from persist
alpine/src/main/java/alpine/persistence/AbstractAlpineQueryManager.java
Removing detachment from persist
<ide><path>lpine/src/main/java/alpine/persistence/AbstractAlpineQueryManager.java <ide> pm.currentTransaction().commit(); <ide> pm.getFetchPlan().setDetachmentOptions(FetchPlan.DETACH_LOAD_FIELDS); <ide> pm.refresh(object); <del> return pm.detachCopy(object); <add> return object; <ide> } <ide> <ide> /** <ide> pm.currentTransaction().commit(); <ide> pm.getFetchPlan().setDetachmentOptions(FetchPlan.DETACH_LOAD_FIELDS); <ide> pm.refreshAll(pcs); <del> return pm.detachCopy(pcs); <add> return pcs; <ide> } <ide> <ide> /** <ide> pm.currentTransaction().commit(); <ide> pm.getFetchPlan().setDetachmentOptions(FetchPlan.DETACH_LOAD_FIELDS); <ide> pm.refreshAll(pcs); <del> return pm.detachCopy(pcs); <add> return pcs; <ide> } <ide> <ide> /**
Java
mit
1f55d44fa14b7b5a293a582ad8f24eb02ed0b8ab
0
Azure/azure-sdk-for-java,Azure/azure-sdk-for-java,Azure/azure-sdk-for-java,Azure/azure-sdk-for-java,Azure/azure-sdk-for-java
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.messaging.eventhubs; import static java.nio.charset.StandardCharsets.UTF_8; import com.azure.core.amqp.AmqpRetryMode; import com.azure.core.amqp.AmqpRetryOptions; import com.azure.messaging.eventhubs.models.SendOptions; import java.time.Duration; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import reactor.core.publisher.Flux; /** * Sample demonstrates how to send an iterable of events to specific event hub partition by defining partition id using * {@link SendOptions#setPartitionId(String)}. */ public class PublishIterableEvents { /** * Main method to invoke this demo about how to send an iterable of events with partition id configured. * * @param args Unused arguments to the program. * @throws InterruptedException If the program was interrupted before completion. */ public static void main(String[] args) throws InterruptedException { // The connection string value can be obtained by: // 1. Going to your Event Hubs namespace in Azure Portal. // 2. Creating an Event Hub instance. // 3. Creating a "Shared access policy" for your Event Hub instance. // 4. Copying the connection string from the policy's properties. String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}"; // Set some custom retry options other than the default set. AmqpRetryOptions retryOptions = new AmqpRetryOptions() .setDelay(Duration.ofSeconds(30)) .setMaxRetries(2) .setMode(AmqpRetryMode.EXPONENTIAL); // Instantiate a client that will be used to call the service. EventHubProducerAsyncClient producer = new EventHubClientBuilder() .connectionString(connectionString) .retry(retryOptions) .buildAsyncProducerClient(); // Create an iterable of events to send. Note that the events in iterable should // fit in a single batch. If the events exceed the size of the batch, then send operation will fail. final Iterable<EventData> events = Flux.range(0, 100).map(number -> { final String contents = "event-data-" + number; return new EventData(contents.getBytes(UTF_8)); }).collectList().block(); // To send our events, we need to know what partition to send it to. For the sake of this example, we take the // first partition id. CountDownLatch countDownLatch = new CountDownLatch(1); producer.getPartitionIds() .take(1) // take the first partition id .flatMap(partitionId -> producer.send(events, new SendOptions().setPartitionId(partitionId))) .subscribe(unused -> { }, ex -> System.out.println("Failed to send events: " + ex.getMessage()), () -> { countDownLatch.countDown(); System.out.println("Sending events completed successfully"); }); // Wait for async operation to complete or timeout after 10 seconds. try { countDownLatch.await(10, TimeUnit.SECONDS); } finally { producer.close(); } } }
sdk/eventhubs/azure-messaging-eventhubs/src/samples/java/com/azure/messaging/eventhubs/PublishIterableEvents.java
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.messaging.eventhubs; import static java.nio.charset.StandardCharsets.UTF_8; import com.azure.core.amqp.AmqpRetryMode; import com.azure.core.amqp.AmqpRetryOptions; import com.azure.messaging.eventhubs.models.SendOptions; import java.time.Duration; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import reactor.core.publisher.Flux; /** * Sample demonstrates how to send an iterable of events to specific event hub partition by defining partition id using * {@link SendOptions#setPartitionId(String)}. */ public class PublishIterableEvents { /** * Main method to invoke this demo about how to send an iterable of events with partition id configured. * * @param args Unused arguments to the program. * @throws InterruptedException If the program was interrupted before completion. */ public static void main(String[] args) throws InterruptedException { // The connection string value can be obtained by: // 1. Going to your Event Hubs namespace in Azure Portal. // 2. Creating an Event Hub instance. // 3. Creating a "Shared access policy" for your Event Hub instance. // 4. Copying the connection string from the policy's properties. String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}"; // Set some custom retry options other than the default set. AmqpRetryOptions retryOptions = new AmqpRetryOptions() .setDelay(Duration.ofSeconds(30)) .setMaxRetries(2) .setMode(AmqpRetryMode.EXPONENTIAL); // Instantiate a client that will be used to call the service. EventHubProducerAsyncClient producer = new EventHubClientBuilder() .connectionString(connectionString) .retry(retryOptions) .buildAsyncProducerClient(); // Create an iterable of events to send. Note that the events in iterable should // fit in a single batch. If the events exceed the size of the batch, then send operation will fail. final Iterable<EventData> events = Flux.range(0, 100).map(number -> { final String contents = "event-data-" + number; return new EventData(contents.getBytes(UTF_8)); }).toIterable(); // To send our events, we need to know what partition to send it to. For the sake of this example, we take the // first partition id. CountDownLatch countDownLatch = new CountDownLatch(1); producer.getPartitionIds() .take(1) // take the first partition id .flatMap(partitionId -> producer.send(events, new SendOptions().setPartitionId(partitionId))) .subscribe(unused -> { }, ex -> System.out.println("Failed to send events: " + ex.getMessage()), () -> { countDownLatch.countDown(); System.out.println("Sending events completed successfully"); }); // Wait for async operation to complete or timeout after 10 seconds. try { countDownLatch.await(10, TimeUnit.SECONDS); } finally { producer.close(); } } }
Fixed Event Hubs Sample issues #16872 (#18319)
sdk/eventhubs/azure-messaging-eventhubs/src/samples/java/com/azure/messaging/eventhubs/PublishIterableEvents.java
Fixed Event Hubs Sample issues #16872 (#18319)
<ide><path>dk/eventhubs/azure-messaging-eventhubs/src/samples/java/com/azure/messaging/eventhubs/PublishIterableEvents.java <ide> final Iterable<EventData> events = Flux.range(0, 100).map(number -> { <ide> final String contents = "event-data-" + number; <ide> return new EventData(contents.getBytes(UTF_8)); <del> }).toIterable(); <add> }).collectList().block(); <ide> <ide> // To send our events, we need to know what partition to send it to. For the sake of this example, we take the <ide> // first partition id.
Java
mit
fb3d4783eb7f19513e8e59d3fb422dbf91591d05
0
TheIndifferent/jenkins-scm-koji-plugin,judovana/jenkins-scm-koji-plugin,TheIndifferent/jenkins-scm-koji-plugin,judovana/jenkins-scm-koji-plugin,judovana/jenkins-scm-koji-plugin
package hudson.plugins.scm.koji.client; import hudson.FilePath; import hudson.model.TaskListener; import hudson.plugins.scm.koji.BuildsSerializer; import hudson.plugins.scm.koji.model.Build; import hudson.plugins.scm.koji.model.KojiBuildDownloadResult; import hudson.plugins.scm.koji.model.KojiScmConfig; import hudson.plugins.scm.koji.model.RPM; import hudson.remoting.VirtualChannel; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; import org.jenkinsci.remoting.RoleChecker; import static hudson.plugins.scm.koji.Constants.BUILD_XML; import hudson.plugins.scm.koji.KojiSCM; import hudson.plugins.scm.koji.LoggerHelp; import java.net.InetAddress; import java.net.MalformedURLException; import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class KojiBuildDownloader implements FilePath.FileCallable<KojiBuildDownloadResult>, LoggerHelp { private static final Logger LOG = LoggerFactory.getLogger(KojiSCM.class); private static final int MAX_REDIRECTIONS = 10; private final KojiScmConfig config; private final Predicate<String> notProcessedNvrPredicate; private TaskListener currentListener; private final boolean verbose = true; public KojiBuildDownloader(KojiScmConfig config, Predicate<String> notProcessedNvrPredicate) { this.config = config; this.notProcessedNvrPredicate = notProcessedNvrPredicate; } @Override public KojiBuildDownloadResult invoke(File workspace, VirtualChannel channel) throws IOException, InterruptedException { File checkoutBuildFile = new File(workspace, BUILD_XML); Build build = new BuildsSerializer().read(checkoutBuildFile); if (build == null) { // if we are here - it is the first build ever, // have to pull the koji and download whatever we'll find: build = new KojiListBuilds(config, notProcessedNvrPredicate).invoke(workspace, channel); if (build == null) { // if we are here - no remote changes on first build, exiting: return null; } } // we got the build info in workspace, downloading: File targetDir = workspace; if (config.getDownloadDir() != null && config.getDownloadDir().length() > 0) { // target dir was specified, targetDir = new File(targetDir, config.getDownloadDir()); // checkbox for dir per nvr was specified: if (config.isDirPerNvr()) { targetDir = new File(targetDir, build.getNvr()); } // do not delete the workspace dir if user specified '.' or hardcoded workspace: if (!targetDir.getAbsoluteFile().equals(workspace.getAbsoluteFile()) && targetDir.exists() && config.isCleanDownloadDir()) { if (!build.isManual()) { log("cleaning " + targetDir.toString()); cleanDirRecursively(targetDir); } else { log("manual tag detected, not cleaning : " + targetDir.toString()); String[] l = targetDir.list(); if (l == null) { l = new String[]{"Error reading"}; } for (String file : l) { log(" " + file); } } } else { log("NOT cleaning " + targetDir.toString() + ":"); log("" + !targetDir.getAbsoluteFile().equals(workspace.getAbsoluteFile())); log("" + targetDir.getAbsoluteFile()); log("" + workspace.getAbsoluteFile()); log("" + targetDir.exists()); log("" + config.isCleanDownloadDir()); } targetDir.mkdirs(); } List<String> rpmFiles = downloadRPMs(targetDir, build); return new KojiBuildDownloadResult(build, targetDir.getAbsolutePath(), rpmFiles); } private void cleanDirRecursively(File file) { if (file.isFile()) { file.delete(); return; } // if we are still here - we have a directory: File[] files = file.listFiles(); if (files != null && files.length > 0) { for (int i = 0; i < files.length; i++) { cleanDirRecursively(files[i]); } } } public List<String> downloadRPMs(File targetDir, Build build) { Predicate<RPM> nvrPredicate = i -> true; if (config.getExcludeNvr() != null && !config.getExcludeNvr().isEmpty()) { GlobPredicate glob = new GlobPredicate(config.getExcludeNvr()); nvrPredicate = rpm -> !glob.test(rpm.getNvr()); } List<String> l = build.getRpms() .stream() .filter(nvrPredicate) .map(r -> downloadRPM(targetDir, build, r)) .map(File::getAbsolutePath) .collect(Collectors.toList()); int rpmsInBuildXml = build.getRpms().size(); int dwnldedFiles = l.size(); if (dwnldedFiles == 0) { if (rpmsInBuildXml == 0) { log("Warning, nothing downloaded, but looks like nothing shoudl be."); } else { log("WARNING, nothing downloaded, but shoudl be ("+rpmsInBuildXml+"). Maybe bad exclude packages?"); } } return l; } private File downloadRPM(File targetDir, Build build, RPM rpm) { try { //FIXME do this better, do not iterate here, but rember origin from checkout. See also help-kojiDownloadUrl.html for (String url : config.getKojiDownloadUrls()) { //tarxz is special suffix used for internal builds/results. it is .tar.xz, but without dot, as we need to follow same number of dots as .rpm have (none) for (String suffix : new String[]{"rpm", "tarxz"}) { String urlString = composeUrl(url, build, rpm, suffix); log(InetAddress.getLocalHost().getHostName()); log(new Date().toString()); if (build.isManual()) { log("Manual tag provided - skipping download of ", urlString); } else { log("Downloading: ", urlString); } if (!isUrlReachable(urlString)) { log("Not accessible, trying another suffix in: ", rpm.getFilename(suffix)); continue; } File targetFile = new File(targetDir, rpm.getFilename(suffix)); log("To: ", targetFile); if (!build.isManual()) { try (OutputStream out = new BufferedOutputStream(new FileOutputStream(targetFile)); InputStream in = httpDownloadStream(urlString)) { byte[] buffer = new byte[8192]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } } return targetFile; } } } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { throw new RuntimeException("Exception while downloading RPM", ex); } return null; } private InputStream httpDownloadStream(String urlString) { HttpURLConnection httpConn = null; boolean keepConnection = false; for (int i = 0; i < MAX_REDIRECTIONS; i++) { try { URL url = new URL(urlString); httpConn = (HttpURLConnection) url.openConnection(); httpConn.setRequestMethod("GET"); int response = httpConn.getResponseCode(); switch (response) { case 200: { keepConnection = true; return httpConn.getInputStream(); } case 301: case 302: { String location = httpConn.getHeaderField("Location"); if (location == null || location.isEmpty()) { throw new Exception("Invalid Location header for response " + response); } if (urlString.equals(location)) { throw new Exception("Infinite redirection loop detected for URL: " + urlString); } urlString = location; break; } default: throw new Exception("Unsupported HTTP response " + response + " for URL: " + urlString); } } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { throw new RuntimeException(ex); } finally { if (!keepConnection && httpConn != null) { httpConn.disconnect(); } } } throw new RuntimeException("Too many redirects for URL: " + urlString); } private String composeUrl(String kojiDownloadUrl, Build build, RPM rpm, String suffix) { StringBuilder sb = new StringBuilder(255); sb.append(kojiDownloadUrl); if (kojiDownloadUrl.charAt(kojiDownloadUrl.length() - 1) != '/') { sb.append('/'); } sb.append(build.getName()).append('/'); sb.append(build.getVersion()).append('/'); sb.append(build.getRelease()).append('/'); sb.append(rpm.getArch()).append('/'); sb.append(rpm.getFilename(suffix)); return sb.toString(); } @Override public void checkRoles(RoleChecker checker) throws SecurityException { // TODO maybe implement? } public void setListener(TaskListener listener) { this.currentListener = listener; } private boolean canLog() { return (verbose && currentListener != null && currentListener.getLogger() != null); } private String host() { try { String h = InetAddress.getLocalHost().getHostName(); if (h == null) { return "null"; } else { return h; } } catch (Exception ex) { return ex.toString(); } } void print(String s) { try { currentListener.getLogger().println(s); } catch (Exception ex) { LOG.error("During printing of log to TaskListener", ex); } } @Override public void log(String s) { LOG.info(s); if (canLog()) { print("[KojiSCM][" + host() + "] " + s); } } @Override public void log(String s, Object o) { LOG.info(s, o); if (canLog()) { print("[KojiSCM][" + host() + "] " + s + ": " + o.toString()); } } @Override public void log(String s, Object... o) { LOG.info(s, o); if (canLog()) { print("[KojiSCM][" + host() + "] " + s); for (Object object : o) { print("[KojiSCM] " + object.toString()); } } } private boolean isUrlReachable(String urlString) { try { return isUrlReachableImpl(urlString, MAX_REDIRECTIONS); } catch (Exception e) { LOG.info(e.toString()); return false; } } private boolean isUrlReachableImpl(String urlString, int redirectionsRemaining) throws MalformedURLException, IOException { URL u = new URL(urlString); HttpURLConnection huc = (HttpURLConnection) u.openConnection(); try { huc.setRequestMethod("GET"); //OR huc.setRequestMethod ("HEAD"); huc.connect(); int code = huc.getResponseCode(); // http 301=Moved Permanently; 302=Found // koji.fedoraproject.org might return both if ((code == 301 || code == 302) && redirectionsRemaining > 0) { return isUrlReachableImpl(huc.getHeaderField("Location"), redirectionsRemaining - 1); } return code == 200; } finally { huc.disconnect(); } } }
src/main/java/hudson/plugins/scm/koji/client/KojiBuildDownloader.java
package hudson.plugins.scm.koji.client; import hudson.FilePath; import hudson.model.TaskListener; import hudson.plugins.scm.koji.BuildsSerializer; import hudson.plugins.scm.koji.model.Build; import hudson.plugins.scm.koji.model.KojiBuildDownloadResult; import hudson.plugins.scm.koji.model.KojiScmConfig; import hudson.plugins.scm.koji.model.RPM; import hudson.remoting.VirtualChannel; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; import org.jenkinsci.remoting.RoleChecker; import static hudson.plugins.scm.koji.Constants.BUILD_XML; import hudson.plugins.scm.koji.KojiSCM; import hudson.plugins.scm.koji.LoggerHelp; import java.net.InetAddress; import java.net.MalformedURLException; import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class KojiBuildDownloader implements FilePath.FileCallable<KojiBuildDownloadResult>, LoggerHelp { private static final Logger LOG = LoggerFactory.getLogger(KojiSCM.class); private static final int MAX_REDIRECTIONS = 10; private final KojiScmConfig config; private final Predicate<String> notProcessedNvrPredicate; private TaskListener currentListener; private final boolean verbose = true; public KojiBuildDownloader(KojiScmConfig config, Predicate<String> notProcessedNvrPredicate) { this.config = config; this.notProcessedNvrPredicate = notProcessedNvrPredicate; } @Override public KojiBuildDownloadResult invoke(File workspace, VirtualChannel channel) throws IOException, InterruptedException { File checkoutBuildFile = new File(workspace, BUILD_XML); Build build = new BuildsSerializer().read(checkoutBuildFile); if (build == null) { // if we are here - it is the first build ever, // have to pull the koji and download whatever we'll find: build = new KojiListBuilds(config, notProcessedNvrPredicate).invoke(workspace, channel); if (build == null) { // if we are here - no remote changes on first build, exiting: return null; } } // we got the build info in workspace, downloading: File targetDir = workspace; if (config.getDownloadDir() != null && config.getDownloadDir().length() > 0) { // target dir was specified, targetDir = new File(targetDir, config.getDownloadDir()); // checkbox for dir per nvr was specified: if (config.isDirPerNvr()) { targetDir = new File(targetDir, build.getNvr()); } // do not delete the workspace dir if user specified '.' or hardcoded workspace: if (!targetDir.getAbsoluteFile().equals(workspace.getAbsoluteFile()) && targetDir.exists() && config.isCleanDownloadDir()) { if (!build.isManual()) { log("cleaning " + targetDir.toString()); cleanDirRecursively(targetDir); } else { log("manual tag detected, not cleaning : " + targetDir.toString()); String[] l = targetDir.list(); if (l == null) { l = new String[]{"Error reading"}; } for (String file : l) { log(" " + file); } } } else { log("NOT cleaning " + targetDir.toString() + ":"); log("" + !targetDir.getAbsoluteFile().equals(workspace.getAbsoluteFile())); log("" + targetDir.getAbsoluteFile()); log("" + workspace.getAbsoluteFile()); log("" + targetDir.exists()); log("" + config.isCleanDownloadDir()); } targetDir.mkdirs(); } List<String> rpmFiles = downloadRPMs(targetDir, build); return new KojiBuildDownloadResult(build, targetDir.getAbsolutePath(), rpmFiles); } private void cleanDirRecursively(File file) { if (file.isFile()) { file.delete(); return; } // if we are still here - we have a directory: File[] files = file.listFiles(); if (files != null && files.length > 0) { for (int i = 0; i < files.length; i++) { cleanDirRecursively(files[i]); } } } public List<String> downloadRPMs(File targetDir, Build build) { Predicate<RPM> nvrPredicate = i -> true; if (config.getExcludeNvr() != null && !config.getExcludeNvr().isEmpty()) { GlobPredicate glob = new GlobPredicate(config.getExcludeNvr()); nvrPredicate = rpm -> !glob.test(rpm.getNvr()); } return build.getRpms() .stream() .filter(nvrPredicate) .map(r -> downloadRPM(targetDir, build, r)) .map(File::getAbsolutePath) .collect(Collectors.toList()); } private File downloadRPM(File targetDir, Build build, RPM rpm) { try { //FIXME do this better, do not iterate here, but rember origin from checkout. See also help-kojiDownloadUrl.html for (String url : config.getKojiDownloadUrls()) { //tarxz is special suffix used for internal builds/results. it is .tar.xz, but without dot, as we need to follow same number of dots as .rpm have (none) for (String suffix : new String[]{"rpm", "tarxz"}) { String urlString = composeUrl(url, build, rpm, suffix); log(InetAddress.getLocalHost().getHostName()); log(new Date().toString()); if (build.isManual()) { log("Manual tag provided - skipping download of ", urlString); } else { log("Downloading: ", urlString); } if (!isUrlReachable(urlString)) { log("Not accessible, trying another suffix in: ", rpm.getFilename(suffix)); continue; } File targetFile = new File(targetDir, rpm.getFilename(suffix)); log("To: ", targetFile); if (!build.isManual()) { try (OutputStream out = new BufferedOutputStream(new FileOutputStream(targetFile)); InputStream in = httpDownloadStream(urlString)) { byte[] buffer = new byte[8192]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } } return targetFile; } } } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { throw new RuntimeException("Exception while downloading RPM", ex); } return null; } private InputStream httpDownloadStream(String urlString) { HttpURLConnection httpConn = null; boolean keepConnection = false; for (int i = 0; i < MAX_REDIRECTIONS; i++) { try { URL url = new URL(urlString); httpConn = (HttpURLConnection) url.openConnection(); httpConn.setRequestMethod("GET"); int response = httpConn.getResponseCode(); switch (response) { case 200: { keepConnection = true; return httpConn.getInputStream(); } case 301: case 302: { String location = httpConn.getHeaderField("Location"); if (location == null || location.isEmpty()) { throw new Exception("Invalid Location header for response " + response); } if (urlString.equals(location)) { throw new Exception("Infinite redirection loop detected for URL: " + urlString); } urlString = location; break; } default: throw new Exception("Unsupported HTTP response " + response + " for URL: " + urlString); } } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { throw new RuntimeException(ex); } finally { if (!keepConnection && httpConn != null) { httpConn.disconnect(); } } } throw new RuntimeException("Too many redirects for URL: " + urlString); } private String composeUrl(String kojiDownloadUrl, Build build, RPM rpm, String suffix) { StringBuilder sb = new StringBuilder(255); sb.append(kojiDownloadUrl); if (kojiDownloadUrl.charAt(kojiDownloadUrl.length() - 1) != '/') { sb.append('/'); } sb.append(build.getName()).append('/'); sb.append(build.getVersion()).append('/'); sb.append(build.getRelease()).append('/'); sb.append(rpm.getArch()).append('/'); sb.append(rpm.getFilename(suffix)); return sb.toString(); } @Override public void checkRoles(RoleChecker checker) throws SecurityException { // TODO maybe implement? } public void setListener(TaskListener listener) { this.currentListener = listener; } private boolean canLog() { return (verbose && currentListener != null && currentListener.getLogger() != null); } private String host() { try { String h = InetAddress.getLocalHost().getHostName(); if (h == null) { return "null"; } else { return h; } } catch (Exception ex) { return ex.toString(); } } void print(String s) { try { currentListener.getLogger().println(s); } catch (Exception ex) { LOG.error("During printing of log to TaskListener", ex); } } @Override public void log(String s) { LOG.info(s); if (canLog()) { print("[KojiSCM][" + host() + "] " + s); } } @Override public void log(String s, Object o) { LOG.info(s, o); if (canLog()) { print("[KojiSCM][" + host() + "] " + s + ": " + o.toString()); } } @Override public void log(String s, Object... o) { LOG.info(s, o); if (canLog()) { print("[KojiSCM][" + host() + "] " + s); for (Object object : o) { print("[KojiSCM] " + object.toString()); } } } private boolean isUrlReachable(String urlString) { try { return isUrlReachableImpl(urlString, MAX_REDIRECTIONS); } catch (Exception e) { LOG.info(e.toString()); return false; } } private boolean isUrlReachableImpl(String urlString, int redirectionsRemaining) throws MalformedURLException, IOException { URL u = new URL(urlString); HttpURLConnection huc = (HttpURLConnection) u.openConnection(); try { huc.setRequestMethod("GET"); //OR huc.setRequestMethod ("HEAD"); huc.connect(); int code = huc.getResponseCode(); // http 301=Moved Permanently; 302=Found // koji.fedoraproject.org might return both if ((code == 301 || code == 302) && redirectionsRemaining > 0) { return isUrlReachableImpl(huc.getHeaderField("Location"), redirectionsRemaining - 1); } return code == 200; } finally { huc.disconnect(); } } }
Added warning when soemthing was about to downlaod, but was not
src/main/java/hudson/plugins/scm/koji/client/KojiBuildDownloader.java
Added warning when soemthing was about to downlaod, but was not
<ide><path>rc/main/java/hudson/plugins/scm/koji/client/KojiBuildDownloader.java <ide> targetDir.mkdirs(); <ide> } <ide> List<String> rpmFiles = downloadRPMs(targetDir, build); <add> <ide> return new KojiBuildDownloadResult(build, targetDir.getAbsolutePath(), rpmFiles); <ide> } <ide> <ide> GlobPredicate glob = new GlobPredicate(config.getExcludeNvr()); <ide> nvrPredicate = rpm -> !glob.test(rpm.getNvr()); <ide> } <del> return build.getRpms() <add> <add> List<String> l = build.getRpms() <ide> .stream() <ide> .filter(nvrPredicate) <ide> .map(r -> downloadRPM(targetDir, build, r)) <ide> .map(File::getAbsolutePath) <ide> .collect(Collectors.toList()); <add> int rpmsInBuildXml = build.getRpms().size(); <add> int dwnldedFiles = l.size(); <add> if (dwnldedFiles == 0) { <add> if (rpmsInBuildXml == 0) { <add> log("Warning, nothing downloaded, but looks like nothing shoudl be."); <add> } else { <add> log("WARNING, nothing downloaded, but shoudl be ("+rpmsInBuildXml+"). Maybe bad exclude packages?"); <add> } <add> } <add> <add> return l; <ide> } <ide> <ide> private File downloadRPM(File targetDir, Build build, RPM rpm) {
JavaScript
apache-2.0
fce17d8ac09bceef1da315debdd589052e5ca13d
0
rackerlabs/pitchfork,rackerlabs/pitchfork,oldarmyc/pitchfork,oldarmyc/pitchfork,oldarmyc/pitchfork,rackerlabs/pitchfork
$('.scrollup').click(function(){ $('html, body').animate({ scrollTop: 0 }, 600); return false; }); $('.toc').click(function(e) { e.preventDefault(); var target = $(this).attr('href'); $('html, body').animate({ scrollTop: $(target).offset().top - 60}, 600); }); $('.testing-button').on('click', function() { var pathname = window.location.pathname; pathname += 'testing'; window.location = pathname; }); $('.active-button').on('click', function() { var pathname = window.location.pathname; var temp_path = pathname.split('/'); window.location = '/' + temp_path[1] + '/'; }); $('.panel-title #toggle_details').click(function(e) { var loop = $(this).data('loop'); var title = $(this).data('title'); var button = $(this); $('.' + title).toggle('slow', function() { if ( $('.' + title).is(':hidden') ) { button.text('Call Details'); } else { button.text('Hide Details'); } }); e.stopPropagation(); }); $('.code-blocks-wrapper #toggle_results').click(function(e){ var loop = $(this).data('loop'); var title = $(this).data('title'); var results = $(this).data('results'); $('#api_results_wrapper_' + title).toggle('slow', function() { if ( $('#api_results_wrapper_' + title).is(':visible') === false) { // $('html, body').animate({ scrollTop: $('#' + title).offset().top - 60}, 10); } }); e.stopPropagation(); }); $('#data_center').on('change', function () { $(this).removeClass('error'); if ($(this).val() == 'none') { $(this).addClass('empty'); } else { $(this).removeClass("empty"); } $('.code-block').text('None'); $('.code-blocks-wrapper').hide(); if (global_count > 1) { display_message('Responses have been cleared as the data does not apply to the new data center', 'info'); } else { global_count += 1; } if (require_dc === 'true') { if ( $('#data_center').val() == 'us' ) { $('span.api-call-endpoint').text("{{ api_settings.us_api }}") } else if ( $('#data_center').val() == 'uk' ) { $('span.api-call-endpoint').text("{{ api_settings.uk_api }}") } else { $('span.api-call-endpoint').text("{{ api_settings.us_api }}") } } }); function display_message(response_message, alert_class) { var message = '<div class="alert alert-' + alert_class +'"><button type="button" class="close" data-dismiss="alert">&times;</button><p>' + response_message + '</p></div>'; $('#generated_messages').html(message); } function validate_field(field_name) { if ( $.trim($('#' + field_name).val()) != '' & $('#' + field_name).val().length != 0 & $.trim($('#' + field_name).val()) != 'none' ) { return true; } else { $('#' + field_name).addClass('error'); return false; } } function escapeHTML(data) { return data.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/\n/g, '<br />').replace(/\s\s/g, '&nbsp;&nbsp;'); } function formatXml(xml) { var formatted = ''; var reg = /(>)(<)(\/*)/g; xml = xml.toString().replace(reg, '$1\r\n$2$3'); var pad = 0; $.each(xml.split('\r\n'), function(index, node) { var indent = 0; if (node.match( /.+<\/\w[^>]*>$/ )) { indent = 0; } else if (node.match( /^<\/\w/ )) { if (pad != 0) { pad -= 2; } } else if (node.match( /^<\w[^>]*[^\/]>.*$/ )) { indent = 2; } else { indent = 0; } var padding = ''; for (var i = 0; i < pad; i++) { padding += ' '; } formatted += padding + node + '\r\n'; pad += indent; }); return escapeHTML(formatted); } function send_api_call(send_to, data) { return $.ajax({ url: send_to, type: 'POST', data: JSON.stringify(data), contentType: "application/json" }); } function process_display_api_call(send_to, data, form_submit, form_value) { send_api_call(send_to, data).done(success_process).fail(error_process); function success_process(result) { $('#loading_div_' + form_submit).hide(); if (!$('#api_results_wrapper_' + form_submit).is(':visible')) { $('#api_results_wrapper_' + form_submit).toggle('slow'); } $('#api_url_' + form_submit).text(result.api_url); $('#api_headers_' + form_submit).html( '<pre>' + JSON.stringify(result.request_headers, null, 4) + '</pre>' ); if (result.data_package) { if ( $('#api_body_wrapper_' + form_submit).is(':hidden') ) { $('#api_body_wrapper_' + form_submit).toggle(); } $('#api_body_' + form_submit).html( '<pre>' + JSON.stringify(result.data_package, null, 4) + '</pre>' ); } if (form_value != 'Mock API Call') { $('.response-headers-' + form_submit).show(); $('.response-body-' + form_submit).show(); $('#api_response_headers_' + form_submit).html( '<pre>' + JSON.stringify(result.response_headers, null, 4) + '</pre>' ); var content_type = []; if (result.response_headers['content-type']) { content_type = result.response_headers['content-type'].split(';'); } if ( result.response_code >= 400 ) { if ( $.inArray('application/xml', content_type) >= 0 || $.inArray('application/atom+xml', content_type) >= 0 ) { $('#api_content_' + form_submit).html( formatXml(result.response_body) ); } else { $('#api_content_' + form_submit).html( '<pre>' + JSON.stringify(result.response_body, null, 4) + '</pre>' ); } } else { if ( $.inArray('application/xml', content_type) >= 0 || $.inArray('application/atom+xml', content_type) >= 0 ) { $('#api_content_' + form_submit).html( formatXml(result.response_body) ); } else { $('#api_content_' + form_submit).html( '<pre>' + JSON.stringify(result.response_body, null, 4) + '</pre>' ); } } } else { $('.response-headers-' + form_submit).hide(); $('.response-body-' + form_submit).hide(); } } function error_process(result) { $('#loading_div_' + form_submit).hide(); } } $('.api_call_submit').on('click', function() { var form_submit = $(this).attr('name'); var form_value = $(this).attr('value'); $("#" + form_submit + "_form").unbind('submit').bind('submit', function(e){ e.preventDefault(); $('#loading_div_' + form_submit).show(); var sending = {}; var send_to = 'api/call/process'; var validated = false; var data = $("#" + form_submit + "_form").serialize(); $.each(data.split('&'), function (index, elem) { var vals = elem.split('='); if (vals[0] === 'app_url_link' && vals[1] != 'None') { send_to = unescape(vals[1].replace(/\+/g, ' ')) + '/api/call/process'; } sending[vals[0].replace(/\+/g, ' ')] = unescape(vals[1].replace(/\+/g, ' ')); }); var message = "You must provide the following data before the request can be sent:<br /><br />"; var dc_check = false; if ( require_dc && form_value != 'Mock API Call' ) { if ( validate_field('data_center') ) { sending['data_center'] = $('#data_center').val(); sending['ddi'] = $('#ddi').val().trim(); dc_check = true; } else { $('#data_center').addClass('error'); if (restrict_dcs === 'true') { message += "<span class='text-danger'>Region</span>"; } else { message += "<span class='text-danger'>Data Center</span>"; } } } else if (require_dc === 'true') { if ($('#data_center').length > 0 && $('#data_center').val() != 'None') { sending['data_center'] = $('#data_center').val(); sending['ddi'] = $('#ddi').val().trim(); } } else { dc_check = true; sending['ddi'] = $('#ddi').val().trim(); } if (dc_check) { sending['testing'] = testing; validated = true; } if (form_value == 'Mock API Call') { validated = true; sending['mock'] = true; sending['data_center'] = '{data_center}'; sending['ddi'] = '{ddi}'; } if (validated) { process_display_api_call( send_to, sending, form_submit, form_value ); } else { bootbox.alert(message); $('#loading_div_' + form_submit).hide(); } }); });
pitchfork/static/js/ui.js
$('.scrollup').click(function(){ $('html, body').animate({ scrollTop: 0 }, 600); return false; }); $('.toc').click(function(e) { e.preventDefault(); var target = $(this).attr('href'); $('html, body').animate({ scrollTop: $(target).offset().top - 60}, 600); }); $('.testing-button').on('click', function() { var pathname = window.location.pathname; pathname += 'testing'; window.location = pathname; }); $('.active-button').on('click', function() { var pathname = window.location.pathname; var temp_path = pathname.split('/'); window.location = '/' + temp_path[1] + '/'; }); $('.panel-title #toggle_details').click(function(e) { var loop = $(this).data('loop'); var title = $(this).data('title'); var button = $(this); $('.' + title).toggle('slow', function() { if ( $('.' + title).is(':hidden') ) { button.text('Call Details'); } else { button.text('Hide Details'); } }); e.stopPropagation(); }); $('.code-blocks-wrapper #toggle_results').click(function(e){ var loop = $(this).data('loop'); var title = $(this).data('title'); var results = $(this).data('results'); $('#api_results_wrapper_' + title).toggle('slow', function() { if ( $('#api_results_wrapper_' + title).is(':visible') === false) { // $('html, body').animate({ scrollTop: $('#' + title).offset().top - 60}, 10); } }); e.stopPropagation(); }); $('#data_center').on('change', function () { $(this).removeClass('error'); if ($(this).val() == 'none') { $(this).addClass('empty'); } else { $(this).removeClass("empty"); } $('.code-block').text('None'); $('.code-blocks-wrapper').hide(); if (global_count > 1) { display_message('Responses have been cleared as the data does not apply to the new data center', 'info'); } else { global_count += 1; } if (require_dc === 'true') { if ( $('#data_center').val() == 'us' ) { $('span.api-call-endpoint').text("{{ api_settings.us_api }}") } else if ( $('#data_center').val() == 'uk' ) { $('span.api-call-endpoint').text("{{ api_settings.uk_api }}") } else { $('span.api-call-endpoint').text("{{ api_settings.us_api }}") } } }); function display_message(response_message, alert_class) { var message = '<div class="alert alert-' + alert_class +'"><button type="button" class="close" data-dismiss="alert">&times;</button><p>' + response_message + '</p></div>'; $('#generated_messages').html(message); } function validate_field(field_name) { if ( $.trim($('#' + field_name).val()) != '' & $('#' + field_name).val().length != 0 & $.trim($('#' + field_name).val()) != 'none' ) { return true; } else { $('#' + field_name).addClass('error'); return false; } } function escapeHTML(data) { return data.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/\n/g, '<br />').replace(/\s\s/g, '&nbsp;&nbsp;'); } function formatXml(xml) { var formatted = ''; var reg = /(>)(<)(\/*)/g; xml = xml.toString().replace(reg, '$1\r\n$2$3'); var pad = 0; $.each(xml.split('\r\n'), function(index, node) { var indent = 0; if (node.match( /.+<\/\w[^>]*>$/ )) { indent = 0; } else if (node.match( /^<\/\w/ )) { if (pad != 0) { pad -= 2; } } else if (node.match( /^<\w[^>]*[^\/]>.*$/ )) { indent = 2; } else { indent = 0; } var padding = ''; for (var i = 0; i < pad; i++) { padding += ' '; } formatted += padding + node + '\r\n'; pad += indent; }); return escapeHTML(formatted); } function send_api_call(send_to, data) { return $.ajax({ url: send_to, type: 'POST', data: JSON.stringify(data), contentType: "application/json" }); } function process_display_api_call(send_to, data, form_submit, form_value) { send_api_call(send_to, data).done(success_process).fail(error_process); function success_process(result) { $('#loading_div_' + form_submit).hide(); if (!$('#api_results_wrapper_' + form_submit).is(':visible')) { $('#api_results_wrapper_' + form_submit).toggle('slow'); } $('#api_url_' + form_submit).text(result.api_url); $('#api_headers_' + form_submit).html( '<pre>' + JSON.stringify(result.request_headers, null, 4) + '</pre>' ); if (result.data_package) { if ( $('#api_body_wrapper_' + form_submit).is(':hidden') ) { $('#api_body_wrapper_' + form_submit).toggle(); } $('#api_body_' + form_submit).html( '<pre>' + JSON.stringify(result.data_package, null, 4) + '</pre>' ); } if (form_value != 'Mock API Call') { $('.response-headers-' + form_submit).show(); $('.response-body-' + form_submit).show(); $('#api_response_headers_' + form_submit).html( '<pre>' + JSON.stringify(result.response_headers, null, 4) + '</pre>' ); var content_type = []; if (result.response_headers['content-type']) { content_type = result.response_headers['content-type'].split(';'); } if ( result.response_code >= 400 ) { if ( $.inArray('application/xml', content_type) >= 0 || $.inArray('application/atom+xml', content_type) >= 0 ) { $('#api_content_' + form_submit).html( formatXml(result.response_body) ); } else { $('#api_content_' + form_submit).html( '<pre>' + JSON.stringify(result.response_body, null, 4) + '</pre>' ); } } else { if ( $.inArray('application/xml', content_type) >= 0 || $.inArray('application/atom+xml', content_type) >= 0 ) { $('#api_content_' + form_submit).html( formatXml(result.response_body) ); } else { $('#api_content_' + form_submit).html( '<pre>' + JSON.stringify(result.response_body, null, 4) + '</pre>' ); } } } else { $('.response-headers-' + form_submit).hide(); $('.response-body-' + form_submit).hide(); } } function error_process(result) { $('#loading_div_' + form_submit).hide(); } } $('.api_call_submit').on('click', function() { var form_submit = $(this).attr('name'); var form_value = $(this).attr('value'); $("#" + form_submit + "_form").unbind('submit').bind('submit', function(e){ e.preventDefault(); $('#loading_div_' + form_submit).show(); var sending = {}; var send_to = 'api/call/process'; var validated = false; var data = $("#" + form_submit + "_form").serialize(); $.each(data.split('&'), function (index, elem) { var vals = elem.split('='); if (vals[0] === 'app_url_link' && vals[1] != 'None') { send_to = unescape(vals[1].replace(/\+/g, ' ')) + '/api/call/process'; } sending[vals[0].replace(/\+/g, ' ')] = unescape(vals[1].replace(/\+/g, ' ')); }); var message = "You must provide the following data before the request can be sent:<br /><br />"; var dc_check = false; if ( require_dc && form_value != 'Mock API Call' ) { if ( validate_field('data_center') ) { sending['data_center'] = $('#data_center').val(); sending['ddi'] = $('#ddi').val().trim(); dc_check = true; } else { $('#data_center').addClass('error'); if (restrict_dcs === 'true') { message += "<span class='text-danger'>Region</span>"; } else { message += "<span class='text-danger'>Data Center</span>"; } } } else if (require_dc === 'true') { if ($('#data_center').length > 0 && $('#data_center').val() != 'None') { sending['data_center'] = $('#data_center').val(); sending['ddi'] = $('#ddi').val().trim(); } } else { dc_check = true; sending['ddi'] = $('#ddi').val().trim(); } if (dc_check) { sending['testing'] = testing; validated = true; } if (form_value == 'Mock API Call') { validated = true; sending['mock'] = true; } if (validated) { process_display_api_call( send_to, sending, form_submit, form_value ); } else { bootbox.alert(message); $('#loading_div_' + form_submit).hide(); } }); });
If mock then send placeholders for DC and DDI
pitchfork/static/js/ui.js
If mock then send placeholders for DC and DDI
<ide><path>itchfork/static/js/ui.js <ide> if (form_value == 'Mock API Call') { <ide> validated = true; <ide> sending['mock'] = true; <add> sending['data_center'] = '{data_center}'; <add> sending['ddi'] = '{ddi}'; <ide> } <ide> if (validated) { <ide> process_display_api_call(
Java
apache-2.0
22f01cbd43ff15a4cbc418ea5bca7286dfe34bf8
0
dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android
package org.commcare.activities; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.RestrictionsManager; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.util.Pair; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Toast; import org.commcare.CommCareApp; import org.commcare.CommCareApplication; import org.commcare.dalvik.BuildConfig; import org.commcare.engine.resource.AppInstallStatus; import org.commcare.engine.resource.ResourceInstallUtils; import org.commcare.google.services.analytics.FirebaseAnalyticsUtil; import org.commcare.interfaces.CommCareActivityUIController; import org.commcare.interfaces.RuntimePermissionRequester; import org.commcare.interfaces.WithUIController; import org.commcare.android.database.app.models.UserKeyRecord; import org.commcare.android.database.global.models.ApplicationRecord; import org.commcare.models.database.user.DemoUserBuilder; import org.commcare.preferences.DevSessionRestorer; import org.commcare.suite.model.OfflineUserRestore; import org.commcare.tasks.DataPullTask; import org.commcare.tasks.InstallStagedUpdateTask; import org.commcare.tasks.ManageKeyRecordTask; import org.commcare.tasks.PullTaskResultReceiver; import org.commcare.tasks.ResultAndError; import org.commcare.utils.CrashUtil; import org.commcare.utils.ConsumerAppsUtil; import org.commcare.utils.Permissions; import org.commcare.views.ViewUtil; import org.commcare.views.dialogs.CustomProgressDialog; import org.commcare.views.dialogs.DialogCreationHelpers; import org.commcare.views.notifications.MessageTag; import org.commcare.views.notifications.NotificationMessage; import org.commcare.views.notifications.NotificationMessageFactory; import org.commcare.views.notifications.NotificationMessageFactory.StockMessages; import org.javarosa.core.services.locale.Localization; import java.util.ArrayList; /** * @author ctsims */ public class LoginActivity extends CommCareActivity<LoginActivity> implements OnItemSelectedListener, DataPullController, RuntimePermissionRequester, WithUIController, PullTaskResultReceiver { private static final String TAG = LoginActivity.class.getSimpleName(); public static final int MENU_DEMO = Menu.FIRST; private static final int MENU_ABOUT = Menu.FIRST + 1; private static final int MENU_PERMISSIONS = Menu.FIRST + 2; private static final int MENU_PASSWORD_MODE = Menu.FIRST + 3; private static final int MENU_APP_MANAGER = Menu.FIRST + 4; public static final String NOTIFICATION_MESSAGE_LOGIN = "login_message"; public final static String KEY_LAST_APP = "id-last-seated-app"; public final static String KEY_ENTERED_USER = "entered-username"; public final static String KEY_ENTERED_PW_OR_PIN = "entered-password-or-pin"; private static final int SEAT_APP_ACTIVITY = 0; public final static String USER_TRIGGERED_LOGOUT = "user-triggered-logout"; public final static String LOGIN_MODE = "login-mode"; public final static String MANUAL_SWITCH_TO_PW_MODE = "manually-swithced-to-password-mode"; private static final int TASK_KEY_EXCHANGE = 1; private static final int TASK_UPGRADE_INSTALL = 2; private final ArrayList<String> appIdDropdownList = new ArrayList<>(); private String usernameBeforeRotation; private String passwordOrPinBeforeRotation; private LoginActivityUIController uiController; private FormAndDataSyncer formAndDataSyncer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); checkManagedConfiguration(); if (shouldFinish()) { // If we're going to finish in onResume() because there is no usable seated app, // don't bother with all of the setup here return; } uiController.setupUI(); formAndDataSyncer = new FormAndDataSyncer(); if (savedInstanceState == null) { // Only restore last user on the initial creation uiController.restoreLastUser(); } else { // If the screen was rotated with entered text present, we will want to restore it // in onResume (can't do it here b/c will get overriden by logic in refreshForNewApp()) usernameBeforeRotation = savedInstanceState.getString(KEY_ENTERED_USER); passwordOrPinBeforeRotation = savedInstanceState.getString(KEY_ENTERED_PW_OR_PIN); } Permissions.acquireAllAppPermissions(this, this, Permissions.ALL_PERMISSIONS_REQUEST); } @Override @TargetApi(Build.VERSION_CODES.M) public void requestNeededPermissions(int requestCode) { ActivityCompat.requestPermissions(this, Permissions.getAppPermissions(), requestCode); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { String[] requiredPerms = Permissions.getRequiredPerms(); if (requestCode == Permissions.ALL_PERMISSIONS_REQUEST) { for (int i = 0; i < permissions.length; i++) { for (String requiredPerm : requiredPerms) { if (requiredPerm.equals(permissions[i]) && grantResults[i] == PackageManager.PERMISSION_DENIED) { uiController.setPermissionDeniedState(); return; } } } } uiController.setPermissionsGrantedState(); } @Override protected void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); String enteredUsername = uiController.getEnteredUsername(); if (!"".equals(enteredUsername) && enteredUsername != null) { savedInstanceState.putString(KEY_ENTERED_USER, enteredUsername); } String enteredPasswordOrPin = uiController.getEnteredPasswordOrPin(); if (!"".equals(enteredPasswordOrPin) && enteredPasswordOrPin != null) { savedInstanceState.putString(KEY_ENTERED_PW_OR_PIN, enteredPasswordOrPin); } } /** * @param restoreSession Indicates if CommCare should attempt to restore the saved session * upon successful login */ protected void initiateLoginAttempt(boolean restoreSession) { LoginMode loginMode = uiController.getLoginMode(); if ("".equals(uiController.getEnteredPasswordOrPin()) && loginMode != LoginMode.PRIMED) { if (loginMode == LoginMode.PASSWORD) { raiseLoginMessage(StockMessages.Auth_EmptyPassword, false); } else { raiseLoginMessage(StockMessages.Auth_EmptyPin, false); } return; } uiController.clearErrorMessage(); ViewUtil.hideVirtualKeyboard(LoginActivity.this); if (loginMode == LoginMode.PASSWORD) { DevSessionRestorer.tryAutoLoginPasswordSave(uiController.getEnteredPasswordOrPin(), false); } if (ResourceInstallUtils.isUpdateReadyToInstall()) { // install update, which triggers login upon completion installPendingUpdate(); } else { localLoginOrPullAndLogin(restoreSession); } } @Override public String getActivityTitle() { return null; } @Override public void startDataPull(DataPullMode mode) { switch(mode) { case CONSUMER_APP: formAndDataSyncer.performLocalRestore(this, getUniformUsername(), uiController.getEnteredPasswordOrPin()); break; case CCZ_DEMO: OfflineUserRestore offlineUserRestore = CommCareApplication.instance().getCommCarePlatform().getDemoUserRestore(); uiController.setUsername(offlineUserRestore.getUsername()); uiController.setPasswordOrPin(OfflineUserRestore.DEMO_USER_PASSWORD); formAndDataSyncer.performDemoUserRestore(this, offlineUserRestore); break; case NORMAL: formAndDataSyncer.performOtaRestore(this, getUniformUsername(), uiController.getEnteredPasswordOrPin()); break; } } @Override protected void onResume() { super.onResume(); if (shouldFinish()) { return; } // Otherwise, refresh the activity for current conditions uiController.refreshView(); } protected boolean checkForSeatedAppChange() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String lastSeatedId = prefs.getString(KEY_LAST_APP, ""); String currentSeatedId = CommCareApplication.instance().getCurrentApp().getUniqueId(); if (!lastSeatedId.equals(currentSeatedId)) { prefs.edit().putString(KEY_LAST_APP, currentSeatedId).commit(); return true; } return false; } private static boolean shouldFinish() { CommCareApp currentApp = CommCareApplication.instance().getCurrentApp(); return currentApp == null || !currentApp.getAppRecord().isUsable(); } @Override protected void onResumeFragments() { super.onResumeFragments(); // It is possible that we left off at the LoginActivity last time we were on the main CC // screen, but have since done something in the app manager to either leave no seated app // at all, or to render the seated app unusable. Redirect to dispatch activity if we // encounter either case if (shouldFinish()) { setResult(RESULT_OK); this.finish(); return; } if (CommCareApplication.instance().isConsumerApp()) { uiController.setUsername(BuildConfig.CONSUMER_APP_USERNAME); uiController.setPasswordOrPin(BuildConfig.CONSUMER_APP_PASSWORD); localLoginOrPullAndLogin(false); } else { tryAutoLogin(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == SEAT_APP_ACTIVITY && resultCode == RESULT_OK) { uiController.refreshForNewApp(); usernameBeforeRotation = passwordOrPinBeforeRotation = null; } super.onActivityResult(requestCode, resultCode, intent); } private void tryAutoLogin() { Pair<String, String> userAndPass = DevSessionRestorer.getAutoLoginCreds(forceAutoLogin()); if (userAndPass != null) { uiController.setUsername(userAndPass.first); uiController.setPasswordOrPin(userAndPass.second); // If we're doing auto-login, means we're using a password so switch UI to pw mode uiController.setNormalPasswordMode(); if (!getIntent().getBooleanExtra(USER_TRIGGERED_LOGOUT, false)) { // If we are attempting auto-login, assume that we want to restore a saved session initiateLoginAttempt(true); } } } private boolean forceAutoLogin() { return CommCareApplication.instance().checkPendingBuildRefresh(); } private String getUniformUsername() { return uiController.getEnteredUsername().toLowerCase().trim(); } private boolean tryLocalLogin(final boolean warnMultipleAccounts, boolean restoreSession, boolean blockRemoteKeyManagement) { //TODO: check username/password for emptiness return tryLocalLogin(getUniformUsername(), uiController.getEnteredPasswordOrPin(), warnMultipleAccounts, restoreSession, uiController.getLoginMode(), blockRemoteKeyManagement, DataPullMode.NORMAL); } private boolean tryLocalLogin(final String username, String passwordOrPin, final boolean warnMultipleAccounts, final boolean restoreSession, LoginMode loginMode, boolean blockRemoteKeyManagement, DataPullMode pullModeToUse) { try { final boolean triggerMultipleUsersWarning = getMatchingUsersCount(username) > 1 && warnMultipleAccounts; ManageKeyRecordTask<LoginActivity> task = new ManageKeyRecordTask<LoginActivity>(this, TASK_KEY_EXCHANGE, username, passwordOrPin, loginMode, CommCareApplication.instance().getCurrentApp(), restoreSession, triggerMultipleUsersWarning, blockRemoteKeyManagement, pullModeToUse) { @Override protected void deliverUpdate(LoginActivity receiver, String... update) { receiver.updateProgress(update[0], TASK_KEY_EXCHANGE); } }; task.connect(this); task.executeParallel(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } private int getMatchingUsersCount(String username) { int count = 0; for (UserKeyRecord record : CommCareApplication.instance().getAppStorage(UserKeyRecord.class)) { if (record.getUsername().equals(username)) { count++; } } return count; } @Override public void dataPullCompleted() { CrashUtil.registerUserData(); ViewUtil.hideVirtualKeyboard(LoginActivity.this); CommCareApplication.notificationManager().clearNotifications(NOTIFICATION_MESSAGE_LOGIN); Intent i = new Intent(); i.putExtra(LOGIN_MODE, uiController.getLoginMode()); i.putExtra(MANUAL_SWITCH_TO_PW_MODE, uiController.userManuallySwitchedToPasswordMode()); setResult(RESULT_OK, i); finish(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MENU_DEMO, 0, Localization.get("login.menu.demo")).setIcon(android.R.drawable.ic_menu_preferences); menu.add(0, MENU_ABOUT, 1, Localization.get("home.menu.about")).setIcon(android.R.drawable.ic_menu_help); menu.add(0, MENU_PERMISSIONS, 1, Localization.get("permission.acquire.required")).setIcon(android.R.drawable.ic_menu_manage); menu.add(0, MENU_PASSWORD_MODE, 1, Localization.get("login.menu.password.mode")); menu.add(0, MENU_APP_MANAGER, 1, Localization.get("login.menu.app.manager")); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); menu.findItem(MENU_PERMISSIONS).setVisible(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M); menu.findItem(MENU_PASSWORD_MODE).setVisible(uiController.getLoginMode() == LoginMode.PIN); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { boolean otherResult = super.onOptionsItemSelected(item); switch (item.getItemId()) { case MENU_DEMO: loginDemoUser(); return true; case MENU_ABOUT: DialogCreationHelpers.buildAboutCommCareDialog(this).showNonPersistentDialog(); return true; case MENU_PERMISSIONS: Permissions.acquireAllAppPermissions(this, this, Permissions.ALL_PERMISSIONS_REQUEST); return true; case MENU_PASSWORD_MODE: uiController.manualSwitchToPasswordMode(); return true; case MENU_APP_MANAGER: Intent i = new Intent(this, AppManagerActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(i); return true; default: return otherResult; } } private void loginDemoUser() { OfflineUserRestore offlineUserRestore = CommCareApplication.instance().getCommCarePlatform().getDemoUserRestore(); FirebaseAnalyticsUtil.reportPracticeModeUsage(offlineUserRestore); if (offlineUserRestore != null) { tryLocalLogin(offlineUserRestore.getUsername(), OfflineUserRestore.DEMO_USER_PASSWORD, false, false, LoginMode.PASSWORD, true, DataPullMode.CCZ_DEMO); } else { DemoUserBuilder.build(this, CommCareApplication.instance().getCurrentApp()); tryLocalLogin(DemoUserBuilder.DEMO_USERNAME, DemoUserBuilder.DEMO_PASSWORD, false, false, LoginMode.PASSWORD, false, DataPullMode.NORMAL); } } @Override public void raiseLoginMessageWithInfo(MessageTag messageTag, String additionalInfo, boolean showTop) { NotificationMessage message = NotificationMessageFactory.message(messageTag, new String[]{null, null, additionalInfo}, NOTIFICATION_MESSAGE_LOGIN); raiseMessage(message, showTop); } @Override public void raiseLoginMessage(MessageTag messageTag, boolean showTop) { NotificationMessage message = NotificationMessageFactory.message(messageTag, NOTIFICATION_MESSAGE_LOGIN); raiseMessage(message, showTop); } @Override public void raiseMessage(NotificationMessage message, boolean showTop) { String toastText = message.getTitle(); if (showTop) { CommCareApplication.notificationManager().reportNotificationMessage(message); } uiController.setErrorMessageUI(toastText, showTop); } /** * Implementation of generateProgressDialog() for DialogController -- other methods * handled entirely in CommCareActivity */ @Override public CustomProgressDialog generateProgressDialog(int taskId) { if (CommCareApplication.instance().isConsumerApp()) { return ConsumerAppsUtil.getGenericConsumerAppsProgressDialog(taskId, false); } CustomProgressDialog dialog; switch (taskId) { case TASK_KEY_EXCHANGE: dialog = CustomProgressDialog.newInstance(Localization.get("key.manage.title"), Localization.get("key.manage.start"), taskId); break; case DataPullTask.DATA_PULL_TASK_ID: dialog = CustomProgressDialog.newInstance(Localization.get("sync.communicating.title"), Localization.get("sync.progress.starting"), taskId); dialog.addCancelButton(); dialog.addProgressBar(); break; case TASK_UPGRADE_INSTALL: dialog = CustomProgressDialog.newInstance(Localization.get("updates.installing.title"), Localization.get("updates.installing.message"), taskId); break; default: Log.w(TAG, "taskId passed to generateProgressDialog does not match " + "any valid possibilities in LoginActivity"); return null; } return dialog; } protected void restoreEnteredTextFromRotation() { if (usernameBeforeRotation != null) { uiController.setUsername(usernameBeforeRotation); usernameBeforeRotation = null; } if (passwordOrPinBeforeRotation != null) { uiController.setPasswordOrPin(passwordOrPinBeforeRotation); passwordOrPinBeforeRotation = null; } } protected void populateAppSpinner(ArrayList<ApplicationRecord> readyApps) { ArrayList<String> appNames = new ArrayList<>(); appIdDropdownList.clear(); for (ApplicationRecord r : readyApps) { appNames.add(r.getDisplayName()); appIdDropdownList.add(r.getUniqueId()); } // Want to set the spinner's selection to match whatever the currently seated app is String currAppId = CommCareApplication.instance().getCurrentApp().getUniqueId(); int position = appIdDropdownList.indexOf(currAppId); uiController.setMultipleAppsUIState(appNames, position); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // Retrieve the app record corresponding to the app selected String appId = appIdDropdownList.get(position); boolean selectedNewApp = !appId.equals(CommCareApplication.instance().getCurrentApp().getUniqueId()); if (selectedNewApp) { // Set the id of the last selected app SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); prefs.edit().putString(KEY_LAST_APP, appId).commit(); // Launch the activity to seat the new app Intent i = new Intent(this, SeatAppActivity.class); i.putExtra(SeatAppActivity.KEY_APP_TO_SEAT, appId); this.startActivityForResult(i, SEAT_APP_ACTIVITY); } } @Override public void onNothingSelected(AdapterView<?> parent) { } /** * Block the user with a dialog while downloaded update is installed. */ private void installPendingUpdate() { InstallStagedUpdateTask<LoginActivity> task = new InstallStagedUpdateTask<LoginActivity>(TASK_UPGRADE_INSTALL) { @Override protected void deliverResult(LoginActivity receiver, AppInstallStatus result) { if (result == AppInstallStatus.Installed) { Toast.makeText(receiver, Localization.get("login.update.install.success"), Toast.LENGTH_LONG).show(); } else { CommCareApplication.notificationManager().reportNotificationMessage(NotificationMessageFactory.message(result)); } localLoginOrPullAndLogin(uiController.isRestoreSessionChecked()); } @Override protected void deliverUpdate(LoginActivity receiver, int[]... update) { } @Override protected void deliverError(LoginActivity receiver, Exception e) { e.printStackTrace(); Log.e(TAG, "update installation on login failed: " + e.getMessage()); Toast.makeText(receiver, Localization.get("login.update.install.failure"), Toast.LENGTH_LONG).show(); localLoginOrPullAndLogin(uiController.isRestoreSessionChecked()); } }; task.connect(this); task.executeParallel(); } private void localLoginOrPullAndLogin(boolean restoreSession) { if (tryLocalLogin(false, restoreSession, false)) { return; } // If local login was not successful startDataPull(CommCareApplication.instance().isConsumerApp() ? DataPullMode.CONSUMER_APP : DataPullMode.NORMAL); } @Override public void initUIController() { if (CommCareApplication.instance().isConsumerApp()) { uiController = new BlankLoginActivityUIController(this); } else { uiController = new LoginActivityUIController(this); } } @Override public CommCareActivityUIController getUIController() { return this.uiController; } @Override public void handlePullTaskResult(ResultAndError<DataPullTask.PullTaskResult> resultAndErrorMessage, boolean userTriggeredSync, boolean formsToSend, boolean usingRemoteKeyManagement) { DataPullTask.PullTaskResult result = resultAndErrorMessage.data; if (result == null) { // The task crashed unexpectedly raiseLoginMessage(StockMessages.Restore_Unknown, true); return; } switch (result) { case AUTH_FAILED: raiseLoginMessage(StockMessages.Auth_BadCredentials, false); break; case BAD_DATA_REQUIRES_INTERVENTION: raiseLoginMessageWithInfo(StockMessages.Remote_BadRestoreRequiresIntervention, resultAndErrorMessage.errorMessage, true); break; case BAD_DATA: raiseLoginMessageWithInfo(StockMessages.Remote_BadRestore, resultAndErrorMessage.errorMessage, true); break; case STORAGE_FULL: raiseLoginMessage(StockMessages.Storage_Full, true); break; case DOWNLOAD_SUCCESS: if (!tryLocalLogin(true, uiController.isRestoreSessionChecked(), !usingRemoteKeyManagement)) { raiseLoginMessage(StockMessages.Auth_CredentialMismatch, true); } break; case UNREACHABLE_HOST: raiseLoginMessage(StockMessages.Remote_NoNetwork, true); break; case CONNECTION_TIMEOUT: raiseLoginMessage(StockMessages.Remote_Timeout, true); break; case SERVER_ERROR: raiseLoginMessage(StockMessages.Remote_ServerError, true); break; case UNKNOWN_FAILURE: raiseLoginMessageWithInfo(StockMessages.Restore_Unknown, resultAndErrorMessage.errorMessage, true); break; case ACTIONABLE_FAILURE: raiseLoginMessageWithInfo(StockMessages.Restore_Unknown, resultAndErrorMessage.errorMessage, true); break; case AUTH_OVER_HTTP: raiseLoginMessage(StockMessages.Auth_Over_HTTP, true); break; } } @Override public void handlePullTaskUpdate(Integer... update) { if (CommCareApplication.instance().isConsumerApp()) { return; } SyncCapableCommCareActivity.handleSyncUpdate(this, update); } @Override public void handlePullTaskError() { raiseLoginMessage(StockMessages.Restore_Unknown, true); } private void checkManagedConfiguration() { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { // Check for managed configuration RestrictionsManager restrictionsManager = (RestrictionsManager) getSystemService(Context.RESTRICTIONS_SERVICE); if (restrictionsManager == null) { return; } Bundle appRestrictions = restrictionsManager.getApplicationRestrictions(); if (appRestrictions.containsKey("username") && appRestrictions.containsKey("password")) { uiController.setUsername(appRestrictions.getString("username")); uiController.setPasswordOrPin(appRestrictions.getString("password")); initiateLoginAttempt(false); } } } }
app/src/org/commcare/activities/LoginActivity.java
package org.commcare.activities; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.RestrictionsManager; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.util.Pair; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Toast; import org.commcare.CommCareApp; import org.commcare.CommCareApplication; import org.commcare.dalvik.BuildConfig; import org.commcare.engine.resource.AppInstallStatus; import org.commcare.engine.resource.ResourceInstallUtils; import org.commcare.google.services.analytics.FirebaseAnalyticsUtil; import org.commcare.interfaces.CommCareActivityUIController; import org.commcare.interfaces.RuntimePermissionRequester; import org.commcare.interfaces.WithUIController; import org.commcare.android.database.app.models.UserKeyRecord; import org.commcare.android.database.global.models.ApplicationRecord; import org.commcare.models.database.user.DemoUserBuilder; import org.commcare.preferences.DevSessionRestorer; import org.commcare.suite.model.OfflineUserRestore; import org.commcare.tasks.DataPullTask; import org.commcare.tasks.InstallStagedUpdateTask; import org.commcare.tasks.ManageKeyRecordTask; import org.commcare.tasks.PullTaskResultReceiver; import org.commcare.tasks.ResultAndError; import org.commcare.utils.CrashUtil; import org.commcare.utils.ConsumerAppsUtil; import org.commcare.utils.Permissions; import org.commcare.views.ViewUtil; import org.commcare.views.dialogs.CustomProgressDialog; import org.commcare.views.dialogs.DialogCreationHelpers; import org.commcare.views.notifications.MessageTag; import org.commcare.views.notifications.NotificationMessage; import org.commcare.views.notifications.NotificationMessageFactory; import org.commcare.views.notifications.NotificationMessageFactory.StockMessages; import org.javarosa.core.services.locale.Localization; import java.util.ArrayList; /** * @author ctsims */ public class LoginActivity extends CommCareActivity<LoginActivity> implements OnItemSelectedListener, DataPullController, RuntimePermissionRequester, WithUIController, PullTaskResultReceiver { private static final String TAG = LoginActivity.class.getSimpleName(); public static final int MENU_DEMO = Menu.FIRST; private static final int MENU_ABOUT = Menu.FIRST + 1; private static final int MENU_PERMISSIONS = Menu.FIRST + 2; private static final int MENU_PASSWORD_MODE = Menu.FIRST + 3; private static final int MENU_APP_MANAGER = Menu.FIRST + 4; public static final String NOTIFICATION_MESSAGE_LOGIN = "login_message"; public final static String KEY_LAST_APP = "id-last-seated-app"; public final static String KEY_ENTERED_USER = "entered-username"; public final static String KEY_ENTERED_PW_OR_PIN = "entered-password-or-pin"; private static final int SEAT_APP_ACTIVITY = 0; public final static String USER_TRIGGERED_LOGOUT = "user-triggered-logout"; public final static String LOGIN_MODE = "login-mode"; public final static String MANUAL_SWITCH_TO_PW_MODE = "manually-swithced-to-password-mode"; private static final int TASK_KEY_EXCHANGE = 1; private static final int TASK_UPGRADE_INSTALL = 2; private final ArrayList<String> appIdDropdownList = new ArrayList<>(); private String usernameBeforeRotation; private String passwordOrPinBeforeRotation; private LoginActivityUIController uiController; private FormAndDataSyncer formAndDataSyncer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); checkManagedConfiguration(); if (shouldFinish()) { // If we're going to finish in onResume() because there is no usable seated app, // don't bother with all of the setup here return; } uiController.setupUI(); formAndDataSyncer = new FormAndDataSyncer(); if (savedInstanceState == null) { // Only restore last user on the initial creation uiController.restoreLastUser(); } else { // If the screen was rotated with entered text present, we will want to restore it // in onResume (can't do it here b/c will get overriden by logic in refreshForNewApp()) usernameBeforeRotation = savedInstanceState.getString(KEY_ENTERED_USER); passwordOrPinBeforeRotation = savedInstanceState.getString(KEY_ENTERED_PW_OR_PIN); } Permissions.acquireAllAppPermissions(this, this, Permissions.ALL_PERMISSIONS_REQUEST); } @Override @TargetApi(Build.VERSION_CODES.M) public void requestNeededPermissions(int requestCode) { ActivityCompat.requestPermissions(this, Permissions.getAppPermissions(), requestCode); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { String[] requiredPerms = Permissions.getRequiredPerms(); if (requestCode == Permissions.ALL_PERMISSIONS_REQUEST) { for (int i = 0; i < permissions.length; i++) { for (String requiredPerm : requiredPerms) { if (requiredPerm.equals(permissions[i]) && grantResults[i] == PackageManager.PERMISSION_DENIED) { uiController.setPermissionDeniedState(); return; } } } } uiController.setPermissionsGrantedState(); } @Override protected void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); String enteredUsername = uiController.getEnteredUsername(); if (!"".equals(enteredUsername) && enteredUsername != null) { savedInstanceState.putString(KEY_ENTERED_USER, enteredUsername); } String enteredPasswordOrPin = uiController.getEnteredPasswordOrPin(); if (!"".equals(enteredPasswordOrPin) && enteredPasswordOrPin != null) { savedInstanceState.putString(KEY_ENTERED_PW_OR_PIN, enteredPasswordOrPin); } } /** * @param restoreSession Indicates if CommCare should attempt to restore the saved session * upon successful login */ protected void initiateLoginAttempt(boolean restoreSession) { LoginMode loginMode = uiController.getLoginMode(); if ("".equals(uiController.getEnteredPasswordOrPin()) && loginMode != LoginMode.PRIMED) { if (loginMode == LoginMode.PASSWORD) { raiseLoginMessage(StockMessages.Auth_EmptyPassword, false); } else { raiseLoginMessage(StockMessages.Auth_EmptyPin, false); } return; } uiController.clearErrorMessage(); ViewUtil.hideVirtualKeyboard(LoginActivity.this); if (loginMode == LoginMode.PASSWORD) { DevSessionRestorer.tryAutoLoginPasswordSave(uiController.getEnteredPasswordOrPin(), false); } if (ResourceInstallUtils.isUpdateReadyToInstall()) { // install update, which triggers login upon completion installPendingUpdate(); } else { localLoginOrPullAndLogin(restoreSession); } } @Override public String getActivityTitle() { return null; } @Override public void startDataPull(DataPullMode mode) { switch(mode) { case CONSUMER_APP: formAndDataSyncer.performLocalRestore(this, getUniformUsername(), uiController.getEnteredPasswordOrPin()); break; case CCZ_DEMO: OfflineUserRestore offlineUserRestore = CommCareApplication.instance().getCommCarePlatform().getDemoUserRestore(); uiController.setUsername(offlineUserRestore.getUsername()); uiController.setPasswordOrPin(OfflineUserRestore.DEMO_USER_PASSWORD); formAndDataSyncer.performDemoUserRestore(this, offlineUserRestore); break; case NORMAL: formAndDataSyncer.performOtaRestore(this, getUniformUsername(), uiController.getEnteredPasswordOrPin()); break; } } @Override protected void onResume() { super.onResume(); if (shouldFinish()) { return; } // Otherwise, refresh the activity for current conditions uiController.refreshView(); } protected boolean checkForSeatedAppChange() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String lastSeatedId = prefs.getString(KEY_LAST_APP, ""); String currentSeatedId = CommCareApplication.instance().getCurrentApp().getUniqueId(); if (!lastSeatedId.equals(currentSeatedId)) { prefs.edit().putString(KEY_LAST_APP, currentSeatedId).commit(); return true; } return false; } private static boolean shouldFinish() { CommCareApp currentApp = CommCareApplication.instance().getCurrentApp(); return currentApp == null || !currentApp.getAppRecord().isUsable(); } @Override protected void onResumeFragments() { super.onResumeFragments(); // It is possible that we left off at the LoginActivity last time we were on the main CC // screen, but have since done something in the app manager to either leave no seated app // at all, or to render the seated app unusable. Redirect to dispatch activity if we // encounter either case if (shouldFinish()) { setResult(RESULT_OK); this.finish(); return; } if (CommCareApplication.instance().isConsumerApp()) { uiController.setUsername(BuildConfig.CONSUMER_APP_USERNAME); uiController.setPasswordOrPin(BuildConfig.CONSUMER_APP_PASSWORD); localLoginOrPullAndLogin(false); } else { tryAutoLogin(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == SEAT_APP_ACTIVITY && resultCode == RESULT_OK) { uiController.refreshForNewApp(); } super.onActivityResult(requestCode, resultCode, intent); } private void tryAutoLogin() { Pair<String, String> userAndPass = DevSessionRestorer.getAutoLoginCreds(forceAutoLogin()); if (userAndPass != null) { uiController.setUsername(userAndPass.first); uiController.setPasswordOrPin(userAndPass.second); // If we're doing auto-login, means we're using a password so switch UI to pw mode uiController.setNormalPasswordMode(); if (!getIntent().getBooleanExtra(USER_TRIGGERED_LOGOUT, false)) { // If we are attempting auto-login, assume that we want to restore a saved session initiateLoginAttempt(true); } } } private boolean forceAutoLogin() { return CommCareApplication.instance().checkPendingBuildRefresh(); } private String getUniformUsername() { return uiController.getEnteredUsername().toLowerCase().trim(); } private boolean tryLocalLogin(final boolean warnMultipleAccounts, boolean restoreSession, boolean blockRemoteKeyManagement) { //TODO: check username/password for emptiness return tryLocalLogin(getUniformUsername(), uiController.getEnteredPasswordOrPin(), warnMultipleAccounts, restoreSession, uiController.getLoginMode(), blockRemoteKeyManagement, DataPullMode.NORMAL); } private boolean tryLocalLogin(final String username, String passwordOrPin, final boolean warnMultipleAccounts, final boolean restoreSession, LoginMode loginMode, boolean blockRemoteKeyManagement, DataPullMode pullModeToUse) { try { final boolean triggerMultipleUsersWarning = getMatchingUsersCount(username) > 1 && warnMultipleAccounts; ManageKeyRecordTask<LoginActivity> task = new ManageKeyRecordTask<LoginActivity>(this, TASK_KEY_EXCHANGE, username, passwordOrPin, loginMode, CommCareApplication.instance().getCurrentApp(), restoreSession, triggerMultipleUsersWarning, blockRemoteKeyManagement, pullModeToUse) { @Override protected void deliverUpdate(LoginActivity receiver, String... update) { receiver.updateProgress(update[0], TASK_KEY_EXCHANGE); } }; task.connect(this); task.executeParallel(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } private int getMatchingUsersCount(String username) { int count = 0; for (UserKeyRecord record : CommCareApplication.instance().getAppStorage(UserKeyRecord.class)) { if (record.getUsername().equals(username)) { count++; } } return count; } @Override public void dataPullCompleted() { CrashUtil.registerUserData(); ViewUtil.hideVirtualKeyboard(LoginActivity.this); CommCareApplication.notificationManager().clearNotifications(NOTIFICATION_MESSAGE_LOGIN); Intent i = new Intent(); i.putExtra(LOGIN_MODE, uiController.getLoginMode()); i.putExtra(MANUAL_SWITCH_TO_PW_MODE, uiController.userManuallySwitchedToPasswordMode()); setResult(RESULT_OK, i); finish(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MENU_DEMO, 0, Localization.get("login.menu.demo")).setIcon(android.R.drawable.ic_menu_preferences); menu.add(0, MENU_ABOUT, 1, Localization.get("home.menu.about")).setIcon(android.R.drawable.ic_menu_help); menu.add(0, MENU_PERMISSIONS, 1, Localization.get("permission.acquire.required")).setIcon(android.R.drawable.ic_menu_manage); menu.add(0, MENU_PASSWORD_MODE, 1, Localization.get("login.menu.password.mode")); menu.add(0, MENU_APP_MANAGER, 1, Localization.get("login.menu.app.manager")); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); menu.findItem(MENU_PERMISSIONS).setVisible(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M); menu.findItem(MENU_PASSWORD_MODE).setVisible(uiController.getLoginMode() == LoginMode.PIN); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { boolean otherResult = super.onOptionsItemSelected(item); switch (item.getItemId()) { case MENU_DEMO: loginDemoUser(); return true; case MENU_ABOUT: DialogCreationHelpers.buildAboutCommCareDialog(this).showNonPersistentDialog(); return true; case MENU_PERMISSIONS: Permissions.acquireAllAppPermissions(this, this, Permissions.ALL_PERMISSIONS_REQUEST); return true; case MENU_PASSWORD_MODE: uiController.manualSwitchToPasswordMode(); return true; case MENU_APP_MANAGER: Intent i = new Intent(this, AppManagerActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(i); return true; default: return otherResult; } } private void loginDemoUser() { OfflineUserRestore offlineUserRestore = CommCareApplication.instance().getCommCarePlatform().getDemoUserRestore(); FirebaseAnalyticsUtil.reportPracticeModeUsage(offlineUserRestore); if (offlineUserRestore != null) { tryLocalLogin(offlineUserRestore.getUsername(), OfflineUserRestore.DEMO_USER_PASSWORD, false, false, LoginMode.PASSWORD, true, DataPullMode.CCZ_DEMO); } else { DemoUserBuilder.build(this, CommCareApplication.instance().getCurrentApp()); tryLocalLogin(DemoUserBuilder.DEMO_USERNAME, DemoUserBuilder.DEMO_PASSWORD, false, false, LoginMode.PASSWORD, false, DataPullMode.NORMAL); } } @Override public void raiseLoginMessageWithInfo(MessageTag messageTag, String additionalInfo, boolean showTop) { NotificationMessage message = NotificationMessageFactory.message(messageTag, new String[]{null, null, additionalInfo}, NOTIFICATION_MESSAGE_LOGIN); raiseMessage(message, showTop); } @Override public void raiseLoginMessage(MessageTag messageTag, boolean showTop) { NotificationMessage message = NotificationMessageFactory.message(messageTag, NOTIFICATION_MESSAGE_LOGIN); raiseMessage(message, showTop); } @Override public void raiseMessage(NotificationMessage message, boolean showTop) { String toastText = message.getTitle(); if (showTop) { CommCareApplication.notificationManager().reportNotificationMessage(message); } uiController.setErrorMessageUI(toastText, showTop); } /** * Implementation of generateProgressDialog() for DialogController -- other methods * handled entirely in CommCareActivity */ @Override public CustomProgressDialog generateProgressDialog(int taskId) { if (CommCareApplication.instance().isConsumerApp()) { return ConsumerAppsUtil.getGenericConsumerAppsProgressDialog(taskId, false); } CustomProgressDialog dialog; switch (taskId) { case TASK_KEY_EXCHANGE: dialog = CustomProgressDialog.newInstance(Localization.get("key.manage.title"), Localization.get("key.manage.start"), taskId); break; case DataPullTask.DATA_PULL_TASK_ID: dialog = CustomProgressDialog.newInstance(Localization.get("sync.communicating.title"), Localization.get("sync.progress.starting"), taskId); dialog.addCancelButton(); dialog.addProgressBar(); break; case TASK_UPGRADE_INSTALL: dialog = CustomProgressDialog.newInstance(Localization.get("updates.installing.title"), Localization.get("updates.installing.message"), taskId); break; default: Log.w(TAG, "taskId passed to generateProgressDialog does not match " + "any valid possibilities in LoginActivity"); return null; } return dialog; } protected void restoreEnteredTextFromRotation() { if (usernameBeforeRotation != null) { uiController.setUsername(usernameBeforeRotation); usernameBeforeRotation = null; } if (passwordOrPinBeforeRotation != null) { uiController.setPasswordOrPin(passwordOrPinBeforeRotation); passwordOrPinBeforeRotation = null; } } protected void populateAppSpinner(ArrayList<ApplicationRecord> readyApps) { ArrayList<String> appNames = new ArrayList<>(); appIdDropdownList.clear(); for (ApplicationRecord r : readyApps) { appNames.add(r.getDisplayName()); appIdDropdownList.add(r.getUniqueId()); } // Want to set the spinner's selection to match whatever the currently seated app is String currAppId = CommCareApplication.instance().getCurrentApp().getUniqueId(); int position = appIdDropdownList.indexOf(currAppId); uiController.setMultipleAppsUIState(appNames, position); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // Retrieve the app record corresponding to the app selected String appId = appIdDropdownList.get(position); boolean selectedNewApp = !appId.equals(CommCareApplication.instance().getCurrentApp().getUniqueId()); if (selectedNewApp) { // Set the id of the last selected app SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); prefs.edit().putString(KEY_LAST_APP, appId).commit(); // Launch the activity to seat the new app Intent i = new Intent(this, SeatAppActivity.class); i.putExtra(SeatAppActivity.KEY_APP_TO_SEAT, appId); this.startActivityForResult(i, SEAT_APP_ACTIVITY); } } @Override public void onNothingSelected(AdapterView<?> parent) { } /** * Block the user with a dialog while downloaded update is installed. */ private void installPendingUpdate() { InstallStagedUpdateTask<LoginActivity> task = new InstallStagedUpdateTask<LoginActivity>(TASK_UPGRADE_INSTALL) { @Override protected void deliverResult(LoginActivity receiver, AppInstallStatus result) { if (result == AppInstallStatus.Installed) { Toast.makeText(receiver, Localization.get("login.update.install.success"), Toast.LENGTH_LONG).show(); } else { CommCareApplication.notificationManager().reportNotificationMessage(NotificationMessageFactory.message(result)); } localLoginOrPullAndLogin(uiController.isRestoreSessionChecked()); } @Override protected void deliverUpdate(LoginActivity receiver, int[]... update) { } @Override protected void deliverError(LoginActivity receiver, Exception e) { e.printStackTrace(); Log.e(TAG, "update installation on login failed: " + e.getMessage()); Toast.makeText(receiver, Localization.get("login.update.install.failure"), Toast.LENGTH_LONG).show(); localLoginOrPullAndLogin(uiController.isRestoreSessionChecked()); } }; task.connect(this); task.executeParallel(); } private void localLoginOrPullAndLogin(boolean restoreSession) { if (tryLocalLogin(false, restoreSession, false)) { return; } // If local login was not successful startDataPull(CommCareApplication.instance().isConsumerApp() ? DataPullMode.CONSUMER_APP : DataPullMode.NORMAL); } @Override public void initUIController() { if (CommCareApplication.instance().isConsumerApp()) { uiController = new BlankLoginActivityUIController(this); } else { uiController = new LoginActivityUIController(this); } } @Override public CommCareActivityUIController getUIController() { return this.uiController; } @Override public void handlePullTaskResult(ResultAndError<DataPullTask.PullTaskResult> resultAndErrorMessage, boolean userTriggeredSync, boolean formsToSend, boolean usingRemoteKeyManagement) { DataPullTask.PullTaskResult result = resultAndErrorMessage.data; if (result == null) { // The task crashed unexpectedly raiseLoginMessage(StockMessages.Restore_Unknown, true); return; } switch (result) { case AUTH_FAILED: raiseLoginMessage(StockMessages.Auth_BadCredentials, false); break; case BAD_DATA_REQUIRES_INTERVENTION: raiseLoginMessageWithInfo(StockMessages.Remote_BadRestoreRequiresIntervention, resultAndErrorMessage.errorMessage, true); break; case BAD_DATA: raiseLoginMessageWithInfo(StockMessages.Remote_BadRestore, resultAndErrorMessage.errorMessage, true); break; case STORAGE_FULL: raiseLoginMessage(StockMessages.Storage_Full, true); break; case DOWNLOAD_SUCCESS: if (!tryLocalLogin(true, uiController.isRestoreSessionChecked(), !usingRemoteKeyManagement)) { raiseLoginMessage(StockMessages.Auth_CredentialMismatch, true); } break; case UNREACHABLE_HOST: raiseLoginMessage(StockMessages.Remote_NoNetwork, true); break; case CONNECTION_TIMEOUT: raiseLoginMessage(StockMessages.Remote_Timeout, true); break; case SERVER_ERROR: raiseLoginMessage(StockMessages.Remote_ServerError, true); break; case UNKNOWN_FAILURE: raiseLoginMessageWithInfo(StockMessages.Restore_Unknown, resultAndErrorMessage.errorMessage, true); break; case ACTIONABLE_FAILURE: raiseLoginMessageWithInfo(StockMessages.Restore_Unknown, resultAndErrorMessage.errorMessage, true); break; case AUTH_OVER_HTTP: raiseLoginMessage(StockMessages.Auth_Over_HTTP, true); break; } } @Override public void handlePullTaskUpdate(Integer... update) { if (CommCareApplication.instance().isConsumerApp()) { return; } SyncCapableCommCareActivity.handleSyncUpdate(this, update); } @Override public void handlePullTaskError() { raiseLoginMessage(StockMessages.Restore_Unknown, true); } private void checkManagedConfiguration() { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { // Check for managed configuration RestrictionsManager restrictionsManager = (RestrictionsManager) getSystemService(Context.RESTRICTIONS_SERVICE); if (restrictionsManager == null) { return; } Bundle appRestrictions = restrictionsManager.getApplicationRestrictions(); if (appRestrictions.containsKey("username") && appRestrictions.containsKey("password")) { uiController.setUsername(appRestrictions.getString("username")); uiController.setPasswordOrPin(appRestrictions.getString("password")); initiateLoginAttempt(false); } } } }
fix overriding of last username
app/src/org/commcare/activities/LoginActivity.java
fix overriding of last username
<ide><path>pp/src/org/commcare/activities/LoginActivity.java <ide> protected void onActivityResult(int requestCode, int resultCode, Intent intent) { <ide> if (requestCode == SEAT_APP_ACTIVITY && resultCode == RESULT_OK) { <ide> uiController.refreshForNewApp(); <add> usernameBeforeRotation = passwordOrPinBeforeRotation = null; <ide> } <ide> <ide> super.onActivityResult(requestCode, resultCode, intent);
Java
apache-2.0
87d955c5b59c90b45ad1d6208daf13bbd25d3e11
0
deib-polimi/modaclouds-tests,deib-polimi/modaclouds-tests
package it.polimi.modaclouds.scalingsdatests; import it.cloud.Configuration; import it.cloud.amazon.ec2.AmazonEC2; import it.cloud.amazon.ec2.Instance; import it.cloud.amazon.ec2.VirtualMachine; import it.cloud.amazon.elb.ElasticLoadBalancing; import it.cloud.amazon.elb.ElasticLoadBalancing.Listener; import it.cloud.utils.CloudException; import it.cloud.utils.JMeterTest; import it.cloud.utils.JMeterTest.RunInstance; import it.cloud.utils.Local; import it.cloud.utils.Ssh; import it.polimi.modaclouds.scalingsdatests.sdavalidator.Validator; import it.polimi.modaclouds.scalingsdatests.utils.CloudMLCall; import it.polimi.modaclouds.scalingsdatests.utils.CloudMLCall.CloudML; import it.polimi.modaclouds.scalingsdatests.utils.MonitoringPlatform; import it.polimi.tower4clouds.rules.MonitoringRule; import it.polimi.tower4clouds.rules.MonitoringRules; import java.io.File; import java.io.StringReader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Scanner; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.RandomStringUtils; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.amazonaws.services.cloudwatch.model.Statistic; public class Test { private static final Logger logger = LoggerFactory.getLogger(Test.class); private VirtualMachine mpl; private VirtualMachine app; private VirtualMachine clients; private VirtualMachine database; private VirtualMachine lb; private boolean useDatabase; private boolean useCloudML; private boolean useSDA; private boolean useOwnLoadBalancer; private boolean useAutoscalingReasoner; private boolean running; private boolean initialized; private boolean cloudMlInitialized; private MonitoringPlatform monitoringPlatform; private CloudML cloudML; public static enum App { MIC( "mic", "MPloadModel-MiC", "jmeterTestTemplate-MiC.jmx", "startContainerMonitoring-MiC.sh", "stopContainerMonitoring-MiC.sh", "grep_methodResult-MiC", new String[] { "reg", "save", "answ" }, "MIC", "cloudml.json", "cloudml-LB.json", "cloudmlrules.txt"), HTTPAGENT( "httpagent", "MPloadModel-HTTPAgent", "jmeterTestTemplate-HTTPAgent.jmx", null, "stopContainerMonitoring-HTTPAgent.sh", "grep_methodResult-HTTPAgent", new String[] { "getPage" }, "HTTPAgent", "cloudml.json", "cloudml-LB.json", "cloudmlrules.txt" ); public String name; public String fileModel; public String baseJmx; public String startContainerMonitoringFile; public String stopContainerMonitoringFile; public String grepMethodResult; public String[] methods; public String tierName; public String cloudMl; public String cloudMlLoadBalancer; public String cpuUtilizationRules; private App(String name, String fileModel, String baseJmx, String startContainerMonitoringFile, String stopContainerMonitoringFile, String grepMethodResult, String[] methods, String tierName, String cloudMl, String cloudMlLoadBalancer, String cpuUtilizationRules) { this.name = name; this.fileModel = fileModel; this.baseJmx = baseJmx; this.startContainerMonitoringFile = startContainerMonitoringFile; this.stopContainerMonitoringFile = stopContainerMonitoringFile; this.grepMethodResult = grepMethodResult; this.methods = methods; this.tierName = tierName; this.cloudMl = cloudMl; this.cloudMlLoadBalancer = cloudMlLoadBalancer; this.cpuUtilizationRules = cpuUtilizationRules; } public Path getBaseJmxPath() { return Configuration.getPathToFile(baseJmx); } public static App getFromName(String name) { for (App a : values()) if (a.name.equalsIgnoreCase(name)) return a; return DEFAULT_APP; } } public static enum DemandEstimator { UBR("UBR"), ERPS("ERPS"), CI("CI"); public String name; private DemandEstimator(String name) { this.name = name; } public static DemandEstimator getFromName(String name) { for (DemandEstimator d : values()) if (d.name.equalsIgnoreCase(name)) return d; return DEFAULT_DEMAND_ESTIMATOR; } } public static final App DEFAULT_APP = App.MIC; public static final DemandEstimator DEFAULT_DEMAND_ESTIMATOR = DemandEstimator.ERPS; public static final long ERROR_STATUS_NULL = -1234; public static final int MAX_ATTEMPTS = 5; public static long performTest(String size, int clients, int servers, App app, String data, boolean useDatabase, boolean startAsOnDemand, boolean reuseInstances, boolean leaveInstancesOn, boolean onlyStartMachines, String loadModelFile, int firstInstancesToSkip, String demandEstimator, int window, boolean useSDA, boolean useCloudML, double highCpu, double lowCpu, int cooldown, String loadBalancerIp, boolean useAutoscalingReasoner, String pathToModel, String sshHost, String sshUsername, String sshPassword) throws Exception { String baseJmx = app.getBaseJmxPath().toString(); if (baseJmx == null || !new File(baseJmx).exists()) throw new RuntimeException("The provided base JMX file (" + baseJmx.toString() + ") doesn't exist!"); if (data == null || !new File(data).exists()) throw new RuntimeException("The provided data file (" + data + ") doesn't exist!"); if (loadModelFile != null && !new File(loadModelFile).exists()) loadModelFile = null; if (window <= 0) window = Validator.DEFAULT_WINDOW; long init = System.currentTimeMillis(); Test t = new Test(size, clients, servers, app.name, useDatabase, useSDA, useCloudML, loadBalancerIp != null, useAutoscalingReasoner); if (reuseInstances) t.considerRunningMachines(); t.startMachines(startAsOnDemand); if (loadBalancerIp != null) t.loadBalancer = loadBalancerIp; else t.createLoadBalancer(); Path path = null; Exception thrown = null; try { t.initSystem(loadModelFile, demandEstimator, window, pathToModel, sshHost, sshUsername, sshPassword); if (onlyStartMachines) return -1; boolean performTheTest = false; if (useCloudML || useAutoscalingReasoner) { String status; int attempt = 0; do { t.initCloudML(app); status = t.getTierStatus(app.tierName); attempt++; } while ((status == null || status.equals("null")) && attempt < MAX_ATTEMPTS); if (status != null && !status.equals("null")) { if (useCloudML) t.addCPUUtilizationMonitoringRules(app.cpuUtilizationRules, app.tierName, highCpu, lowCpu, window, cooldown); performTheTest = true; } else { logger.error("CloudML isn't working (the statuses are null)."); performTheTest = false; } } else { performTheTest = true; } if (performTheTest) path = t.runTest(app, data, demandEstimator); } catch (Exception e) { logger.error("Error while performing the test.", e); thrown = e; } if (thrown != null) { try { Date date = new Date(); String now = String.format("%1$td%1$tm%1$ty%1$tH%1$tM-%2$s-%3$dx%4$d-%5$s%6$s-broken", date, size, getPeakFromData(data) / clients, clients, app.name, (useSDA ? "-" + demandEstimator : "") + (useCloudML ? "-CloudML" : "") + (useAutoscalingReasoner ? "-AR" : "")); t.localPath = "tests" + File.separator + now; t.retrieveFiles(app); } catch (Exception e) { logger.error("Error while trying to retrieve the files after an error.", e); } } if (!leaveInstancesOn) { if (useCloudML) { t.stopCloudMLInstances(); t.terminateCloudMLDaemon(); } if (loadBalancerIp == null) t.destroyLoadBalancer(); t.stopMachines(); } if (useSDA) Validator.perform(path, t.getCores(), firstInstancesToSkip, app, window); if (thrown != null) throw thrown; return System.currentTimeMillis() - init; } public Test(String size, int clients, int servers, String app, boolean useDatabase, boolean useSDA, boolean useCloudML, boolean useOwnLoadBalancer, boolean useAutoscalingReasoner) throws CloudException { if (clients <= 0) throw new RuntimeException("You need at least 1 client!"); if (servers <= 0) throw new RuntimeException("You need at least 1 server!"); mpl = VirtualMachine.getVM("mpl", size, 1); this.app = VirtualMachine.getVM(app, size, servers); this.clients = VirtualMachine.getVM("client", size, clients); this.useDatabase = useDatabase; if (useDatabase) database = VirtualMachine.getVM("database", size, 1); running = false; initialized = false; cloudMlInitialized = false; this.useCloudML = useCloudML; this.useSDA = useSDA; this.useOwnLoadBalancer = useOwnLoadBalancer; if (useOwnLoadBalancer) lb = VirtualMachine.getVM("lb"); otherThreads = new ArrayList<Thread>(); this.useAutoscalingReasoner = useAutoscalingReasoner; } private String loadBalancer; public static final String LB_BASENAME = "ScalingSDATests"; private void createLoadBalancer() { if ((app.getInstancesNeeded() <= 1 && (!useCloudML || !useAutoscalingReasoner)) || useOwnLoadBalancer) return; if (loadBalancer != null) throw new RuntimeException( "You've already created a load balancer!"); loadBalancer = LB_BASENAME + RandomStringUtils.randomNumeric(3); ElasticLoadBalancing.createNewLoadBalancer(loadBalancer, new Listener("HTTP", Integer.parseInt(app.getParameter("PORT")))); } private void destroyLoadBalancer() { if ((app.getInstancesNeeded() <= 1 && (!useCloudML || !useAutoscalingReasoner)) || useOwnLoadBalancer) return; if (loadBalancer == null) throw new RuntimeException( "You've still to create a load balancer!"); ElasticLoadBalancing.deleteLoadBalancer(loadBalancer); loadBalancer = null; } private String getTierStatus(String tier) { cloudML.updateStatus(); return cloudML.getTierStatus(tier); } public void startMachines(boolean startAsOnDemand) { if (running) throw new RuntimeException("The system is already running!"); logger.info("Starting all the machines..."); if (!startAsOnDemand) { mpl.spotRequest(); if (!useCloudML && !useAutoscalingReasoner) app.spotRequest(); clients.spotRequest(); if (useDatabase) database.spotRequest(); } else { mpl.onDemandRequest(); if (!useCloudML && !useAutoscalingReasoner) app.onDemandRequest(); clients.onDemandRequest(); if (useDatabase) database.onDemandRequest(); } mpl.waitUntilRunning(); if (!useCloudML && !useAutoscalingReasoner) app.waitUntilRunning(); clients.waitUntilRunning(); if (useDatabase) database.waitUntilRunning(); mpl.setNameToInstances(mpl.getParameter("NAME")); if (!useCloudML && !useAutoscalingReasoner) app.setNameToInstances(app.getParameter("NAME")); clients.setNameToInstances(clients.getParameter("NAME")); if (useDatabase) database.setNameToInstances(database.getParameter("NAME")); mpl.getInstances().get(0).waitUntilSshAvailable(); if (!useCloudML && !useAutoscalingReasoner) app.getInstances().get(0).waitUntilSshAvailable(); if (useDatabase) database.getInstances().get(0).waitUntilSshAvailable(); logger.info("All the machines are now running!"); running = true; } public void considerRunningMachines() { considerRunningMachines(true); } public void considerRunningMachines(boolean rebootMachines) { if (running) throw new RuntimeException("The system is already running!"); logger.info("Searching for running machines..."); AmazonEC2 ec2 = new AmazonEC2(); ec2.addRunningInstances(mpl); if (!useCloudML && !useAutoscalingReasoner) ec2.addRunningInstances(app); ec2.addRunningInstances(clients); if (useDatabase) ec2.addRunningInstances(database); if (rebootMachines) { mpl.reboot(); if (!useCloudML && !useAutoscalingReasoner) app.reboot(); clients.reboot(); if (useDatabase) database.reboot(); } logger.info("Added running instances!"); } public void stopMachines() { if (!running) throw new RuntimeException("The system isn't running yet!"); logger.info("Stopping all the machines..."); if (!Boolean.parseBoolean(mpl.getParameter("LEAVE_INSTANCES_ON"))) mpl.terminate(); if (!useCloudML && !useAutoscalingReasoner && !Boolean.parseBoolean(app.getParameter("LEAVE_INSTANCES_ON"))) app.terminate(); if (!Boolean.parseBoolean(clients.getParameter("LEAVE_INSTANCES_ON"))) clients.terminate(); if (useDatabase && !Boolean.parseBoolean(database.getParameter("LEAVE_INSTANCES_ON"))) database.terminate(); logger.info("All the machines have been shutted down!"); running = false; initialized = false; localPath = null; } public void stopCloudMLInstances() { if (!running) throw new RuntimeException("The system isn't running yet!"); if (Boolean.parseBoolean(app.getParameter("LEAVE_INSTANCES_ON"))) { logger.info("Leaving the CLoudML instances on as requested..."); return; } logger.info("Stopping CloudML instances..."); cloudML.terminateAllInstances(); } public void terminateCloudMLDaemon() throws Exception { if (!running) throw new RuntimeException("The system isn't running yet!"); logger.info("Stopping the CloudML daemon..."); String cloudMLIp = mpl.getInstances().get(0).getIp(); String cloudMLPort = mpl.getParameter("CLOUDML_PORT"); Ssh.execInBackground(cloudMLIp, mpl, String.format(mpl.getParameter("CLOUDML_STARTER"), cloudMLPort + " -stop")); } private List<Thread> otherThreads; public void initSystem(String loadModelFile, String demandEstimator, int window, String pathToModel, String sshHost, String sshUsername, String sshPassword) throws Exception { if (!running) throw new RuntimeException("The system isn't running yet!"); if (initialized) throw new RuntimeException("The system is already initialized!"); logger.info("Deleting the files set for removal before the test and upgrading the scripts..."); if (!useCloudML && !useAutoscalingReasoner) { app.deleteFiles(); app.execDownloader(); } mpl.deleteFiles(); Instance impl = (Instance)mpl.getInstances().get(0); impl.execDownloader(); clients.deleteFiles(); clients.execDownloader(); clients.execUpdater(); if (useDatabase) database.deleteFiles(); if (useOwnLoadBalancer) { logger.info("Updating and starting the load balancer..."); Ssh.exec(loadBalancer, lb, lb.getParameter("DOWNLOADER")); Ssh.exec(loadBalancer, lb, lb.getParameter("STOPPER")); VirtualMachine.deleteFiles(loadBalancer, lb); Ssh.exec(loadBalancer, lb, lb.getParameter("UPDATER")); try { Thread.sleep(10000); } catch (Exception e) { } Ssh.exec(loadBalancer, lb, lb.getParameter("STARTER")); } logger.info("Initializing the system..."); String mplIp = impl.getIp(); int mplPort = Integer.parseInt(mpl.getParameter("MP_PORT")); impl.execUpdater(); impl.exec(String.format(mpl.getParameter("STARTER"), mplIp)); try { Thread.sleep(10000); } catch (Exception e) { } monitoringPlatform = new MonitoringPlatform(mplIp, mplPort); int cores = getCores(); Local.exec(String.format("bash %s %s %s %d %s %d %b", loadModelFile, impl.getIp(), impl.getIp(), cores, demandEstimator, window, useSDA)); try { Thread.sleep(10000); } catch (Exception e) { } if (useSDA) { otherThreads.add(Ssh.execInBackground(impl, String.format( mpl.getParameter("SDA_STARTER"), mplIp))); try { Thread.sleep(10000); } catch (Exception e) { } } if (!useCloudML && !useAutoscalingReasoner) for (it.cloud.Instance iapp : app.getInstances()) { iapp.execUpdater(); iapp.exec(String.format( app.getParameter("STARTER"), useDatabase ? database.getIps().get(0) : "127.0.0.1", mplIp, mpl.getParameter("MP_PORT") )); try { Thread.sleep(10000); } catch (Exception e) { } if (app.getInstancesNeeded() > 1 && loadBalancer != null) { iapp.exec(String.format(app.getParameter("ADD_TO_LOAD_BALANCER"), loadBalancer)); try { Thread.sleep(10000); } catch (Exception e) { } } } if (useAutoscalingReasoner) { String remotePathToModel = getActualFile(impl.getIp(), mpl, pathToModel, "autoscalingReasoner"); impl.exec(String.format(mpl.getParameter("AR_STARTER"), impl.getIp(), mpl.getParameter("AR_PORT"), remotePathToModel, sshHost, sshUsername, sshPassword, impl.getIp(), mpl.getParameter("CLOUDML_PORT"))); try { Thread.sleep(10000); } catch (Exception e) { } } logger.info("System initialized!"); initialized = true; } public static int getPeakFromData(String data) { int peak = 0; try (Scanner sc = new Scanner(Configuration.getInputStream(data))) { while (sc.hasNextLine()) { String line = sc.nextLine(); int value; try { value = Integer.parseInt(line.split(" ")[0]); } catch (Exception e) { continue; } if (value > peak) peak = value; } } catch (Exception e) { } return peak; } public void initCloudML(App app) throws Exception { if (!running) throw new RuntimeException("The system isn't running yet!"); if (!initialized) throw new RuntimeException("The system isn't initialized yet!"); if (cloudMlInitialized) { stopCloudMLInstances(); terminateCloudMLDaemon(); try { Thread.sleep(10000); } catch (Exception e) { } cloudMlInitialized = false; } logger.info("Initializing CloudML..."); Instance impl = (Instance)mpl.getInstances().get(0); String mplIp = impl.getIp(); String cloudMLIp = mplIp; int cloudMLPort = Integer.parseInt(mpl.getParameter("CLOUDML_PORT")); logger.info("Trying connecting to the CloudML daemon..."); try { cloudML = CloudMLCall.getCloudML(cloudMLIp, cloudMLPort); } catch (Exception e) { logger.info("The daemon wasn't running, starting it..."); Ssh.execInBackground(cloudMLIp, mpl, String.format(mpl.getParameter("CLOUDML_STARTER"), Integer.toString(cloudMLPort))); boolean goOn = true; while (goOn) { try { Thread.sleep(10000); } catch (Exception e1) { } try { cloudML = CloudMLCall.getCloudML(cloudMLIp, cloudMLPort); goOn = false; } catch (Exception e1) { logger.warn("Trying again to connect to the CloudML daemon in 10 seconds..."); } } } logger.info("Connected to the CloudML daemon!"); cloudML.deploy(getActualDeploymentModel(app, true).toFile()); logger.info("CloudML initialized!"); cloudMlInitialized = true; } private static List<MonitoringRule> getMonitoringRulesFromFile(String fileName, Object... substitutions) throws Exception { String tmp = FileUtils.readFileToString(Configuration.getPathToFile(fileName).toFile()); if (substitutions.length > 0) tmp = String.format(tmp, substitutions); if (tmp.indexOf("<monitoringRules") == -1) tmp = "<monitoringRules xmlns=\"http://www.modaclouds.eu/xsd/1.0/monitoring_rules_schema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.modaclouds.eu/xsd/1.0/monitoring_rules_schema\">" + tmp + "</monitoringRules>"; JAXBContext context = JAXBContext.newInstance(MonitoringRules.class); Unmarshaller unmarshaller = context.createUnmarshaller(); MonitoringRules rules = (MonitoringRules) unmarshaller.unmarshal(new StringReader(tmp)); return rules.getMonitoringRules(); } private static DecimalFormat doubleFormatter = doubleFormatter(); private static DecimalFormat doubleFormatter() { DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.getDefault()); otherSymbols.setDecimalSeparator('.'); DecimalFormat myFormatter = new DecimalFormat("0.0#########", otherSymbols); return myFormatter; } public void addCPUUtilizationMonitoringRules(String file, String tierName, double aboveValue, double belowValue, int window, int cooldown) throws Exception { if (aboveValue > 1.0) aboveValue = 1.0; if (aboveValue <= 0.0) aboveValue = Main.DEFAULT_HIGH_CPU; if (belowValue <= 0.0) belowValue = 0.0; if (belowValue >= 1.0) belowValue = Main.DEFAULT_LOW_CPU; String cloudMLIp = mpl.getInstances().get(0).getIp(); int cloudMLPort = Integer.parseInt(mpl.getParameter("CLOUDML_PORT")); MonitoringRules rules = new MonitoringRules(); rules.getMonitoringRules() .addAll(getMonitoringRulesFromFile( file, doubleFormatter.format(aboveValue), doubleFormatter.format(belowValue), cloudMLIp, cloudMLPort, tierName, window, cooldown)); monitoringPlatform.installRules(rules); monitoringPlatform.attachObserver("FrontendCPUUtilization", cloudMLIp, "8001"); monitoringPlatform.attachObserver("AvarageEffectiveResponseTime", cloudMLIp, "8001"); monitoringPlatform.attachObserver("Workload", cloudMLIp, "8001"); } public static String getActualFile(String ip, VirtualMachine vm, String filePath, String folder) throws Exception { Path p = Configuration.getPathToFile(filePath); if (!ip.equals("localhost") && !ip.equals("127.0.0.1")) { String remotePath = vm.getParameter("REMOTE_PATH") + "/" + folder; String newFile = remotePath + "/" + p.toFile().getName(); Ssh.exec(ip, vm, "mkdir -p " + remotePath); Ssh.sendFile(ip, vm, p.toString(), newFile); return newFile; } return p.toString(); } public static String getActualKey(String ip, VirtualMachine vm, String filePath, String folder) throws Exception { String newFile = getActualFile(ip, vm, filePath, folder); if (!ip.equals("localhost") && !ip.equals("127.0.0.1")) Ssh.exec(ip, vm, "chmod 400 " + newFile); return newFile; } public Path getActualDeploymentModel(App app, boolean remotePathIfNecessary) throws Exception { String ipMpl = mpl.getInstances().get(0).getIp(); return getActualDeploymentModel(ipMpl, mpl, this.app, app.cloudMl, app.cloudMlLoadBalancer, loadBalancer, remotePathIfNecessary, useDatabase, database, useOwnLoadBalancer); } private static boolean isInString(String previousString) { int count = 0; int i = previousString.indexOf('"'); while (i > -1) { count++; i = previousString.indexOf('"', i+1); } return count % 2 == 1; } public static String removeCommentedLines(String body) { StringBuilder sb = new StringBuilder(); boolean inComment = false; try (Scanner sc = new Scanner(body)) { while (sc.hasNextLine()) { String line = sc.nextLine(); int i = line.indexOf("//"); int j = line.indexOf("/*"); int k = line.indexOf("*/"); if (inComment && (k == -1 || isInString(line.substring(0, k)))) { continue; } else if (inComment) { line = line.substring(k+2); inComment = false; if (line.trim().length() == 0) continue; } else if (j > -1 && !isInString(line.substring(0, j))) { if (k > -1) { line = line.substring(0, j).concat(line.substring(k+2)); } else { line = line.substring(0, j); inComment = true; } if (line.trim().length() == 0) continue; } else if (i > -1 && !isInString(line.substring(0, i))) { line = line.substring(0, i); if (line.trim().length() == 0) continue; } sb.append(line + "\n"); } } return sb.toString(); } private static String now = String.format("%1$td%1$tm%1$ty%1$tH%1$tM", new Date()); public static Path getActualDeploymentModel(String ipMpl, VirtualMachine mpl, VirtualMachine app, String cloudMl, String cloudMlLoadBalancer, String loadBalancer, boolean remotePathIfNecessary, boolean useDatabase, VirtualMachine database, boolean useOwnLoadBalancer) throws Exception { String body = null; if (useOwnLoadBalancer) body = FileUtils.readFileToString(Configuration.getPathToFile(cloudMlLoadBalancer).toFile()); else body = FileUtils.readFileToString(Configuration.getPathToFile(cloudMl).toFile()); body = removeCommentedLines(body); JSONObject jsonObject = new JSONObject(body); if (jsonObject.has("providers")) { JSONArray array = jsonObject.getJSONArray("providers"); for (int i = 0; i < array.length(); ++i) { JSONObject provider = array.getJSONObject(i); if (provider.has("credentials")) { String credentials = provider.getString("credentials"); String s = null; if (remotePathIfNecessary) s = Test.getActualFile(ipMpl, mpl, credentials, now); else s = Configuration.getPathToFile(credentials).toString(); provider.put("credentials", s); body = body.replaceAll(credentials, s); } } } if (jsonObject.has("vms")) { JSONArray array = jsonObject.getJSONArray("vms"); for (int i = 0; i < array.length(); ++i) { JSONObject vmo = array.getJSONObject(i); if (vmo.has("privateKey")) { String privateKey = vmo.getString("privateKey"); String s = null; if (remotePathIfNecessary) s = Test.getActualKey(ipMpl, mpl, privateKey, now); else s = Configuration.getPathToFile(privateKey).toString(); vmo.put("privateKey", s); body = body.replaceAll(privateKey, s); } } } if (useOwnLoadBalancer) body = String.format(body, RandomStringUtils.randomNumeric(3), app.getImageId(), it.cloud.amazon.Configuration.REGION, app.getParameter("DOWNLOADER").replaceAll("&&", ";"), app.getParameter("INSTALLER").replaceAll("&&", ";"), String.format( app.getParameter("STARTER").replaceAll("&&", ";"), useDatabase ? database.getIps().get(0) : "127.0.0.1", ipMpl, mpl.getParameter("MP_PORT")), "echo DONE", "echo DONE", app.getSize(), app.getParameter("NAME"), loadBalancer ); else body = String.format(body, RandomStringUtils.randomNumeric(3), app.getImageId(), it.cloud.amazon.Configuration.REGION, app.getParameter("DOWNLOADER").replaceAll("&&", ";"), app.getParameter("INSTALLER").replaceAll("&&", ";"), String.format( app.getParameter("STARTER").replaceAll("&&", ";"), useDatabase ? database.getIps().get(0) : "127.0.0.1", ipMpl, mpl.getParameter("MP_PORT")), String.format( app.getParameter("ADD_TO_LOAD_BALANCER").replaceAll("&&", ";"), it.cloud.amazon.Configuration.AWS_CREDENTIALS.getAWSAccessKeyId(), it.cloud.amazon.Configuration.AWS_CREDENTIALS.getAWSSecretKey(), it.cloud.amazon.Configuration.REGION, loadBalancer), String.format( app.getParameter("DEL_FROM_LOAD_BALANCER").replaceAll("&&", ";"), it.cloud.amazon.Configuration.AWS_CREDENTIALS.getAWSAccessKeyId(), it.cloud.amazon.Configuration.AWS_CREDENTIALS.getAWSSecretKey(), it.cloud.amazon.Configuration.REGION, loadBalancer), app.getSize(), app.getParameter("NAME") ); Path p = Files.createTempFile("model", ".json"); FileUtils.writeStringToFile(p.toFile(), body); return p; } private void printSystemStatus() { if (!running || !initialized || (!cloudMlInitialized && (useCloudML || useAutoscalingReasoner))) return; logger.info(mpl.toString()); for (it.cloud.Instance i : mpl.getInstances()) logger.info("- {}", i.getIp()); logger.info(clients.toString()); for (it.cloud.Instance i : clients.getInstances()) logger.info("- {}", i.getIp()); if (!useCloudML && !useAutoscalingReasoner) { logger.info(app.toString()); for (it.cloud.Instance i : app.getInstances()) logger.info("- {}", i.getIp()); } if (useDatabase) { logger.info(database.toString()); for (it.cloud.Instance i : database.getInstances()) logger.info("- {}", i.getIp()); } } private String localPath; public Path runTest(App app, String data, String method) throws Exception { if (!running) throw new RuntimeException("The system isn't running yet!"); if (!initialized) throw new RuntimeException("The system isn't initialized yet!"); if (!cloudMlInitialized && (useCloudML || useAutoscalingReasoner)) throw new RuntimeException("CloudML isn't initialized yet!"); printSystemStatus(); Date date = new Date(); String now = String.format("%1$td%1$tm%1$ty%1$tH%1$tM-%2$s-%3$dx%4$d-%5$s%6$s", date, clients.getSize(), getPeakFromData(data) / clients.getInstancesRunning(), clients.getInstancesRunning(), app.name, (useSDA ? "-" + method : "") + (useCloudML ? "-CloudML" : "")); localPath = "tests" + File.separator + now; File f = new File(localPath); for (int i = 2; f.exists(); ++i) f = new File(localPath + "-" + i); f.mkdirs(); String remotePath = clients.getParameter("REMOTE_PATH") + "/" + now; String protocol = this.app.getParameter("PROTOCOL"); if (protocol == null) protocol = "http"; String port = this.app.getParameter("PORT"); if (port == null) port = "8080"; String server; if (useOwnLoadBalancer) server = loadBalancer; else server = loadBalancer != null ? ElasticLoadBalancing.getLoadBalancerDNS(loadBalancer) : this.app.getIps().get(0); JMeterTest test = new JMeterTest(clients.getParameter("AMI"), clients.getInstancesRunning(), localPath, remotePath, clients.getParameter("JMETER_PATH"), data, server, protocol, port); RunInstance run = test.createModifiedFile(app.getBaseJmxPath()); String javaParameters = clients.getParameter("JAVA_PARAMETERS"); if (javaParameters != null && (javaParameters.trim().length() == 0 || !javaParameters.startsWith("-"))) javaParameters = null; JMeterTest.javaParameters = javaParameters; if (!useCloudML && !useAutoscalingReasoner) if (app.startContainerMonitoringFile != null) for (it.cloud.Instance iapp : this.app.getInstances()) Local.exec(String.format("bash %s %s", Configuration.getPathToFile(app.startContainerMonitoringFile), iapp.getIp())); logger.info("Test starting..."); test.performTest(clients, run); logger.info("Test ended!"); logger.info("Retrieving the files from the instances..."); retrieveFiles(app); logger.info("Retrieving the data from the metrics..."); int period = getSuggestedPeriod(date); if (!useCloudML && !useAutoscalingReasoner) this.app.retrieveMetrics(localPath, date, period, Statistic.Average, null); mpl.retrieveMetrics(localPath, date, period, Statistic.Average, null); clients.retrieveMetrics(localPath, date, period, Statistic.Average, null); if (useDatabase) database.retrieveMetrics(localPath, date, period, Statistic.Average, null); logger.info("Done!"); return Paths.get(localPath, "mpl1", "home", mpl.getParameter("SSH_USER")); } private void retrieveFiles(App app) throws Exception { if (!running || !initialized || localPath == null) return; if (!useCloudML && !useAutoscalingReasoner) { if (app.stopContainerMonitoringFile != null) { int i = 1; for (it.cloud.Instance iapp : this.app.getInstances()) Local.exec(String.format("bash %s %s %s %s", Configuration.getPathToFile(app.stopContainerMonitoringFile), iapp.getIp(), Paths.get(localPath, app.name + i++), Configuration.getPathToFile(this.app.getParameter("KEYPAIR_NAME") + ".pem"))); } this.app.retrieveFiles(localPath, "/home/" + this.app.getParameter("SSH_USER")); } mpl.retrieveFiles(localPath, "/home/" + mpl.getParameter("SSH_USER")); clients.retrieveFiles(localPath, "/home/" + clients.getParameter("SSH_USER")); if (useDatabase) database.retrieveFiles(localPath, "/home/" + database.getParameter("SSH_USER")); if (useOwnLoadBalancer) VirtualMachine.retrieveFiles(loadBalancer, lb, 1, localPath, "/home/" + lb.getParameter("SSH_USER")); } private static int getSuggestedPeriod(Date date) { Date now = new Date(); double diff = now.getTime() - date.getTime(); diff /= 1000 * 60; final int maxData = 1440; double res = diff / maxData; res = Math.ceil(res); if (res < 1) res = 1; return (int)res * 60; } public static int getCores(String resourceName) { switch (resourceName) { case "m3.medium": return 1; case "m3.large": return 2; case "m3.xlarge": return 4; case "m3.2xlarge": return 8; default: return 1; } } public int getCores() { return getCores(app.getSize()); } }
modaclouds-scalingsdatests/src/it/polimi/modaclouds/scalingsdatests/Test.java
package it.polimi.modaclouds.scalingsdatests; import it.cloud.Configuration; import it.cloud.amazon.ec2.AmazonEC2; import it.cloud.amazon.ec2.Instance; import it.cloud.amazon.ec2.VirtualMachine; import it.cloud.amazon.elb.ElasticLoadBalancing; import it.cloud.amazon.elb.ElasticLoadBalancing.Listener; import it.cloud.utils.CloudException; import it.cloud.utils.JMeterTest; import it.cloud.utils.JMeterTest.RunInstance; import it.cloud.utils.Local; import it.cloud.utils.Ssh; import it.polimi.modaclouds.scalingsdatests.sdavalidator.Validator; import it.polimi.modaclouds.scalingsdatests.utils.CloudMLCall; import it.polimi.modaclouds.scalingsdatests.utils.CloudMLCall.CloudML; import it.polimi.modaclouds.scalingsdatests.utils.MonitoringPlatform; import it.polimi.tower4clouds.rules.MonitoringRule; import it.polimi.tower4clouds.rules.MonitoringRules; import java.io.File; import java.io.StringReader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Scanner; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.RandomStringUtils; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.amazonaws.services.cloudwatch.model.Statistic; public class Test { private static final Logger logger = LoggerFactory.getLogger(Test.class); private VirtualMachine mpl; private VirtualMachine app; private VirtualMachine clients; private VirtualMachine database; private VirtualMachine lb; private boolean useDatabase; private boolean useCloudML; private boolean useSDA; private boolean useOwnLoadBalancer; private boolean useAutoscalingReasoner; private boolean running; private boolean initialized; private boolean cloudMlInitialized; private MonitoringPlatform monitoringPlatform; private CloudML cloudML; public static enum App { MIC( "mic", "MPloadModel-MiC", "jmeterTestTemplate-MiC.jmx", "startContainerMonitoring-MiC.sh", "stopContainerMonitoring-MiC.sh", "grep_methodResult-MiC", new String[] { "reg", "save", "answ" }, "MIC", "cloudml.json", "cloudml-LB.json", "cloudmlrules.txt"), HTTPAGENT( "httpagent", "MPloadModel-HTTPAgent", "jmeterTestTemplate-HTTPAgent.jmx", null, "stopContainerMonitoring-HTTPAgent.sh", "grep_methodResult-HTTPAgent", new String[] { "getPage" }, "HTTPAgent", "cloudml.json", "cloudml-LB.json", "cloudmlrules.txt" ); public String name; public String fileModel; public String baseJmx; public String startContainerMonitoringFile; public String stopContainerMonitoringFile; public String grepMethodResult; public String[] methods; public String tierName; public String cloudMl; public String cloudMlLoadBalancer; public String cpuUtilizationRules; private App(String name, String fileModel, String baseJmx, String startContainerMonitoringFile, String stopContainerMonitoringFile, String grepMethodResult, String[] methods, String tierName, String cloudMl, String cloudMlLoadBalancer, String cpuUtilizationRules) { this.name = name; this.fileModel = fileModel; this.baseJmx = baseJmx; this.startContainerMonitoringFile = startContainerMonitoringFile; this.stopContainerMonitoringFile = stopContainerMonitoringFile; this.grepMethodResult = grepMethodResult; this.methods = methods; this.tierName = tierName; this.cloudMl = cloudMl; this.cloudMlLoadBalancer = cloudMlLoadBalancer; this.cpuUtilizationRules = cpuUtilizationRules; } public Path getBaseJmxPath() { return Configuration.getPathToFile(baseJmx); } public static App getFromName(String name) { for (App a : values()) if (a.name.equalsIgnoreCase(name)) return a; return DEFAULT_APP; } } public static enum DemandEstimator { UBR("UBR"), ERPS("ERPS"), CI("CI"); public String name; private DemandEstimator(String name) { this.name = name; } public static DemandEstimator getFromName(String name) { for (DemandEstimator d : values()) if (d.name.equalsIgnoreCase(name)) return d; return DEFAULT_DEMAND_ESTIMATOR; } } public static final App DEFAULT_APP = App.MIC; public static final DemandEstimator DEFAULT_DEMAND_ESTIMATOR = DemandEstimator.ERPS; public static final long ERROR_STATUS_NULL = -1234; public static final int MAX_ATTEMPTS = 5; public static long performTest(String size, int clients, int servers, App app, String data, boolean useDatabase, boolean startAsOnDemand, boolean reuseInstances, boolean leaveInstancesOn, boolean onlyStartMachines, String loadModelFile, int firstInstancesToSkip, String demandEstimator, int window, boolean useSDA, boolean useCloudML, double highCpu, double lowCpu, int cooldown, String loadBalancerIp, boolean useAutoscalingReasoner, String pathToModel, String sshHost, String sshUsername, String sshPassword) throws Exception { String baseJmx = app.getBaseJmxPath().toString(); if (baseJmx == null || !new File(baseJmx).exists()) throw new RuntimeException("The provided base JMX file (" + baseJmx.toString() + ") doesn't exist!"); if (data == null || !new File(data).exists()) throw new RuntimeException("The provided data file (" + data + ") doesn't exist!"); if (loadModelFile != null && !new File(loadModelFile).exists()) loadModelFile = null; if (window <= 0) window = Validator.DEFAULT_WINDOW; long init = System.currentTimeMillis(); Test t = new Test(size, clients, servers, app.name, useDatabase, useSDA, useCloudML, loadBalancerIp != null, useAutoscalingReasoner); if (reuseInstances) t.considerRunningMachines(); t.startMachines(startAsOnDemand); if (loadBalancerIp != null) t.loadBalancer = loadBalancerIp; else t.createLoadBalancer(); Path path = null; Exception thrown = null; try { t.initSystem(loadModelFile, demandEstimator, window, pathToModel, sshHost, sshUsername, sshPassword); if (onlyStartMachines) return -1; boolean performTheTest = false; if (useCloudML || useAutoscalingReasoner) { String status; int attempt = 0; do { t.initCloudML(app); status = t.getTierStatus(app.tierName); attempt++; } while ((status == null || status.equals("null")) && attempt < MAX_ATTEMPTS); if (status != null && !status.equals("null")) { if (useCloudML) t.addCPUUtilizationMonitoringRules(app.cpuUtilizationRules, app.tierName, highCpu, lowCpu, window, cooldown); performTheTest = true; } else { logger.error("CloudML isn't working (the statuses are null)."); performTheTest = false; } } else { performTheTest = true; } if (performTheTest) path = t.runTest(app, data, demandEstimator); } catch (Exception e) { logger.error("Error while performing the test.", e); thrown = e; } if (thrown != null) { try { Date date = new Date(); String now = String.format("%1$td%1$tm%1$ty%1$tH%1$tM-%2$s-%3$dx%4$d-%5$s%6$s-broken", date, size, getPeakFromData(data) / clients, clients, app.name, (useSDA ? "-" + demandEstimator : "") + (useCloudML ? "-CloudML" : "") + (useAutoscalingReasoner ? "-AR" : "")); t.localPath = "tests" + File.separator + now; t.retrieveFiles(app); } catch (Exception e) { logger.error("Error while trying to retrieve the files after an error.", e); } } if (!leaveInstancesOn) { if (useCloudML) { t.stopCloudMLInstances(); t.terminateCloudMLDaemon(); } if (loadBalancerIp == null) t.destroyLoadBalancer(); t.stopMachines(); } if (useSDA) Validator.perform(path, t.getCores(), firstInstancesToSkip, app, window); if (thrown != null) throw thrown; return System.currentTimeMillis() - init; } public Test(String size, int clients, int servers, String app, boolean useDatabase, boolean useSDA, boolean useCloudML, boolean useOwnLoadBalancer, boolean useAutoscalingReasoner) throws CloudException { if (clients <= 0) throw new RuntimeException("You need at least 1 client!"); if (servers <= 0) throw new RuntimeException("You need at least 1 server!"); mpl = VirtualMachine.getVM("mpl", size, 1); this.app = VirtualMachine.getVM(app, size, servers); this.clients = VirtualMachine.getVM("client", size, clients); this.useDatabase = useDatabase; if (useDatabase) database = VirtualMachine.getVM("database", size, 1); running = false; initialized = false; cloudMlInitialized = false; this.useCloudML = useCloudML; this.useSDA = useSDA; this.useOwnLoadBalancer = useOwnLoadBalancer; if (useOwnLoadBalancer) lb = VirtualMachine.getVM("lb"); otherThreads = new ArrayList<Thread>(); this.useAutoscalingReasoner = useAutoscalingReasoner; } private String loadBalancer; public static final String LB_BASENAME = "ScalingSDATests"; private void createLoadBalancer() { if ((app.getInstancesNeeded() <= 1 && (!useCloudML || !useAutoscalingReasoner)) || useOwnLoadBalancer) return; if (loadBalancer != null) throw new RuntimeException( "You've already created a load balancer!"); loadBalancer = LB_BASENAME + RandomStringUtils.randomNumeric(3); ElasticLoadBalancing.createNewLoadBalancer(loadBalancer, new Listener("HTTP", Integer.parseInt(app.getParameter("PORT")))); } private void destroyLoadBalancer() { if ((app.getInstancesNeeded() <= 1 && (!useCloudML || !useAutoscalingReasoner)) || useOwnLoadBalancer) return; if (loadBalancer == null) throw new RuntimeException( "You've still to create a load balancer!"); ElasticLoadBalancing.deleteLoadBalancer(loadBalancer); loadBalancer = null; } private String getTierStatus(String tier) { cloudML.updateStatus(); return cloudML.getTierStatus(tier); } public void startMachines(boolean startAsOnDemand) { if (running) throw new RuntimeException("The system is already running!"); logger.info("Starting all the machines..."); if (!startAsOnDemand) { mpl.spotRequest(); if (!useCloudML && !useAutoscalingReasoner) app.spotRequest(); clients.spotRequest(); if (useDatabase) database.spotRequest(); } else { mpl.onDemandRequest(); if (!useCloudML && !useAutoscalingReasoner) app.onDemandRequest(); clients.onDemandRequest(); if (useDatabase) database.onDemandRequest(); } mpl.waitUntilRunning(); if (!useCloudML && !useAutoscalingReasoner) app.waitUntilRunning(); clients.waitUntilRunning(); if (useDatabase) database.waitUntilRunning(); mpl.setNameToInstances(mpl.getParameter("NAME")); if (!useCloudML && !useAutoscalingReasoner) app.setNameToInstances(app.getParameter("NAME")); clients.setNameToInstances(clients.getParameter("NAME")); if (useDatabase) database.setNameToInstances(database.getParameter("NAME")); mpl.getInstances().get(0).waitUntilSshAvailable(); if (!useCloudML && !useAutoscalingReasoner) app.getInstances().get(0).waitUntilSshAvailable(); if (useDatabase) database.getInstances().get(0).waitUntilSshAvailable(); logger.info("All the machines are now running!"); running = true; } public void considerRunningMachines() { considerRunningMachines(true); } public void considerRunningMachines(boolean rebootMachines) { if (running) throw new RuntimeException("The system is already running!"); logger.info("Searching for running machines..."); AmazonEC2 ec2 = new AmazonEC2(); ec2.addRunningInstances(mpl); if (!useCloudML && !useAutoscalingReasoner) ec2.addRunningInstances(app); ec2.addRunningInstances(clients); if (useDatabase) ec2.addRunningInstances(database); if (rebootMachines) { mpl.reboot(); if (!useCloudML && !useAutoscalingReasoner) app.reboot(); clients.reboot(); if (useDatabase) database.reboot(); } logger.info("Added running instances!"); } public void stopMachines() { if (!running) throw new RuntimeException("The system isn't running yet!"); logger.info("Stopping all the machines..."); if (!Boolean.parseBoolean(mpl.getParameter("LEAVE_INSTANCES_ON"))) mpl.terminate(); if (!useCloudML && !useAutoscalingReasoner && !Boolean.parseBoolean(app.getParameter("LEAVE_INSTANCES_ON"))) app.terminate(); if (!Boolean.parseBoolean(clients.getParameter("LEAVE_INSTANCES_ON"))) clients.terminate(); if (useDatabase && !Boolean.parseBoolean(database.getParameter("LEAVE_INSTANCES_ON"))) database.terminate(); logger.info("All the machines have been shutted down!"); running = false; initialized = false; localPath = null; } public void stopCloudMLInstances() { if (!running) throw new RuntimeException("The system isn't running yet!"); if (Boolean.parseBoolean(app.getParameter("LEAVE_INSTANCES_ON"))) { logger.info("Leaving the CLoudML instances on as requested..."); return; } logger.info("Stopping CloudML instances..."); cloudML.terminateAllInstances(); } public void terminateCloudMLDaemon() throws Exception { if (!running) throw new RuntimeException("The system isn't running yet!"); logger.info("Stopping the CloudML daemon..."); String cloudMLIp = mpl.getInstances().get(0).getIp(); String cloudMLPort = mpl.getParameter("CLOUDML_PORT"); Ssh.execInBackground(cloudMLIp, mpl, String.format(mpl.getParameter("CLOUDML_STARTER"), cloudMLPort + " -stop")); } private List<Thread> otherThreads; public void initSystem(String loadModelFile, String demandEstimator, int window, String pathToModel, String sshHost, String sshUsername, String sshPassword) throws Exception { if (!running) throw new RuntimeException("The system isn't running yet!"); if (initialized) throw new RuntimeException("The system is already initialized!"); logger.info("Deleting the files set for removal before the test and upgrading the scripts..."); if (!useCloudML && !useAutoscalingReasoner) { app.deleteFiles(); app.execDownloader(); } mpl.deleteFiles(); Instance impl = (Instance)mpl.getInstances().get(0); impl.execDownloader(); clients.deleteFiles(); clients.execDownloader(); clients.execUpdater(); if (useDatabase) database.deleteFiles(); if (useOwnLoadBalancer) { logger.info("Updating and starting the load balancer..."); Ssh.exec(loadBalancer, lb, lb.getParameter("DOWNLOADER")); Ssh.exec(loadBalancer, lb, lb.getParameter("STOPPER")); VirtualMachine.deleteFiles(loadBalancer, lb); Ssh.exec(loadBalancer, lb, lb.getParameter("UPDATER")); try { Thread.sleep(10000); } catch (Exception e) { } Ssh.exec(loadBalancer, lb, lb.getParameter("STARTER")); } logger.info("Initializing the system..."); String mplIp = impl.getIp(); int mplPort = Integer.parseInt(mpl.getParameter("MP_PORT")); impl.execUpdater(); impl.exec(String.format(mpl.getParameter("STARTER"), mplIp)); try { Thread.sleep(10000); } catch (Exception e) { } monitoringPlatform = new MonitoringPlatform(mplIp, mplPort); int cores = getCores(); Local.exec(String.format("bash %s %s %s %d %s %d %b", loadModelFile, impl.getIp(), impl.getIp(), cores, demandEstimator, window, useSDA)); try { Thread.sleep(10000); } catch (Exception e) { } if (useSDA) { otherThreads.add(Ssh.execInBackground(impl, String.format( mpl.getParameter("SDA_STARTER"), mplIp))); try { Thread.sleep(10000); } catch (Exception e) { } } if (!useCloudML && !useAutoscalingReasoner) for (it.cloud.Instance iapp : app.getInstances()) { iapp.execUpdater(); iapp.exec(String.format( app.getParameter("STARTER"), useDatabase ? database.getIps().get(0) : "127.0.0.1", mplIp )); try { Thread.sleep(10000); } catch (Exception e) { } if (app.getInstancesNeeded() > 1 && loadBalancer != null) { iapp.exec(String.format(app.getParameter("ADD_TO_LOAD_BALANCER"), loadBalancer)); try { Thread.sleep(10000); } catch (Exception e) { } } } if (useAutoscalingReasoner) { String remotePathToModel = getActualFile(impl.getIp(), mpl, pathToModel, "autoscalingReasoner"); impl.exec(String.format(mpl.getParameter("AR_STARTER"), impl.getIp(), mpl.getParameter("AR_PORT"), remotePathToModel, sshHost, sshUsername, sshPassword, impl.getIp(), mpl.getParameter("CLOUDML_PORT"))); try { Thread.sleep(10000); } catch (Exception e) { } } logger.info("System initialized!"); initialized = true; } public static int getPeakFromData(String data) { int peak = 0; try (Scanner sc = new Scanner(Configuration.getInputStream(data))) { while (sc.hasNextLine()) { String line = sc.nextLine(); int value; try { value = Integer.parseInt(line.split(" ")[0]); } catch (Exception e) { continue; } if (value > peak) peak = value; } } catch (Exception e) { } return peak; } public void initCloudML(App app) throws Exception { if (!running) throw new RuntimeException("The system isn't running yet!"); if (!initialized) throw new RuntimeException("The system isn't initialized yet!"); if (cloudMlInitialized) { stopCloudMLInstances(); terminateCloudMLDaemon(); try { Thread.sleep(10000); } catch (Exception e) { } cloudMlInitialized = false; } logger.info("Initializing CloudML..."); Instance impl = (Instance)mpl.getInstances().get(0); String mplIp = impl.getIp(); String cloudMLIp = mplIp; int cloudMLPort = Integer.parseInt(mpl.getParameter("CLOUDML_PORT")); logger.info("Trying connecting to the CloudML daemon..."); try { cloudML = CloudMLCall.getCloudML(cloudMLIp, cloudMLPort); } catch (Exception e) { logger.info("The daemon wasn't running, starting it..."); Ssh.execInBackground(cloudMLIp, mpl, String.format(mpl.getParameter("CLOUDML_STARTER"), Integer.toString(cloudMLPort))); boolean goOn = true; while (goOn) { try { Thread.sleep(10000); } catch (Exception e1) { } try { cloudML = CloudMLCall.getCloudML(cloudMLIp, cloudMLPort); goOn = false; } catch (Exception e1) { logger.warn("Trying again to connect to the CloudML daemon in 10 seconds..."); } } } logger.info("Connected to the CloudML daemon!"); cloudML.deploy(getActualDeploymentModel(app, true).toFile()); logger.info("CloudML initialized!"); cloudMlInitialized = true; } private static List<MonitoringRule> getMonitoringRulesFromFile(String fileName, Object... substitutions) throws Exception { String tmp = FileUtils.readFileToString(Configuration.getPathToFile(fileName).toFile()); if (substitutions.length > 0) tmp = String.format(tmp, substitutions); if (tmp.indexOf("<monitoringRules") == -1) tmp = "<monitoringRules xmlns=\"http://www.modaclouds.eu/xsd/1.0/monitoring_rules_schema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.modaclouds.eu/xsd/1.0/monitoring_rules_schema\">" + tmp + "</monitoringRules>"; JAXBContext context = JAXBContext.newInstance(MonitoringRules.class); Unmarshaller unmarshaller = context.createUnmarshaller(); MonitoringRules rules = (MonitoringRules) unmarshaller.unmarshal(new StringReader(tmp)); return rules.getMonitoringRules(); } private static DecimalFormat doubleFormatter = doubleFormatter(); private static DecimalFormat doubleFormatter() { DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.getDefault()); otherSymbols.setDecimalSeparator('.'); DecimalFormat myFormatter = new DecimalFormat("0.0#########", otherSymbols); return myFormatter; } public void addCPUUtilizationMonitoringRules(String file, String tierName, double aboveValue, double belowValue, int window, int cooldown) throws Exception { if (aboveValue > 1.0) aboveValue = 1.0; if (aboveValue <= 0.0) aboveValue = Main.DEFAULT_HIGH_CPU; if (belowValue <= 0.0) belowValue = 0.0; if (belowValue >= 1.0) belowValue = Main.DEFAULT_LOW_CPU; String cloudMLIp = mpl.getInstances().get(0).getIp(); int cloudMLPort = Integer.parseInt(mpl.getParameter("CLOUDML_PORT")); MonitoringRules rules = new MonitoringRules(); rules.getMonitoringRules() .addAll(getMonitoringRulesFromFile( file, doubleFormatter.format(aboveValue), doubleFormatter.format(belowValue), cloudMLIp, cloudMLPort, tierName, window, cooldown)); monitoringPlatform.installRules(rules); monitoringPlatform.attachObserver("FrontendCPUUtilization", cloudMLIp, "8001"); monitoringPlatform.attachObserver("AvarageEffectiveResponseTime", cloudMLIp, "8001"); monitoringPlatform.attachObserver("Workload", cloudMLIp, "8001"); } public static String getActualFile(String ip, VirtualMachine vm, String filePath, String folder) throws Exception { Path p = Configuration.getPathToFile(filePath); if (!ip.equals("localhost") && !ip.equals("127.0.0.1")) { String remotePath = vm.getParameter("REMOTE_PATH") + "/" + folder; String newFile = remotePath + "/" + p.toFile().getName(); Ssh.exec(ip, vm, "mkdir -p " + remotePath); Ssh.sendFile(ip, vm, p.toString(), newFile); return newFile; } return p.toString(); } public static String getActualKey(String ip, VirtualMachine vm, String filePath, String folder) throws Exception { String newFile = getActualFile(ip, vm, filePath, folder); if (!ip.equals("localhost") && !ip.equals("127.0.0.1")) Ssh.exec(ip, vm, "chmod 400 " + newFile); return newFile; } public Path getActualDeploymentModel(App app, boolean remotePathIfNecessary) throws Exception { String ipMpl = mpl.getInstances().get(0).getIp(); return getActualDeploymentModel(ipMpl, mpl, this.app, app.cloudMl, app.cloudMlLoadBalancer, loadBalancer, remotePathIfNecessary, useDatabase, database, useOwnLoadBalancer); } private static boolean isInString(String previousString) { int count = 0; int i = previousString.indexOf('"'); while (i > -1) { count++; i = previousString.indexOf('"', i+1); } return count % 2 == 1; } public static String removeCommentedLines(String body) { StringBuilder sb = new StringBuilder(); boolean inComment = false; try (Scanner sc = new Scanner(body)) { while (sc.hasNextLine()) { String line = sc.nextLine(); int i = line.indexOf("//"); int j = line.indexOf("/*"); int k = line.indexOf("*/"); if (inComment && (k == -1 || isInString(line.substring(0, k)))) { continue; } else if (inComment) { line = line.substring(k+2); inComment = false; if (line.trim().length() == 0) continue; } else if (j > -1 && !isInString(line.substring(0, j))) { if (k > -1) { line = line.substring(0, j).concat(line.substring(k+2)); } else { line = line.substring(0, j); inComment = true; } if (line.trim().length() == 0) continue; } else if (i > -1 && !isInString(line.substring(0, i))) { line = line.substring(0, i); if (line.trim().length() == 0) continue; } sb.append(line + "\n"); } } return sb.toString(); } private static String now = String.format("%1$td%1$tm%1$ty%1$tH%1$tM", new Date()); public static Path getActualDeploymentModel(String ipMpl, VirtualMachine mpl, VirtualMachine app, String cloudMl, String cloudMlLoadBalancer, String loadBalancer, boolean remotePathIfNecessary, boolean useDatabase, VirtualMachine database, boolean useOwnLoadBalancer) throws Exception { String body = null; if (useOwnLoadBalancer) body = FileUtils.readFileToString(Configuration.getPathToFile(cloudMlLoadBalancer).toFile()); else body = FileUtils.readFileToString(Configuration.getPathToFile(cloudMl).toFile()); body = removeCommentedLines(body); JSONObject jsonObject = new JSONObject(body); if (jsonObject.has("providers")) { JSONArray array = jsonObject.getJSONArray("providers"); for (int i = 0; i < array.length(); ++i) { JSONObject provider = array.getJSONObject(i); if (provider.has("credentials")) { String credentials = provider.getString("credentials"); String s = null; if (remotePathIfNecessary) s = Test.getActualFile(ipMpl, mpl, credentials, now); else s = Configuration.getPathToFile(credentials).toString(); provider.put("credentials", s); body = body.replaceAll(credentials, s); } } } if (jsonObject.has("vms")) { JSONArray array = jsonObject.getJSONArray("vms"); for (int i = 0; i < array.length(); ++i) { JSONObject vmo = array.getJSONObject(i); if (vmo.has("privateKey")) { String privateKey = vmo.getString("privateKey"); String s = null; if (remotePathIfNecessary) s = Test.getActualKey(ipMpl, mpl, privateKey, now); else s = Configuration.getPathToFile(privateKey).toString(); vmo.put("privateKey", s); body = body.replaceAll(privateKey, s); } } } if (useOwnLoadBalancer) body = String.format(body, RandomStringUtils.randomNumeric(3), app.getImageId(), it.cloud.amazon.Configuration.REGION, app.getParameter("DOWNLOADER").replaceAll("&&", ";"), app.getParameter("INSTALLER").replaceAll("&&", ";"), String.format( app.getParameter("STARTER").replaceAll("&&", ";"), useDatabase ? database.getIps().get(0) : "127.0.0.1", ipMpl, mpl.getParameter("MP_PORT")), "echo DONE", "echo DONE", app.getSize(), app.getParameter("NAME"), loadBalancer ); else body = String.format(body, RandomStringUtils.randomNumeric(3), app.getImageId(), it.cloud.amazon.Configuration.REGION, app.getParameter("DOWNLOADER").replaceAll("&&", ";"), app.getParameter("INSTALLER").replaceAll("&&", ";"), String.format( app.getParameter("STARTER").replaceAll("&&", ";"), useDatabase ? database.getIps().get(0) : "127.0.0.1", ipMpl, mpl.getParameter("MP_PORT")), String.format( app.getParameter("ADD_TO_LOAD_BALANCER").replaceAll("&&", ";"), it.cloud.amazon.Configuration.AWS_CREDENTIALS.getAWSAccessKeyId(), it.cloud.amazon.Configuration.AWS_CREDENTIALS.getAWSSecretKey(), it.cloud.amazon.Configuration.REGION, loadBalancer), String.format( app.getParameter("DEL_FROM_LOAD_BALANCER").replaceAll("&&", ";"), it.cloud.amazon.Configuration.AWS_CREDENTIALS.getAWSAccessKeyId(), it.cloud.amazon.Configuration.AWS_CREDENTIALS.getAWSSecretKey(), it.cloud.amazon.Configuration.REGION, loadBalancer), app.getSize(), app.getParameter("NAME") ); Path p = Files.createTempFile("model", ".json"); FileUtils.writeStringToFile(p.toFile(), body); return p; } private void printSystemStatus() { if (!running || !initialized || (!cloudMlInitialized && (useCloudML || useAutoscalingReasoner))) return; logger.info(mpl.toString()); for (it.cloud.Instance i : mpl.getInstances()) logger.info("- {}", i.getIp()); logger.info(clients.toString()); for (it.cloud.Instance i : clients.getInstances()) logger.info("- {}", i.getIp()); if (!useCloudML && !useAutoscalingReasoner) { logger.info(app.toString()); for (it.cloud.Instance i : app.getInstances()) logger.info("- {}", i.getIp()); } if (useDatabase) { logger.info(database.toString()); for (it.cloud.Instance i : database.getInstances()) logger.info("- {}", i.getIp()); } } private String localPath; public Path runTest(App app, String data, String method) throws Exception { if (!running) throw new RuntimeException("The system isn't running yet!"); if (!initialized) throw new RuntimeException("The system isn't initialized yet!"); if (!cloudMlInitialized && (useCloudML || useAutoscalingReasoner)) throw new RuntimeException("CloudML isn't initialized yet!"); printSystemStatus(); Date date = new Date(); String now = String.format("%1$td%1$tm%1$ty%1$tH%1$tM-%2$s-%3$dx%4$d-%5$s%6$s", date, clients.getSize(), getPeakFromData(data) / clients.getInstancesRunning(), clients.getInstancesRunning(), app.name, (useSDA ? "-" + method : "") + (useCloudML ? "-CloudML" : "")); localPath = "tests" + File.separator + now; File f = new File(localPath); for (int i = 2; f.exists(); ++i) f = new File(localPath + "-" + i); f.mkdirs(); String remotePath = clients.getParameter("REMOTE_PATH") + "/" + now; String protocol = this.app.getParameter("PROTOCOL"); if (protocol == null) protocol = "http"; String port = this.app.getParameter("PORT"); if (port == null) port = "8080"; String server; if (useOwnLoadBalancer) server = loadBalancer; else server = loadBalancer != null ? ElasticLoadBalancing.getLoadBalancerDNS(loadBalancer) : this.app.getIps().get(0); JMeterTest test = new JMeterTest(clients.getParameter("AMI"), clients.getInstancesRunning(), localPath, remotePath, clients.getParameter("JMETER_PATH"), data, server, protocol, port); RunInstance run = test.createModifiedFile(app.getBaseJmxPath()); String javaParameters = clients.getParameter("JAVA_PARAMETERS"); if (javaParameters != null && (javaParameters.trim().length() == 0 || !javaParameters.startsWith("-"))) javaParameters = null; JMeterTest.javaParameters = javaParameters; if (!useCloudML && !useAutoscalingReasoner) if (app.startContainerMonitoringFile != null) for (it.cloud.Instance iapp : this.app.getInstances()) Local.exec(String.format("bash %s %s", Configuration.getPathToFile(app.startContainerMonitoringFile), iapp.getIp())); logger.info("Test starting..."); test.performTest(clients, run); logger.info("Test ended!"); logger.info("Retrieving the files from the instances..."); retrieveFiles(app); logger.info("Retrieving the data from the metrics..."); int period = getSuggestedPeriod(date); if (!useCloudML && !useAutoscalingReasoner) this.app.retrieveMetrics(localPath, date, period, Statistic.Average, null); mpl.retrieveMetrics(localPath, date, period, Statistic.Average, null); clients.retrieveMetrics(localPath, date, period, Statistic.Average, null); if (useDatabase) database.retrieveMetrics(localPath, date, period, Statistic.Average, null); logger.info("Done!"); return Paths.get(localPath, "mpl1", "home", mpl.getParameter("SSH_USER")); } private void retrieveFiles(App app) throws Exception { if (!running || !initialized || localPath == null) return; if (!useCloudML && !useAutoscalingReasoner) { if (app.stopContainerMonitoringFile != null) { int i = 1; for (it.cloud.Instance iapp : this.app.getInstances()) Local.exec(String.format("bash %s %s %s %s", Configuration.getPathToFile(app.stopContainerMonitoringFile), iapp.getIp(), Paths.get(localPath, app.name + i++), Configuration.getPathToFile(this.app.getParameter("KEYPAIR_NAME") + ".pem"))); } this.app.retrieveFiles(localPath, "/home/" + this.app.getParameter("SSH_USER")); } mpl.retrieveFiles(localPath, "/home/" + mpl.getParameter("SSH_USER")); clients.retrieveFiles(localPath, "/home/" + clients.getParameter("SSH_USER")); if (useDatabase) database.retrieveFiles(localPath, "/home/" + database.getParameter("SSH_USER")); if (useOwnLoadBalancer) VirtualMachine.retrieveFiles(loadBalancer, lb, 1, localPath, "/home/" + lb.getParameter("SSH_USER")); } private static int getSuggestedPeriod(Date date) { Date now = new Date(); double diff = now.getTime() - date.getTime(); diff /= 1000 * 60; final int maxData = 1440; double res = diff / maxData; res = Math.ceil(res); if (res < 1) res = 1; return (int)res * 60; } public static int getCores(String resourceName) { switch (resourceName) { case "m3.medium": return 1; case "m3.large": return 2; case "m3.xlarge": return 4; case "m3.2xlarge": return 8; default: return 1; } } public int getCores() { return getCores(app.getSize()); } }
Bugfix
modaclouds-scalingsdatests/src/it/polimi/modaclouds/scalingsdatests/Test.java
Bugfix
<ide><path>odaclouds-scalingsdatests/src/it/polimi/modaclouds/scalingsdatests/Test.java <ide> iapp.exec(String.format( <ide> app.getParameter("STARTER"), <ide> useDatabase ? database.getIps().get(0) : "127.0.0.1", <del> mplIp <add> mplIp, <add> mpl.getParameter("MP_PORT") <ide> )); <ide> <ide> try { Thread.sleep(10000); } catch (Exception e) { }
Java
apache-2.0
cb33ecf7442715ef44efababaa2c01a5a7fa624f
0
HTML5MSc/HTML5Parser,carlos-anaya/HTML5Parser
package com.html5parser.algorithms; import java.util.Stack; import org.w3c.dom.Element; import com.html5parser.classes.InsertionMode; import com.html5parser.classes.ParserContext; import com.html5parser.factories.InsertionModeFactory; public class ResetTheInsertionModeAppropriately { public static void Run(ParserContext parserContext) { if(parserContext.isFlagHTMLFragmentParser()) Run(parserContext, parserContext.getHtmlFragmentContext()); else Run(parserContext, null); } public static void Run(ParserContext parserContext, Element context) { InsertionModeFactory factory = InsertionModeFactory.getInstance(); Stack<Element> openElements = new Stack<Element>(); openElements.addAll(parserContext.getOpenElements()); // 1 Let last be false. Boolean last = false; // 2 Let node be the last node in the stack of open elements. Element node = openElements.pop(); // 3 Loop: If node is the first node in the stack of open elements, then // set last to true, and, if the parser was originally created as part // of the HTML fragment parsing algorithm (fragment case) set node to // the context element. do { if (openElements.isEmpty()) { last = true; // if fragment case, node = context element if (context != null) { node = context; } } switch (node.getNodeName()) { // 4 If node is a select element, run these substeps: case "select": Boolean done = false; // 1 If last is true, jump to the step below labeled done. if (last) done = true; else { // 2 Let ancestor be node. Element ancestor = node; // 3 Loop: If ancestor is the first node in the stack of // open // elements, jump to the step below labeled done. do { if (openElements.isEmpty()) done = true; // 4 Let ancestor be the node before ancestor in the // stack of open elements. ancestor = openElements.pop(); // 5 If ancestor is a template node, jump to the step // below // labeled done. if (ancestor.getNodeName().equals("template")) done = true; // 6 If ancestor is a table node, switch the insertion // mode // to "in select in table" and abort these steps. if (ancestor.getNodeName().equals("table")) { parserContext .setInsertionMode(factory .getInsertionMode(InsertionMode.in_select_in_table)); return; } // 7 Jump back to the step labeled loop. } while (!done); } // 8 Done: Switch the insertion mode to "in select" and // abort these steps. if (done) { parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_select)); return; } break; // 5 If node is a td or th element and last is false, then // switch // the insertion mode to "in cell" and abort these steps. case "td": case "th": if (!last) { parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_cell)); return; } else { parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_body)); return; } // 6 If node is a tr element, then switch the insertion mode to // "in row" and abort these steps. case "tr": parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_row)); return; // 7 If node is a tbody, thead, or tfoot element, then switch // the insertion mode to "in table body" and abort these steps. case "tbody": case "thead": case "tfoot": parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_table_body)); return; // 8 If node is a caption element, then switch the insertion // mode to "in caption" and abort these steps. case "caption": parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_caption)); return; // 9 If node is a colgroup element, then switch the insertion // mode to "in column group" and abort these steps. case "colgroup": parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_column_group)); return; // 10 If node is a table element, then switch the insertion mode // to "in table" and abort these steps. case "table": parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_table)); return; // 11 If node is a template element, then switch the insertion // mode to the // current template insertion mode and abort these steps. case "template": parserContext.setInsertionMode(parserContext .getCurrentTemplateInsertionMode()); return; // 12 If node is a head element and last is true, then switch // the insertion mode to "in body" ("in body"! not "in head"!) // and abort these steps. (fragment case) // 13 If node is a head element and last is false, then switch // the insertion mode to "in head" and abort these steps. case "head": if (last) parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_body)); else parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_head)); return; // 14 If node is a body element, then switch the insertion mode // to "in body" and abort these steps. case "body": parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_body)); return; // 15 If node is a frameset element, then switch the insertion // mode to "in frameset" and abort these steps. (fragment case) case "frameset": parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_frameset)); return; // 16 If node is an html element, run these substeps: case "html": // 1 If the head element pointer is null, switch the insertion // mode to "before head" and abort these steps. (fragment case) if (parserContext.getHeadElementPointer() == null) parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.before_head)); // 2 Otherwise, the head element pointer is not null, switch the // insertion mode to "after head" and abort these steps. else parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.after_head)); return; // 17 If last is true, then switch the insertion mode to // "in body" and // abort these steps. (fragment case) default: if (last) { parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_body)); return; } break; } // 18 Let node now be the node before node in the stack of open // elements. // 19 Return to the step labeled loop. node = openElements.pop(); } while (true); } }
Code/src/main/java/com/html5parser/algorithms/ResetTheInsertionModeAppropriately.java
package com.html5parser.algorithms; import java.util.Stack; import org.w3c.dom.Element; import com.html5parser.classes.InsertionMode; import com.html5parser.classes.ParserContext; import com.html5parser.factories.InsertionModeFactory; public class ResetTheInsertionModeAppropriately { public static void Run(ParserContext parserContext) { Run(parserContext, null); } public static void Run(ParserContext parserContext, Element context) { InsertionModeFactory factory = InsertionModeFactory.getInstance(); Stack<Element> openElements = new Stack<Element>(); openElements.addAll(parserContext.getOpenElements()); // 1 Let last be false. Boolean last = false; // 2 Let node be the last node in the stack of open elements. Element node = openElements.pop(); // 3 Loop: If node is the first node in the stack of open elements, then // set last to true, and, if the parser was originally created as part // of the HTML fragment parsing algorithm (fragment case) set node to // the context element. do { if (openElements.isEmpty()) { last = true; // if fragment case, node = context element if (context != null) { node = context; } } switch (node.getNodeName()) { // 4 If node is a select element, run these substeps: case "select": Boolean done = false; // 1 If last is true, jump to the step below labeled done. if (last) done = true; else { // 2 Let ancestor be node. Element ancestor = node; // 3 Loop: If ancestor is the first node in the stack of // open // elements, jump to the step below labeled done. do { if (openElements.isEmpty()) done = true; // 4 Let ancestor be the node before ancestor in the // stack of open elements. ancestor = openElements.pop(); // 5 If ancestor is a template node, jump to the step // below // labeled done. if (ancestor.getNodeName().equals("template")) done = true; // 6 If ancestor is a table node, switch the insertion // mode // to "in select in table" and abort these steps. if (ancestor.getNodeName().equals("table")) { parserContext .setInsertionMode(factory .getInsertionMode(InsertionMode.in_select_in_table)); return; } // 7 Jump back to the step labeled loop. } while (!done); } // 8 Done: Switch the insertion mode to "in select" and // abort these steps. if (done) { parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_select)); return; } break; // 5 If node is a td or th element and last is false, then // switch // the insertion mode to "in cell" and abort these steps. case "td": case "th": if (!last) { parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_cell)); return; } else { parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_body)); return; } // 6 If node is a tr element, then switch the insertion mode to // "in row" and abort these steps. case "tr": parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_row)); return; // 7 If node is a tbody, thead, or tfoot element, then switch // the insertion mode to "in table body" and abort these steps. case "tbody": case "thead": case "tfoot": parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_table_body)); return; // 8 If node is a caption element, then switch the insertion // mode to "in caption" and abort these steps. case "caption": parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_caption)); return; // 9 If node is a colgroup element, then switch the insertion // mode to "in column group" and abort these steps. case "colgroup": parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_column_group)); return; // 10 If node is a table element, then switch the insertion mode // to "in table" and abort these steps. case "table": parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_table)); return; // 11 If node is a template element, then switch the insertion // mode to the // current template insertion mode and abort these steps. case "template": parserContext.setInsertionMode(parserContext .getCurrentTemplateInsertionMode()); return; // 12 If node is a head element and last is true, then switch // the insertion mode to "in body" ("in body"! not "in head"!) // and abort these steps. (fragment case) // 13 If node is a head element and last is false, then switch // the insertion mode to "in head" and abort these steps. case "head": if (last) parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_body)); else parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_head)); return; // 14 If node is a body element, then switch the insertion mode // to "in body" and abort these steps. case "body": parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_body)); return; // 15 If node is a frameset element, then switch the insertion // mode to "in frameset" and abort these steps. (fragment case) case "frameset": parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_frameset)); return; // 16 If node is an html element, run these substeps: case "html": // 1 If the head element pointer is null, switch the insertion // mode to "before head" and abort these steps. (fragment case) if (parserContext.getHeadElementPointer() == null) parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.before_head)); // 2 Otherwise, the head element pointer is not null, switch the // insertion mode to "after head" and abort these steps. else parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.after_head)); return; // 17 If last is true, then switch the insertion mode to // "in body" and // abort these steps. (fragment case) default: if (last) { parserContext.setInsertionMode(factory .getInsertionMode(InsertionMode.in_body)); return; } break; } // 18 Let node now be the node before node in the stack of open // elements. // 19 Return to the step labeled loop. node = openElements.pop(); } while (true); } }
Fix fragment context error
Code/src/main/java/com/html5parser/algorithms/ResetTheInsertionModeAppropriately.java
Fix fragment context error
<ide><path>ode/src/main/java/com/html5parser/algorithms/ResetTheInsertionModeAppropriately.java <ide> public class ResetTheInsertionModeAppropriately { <ide> <ide> public static void Run(ParserContext parserContext) { <del> Run(parserContext, null); <add> if(parserContext.isFlagHTMLFragmentParser()) <add> Run(parserContext, parserContext.getHtmlFragmentContext()); <add> else <add> Run(parserContext, null); <ide> } <ide> <ide> public static void Run(ParserContext parserContext, Element context) {
Java
lgpl-2.1
7c1e261199a69bc92f4f0bbd774725555139cce4
0
xkfz007/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,krichter722/vlc,xkfz007/vlc,shyamalschandra/vlc,shyamalschandra/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,shyamalschandra/vlc,xkfz007/vlc,xkfz007/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,krichter722/vlc,krichter722/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,shyamalschandra/vlc,krichter722/vlc,krichter722/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.1,xkfz007/vlc,shyamalschandra/vlc,vlc-mirror/vlc,vlc-mirror/vlc,vlc-mirror/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,jomanmuk/vlc-2.1,krichter722/vlc,shyamalschandra/vlc,vlc-mirror/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2
/***************************************************************************** * JVLC.java: Main Java Class, represents a libvlc_instance_t object ***************************************************************************** * * Copyright (C) 1998-2008 the VideoLAN team * * Author: Filippo Carone <[email protected]> * Philippe Morin <[email protected]> * * Created on 28-feb-2006 * * $Id: JVLC.java 20141 2007-05-16 19:31:35Z littlejohn $ * * This program is free software; you can redistribute it * and/or modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. * */ package org.videolan.jvlc; import java.awt.Canvas; import org.videolan.jvlc.internal.LibVlc; import org.videolan.jvlc.internal.LibVlc.LibVlcInstance; import org.videolan.jvlc.internal.LibVlc.libvlc_exception_t; import com.sun.jna.Native; public class JVLC { private final LibVlcInstance instance; private final LibVlc libvlc = LibVlc.SYNC_INSTANCE; private MediaList mediaList; private VLM vlm; private volatile boolean released; public JVLC() { String[] args = new String[] {}; instance = createInstance(args); mediaList = new MediaList(this); } public JVLC(String[] args) { instance = createInstance(args); } public JVLC(String args) { this(args.split(" ")); } /* * Core methods */ private LibVlcInstance createInstance(String[] args) { libvlc_exception_t exception = new libvlc_exception_t(); return libvlc.libvlc_new(args.length, args, exception); } public MediaInstance play(String media) { MediaDescriptor mediaDescriptor = new MediaDescriptor(this, media); MediaInstance mediaInstance = new MediaInstance(mediaDescriptor); mediaInstance.play(); mediaDescriptor.release(); return mediaInstance; } public void setVideoOutput(Canvas canvas) { long drawable = Native.getComponentID(canvas); libvlc_exception_t exception = new libvlc_exception_t(); libvlc.libvlc_video_set_parent(instance, drawable, exception ); } public Logger getLogger() { return new Logger(this); } /** * Returns the mediaList. * @return the mediaList */ public MediaList getMediaList() { return mediaList; } public VLM getVLM() { if (vlm != null) { vlm.release(); } this.vlm = new VLM(this); return vlm; } public LoggerVerbosityLevel getLogVerbosity() { libvlc_exception_t exception = new libvlc_exception_t(); int level = libvlc.libvlc_get_log_verbosity(instance, exception); return LoggerVerbosityLevel.getSeverity(level); } public void setLogVerbosity(LoggerVerbosityLevel level) { libvlc_exception_t exception = new libvlc_exception_t(); libvlc.libvlc_set_log_verbosity(instance, level.ordinal(), exception); } /** * Returns the _instance. * @return the _instance */ LibVlcInstance getInstance() { return instance; } /** * Returns the libvlc. * @return the libvlc */ LibVlc getLibvlc() { return libvlc; } /** * Releases this instance and the native resources. */ public void release() { if (released) { return; } released = true; if (vlm != null) { vlm.release(); vlm = null; } libvlc.libvlc_release(instance); } /* * (non-Javadoc) * @see java.lang.Object#finalize() */ @Override protected void finalize() throws Throwable { release(); super.finalize(); } }
bindings/java/core/src/main/java/org/videolan/jvlc/JVLC.java
/***************************************************************************** * JVLC.java: Main Java Class, represents a libvlc_instance_t object ***************************************************************************** * * Copyright (C) 1998-2008 the VideoLAN team * * Author: Filippo Carone <[email protected]> * Philippe Morin <[email protected]> * * Created on 28-feb-2006 * * $Id: JVLC.java 20141 2007-05-16 19:31:35Z littlejohn $ * * This program is free software; you can redistribute it * and/or modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. * */ package org.videolan.jvlc; import java.awt.Canvas; import org.videolan.jvlc.internal.LibVlc; import org.videolan.jvlc.internal.LibVlc.LibVlcInstance; import org.videolan.jvlc.internal.LibVlc.libvlc_exception_t; import com.sun.jna.Native; public class JVLC { private final LibVlcInstance instance; private final LibVlc libvlc = LibVlc.SYNC_INSTANCE; private MediaList mediaList; private VLM vlm; private volatile boolean released; public JVLC() { String[] args = new String[] {}; instance = createInstance(args); mediaList = new MediaList(this); } public JVLC(String[] args) { instance = createInstance(args); } public JVLC(String args) { this(args.split(" ")); } public MediaInstance play(String media) { MediaDescriptor mediaDescriptor = new MediaDescriptor(this, media); MediaInstance mediaInstance = new MediaInstance(mediaDescriptor); mediaInstance.play(); return mediaInstance; } public void setVideoOutput(Canvas canvas) { long drawable = Native.getComponentID(canvas); libvlc_exception_t exception = new libvlc_exception_t(); libvlc.libvlc_video_set_parent(instance, drawable, exception ); } /* * Core methods */ private LibVlcInstance createInstance(String[] args) { libvlc_exception_t exception = new libvlc_exception_t(); libvlc.libvlc_exception_init(exception); return libvlc.libvlc_new(args.length, args, exception); } public Logger getLogger() { return new Logger(this); } public VLM getVLM() { if (vlm != null) { vlm.release(); } this.vlm = new VLM(this); return vlm; } public LoggerVerbosityLevel getLogVerbosity() { libvlc_exception_t exception = new libvlc_exception_t(); int level = libvlc.libvlc_get_log_verbosity(instance, exception); return LoggerVerbosityLevel.getSeverity(level); } public void setLogVerbosity(LoggerVerbosityLevel level) { libvlc_exception_t exception = new libvlc_exception_t(); libvlc.libvlc_set_log_verbosity(instance, level.ordinal(), exception); } /** * Returns the _instance. * @return the _instance */ LibVlcInstance getInstance() { return instance; } /** * Returns the libvlc. * @return the libvlc */ LibVlc getLibvlc() { return libvlc; } /** * Releases this instance and the native resources. */ public void release() { if (!released) { released = true; if (vlm != null) { vlm.release(); vlm = null; } libvlc.libvlc_release(instance); } } /* * (non-Javadoc) * @see java.lang.Object#finalize() */ @Override protected void finalize() throws Throwable { if (!released) { released = true; libvlc.libvlc_release(instance); } super.finalize(); } /** * Returns the mediaList. * @return the mediaList */ public MediaList getMediaList() { return mediaList; } }
minor changes to JVLC class
bindings/java/core/src/main/java/org/videolan/jvlc/JVLC.java
minor changes to JVLC class
<ide><path>indings/java/core/src/main/java/org/videolan/jvlc/JVLC.java <ide> <ide> private VLM vlm; <ide> <del> private volatile boolean released; <add> private volatile boolean released; <ide> <ide> public JVLC() <ide> { <ide> this(args.split(" ")); <ide> } <ide> <add> /* <add> * Core methods <add> */ <add> private LibVlcInstance createInstance(String[] args) <add> { <add> libvlc_exception_t exception = new libvlc_exception_t(); <add> return libvlc.libvlc_new(args.length, args, exception); <add> } <add> <ide> public MediaInstance play(String media) <ide> { <ide> MediaDescriptor mediaDescriptor = new MediaDescriptor(this, media); <ide> MediaInstance mediaInstance = new MediaInstance(mediaDescriptor); <ide> mediaInstance.play(); <add> mediaDescriptor.release(); <ide> return mediaInstance; <ide> } <ide> <ide> libvlc.libvlc_video_set_parent(instance, drawable, exception ); <ide> } <ide> <del> /* <del> * Core methods <del> */ <del> private LibVlcInstance createInstance(String[] args) <del> { <del> libvlc_exception_t exception = new libvlc_exception_t(); <del> libvlc.libvlc_exception_init(exception); <del> <del> return libvlc.libvlc_new(args.length, args, exception); <del> } <del> <ide> public Logger getLogger() <ide> { <ide> return new Logger(this); <ide> } <ide> <add> /** <add> * Returns the mediaList. <add> * @return the mediaList <add> */ <add> public MediaList getMediaList() <add> { <add> return mediaList; <add> } <add> <ide> public VLM getVLM() <ide> { <ide> if (vlm != null) <ide> */ <ide> public void release() <ide> { <del> if (!released) <add> if (released) <ide> { <del> released = true; <del> if (vlm != null) <del> { <del> vlm.release(); <del> vlm = null; <del> } <del> libvlc.libvlc_release(instance); <add> return; <ide> } <add> released = true; <add> if (vlm != null) <add> { <add> vlm.release(); <add> vlm = null; <add> } <add> libvlc.libvlc_release(instance); <ide> } <ide> <ide> /* <ide> @Override <ide> protected void finalize() throws Throwable <ide> { <del> if (!released) <del> { <del> released = true; <del> libvlc.libvlc_release(instance); <del> } <add> release(); <ide> super.finalize(); <ide> } <ide> <del> /** <del> * Returns the mediaList. <del> * @return the mediaList <del> */ <del> public MediaList getMediaList() <del> { <del> return mediaList; <del> } <del> <ide> }
Java
mit
cab193c084af2dddb15b8cbefb42d7ac04aa3785
0
kolach/cordova-plugin-hockeyapp,kolach/cordova-plugin-hockeyapp
package com.assuredlabor.cordova.hockeyapp; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.apache.cordova.CallbackContext; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import static net.hockeyapp.android.ExceptionHandler.saveException; import net.hockeyapp.android.CrashManager; import net.hockeyapp.android.FeedbackManager; import net.hockeyapp.android.UpdateManager; import net.hockeyapp.android.CrashManagerListener; import java.lang.RuntimeException; public class HockeyApp extends CordovaPlugin { String appId; /** * Actions the HockeyAppPlugin can parse. */ public enum DefinedAction { register, // registers HockeyApp with tocken reportCrash // crash report }; @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { try { DefinedAction definedAction = DefinedAction.valueOf(action); switch (definedAction) { case register: PluginResult result = null; result = register(args); result.setKeepCallback(false); callbackContext.sendPluginResult(result); break; case reportCrash: final String message = args.getString(0); cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { Exception e = new Exception(message); saveException(e, new CrashManagerListener() { public String getDescription() { return message; } }); } }); callbackContext.success(); break; } return true; } catch (RuntimeException e) { callbackContext.success("Reported error: " + e.toString()); throw e; } catch (JSONException e) { callbackContext.error(e.getMessage()); return false; } } @Override public void onResume(boolean multitasking) { super.onResume(multitasking); checkForCrashes(); } private void checkForCrashes() { CrashManager.register(cordova.getActivity(), appId); } private void checkForUpdates() { UpdateManager.register(cordova.getActivity(), appId); } private PluginResult register(JSONArray args) throws JSONException { appId = args.getString(0); checkForUpdates(); checkForCrashes(); return new PluginResult(PluginResult.Status.OK); } }
src/android/HockeyApp.java
package com.assuredlabor.cordova.hockeyapp; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.PluginResult; import org.apache.cordova.CallbackContext; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import static net.hockeyapp.android.ExceptionHandler.saveException; import net.hockeyapp.android.CrashManager; import net.hockeyapp.android.FeedbackManager; import net.hockeyapp.android.UpdateManager; import net.hockeyapp.android.CrashManagerListener; import java.lang.RuntimeException; public class HockeyApp extends CordovaPlugin { String appId; /** * Actions the HockeyAppPlugin can parse. */ public enum DefinedAction { register, // registers HockeyApp with tocken reportCrash // crash report }; @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { try { DefinedAction definedAction = DefinedAction.valueOf(action); switch (definedAction) { case register: PluginResult result = null; result = register(args); result.setKeepCallback(false); callbackContext.sendPluginResult(result); break; case reportCrash: final String message = args.getString(0); cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { Exception e = new Exception(message); saveException(e, new CrashManagerListener() { public String getDescription() { return message; } }); } }); callbackContext.success(); break; } return true; } catch (RuntimeException e) { callbackContext.success("Reported error: " + e.toString()); throw e; } catch (JSONException e) { callbackContext.error(e.getMessage()); return false; } } @Override public void onResume(boolean multitasking) { super.onResume(multitasking); checkForCrashes(); } private void checkForCrashes() { CrashManager.register(cordova.getActivity(), appId); } private void checkForUpdates() { UpdateManager.register(cordova.getActivity(), appId); } private PluginResult register(JSONArray args) throws JSONException { appId = args.getString(0); checkForUpdates(); checkForCrashes(); return new PluginResult(PluginResult.Status.OK); } // private PluginResult reportCrash(JSONArray args) throws JSONException { //// String message = args.getString(0); //// throw new RuntimeException(message); // // // // } }
code cleanup
src/android/HockeyApp.java
code cleanup
<ide><path>rc/android/HockeyApp.java <ide> return new PluginResult(PluginResult.Status.OK); <ide> } <ide> <del>// private PluginResult reportCrash(JSONArray args) throws JSONException { <del>//// String message = args.getString(0); <del>//// throw new RuntimeException(message); <del>// <del>// <del>// <del>// } <ide> <ide> }
Java
epl-1.0
10cdda737aa9cc74b1b2f15f4bccd47c9881b374
0
css-iter/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio
/* * Copyright (c) 2010 Stiftung Deutsches Elektronen-Synchrotron, * Member of the Helmholtz Association, (DESY), HAMBURG, GERMANY. * * THIS SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "../AS IS" BASIS. * WITHOUT WARRANTY OF ANY KIND, EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR PARTICULAR PURPOSE AND * NON-INFRINGEMENT. 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. SHOULD THE SOFTWARE PROVE DEFECTIVE * IN ANY RESPECT, THE USER ASSUMES THE COST OF ANY NECESSARY SERVICING, REPAIR OR * CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. * NO USE OF ANY SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. * DESY HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, * OR MODIFICATIONS. * THE FULL LICENSE SPECIFYING FOR THE SOFTWARE THE REDISTRIBUTION, MODIFICATION, * USAGE AND OTHER RIGHTS AND OBLIGATIONS IS INCLUDED WITH THE DISTRIBUTION OF THIS * PROJECT IN THE FILE LICENSE.HTML. IF THE LICENSE IS NOT INCLUDED YOU MAY FIND A COPY * AT HTTP://WWW.DESY.DE/LEGAL/LICENSE.HTM */ package org.csstudio.config.ioconfig.editorparts; import java.util.ArrayList; import java.util.Collection; import java.util.Formatter; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeMap; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.csstudio.config.ioconfig.config.view.OverviewLabelProvider; import org.csstudio.config.ioconfig.config.view.helper.ProfibusHelper; import org.csstudio.config.ioconfig.model.DocumentDBO; import org.csstudio.config.ioconfig.model.AbstractNodeDBO; import org.csstudio.config.ioconfig.model.pbmodel.ChannelDBO; import org.csstudio.config.ioconfig.model.pbmodel.ChannelStructureDBO; import org.csstudio.config.ioconfig.model.pbmodel.GSDFileDBO; import org.csstudio.config.ioconfig.model.pbmodel.ModuleDBO; import org.csstudio.config.ioconfig.model.pbmodel.Ranges; import org.csstudio.config.ioconfig.model.pbmodel.SlaveDBO; import org.csstudio.config.ioconfig.model.pbmodel.gsdParser.ExtUserPrmData; import org.csstudio.config.ioconfig.model.pbmodel.gsdParser.ExtUserPrmDataConst; import org.csstudio.config.ioconfig.model.pbmodel.gsdParser.ExtUserPrmDataRef; import org.csstudio.config.ioconfig.model.pbmodel.gsdParser.GSD2Module; import org.csstudio.config.ioconfig.model.pbmodel.gsdParser.GsdFactory; import org.csstudio.config.ioconfig.model.pbmodel.gsdParser.GsdModuleModel; import org.csstudio.config.ioconfig.model.pbmodel.gsdParser.GsdSlaveModel; import org.csstudio.config.ioconfig.model.pbmodel.gsdParser.PrmText; import org.csstudio.config.ioconfig.model.xml.ProfibusConfigXMLGenerator; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.events.ControlAdapter; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowData; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.Text; /** * TODO (hrickens) : * * @author hrickens * @author $Author: hrickens $ * @version $Revision: 1.3 $ * @since 21.05.2010 */ public class SlaveEditor extends AbstractNodeEditor { public static final String ID = "org.csstudio.config.ioconfig.view.editor.slave"; /** * The Slave which displayed. */ private SlaveDBO _slave; /** * The GSD File of the Slave. */ private GSDFileDBO _gsdFile; /** * The Text field for the Vendor. */ private Text _vendorText; /** * Slave ID Number. */ private Text _iDNo; /** * The Text field for the Revision. */ private Text _revisionsText; /** * The Module max size of this Slave. */ private int _maxSize; /** * The number of max slots. */ private Text _maxSlots; /** * List with User Prm Data's. */ private TableViewer _userPrmDataList; /** * Inputs. */ private Text _inputsText; /** * Outputs. */ private Text _outputsText; /** * Die Bedeutung dieses Feldes ist noch unbekannt. */ // private Text _unbekannt; /** * The minimum Station Delay Time. */ private Text _minStationDelayText; /** * The Watchdog Time. */ private Text _watchDogText; /** * Marker of Background Color for normal use. Get from widget by first use. */ private Color _defaultBackgroundColor; /** * Check Button to de.-/activate Station Address. */ private Button _stationAddressActiveCButton; private Button _freezeButton; private Button _failButton; private Button _watchDogButton; private Button _syncButton; private int _groupIdent; private int _groupIdentStored; private Group _groupsRadioButtons; private ComboViewer _indexCombo; private Group _currentUserParamDataGroup; private final ArrayList<Object> _prmTextCV = new ArrayList<Object>(); /** * * @author hrickens * @author $Author: hrickens $ * @version $Revision: 1.3 $ * @since 14.08.2007 */ class RowNumLabelProvider implements ITableLabelProvider { /** * {@inheritDoc} */ @Override public void addListener(@Nullable final ILabelProviderListener listener) { // handle no listener } /** * {@inheritDoc} */ @Override public void dispose() { if (getDefaultBackgroundColor() != null) { getDefaultBackgroundColor().dispose(); } } /** * {@inheritDoc} */ @Override public boolean isLabelProperty(@Nullable final Object element, @Nullable final String property) { return false; } /** * {@inheritDoc} */ @Override public void removeListener( @Nullable final ILabelProviderListener listener) { // handle no listener } @Override public Image getColumnImage(@Nullable final Object element, @Nullable final int columnIndex) { return null; } @Override public String getColumnText(@Nullable final Object element, final int columnIndex) { if (element instanceof SlaveDBO) { SlaveDBO slave = (SlaveDBO) element; return onSlave(slave, columnIndex); } else if (element instanceof ModuleDBO) { ModuleDBO module = (ModuleDBO) element; return onModule(module, columnIndex); } return null; } /** * @param module * @param columnIndex */ @CheckForNull private String onModule(@Nonnull final ModuleDBO module, final int columnIndex) { switch (columnIndex) { case 0: return module.getSortIndex().toString(); case 1: return module.getName(); case 2: return module.getExtUserPrmDataConst(); default: break; } return null; } /** * @param slave */ @CheckForNull private String onSlave(@Nonnull final SlaveDBO slave, final int columnIndex) { // TreeMap<String, ExtUserPrmDataConst> extUserPrmDataConst = // slave.getGSDSlaveData() // .getExtUserPrmDataConst(); switch (columnIndex) { case 1: return slave.getName(); case 2: // StringBuffer sb = new StringBuffer(); // Set<String> keySet = extUserPrmDataConst.keySet(); // for (String key : keySet) { // sb.append(extUserPrmDataConst.get(key).getValue()); // } // return sb.toString(); return slave.getPrmUserData(); default: break; } return null; } } /** * {@inheritDoc} */ @Override public void createPartControl(@Nonnull final Composite parent) { _slave = (SlaveDBO) getNode(); super.createPartControl(parent); makeSlaveKonfiguration(parent); getTabFolder().setSelection(0); } /** * @param parent * Parent Composite. * @param style * Style of the Composite. * @param slave * the Profibus Slave to Configer. */ private void makeSlaveKonfiguration(final Composite parent) { boolean nevv = false; if (_slave == null) { if (!newNode("TODO")) { // this.dispose(); setSaveButtonSaved(); getProfiBusTreeView().getTreeViewer().setSelection( getProfiBusTreeView().getTreeViewer().getSelection()); return; } nevv = true; _slave.setMinTsdr((short) 11); _slave.setWdFact1((short) 100); } setSavebuttonEnabled(null, getNode().isPersistent()); String[] heads = { "Basics", "Settings", "Overview" }; overview(heads[2]); settings(heads[1]); basics(heads[0]); if (_slave.getGSDFile() != null) { fill(_slave.getGSDFile()); } getTabFolder().pack(); if (nevv) { getTabFolder().setSelection(4); } } @SuppressWarnings("unchecked") private void overview(@Nonnull final String headline) { Composite comp = getNewTabItem(headline, 1); comp.setLayout(new GridLayout(1, false)); TableViewer overViewer = new TableViewer(comp, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.FULL_SELECTION); overViewer.setContentProvider(new ArrayContentProvider()); overViewer.setLabelProvider(new OverviewLabelProvider()); overViewer.getTable().setHeaderVisible(true); overViewer.getTable().setLinesVisible(true); overViewer.getTable().setLayoutData( new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); TableColumn c0 = new TableColumn(overViewer.getTable(), SWT.RIGHT); c0.setText("Adr"); TableColumn c0b = new TableColumn(overViewer.getTable(), SWT.RIGHT); c0b.setText("Adr"); TableColumn c1 = new TableColumn(overViewer.getTable(), SWT.LEFT); c1.setText("Name"); TableColumn c2 = new TableColumn(overViewer.getTable(), SWT.LEFT); // c2.setWidth(200); c2.setText("IO Name"); TableColumn c3 = new TableColumn(overViewer.getTable(), SWT.LEFT); // c3.setWidth(200); c3.setText("IO Epics Address"); TableColumn c4 = new TableColumn(overViewer.getTable(), SWT.LEFT); // c4.setWidth(200); c4.setText("Desc"); TableColumn c5 = new TableColumn(overViewer.getTable(), SWT.LEFT); // c5.setWidth(60); c5.setText("Type"); TableColumn c6 = new TableColumn(overViewer.getTable(), SWT.LEFT); // c5.setWidth(60); c6.setText("DB Id"); overViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged( @Nonnull final SelectionChangedEvent event) { getProfiBusTreeView().getTreeViewer().setSelection( event.getSelection(), true); } }); ArrayList<AbstractNodeDBO> children = new ArrayList<AbstractNodeDBO>(); Collection<ModuleDBO> modules = (Collection<ModuleDBO>) _slave .getChildrenAsMap().values(); for (ModuleDBO module : modules) { children.add(module); Collection<ChannelStructureDBO> channelStructures = module .getChannelStructsAsMap().values(); for (ChannelStructureDBO channelStructure : channelStructures) { Collection<ChannelDBO> channels = channelStructure .getChannelsAsMap().values(); for (ChannelDBO channel : channels) { children.add(channel); } } } overViewer.setInput(children); c0.pack(); c0b.pack(); c1.pack(); c2.pack(); c3.pack(); c4.pack(); c5.pack(); c6.pack(); } /** * @param head * The Tab text. */ private void basics(@Nonnull final String head) { Composite comp = getNewTabItem(head, 2); /* * Name */ Group gName = new Group(comp, SWT.NONE); gName.setText("Name"); gName.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 5, 1)); gName.setLayout(new GridLayout(3, false)); Text nameText = new Text(gName, SWT.BORDER | SWT.SINGLE); setText(nameText, _slave.getName(), 255); nameText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1)); setNameWidget(nameText); // Label Label slotIndexLabel = new Label(gName, SWT.NONE); slotIndexLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); slotIndexLabel.setText("Station Adress:"); _indexCombo = new ComboViewer(gName, SWT.DROP_DOWN | SWT.READ_ONLY); _indexCombo.getCombo().setLayoutData( new GridData(SWT.RIGHT, SWT.RIGHT, false, false)); _indexCombo.setContentProvider(new ArrayContentProvider()); _indexCombo.setLabelProvider(new LabelProvider()); Collection<Short> freeStationAddress = _slave.getProfibusDPMaster() .getFreeStationAddress(); Short sortIndex = _slave.getSortIndex(); if (sortIndex >= 0) { if (!freeStationAddress.contains(sortIndex)) { freeStationAddress.add(sortIndex); } _indexCombo.setInput(freeStationAddress); _indexCombo.setSelection(new StructuredSelection(sortIndex)); } else { _indexCombo.setInput(freeStationAddress); _indexCombo.getCombo().select(0); _slave.setSortIndexNonHibernate((Short) ((StructuredSelection) _indexCombo .getSelection()).getFirstElement()); } _indexCombo.getCombo().setData( _indexCombo.getCombo().getSelectionIndex()); _indexCombo.getCombo().addModifyListener(getMLSB()); _indexCombo .addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged( @Nonnull final SelectionChangedEvent event) { short index = (Short) ((StructuredSelection) _indexCombo .getSelection()).getFirstElement(); getNode().moveSortIndex(index); if (getNode().getParent() != null) { getProfiBusTreeView() .refresh(getNode().getParent()); } else { getProfiBusTreeView().refresh(); } } }); // setIndexSpinner(ConfigHelper.getIndexSpinner(gName, _slave, // getMLSB(), // "Station Adress:",getProfiBusTreeView())); // _defaultBackgroundColor = getIndexSpinner().getBackground(); /* * Slave Information */ Group slaveInfoGroup = new Group(comp, SWT.NONE); slaveInfoGroup.setText("Slave Information"); slaveInfoGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 2)); slaveInfoGroup.setLayout(new GridLayout(4, false)); slaveInfoGroup.setTabList(new Control[0]); _vendorText = new Text(slaveInfoGroup, SWT.SINGLE | SWT.BORDER); _vendorText.setEditable(false); _vendorText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 4, 1)); _iDNo = new Text(slaveInfoGroup, SWT.SINGLE); _iDNo.setEditable(false); _iDNo.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1)); Label revisionsLable = new Label(slaveInfoGroup, SWT.NONE); revisionsLable.setText("Revision:"); _revisionsText = new Text(slaveInfoGroup, SWT.SINGLE); _revisionsText.setEditable(false); _revisionsText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1)); new Label(slaveInfoGroup, SWT.None).setText("Max. available slots:"); _maxSlots = new Text(slaveInfoGroup, SWT.BORDER); _maxSlots.setEditable(false); /* * DP/FDL Access Group */ Group dpFdlAccessGroup = new Group(comp, SWT.NONE); dpFdlAccessGroup.setText("DP / FDL Access"); dpFdlAccessGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); dpFdlAccessGroup.setLayout(new GridLayout(2, false)); Label stationAdrLabel = new Label(dpFdlAccessGroup, SWT.None); stationAdrLabel.setText("Station Address"); GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1); gd.minimumWidth = 50; _stationAddressActiveCButton = new Button(dpFdlAccessGroup, SWT.CHECK); _stationAddressActiveCButton.setText("Active"); _stationAddressActiveCButton.setSelection(false); _stationAddressActiveCButton.setData(false); _stationAddressActiveCButton .addSelectionListener(new SelectionListener() { @Override public void widgetDefaultSelected( @Nonnull final SelectionEvent e) { change(); } @Override public void widgetSelected(@Nonnull final SelectionEvent e) { change(); } private void change() { setSavebuttonEnabled( "Button:" + _stationAddressActiveCButton .hashCode(), (Boolean) _stationAddressActiveCButton .getData() != _stationAddressActiveCButton .getSelection()); } }); /* * Input / Output Group */ Group ioGroup = new Group(comp, SWT.NONE); ioGroup.setText("Inputs / Outputs"); ioGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); ioGroup.setLayout(new GridLayout(3, false)); ioGroup.setTabList(new Control[0]); int input = 0; int output = 0; if (_slave.hasChildren()) { Iterator<ModuleDBO> iterator = _slave.getModules().iterator(); while (iterator.hasNext()) { ModuleDBO module = iterator.next(); input += module.getInputSize(); output += module.getOutputSize(); } } Label inputLabel = new Label(ioGroup, SWT.RIGHT); inputLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false, 2, 1)); inputLabel.setText("Inputs: "); _inputsText = new Text(ioGroup, SWT.SINGLE); _inputsText.setEditable(false); _inputsText.setText(Integer.toString(input)); Label outputsLabel = new Label(ioGroup, SWT.RIGHT); outputsLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false, 2, 1)); outputsLabel.setText("Outputs: "); _outputsText = new Text(ioGroup, SWT.SINGLE); _outputsText.setEditable(false); _outputsText.setText(Integer.toString(output)); /* * Description Group */ makeDescGroup(comp, 3); } /** * */ private void setSlots() { Formatter slotFormarter = new Formatter(); slotFormarter.format(" %2d / %2d", _slave.getChildren().size(), _maxSize); _maxSlots.setText(slotFormarter.toString()); if (_maxSize < _slave.getChildren().size()) { if (getDefaultBackgroundColor() == null) { setDefaultBackgroundColor(Display.getDefault().getSystemColor( SWT.COLOR_WIDGET_BACKGROUND)); } _maxSlots.setBackground(WARN_BACKGROUND_COLOR); } else { _maxSlots.setBackground(getDefaultBackgroundColor()); } slotFormarter = null; } /** * @param head * the tabItemName */ private void settings(@Nonnull final String head) { Composite comp = getNewTabItem(head, 2); comp.setLayout(new GridLayout(3, false)); // Operation Mode Group operationModeGroup = new Group(comp, SWT.NONE); GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); layoutData.minimumWidth = 170; operationModeGroup.setLayoutData(layoutData); operationModeGroup.setText("Operation Mode"); operationModeGroup.setLayout(new GridLayout(3, false)); Label delayLabel = new Label(operationModeGroup, SWT.NONE); delayLabel.setText("Min. Station Delay"); _minStationDelayText = ProfibusHelper.getTextField(operationModeGroup, true, _slave.getMinTsdr() + "", Ranges.WATCHDOG, ProfibusHelper.VL_TYP_U16); Label bitLabel = new Label(operationModeGroup, SWT.NONE); bitLabel.setText("Bit"); _syncButton = new Button(operationModeGroup, SWT.CHECK); _syncButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 3, 1)); _syncButton.addTraverseListener(ProfibusHelper.getNETL()); _syncButton.setText("Sync Request"); _syncButton.setData(false); _syncButton.addSelectionListener(new SelectionListener() { @Override public void widgetDefaultSelected(@Nonnull final SelectionEvent e) { change(_syncButton); } @Override public void widgetSelected(@Nonnull final SelectionEvent e) { change(_syncButton); } }); _freezeButton = new Button(operationModeGroup, SWT.CHECK); _freezeButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 3, 1)); _freezeButton.addTraverseListener(ProfibusHelper.getNETL()); _freezeButton.setText("Freeze Request"); _freezeButton.setSelection(false); _freezeButton.setData(false); _freezeButton.addSelectionListener(new SelectionListener() { @Override public void widgetDefaultSelected(@Nonnull final SelectionEvent e) { change(_freezeButton); } @Override public void widgetSelected(@Nonnull final SelectionEvent e) { change(_freezeButton); } }); setFailButton(new Button(operationModeGroup, SWT.CHECK)); getFailButton().setLayoutData( new GridData(SWT.FILL, SWT.FILL, false, false, 3, 1)); getFailButton().addTraverseListener(ProfibusHelper.getNETL()); getFailButton().setText("Fail Save"); getFailButton().setEnabled(false); getFailButton().setData(false); getFailButton().addSelectionListener(new SelectionListener() { @Override public void widgetDefaultSelected(@Nonnull final SelectionEvent e) { change(getFailButton()); } @Override public void widgetSelected(@Nonnull final SelectionEvent e) { change(getFailButton()); } }); _watchDogButton = new Button(operationModeGroup, SWT.CHECK); _watchDogButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); _watchDogButton.addTraverseListener(ProfibusHelper.getNETL()); _watchDogButton.setText("Watchdog Time"); _watchDogButton.setSelection(true); _watchDogButton.setData(true); _watchDogText = ProfibusHelper.getTextField(operationModeGroup, _watchDogButton.getSelection(), Integer.toString(_slave.getWdFact1()), Ranges.TTR, ProfibusHelper.VL_TYP_U32); _watchDogText.addModifyListener(getMLSB()); Label timeLabel = new Label(operationModeGroup, SWT.NONE); timeLabel.setText("ms"); _watchDogButton.addSelectionListener(new SelectionListener() { @Override public void widgetDefaultSelected(@Nonnull final SelectionEvent e) { change(); } @Override public void widgetSelected(@Nonnull final SelectionEvent e) { change(); } private void change() { SlaveEditor.this.change(_watchDogButton); _watchDogText.setEnabled(_watchDogButton.getSelection()); } }); makeCurrentUserParamData(comp); makeUserPRMMode(comp); } /** * @param comp */ private void makeUserPRMMode(@Nonnull final Composite comp) { Group userPrmData = new Group(comp, SWT.V_SCROLL); userPrmData.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 2)); userPrmData.setLayout(new GridLayout(2, false)); userPrmData.setTabList(new Control[0]); userPrmData.setText("User PRM Mode"); _userPrmDataList = new TableViewer(userPrmData, SWT.BORDER | SWT.V_SCROLL); Table table = _userPrmDataList.getTable(); table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 15)); table.setHeaderVisible(true); table.setLinesVisible(true); _userPrmDataList.setContentProvider(new ArrayContentProvider()); _userPrmDataList.setLabelProvider(new RowNumLabelProvider()); TableColumn tc = new TableColumn(table, SWT.RIGHT); tc.setText(""); tc.setWidth(20); tc = new TableColumn(table, SWT.LEFT); tc.setText("Name"); tc.setWidth(130); tc = new TableColumn(table, SWT.LEFT); tc.setText("Ext User Prm Data Const"); tc.setWidth(450); // Groups _groupsRadioButtons = new Group(comp, SWT.NONE); _groupsRadioButtons.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1)); _groupsRadioButtons.setLayout(new GridLayout(4, true)); _groupsRadioButtons.setText("Groups"); _groupIdentStored = _slave.getGroupIdent(); if ((_groupIdentStored < 0) || (_groupIdentStored > 7)) { _groupIdentStored = 0; } _groupIdent = _groupIdentStored; for (int i = 0; i <= 7; i++) { final Button b = new Button(_groupsRadioButtons, SWT.RADIO); b.setText(Integer.toString(i + 1)); if (i == _groupIdent) { b.setSelection(true); } b.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected( @Nonnull final SelectionEvent e) { check(); } @Override public void widgetSelected(@Nonnull final SelectionEvent e) { check(); } private void check() { _groupIdent = Short.parseShort(b.getText()); _groupIdent--; setSavebuttonEnabled( "groupButton" + _groupsRadioButtons.hashCode(), _groupIdent != _groupIdentStored); } }); } } /** {@inheritDoc} */ @Override public final boolean fill(@Nullable final GSDFileDBO gsdFile) { // Read GSD-File if (gsdFile == null) { return false; } else if (gsdFile.equals(_gsdFile)) { return true; } _gsdFile = gsdFile; GsdSlaveModel slaveModel = GsdFactory.makeGsdSlave(_gsdFile); // setGSDData HashMap<Integer, GsdModuleModel> moduleList = GSD2Module.parse( _gsdFile, slaveModel); slaveModel.setGsdModuleList(moduleList); _slave.setGSDSlaveData(slaveModel); // Head getHeaderField(HeaderFields.VERSION).setText( slaveModel.getGsdRevision() + ""); // Basic - Slave Discription (read only) _vendorText.setText(slaveModel.getVendorName()); _iDNo.setText(String.format("0x%04X", slaveModel.getIdentNumber())); _revisionsText.setText(slaveModel.getRevision()); // Basic - Inputs / Outputs (read only) // Set all GSD-File Data to Slave. _slave.setMinTsdr(_slave.getMinTsdr()); _slave.setModelName(slaveModel.getModelName()); _slave.setPrmUserData(slaveModel.getUserPrmData()); _slave.setProfibusPNoID(slaveModel.getIdentNumber()); _slave.setRevision(slaveModel.getRevision()); // Basic - DP / FDL Access // Modules _maxSize = slaveModel.getMaxModule(); setSlots(); // Settings - Operation Mode // Settings - Groups // Settings - USER PRM MODE ArrayList<AbstractNodeDBO> nodes = new ArrayList<AbstractNodeDBO>(); nodes.add(_slave); nodes.addAll(_slave.getChildrenAsMap().values()); _userPrmDataList.setInput(nodes); TableColumn[] columns = _userPrmDataList.getTable().getColumns(); for (TableColumn tableColumn : columns) { if (tableColumn != null) { tableColumn.pack(); } } return true; } /** {@inheritDoc} */ @Override public final GSDFileDBO getGSDFile() { return _slave.getGSDFile(); } /** * {@inheritDoc} */ @Override public void doSave(@Nullable final IProgressMonitor monitor) { super.doSave(monitor); // Name _slave.setName(getNameWidget().getText()); getNameWidget().setData(getNameWidget().getText()); // _slave.moveSortIndex((short) getIndexSpinner().getSelection()); Short stationAddress = (Short) ((StructuredSelection) _indexCombo .getSelection()).getFirstElement(); _slave.setSortIndexNonHibernate(stationAddress); _slave.setFdlAddress(stationAddress); _indexCombo.getCombo().setData( _indexCombo.getCombo().getSelectionIndex()); short minTsdr = 0; try { minTsdr = Short.parseShort(_minStationDelayText.getText()); } catch (NumberFormatException e) { // don't change the old Value when the new value a invalid. } _slave.setMinTsdr(minTsdr); _slave.setGroupIdent(_groupIdent); _groupIdentStored = _groupIdent; _slave.setSlaveFlag((short) 192); short wdFact = Short.parseShort(_watchDogText.getText()); _watchDogText.setData(_watchDogText.getText()); _slave.setWdFact1(wdFact); _slave.setWdFact2((short) (wdFact / 10)); // Static Station status 136 _slave.setStationStatus((short) 136); saveUserPrmData(); // GSD File _slave.setGSDFile(_gsdFile); fill(_gsdFile); // Document Set<DocumentDBO> docs = getDocumentationManageView().getDocuments(); _slave.setDocuments(docs); _slave.update(); save(); } /** * */ private void saveUserPrmData() { TreeMap<String, ExtUserPrmDataConst> extUserPrmDataConst = _slave .getGSDSlaveData().getExtUserPrmDataConst(); List<ExtUserPrmDataRef> extUserPrmDataRefMap = _slave.getGSDSlaveData() .getExtUserPrmDataRefMap(); if (extUserPrmDataRefMap.size() == _prmTextCV.size()) { for (int i = 0; i < extUserPrmDataRefMap.size(); i++) { ExtUserPrmDataRef ref = extUserPrmDataRefMap.get(i); Object prmTextObject = _prmTextCV.get(i); if (prmTextObject instanceof ComboViewer) { ComboViewer prmTextCV = (ComboViewer) prmTextObject; handleComboViewer(extUserPrmDataConst, prmTextCV, ref.getValue()); } else if (prmTextObject instanceof Text) { Text prmText = (Text) prmTextObject; extUserPrmDataConst = handleText(extUserPrmDataConst, prmText); } } } else { // TODO: throw extUserPrmDataRefMap und prmTextCV passen nicht zu // sammen } // GsdModuleModel mod = (GsdModuleModel) ((StructuredSelection) // _moduleTypList.getSelection()) // .getFirstElement(); // if (mod != null) { // // _slave.setModuleNumber(mod.getModuleNumber()); // // _moduleTypList.getTable().setData(mod.getModuleNumber()); // // // String[] extUserPrmDataConst = // _module.getGsdModuleModel().getExtUserPrmDataConst() // // .split(","); // // String extUserPrmDataConst = _slave.getPrmUserData(); // for (Object prmTextObject : _prmTextCV) { // if (prmTextObject instanceof ComboViewer) { // ComboViewer prmTextCV = (ComboViewer) prmTextObject; // // handleComboViewer(extUserPrmDataConst, prmTextCV); // } else if (prmTextObject instanceof Text) { // Text prmText = (Text) prmTextObject; // // extUserPrmDataConst = handleText(extUserPrmDataConst, prmText); // } // } // // _module.setConfigurationData(Arrays.toString(extUserPrmDataConst) // // .replaceAll("[\\[\\]]", "")); // } } /** * @param extUserPrmDataConst * @param prmText * @return */ @Nonnull private TreeMap<String, ExtUserPrmDataConst> handleText( @Nonnull final TreeMap<String, ExtUserPrmDataConst> extUserPrmDataConst, @Nonnull final Text prmText) { if (!prmText.isDisposed()) { String value = (String) prmText.getData(); if (value != null) { prmText.setText(value); int val = Integer.parseInt(value); // return new String[] {String.format("%1$#04x", val) }; } } return extUserPrmDataConst; } /** * @param extUserPrmDataConst * @param byteIndexString * @param prmTextObject */ private void handleComboViewer( @Nonnull final TreeMap<String, ExtUserPrmDataConst> extUserPrmDataConst, @Nonnull final ComboViewer prmTextCV, @Nonnull final String byteIndexString) { if (!prmTextCV.getCombo().isDisposed()) { int byteIndex = ProfibusConfigXMLGenerator.getInt(byteIndexString); ExtUserPrmData input = (ExtUserPrmData) prmTextCV.getInput(); StructuredSelection selection = (StructuredSelection) prmTextCV .getSelection(); Integer bitValue = ((PrmText) selection.getFirstElement()) .getValue(); String newValue = setValue2BitMask(input, bitValue, _slave .getPrmUserDataList().get(byteIndex)); _slave.setPrmUserDataByte(byteIndex, newValue); Integer indexOf = prmTextCV.getCombo().indexOf( selection.getFirstElement().toString()); prmTextCV.getCombo().setData(indexOf); } } /** * Change the a value on the Bit places, that is given from the input, to * the bitValue. * * @param ranges * give the start and end Bit position. * @param bitValue * the new Value for the given Bit position. * @param value * the value was changed. * @return the changed value as Hex String. */ @Nonnull private String setValue2BitMask(@Nonnull final ExtUserPrmData ranges, @Nonnull final Integer bitValue, @Nonnull final String value) { int val = ProfibusConfigXMLGenerator.getInt(value); int minBit = ranges.getMinBit(); int maxBit = ranges.getMaxBit(); if (maxBit < minBit) { minBit = ranges.getMaxBit(); maxBit = ranges.getMinBit(); } int mask = ~((int) (Math.pow(2, maxBit + 1) - Math.pow(2, minBit))); val = val & mask; val = val | (bitValue << minBit); return String.format("%1$#04x", val); } /* * (non-Javadoc) * * @see org.csstudio.config.ioconfig.config.view.NodeConfig#cancel() */ @Override public void cancel() { super.cancel(); // getIndexSpinner().setSelection((Short) getIndexSpinner().getData()); if (_indexCombo != null) { _indexCombo.getCombo().select( (Integer) _indexCombo.getCombo().getData()); getNameWidget().setText((String) getNameWidget().getData()); _stationAddressActiveCButton .setSelection((Boolean) _stationAddressActiveCButton .getData()); _minStationDelayText.setText((String) _minStationDelayText .getData()); _syncButton.setSelection((Boolean) _syncButton.getData()); getFailButton().setSelection((Boolean) getFailButton().getData()); _freezeButton.setSelection((Boolean) _freezeButton.getData()); _watchDogButton.setSelection((Boolean) _watchDogButton.getData()); _watchDogText.setEnabled(_watchDogButton.getSelection()); _watchDogText.setText((String) _watchDogText.getData()); _groupIdent = _groupIdentStored; for (Control control : _groupsRadioButtons.getChildren()) { if (control instanceof Button) { Button button = (Button) control; button.setSelection(Short.parseShort(button.getText()) == _groupIdentStored + 1); } } if (_slave != null) { if (_slave.getGSDFile() != null) { fill(_slave.getGSDFile()); } else { getHeaderField(HeaderFields.VERSION).setText(""); _vendorText.setText(""); getNameWidget().setText(""); _revisionsText.setText(""); } } else { _gsdFile = null; fill(_gsdFile); } } } void change(@Nonnull final Button button) { setSavebuttonEnabled("Button:" + button.hashCode(), (Boolean) button.getData() != button.getSelection()); } /** * * @param topGroup * The parent Group for the CurrentUserParamData content. */ private void makeCurrentUserParamData(@Nonnull final Composite topGroup) { if (_currentUserParamDataGroup != null) { _currentUserParamDataGroup.dispose(); } // Current User Param Data Group _currentUserParamDataGroup = new Group(topGroup, SWT.NONE); GridData gd = new GridData(SWT.FILL, SWT.FILL, false, true, 1, 3); _currentUserParamDataGroup.setLayoutData(gd); _currentUserParamDataGroup.setLayout(new FillLayout()); _currentUserParamDataGroup.setText("Current User Param Data:"); final ScrolledComposite scrollComposite = new ScrolledComposite( _currentUserParamDataGroup, SWT.V_SCROLL); final Composite currentUserParamDataComposite = new Composite( scrollComposite, SWT.NONE); RowLayout rowLayout = new RowLayout(SWT.VERTICAL); rowLayout.wrap = false; rowLayout.fill = true; currentUserParamDataComposite.setLayout(rowLayout); scrollComposite.setContent(currentUserParamDataComposite); scrollComposite.setExpandHorizontal(true); scrollComposite.setExpandVertical(true); _currentUserParamDataGroup.addControlListener(new ControlAdapter() { @Override public void controlResized(@Nonnull final ControlEvent e) { Rectangle r = scrollComposite.getClientArea(); scrollComposite.setMinSize(scrollComposite.computeSize(r.width, SWT.DEFAULT)); } }); scrollComposite.addControlListener(new ControlAdapter() { @Override public void controlResized(@Nonnull final ControlEvent e) { Rectangle r = scrollComposite.getClientArea(); scrollComposite.setMinSize(currentUserParamDataComposite .computeSize(r.width, SWT.DEFAULT)); } }); // Current User Param Data GsdSlaveModel gsdSlaveModel = _slave.getGSDSlaveData(); if (gsdSlaveModel != null) { List<ExtUserPrmDataRef> extUserPrmDataRefMap = gsdSlaveModel .getExtUserPrmDataRefMap(); if (extUserPrmDataRefMap != null) { for (ExtUserPrmDataRef extUserPrmDataRef : extUserPrmDataRefMap) { int val = 0; String byteIndex = extUserPrmDataRef.getIndex(); ExtUserPrmData extUserPrmData = gsdSlaveModel .getExtUserPrmData(extUserPrmDataRef.getValue()); makeCurrentUserParamDataItem(currentUserParamDataComposite, extUserPrmData, val, byteIndex); } } } topGroup.layout(); } /** * * @param currentUserParamDataGroup * @param extUserPrmData * @param value * @param byteIndex */ private void makeCurrentUserParamDataItem( @Nonnull final Composite currentUserParamDataGroup, @Nullable final ExtUserPrmData extUserPrmData, final Integer value, final String byteIndex) { HashMap<Integer, PrmText> prmTextMap = null; Text text = new Text(currentUserParamDataGroup, SWT.SINGLE | SWT.READ_ONLY); if (extUserPrmData != null) { text.setText(extUserPrmData.getText() + ":"); prmTextMap = extUserPrmData.getPrmText(); if ((extUserPrmData.getPrmText() == null) && (extUserPrmData.getMaxValue() - extUserPrmData.getMinValue() > 10)) { _prmTextCV.add(makeTextField(currentUserParamDataGroup, value, extUserPrmData)); } else { _prmTextCV.add(makeComboViewer(currentUserParamDataGroup, value, extUserPrmData, prmTextMap, byteIndex)); } } new Label(currentUserParamDataGroup, SWT.SEPARATOR | SWT.HORIZONTAL);// .setLayoutData(new } /** * * @param currentUserParamDataGroup * @param value * @param extUserPrmData * @return */ private Text makeTextField(final Composite currentUserParamDataGroup, final Integer value, final ExtUserPrmData extUserPrmData) { Integer localValue = value; Text prmText = new Text(currentUserParamDataGroup, SWT.BORDER | SWT.SINGLE | SWT.RIGHT); Formatter f = new Formatter(); f.format("Min: %d, Min: %d", extUserPrmData.getMinValue(), extUserPrmData.getMaxValue()); prmText.setToolTipText(f.toString()); prmText.setTextLimit(Integer.toString(extUserPrmData.getMaxValue()) .length()); if (localValue == null) { localValue = extUserPrmData.getDefault(); } prmText.setText(localValue.toString()); prmText.setData(localValue.toString()); prmText.addModifyListener(getMLSB()); prmText.addVerifyListener(new VerifyListener() { public void verifyText(final VerifyEvent e) { if (e.text.matches("^\\D+$")) { e.doit = false; } } }); return prmText; } /** * * @param parent * the Parent Composite. * @param value * the Selected currentUserParamData Value. * @param extUserPrmData * @param prmTextMap * @param byteIndex * @return a ComboView for are currentUserParamData Property */ private ComboViewer makeComboViewer(final Composite parent, final Integer value, final ExtUserPrmData extUserPrmData, final HashMap<Integer, PrmText> prmTextMap, final String byteIndex) { final int index = ProfibusConfigXMLGenerator.getInt(byteIndex); Integer localValue = value; ComboViewer prmTextCV = new ComboViewer(parent); RowData data = new RowData(); data.exclude = false; prmTextCV.getCombo().setLayoutData(data); prmTextCV.setLabelProvider(new LabelProvider()); prmTextCV.setContentProvider(new IStructuredContentProvider() { @Override public Object[] getElements(@Nullable final Object inputElement) { if (inputElement instanceof ExtUserPrmData) { ExtUserPrmData eUPD = (ExtUserPrmData) inputElement; HashMap<Integer, PrmText> prmText = eUPD.getPrmText(); if (prmText == null) { PrmText[] prmTextArray = new PrmText[eUPD.getMaxValue() - eUPD.getMinValue() + 1]; for (int i = eUPD.getMinValue(); i <= eUPD .getMaxValue(); i++) { prmTextArray[i] = new PrmText(Integer.toString(i), i); } return prmTextArray; } return prmText.values().toArray(); } return null; } public void dispose() { } public void inputChanged(final Viewer viewer, final Object oldInput, final Object newInput) { } }); prmTextCV.getCombo().addModifyListener(getMLSB()); prmTextCV.setSorter(new ViewerSorter() { @Override public int compare(final Viewer viewer, final Object e1, final Object e2) { if ((e1 instanceof PrmText) && (e2 instanceof PrmText)) { PrmText eUPD1 = (PrmText) e1; PrmText eUPD2 = (PrmText) e2; return eUPD1.getValue() - eUPD2.getValue(); } return super.compare(viewer, e1, e2); } }); if (localValue == null) { localValue = extUserPrmData.getDefault(); } prmTextCV.setInput(extUserPrmData); if (prmTextMap != null) { PrmText prmText = prmTextMap.get(localValue); if (prmText != null) { prmTextCV.setSelection(new StructuredSelection(prmTextMap .get(localValue))); } else { prmTextCV.getCombo().select(0); } } else { prmTextCV.getCombo().select(localValue); } prmTextCV.getCombo().setData(prmTextCV.getCombo().getSelectionIndex()); setModify(prmTextCV); return prmTextCV; } /** * * @param prmTextCV */ private void setModify(final ComboViewer prmTextCV) { // PrmText prmText = (PrmText) ((StructuredSelection) // prmTextCV.getSelection()) // .getFirstElement(); // ExtUserPrmData extUserPrmData = (ExtUserPrmData) // prmTextCV.getInput(); // String index = extUserPrmData.getIndex(); // GsdModuleModel gsdModule = _slave.getGsdModuleModel(); // int bytePos = // Integer.parseInt(gsdModule.getExtUserPrmDataRef(index)); // int bitMin = extUserPrmData.getMinBit(); // int bitMax = extUserPrmData.getMaxBit(); // // int val = 0; // if (prmText != null) { // val = prmText.getValue(); // } // gsdModule.addModify(bytePos, bitMin, bitMax, val); } /** * {@inheritDoc} */ @Override public void setFocus() { // TODO Auto-generated method stub } protected void setDefaultBackgroundColor( @Nonnull Color defaultBackgroundColor) { _defaultBackgroundColor = defaultBackgroundColor; } @CheckForNull protected Color getDefaultBackgroundColor() { return _defaultBackgroundColor; } protected void setFailButton(@Nonnull Button failButton) { _failButton = failButton; } @CheckForNull Button getFailButton() { return _failButton; } }
applications/plugins/org.csstudio.config.ioconfig.view/src/java/org/csstudio/config/ioconfig/editorparts/SlaveEditor.java
/* * Copyright (c) 2010 Stiftung Deutsches Elektronen-Synchrotron, * Member of the Helmholtz Association, (DESY), HAMBURG, GERMANY. * * THIS SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "../AS IS" BASIS. * WITHOUT WARRANTY OF ANY KIND, EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR PARTICULAR PURPOSE AND * NON-INFRINGEMENT. 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. SHOULD THE SOFTWARE PROVE DEFECTIVE * IN ANY RESPECT, THE USER ASSUMES THE COST OF ANY NECESSARY SERVICING, REPAIR OR * CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. * NO USE OF ANY SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. * DESY HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, * OR MODIFICATIONS. * THE FULL LICENSE SPECIFYING FOR THE SOFTWARE THE REDISTRIBUTION, MODIFICATION, * USAGE AND OTHER RIGHTS AND OBLIGATIONS IS INCLUDED WITH THE DISTRIBUTION OF THIS * PROJECT IN THE FILE LICENSE.HTML. IF THE LICENSE IS NOT INCLUDED YOU MAY FIND A COPY * AT HTTP://WWW.DESY.DE/LEGAL/LICENSE.HTM */ package org.csstudio.config.ioconfig.editorparts; import java.util.ArrayList; import java.util.Collection; import java.util.Formatter; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeMap; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.csstudio.config.ioconfig.config.view.OverviewLabelProvider; import org.csstudio.config.ioconfig.config.view.helper.ProfibusHelper; import org.csstudio.config.ioconfig.model.DocumentDBO; import org.csstudio.config.ioconfig.model.AbstractNodeDBO; import org.csstudio.config.ioconfig.model.pbmodel.ChannelDBO; import org.csstudio.config.ioconfig.model.pbmodel.ChannelStructureDBO; import org.csstudio.config.ioconfig.model.pbmodel.GSDFileDBO; import org.csstudio.config.ioconfig.model.pbmodel.ModuleDBO; import org.csstudio.config.ioconfig.model.pbmodel.Ranges; import org.csstudio.config.ioconfig.model.pbmodel.SlaveDBO; import org.csstudio.config.ioconfig.model.pbmodel.gsdParser.ExtUserPrmData; import org.csstudio.config.ioconfig.model.pbmodel.gsdParser.ExtUserPrmDataConst; import org.csstudio.config.ioconfig.model.pbmodel.gsdParser.ExtUserPrmDataRef; import org.csstudio.config.ioconfig.model.pbmodel.gsdParser.GSD2Module; import org.csstudio.config.ioconfig.model.pbmodel.gsdParser.GsdFactory; import org.csstudio.config.ioconfig.model.pbmodel.gsdParser.GsdModuleModel; import org.csstudio.config.ioconfig.model.pbmodel.gsdParser.GsdSlaveModel; import org.csstudio.config.ioconfig.model.pbmodel.gsdParser.PrmText; import org.csstudio.config.ioconfig.model.xml.ProfibusConfigXMLGenerator; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.events.ControlAdapter; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowData; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.Text; /** * TODO (hrickens) : * * @author hrickens * @author $Author: hrickens $ * @version $Revision: 1.3 $ * @since 21.05.2010 */ public class SlaveEditor extends AbstractNodeEditor { public static final String ID = "org.csstudio.config.ioconfig.view.editor.slave"; /** * The Slave which displayed. */ private SlaveDBO _slave; /** * The GSD File of the Slave. */ private GSDFileDBO _gsdFile; /** * The Text field for the Vendor. */ private Text _vendorText; /** * Slave ID Number. */ private Text _iDNo; /** * The Text field for the Revision. */ private Text _revisionsText; /** * The Module max size of this Slave. */ private int _maxSize; /** * The number of max slots. */ private Text _maxSlots; /** * List with User Prm Data's. */ private TableViewer _userPrmDataList; /** * Inputs. */ private Text _inputsText; /** * Outputs. */ private Text _outputsText; /** * Die Bedeutung dieses Feldes ist noch unbekannt. */ // private Text _unbekannt; /** * The minimum Station Delay Time. */ private Text _minStationDelayText; /** * The Watchdog Time. */ private Text _watchDogText; /** * Marker of Background Color for normal use. Get from widget by first use. */ private Color _defaultBackgroundColor; /** * Check Button to de.-/activate Station Address. */ private Button _stationAddressActiveCButton; private Button _freezeButton; private Button _failButton; private Button _watchDogButton; private Button _syncButton; private int _groupIdent; private int _groupIdentStored; private Group _groupsRadioButtons; private ComboViewer _indexCombo; private Group _currentUserParamDataGroup; private final ArrayList<Object> _prmTextCV = new ArrayList<Object>(); /** * * @author hrickens * @author $Author: hrickens $ * @version $Revision: 1.3 $ * @since 14.08.2007 */ class RowNumLabelProvider implements ITableLabelProvider { /** * {@inheritDoc} */ public void addListener(final ILabelProviderListener listener) { // handle no listener } /** * {@inheritDoc} */ public void dispose() { if (_defaultBackgroundColor != null) { _defaultBackgroundColor.dispose(); } } /** * {@inheritDoc} */ public boolean isLabelProperty(final Object element, final String property) { return false; } /** * {@inheritDoc} */ public void removeListener(final ILabelProviderListener listener) { // handle no listener } public Image getColumnImage(final Object element, final int columnIndex) { return null; } public String getColumnText(final Object element, final int columnIndex) { if (element instanceof SlaveDBO) { SlaveDBO slave = (SlaveDBO) element; return onSlave(slave, columnIndex); } else if (element instanceof ModuleDBO) { ModuleDBO module = (ModuleDBO) element; return onModule(module, columnIndex); } return null; } /** * @param module * @param columnIndex */ @Nullable private String onModule(@Nonnull final ModuleDBO module, final int columnIndex) { switch (columnIndex) { case 0: return module.getSortIndex().toString(); case 1: return module.getName(); case 2: return module.getExtUserPrmDataConst(); default: break; } return null; } /** * @param slave */ @Nullable private String onSlave(@Nonnull final SlaveDBO slave, final int columnIndex) { // TreeMap<String, ExtUserPrmDataConst> extUserPrmDataConst = slave.getGSDSlaveData() // .getExtUserPrmDataConst(); switch (columnIndex) { case 1: return slave.getName(); case 2: // StringBuffer sb = new StringBuffer(); // Set<String> keySet = extUserPrmDataConst.keySet(); // for (String key : keySet) { // sb.append(extUserPrmDataConst.get(key).getValue()); // } // return sb.toString(); return slave.getPrmUserData(); default: break; } return null; } } /** * {@inheritDoc} */ @Override public void createPartControl(final Composite parent) { _slave = (SlaveDBO) getNode(); super.createPartControl(parent); makeSlaveKonfiguration(parent); getTabFolder().setSelection(0); } /** * @param parent * Parent Composite. * @param style * Style of the Composite. * @param slave * the Profibus Slave to Configer. */ private void makeSlaveKonfiguration(final Composite parent) { boolean nevv = false; if (_slave == null) { if (!newNode("TODO")) { // this.dispose(); setSaveButtonSaved(); getProfiBusTreeView().getTreeViewer().setSelection(getProfiBusTreeView() .getTreeViewer().getSelection()); return; } nevv = true; _slave.setMinTsdr((short) 11); _slave.setWdFact1((short) 100); } setSavebuttonEnabled(null, getNode().isPersistent()); String[] heads = { "Basics", "Settings", "Overview" }; overview(heads[2]); settings(heads[1]); basics(heads[0]); if (_slave.getGSDFile() != null) { fill(_slave.getGSDFile()); } getTabFolder().pack(); if (nevv) { getTabFolder().setSelection(4); } } @SuppressWarnings("unchecked") private void overview(final String headline) { Composite comp = getNewTabItem(headline, 1); comp.setLayout(new GridLayout(1, false)); TableViewer overViewer = new TableViewer(comp, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.FULL_SELECTION); overViewer.setContentProvider(new ArrayContentProvider()); overViewer.setLabelProvider(new OverviewLabelProvider()); overViewer.getTable().setHeaderVisible(true); overViewer.getTable().setLinesVisible(true); overViewer.getTable().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); TableColumn c0 = new TableColumn(overViewer.getTable(), SWT.RIGHT); c0.setText("Adr"); TableColumn c0b = new TableColumn(overViewer.getTable(), SWT.RIGHT); c0b.setText("Adr"); TableColumn c1 = new TableColumn(overViewer.getTable(), SWT.LEFT); c1.setText("Name"); TableColumn c2 = new TableColumn(overViewer.getTable(), SWT.LEFT); // c2.setWidth(200); c2.setText("IO Name"); TableColumn c3 = new TableColumn(overViewer.getTable(), SWT.LEFT); // c3.setWidth(200); c3.setText("IO Epics Address"); TableColumn c4 = new TableColumn(overViewer.getTable(), SWT.LEFT); // c4.setWidth(200); c4.setText("Desc"); TableColumn c5 = new TableColumn(overViewer.getTable(), SWT.LEFT); // c5.setWidth(60); c5.setText("Type"); TableColumn c6 = new TableColumn(overViewer.getTable(), SWT.LEFT); // c5.setWidth(60); c6.setText("DB Id"); overViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(final SelectionChangedEvent event) { // IStructuredSelection sel = (IStructuredSelection) event.getSelection(); getProfiBusTreeView().getTreeViewer().setSelection(event.getSelection(), true); } }); ArrayList<AbstractNodeDBO> children = new ArrayList<AbstractNodeDBO>(); Collection<ModuleDBO> modules = (Collection<ModuleDBO>) _slave.getChildrenAsMap().values(); for (ModuleDBO module : modules) { children.add(module); Collection<ChannelStructureDBO> channelStructures = module.getChannelStructsAsMap() .values(); for (ChannelStructureDBO channelStructure : channelStructures) { Collection<ChannelDBO> channels = channelStructure.getChannelsAsMap().values(); for (ChannelDBO channel : channels) { children.add(channel); } } } overViewer.setInput(children); c0.pack(); c0b.pack(); c1.pack(); c2.pack(); c3.pack(); c4.pack(); c5.pack(); c6.pack(); } /** * @param head * The Tab text. */ private void basics(final String head) { Composite comp = getNewTabItem(head, 2); /* * Name */ Group gName = new Group(comp, SWT.NONE); gName.setText("Name"); gName.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 5, 1)); gName.setLayout(new GridLayout(3, false)); Text nameText = new Text(gName, SWT.BORDER | SWT.SINGLE); setText(nameText, _slave.getName(), 255); nameText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1)); setNameWidget(nameText); // Label Label slotIndexLabel = new Label(gName, SWT.NONE); slotIndexLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); slotIndexLabel.setText("Station Adress:"); _indexCombo = new ComboViewer(gName, SWT.DROP_DOWN | SWT.READ_ONLY); _indexCombo.getCombo().setLayoutData(new GridData(SWT.RIGHT, SWT.RIGHT, false, false)); _indexCombo.setContentProvider(new ArrayContentProvider()); _indexCombo.setLabelProvider(new LabelProvider()); Collection<Short> freeStationAddress = _slave.getProfibusDPMaster().getFreeStationAddress(); Short sortIndex = _slave.getSortIndex(); if (sortIndex >= 0) { if (!freeStationAddress.contains(sortIndex)) { freeStationAddress.add(sortIndex); } _indexCombo.setInput(freeStationAddress); _indexCombo.setSelection(new StructuredSelection(sortIndex)); } else { _indexCombo.setInput(freeStationAddress); _indexCombo.getCombo().select(0); _slave.setSortIndexNonHibernate((Short) ((StructuredSelection) _indexCombo .getSelection()).getFirstElement()); } _indexCombo.getCombo().setData(_indexCombo.getCombo().getSelectionIndex()); _indexCombo.getCombo().addModifyListener(getMLSB()); _indexCombo.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(final SelectionChangedEvent event) { short index = (Short) ((StructuredSelection) _indexCombo.getSelection()) .getFirstElement(); getNode().moveSortIndex(index); if (getNode().getParent() != null) { getProfiBusTreeView().refresh(getNode().getParent()); } else { getProfiBusTreeView().refresh(); } } }); // setIndexSpinner(ConfigHelper.getIndexSpinner(gName, _slave, getMLSB(), // "Station Adress:",getProfiBusTreeView())); // _defaultBackgroundColor = getIndexSpinner().getBackground(); /* * Slave Information */ Group slaveInfoGroup = new Group(comp, SWT.NONE); slaveInfoGroup.setText("Slave Information"); slaveInfoGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 2)); slaveInfoGroup.setLayout(new GridLayout(4, false)); slaveInfoGroup.setTabList(new Control[0]); _vendorText = new Text(slaveInfoGroup, SWT.SINGLE | SWT.BORDER); _vendorText.setEditable(false); _vendorText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 4, 1)); _iDNo = new Text(slaveInfoGroup, SWT.SINGLE); _iDNo.setEditable(false); _iDNo.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1)); Label revisionsLable = new Label(slaveInfoGroup, SWT.NONE); revisionsLable.setText("Revision:"); _revisionsText = new Text(slaveInfoGroup, SWT.SINGLE); _revisionsText.setEditable(false); _revisionsText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1)); new Label(slaveInfoGroup, SWT.None).setText("Max. available slots:"); _maxSlots = new Text(slaveInfoGroup, SWT.BORDER); _maxSlots.setEditable(false); /* * DP/FDL Access Group */ Group dpFdlAccessGroup = new Group(comp, SWT.NONE); dpFdlAccessGroup.setText("DP / FDL Access"); dpFdlAccessGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); dpFdlAccessGroup.setLayout(new GridLayout(2, false)); Label stationAdrLabel = new Label(dpFdlAccessGroup, SWT.None); stationAdrLabel.setText("Station Address"); GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1); gd.minimumWidth = 50; _stationAddressActiveCButton = new Button(dpFdlAccessGroup, SWT.CHECK); _stationAddressActiveCButton.setText("Active"); _stationAddressActiveCButton.setSelection(false); _stationAddressActiveCButton.setData(false); _stationAddressActiveCButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(final SelectionEvent e) { change(); } public void widgetSelected(final SelectionEvent e) { change(); } private void change() { setSavebuttonEnabled("Button:" + _stationAddressActiveCButton.hashCode(), (Boolean) _stationAddressActiveCButton.getData() != _stationAddressActiveCButton .getSelection()); } }); /* * Input / Output Group */ Group ioGroup = new Group(comp, SWT.NONE); ioGroup.setText("Inputs / Outputs"); ioGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); ioGroup.setLayout(new GridLayout(3, false)); ioGroup.setTabList(new Control[0]); int input = 0; int output = 0; if (_slave.hasChildren()) { Iterator<ModuleDBO> iterator = _slave.getModules().iterator(); while (iterator.hasNext()) { ModuleDBO module = iterator.next(); input += module.getInputSize(); output += module.getOutputSize(); } } Label inputLabel = new Label(ioGroup, SWT.RIGHT); inputLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false, 2, 1)); inputLabel.setText("Inputs: "); _inputsText = new Text(ioGroup, SWT.SINGLE); _inputsText.setEditable(false); _inputsText.setText(Integer.toString(input)); Label outputsLabel = new Label(ioGroup, SWT.RIGHT); outputsLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false, 2, 1)); outputsLabel.setText("Outputs: "); _outputsText = new Text(ioGroup, SWT.SINGLE); _outputsText.setEditable(false); _outputsText.setText(Integer.toString(output)); /* * Description Group */ makeDescGroup(comp, 3); } /** * */ private void setSlots() { Formatter slotFormarter = new Formatter(); slotFormarter.format(" %2d / %2d", _slave.getChildren().size(), _maxSize); _maxSlots.setText(slotFormarter.toString()); if (_maxSize < _slave.getChildren().size()) { if (_defaultBackgroundColor == null) { _defaultBackgroundColor = Display.getDefault() .getSystemColor(SWT.COLOR_WIDGET_BACKGROUND); } _maxSlots.setBackground(WARN_BACKGROUND_COLOR); } else { _maxSlots.setBackground(_defaultBackgroundColor); } slotFormarter = null; } /** * @param head * the tabItemName */ private void settings(final String head) { Composite comp = getNewTabItem(head, 2); comp.setLayout(new GridLayout(3, false)); // Operation Mode Group operationModeGroup = new Group(comp, SWT.NONE); GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); layoutData.minimumWidth = 170; operationModeGroup.setLayoutData(layoutData); operationModeGroup.setText("Operation Mode"); operationModeGroup.setLayout(new GridLayout(3, false)); Label delayLabel = new Label(operationModeGroup, SWT.NONE); delayLabel.setText("Min. Station Delay"); _minStationDelayText = ProfibusHelper.getTextField(operationModeGroup, true, _slave .getMinTsdr() + "", Ranges.WATCHDOG, ProfibusHelper.VL_TYP_U16); Label bitLabel = new Label(operationModeGroup, SWT.NONE); bitLabel.setText("Bit"); _syncButton = new Button(operationModeGroup, SWT.CHECK); _syncButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 3, 1)); _syncButton.addTraverseListener(ProfibusHelper.getNETL()); _syncButton.setText("Sync Request"); _syncButton.setData(false); _syncButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(final SelectionEvent e) { change(_syncButton); } public void widgetSelected(final SelectionEvent e) { change(_syncButton); } }); _freezeButton = new Button(operationModeGroup, SWT.CHECK); _freezeButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 3, 1)); _freezeButton.addTraverseListener(ProfibusHelper.getNETL()); _freezeButton.setText("Freeze Request"); _freezeButton.setSelection(false); _freezeButton.setData(false); _freezeButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(final SelectionEvent e) { change(_freezeButton); } public void widgetSelected(final SelectionEvent e) { change(_freezeButton); } }); _failButton = new Button(operationModeGroup, SWT.CHECK); _failButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 3, 1)); _failButton.addTraverseListener(ProfibusHelper.getNETL()); _failButton.setText("Fail Save"); _failButton.setEnabled(false); _failButton.setData(false); _failButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(final SelectionEvent e) { change(_failButton); } public void widgetSelected(final SelectionEvent e) { change(_failButton); } }); _watchDogButton = new Button(operationModeGroup, SWT.CHECK); _watchDogButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); _watchDogButton.addTraverseListener(ProfibusHelper.getNETL()); _watchDogButton.setText("Watchdog Time"); _watchDogButton.setSelection(true); _watchDogButton.setData(true); _watchDogText = ProfibusHelper.getTextField(operationModeGroup, _watchDogButton.getSelection(), Integer.toString(_slave.getWdFact1()), Ranges.TTR, ProfibusHelper.VL_TYP_U32); _watchDogText.addModifyListener(getMLSB()); Label timeLabel = new Label(operationModeGroup, SWT.NONE); timeLabel.setText("ms"); _watchDogButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(final SelectionEvent e) { change(); } public void widgetSelected(final SelectionEvent e) { change(); } private void change() { SlaveEditor.this.change(_watchDogButton); _watchDogText.setEnabled(_watchDogButton.getSelection()); } }); makeCurrentUserParamData(comp); makeUserPRMMode(comp); } /** * @param comp */ private void makeUserPRMMode(final Composite comp) { Group userPrmData = new Group(comp, SWT.V_SCROLL); userPrmData.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 2)); userPrmData.setLayout(new GridLayout(2, false)); userPrmData.setTabList(new Control[0]); userPrmData.setText("User PRM Mode"); _userPrmDataList = new TableViewer(userPrmData, SWT.BORDER | SWT.V_SCROLL); Table table = _userPrmDataList.getTable(); table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 15)); table.setHeaderVisible(true); table.setLinesVisible(true); _userPrmDataList.setContentProvider(new ArrayContentProvider()); _userPrmDataList.setLabelProvider(new RowNumLabelProvider()); TableColumn tc = new TableColumn(table, SWT.RIGHT); tc.setText(""); tc.setWidth(20); tc = new TableColumn(table, SWT.LEFT); tc.setText("Name"); tc.setWidth(130); tc = new TableColumn(table, SWT.LEFT); tc.setText("Ext User Prm Data Const"); tc.setWidth(450); // Groups _groupsRadioButtons = new Group(comp, SWT.NONE); _groupsRadioButtons.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1)); _groupsRadioButtons.setLayout(new GridLayout(4, true)); _groupsRadioButtons.setText("Groups"); _groupIdentStored = _slave.getGroupIdent(); if ( (_groupIdentStored < 0) || (_groupIdentStored > 7)) { _groupIdentStored = 0; } _groupIdent = _groupIdentStored; for (int i = 0; i <= 7; i++) { final Button b = new Button(_groupsRadioButtons, SWT.RADIO); b.setText(Integer.toString(i + 1)); if (i == _groupIdent) { b.setSelection(true); } b.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(final SelectionEvent e) { check(); } public void widgetSelected(final SelectionEvent e) { check(); } private void check() { _groupIdent = Short.parseShort(b.getText()); _groupIdent--; setSavebuttonEnabled("groupButton" + _groupsRadioButtons.hashCode(), _groupIdent != _groupIdentStored); } }); } } /** {@inheritDoc} */ @Override public final boolean fill(final GSDFileDBO gsdFile) { /* * Read GSD-File */ if (gsdFile == null) { return false; } else if (gsdFile.equals(_gsdFile)) { return true; } _gsdFile = gsdFile; GsdSlaveModel slaveModel = GsdFactory.makeGsdSlave(_gsdFile); // setGSDData HashMap<Integer, GsdModuleModel> moduleList = GSD2Module.parse(_gsdFile, slaveModel); slaveModel.setGsdModuleList(moduleList); _slave.setGSDSlaveData(slaveModel); /* * Head */ getHeaderField(HeaderFields.VERSION).setText(slaveModel.getGsdRevision() + ""); /* * Basic - Slave Discription (read only) */ _vendorText.setText(slaveModel.getVendorName()); _iDNo.setText(String.format("0x%04X", slaveModel.getIdentNumber())); _revisionsText.setText(slaveModel.getRevision()); /* * Basic - Inputs / Outputs (read only) */ /* * Set all GSD-File Data to Slave. */ _slave.setMinTsdr(_slave.getMinTsdr()); _slave.setModelName(slaveModel.getModelName()); _slave.setPrmUserData(slaveModel.getUserPrmData()); _slave.setProfibusPNoID(slaveModel.getIdentNumber()); _slave.setRevision(slaveModel.getRevision()); /* * Basic - DP / FDL Access */ /* * Modules */ _maxSize = slaveModel.getMaxModule(); setSlots(); /* * Settings - Operation Mode */ /* * Settings - Groups */ /* * Settings - USER PRM MODE */ ArrayList<AbstractNodeDBO> nodes = new ArrayList<AbstractNodeDBO>(); nodes.add(_slave); nodes.addAll(_slave.getChildrenAsMap().values()); _userPrmDataList.setInput(nodes); TableColumn[] columns = _userPrmDataList.getTable().getColumns(); for (TableColumn tableColumn : columns) { if (tableColumn != null) { tableColumn.pack(); } } return true; } /** {@inheritDoc} */ @Override public final GSDFileDBO getGSDFile() { return _slave.getGSDFile(); } /** * {@inheritDoc} */ @Override public void doSave(final IProgressMonitor monitor) { super.doSave(monitor); // Name _slave.setName(getNameWidget().getText()); getNameWidget().setData(getNameWidget().getText()); // _slave.moveSortIndex((short) getIndexSpinner().getSelection()); Short stationAddress = (Short) ((StructuredSelection) _indexCombo.getSelection()) .getFirstElement(); _slave.setSortIndexNonHibernate(stationAddress); _slave.setFdlAddress(stationAddress); _indexCombo.getCombo().setData(_indexCombo.getCombo().getSelectionIndex()); short minTsdr = 0; try { minTsdr = Short.parseShort(_minStationDelayText.getText()); } catch (NumberFormatException e) { } _slave.setMinTsdr(minTsdr); _slave.setGroupIdent(_groupIdent); _groupIdentStored = _groupIdent; _slave.setSlaveFlag((short) 192); short wdFact = Short.parseShort(_watchDogText.getText()); _watchDogText.setData(_watchDogText.getText()); _slave.setWdFact1(wdFact); _slave.setWdFact2((short) (wdFact / 10)); // Static Station status 136 _slave.setStationStatus((short) 136); saveUserPrmData(); // GSD File _slave.setGSDFile(_gsdFile); fill(_gsdFile); // Document Set<DocumentDBO> docs = getDocumentationManageView().getDocuments(); _slave.setDocuments(docs); _slave.update(); save(); } /** * */ private void saveUserPrmData() { TreeMap<String, ExtUserPrmDataConst> extUserPrmDataConst = _slave.getGSDSlaveData().getExtUserPrmDataConst(); List<ExtUserPrmDataRef> extUserPrmDataRefMap = _slave.getGSDSlaveData().getExtUserPrmDataRefMap(); if(extUserPrmDataRefMap.size()==_prmTextCV.size()) { for (int i = 0; i < extUserPrmDataRefMap.size(); i++) { ExtUserPrmDataRef ref = extUserPrmDataRefMap.get(i); Object prmTextObject = _prmTextCV.get(i); if (prmTextObject instanceof ComboViewer) { ComboViewer prmTextCV = (ComboViewer) prmTextObject; handleComboViewer(extUserPrmDataConst, prmTextCV, ref.getValue()); } else if (prmTextObject instanceof Text) { Text prmText = (Text) prmTextObject; extUserPrmDataConst = handleText(extUserPrmDataConst, prmText, ref.getValue()); } } }else { //TODO: throw extUserPrmDataRefMap und prmTextCV passen nicht zu sammen } // GsdModuleModel mod = (GsdModuleModel) ((StructuredSelection) _moduleTypList.getSelection()) // .getFirstElement(); // if (mod != null) { //// _slave.setModuleNumber(mod.getModuleNumber()); //// _moduleTypList.getTable().setData(mod.getModuleNumber()); // //// String[] extUserPrmDataConst = _module.getGsdModuleModel().getExtUserPrmDataConst() //// .split(","); // // String extUserPrmDataConst = _slave.getPrmUserData(); // for (Object prmTextObject : _prmTextCV) { // if (prmTextObject instanceof ComboViewer) { // ComboViewer prmTextCV = (ComboViewer) prmTextObject; //// handleComboViewer(extUserPrmDataConst, prmTextCV); // } else if (prmTextObject instanceof Text) { // Text prmText = (Text) prmTextObject; //// extUserPrmDataConst = handleText(extUserPrmDataConst, prmText); // } // } //// _module.setConfigurationData(Arrays.toString(extUserPrmDataConst) //// .replaceAll("[\\[\\]]", "")); // } } /** * @param extUserPrmDataConst * @param prmText * @return */ @Nonnull private TreeMap<String, ExtUserPrmDataConst> handleText(@Nonnull final TreeMap<String,ExtUserPrmDataConst> extUserPrmDataConst,@Nonnull final Text prmText) { if (!prmText.isDisposed()) { String value = (String) prmText.getData(); if (value != null) { prmText.setText(value); int val = Integer.parseInt(value); // return new String[] {String.format("%1$#04x", val) }; } } return extUserPrmDataConst; } /** * @param extUserPrmDataConst * @param byteIndexString * @param prmTextObject */ private void handleComboViewer(final TreeMap<String,ExtUserPrmDataConst> extUserPrmDataConst, final ComboViewer prmTextCV, final String byteIndexString) { if (!prmTextCV.getCombo().isDisposed()) { int byteIndex = ProfibusConfigXMLGenerator.getInt(byteIndexString); ExtUserPrmData input = (ExtUserPrmData) prmTextCV.getInput(); StructuredSelection selection = (StructuredSelection) prmTextCV .getSelection(); Integer bitValue = ((PrmText) selection.getFirstElement()).getValue(); String newValue = setValue2BitMask(input, bitValue, _slave.getPrmUserDataList().get(byteIndex)); _slave.setPrmUserDataByte(byteIndex, newValue); Integer indexOf = prmTextCV.getCombo().indexOf(selection.getFirstElement() .toString()); prmTextCV.getCombo().setData(indexOf); } } /** * Change the a value on the Bit places, that is given from the input, to the bitValue. * * @param ranges * give the start and end Bit position. * @param bitValue * the new Value for the given Bit position. * @param value * the value was changed. * @return the changed value as Hex String. */ @Nonnull private String setValue2BitMask(@Nonnull final ExtUserPrmData ranges, @Nonnull final Integer bitValue, @Nonnull final String value) { int val = ProfibusConfigXMLGenerator.getInt(value); int minBit = ranges.getMinBit(); int maxBit = ranges.getMaxBit(); if (maxBit < minBit) { minBit = ranges.getMaxBit(); maxBit = ranges.getMinBit(); } int mask = ~ ((int) (Math.pow(2, maxBit + 1) - Math.pow(2, minBit))); val = val & mask; val = val | (bitValue << minBit); return String.format("%1$#04x", val); } /* * (non-Javadoc) * * @see org.csstudio.config.ioconfig.config.view.NodeConfig#cancel() */ @Override public void cancel() { super.cancel(); // getIndexSpinner().setSelection((Short) getIndexSpinner().getData()); if (_indexCombo != null) { _indexCombo.getCombo().select((Integer) _indexCombo.getCombo().getData()); getNameWidget().setText((String) getNameWidget().getData()); _stationAddressActiveCButton.setSelection((Boolean) _stationAddressActiveCButton .getData()); _minStationDelayText.setText((String) _minStationDelayText.getData()); _syncButton.setSelection((Boolean) _syncButton.getData()); _failButton.setSelection((Boolean) _failButton.getData()); _freezeButton.setSelection((Boolean) _freezeButton.getData()); _watchDogButton.setSelection((Boolean) _watchDogButton.getData()); _watchDogText.setEnabled(_watchDogButton.getSelection()); _watchDogText.setText((String) _watchDogText.getData()); _groupIdent = _groupIdentStored; for (Control control : _groupsRadioButtons.getChildren()) { if (control instanceof Button) { Button button = (Button) control; button .setSelection(Short.parseShort(button.getText()) == _groupIdentStored + 1); } } if (_slave != null) { if (_slave.getGSDFile() != null) { fill(_slave.getGSDFile()); } else { getHeaderField(HeaderFields.VERSION).setText(""); _vendorText.setText(""); getNameWidget().setText(""); _revisionsText.setText(""); } } else { _gsdFile = null; fill(_gsdFile); } } } private void change(final Button button) { setSavebuttonEnabled("Button:" + button.hashCode(), (Boolean) button.getData() != button .getSelection()); } /** * * @param topGroup * The parent Group for the CurrentUserParamData content. */ private void makeCurrentUserParamData(final Composite topGroup) { if (_currentUserParamDataGroup != null) { _currentUserParamDataGroup.dispose(); } // Current User Param Data Group _currentUserParamDataGroup = new Group(topGroup, SWT.NONE); GridData gd = new GridData(SWT.FILL, SWT.FILL, false, true, 1, 3); _currentUserParamDataGroup.setLayoutData(gd); _currentUserParamDataGroup.setLayout(new FillLayout()); _currentUserParamDataGroup.setText("Current User Param Data:"); final ScrolledComposite scrollComposite = new ScrolledComposite(_currentUserParamDataGroup, SWT.V_SCROLL); final Composite currentUserParamDataComposite = new Composite(scrollComposite, SWT.NONE); RowLayout rowLayout = new RowLayout(SWT.VERTICAL); rowLayout.wrap = false; rowLayout.fill = true; currentUserParamDataComposite.setLayout(rowLayout); scrollComposite.setContent(currentUserParamDataComposite); scrollComposite.setExpandHorizontal(true); scrollComposite.setExpandVertical(true); _currentUserParamDataGroup.addControlListener(new ControlAdapter() { @Override public void controlResized(@Nonnull final ControlEvent e) { Rectangle r = scrollComposite.getClientArea(); scrollComposite.setMinSize(scrollComposite.computeSize(r.width, SWT.DEFAULT)); } }); scrollComposite.addControlListener(new ControlAdapter() { @Override public void controlResized(@Nonnull final ControlEvent e) { Rectangle r = scrollComposite.getClientArea(); scrollComposite.setMinSize(currentUserParamDataComposite.computeSize(r.width, SWT.DEFAULT)); } }); // Current User Param Data GsdSlaveModel gsdSlaveModel = _slave.getGSDSlaveData(); if (gsdSlaveModel != null) { List<ExtUserPrmDataRef> extUserPrmDataRefMap = gsdSlaveModel.getExtUserPrmDataRefMap(); if (extUserPrmDataRefMap != null) { for (ExtUserPrmDataRef extUserPrmDataRef : extUserPrmDataRefMap) { int val = 0; String byteIndex = extUserPrmDataRef.getIndex(); ExtUserPrmData extUserPrmData = gsdSlaveModel .getExtUserPrmData(extUserPrmDataRef.getValue()); makeCurrentUserParamDataItem(currentUserParamDataComposite, extUserPrmData, val, byteIndex); } } } topGroup.layout(); } /** * * @param currentUserParamDataGroup * @param extUserPrmData * @param value * @param byteIndex */ private void makeCurrentUserParamDataItem(final Composite currentUserParamDataGroup, final ExtUserPrmData extUserPrmData, final Integer value, final String byteIndex) { HashMap<Integer, PrmText> prmTextMap = null; Text text = new Text(currentUserParamDataGroup, SWT.SINGLE | SWT.READ_ONLY); if (extUserPrmData != null) { text.setText(extUserPrmData.getText() + ":"); prmTextMap = extUserPrmData.getPrmText(); if ( (extUserPrmData.getPrmText() == null) && (extUserPrmData.getMaxValue() - extUserPrmData.getMinValue() > 10)) { _prmTextCV.add(makeTextField(currentUserParamDataGroup, value, extUserPrmData)); } else { _prmTextCV.add(makeComboViewer(currentUserParamDataGroup, value, extUserPrmData, prmTextMap, byteIndex)); } } new Label(currentUserParamDataGroup, SWT.SEPARATOR | SWT.HORIZONTAL);// .setLayoutData(new } /** * * @param currentUserParamDataGroup * @param value * @param extUserPrmData * @return */ private Text makeTextField(final Composite currentUserParamDataGroup, final Integer value, final ExtUserPrmData extUserPrmData) { Integer localValue = value; Text prmText = new Text(currentUserParamDataGroup, SWT.BORDER | SWT.SINGLE | SWT.RIGHT); Formatter f = new Formatter(); f.format("Min: %d, Min: %d", extUserPrmData.getMinValue(), extUserPrmData.getMaxValue()); prmText.setToolTipText(f.toString()); prmText.setTextLimit(Integer.toString(extUserPrmData.getMaxValue()).length()); if (localValue == null) { localValue = extUserPrmData.getDefault(); } prmText.setText(localValue.toString()); prmText.setData(localValue.toString()); prmText.addModifyListener(getMLSB()); prmText.addVerifyListener(new VerifyListener() { public void verifyText(final VerifyEvent e) { if (e.text.matches("^\\D+$")) { e.doit = false; } } }); return prmText; } /** * * @param parent * the Parent Composite. * @param value * the Selected currentUserParamData Value. * @param extUserPrmData * @param prmTextMap * @param byteIndex * @return a ComboView for are currentUserParamData Property */ private ComboViewer makeComboViewer(final Composite parent, final Integer value, final ExtUserPrmData extUserPrmData, final HashMap<Integer, PrmText> prmTextMap, final String byteIndex) { final int index = ProfibusConfigXMLGenerator.getInt(byteIndex); Integer localValue = value; ComboViewer prmTextCV = new ComboViewer(parent); RowData data = new RowData(); data.exclude = false; prmTextCV.getCombo().setLayoutData(data); prmTextCV.setLabelProvider(new LabelProvider()); prmTextCV.setContentProvider(new IStructuredContentProvider() { public Object[] getElements(final Object inputElement) { if (inputElement instanceof ExtUserPrmData) { ExtUserPrmData extUserPrmData = (ExtUserPrmData) inputElement; HashMap<Integer, PrmText> prmText = extUserPrmData.getPrmText(); if (prmText == null) { PrmText[] prmTextArray = new PrmText[extUserPrmData.getMaxValue() - extUserPrmData.getMinValue() + 1]; for (int i = extUserPrmData.getMinValue(); i <= extUserPrmData .getMaxValue(); i++) { prmTextArray[i] = new PrmText(Integer.toString(i), i); } return prmTextArray; } return prmText.values().toArray(); } return null; } public void dispose() { } public void inputChanged(final Viewer viewer, final Object oldInput, final Object newInput) { } }); prmTextCV.getCombo().addModifyListener(getMLSB()); prmTextCV.setSorter(new ViewerSorter() { @Override public int compare(final Viewer viewer, final Object e1, final Object e2) { if ( (e1 instanceof PrmText) && (e2 instanceof PrmText)) { PrmText eUPD1 = (PrmText) e1; PrmText eUPD2 = (PrmText) e2; return eUPD1.getValue() - eUPD2.getValue(); } return super.compare(viewer, e1, e2); } }); if (localValue == null) { localValue = extUserPrmData.getDefault(); } prmTextCV.setInput(extUserPrmData); if (prmTextMap != null) { PrmText prmText = prmTextMap.get(localValue); if (prmText != null) { prmTextCV.setSelection(new StructuredSelection(prmTextMap.get(localValue))); } else { prmTextCV.getCombo().select(0); } } else { prmTextCV.getCombo().select(localValue); } prmTextCV.getCombo().setData(prmTextCV.getCombo().getSelectionIndex()); setModify(prmTextCV); return prmTextCV; } /** * * @param prmTextCV */ private void setModify(final ComboViewer prmTextCV) { // PrmText prmText = (PrmText) ((StructuredSelection) prmTextCV.getSelection()) // .getFirstElement(); // ExtUserPrmData extUserPrmData = (ExtUserPrmData) prmTextCV.getInput(); // String index = extUserPrmData.getIndex(); // GsdModuleModel gsdModule = _slave.getGsdModuleModel(); // int bytePos = Integer.parseInt(gsdModule.getExtUserPrmDataRef(index)); // int bitMin = extUserPrmData.getMinBit(); // int bitMax = extUserPrmData.getMaxBit(); // // int val = 0; // if (prmText != null) { // val = prmText.getValue(); // } // gsdModule.addModify(bytePos, bitMin, bitMax, val); } /** * {@inheritDoc} */ @Override public void setFocus() { // TODO Auto-generated method stub } }
o.c.config.ioconfig.view: fix the handling of free text parameter
applications/plugins/org.csstudio.config.ioconfig.view/src/java/org/csstudio/config/ioconfig/editorparts/SlaveEditor.java
o.c.config.ioconfig.view: fix the handling of free text parameter
<ide><path>pplications/plugins/org.csstudio.config.ioconfig.view/src/java/org/csstudio/config/ioconfig/editorparts/SlaveEditor.java <ide> /* <del> * Copyright (c) 2010 Stiftung Deutsches Elektronen-Synchrotron, <del> * Member of the Helmholtz Association, (DESY), HAMBURG, GERMANY. <del> * <del> * THIS SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "../AS IS" BASIS. <del> * WITHOUT WARRANTY OF ANY KIND, EXPRESSED OR IMPLIED, INCLUDING BUT <del> NOT LIMITED <del> * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR PARTICULAR PURPOSE <del> AND <del> * NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS <del> BE LIABLE <del> * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF <del> CONTRACT, <del> * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE <del> SOFTWARE OR <del> * THE USE OR OTHER DEALINGS IN THE SOFTWARE. SHOULD THE SOFTWARE PROVE <del> DEFECTIVE <del> * IN ANY RESPECT, THE USER ASSUMES THE COST OF ANY NECESSARY SERVICING, <del> REPAIR OR <del> * CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART <del> OF THIS LICENSE. <del> * NO USE OF ANY SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS <del> DISCLAIMER. <del> * DESY HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, <del> ENHANCEMENTS, <del> * OR MODIFICATIONS. <del> * THE FULL LICENSE SPECIFYING FOR THE SOFTWARE THE REDISTRIBUTION, <del> MODIFICATION, <del> * USAGE AND OTHER RIGHTS AND OBLIGATIONS IS INCLUDED WITH THE <del> DISTRIBUTION OF THIS <del> * PROJECT IN THE FILE LICENSE.HTML. IF THE LICENSE IS NOT INCLUDED YOU <del> MAY FIND A COPY <del> * AT HTTP://WWW.DESY.DE/LEGAL/LICENSE.HTM <del> */ <add> * Copyright (c) 2010 Stiftung Deutsches Elektronen-Synchrotron, <add> * Member of the Helmholtz Association, (DESY), HAMBURG, GERMANY. <add> * <add> * THIS SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "../AS IS" BASIS. <add> * WITHOUT WARRANTY OF ANY KIND, EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED <add> * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR PARTICULAR PURPOSE AND <add> * NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE <add> * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, <add> * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR <add> * THE USE OR OTHER DEALINGS IN THE SOFTWARE. SHOULD THE SOFTWARE PROVE DEFECTIVE <add> * IN ANY RESPECT, THE USER ASSUMES THE COST OF ANY NECESSARY SERVICING, REPAIR OR <add> * CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. <add> * NO USE OF ANY SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. <add> * DESY HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, <add> * OR MODIFICATIONS. <add> * THE FULL LICENSE SPECIFYING FOR THE SOFTWARE THE REDISTRIBUTION, MODIFICATION, <add> * USAGE AND OTHER RIGHTS AND OBLIGATIONS IS INCLUDED WITH THE DISTRIBUTION OF THIS <add> * PROJECT IN THE FILE LICENSE.HTML. IF THE LICENSE IS NOT INCLUDED YOU MAY FIND A COPY <add> * AT HTTP://WWW.DESY.DE/LEGAL/LICENSE.HTM <add> */ <ide> package org.csstudio.config.ioconfig.editorparts; <ide> <ide> import java.util.ArrayList; <ide> import java.util.Set; <ide> import java.util.TreeMap; <ide> <add>import javax.annotation.CheckForNull; <ide> import javax.annotation.Nonnull; <ide> import javax.annotation.Nullable; <ide> <ide> <ide> /** <ide> * TODO (hrickens) : <del> * <add> * <ide> * @author hrickens <ide> * @author $Author: hrickens $ <ide> * @version $Revision: 1.3 $ <ide> */ <ide> public class SlaveEditor extends AbstractNodeEditor { <ide> <del> public static final String ID = "org.csstudio.config.ioconfig.view.editor.slave"; <del> <del> /** <del> * The Slave which displayed. <del> */ <del> private SlaveDBO _slave; <del> /** <del> * The GSD File of the Slave. <del> */ <del> private GSDFileDBO _gsdFile; <del> /** <del> * The Text field for the Vendor. <del> */ <del> private Text _vendorText; <del> /** <del> * Slave ID Number. <del> */ <del> private Text _iDNo; <del> /** <del> * The Text field for the Revision. <del> */ <del> private Text _revisionsText; <del> /** <del> * The Module max size of this Slave. <del> */ <del> private int _maxSize; <del> /** <del> * The number of max slots. <del> */ <del> private Text _maxSlots; <del> /** <del> * List with User Prm Data's. <del> */ <del> private TableViewer _userPrmDataList; <del> /** <del> * Inputs. <del> */ <del> private Text _inputsText; <del> /** <del> * Outputs. <del> */ <del> private Text _outputsText; <del> /** <del> * Die Bedeutung dieses Feldes ist noch unbekannt. <del> */ <del> // private Text _unbekannt; <del> /** <del> * The minimum Station Delay Time. <del> */ <del> private Text _minStationDelayText; <del> /** <del> * The Watchdog Time. <del> */ <del> private Text _watchDogText; <del> /** <del> * Marker of Background Color for normal use. Get from widget by first use. <del> */ <del> private Color _defaultBackgroundColor; <del> /** <del> * Check Button to de.-/activate Station Address. <del> */ <del> private Button _stationAddressActiveCButton; <del> private Button _freezeButton; <del> private Button _failButton; <del> private Button _watchDogButton; <del> private Button _syncButton; <del> private int _groupIdent; <del> private int _groupIdentStored; <del> private Group _groupsRadioButtons; <del> private ComboViewer _indexCombo; <del> private Group _currentUserParamDataGroup; <del> private final ArrayList<Object> _prmTextCV = new ArrayList<Object>(); <del> <del> /** <del> * <del> * @author hrickens <del> * @author $Author: hrickens $ <del> * @version $Revision: 1.3 $ <del> * @since 14.08.2007 <del> */ <del> class RowNumLabelProvider implements ITableLabelProvider { <del> <del> /** <del> * {@inheritDoc} <del> */ <del> public void addListener(final ILabelProviderListener listener) { <del> // handle no listener <del> } <del> <del> /** <del> * {@inheritDoc} <del> */ <del> public void dispose() { <del> if (_defaultBackgroundColor != null) { <del> _defaultBackgroundColor.dispose(); <del> } <del> } <del> <del> /** <del> * {@inheritDoc} <del> */ <del> public boolean isLabelProperty(final Object element, final String property) { <del> return false; <del> } <del> <del> /** <del> * {@inheritDoc} <del> */ <del> public void removeListener(final ILabelProviderListener listener) { <del> // handle no listener <del> } <del> <del> public Image getColumnImage(final Object element, final int columnIndex) { <del> return null; <del> } <del> <del> public String getColumnText(final Object element, final int columnIndex) { <del> if (element instanceof SlaveDBO) { <del> SlaveDBO slave = (SlaveDBO) element; <del> return onSlave(slave, columnIndex); <del> } else if (element instanceof ModuleDBO) { <del> ModuleDBO module = (ModuleDBO) element; <del> return onModule(module, columnIndex); <del> } <del> return null; <del> } <del> <del> /** <del> * @param module <del> * @param columnIndex <del> */ <del> @Nullable <del> private String onModule(@Nonnull final ModuleDBO module, final int columnIndex) { <del> switch (columnIndex) { <del> case 0: <del> return module.getSortIndex().toString(); <del> case 1: <del> return module.getName(); <del> case 2: <del> return module.getExtUserPrmDataConst(); <del> <del> default: <del> break; <del> } <del> return null; <del> } <del> <del> /** <del> * @param slave <del> */ <del> @Nullable <del> private String onSlave(@Nonnull final SlaveDBO slave, final int columnIndex) { <del>// TreeMap<String, ExtUserPrmDataConst> extUserPrmDataConst = slave.getGSDSlaveData() <del>// .getExtUserPrmDataConst(); <del> <del> switch (columnIndex) { <del> case 1: <del> return slave.getName(); <del> case 2: <del>// StringBuffer sb = new StringBuffer(); <del>// Set<String> keySet = extUserPrmDataConst.keySet(); <del>// for (String key : keySet) { <del>// sb.append(extUserPrmDataConst.get(key).getValue()); <del>// } <del>// return sb.toString(); <del> return slave.getPrmUserData(); <del> default: <del> break; <del> } <del> return null; <del> } <del> } <del> <del> /** <del> * {@inheritDoc} <del> */ <del> @Override <del> public void createPartControl(final Composite parent) { <del> _slave = (SlaveDBO) getNode(); <del> super.createPartControl(parent); <del> makeSlaveKonfiguration(parent); <del> getTabFolder().setSelection(0); <del> } <del> <del> /** <del> * @param parent <del> * Parent Composite. <del> * @param style <del> * Style of the Composite. <del> * @param slave <del> * the Profibus Slave to Configer. <del> */ <del> private void makeSlaveKonfiguration(final Composite parent) { <del> boolean nevv = false; <del> if (_slave == null) { <del> if (!newNode("TODO")) { <del> // this.dispose(); <del> setSaveButtonSaved(); <del> getProfiBusTreeView().getTreeViewer().setSelection(getProfiBusTreeView() <del> .getTreeViewer().getSelection()); <del> return; <del> } <del> nevv = true; <del> _slave.setMinTsdr((short) 11); <del> _slave.setWdFact1((short) 100); <del> } <del> setSavebuttonEnabled(null, getNode().isPersistent()); <del> String[] heads = { "Basics", "Settings", "Overview" }; <del> overview(heads[2]); <del> settings(heads[1]); <del> basics(heads[0]); <del> if (_slave.getGSDFile() != null) { <del> fill(_slave.getGSDFile()); <del> } <del> <del> getTabFolder().pack(); <del> if (nevv) { <del> getTabFolder().setSelection(4); <del> } <del> } <del> <del> @SuppressWarnings("unchecked") <del> private void overview(final String headline) { <del> Composite comp = getNewTabItem(headline, 1); <del> comp.setLayout(new GridLayout(1, false)); <del> <del> TableViewer overViewer = new TableViewer(comp, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER <del> | SWT.FULL_SELECTION); <del> overViewer.setContentProvider(new ArrayContentProvider()); <del> overViewer.setLabelProvider(new OverviewLabelProvider()); <del> overViewer.getTable().setHeaderVisible(true); <del> overViewer.getTable().setLinesVisible(true); <del> overViewer.getTable().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); <del> TableColumn c0 = new TableColumn(overViewer.getTable(), SWT.RIGHT); <del> c0.setText("Adr"); <del> TableColumn c0b = new TableColumn(overViewer.getTable(), SWT.RIGHT); <del> c0b.setText("Adr"); <del> TableColumn c1 = new TableColumn(overViewer.getTable(), SWT.LEFT); <del> c1.setText("Name"); <del> TableColumn c2 = new TableColumn(overViewer.getTable(), SWT.LEFT); <del> // c2.setWidth(200); <del> c2.setText("IO Name"); <del> TableColumn c3 = new TableColumn(overViewer.getTable(), SWT.LEFT); <del> // c3.setWidth(200); <del> c3.setText("IO Epics Address"); <del> TableColumn c4 = new TableColumn(overViewer.getTable(), SWT.LEFT); <del> // c4.setWidth(200); <del> c4.setText("Desc"); <del> TableColumn c5 = new TableColumn(overViewer.getTable(), SWT.LEFT); <del> // c5.setWidth(60); <del> c5.setText("Type"); <del> TableColumn c6 = new TableColumn(overViewer.getTable(), SWT.LEFT); <del> // c5.setWidth(60); <del> c6.setText("DB Id"); <del> <del> overViewer.addSelectionChangedListener(new ISelectionChangedListener() { <del> <del> public void selectionChanged(final SelectionChangedEvent event) { <del> // IStructuredSelection sel = (IStructuredSelection) event.getSelection(); <del> getProfiBusTreeView().getTreeViewer().setSelection(event.getSelection(), true); <del> } <del> <del> }); <del> <del> ArrayList<AbstractNodeDBO> children = new ArrayList<AbstractNodeDBO>(); <del> Collection<ModuleDBO> modules = (Collection<ModuleDBO>) _slave.getChildrenAsMap().values(); <del> for (ModuleDBO module : modules) { <del> children.add(module); <del> Collection<ChannelStructureDBO> channelStructures = module.getChannelStructsAsMap() <del> .values(); <del> for (ChannelStructureDBO channelStructure : channelStructures) { <del> Collection<ChannelDBO> channels = channelStructure.getChannelsAsMap().values(); <del> for (ChannelDBO channel : channels) { <del> children.add(channel); <del> } <del> <del> } <del> } <del> overViewer.setInput(children); <del> c0.pack(); <del> c0b.pack(); <del> c1.pack(); <del> c2.pack(); <del> c3.pack(); <del> c4.pack(); <del> c5.pack(); <del> c6.pack(); <del> } <del> <del> /** <del> * @param head <del> * The Tab text. <del> */ <del> private void basics(final String head) { <del> <del> Composite comp = getNewTabItem(head, 2); <del> <del> /* <del> * Name <del> */ <del> Group gName = new Group(comp, SWT.NONE); <del> gName.setText("Name"); <del> gName.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 5, 1)); <del> gName.setLayout(new GridLayout(3, false)); <del> <del> Text nameText = new Text(gName, SWT.BORDER | SWT.SINGLE); <del> setText(nameText, _slave.getName(), 255); <del> nameText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1)); <del> setNameWidget(nameText); <del> <del> // Label <del> Label slotIndexLabel = new Label(gName, SWT.NONE); <del> slotIndexLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); <del> slotIndexLabel.setText("Station Adress:"); <del> <del> _indexCombo = new ComboViewer(gName, SWT.DROP_DOWN | SWT.READ_ONLY); <del> _indexCombo.getCombo().setLayoutData(new GridData(SWT.RIGHT, SWT.RIGHT, false, false)); <del> _indexCombo.setContentProvider(new ArrayContentProvider()); <del> _indexCombo.setLabelProvider(new LabelProvider()); <del> Collection<Short> freeStationAddress = _slave.getProfibusDPMaster().getFreeStationAddress(); <del> Short sortIndex = _slave.getSortIndex(); <del> if (sortIndex >= 0) { <del> if (!freeStationAddress.contains(sortIndex)) { <del> freeStationAddress.add(sortIndex); <del> } <del> _indexCombo.setInput(freeStationAddress); <del> _indexCombo.setSelection(new StructuredSelection(sortIndex)); <del> } else { <del> _indexCombo.setInput(freeStationAddress); <del> _indexCombo.getCombo().select(0); <del> _slave.setSortIndexNonHibernate((Short) ((StructuredSelection) _indexCombo <del> .getSelection()).getFirstElement()); <del> } <del> _indexCombo.getCombo().setData(_indexCombo.getCombo().getSelectionIndex()); <del> _indexCombo.getCombo().addModifyListener(getMLSB()); <del> _indexCombo.addSelectionChangedListener(new ISelectionChangedListener() { <del> <del> @Override <del> public void selectionChanged(final SelectionChangedEvent event) { <del> short index = (Short) ((StructuredSelection) _indexCombo.getSelection()) <del> .getFirstElement(); <del> getNode().moveSortIndex(index); <del> if (getNode().getParent() != null) { <del> getProfiBusTreeView().refresh(getNode().getParent()); <del> } else { <del> getProfiBusTreeView().refresh(); <del> } <del> } <del> }); <del> <del> // setIndexSpinner(ConfigHelper.getIndexSpinner(gName, _slave, getMLSB(), <del> // "Station Adress:",getProfiBusTreeView())); <del> // _defaultBackgroundColor = getIndexSpinner().getBackground(); <del> <del> /* <del> * Slave Information <del> */ <del> Group slaveInfoGroup = new Group(comp, SWT.NONE); <del> slaveInfoGroup.setText("Slave Information"); <del> slaveInfoGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 2)); <del> slaveInfoGroup.setLayout(new GridLayout(4, false)); <del> slaveInfoGroup.setTabList(new Control[0]); <del> <del> _vendorText = new Text(slaveInfoGroup, SWT.SINGLE | SWT.BORDER); <del> _vendorText.setEditable(false); <del> _vendorText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 4, 1)); <del> <del> _iDNo = new Text(slaveInfoGroup, SWT.SINGLE); <del> _iDNo.setEditable(false); <del> _iDNo.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1)); <del> <del> Label revisionsLable = new Label(slaveInfoGroup, SWT.NONE); <del> revisionsLable.setText("Revision:"); <del> <del> _revisionsText = new Text(slaveInfoGroup, SWT.SINGLE); <del> _revisionsText.setEditable(false); <del> _revisionsText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1)); <del> <del> new Label(slaveInfoGroup, SWT.None).setText("Max. available slots:"); <del> _maxSlots = new Text(slaveInfoGroup, SWT.BORDER); <del> _maxSlots.setEditable(false); <del> <del> /* <del> * DP/FDL Access Group <del> */ <del> Group dpFdlAccessGroup = new Group(comp, SWT.NONE); <del> dpFdlAccessGroup.setText("DP / FDL Access"); <del> dpFdlAccessGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); <del> dpFdlAccessGroup.setLayout(new GridLayout(2, false)); <del> <del> Label stationAdrLabel = new Label(dpFdlAccessGroup, SWT.None); <del> stationAdrLabel.setText("Station Address"); <del> <del> GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1); <del> gd.minimumWidth = 50; <del> <del> _stationAddressActiveCButton = new Button(dpFdlAccessGroup, SWT.CHECK); <del> _stationAddressActiveCButton.setText("Active"); <del> _stationAddressActiveCButton.setSelection(false); <del> _stationAddressActiveCButton.setData(false); <del> _stationAddressActiveCButton.addSelectionListener(new SelectionListener() { <del> <del> public void widgetDefaultSelected(final SelectionEvent e) { <del> change(); <del> } <del> <del> public void widgetSelected(final SelectionEvent e) { <del> change(); <del> <del> } <del> <del> private void change() { <del> setSavebuttonEnabled("Button:" + _stationAddressActiveCButton.hashCode(), <del> (Boolean) _stationAddressActiveCButton.getData() != _stationAddressActiveCButton <del> .getSelection()); <del> } <del> <del> }); <del> <del> /* <del> * Input / Output Group <del> */ <del> Group ioGroup = new Group(comp, SWT.NONE); <del> ioGroup.setText("Inputs / Outputs"); <del> ioGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); <del> ioGroup.setLayout(new GridLayout(3, false)); <del> ioGroup.setTabList(new Control[0]); <del> <del> int input = 0; <del> int output = 0; <del> <del> if (_slave.hasChildren()) { <del> Iterator<ModuleDBO> iterator = _slave.getModules().iterator(); <del> while (iterator.hasNext()) { <del> ModuleDBO module = iterator.next(); <del> input += module.getInputSize(); <del> output += module.getOutputSize(); <del> } <del> } <del> Label inputLabel = new Label(ioGroup, SWT.RIGHT); <del> inputLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false, 2, 1)); <del> inputLabel.setText("Inputs: "); <del> _inputsText = new Text(ioGroup, SWT.SINGLE); <del> _inputsText.setEditable(false); <del> _inputsText.setText(Integer.toString(input)); <del> <del> Label outputsLabel = new Label(ioGroup, SWT.RIGHT); <del> outputsLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false, 2, 1)); <del> outputsLabel.setText("Outputs: "); <del> _outputsText = new Text(ioGroup, SWT.SINGLE); <del> _outputsText.setEditable(false); <del> _outputsText.setText(Integer.toString(output)); <del> <del> /* <del> * Description Group <del> */ <del> makeDescGroup(comp, 3); <del> } <del> <del> /** <add> public static final String ID = "org.csstudio.config.ioconfig.view.editor.slave"; <add> <add> /** <add> * The Slave which displayed. <add> */ <add> private SlaveDBO _slave; <add> /** <add> * The GSD File of the Slave. <add> */ <add> private GSDFileDBO _gsdFile; <add> /** <add> * The Text field for the Vendor. <add> */ <add> private Text _vendorText; <add> /** <add> * Slave ID Number. <add> */ <add> private Text _iDNo; <add> /** <add> * The Text field for the Revision. <add> */ <add> private Text _revisionsText; <add> /** <add> * The Module max size of this Slave. <add> */ <add> private int _maxSize; <add> /** <add> * The number of max slots. <add> */ <add> private Text _maxSlots; <add> /** <add> * List with User Prm Data's. <add> */ <add> private TableViewer _userPrmDataList; <add> /** <add> * Inputs. <add> */ <add> private Text _inputsText; <add> /** <add> * Outputs. <add> */ <add> private Text _outputsText; <add> /** <add> * Die Bedeutung dieses Feldes ist noch unbekannt. <add> */ <add> // private Text _unbekannt; <add> /** <add> * The minimum Station Delay Time. <add> */ <add> private Text _minStationDelayText; <add> /** <add> * The Watchdog Time. <add> */ <add> private Text _watchDogText; <add> /** <add> * Marker of Background Color for normal use. Get from widget by first use. <add> */ <add> private Color _defaultBackgroundColor; <add> /** <add> * Check Button to de.-/activate Station Address. <add> */ <add> private Button _stationAddressActiveCButton; <add> private Button _freezeButton; <add> private Button _failButton; <add> private Button _watchDogButton; <add> private Button _syncButton; <add> private int _groupIdent; <add> private int _groupIdentStored; <add> private Group _groupsRadioButtons; <add> private ComboViewer _indexCombo; <add> private Group _currentUserParamDataGroup; <add> private final ArrayList<Object> _prmTextCV = new ArrayList<Object>(); <add> <add> /** <add> * <add> * @author hrickens <add> * @author $Author: hrickens $ <add> * @version $Revision: 1.3 $ <add> * @since 14.08.2007 <add> */ <add> class RowNumLabelProvider implements ITableLabelProvider { <add> <add> /** <add> * {@inheritDoc} <add> */ <add> @Override <add> public void addListener(@Nullable final ILabelProviderListener listener) { <add> // handle no listener <add> } <add> <add> /** <add> * {@inheritDoc} <add> */ <add> @Override <add> public void dispose() { <add> if (getDefaultBackgroundColor() != null) { <add> getDefaultBackgroundColor().dispose(); <add> } <add> } <add> <add> /** <add> * {@inheritDoc} <add> */ <add> @Override <add> public boolean isLabelProperty(@Nullable final Object element, <add> @Nullable final String property) { <add> return false; <add> } <add> <add> /** <add> * {@inheritDoc} <add> */ <add> @Override <add> public void removeListener( <add> @Nullable final ILabelProviderListener listener) { <add> // handle no listener <add> } <add> <add> @Override <add> public Image getColumnImage(@Nullable final Object element, <add> @Nullable final int columnIndex) { <add> return null; <add> } <add> <add> @Override <add> public String getColumnText(@Nullable final Object element, <add> final int columnIndex) { <add> if (element instanceof SlaveDBO) { <add> SlaveDBO slave = (SlaveDBO) element; <add> return onSlave(slave, columnIndex); <add> } else if (element instanceof ModuleDBO) { <add> ModuleDBO module = (ModuleDBO) element; <add> return onModule(module, columnIndex); <add> } <add> return null; <add> } <add> <add> /** <add> * @param module <add> * @param columnIndex <add> */ <add> @CheckForNull <add> private String onModule(@Nonnull final ModuleDBO module, <add> final int columnIndex) { <add> switch (columnIndex) { <add> case 0: <add> return module.getSortIndex().toString(); <add> case 1: <add> return module.getName(); <add> case 2: <add> return module.getExtUserPrmDataConst(); <add> <add> default: <add> break; <add> } <add> return null; <add> } <add> <add> /** <add> * @param slave <add> */ <add> @CheckForNull <add> private String onSlave(@Nonnull final SlaveDBO slave, <add> final int columnIndex) { <add> // TreeMap<String, ExtUserPrmDataConst> extUserPrmDataConst = <add> // slave.getGSDSlaveData() <add> // .getExtUserPrmDataConst(); <add> <add> switch (columnIndex) { <add> case 1: <add> return slave.getName(); <add> case 2: <add> // StringBuffer sb = new StringBuffer(); <add> // Set<String> keySet = extUserPrmDataConst.keySet(); <add> // for (String key : keySet) { <add> // sb.append(extUserPrmDataConst.get(key).getValue()); <add> // } <add> // return sb.toString(); <add> return slave.getPrmUserData(); <add> default: <add> break; <add> } <add> return null; <add> } <add> } <add> <add> /** <add> * {@inheritDoc} <add> */ <add> @Override <add> public void createPartControl(@Nonnull final Composite parent) { <add> _slave = (SlaveDBO) getNode(); <add> super.createPartControl(parent); <add> makeSlaveKonfiguration(parent); <add> getTabFolder().setSelection(0); <add> } <add> <add> /** <add> * @param parent <add> * Parent Composite. <add> * @param style <add> * Style of the Composite. <add> * @param slave <add> * the Profibus Slave to Configer. <add> */ <add> private void makeSlaveKonfiguration(final Composite parent) { <add> boolean nevv = false; <add> if (_slave == null) { <add> if (!newNode("TODO")) { <add> // this.dispose(); <add> setSaveButtonSaved(); <add> getProfiBusTreeView().getTreeViewer().setSelection( <add> getProfiBusTreeView().getTreeViewer().getSelection()); <add> return; <add> } <add> nevv = true; <add> _slave.setMinTsdr((short) 11); <add> _slave.setWdFact1((short) 100); <add> } <add> setSavebuttonEnabled(null, getNode().isPersistent()); <add> String[] heads = { "Basics", "Settings", "Overview" }; <add> overview(heads[2]); <add> settings(heads[1]); <add> basics(heads[0]); <add> if (_slave.getGSDFile() != null) { <add> fill(_slave.getGSDFile()); <add> } <add> <add> getTabFolder().pack(); <add> if (nevv) { <add> getTabFolder().setSelection(4); <add> } <add> } <add> <add> @SuppressWarnings("unchecked") <add> private void overview(@Nonnull final String headline) { <add> Composite comp = getNewTabItem(headline, 1); <add> comp.setLayout(new GridLayout(1, false)); <add> <add> TableViewer overViewer = new TableViewer(comp, SWT.H_SCROLL <add> | SWT.V_SCROLL | SWT.BORDER | SWT.FULL_SELECTION); <add> overViewer.setContentProvider(new ArrayContentProvider()); <add> overViewer.setLabelProvider(new OverviewLabelProvider()); <add> overViewer.getTable().setHeaderVisible(true); <add> overViewer.getTable().setLinesVisible(true); <add> overViewer.getTable().setLayoutData( <add> new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); <add> TableColumn c0 = new TableColumn(overViewer.getTable(), SWT.RIGHT); <add> c0.setText("Adr"); <add> TableColumn c0b = new TableColumn(overViewer.getTable(), SWT.RIGHT); <add> c0b.setText("Adr"); <add> TableColumn c1 = new TableColumn(overViewer.getTable(), SWT.LEFT); <add> c1.setText("Name"); <add> TableColumn c2 = new TableColumn(overViewer.getTable(), SWT.LEFT); <add> // c2.setWidth(200); <add> c2.setText("IO Name"); <add> TableColumn c3 = new TableColumn(overViewer.getTable(), SWT.LEFT); <add> // c3.setWidth(200); <add> c3.setText("IO Epics Address"); <add> TableColumn c4 = new TableColumn(overViewer.getTable(), SWT.LEFT); <add> // c4.setWidth(200); <add> c4.setText("Desc"); <add> TableColumn c5 = new TableColumn(overViewer.getTable(), SWT.LEFT); <add> // c5.setWidth(60); <add> c5.setText("Type"); <add> TableColumn c6 = new TableColumn(overViewer.getTable(), SWT.LEFT); <add> // c5.setWidth(60); <add> c6.setText("DB Id"); <add> <add> overViewer.addSelectionChangedListener(new ISelectionChangedListener() { <add> <add> @Override <add> public void selectionChanged( <add> @Nonnull final SelectionChangedEvent event) { <add> getProfiBusTreeView().getTreeViewer().setSelection( <add> event.getSelection(), true); <add> } <add> <add> }); <add> <add> ArrayList<AbstractNodeDBO> children = new ArrayList<AbstractNodeDBO>(); <add> Collection<ModuleDBO> modules = (Collection<ModuleDBO>) _slave <add> .getChildrenAsMap().values(); <add> for (ModuleDBO module : modules) { <add> children.add(module); <add> Collection<ChannelStructureDBO> channelStructures = module <add> .getChannelStructsAsMap().values(); <add> for (ChannelStructureDBO channelStructure : channelStructures) { <add> Collection<ChannelDBO> channels = channelStructure <add> .getChannelsAsMap().values(); <add> for (ChannelDBO channel : channels) { <add> children.add(channel); <add> } <add> <add> } <add> } <add> overViewer.setInput(children); <add> c0.pack(); <add> c0b.pack(); <add> c1.pack(); <add> c2.pack(); <add> c3.pack(); <add> c4.pack(); <add> c5.pack(); <add> c6.pack(); <add> } <add> <add> /** <add> * @param head <add> * The Tab text. <add> */ <add> private void basics(@Nonnull final String head) { <add> <add> Composite comp = getNewTabItem(head, 2); <add> <add> /* <add> * Name <add> */ <add> Group gName = new Group(comp, SWT.NONE); <add> gName.setText("Name"); <add> gName.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 5, 1)); <add> gName.setLayout(new GridLayout(3, false)); <add> <add> Text nameText = new Text(gName, SWT.BORDER | SWT.SINGLE); <add> setText(nameText, _slave.getName(), 255); <add> nameText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, <add> 1)); <add> setNameWidget(nameText); <add> <add> // Label <add> Label slotIndexLabel = new Label(gName, SWT.NONE); <add> slotIndexLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, <add> false, 1, 1)); <add> slotIndexLabel.setText("Station Adress:"); <add> <add> _indexCombo = new ComboViewer(gName, SWT.DROP_DOWN | SWT.READ_ONLY); <add> _indexCombo.getCombo().setLayoutData( <add> new GridData(SWT.RIGHT, SWT.RIGHT, false, false)); <add> _indexCombo.setContentProvider(new ArrayContentProvider()); <add> _indexCombo.setLabelProvider(new LabelProvider()); <add> Collection<Short> freeStationAddress = _slave.getProfibusDPMaster() <add> .getFreeStationAddress(); <add> Short sortIndex = _slave.getSortIndex(); <add> if (sortIndex >= 0) { <add> if (!freeStationAddress.contains(sortIndex)) { <add> freeStationAddress.add(sortIndex); <add> } <add> _indexCombo.setInput(freeStationAddress); <add> _indexCombo.setSelection(new StructuredSelection(sortIndex)); <add> } else { <add> _indexCombo.setInput(freeStationAddress); <add> _indexCombo.getCombo().select(0); <add> _slave.setSortIndexNonHibernate((Short) ((StructuredSelection) _indexCombo <add> .getSelection()).getFirstElement()); <add> } <add> _indexCombo.getCombo().setData( <add> _indexCombo.getCombo().getSelectionIndex()); <add> _indexCombo.getCombo().addModifyListener(getMLSB()); <add> _indexCombo <add> .addSelectionChangedListener(new ISelectionChangedListener() { <add> <add> @Override <add> public void selectionChanged( <add> @Nonnull final SelectionChangedEvent event) { <add> short index = (Short) ((StructuredSelection) _indexCombo <add> .getSelection()).getFirstElement(); <add> getNode().moveSortIndex(index); <add> if (getNode().getParent() != null) { <add> getProfiBusTreeView() <add> .refresh(getNode().getParent()); <add> } else { <add> getProfiBusTreeView().refresh(); <add> } <add> } <add> }); <add> <add> // setIndexSpinner(ConfigHelper.getIndexSpinner(gName, _slave, <add> // getMLSB(), <add> // "Station Adress:",getProfiBusTreeView())); <add> // _defaultBackgroundColor = getIndexSpinner().getBackground(); <add> <add> /* <add> * Slave Information <add> */ <add> Group slaveInfoGroup = new Group(comp, SWT.NONE); <add> slaveInfoGroup.setText("Slave Information"); <add> slaveInfoGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, <add> false, 1, 2)); <add> slaveInfoGroup.setLayout(new GridLayout(4, false)); <add> slaveInfoGroup.setTabList(new Control[0]); <add> <add> _vendorText = new Text(slaveInfoGroup, SWT.SINGLE | SWT.BORDER); <add> _vendorText.setEditable(false); <add> _vendorText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, <add> 4, 1)); <add> <add> _iDNo = new Text(slaveInfoGroup, SWT.SINGLE); <add> _iDNo.setEditable(false); <add> _iDNo.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1)); <add> <add> Label revisionsLable = new Label(slaveInfoGroup, SWT.NONE); <add> revisionsLable.setText("Revision:"); <add> <add> _revisionsText = new Text(slaveInfoGroup, SWT.SINGLE); <add> _revisionsText.setEditable(false); <add> _revisionsText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, <add> false, 1, 1)); <add> <add> new Label(slaveInfoGroup, SWT.None).setText("Max. available slots:"); <add> _maxSlots = new Text(slaveInfoGroup, SWT.BORDER); <add> _maxSlots.setEditable(false); <add> <add> /* <add> * DP/FDL Access Group <add> */ <add> Group dpFdlAccessGroup = new Group(comp, SWT.NONE); <add> dpFdlAccessGroup.setText("DP / FDL Access"); <add> dpFdlAccessGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, <add> false, 1, 1)); <add> dpFdlAccessGroup.setLayout(new GridLayout(2, false)); <add> <add> Label stationAdrLabel = new Label(dpFdlAccessGroup, SWT.None); <add> stationAdrLabel.setText("Station Address"); <add> <add> GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1); <add> gd.minimumWidth = 50; <add> <add> _stationAddressActiveCButton = new Button(dpFdlAccessGroup, SWT.CHECK); <add> _stationAddressActiveCButton.setText("Active"); <add> _stationAddressActiveCButton.setSelection(false); <add> _stationAddressActiveCButton.setData(false); <add> _stationAddressActiveCButton <add> .addSelectionListener(new SelectionListener() { <add> <add> @Override <add> public void widgetDefaultSelected( <add> @Nonnull final SelectionEvent e) { <add> change(); <add> } <add> <add> @Override <add> public void widgetSelected(@Nonnull final SelectionEvent e) { <add> change(); <add> <add> } <add> <add> private void change() { <add> setSavebuttonEnabled( <add> "Button:" <add> + _stationAddressActiveCButton <add> .hashCode(), <add> (Boolean) _stationAddressActiveCButton <add> .getData() != _stationAddressActiveCButton <add> .getSelection()); <add> } <add> <add> }); <add> <add> /* <add> * Input / Output Group <add> */ <add> Group ioGroup = new Group(comp, SWT.NONE); <add> ioGroup.setText("Inputs / Outputs"); <add> ioGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, <add> 1)); <add> ioGroup.setLayout(new GridLayout(3, false)); <add> ioGroup.setTabList(new Control[0]); <add> <add> int input = 0; <add> int output = 0; <add> <add> if (_slave.hasChildren()) { <add> Iterator<ModuleDBO> iterator = _slave.getModules().iterator(); <add> while (iterator.hasNext()) { <add> ModuleDBO module = iterator.next(); <add> input += module.getInputSize(); <add> output += module.getOutputSize(); <add> } <add> } <add> Label inputLabel = new Label(ioGroup, SWT.RIGHT); <add> inputLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, <add> false, 2, 1)); <add> inputLabel.setText("Inputs: "); <add> _inputsText = new Text(ioGroup, SWT.SINGLE); <add> _inputsText.setEditable(false); <add> _inputsText.setText(Integer.toString(input)); <add> <add> Label outputsLabel = new Label(ioGroup, SWT.RIGHT); <add> outputsLabel.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, <add> false, false, 2, 1)); <add> outputsLabel.setText("Outputs: "); <add> _outputsText = new Text(ioGroup, SWT.SINGLE); <add> _outputsText.setEditable(false); <add> _outputsText.setText(Integer.toString(output)); <add> <add> /* <add> * Description Group <add> */ <add> makeDescGroup(comp, 3); <add> } <add> <add> /** <ide> * <ide> */ <del> private void setSlots() { <del> Formatter slotFormarter = new Formatter(); <del> slotFormarter.format(" %2d / %2d", _slave.getChildren().size(), _maxSize); <del> _maxSlots.setText(slotFormarter.toString()); <del> if (_maxSize < _slave.getChildren().size()) { <del> if (_defaultBackgroundColor == null) { <del> _defaultBackgroundColor = Display.getDefault() <del> .getSystemColor(SWT.COLOR_WIDGET_BACKGROUND); <del> } <del> _maxSlots.setBackground(WARN_BACKGROUND_COLOR); <del> } else { <del> _maxSlots.setBackground(_defaultBackgroundColor); <del> } <del> slotFormarter = null; <del> } <del> <del> /** <del> * @param head <del> * the tabItemName <del> */ <del> private void settings(final String head) { <del> Composite comp = getNewTabItem(head, 2); <del> comp.setLayout(new GridLayout(3, false)); <del> // Operation Mode <del> Group operationModeGroup = new Group(comp, SWT.NONE); <del> GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); <del> layoutData.minimumWidth = 170; <del> operationModeGroup.setLayoutData(layoutData); <del> operationModeGroup.setText("Operation Mode"); <del> operationModeGroup.setLayout(new GridLayout(3, false)); <del> Label delayLabel = new Label(operationModeGroup, SWT.NONE); <del> delayLabel.setText("Min. Station Delay"); <del> _minStationDelayText = ProfibusHelper.getTextField(operationModeGroup, true, _slave <del> .getMinTsdr() <del> + "", Ranges.WATCHDOG, ProfibusHelper.VL_TYP_U16); <del> Label bitLabel = new Label(operationModeGroup, SWT.NONE); <del> bitLabel.setText("Bit"); <del> <del> _syncButton = new Button(operationModeGroup, SWT.CHECK); <del> _syncButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 3, 1)); <del> _syncButton.addTraverseListener(ProfibusHelper.getNETL()); <del> _syncButton.setText("Sync Request"); <del> _syncButton.setData(false); <del> _syncButton.addSelectionListener(new SelectionListener() { <del> <del> public void widgetDefaultSelected(final SelectionEvent e) { <del> change(_syncButton); <del> } <del> <del> public void widgetSelected(final SelectionEvent e) { <del> change(_syncButton); <del> } <del> }); <del> _freezeButton = new Button(operationModeGroup, SWT.CHECK); <del> _freezeButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 3, 1)); <del> _freezeButton.addTraverseListener(ProfibusHelper.getNETL()); <del> _freezeButton.setText("Freeze Request"); <del> _freezeButton.setSelection(false); <del> _freezeButton.setData(false); <del> _freezeButton.addSelectionListener(new SelectionListener() { <del> <del> public void widgetDefaultSelected(final SelectionEvent e) { <del> change(_freezeButton); <del> } <del> <del> public void widgetSelected(final SelectionEvent e) { <del> change(_freezeButton); <del> } <del> }); <del> _failButton = new Button(operationModeGroup, SWT.CHECK); <del> _failButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 3, 1)); <del> _failButton.addTraverseListener(ProfibusHelper.getNETL()); <del> _failButton.setText("Fail Save"); <del> _failButton.setEnabled(false); <del> _failButton.setData(false); <del> _failButton.addSelectionListener(new SelectionListener() { <del> <del> public void widgetDefaultSelected(final SelectionEvent e) { <del> change(_failButton); <del> } <del> <del> public void widgetSelected(final SelectionEvent e) { <del> change(_failButton); <del> } <del> }); <del> _watchDogButton = new Button(operationModeGroup, SWT.CHECK); <del> _watchDogButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); <del> _watchDogButton.addTraverseListener(ProfibusHelper.getNETL()); <del> _watchDogButton.setText("Watchdog Time"); <del> _watchDogButton.setSelection(true); <del> _watchDogButton.setData(true); <del> _watchDogText = ProfibusHelper.getTextField(operationModeGroup, <del> _watchDogButton.getSelection(), <del> Integer.toString(_slave.getWdFact1()), <del> Ranges.TTR, <del> ProfibusHelper.VL_TYP_U32); <del> _watchDogText.addModifyListener(getMLSB()); <del> Label timeLabel = new Label(operationModeGroup, SWT.NONE); <del> timeLabel.setText("ms"); <del> _watchDogButton.addSelectionListener(new SelectionListener() { <del> <del> public void widgetDefaultSelected(final SelectionEvent e) { <del> change(); <del> } <del> <del> public void widgetSelected(final SelectionEvent e) { <del> change(); <del> } <del> <del> private void change() { <del> SlaveEditor.this.change(_watchDogButton); <del> _watchDogText.setEnabled(_watchDogButton.getSelection()); <del> } <del> }); <del> <del> makeCurrentUserParamData(comp); <del> <del> makeUserPRMMode(comp); <del> <del> } <del> <del> /** <del> * @param comp <del> */ <del> private void makeUserPRMMode(final Composite comp) { <del> Group userPrmData = new Group(comp, SWT.V_SCROLL); <del> userPrmData.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 2)); <del> userPrmData.setLayout(new GridLayout(2, false)); <del> userPrmData.setTabList(new Control[0]); <del> userPrmData.setText("User PRM Mode"); <del> _userPrmDataList = new TableViewer(userPrmData, SWT.BORDER | SWT.V_SCROLL); <del> <del> Table table = _userPrmDataList.getTable(); <del> table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 15)); <del> table.setHeaderVisible(true); <del> table.setLinesVisible(true); <del> <del> _userPrmDataList.setContentProvider(new ArrayContentProvider()); <del> _userPrmDataList.setLabelProvider(new RowNumLabelProvider()); <del> <del> TableColumn tc = new TableColumn(table, SWT.RIGHT); <del> tc.setText(""); <del> tc.setWidth(20); <del> tc = new TableColumn(table, SWT.LEFT); <del> tc.setText("Name"); <del> tc.setWidth(130); <del> tc = new TableColumn(table, SWT.LEFT); <del> tc.setText("Ext User Prm Data Const"); <del> tc.setWidth(450); <del> <del> // Groups <del> _groupsRadioButtons = new Group(comp, SWT.NONE); <del> _groupsRadioButtons.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1)); <del> _groupsRadioButtons.setLayout(new GridLayout(4, true)); <del> _groupsRadioButtons.setText("Groups"); <del> _groupIdentStored = _slave.getGroupIdent(); <del> if ( (_groupIdentStored < 0) || (_groupIdentStored > 7)) { <del> _groupIdentStored = 0; <del> } <del> _groupIdent = _groupIdentStored; <del> for (int i = 0; i <= 7; i++) { <del> final Button b = new Button(_groupsRadioButtons, SWT.RADIO); <del> b.setText(Integer.toString(i + 1)); <del> if (i == _groupIdent) { <del> b.setSelection(true); <del> } <del> b.addSelectionListener(new SelectionListener() { <del> <del> public void widgetDefaultSelected(final SelectionEvent e) { <del> check(); <del> } <del> <del> public void widgetSelected(final SelectionEvent e) { <del> check(); <del> } <del> <del> private void check() { <del> _groupIdent = Short.parseShort(b.getText()); <del> _groupIdent--; <del> setSavebuttonEnabled("groupButton" + _groupsRadioButtons.hashCode(), <del> _groupIdent != _groupIdentStored); <del> } <del> <del> }); <del> } <del> } <del> <del> /** {@inheritDoc} */ <del> @Override <del> public final boolean fill(final GSDFileDBO gsdFile) { <del> /* <del> * Read GSD-File <del> */ <del> if (gsdFile == null) { <del> return false; <del> } else if (gsdFile.equals(_gsdFile)) { <del> return true; <del> } <del> <del> _gsdFile = gsdFile; <del> GsdSlaveModel slaveModel = GsdFactory.makeGsdSlave(_gsdFile); <del> <del> // setGSDData <del> HashMap<Integer, GsdModuleModel> moduleList = GSD2Module.parse(_gsdFile, slaveModel); <del> slaveModel.setGsdModuleList(moduleList); <del> _slave.setGSDSlaveData(slaveModel); <del> <del> /* <del> * Head <del> */ <del> getHeaderField(HeaderFields.VERSION).setText(slaveModel.getGsdRevision() + ""); <del> <del> /* <del> * Basic - Slave Discription (read only) <del> */ <del> _vendorText.setText(slaveModel.getVendorName()); <del> _iDNo.setText(String.format("0x%04X", slaveModel.getIdentNumber())); <del> _revisionsText.setText(slaveModel.getRevision()); <del> <del> /* <del> * Basic - Inputs / Outputs (read only) <del> */ <del> <del> /* <del> * Set all GSD-File Data to Slave. <del> */ <del> _slave.setMinTsdr(_slave.getMinTsdr()); <del> _slave.setModelName(slaveModel.getModelName()); <del> _slave.setPrmUserData(slaveModel.getUserPrmData()); <del> _slave.setProfibusPNoID(slaveModel.getIdentNumber()); <del> _slave.setRevision(slaveModel.getRevision()); <del> <del> /* <del> * Basic - DP / FDL Access <del> */ <del> <del> /* <del> * Modules <del> */ <del> _maxSize = slaveModel.getMaxModule(); <del> setSlots(); <del> <del> /* <del> * Settings - Operation Mode <del> */ <del> /* <del> * Settings - Groups <del> */ <del> /* <del> * Settings - USER PRM MODE <del> */ <del> <del> ArrayList<AbstractNodeDBO> nodes = new ArrayList<AbstractNodeDBO>(); <del> nodes.add(_slave); <del> nodes.addAll(_slave.getChildrenAsMap().values()); <del> _userPrmDataList.setInput(nodes); <del> TableColumn[] columns = _userPrmDataList.getTable().getColumns(); <del> for (TableColumn tableColumn : columns) { <del> if (tableColumn != null) { <del> tableColumn.pack(); <del> } <del> } <del> return true; <del> } <del> <del> /** {@inheritDoc} */ <del> @Override <del> public final GSDFileDBO getGSDFile() { <del> return _slave.getGSDFile(); <del> } <del> <del> /** <del> * {@inheritDoc} <del> */ <del> @Override <del> public void doSave(final IProgressMonitor monitor) { <del> super.doSave(monitor); <del> // Name <del> _slave.setName(getNameWidget().getText()); <del> getNameWidget().setData(getNameWidget().getText()); <del> <del> // _slave.moveSortIndex((short) getIndexSpinner().getSelection()); <del> Short stationAddress = (Short) ((StructuredSelection) _indexCombo.getSelection()) <del> .getFirstElement(); <del> _slave.setSortIndexNonHibernate(stationAddress); <del> _slave.setFdlAddress(stationAddress); <del> _indexCombo.getCombo().setData(_indexCombo.getCombo().getSelectionIndex()); <del> short minTsdr = 0; <del> try { <del> minTsdr = Short.parseShort(_minStationDelayText.getText()); <del> } catch (NumberFormatException e) { <del> } <del> _slave.setMinTsdr(minTsdr); <del> <del> _slave.setGroupIdent(_groupIdent); <del> _groupIdentStored = _groupIdent; <del> <del> _slave.setSlaveFlag((short) 192); <del> short wdFact = Short.parseShort(_watchDogText.getText()); <del> _watchDogText.setData(_watchDogText.getText()); <del> _slave.setWdFact1(wdFact); <del> _slave.setWdFact2((short) (wdFact / 10)); <del> <del> // Static Station status 136 <del> _slave.setStationStatus((short) 136); <del> <del> saveUserPrmData(); <del> <del> // GSD File <del> _slave.setGSDFile(_gsdFile); <del> fill(_gsdFile); <del> <del> // Document <del> Set<DocumentDBO> docs = getDocumentationManageView().getDocuments(); <del> _slave.setDocuments(docs); <del> <del> _slave.update(); <del> save(); <del> } <del> <del> /** <add> private void setSlots() { <add> Formatter slotFormarter = new Formatter(); <add> slotFormarter.format(" %2d / %2d", _slave.getChildren().size(), <add> _maxSize); <add> _maxSlots.setText(slotFormarter.toString()); <add> if (_maxSize < _slave.getChildren().size()) { <add> if (getDefaultBackgroundColor() == null) { <add> setDefaultBackgroundColor(Display.getDefault().getSystemColor( <add> SWT.COLOR_WIDGET_BACKGROUND)); <add> } <add> _maxSlots.setBackground(WARN_BACKGROUND_COLOR); <add> } else { <add> _maxSlots.setBackground(getDefaultBackgroundColor()); <add> } <add> slotFormarter = null; <add> } <add> <add> /** <add> * @param head <add> * the tabItemName <add> */ <add> private void settings(@Nonnull final String head) { <add> Composite comp = getNewTabItem(head, 2); <add> comp.setLayout(new GridLayout(3, false)); <add> // Operation Mode <add> Group operationModeGroup = new Group(comp, SWT.NONE); <add> GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1); <add> layoutData.minimumWidth = 170; <add> operationModeGroup.setLayoutData(layoutData); <add> operationModeGroup.setText("Operation Mode"); <add> operationModeGroup.setLayout(new GridLayout(3, false)); <add> Label delayLabel = new Label(operationModeGroup, SWT.NONE); <add> delayLabel.setText("Min. Station Delay"); <add> _minStationDelayText = ProfibusHelper.getTextField(operationModeGroup, <add> true, _slave.getMinTsdr() + "", Ranges.WATCHDOG, <add> ProfibusHelper.VL_TYP_U16); <add> Label bitLabel = new Label(operationModeGroup, SWT.NONE); <add> bitLabel.setText("Bit"); <add> <add> _syncButton = new Button(operationModeGroup, SWT.CHECK); <add> _syncButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, <add> false, 3, 1)); <add> _syncButton.addTraverseListener(ProfibusHelper.getNETL()); <add> _syncButton.setText("Sync Request"); <add> _syncButton.setData(false); <add> _syncButton.addSelectionListener(new SelectionListener() { <add> <add> @Override <add> public void widgetDefaultSelected(@Nonnull final SelectionEvent e) { <add> change(_syncButton); <add> } <add> <add> @Override <add> public void widgetSelected(@Nonnull final SelectionEvent e) { <add> change(_syncButton); <add> } <add> }); <add> _freezeButton = new Button(operationModeGroup, SWT.CHECK); <add> _freezeButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, <add> false, 3, 1)); <add> _freezeButton.addTraverseListener(ProfibusHelper.getNETL()); <add> _freezeButton.setText("Freeze Request"); <add> _freezeButton.setSelection(false); <add> _freezeButton.setData(false); <add> _freezeButton.addSelectionListener(new SelectionListener() { <add> <add> @Override <add> public void widgetDefaultSelected(@Nonnull final SelectionEvent e) { <add> change(_freezeButton); <add> } <add> <add> @Override <add> public void widgetSelected(@Nonnull final SelectionEvent e) { <add> change(_freezeButton); <add> } <add> }); <add> setFailButton(new Button(operationModeGroup, SWT.CHECK)); <add> getFailButton().setLayoutData( <add> new GridData(SWT.FILL, SWT.FILL, false, false, 3, 1)); <add> getFailButton().addTraverseListener(ProfibusHelper.getNETL()); <add> getFailButton().setText("Fail Save"); <add> getFailButton().setEnabled(false); <add> getFailButton().setData(false); <add> getFailButton().addSelectionListener(new SelectionListener() { <add> <add> @Override <add> public void widgetDefaultSelected(@Nonnull final SelectionEvent e) { <add> change(getFailButton()); <add> } <add> <add> @Override <add> public void widgetSelected(@Nonnull final SelectionEvent e) { <add> change(getFailButton()); <add> } <add> }); <add> _watchDogButton = new Button(operationModeGroup, SWT.CHECK); <add> _watchDogButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, <add> false, 1, 1)); <add> _watchDogButton.addTraverseListener(ProfibusHelper.getNETL()); <add> _watchDogButton.setText("Watchdog Time"); <add> _watchDogButton.setSelection(true); <add> _watchDogButton.setData(true); <add> _watchDogText = ProfibusHelper.getTextField(operationModeGroup, <add> _watchDogButton.getSelection(), <add> Integer.toString(_slave.getWdFact1()), Ranges.TTR, <add> ProfibusHelper.VL_TYP_U32); <add> _watchDogText.addModifyListener(getMLSB()); <add> Label timeLabel = new Label(operationModeGroup, SWT.NONE); <add> timeLabel.setText("ms"); <add> _watchDogButton.addSelectionListener(new SelectionListener() { <add> <add> @Override <add> public void widgetDefaultSelected(@Nonnull final SelectionEvent e) { <add> change(); <add> } <add> <add> @Override <add> public void widgetSelected(@Nonnull final SelectionEvent e) { <add> change(); <add> } <add> <add> private void change() { <add> SlaveEditor.this.change(_watchDogButton); <add> _watchDogText.setEnabled(_watchDogButton.getSelection()); <add> } <add> }); <add> <add> makeCurrentUserParamData(comp); <add> <add> makeUserPRMMode(comp); <add> <add> } <add> <add> /** <add> * @param comp <add> */ <add> private void makeUserPRMMode(@Nonnull final Composite comp) { <add> Group userPrmData = new Group(comp, SWT.V_SCROLL); <add> userPrmData.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, <add> 1, 2)); <add> userPrmData.setLayout(new GridLayout(2, false)); <add> userPrmData.setTabList(new Control[0]); <add> userPrmData.setText("User PRM Mode"); <add> _userPrmDataList = new TableViewer(userPrmData, SWT.BORDER <add> | SWT.V_SCROLL); <add> <add> Table table = _userPrmDataList.getTable(); <add> table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 15)); <add> table.setHeaderVisible(true); <add> table.setLinesVisible(true); <add> <add> _userPrmDataList.setContentProvider(new ArrayContentProvider()); <add> _userPrmDataList.setLabelProvider(new RowNumLabelProvider()); <add> <add> TableColumn tc = new TableColumn(table, SWT.RIGHT); <add> tc.setText(""); <add> tc.setWidth(20); <add> tc = new TableColumn(table, SWT.LEFT); <add> tc.setText("Name"); <add> tc.setWidth(130); <add> tc = new TableColumn(table, SWT.LEFT); <add> tc.setText("Ext User Prm Data Const"); <add> tc.setWidth(450); <add> <add> // Groups <add> _groupsRadioButtons = new Group(comp, SWT.NONE); <add> _groupsRadioButtons.setLayoutData(new GridData(SWT.FILL, SWT.FILL, <add> true, false, 1, 1)); <add> _groupsRadioButtons.setLayout(new GridLayout(4, true)); <add> _groupsRadioButtons.setText("Groups"); <add> _groupIdentStored = _slave.getGroupIdent(); <add> if ((_groupIdentStored < 0) || (_groupIdentStored > 7)) { <add> _groupIdentStored = 0; <add> } <add> _groupIdent = _groupIdentStored; <add> for (int i = 0; i <= 7; i++) { <add> final Button b = new Button(_groupsRadioButtons, SWT.RADIO); <add> b.setText(Integer.toString(i + 1)); <add> if (i == _groupIdent) { <add> b.setSelection(true); <add> } <add> b.addSelectionListener(new SelectionListener() { <add> <add> public void widgetDefaultSelected( <add> @Nonnull final SelectionEvent e) { <add> check(); <add> } <add> <add> @Override <add> public void widgetSelected(@Nonnull final SelectionEvent e) { <add> check(); <add> } <add> <add> private void check() { <add> _groupIdent = Short.parseShort(b.getText()); <add> _groupIdent--; <add> setSavebuttonEnabled( <add> "groupButton" + _groupsRadioButtons.hashCode(), <add> _groupIdent != _groupIdentStored); <add> } <add> <add> }); <add> } <add> } <add> <add> /** {@inheritDoc} */ <add> @Override <add> public final boolean fill(@Nullable final GSDFileDBO gsdFile) { <add> // Read GSD-File <add> if (gsdFile == null) { <add> return false; <add> } else if (gsdFile.equals(_gsdFile)) { <add> return true; <add> } <add> <add> _gsdFile = gsdFile; <add> GsdSlaveModel slaveModel = GsdFactory.makeGsdSlave(_gsdFile); <add> <add> // setGSDData <add> HashMap<Integer, GsdModuleModel> moduleList = GSD2Module.parse( <add> _gsdFile, slaveModel); <add> slaveModel.setGsdModuleList(moduleList); <add> _slave.setGSDSlaveData(slaveModel); <add> <add> // Head <add> getHeaderField(HeaderFields.VERSION).setText( <add> slaveModel.getGsdRevision() + ""); <add> <add> // Basic - Slave Discription (read only) <add> _vendorText.setText(slaveModel.getVendorName()); <add> _iDNo.setText(String.format("0x%04X", slaveModel.getIdentNumber())); <add> _revisionsText.setText(slaveModel.getRevision()); <add> <add> // Basic - Inputs / Outputs (read only) <add> <add> // Set all GSD-File Data to Slave. <add> _slave.setMinTsdr(_slave.getMinTsdr()); <add> _slave.setModelName(slaveModel.getModelName()); <add> _slave.setPrmUserData(slaveModel.getUserPrmData()); <add> _slave.setProfibusPNoID(slaveModel.getIdentNumber()); <add> _slave.setRevision(slaveModel.getRevision()); <add> <add> // Basic - DP / FDL Access <add> <add> // Modules <add> _maxSize = slaveModel.getMaxModule(); <add> setSlots(); <add> <add> // Settings - Operation Mode <add> <add> // Settings - Groups <add> <add> // Settings - USER PRM MODE <add> ArrayList<AbstractNodeDBO> nodes = new ArrayList<AbstractNodeDBO>(); <add> nodes.add(_slave); <add> nodes.addAll(_slave.getChildrenAsMap().values()); <add> _userPrmDataList.setInput(nodes); <add> TableColumn[] columns = _userPrmDataList.getTable().getColumns(); <add> for (TableColumn tableColumn : columns) { <add> if (tableColumn != null) { <add> tableColumn.pack(); <add> } <add> } <add> return true; <add> } <add> <add> /** {@inheritDoc} */ <add> @Override <add> public final GSDFileDBO getGSDFile() { <add> return _slave.getGSDFile(); <add> } <add> <add> /** <add> * {@inheritDoc} <add> */ <add> @Override <add> public void doSave(@Nullable final IProgressMonitor monitor) { <add> super.doSave(monitor); <add> // Name <add> _slave.setName(getNameWidget().getText()); <add> getNameWidget().setData(getNameWidget().getText()); <add> <add> // _slave.moveSortIndex((short) getIndexSpinner().getSelection()); <add> Short stationAddress = (Short) ((StructuredSelection) _indexCombo <add> .getSelection()).getFirstElement(); <add> _slave.setSortIndexNonHibernate(stationAddress); <add> _slave.setFdlAddress(stationAddress); <add> _indexCombo.getCombo().setData( <add> _indexCombo.getCombo().getSelectionIndex()); <add> short minTsdr = 0; <add> try { <add> minTsdr = Short.parseShort(_minStationDelayText.getText()); <add> } catch (NumberFormatException e) { <add> // don't change the old Value when the new value a invalid. <add> } <add> _slave.setMinTsdr(minTsdr); <add> <add> _slave.setGroupIdent(_groupIdent); <add> _groupIdentStored = _groupIdent; <add> <add> _slave.setSlaveFlag((short) 192); <add> short wdFact = Short.parseShort(_watchDogText.getText()); <add> _watchDogText.setData(_watchDogText.getText()); <add> _slave.setWdFact1(wdFact); <add> _slave.setWdFact2((short) (wdFact / 10)); <add> <add> // Static Station status 136 <add> _slave.setStationStatus((short) 136); <add> <add> saveUserPrmData(); <add> <add> // GSD File <add> _slave.setGSDFile(_gsdFile); <add> fill(_gsdFile); <add> <add> // Document <add> Set<DocumentDBO> docs = getDocumentationManageView().getDocuments(); <add> _slave.setDocuments(docs); <add> <add> _slave.update(); <add> save(); <add> } <add> <add> /** <ide> * <ide> */ <del> private void saveUserPrmData() { <del> TreeMap<String, ExtUserPrmDataConst> extUserPrmDataConst = _slave.getGSDSlaveData().getExtUserPrmDataConst(); <del> List<ExtUserPrmDataRef> extUserPrmDataRefMap = _slave.getGSDSlaveData().getExtUserPrmDataRefMap(); <del> if(extUserPrmDataRefMap.size()==_prmTextCV.size()) { <del> for (int i = 0; i < extUserPrmDataRefMap.size(); i++) { <del> ExtUserPrmDataRef ref = extUserPrmDataRefMap.get(i); <del> Object prmTextObject = _prmTextCV.get(i); <del> if (prmTextObject instanceof ComboViewer) { <del> ComboViewer prmTextCV = (ComboViewer) prmTextObject; <del> handleComboViewer(extUserPrmDataConst, prmTextCV, ref.getValue()); <del> } else if (prmTextObject instanceof Text) { <del> Text prmText = (Text) prmTextObject; <del> extUserPrmDataConst = handleText(extUserPrmDataConst, prmText, ref.getValue()); <del> } <del> } <del> <del> }else { <del> //TODO: throw extUserPrmDataRefMap und prmTextCV passen nicht zu sammen <del> } <del>// GsdModuleModel mod = (GsdModuleModel) ((StructuredSelection) _moduleTypList.getSelection()) <del>// .getFirstElement(); <del>// if (mod != null) { <del>//// _slave.setModuleNumber(mod.getModuleNumber()); <del>//// _moduleTypList.getTable().setData(mod.getModuleNumber()); <del>// <del>//// String[] extUserPrmDataConst = _module.getGsdModuleModel().getExtUserPrmDataConst() <del>//// .split(","); <del>// <del>// String extUserPrmDataConst = _slave.getPrmUserData(); <del>// for (Object prmTextObject : _prmTextCV) { <del>// if (prmTextObject instanceof ComboViewer) { <del>// ComboViewer prmTextCV = (ComboViewer) prmTextObject; <del>//// handleComboViewer(extUserPrmDataConst, prmTextCV); <del>// } else if (prmTextObject instanceof Text) { <del>// Text prmText = (Text) prmTextObject; <del>//// extUserPrmDataConst = handleText(extUserPrmDataConst, prmText); <del>// } <del>// } <del>//// _module.setConfigurationData(Arrays.toString(extUserPrmDataConst) <del>//// .replaceAll("[\\[\\]]", "")); <del>// } <del> } <del> <del> /** <del> * @param extUserPrmDataConst <del> * @param prmText <del> * @return <del> */ <del> @Nonnull <del> private TreeMap<String, ExtUserPrmDataConst> handleText(@Nonnull final TreeMap<String,ExtUserPrmDataConst> extUserPrmDataConst,@Nonnull final Text prmText) { <del> if (!prmText.isDisposed()) { <del> String value = (String) prmText.getData(); <del> if (value != null) { <del> prmText.setText(value); <del> int val = Integer.parseInt(value); <del>// return new String[] {String.format("%1$#04x", val) }; <del> } <del> } <del> return extUserPrmDataConst; <del> } <del> <del> /** <del> * @param extUserPrmDataConst <del> * @param byteIndexString <del> * @param prmTextObject <del> */ <del> private void handleComboViewer(final TreeMap<String,ExtUserPrmDataConst> extUserPrmDataConst, final ComboViewer prmTextCV, final String byteIndexString) { <del> if (!prmTextCV.getCombo().isDisposed()) { <del> int byteIndex = ProfibusConfigXMLGenerator.getInt(byteIndexString); <del> ExtUserPrmData input = (ExtUserPrmData) prmTextCV.getInput(); <del> StructuredSelection selection = (StructuredSelection) prmTextCV <del> .getSelection(); <del> Integer bitValue = ((PrmText) selection.getFirstElement()).getValue(); <del> String newValue = setValue2BitMask(input, bitValue, _slave.getPrmUserDataList().get(byteIndex)); <del> _slave.setPrmUserDataByte(byteIndex, newValue); <del> Integer indexOf = prmTextCV.getCombo().indexOf(selection.getFirstElement() <del> .toString()); <del> prmTextCV.getCombo().setData(indexOf); <del> } <del> } <del> <del> /** <del> * Change the a value on the Bit places, that is given from the input, to the bitValue. <del> * <del> * @param ranges <del> * give the start and end Bit position. <del> * @param bitValue <del> * the new Value for the given Bit position. <del> * @param value <del> * the value was changed. <del> * @return the changed value as Hex String. <del> */ <del> @Nonnull <del> private String setValue2BitMask(@Nonnull final ExtUserPrmData ranges, <del> @Nonnull final Integer bitValue, <del> @Nonnull final String value) { <del> int val = ProfibusConfigXMLGenerator.getInt(value); <del> int minBit = ranges.getMinBit(); <del> int maxBit = ranges.getMaxBit(); <del> if (maxBit < minBit) { <del> minBit = ranges.getMaxBit(); <del> maxBit = ranges.getMinBit(); <del> } <del> int mask = ~ ((int) (Math.pow(2, maxBit + 1) - Math.pow(2, minBit))); <del> val = val & mask; <del> val = val | (bitValue << minBit); <del> return String.format("%1$#04x", val); <del> } <del> <del> /* <del> * (non-Javadoc) <del> * <del> * @see org.csstudio.config.ioconfig.config.view.NodeConfig#cancel() <del> */ <del> @Override <del> public void cancel() { <del> super.cancel(); <del> // getIndexSpinner().setSelection((Short) getIndexSpinner().getData()); <del> if (_indexCombo != null) { <del> _indexCombo.getCombo().select((Integer) _indexCombo.getCombo().getData()); <del> getNameWidget().setText((String) getNameWidget().getData()); <del> _stationAddressActiveCButton.setSelection((Boolean) _stationAddressActiveCButton <del> .getData()); <del> _minStationDelayText.setText((String) _minStationDelayText.getData()); <del> _syncButton.setSelection((Boolean) _syncButton.getData()); <del> _failButton.setSelection((Boolean) _failButton.getData()); <del> _freezeButton.setSelection((Boolean) _freezeButton.getData()); <del> _watchDogButton.setSelection((Boolean) _watchDogButton.getData()); <del> _watchDogText.setEnabled(_watchDogButton.getSelection()); <del> _watchDogText.setText((String) _watchDogText.getData()); <del> _groupIdent = _groupIdentStored; <del> for (Control control : _groupsRadioButtons.getChildren()) { <del> if (control instanceof Button) { <del> Button button = (Button) control; <del> button <del> .setSelection(Short.parseShort(button.getText()) == _groupIdentStored + 1); <del> } <del> } <del> <del> if (_slave != null) { <del> if (_slave.getGSDFile() != null) { <del> fill(_slave.getGSDFile()); <del> } else { <del> getHeaderField(HeaderFields.VERSION).setText(""); <del> _vendorText.setText(""); <del> getNameWidget().setText(""); <del> _revisionsText.setText(""); <del> } <del> } else { <del> _gsdFile = null; <del> fill(_gsdFile); <del> } <del> } <del> } <del> <del> private void change(final Button button) { <del> setSavebuttonEnabled("Button:" + button.hashCode(), (Boolean) button.getData() != button <del> .getSelection()); <del> } <del> <del> /** <del> * <del> * @param topGroup <del> * The parent Group for the CurrentUserParamData content. <del> */ <del> private void makeCurrentUserParamData(final Composite topGroup) { <del> if (_currentUserParamDataGroup != null) { <del> _currentUserParamDataGroup.dispose(); <del> } <del> // Current User Param Data Group <del> _currentUserParamDataGroup = new Group(topGroup, SWT.NONE); <del> GridData gd = new GridData(SWT.FILL, SWT.FILL, false, true, 1, 3); <del> _currentUserParamDataGroup.setLayoutData(gd); <del> _currentUserParamDataGroup.setLayout(new FillLayout()); <del> _currentUserParamDataGroup.setText("Current User Param Data:"); <del> final ScrolledComposite scrollComposite = new ScrolledComposite(_currentUserParamDataGroup, <del> SWT.V_SCROLL); <del> final Composite currentUserParamDataComposite = new Composite(scrollComposite, SWT.NONE); <del> RowLayout rowLayout = new RowLayout(SWT.VERTICAL); <del> rowLayout.wrap = false; <del> rowLayout.fill = true; <del> currentUserParamDataComposite.setLayout(rowLayout); <del> scrollComposite.setContent(currentUserParamDataComposite); <del> scrollComposite.setExpandHorizontal(true); <del> scrollComposite.setExpandVertical(true); <del> _currentUserParamDataGroup.addControlListener(new ControlAdapter() { <del> @Override <del> public void controlResized(@Nonnull final ControlEvent e) { <del> Rectangle r = scrollComposite.getClientArea(); <del> scrollComposite.setMinSize(scrollComposite.computeSize(r.width, SWT.DEFAULT)); <del> } <del> }); <del> scrollComposite.addControlListener(new ControlAdapter() { <del> @Override <del> public void controlResized(@Nonnull final ControlEvent e) { <del> Rectangle r = scrollComposite.getClientArea(); <del> scrollComposite.setMinSize(currentUserParamDataComposite.computeSize(r.width, <del> SWT.DEFAULT)); <del> } <del> }); <add> private void saveUserPrmData() { <add> TreeMap<String, ExtUserPrmDataConst> extUserPrmDataConst = _slave <add> .getGSDSlaveData().getExtUserPrmDataConst(); <add> List<ExtUserPrmDataRef> extUserPrmDataRefMap = _slave.getGSDSlaveData() <add> .getExtUserPrmDataRefMap(); <add> if (extUserPrmDataRefMap.size() == _prmTextCV.size()) { <add> for (int i = 0; i < extUserPrmDataRefMap.size(); i++) { <add> ExtUserPrmDataRef ref = extUserPrmDataRefMap.get(i); <add> Object prmTextObject = _prmTextCV.get(i); <add> if (prmTextObject instanceof ComboViewer) { <add> ComboViewer prmTextCV = (ComboViewer) prmTextObject; <add> handleComboViewer(extUserPrmDataConst, prmTextCV, <add> ref.getValue()); <add> } else if (prmTextObject instanceof Text) { <add> Text prmText = (Text) prmTextObject; <add> extUserPrmDataConst = handleText(extUserPrmDataConst, <add> prmText); <add> } <add> } <add> <add> } else { <add> // TODO: throw extUserPrmDataRefMap und prmTextCV passen nicht zu <add> // sammen <add> } <add> // GsdModuleModel mod = (GsdModuleModel) ((StructuredSelection) <add> // _moduleTypList.getSelection()) <add> // .getFirstElement(); <add> // if (mod != null) { <add> // // _slave.setModuleNumber(mod.getModuleNumber()); <add> // // _moduleTypList.getTable().setData(mod.getModuleNumber()); <add> // <add> // // String[] extUserPrmDataConst = <add> // _module.getGsdModuleModel().getExtUserPrmDataConst() <add> // // .split(","); <add> // <add> // String extUserPrmDataConst = _slave.getPrmUserData(); <add> // for (Object prmTextObject : _prmTextCV) { <add> // if (prmTextObject instanceof ComboViewer) { <add> // ComboViewer prmTextCV = (ComboViewer) prmTextObject; <add> // // handleComboViewer(extUserPrmDataConst, prmTextCV); <add> // } else if (prmTextObject instanceof Text) { <add> // Text prmText = (Text) prmTextObject; <add> // // extUserPrmDataConst = handleText(extUserPrmDataConst, prmText); <add> // } <add> // } <add> // // _module.setConfigurationData(Arrays.toString(extUserPrmDataConst) <add> // // .replaceAll("[\\[\\]]", "")); <add> // } <add> } <add> <add> /** <add> * @param extUserPrmDataConst <add> * @param prmText <add> * @return <add> */ <add> @Nonnull <add> private TreeMap<String, ExtUserPrmDataConst> handleText( <add> @Nonnull final TreeMap<String, ExtUserPrmDataConst> extUserPrmDataConst, <add> @Nonnull final Text prmText) { <add> if (!prmText.isDisposed()) { <add> String value = (String) prmText.getData(); <add> if (value != null) { <add> prmText.setText(value); <add> int val = Integer.parseInt(value); <add> // return new String[] {String.format("%1$#04x", val) }; <add> } <add> } <add> return extUserPrmDataConst; <add> } <add> <add> /** <add> * @param extUserPrmDataConst <add> * @param byteIndexString <add> * @param prmTextObject <add> */ <add> private void handleComboViewer( <add> @Nonnull final TreeMap<String, ExtUserPrmDataConst> extUserPrmDataConst, <add> @Nonnull final ComboViewer prmTextCV, <add> @Nonnull final String byteIndexString) { <add> if (!prmTextCV.getCombo().isDisposed()) { <add> int byteIndex = ProfibusConfigXMLGenerator.getInt(byteIndexString); <add> ExtUserPrmData input = (ExtUserPrmData) prmTextCV.getInput(); <add> StructuredSelection selection = (StructuredSelection) prmTextCV <add> .getSelection(); <add> Integer bitValue = ((PrmText) selection.getFirstElement()) <add> .getValue(); <add> String newValue = setValue2BitMask(input, bitValue, _slave <add> .getPrmUserDataList().get(byteIndex)); <add> _slave.setPrmUserDataByte(byteIndex, newValue); <add> Integer indexOf = prmTextCV.getCombo().indexOf( <add> selection.getFirstElement().toString()); <add> prmTextCV.getCombo().setData(indexOf); <add> } <add> } <add> <add> /** <add> * Change the a value on the Bit places, that is given from the input, to <add> * the bitValue. <add> * <add> * @param ranges <add> * give the start and end Bit position. <add> * @param bitValue <add> * the new Value for the given Bit position. <add> * @param value <add> * the value was changed. <add> * @return the changed value as Hex String. <add> */ <add> @Nonnull <add> private String setValue2BitMask(@Nonnull final ExtUserPrmData ranges, <add> @Nonnull final Integer bitValue, @Nonnull final String value) { <add> int val = ProfibusConfigXMLGenerator.getInt(value); <add> int minBit = ranges.getMinBit(); <add> int maxBit = ranges.getMaxBit(); <add> if (maxBit < minBit) { <add> minBit = ranges.getMaxBit(); <add> maxBit = ranges.getMinBit(); <add> } <add> int mask = ~((int) (Math.pow(2, maxBit + 1) - Math.pow(2, minBit))); <add> val = val & mask; <add> val = val | (bitValue << minBit); <add> return String.format("%1$#04x", val); <add> } <add> <add> /* <add> * (non-Javadoc) <add> * <add> * @see org.csstudio.config.ioconfig.config.view.NodeConfig#cancel() <add> */ <add> @Override <add> public void cancel() { <add> super.cancel(); <add> // getIndexSpinner().setSelection((Short) getIndexSpinner().getData()); <add> if (_indexCombo != null) { <add> _indexCombo.getCombo().select( <add> (Integer) _indexCombo.getCombo().getData()); <add> getNameWidget().setText((String) getNameWidget().getData()); <add> _stationAddressActiveCButton <add> .setSelection((Boolean) _stationAddressActiveCButton <add> .getData()); <add> _minStationDelayText.setText((String) _minStationDelayText <add> .getData()); <add> _syncButton.setSelection((Boolean) _syncButton.getData()); <add> getFailButton().setSelection((Boolean) getFailButton().getData()); <add> _freezeButton.setSelection((Boolean) _freezeButton.getData()); <add> _watchDogButton.setSelection((Boolean) _watchDogButton.getData()); <add> _watchDogText.setEnabled(_watchDogButton.getSelection()); <add> _watchDogText.setText((String) _watchDogText.getData()); <add> _groupIdent = _groupIdentStored; <add> for (Control control : _groupsRadioButtons.getChildren()) { <add> if (control instanceof Button) { <add> Button button = (Button) control; <add> button.setSelection(Short.parseShort(button.getText()) == _groupIdentStored + 1); <add> } <add> } <add> <add> if (_slave != null) { <add> if (_slave.getGSDFile() != null) { <add> fill(_slave.getGSDFile()); <add> } else { <add> getHeaderField(HeaderFields.VERSION).setText(""); <add> _vendorText.setText(""); <add> getNameWidget().setText(""); <add> _revisionsText.setText(""); <add> } <add> } else { <add> _gsdFile = null; <add> fill(_gsdFile); <add> } <add> } <add> } <add> <add> void change(@Nonnull final Button button) { <add> setSavebuttonEnabled("Button:" + button.hashCode(), <add> (Boolean) button.getData() != button.getSelection()); <add> } <add> <add> /** <add> * <add> * @param topGroup <add> * The parent Group for the CurrentUserParamData content. <add> */ <add> private void makeCurrentUserParamData(@Nonnull final Composite topGroup) { <add> if (_currentUserParamDataGroup != null) { <add> _currentUserParamDataGroup.dispose(); <add> } <add> // Current User Param Data Group <add> _currentUserParamDataGroup = new Group(topGroup, SWT.NONE); <add> GridData gd = new GridData(SWT.FILL, SWT.FILL, false, true, 1, 3); <add> _currentUserParamDataGroup.setLayoutData(gd); <add> _currentUserParamDataGroup.setLayout(new FillLayout()); <add> _currentUserParamDataGroup.setText("Current User Param Data:"); <add> final ScrolledComposite scrollComposite = new ScrolledComposite( <add> _currentUserParamDataGroup, SWT.V_SCROLL); <add> final Composite currentUserParamDataComposite = new Composite( <add> scrollComposite, SWT.NONE); <add> RowLayout rowLayout = new RowLayout(SWT.VERTICAL); <add> rowLayout.wrap = false; <add> rowLayout.fill = true; <add> currentUserParamDataComposite.setLayout(rowLayout); <add> scrollComposite.setContent(currentUserParamDataComposite); <add> scrollComposite.setExpandHorizontal(true); <add> scrollComposite.setExpandVertical(true); <add> _currentUserParamDataGroup.addControlListener(new ControlAdapter() { <add> @Override <add> public void controlResized(@Nonnull final ControlEvent e) { <add> Rectangle r = scrollComposite.getClientArea(); <add> scrollComposite.setMinSize(scrollComposite.computeSize(r.width, <add> SWT.DEFAULT)); <add> } <add> }); <add> scrollComposite.addControlListener(new ControlAdapter() { <add> @Override <add> public void controlResized(@Nonnull final ControlEvent e) { <add> Rectangle r = scrollComposite.getClientArea(); <add> scrollComposite.setMinSize(currentUserParamDataComposite <add> .computeSize(r.width, SWT.DEFAULT)); <add> } <add> }); <ide> <ide> // Current User Param Data <ide> GsdSlaveModel gsdSlaveModel = _slave.getGSDSlaveData(); <ide> if (gsdSlaveModel != null) { <del> List<ExtUserPrmDataRef> extUserPrmDataRefMap = gsdSlaveModel.getExtUserPrmDataRefMap(); <add> List<ExtUserPrmDataRef> extUserPrmDataRefMap = gsdSlaveModel <add> .getExtUserPrmDataRefMap(); <ide> if (extUserPrmDataRefMap != null) { <ide> for (ExtUserPrmDataRef extUserPrmDataRef : extUserPrmDataRefMap) { <ide> int val = 0; <ide> topGroup.layout(); <ide> } <ide> <del> /** <del> * <del> * @param currentUserParamDataGroup <del> * @param extUserPrmData <del> * @param value <del> * @param byteIndex <del> */ <del> private void makeCurrentUserParamDataItem(final Composite currentUserParamDataGroup, <del> final ExtUserPrmData extUserPrmData, <del> final Integer value, final String byteIndex) { <del> HashMap<Integer, PrmText> prmTextMap = null; <del> <del> Text text = new Text(currentUserParamDataGroup, SWT.SINGLE | SWT.READ_ONLY); <del> <del> if (extUserPrmData != null) { <del> text.setText(extUserPrmData.getText() + ":"); <del> prmTextMap = extUserPrmData.getPrmText(); <del> if ( (extUserPrmData.getPrmText() == null) <del> && (extUserPrmData.getMaxValue() - extUserPrmData.getMinValue() > 10)) { <del> _prmTextCV.add(makeTextField(currentUserParamDataGroup, value, extUserPrmData)); <del> } else { <del> _prmTextCV.add(makeComboViewer(currentUserParamDataGroup, <del> value, <del> extUserPrmData, <del> prmTextMap, byteIndex)); <del> } <del> } <del> new Label(currentUserParamDataGroup, SWT.SEPARATOR | SWT.HORIZONTAL);// .setLayoutData(new <del> } <del> <del> /** <del> * <del> * @param currentUserParamDataGroup <del> * @param value <del> * @param extUserPrmData <del> * @return <del> */ <del> private Text makeTextField(final Composite currentUserParamDataGroup, <del> final Integer value, <del> final ExtUserPrmData extUserPrmData) { <del> Integer localValue = value; <del> Text prmText = new Text(currentUserParamDataGroup, SWT.BORDER | SWT.SINGLE | SWT.RIGHT); <del> Formatter f = new Formatter(); <del> f.format("Min: %d, Min: %d", extUserPrmData.getMinValue(), extUserPrmData.getMaxValue()); <del> prmText.setToolTipText(f.toString()); <del> prmText.setTextLimit(Integer.toString(extUserPrmData.getMaxValue()).length()); <del> <del> if (localValue == null) { <del> localValue = extUserPrmData.getDefault(); <del> } <del> prmText.setText(localValue.toString()); <del> prmText.setData(localValue.toString()); <del> prmText.addModifyListener(getMLSB()); <del> prmText.addVerifyListener(new VerifyListener() { <del> <del> public void verifyText(final VerifyEvent e) { <del> if (e.text.matches("^\\D+$")) { <del> e.doit = false; <del> } <del> } <del> <del> }); <del> return prmText; <del> } <del> <del> /** <del> * <del> * @param parent <del> * the Parent Composite. <del> * @param value <del> * the Selected currentUserParamData Value. <del> * @param extUserPrmData <del> * @param prmTextMap <del> * @param byteIndex <del> * @return a ComboView for are currentUserParamData Property <del> */ <del> private ComboViewer makeComboViewer(final Composite parent, <del> final Integer value, <del> final ExtUserPrmData extUserPrmData, <del> final HashMap<Integer, PrmText> prmTextMap, final String byteIndex) { <del> final int index = ProfibusConfigXMLGenerator.getInt(byteIndex); <del> Integer localValue = value; <del> ComboViewer prmTextCV = new ComboViewer(parent); <del> RowData data = new RowData(); <del> data.exclude = false; <del> prmTextCV.getCombo().setLayoutData(data); <del> prmTextCV.setLabelProvider(new LabelProvider()); <del> prmTextCV.setContentProvider(new IStructuredContentProvider() { <del> <del> public Object[] getElements(final Object inputElement) { <del> if (inputElement instanceof ExtUserPrmData) { <del> ExtUserPrmData extUserPrmData = (ExtUserPrmData) inputElement; <del> HashMap<Integer, PrmText> prmText = extUserPrmData.getPrmText(); <del> if (prmText == null) { <del> PrmText[] prmTextArray = new PrmText[extUserPrmData.getMaxValue() <del> - extUserPrmData.getMinValue() + 1]; <del> for (int i = extUserPrmData.getMinValue(); i <= extUserPrmData <del> .getMaxValue(); i++) { <del> prmTextArray[i] = new PrmText(Integer.toString(i), i); <del> } <del> return prmTextArray; <del> } <del> return prmText.values().toArray(); <del> } <del> return null; <del> } <del> <del> public void dispose() { <del> } <del> <del> public void inputChanged(final Viewer viewer, <del> final Object oldInput, <del> final Object newInput) { <del> } <del> }); <del> prmTextCV.getCombo().addModifyListener(getMLSB()); <del> prmTextCV.setSorter(new ViewerSorter() { <del> <del> @Override <del> public int compare(final Viewer viewer, final Object e1, final Object e2) { <del> if ( (e1 instanceof PrmText) && (e2 instanceof PrmText)) { <del> PrmText eUPD1 = (PrmText) e1; <del> PrmText eUPD2 = (PrmText) e2; <del> return eUPD1.getValue() - eUPD2.getValue(); <del> } <del> return super.compare(viewer, e1, e2); <del> } <del> <del> }); <del> <del> if (localValue == null) { <del> localValue = extUserPrmData.getDefault(); <del> } <del> prmTextCV.setInput(extUserPrmData); <del> if (prmTextMap != null) { <del> PrmText prmText = prmTextMap.get(localValue); <del> if (prmText != null) { <del> prmTextCV.setSelection(new StructuredSelection(prmTextMap.get(localValue))); <del> } else { <del> prmTextCV.getCombo().select(0); <del> } <del> } else { <del> prmTextCV.getCombo().select(localValue); <del> } <del> prmTextCV.getCombo().setData(prmTextCV.getCombo().getSelectionIndex()); <del> setModify(prmTextCV); <del> return prmTextCV; <del> } <del> <del> /** <del> * <del> * @param prmTextCV <del> */ <del> private void setModify(final ComboViewer prmTextCV) { <del> // PrmText prmText = (PrmText) ((StructuredSelection) prmTextCV.getSelection()) <del> // .getFirstElement(); <del> // ExtUserPrmData extUserPrmData = (ExtUserPrmData) prmTextCV.getInput(); <del> // String index = extUserPrmData.getIndex(); <del> // GsdModuleModel gsdModule = _slave.getGsdModuleModel(); <del> // int bytePos = Integer.parseInt(gsdModule.getExtUserPrmDataRef(index)); <del> // int bitMin = extUserPrmData.getMinBit(); <del> // int bitMax = extUserPrmData.getMaxBit(); <del> // <del> // int val = 0; <del> // if (prmText != null) { <del> // val = prmText.getValue(); <del> // } <del> // gsdModule.addModify(bytePos, bitMin, bitMax, val); <del> } <del> <del> /** <del> * {@inheritDoc} <del> */ <del> @Override <del> public void setFocus() { <del> // TODO Auto-generated method stub <del> <del> } <add> /** <add> * <add> * @param currentUserParamDataGroup <add> * @param extUserPrmData <add> * @param value <add> * @param byteIndex <add> */ <add> private void makeCurrentUserParamDataItem( <add> @Nonnull final Composite currentUserParamDataGroup, <add> @Nullable final ExtUserPrmData extUserPrmData, final Integer value, <add> final String byteIndex) { <add> HashMap<Integer, PrmText> prmTextMap = null; <add> <add> Text text = new Text(currentUserParamDataGroup, SWT.SINGLE <add> | SWT.READ_ONLY); <add> <add> if (extUserPrmData != null) { <add> text.setText(extUserPrmData.getText() + ":"); <add> prmTextMap = extUserPrmData.getPrmText(); <add> if ((extUserPrmData.getPrmText() == null) <add> && (extUserPrmData.getMaxValue() <add> - extUserPrmData.getMinValue() > 10)) { <add> _prmTextCV.add(makeTextField(currentUserParamDataGroup, value, <add> extUserPrmData)); <add> } else { <add> _prmTextCV.add(makeComboViewer(currentUserParamDataGroup, <add> value, extUserPrmData, prmTextMap, byteIndex)); <add> } <add> } <add> new Label(currentUserParamDataGroup, SWT.SEPARATOR | SWT.HORIZONTAL);// .setLayoutData(new <add> } <add> <add> /** <add> * <add> * @param currentUserParamDataGroup <add> * @param value <add> * @param extUserPrmData <add> * @return <add> */ <add> private Text makeTextField(final Composite currentUserParamDataGroup, <add> final Integer value, final ExtUserPrmData extUserPrmData) { <add> Integer localValue = value; <add> Text prmText = new Text(currentUserParamDataGroup, SWT.BORDER <add> | SWT.SINGLE | SWT.RIGHT); <add> Formatter f = new Formatter(); <add> f.format("Min: %d, Min: %d", extUserPrmData.getMinValue(), <add> extUserPrmData.getMaxValue()); <add> prmText.setToolTipText(f.toString()); <add> prmText.setTextLimit(Integer.toString(extUserPrmData.getMaxValue()) <add> .length()); <add> <add> if (localValue == null) { <add> localValue = extUserPrmData.getDefault(); <add> } <add> prmText.setText(localValue.toString()); <add> prmText.setData(localValue.toString()); <add> prmText.addModifyListener(getMLSB()); <add> prmText.addVerifyListener(new VerifyListener() { <add> <add> public void verifyText(final VerifyEvent e) { <add> if (e.text.matches("^\\D+$")) { <add> e.doit = false; <add> } <add> } <add> <add> }); <add> return prmText; <add> } <add> <add> /** <add> * <add> * @param parent <add> * the Parent Composite. <add> * @param value <add> * the Selected currentUserParamData Value. <add> * @param extUserPrmData <add> * @param prmTextMap <add> * @param byteIndex <add> * @return a ComboView for are currentUserParamData Property <add> */ <add> private ComboViewer makeComboViewer(final Composite parent, <add> final Integer value, final ExtUserPrmData extUserPrmData, <add> final HashMap<Integer, PrmText> prmTextMap, final String byteIndex) { <add> final int index = ProfibusConfigXMLGenerator.getInt(byteIndex); <add> Integer localValue = value; <add> ComboViewer prmTextCV = new ComboViewer(parent); <add> RowData data = new RowData(); <add> data.exclude = false; <add> prmTextCV.getCombo().setLayoutData(data); <add> prmTextCV.setLabelProvider(new LabelProvider()); <add> prmTextCV.setContentProvider(new IStructuredContentProvider() { <add> <add> @Override <add> public Object[] getElements(@Nullable final Object inputElement) { <add> if (inputElement instanceof ExtUserPrmData) { <add> ExtUserPrmData eUPD = (ExtUserPrmData) inputElement; <add> HashMap<Integer, PrmText> prmText = eUPD.getPrmText(); <add> if (prmText == null) { <add> PrmText[] prmTextArray = new PrmText[eUPD.getMaxValue() <add> - eUPD.getMinValue() + 1]; <add> for (int i = eUPD.getMinValue(); i <= eUPD <add> .getMaxValue(); i++) { <add> prmTextArray[i] = new PrmText(Integer.toString(i), <add> i); <add> } <add> return prmTextArray; <add> } <add> return prmText.values().toArray(); <add> } <add> return null; <add> } <add> <add> public void dispose() { <add> } <add> <add> public void inputChanged(final Viewer viewer, <add> final Object oldInput, final Object newInput) { <add> } <add> }); <add> prmTextCV.getCombo().addModifyListener(getMLSB()); <add> prmTextCV.setSorter(new ViewerSorter() { <add> <add> @Override <add> public int compare(final Viewer viewer, final Object e1, <add> final Object e2) { <add> if ((e1 instanceof PrmText) && (e2 instanceof PrmText)) { <add> PrmText eUPD1 = (PrmText) e1; <add> PrmText eUPD2 = (PrmText) e2; <add> return eUPD1.getValue() - eUPD2.getValue(); <add> } <add> return super.compare(viewer, e1, e2); <add> } <add> <add> }); <add> <add> if (localValue == null) { <add> localValue = extUserPrmData.getDefault(); <add> } <add> prmTextCV.setInput(extUserPrmData); <add> if (prmTextMap != null) { <add> PrmText prmText = prmTextMap.get(localValue); <add> if (prmText != null) { <add> prmTextCV.setSelection(new StructuredSelection(prmTextMap <add> .get(localValue))); <add> } else { <add> prmTextCV.getCombo().select(0); <add> } <add> } else { <add> prmTextCV.getCombo().select(localValue); <add> } <add> prmTextCV.getCombo().setData(prmTextCV.getCombo().getSelectionIndex()); <add> setModify(prmTextCV); <add> return prmTextCV; <add> } <add> <add> /** <add> * <add> * @param prmTextCV <add> */ <add> private void setModify(final ComboViewer prmTextCV) { <add> // PrmText prmText = (PrmText) ((StructuredSelection) <add> // prmTextCV.getSelection()) <add> // .getFirstElement(); <add> // ExtUserPrmData extUserPrmData = (ExtUserPrmData) <add> // prmTextCV.getInput(); <add> // String index = extUserPrmData.getIndex(); <add> // GsdModuleModel gsdModule = _slave.getGsdModuleModel(); <add> // int bytePos = <add> // Integer.parseInt(gsdModule.getExtUserPrmDataRef(index)); <add> // int bitMin = extUserPrmData.getMinBit(); <add> // int bitMax = extUserPrmData.getMaxBit(); <add> // <add> // int val = 0; <add> // if (prmText != null) { <add> // val = prmText.getValue(); <add> // } <add> // gsdModule.addModify(bytePos, bitMin, bitMax, val); <add> } <add> <add> /** <add> * {@inheritDoc} <add> */ <add> @Override <add> public void setFocus() { <add> // TODO Auto-generated method stub <add> <add> } <add> <add> protected void setDefaultBackgroundColor( <add> @Nonnull Color defaultBackgroundColor) { <add> _defaultBackgroundColor = defaultBackgroundColor; <add> } <add> <add> @CheckForNull <add> protected Color getDefaultBackgroundColor() { <add> return _defaultBackgroundColor; <add> } <add> <add> protected void setFailButton(@Nonnull Button failButton) { <add> _failButton = failButton; <add> } <add> <add> @CheckForNull <add> Button getFailButton() { <add> return _failButton; <add> } <ide> }
JavaScript
mit
9ac63a724757a53b7ff5e38cdb369326b6272869
0
jmarymee/TaskHelper,jmarymee/TaskHelper,zbrad/TaskHelper,jmarymee/TaskHelper,zbrad/TaskHelper,jmarymee/TaskHelper,zbrad/TaskHelper,zbrad/TaskHelper
/// <reference path="../App.js" /> (function () { "use strict"; // The Office initialize function must be run each time a new page is loaded Office.initialize = function (reason) { $(document).ready(function () { app.initialize(); displayItemDetails(); //displayTasks(); //displaySubject(); sendGetAllTasks(); //sendCreateTask(); $('#createNewTasks').click(getListOfTasksToCreate); }); }; //This test method creates an array of strings (tasks) and sends to the createAllMethod function getListOfTasksToCreate() { var arrayofTasks = ['task1', 'task2', 'task3']; debugger; sendCreateAllTasks(arrayofTasks); } //Thus function iterates over a task object array and sends a create for each one function sendCreateAllTasks(arrayOfTasks) { var arrayLen = arrayOfTasks.length; var loop = 0; for (loop = 0; loop < arrayLen; loop++) { var taskName = { taskName: arrayOfTasks[loop], startDateString: '2015-10-08T21:32:52' } sendCreateTask(taskName); } } function displayTasks() { var tasks = Office.context.mailbox.item.getEntitiesByType(Office.MailboxEnums.EntityType.TaskSuggestion); var s = "count=" + tasks.length + "\n"; for (t in tasks) { s += t + "\n" } $('#tasks').text(s); } function displaySubject() { sendRequest(); } // Displays the "Subject" and "From" fields, based on the current mail item function displayItemDetails() { var item = Office.cast.item.toItemRead(Office.context.mailbox.item); $('#subject').text(item.subject); var from; if (item.itemType === Office.MailboxEnums.ItemType.Message) { from = Office.cast.item.toMessageRead(item).from; } else if (item.itemType === Office.MailboxEnums.ItemType.Appointment) { from = Office.cast.item.toAppointmentRead(item).organizer; } if (from) { $('#from').text(from.displayName); $('#from').click(function () { app.showNotification(from.displayName, from.emailAddress); }); } } function getProperties() { return ' <t:AdditionalProperties>' + ' <t:FieldURI FieldURI="item:Subject" />' + // ' <t:FieldURI FieldURI="item:Priority" />' + ' <t:FieldURI FieldURI="item:Status" />' + ' </t:AdditionalProperties>'; } function getAllTasks() { var result = getBodyPrefix() + ' <m:FindItem Traversal="Shallow">' + ' <m:ItemShape>' + ' <t:BaseShape>AllProperties</t:BaseShape>' + // getProperties() + ' </m:ItemShape>' + getRestriction() + ' <m:ParentFolderIds>' + ' <t:DistinguishedFolderId Id="tasks"/>' + ' </m:ParentFolderIds>' + ' </m:FindItem>' + getBodyPostfix(); return result; } function getRestriction() { return ' <m:Restriction>' + // ' <t:And>' + ' <t:IsNotEqualTo>' + ' <t:FieldURI FieldURI="task:Status" />' + ' <t:FieldURIOrConstant>' + ' <t:Constant Value="2" />' + ' </t:FieldURIOrConstant>' + ' </t:IsNotEqualTo>' + // ' </t:And>' + ' </m:Restriction>'; } function addSort() { return ' <m:SortOrder>' + ' <t:FieldOrder Order="Descending">' + ' <t:FieldURI FieldURI="item:Priority" />' + ' </t:FieldOrder>' + ' </m:SortOrder>'; } function getBodyPrefix() { return '<?xml version="1.0" encoding="utf-8"?>' + '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' + ' xmlns:xsd="http://www.w3.org/2001/XMLSchema"' + ' xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"' + ' xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" ' + ' xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">' + ' <soap:Header>' + ' <t:RequestServerVersion Version="Exchange2013" soap:mustUnderstand="0" />' + ' </soap:Header>' + ' <soap:Body>'; } function getBodyPostfix() { return ' </soap:Body>' + '</soap:Envelope>'; } function getCreateTask(taskObject) { //sample date //2006-10-26T21:32:52 var result = getBodyPrefix() + ' <m:CreateItem>' + ' <m:Items>' + ' <t:Task>' + ' <t:Subject>'+taskObject.taskName+'</t:Subject>' + ' <t:DueDate>'+taskObject.startDateString+'</t:DueDate>' + ' <t:Status>NotStarted</t:Status>' + ' </t:Task>' + ' </m:Items>' + ' </m:CreateItem>' + getBodyPostfix(); return result; } function getSubjectRequest(id) { // Return a GetItem operation request for the subject of the specified item. var result = '<?xml version="1.0" encoding="utf-8"?>' + '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' + ' xmlns:xsd="http://www.w3.org/2001/XMLSchema"' + ' xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"' + ' xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">' + ' <soap:Header>' + ' <t:RequestServerVersion Version="Exchange2013" xmlns="http://schemas.microsoft.com/exchange/services/2006/types" soap:mustUnderstand="0" />' + ' </soap:Header>' + ' <soap:Body>' + ' <GetItem xmlns="http://schemas.microsoft.com/exchange/services/2006/messages">' + ' <ItemShape>' + ' <t:BaseShape>IdOnly</t:BaseShape>' + ' <t:AdditionalProperties>' + ' <t:FieldURI FieldURI="item:Subject"/>' + ' </t:AdditionalProperties>' + ' </ItemShape>' + ' <ItemIds><t:ItemId Id="' + id + '"/></ItemIds>' + ' </GetItem>' + ' </soap:Body>' + '</soap:Envelope>'; return result; } function sendRequest() { // Create a local variable that contains the mailbox. var mailbox = Office.context.mailbox; var id = mailbox.item.itemId; var soap = getSubjectRequest(id); mailbox.makeEwsRequestAsync(soap, callback); } function sendGetAllTasks() { var mailbox = Office.context.mailbox; var soap = getAllTasks(); mailbox.makeEwsRequestAsync(soap, callback); } function sendCreateTask(taskName) { var mailbox = Office.context.mailbox; var soap = getCreateTask(taskName); mailbox.makeEwsRequestAsync(soap, callback); } //This function takes a task JS objetc and creates ONE task using the EWS / O365 wrapped call function sendCreateTaskWithData(newtask) { } function callback(asyncResult) { var result = asyncResult.value; var context = asyncResult.context; // Process the returned response here. //$('#tasks').text("EWS URL: " + Office.context.mailbox.ewsUrl + "\n" + result); } })();
TaskHelperWeb/AppRead/Home/Home.js
/// <reference path="../App.js" /> (function () { "use strict"; // The Office initialize function must be run each time a new page is loaded Office.initialize = function (reason) { $(document).ready(function () { app.initialize(); displayItemDetails(); //displayTasks(); //displaySubject(); sendGetAllTasks(); //sendCreateTask(); $('#createNewTasks').click(sendCreateAllTasks); }); }; //Thus function iterates over a task object array and sends a create for each one function sendCreateAllTasks() { debugger; sendCreateTask(); } function displayTasks() { var tasks = Office.context.mailbox.item.getEntitiesByType(Office.MailboxEnums.EntityType.TaskSuggestion); var s = "count=" + tasks.length + "\n"; for (t in tasks) { s += t + "\n" } $('#tasks').text(s); } function displaySubject() { sendRequest(); } // Displays the "Subject" and "From" fields, based on the current mail item function displayItemDetails() { var item = Office.cast.item.toItemRead(Office.context.mailbox.item); $('#subject').text(item.subject); var from; if (item.itemType === Office.MailboxEnums.ItemType.Message) { from = Office.cast.item.toMessageRead(item).from; } else if (item.itemType === Office.MailboxEnums.ItemType.Appointment) { from = Office.cast.item.toAppointmentRead(item).organizer; } if (from) { $('#from').text(from.displayName); $('#from').click(function () { app.showNotification(from.displayName, from.emailAddress); }); } } function getProperties() { return ' <t:AdditionalProperties>' + ' <t:FieldURI FieldURI="item:Subject" />' + // ' <t:FieldURI FieldURI="item:Priority" />' + ' <t:FieldURI FieldURI="item:Status" />' + ' </t:AdditionalProperties>'; } function getAllTasks() { var result = getBodyPrefix() + ' <m:FindItem Traversal="Shallow">' + ' <m:ItemShape>' + ' <t:BaseShape>AllProperties</t:BaseShape>' + // getProperties() + ' </m:ItemShape>' + getRestriction() + ' <m:ParentFolderIds>' + ' <t:DistinguishedFolderId Id="tasks"/>' + ' </m:ParentFolderIds>' + ' </m:FindItem>' + getBodyPostfix(); return result; } function getRestriction() { return ' <m:Restriction>' + // ' <t:And>' + ' <t:IsNotEqualTo>' + ' <t:FieldURI FieldURI="task:Status" />' + ' <t:FieldURIOrConstant>' + ' <t:Constant Value="2" />' + ' </t:FieldURIOrConstant>' + ' </t:IsNotEqualTo>' + // ' </t:And>' + ' </m:Restriction>'; } function addSort() { return ' <m:SortOrder>' + ' <t:FieldOrder Order="Descending">' + ' <t:FieldURI FieldURI="item:Priority" />' + ' </t:FieldOrder>' + ' </m:SortOrder>'; } function getBodyPrefix() { return '<?xml version="1.0" encoding="utf-8"?>' + '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' + ' xmlns:xsd="http://www.w3.org/2001/XMLSchema"' + ' xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"' + ' xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" ' + ' xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">' + ' <soap:Header>' + ' <t:RequestServerVersion Version="Exchange2013" soap:mustUnderstand="0" />' + ' </soap:Header>' + ' <soap:Body>'; } function getBodyPostfix() { return ' </soap:Body>' + '</soap:Envelope>'; } function getCreateTask() { var result = getBodyPrefix() + ' <m:CreateItem>' + ' <m:Items>' + ' <t:Task>' + ' <t:Subject>Test EWS TaskHelper</t:Subject>' + ' <t:DueDate>2006-10-26T21:32:52</t:DueDate>' + ' <t:Status>NotStarted</t:Status>' + ' </t:Task>' + ' </m:Items>' + ' </m:CreateItem>' + getBodyPostfix(); return result; } function getSubjectRequest(id) { // Return a GetItem operation request for the subject of the specified item. var result = '<?xml version="1.0" encoding="utf-8"?>' + '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' + ' xmlns:xsd="http://www.w3.org/2001/XMLSchema"' + ' xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"' + ' xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">' + ' <soap:Header>' + ' <t:RequestServerVersion Version="Exchange2013" xmlns="http://schemas.microsoft.com/exchange/services/2006/types" soap:mustUnderstand="0" />' + ' </soap:Header>' + ' <soap:Body>' + ' <GetItem xmlns="http://schemas.microsoft.com/exchange/services/2006/messages">' + ' <ItemShape>' + ' <t:BaseShape>IdOnly</t:BaseShape>' + ' <t:AdditionalProperties>' + ' <t:FieldURI FieldURI="item:Subject"/>' + ' </t:AdditionalProperties>' + ' </ItemShape>' + ' <ItemIds><t:ItemId Id="' + id + '"/></ItemIds>' + ' </GetItem>' + ' </soap:Body>' + '</soap:Envelope>'; return result; } function sendRequest() { // Create a local variable that contains the mailbox. var mailbox = Office.context.mailbox; var id = mailbox.item.itemId; var soap = getSubjectRequest(id); mailbox.makeEwsRequestAsync(soap, callback); } function sendGetAllTasks() { var mailbox = Office.context.mailbox; var soap = getAllTasks(); mailbox.makeEwsRequestAsync(soap, callback); } function sendCreateTask() { var mailbox = Office.context.mailbox; var soap = getCreateTask(); debugger; mailbox.makeEwsRequestAsync(soap, callback); } //This function takes a task JS objetc and creates ONE task using the EWS / O365 wrapped call function sendCreateTaskWithData(newtask) { } function callback(asyncResult) { var result = asyncResult.value; var context = asyncResult.context; // Process the returned response here. //$('#tasks').text("EWS URL: " + Office.context.mailbox.ewsUrl + "\n" + result); } })();
Successful creation of a canned list of tasks
TaskHelperWeb/AppRead/Home/Home.js
Successful creation of a canned list of tasks
<ide><path>askHelperWeb/AppRead/Home/Home.js <ide> sendGetAllTasks(); <ide> //sendCreateTask(); <ide> <del> $('#createNewTasks').click(sendCreateAllTasks); <add> $('#createNewTasks').click(getListOfTasksToCreate); <ide> }); <ide> }; <ide> <add> //This test method creates an array of strings (tasks) and sends to the createAllMethod <add> function getListOfTasksToCreate() { <add> var arrayofTasks = ['task1', 'task2', 'task3']; <add> debugger; <add> sendCreateAllTasks(arrayofTasks); <add> } <add> <ide> //Thus function iterates over a task object array and sends a create for each one <del> function sendCreateAllTasks() { <del> debugger; <del> sendCreateTask(); <add> function sendCreateAllTasks(arrayOfTasks) { <add> <add> var arrayLen = arrayOfTasks.length; <add> var loop = 0; <add> for (loop = 0; loop < arrayLen; loop++) { <add> <add> var taskName = { <add> taskName: arrayOfTasks[loop], <add> startDateString: '2015-10-08T21:32:52' <add> } <add> sendCreateTask(taskName); <add> } <ide> } <ide> <ide> function displayTasks() { <ide> '</soap:Envelope>'; <ide> } <ide> <del> function getCreateTask() { <add> function getCreateTask(taskObject) { <add> //sample date <add> //2006-10-26T21:32:52 <ide> var result = getBodyPrefix() + <ide> ' <m:CreateItem>' + <ide> ' <m:Items>' + <ide> ' <t:Task>' + <del> ' <t:Subject>Test EWS TaskHelper</t:Subject>' + <del> ' <t:DueDate>2006-10-26T21:32:52</t:DueDate>' + <add> ' <t:Subject>'+taskObject.taskName+'</t:Subject>' + <add> ' <t:DueDate>'+taskObject.startDateString+'</t:DueDate>' + <ide> ' <t:Status>NotStarted</t:Status>' + <ide> ' </t:Task>' + <ide> ' </m:Items>' + <ide> <ide> function sendGetAllTasks() { <ide> var mailbox = Office.context.mailbox; <add> <ide> var soap = getAllTasks(); <ide> <ide> mailbox.makeEwsRequestAsync(soap, callback); <ide> } <ide> <ide> <del> function sendCreateTask() { <add> function sendCreateTask(taskName) { <ide> var mailbox = Office.context.mailbox; <del> var soap = getCreateTask(); <del> debugger; <add> var soap = getCreateTask(taskName); <ide> mailbox.makeEwsRequestAsync(soap, callback); <ide> } <ide>
Java
apache-2.0
db791a47f82c91bbfda7297dd934cc907f39be8e
0
pageseeder/diffx
/* * This file is part of the DiffX library. * * For licensing information please see the file license.txt included in the release. * A copy of this licence can also be found at * http://www.opensource.org/licenses/artistic-license-2.0.php */ package com.topologi.diffx.algorithm; import java.lang.reflect.Constructor; import com.topologi.diffx.sequence.EventSequence; /** * Factory for creating a Diff-X algorithm instance. * * @author Christophe Lauret * @version 3 February 2005 */ public final class DiffXFactory { /** * Private constructor. * * <p>This constructor prevents the class from being instantiated. */ private DiffXFactory() { } /** * The classes of the arguments of the constructor. */ private static final Class[] ARGS = new Class[]{EventSequence.class, EventSequence.class}; /** * Creates a Diff-X instance using the specified class name and event sequences. * * @param className The class name of the Diff-X implementation to use. * @param sequence1 The first sequence to use for the Diff-X constructor. * @param sequence2 The second sequence to use for the Diff-X constructor. * * @return A Diff-X algorithm instance. * * @throws FactoryException Should an error occur when trying to instantiate the class. */ public static DiffXAlgorithm createDiffex(String className, EventSequence sequence1, EventSequence sequence2) throws FactoryException { DiffXAlgorithm diffex = null; try { Class cls = Class.forName(className); Constructor cons = cls.getConstructor(ARGS); diffex = (DiffXAlgorithm)cons.newInstance(new EventSequence[]{sequence1, sequence2}); } catch (Exception ex) { throw new FactoryException(ex); } return diffex; } }
src/com/topologi/diffx/algorithm/DiffXFactory.java
/* * This file is part of the DiffX library. * * For licensing information please see the file license.txt included in the release. * A copy of this licence can also be found at * http://www.opensource.org/licenses/artistic-license-2.0.php */ package com.topologi.diffx.algorithm; import java.lang.reflect.Constructor; import com.topologi.diffx.sequence.EventSequence; /** * Factory for creating a Diff-X algorithm instance. * * @author Christophe Lauret * @version 3 February 2005 */ public final class DiffXFactory { /** * Private constructor. * * <p>This constructor prevents the class from being instantiated. */ private DiffXFactory() { } /** * The classes of the arguments of the constructor. */ private static final Class[] ARGS = new Class[]{EventSequence.class, EventSequence.class}; /** * Creates a diffex instance using the specified class name and event sequences. * * @param className The class name of the diffex implementation to use. * @param sequence1 The first sequence to use for the diffex constructor. * @param sequence2 The second sequence to use for the diffex constructor. * * @return A Diff-X algorithm instance. * * @throws FactoryException Should an error occur when trying to instantiate the class. */ public static DiffXAlgorithm createDiffex(String className, EventSequence sequence1, EventSequence sequence2) throws FactoryException { DiffXAlgorithm diffex = null; try { Class cls = Class.forName(className); Constructor cons = cls.getConstructor(ARGS); diffex = (DiffXAlgorithm)cons.newInstance(new EventSequence[]{sequence1, sequence2}); } catch (Exception ex) { throw new FactoryException(ex); } return diffex; } }
Improved consistency in comments
src/com/topologi/diffx/algorithm/DiffXFactory.java
Improved consistency in comments
<ide><path>rc/com/topologi/diffx/algorithm/DiffXFactory.java <ide> private static final Class[] ARGS = new Class[]{EventSequence.class, EventSequence.class}; <ide> <ide> /** <del> * Creates a diffex instance using the specified class name and event sequences. <add> * Creates a Diff-X instance using the specified class name and event sequences. <ide> * <del> * @param className The class name of the diffex implementation to use. <del> * @param sequence1 The first sequence to use for the diffex constructor. <del> * @param sequence2 The second sequence to use for the diffex constructor. <add> * @param className The class name of the Diff-X implementation to use. <add> * @param sequence1 The first sequence to use for the Diff-X constructor. <add> * @param sequence2 The second sequence to use for the Diff-X constructor. <ide> * <ide> * @return A Diff-X algorithm instance. <ide> *
JavaScript
mit
8aa65122def2185fe52a946dbdee80809d4f9491
0
derDaywalker/dmptool,derDaywalker/dmptool,derDaywalker/dmptool,derDaywalker/dmptool
// Place all the behaviors and hooks related to the matching controller here. // All this logic will automatically be available in application.js. $(function() { $('#dialog_form').hide(); $('#add_authorization_view').click(function() { $('#dialog_form').dialog( { width: 800, height: 200, modal: true, closeOnEscape: true, draggable: true, resizable: false, title: "Grant New Role", show: { effect: "blind", duration: 1000 }, hide: { effect: "toggle", duration: 1000 }, open: function() { $("#dialog_form").dialog("open"); }, close: function() { $('#dialog-form').dialog("close"); $(this).find('form')[0].reset(); } }).prev ().find (".ui-dialog-titlebar-close").show(); return false }); }); $(function() { $("#cancel_action").bind("click",function() { $("#flash_notice").remove(); }); }); $(function() { $(".tip").tooltip(); }); // //automatically checks Institutional reviewer role when Institutional Administrator role gets checked $(function() { $('#5').change(function(){ if ($('#5').is(':checked')) { $('#4').prop('checked', true); } }); }); // alert message if Institutional Admin remove his own Inst admin role $(function() { $('#current_admin_with_alert').click(function(){ if (!$('#5').is(':checked')) { if (confirm( "Do you really want to remove yourself from the Institutional Administrator role? You will lose all administrative permissions.")){ return true; } else { return false; }; }; }); }); $.extend({ alert: function (message, title) { $("<div></div>").dialog( { buttons: { "Ok": function () { $(this).dialog("close"); } }, close: function (event, ui) { $(this).remove(); }, resizable: false, title: title, modal: true }).text(message); } }); function validateFiles(inputFile) { var extErrorMessage = "Only image file with extension: .jpg, .jpeg, .gif or .png is allowed"; var allowedExtension = ["jpg", "jpeg", "gif", "png"]; var extName; var extError = false; $.each(inputFile.files, function() { extName = this.name.split('.').pop(); if ($.inArray(extName, allowedExtension) == -1) {extError=true;}; }); if (extError) { // window.alert(extErrorMessage); $.alert(extErrorMessage, "Wrong File Extension"); $(inputFile).val(''); }; } $(function(){ $("#run_date").on('change', function(e){ var run_date = $("#run_date option:selected")[0]; $.getJSON("usage_statistics", {run_date: run_date.value}) .done(function(data){ console.log(data); $(".effective-month").text(data['global_statistics']['effective_month']); Object.keys(data['institution_statistics']).forEach(function(key){ if($(".institutional_stats #" + key.replace('_', '-')) != null){ $(".institutional_stats #" + key.replace('_', '-')).text(data['institution_statistics'][key]); } }); Object.keys(data['global_statistics']).forEach(function(key){ console.log($(".global_stats #" + key.replace('_', '-'))); if($(".global_stats #" + key.replace('_', '-')) != null){ $(".global_stats #" + key.replace('_', '-')).text(data['global_statistics'][key]); } }); var top5 = ''; for(var i = 0; i < data['top_five_public_templates'].length; i++){ var tmplt = data['top_five_public_templates'][i]; top5 += tmplt['name'].substr(0,40) + ' ' + '(' + tmplt['new_plans'] + ' new ' + (tmplt['new_plans'] == 1 ? 'plan ' : 'plans, ') + '(' + tmplt['total_plans'] + ' total ' + (tmplt['total_plans'] == 1 ? 'plan ' : 'plans ') + ')<br/ >'; } $("#top-five-public-templates").html(top5); }).fail(function(xhr, stat, e){ console.log(stat + ', ' + e); }); }); });
app/assets/javascripts/institutions.js
// Place all the behaviors and hooks related to the matching controller here. // All this logic will automatically be available in application.js. $(function() { $('#dialog_form').hide(); $('#add_authorization_view').click(function() { $('#dialog_form').dialog( { width: 800, height: 200, modal: true, closeOnEscape: true, draggable: true, resizable: false, title: "Grant New Role", show: { effect: "blind", duration: 1000 }, hide: { effect: "toggle", duration: 1000 }, open: function() { $("#dialog_form").dialog("open"); }, close: function() { $('#dialog-form').dialog("close"); $(this).find('form')[0].reset(); } }).prev ().find (".ui-dialog-titlebar-close").show(); return false }); }); $(function() { $("#cancel_action").bind("click",function() { $("#flash_notice").remove(); }); }); $(function() { $(".tip").tooltip(); }); // //automatically checks Institutional reviewer role when Institutional Administrator role gets checked $(function() { $('#5').change(function(){ if ($('#5').is(':checked')) { $('#4').prop('checked', true); } }); }); // alert message if Institutional Admin remove his own Inst admin role $(function() { $('#current_admin_with_alert').click(function(){ if (!$('#5').is(':checked')) { if (confirm( "Do you really want to remove yourself from the Institutional Administrator role? You will lose all administrative permissions.")){ return true; } else { return false; }; }; }); }); $.extend({ alert: function (message, title) { $("<div></div>").dialog( { buttons: { "Ok": function () { $(this).dialog("close"); } }, close: function (event, ui) { $(this).remove(); }, resizable: false, title: title, modal: true }).text(message); } }); function validateFiles(inputFile) { var extErrorMessage = "Only image file with extension: .jpg, .jpeg, .gif or .png is allowed"; var allowedExtension = ["jpg", "jpeg", "gif", "png"]; var extName; var extError = false; $.each(inputFile.files, function() { extName = this.name.split('.').pop(); if ($.inArray(extName, allowedExtension) == -1) {extError=true;}; }); if (extError) { // window.alert(extErrorMessage); $.alert(extErrorMessage, "Wrong File Extension"); $(inputFile).val(''); }; } $(function(){ $("#run_date").on('change', function(e){ var run_date = $("#run_date option:selected")[0]; console.log('run_date selected: ' + run_date.value); $.getJSON("usage_statistics", {run_date: run_date.value}) .done(function(data){ console.log(data); $(".effective-month").text(data['global_statistics']['effective_month']); Object.keys(data['institution_statistics']).forEach(function(key){ if($(".institutional_stats #" + key.replace('_', '-')) != null){ $(".institutional_stats #" + key.replace('_', '-')).text(data['institution_statistics'][key]); } }); Object.keys(data['global_statistics']).forEach(function(key){ if($(".global_stats #" + key.replace('_', '-')) != null){ $(".global_stats #" + key.replace('_', '-')).text(data['global_statistics'][key]); } }); var top5 = ''; for(var i = 0; i < data['top_five_public_templates'].length; i++){ var tmplt = data['top_five_public_templates'][i]; top5 += tmplt['name'].substr(0,40) + ' ' + '(' + tmplt['new_plans'] + ' new ' + (tmplt['new_plans'] == 1 ? 'plan ' : 'plans, ') + '(' + tmplt['total_plans'] + ' total ' + (tmplt['total_plans'] == 1 ? 'plan ' : 'plans ') + ')<br/ >'; } $("#top-five-public-templates").html(top5); }).fail(function(xhr, stat, e){ console.log(stat + ', ' + e); }); }); });
added some debug to js
app/assets/javascripts/institutions.js
added some debug to js
<ide><path>pp/assets/javascripts/institutions.js <ide> $(function(){ <ide> $("#run_date").on('change', function(e){ <ide> var run_date = $("#run_date option:selected")[0]; <del> <del> console.log('run_date selected: ' + run_date.value); <del> <add> <ide> $.getJSON("usage_statistics", {run_date: run_date.value}) <ide> .done(function(data){ <del> console.log(data); <add>console.log(data); <ide> <ide> $(".effective-month").text(data['global_statistics']['effective_month']); <ide> <ide> }); <ide> <ide> Object.keys(data['global_statistics']).forEach(function(key){ <add>console.log($(".global_stats #" + key.replace('_', '-'))); <add> <ide> if($(".global_stats #" + key.replace('_', '-')) != null){ <ide> $(".global_stats #" + key.replace('_', '-')).text(data['global_statistics'][key]); <ide> }
Java
bsd-2-clause
e4bd74241f445fd8c9c5d929d0fa069aef4ce6b4
0
jchambers/jeospatial,jchambers/jeospatial
package com.eatthepath.jeospatial.vptree; import java.lang.reflect.Array; import java.util.ArrayDeque; import java.util.Collection; import java.util.Deque; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Vector; import com.eatthepath.jeospatial.CachingGeospatialPoint; import com.eatthepath.jeospatial.GeospatialPoint; import com.eatthepath.jeospatial.GeospatialPointDatabase; import com.eatthepath.jeospatial.SearchCriteria; import com.eatthepath.jeospatial.SimpleGeospatialPoint; import com.eatthepath.jeospatial.util.GeospatialDistanceComparator; import com.eatthepath.jeospatial.util.SearchResults; /** * <p>A geospatial database that uses a vantage point tree as its storage * mechanism.</p> * * <p>Vantage point trees (or "vp-trees") are a subclass of metric trees. * Vantage point trees use binary space partitioning to recursively divide * points among their nodes. Nodes in a vantage point tree have a center point * and a distance threshold; points with a distance less than or equal to the * threshold are assigned to the "left" child of a node and the others are * assigned to the "right" child.</p> * * <p>Queries in a vp-tree execute in O(log n) time in the best case, and tree * construction takes O(n log n) time.</p> * * <p>Vantage point trees may optionally be constructed with a * {@code nodeCapacity} argument. The node capacity dictates the maximum number * of points that <em>should</em> be stored in any given leaf node, although * nodes may hold more than that many points if its contents can't be * partitioned (i.e. all of the points in the node are coincident).</p> * * <p>When a search executed against a vp-tree reaches a leaf node, all of the * points in that node are considered for inclusion in the result set. It's * possible that a k-nearest-neighbor search will only need to visit one leaf * node if that node contains all of the k nearest neighbors to the query point. * A "good" node capacity for a vp-tree will be orders of magnitude smaller than * the size of the whole dataset and slightly larger (on the same order of * magnitude) than the "usual" number of nearest neighbors returned in a search; * a well-chosen node capacity will make searches more efficient by minimizing * the number of nodes that need to be visited while still minimizing the number * of "bad" points considered.</p> * * <p>The default node capacity for a vp-tree is {@value DEFAULT_BIN_SIZE} * points.</p> * * <p>Note that the {@code VPTree} class is <strong>not</strong> thread-safe; * because they forego any kind of synchronization or locking, {@code VPTree} * instances can achieve slightly higher search throughput than their * thread-safe counterparts. This makes the {@code VPTree} class a good choice * for single-threaded applications or applications where the tree will not be * modified after construction. For a thread-safe alternative, use the * {@link LockingVPTree} class.</p> * * @author <a href="mailto:[email protected]">Jon Chambers</a> * * @see <a href="http://pnylab.com/pny/papers/vptree/main.html">Yianilos, Peter * N. "Data Structures and Algorithms for Nearest Neighbor Search in * General Metric Spaces". Proceedings of the Fifth Annual ACM-SIAM * Symposium on Discrete Algorithms (SODA). 1993.</a> */ public class VPTree<E extends GeospatialPoint> implements GeospatialPointDatabase<E> { /** * <p>{@code VPNodes} are the nodes of a vantage point tree. {@code VPNodes} * may or may not be leaf nodes; if they are leaf nodes, they have no * children (their child node members will be {@code null}) and they will * have a non-null {@code points} member that contains all of the points * stored in the node.</p> * * <p>Non-leaf nodes will have non-{@code null} children and contain no * points of their own.</p> */ protected class VPNode<T extends GeospatialPoint> { private CachingGeospatialPoint center; private double threshold; private VPNode<T> closer; private VPNode<T> farther; private Vector<T> points; private final int binSize; /** * Constructs a new, empty node with the given capacity. * * @param binSize the largest number of points this node should hold */ public VPNode(int binSize) { this.binSize = binSize; this.points = new Vector<T>(this.binSize); this.center = null; } /** * Constructs a new node that contains a subset of the given array of * points. If the subset of points is larger than the given bin * capacity, child nodes will be created recursively. * * @param points * the array of points from which to build this node * @param fromIndex * the starting index (inclusive) of the subset of the array * from which to build this node * @param toIndex * the end index (exclusive) of the subset of the array from * which to build this node * @param binSize * the largest number of points this node should hold */ public VPNode(T[] points, int fromIndex, int toIndex, int binSize) { this.binSize = binSize; if(toIndex - fromIndex <= binSize) { // All done! This is a leaf node. this.storePoints(points, fromIndex, toIndex); } else { // We have more points than we want to store in a single leaf // node; try to partition the nodes. try { this.partition(points, fromIndex, toIndex); } catch(PartitionException e) { // Partitioning failed; this is most likely because all of // the points we were given are coincident. this.storePoints(points, fromIndex, toIndex); } } } /** * Returns a reference to this node's child that contains points that * are closer to this node's center than this node's distance threshold. * * @return a reference to this node's "closer" child, or {@code null} if * this is a leaf node * * @see VPNode#isLeafNode() */ public VPNode<T> getCloserNode() { return this.closer; } /** * Returns a reference to this node's child that contains points that * are farther away from this node's center than this node's distance * threshold. * * @return a reference to this node's "farther" child, or {@code null} * if this is a leaf node * * @see VPNode#isLeafNode() */ public VPNode<T> getFartherNode() { return this.farther; } /** * Returns a point that is coincident with this node's center point. * * @return a point that is coincident with this node's center point */ public GeospatialPoint getCenter() { return new SimpleGeospatialPoint(this.center); } /** * Returns the distance threshold for this node if it is a non-leaf * node. Points that have a distance to this node's center less than or * equal to the distance threshold are stored in the "closer" child node * of this tree while points with a distance from the center greater * than the threshold are stored in the "farther" node. * * @return the distance threshold for this node * * @throws IllegalStateException if this node is a leaf node * * @see VPNode#getCenter() * @see VPNode#getCloserNode() * @see VPNode#getFartherNode() */ public double getThreshold() { if(this.isLeafNode()) { throw new IllegalStateException("Leaf nodes do not have a distance threshold."); } return this.threshold; } /** * <p>Adds all of the points in a collection to this node (if it is a * leaf node) or its children. If this node is a leaf node and the added * points push this node beyond its capacity, it is partitioned as * needed after all points have been added.</p> * * <p>This method defers partitioning of child nodes until all points * have been added.</p> * * @param points * the collection of points to add to this node or its * children * * @return {@code true} if this node or its children were modified or * {@code false} otherwise */ public boolean addAll(Collection<? extends T> points) { HashSet<VPNode<T>> nodesToPartition = new HashSet<VPNode<T>>(); for(T point : points) { this.add(point, true, nodesToPartition); } // Resolve all of the deferred partitioning for(VPNode<T> node : nodesToPartition) { try { node.partition(); } catch(PartitionException e) { // Nothing to do here; this just means some nodes are bigger // than they want to be. } } // The tree was definitely modified as long as we were given a // non-empty collection of points to add. return !points.isEmpty(); } /** * Adds a point to this node if it is a leaf node or one of its children * if not. If the node that ultimately holds the new point is loaded * beyond its capacity, it will be partitioned. * * @param point * the point to add to this node or one of its children * * @return {@code true} if this node or one of its children was modified * by the addition of this point or {@code false} otherwise */ public boolean add(T point) { return this.add(point, false, null); } /** * <p>Adds a point to this node if it is a leaf node or one of its * children if not. If the node that ultimately holds the new point is * loaded beyond its capacity, it will be partitioned.</p> * * <p>Partitioning may optionally be deferred, in which case it is the * responsibility of the caller to partition overloaded nodes.</p> * * @param point * the point to add to this node or one of its children * @param deferPartitioning * if {@code true}, defer partitioning of overloaded nodes * until the caller chooses to partition them; if * {@code false}, overloaded nodes are partitioned * immediately * @param nodesToPartition * a {@code Set} that collects overloaded nodes in need of * deferred partitioning; this may be {@code null} if * {@code deferPartitioning} is {@code false}; callers must * use this set to partition nodes later * * @return {@code true} if this node or any of its children were * modified by the addition of the new point or {@code false} * otherwise; note that adding points always results in * modification */ protected boolean add(T point, boolean deferPartitioning, Set<VPNode<T>> nodesToPartition) { if(this.isLeafNode()) { this.points.add(point); // Should we try to repartition? if(this.points.size() > this.binSize) { if(deferPartitioning) { nodesToPartition.add(this); } else { try { this.partition(); } catch(PartitionException e) { // Nothing to do here; just hold on to all of our // points. } } } } else { if(this.center.getDistanceTo(point) <= this.threshold) { return this.closer.add(point); } else { return this.farther.add(point); } } // There's no way to add a point and not modify the tree. return true; } /** * Tests whether this node or one of its children contains the given * point. * * @param point * the point whose presence is to be tested * * @return {@code true} if the given point is present in this node or * one of its children or {@code false} otherwise */ public boolean contains(T point) { if(this.isLeafNode()) { return this.points.contains(point); } else { if(this.center.getDistanceTo(point) <= this.threshold) { return this.closer.contains(point); } else { return this.farther.contains(point); } } } /** * Returns the number of points contained in this node and its child * nodes. * * @return the number of points in this node and its children */ public int size() { if(this.isLeafNode()) { return this.points.size(); } else { return this.closer.size() + this.farther.size(); } } /** * Stores a subset of an array of points in this node directly, making * this node a leaf node. * * @param points * the array of points from which to store a subset * @param fromIndex * the starting index (inclusive) of the subset of the array * to store * @param toIndex * the end index (exclusive) of the subset of the array to * store */ private void storePoints(T[] points, int fromIndex, int toIndex) { this.points = new Vector<T>(this.binSize); for(int i = fromIndex; i < toIndex; i++) { this.points.add(points[i]); } // Always choose a center point if we don't already have one if(this.center == null && !this.points.isEmpty()) { this.center = new CachingGeospatialPoint(this.points.get(0)); } this.closer = null; this.farther = null; } /** * Returns a collection of all the points stored directly in this node. * * @return a collection of all the points stored directly in this node * * @throws IllegalStateException if this node is not a leaf node */ public Collection<T> getPoints() { if(!this.isLeafNode()) { throw new IllegalStateException("Cannot retrieve points from a non-leaf node."); } return new Vector<T>(this.points); } /** * Attempts to partition the points contained in this node into two * child nodes. Partitioning this node may trigger recursive * partitioning attempts in the generated child nodes. * * @throws PartitionException * if this node is node a leaf node, if this node is empty, * or if no viable distance threshold could be found (i.e. * all points in this node have the same distance from the * node's center) */ public void partition() throws PartitionException { if(!this.isLeafNode()) { throw new PartitionException("Cannot partition a non-leaf node."); } if(!this.isEmpty()) { @SuppressWarnings("unchecked") T[] pointArray = this.points.toArray((T[])Array.newInstance(points.iterator().next().getClass(), 0)); this.partition(pointArray, 0, pointArray.length); } else { throw new PartitionException("Cannot partition an empty node."); } } /** * Attempts to partition the points in a subset of the given array into * two child nodes based on their distance from the center of this node. * This method chooses a center point if none exists and chooses a * distance threshold to use as the criterion for node partitioning. The * threshold is chosen to be as close to the median distance of the * points in the sub-array as possible while still partitioning the * points into two groups. The child nodes generated by this method may * be partitioned recursively. * * @param points * an array from which to partition a subset of points * @param fromIndex * the start index of the sub-array of points to partition * (inclusive) * @param toIndex * the end index of the sub-array of points to partition * (exclusive) * * @throws PartitionException * if the range specified by {@code fromIndex} and * {@code toIndex} includes fewer than two points or if no * viable distance threshold could be found (i.e. all of the * points in the subarray have the same distance from this * node's center point) */ protected void partition(T[] points, int fromIndex, int toIndex) throws PartitionException { // We can't partition fewer then two points. if(toIndex - fromIndex < 2) { throw new PartitionException("Cannot partition fewer than two points."); } // We start by choosing a center point and a distance threshold; the // median distance from our center to points in our set is a safe // bet. if(this.center == null) { this.center = new CachingGeospatialPoint(points[fromIndex]); } // TODO Consider optimizing this whole approach to partitioning java.util.Arrays.sort(points, fromIndex, toIndex, new GeospatialDistanceComparator<T>(this.center)); int medianIndex = (fromIndex + toIndex - 1) / 2; double medianDistance = this.center.getDistanceTo(points[medianIndex]); // Since we're picking a definite median value from the list, we're // guaranteed to have at least one point that is closer to or EQUAL TO // (via identity) the threshold; what we want to do now is make sure // there's at least one point that's farther away from the center // than the threshold. int partitionIndex = -1; for(int i = medianIndex + 1; i < toIndex; i++) { if(this.center.getDistanceTo(points[i]) > medianDistance) { // We found at least one point farther away than the median // distance. That means we can use the median as our // distance threshold and everything after that point in the // sorted array as members of the "farther" node. partitionIndex = i; this.threshold = medianDistance; break; } } // Did we find a point that's farther away than the median distance? // If so, great! // // If not, we know that all points after the median point in the // sorted array have the same distance from the center, and we need // to try to move the threshold back until we find a point that's // less distant than the median distance. If we find such a point, // we'll use its distance from the center as our distance threshold. // If the median distance is zero, though, and we've made it this // far, we know there's nothing MORE distant than that and shouldn't // spend time searching. if(partitionIndex == -1) { if(medianDistance != 0) { for(int i = medianIndex; i > fromIndex; i--) { if(this.center.getDistanceTo(points[i]) < medianDistance) { partitionIndex = i; this.threshold = this.center.getDistanceTo(points[i]); break; } } // Did we still fail to find anything? There's still one // special case that can save us. If we've made it here, we // know that everything except the center point has the same // non-zero distance from the center. We can and should // still partition by putting the center alone in the // "closer" node and everything else in the "farther" node. // This, of course, assumes there's more than one point to // work with. if(partitionIndex == -1) { partitionIndex = fromIndex + 1; } } } // Still nothing? Bail out. if(partitionIndex == -1) { throw new PartitionException( "No viable partition threshold found (all points have equal distance from center)."); } // Okay! Now actually use that partition index. this.closer = new VPNode<T>(points, fromIndex, partitionIndex, this.binSize); this.farther = new VPNode<T>(points, partitionIndex, toIndex, this.binSize); // We're definitely not a leaf node now, so clear out our internal // point vector (if we had one). this.points = null; } /** * Tests whether this is a leaf node. * * @return {@code true} if this node is a leaf node or {@code false} * otherwise */ public boolean isLeafNode() { return this.closer == null; } /** * Tests whether this node and all of its children are empty. * * @return {@code true} if this node and all of its children contain no * points or {@code false} otherwise */ public boolean isEmpty() { if(this.isLeafNode()) { return this.points.isEmpty(); } else { return (this.closer.isEmpty() && this.farther.isEmpty()); } } /** * Tests whether this node contains more points than its maximum * capacity. * * @return {@code true} if the number of points stored in this node is * greater than its capacity or {@code false} otherwise * * @throws IllegalStateException if this is not a leaf node */ public boolean isOverloaded() { if(!this.isLeafNode()) { throw new IllegalStateException("Non-leaf nodes cannot be overloaded."); } return this.points.size() > this.binSize; } /** * Populates the given search result set with points close to the query * point. If this node is a leaf node, all of its contained points are * "offered" to the search result set as potential nearest neighbors. If * this is not a leaf node, one or both of its children are searched * recursively. * * @param queryPoint the point for which to find nearby neighbors * @param results the result set to which to offer points */ public void getNearestNeighbors(final GeospatialPoint queryPoint, final SearchResults<T> results) { // If this is a leaf node, our job is easy. Offer all of our points // to the result set and bail out. if(this.isLeafNode()) { results.addAll(this.points); } else { // Descend through the tree recursively. boolean searchedCloserFirst; double distanceToCenter = this.center.getDistanceTo(queryPoint); if(distanceToCenter <= this.threshold) { this.closer.getNearestNeighbors(queryPoint, results); searchedCloserFirst = true; } else { this.farther.getNearestNeighbors(queryPoint, results); searchedCloserFirst = false; } // ...and now we're on our way back up. Decide if we need to search // whichever child we didn't search on the way down. if(searchedCloserFirst) { // We've already searched the node that contains points // within our threshold (which also implies that the query // point is inside our threshold); we also want to search // the node beyond our threshold if the distance from the // query point to the most distant match is longer than the // distance from the query point to our threshold, since // there could be a point outside our threshold that's // closer than the most distant match. double distanceToThreshold = this.threshold - distanceToCenter; if(results.getLongestDistanceFromQueryPoint() > distanceToThreshold) { this.farther.getNearestNeighbors(queryPoint, results); } } else { // We've already searched the node that contains points // beyond our threshold, and the query point itself is // beyond our threshold. We want to search the // within-threshold node if it's "easier" to get from the // query point to our region than it is to get from the // query point to the most distant match, since there could // be a point within our threshold that's closer than the // most distant match. double distanceToThreshold = distanceToCenter - this.threshold; if(distanceToThreshold <= results.getLongestDistanceFromQueryPoint()) { this.closer.getNearestNeighbors(queryPoint, results); } } } } /** * Populates the given {@code Vector} with all points within the given * range that match the given search criteria (if any). If this node is * a leaf node, all points contained within the node that are within the * given distance of the query point and match the search criteria are * added to the {@code Vector}. If this node is not a leaf node, its * children are searched recursively. * * @param queryPoint * the point for which to find nearby neighbors * @param maxDistance * the maximum distance within which points should be added * to the result set * @param criteria * the search criteria to apply to potential matches; if * {@code null}, only a point's distance from the query point * is considered when deciding to include it in the result * set * @param results * the {@code Vector} to populate */ public void getAllWithinRange(final CachingGeospatialPoint queryPoint, final double maxDistance, final SearchCriteria<T> criteria, final Vector<T> results) { // If this is a leaf node, just add all of our points to the list if // they fall within range and meet the search criteria (if any). if(this.isLeafNode()) { for(T point : this.points) { if(queryPoint.getDistanceTo(point) <= maxDistance) { if(criteria == null || criteria.matches(point)) { results.add(point); } } } } else { // We want to search whichever of our nodes intersect with the // query region, which remains static throughout an // "all within range" search. double distanceToQueryPoint = this.center.getDistanceTo(queryPoint); // Does any part of the query region fall within our threshold? if(distanceToQueryPoint <= this.threshold + maxDistance) { this.closer.getAllWithinRange(queryPoint, maxDistance, criteria, results); } // Does any part of the query region fall outside of our // threshold? Or, put differently, does our region fail to // completely enclose the query region? if(distanceToQueryPoint + maxDistance > this.threshold) { this.farther.getAllWithinRange(queryPoint, maxDistance, criteria, results); } } } /** * Adds all of the points from this node if it is a leaf node or its * children if it is not to an array. It is the responsibility of the * caller to ensure that the array has sufficient capacity to hold all * of the points in this node and its children. * * @param array * the array to which to add points * * @see VPNode#size() */ public void addPointsToArray(Object[] array) { this.addPointsToArray(array, 0); } /** * Adds all of the points from this node and its children to the given * array starting at the given offset. It is the responsibility of the * caller to ensure that the array has sufficient capacity to hold all * of the points in this node and its children. * * @param array * the array to which to ad points * @param offset * the starting index (inclusive) of the array to begin * adding points * * @return the number of points added to the array */ public int addPointsToArray(Object[] array, int offset) { if(this.isLeafNode()) { if(this.isEmpty()) { return 0; } System.arraycopy(this.points.toArray(), 0, array, offset, this.points.size()); return this.points.size(); } else { int nAddedFromCloser = this.closer.addPointsToArray(array, offset); int nAddedFromFarther = this.farther.addPointsToArray(array, offset + nAddedFromCloser); return nAddedFromCloser + nAddedFromFarther; } } /** * Finds the node at or below this node that contains (or would contain) * the given point. The given stack is populated with each node on the * path to the leaf node that contains the given point. * * @param p * the point for which to find the containing node * @param stack * the stack to populate with the chain of nodes leading to * the leaf node that contains or would contain the given * point */ public void findNodeContainingPoint(final GeospatialPoint p, final Deque<VPNode<T>> stack) { // First things first; add ourselves to the stack. stack.push(this); // If this is a leaf node, we don't need to do anything else. If // it's not a leaf node, recurse! if(!this.isLeafNode()) { if(this.center.getDistanceTo(p) <= this.threshold) { this.closer.findNodeContainingPoint(p, stack); } else { this.farther.findNodeContainingPoint(p, stack); } } } /** * Removes a point from this node's internal list of points. * * @param point * the point to remove from this node * * @return {@code true} if the point was removed from this node (i.e. * this node actually contained the given point) or * {@code false} otherwise * * @throws IllegalStateException if this node is not a leaf node */ public boolean remove(T point) { if(this.isLeafNode()) { return this.points.remove(point); } else { throw new IllegalStateException("Cannot remove points from a non-leaf node."); } } /** * Recursively absorbs the points contained in this node's children into * this node, making this node a leaf node in the process. * * @throws IllegalStateException * if this node is a leaf node (and thus has no children) */ public void absorbChildren() { if(this.isLeafNode()) { throw new IllegalStateException("Leaf nodes have no children."); } this.points = new Vector<T>(this.binSize); if(!this.closer.isLeafNode()) { this.closer.absorbChildren(); } if(!this.farther.isLeafNode()) { this.farther.absorbChildren(); } this.points.addAll(this.closer.getPoints()); this.points.addAll(this.farther.getPoints()); this.closer = null; this.farther = null; } /** * Populates the given {@code List} with all of the leaf nodes that are * descendants of this node. * * @param leafNodes the list to populate with leaf nodes */ public void gatherLeafNodes(List<VPNode<T>> leafNodes) { if(this.isLeafNode()) { leafNodes.add(this); } else { this.closer.gatherLeafNodes(leafNodes); this.farther.gatherLeafNodes(leafNodes); } } /** * Tests whether this node is an ancestor of the given node. * * @param node * the node for which to test ancestry * * @return {@code true} if the given node is a descendant of this node * or {@code false} otherwise */ public boolean isAncestorOfNode(VPNode<T> node) { // Obviously, leaf nodes can't be the ancestors of anything if(this.isLeafNode()) { return false; } // Find a path to the center of the node we've been given ArrayDeque<VPNode<T>> stack = new ArrayDeque<VPNode<T>>(); this.findNodeContainingPoint(node.getCenter(), stack); // We're an ancestor if we appear anywhere in the path to the given // node return stack.contains(this); } } /** * The default node capacity ({@value} points) for nodes in this tree. */ public static final int DEFAULT_BIN_SIZE = 32; private final int binSize; private VPNode<E> root; /** * Constructs a new, empty vp-tree with a default node capacity. */ public VPTree() { this(DEFAULT_BIN_SIZE); } /** * Constructs a new, empty vp-tree with the specified node capacity. * * @param nodeCapacity * the maximum number of points to store in a leaf node of the * tree */ public VPTree(int nodeCapacity) { if(nodeCapacity < 1) { throw new IllegalArgumentException("Node capacity must be greater than zero."); } this.binSize = nodeCapacity; this.root = new VPNode<E>(this.binSize); } /** * Constructs a new vp-tree that contains (and indexes) all of the points in * the given collection. Nodes of the tree are created with a default * capacity. * * @param points * the points to use to populate this tree */ public VPTree(Collection<E> points) { this(points, DEFAULT_BIN_SIZE); } /** * Constructs a new vp-tree that contains (and indexes) all of the points in * the given collection and has leaf nodes with the given point capacity. * * @param points * the points to use to populate this tree * @param nodeCapacity * the largest number of points any leaf node of the tree should * contain */ public VPTree(Collection<E> points, int nodeCapacity) { if(nodeCapacity < 1) { throw new IllegalArgumentException("Node capacity must be greater than zero."); } this.binSize = nodeCapacity; if(!points.isEmpty()) { @SuppressWarnings("unchecked") E[] pointArray = points.toArray((E[])Array.newInstance(points.iterator().next().getClass(), 0)); this.root = new VPNode<E>(pointArray, 0, pointArray.length, this.binSize); } else { this.root = new VPNode<E>(this.binSize); } } /** * Returns a reference to this tree's root node. This method is intended for * testing purposes only. * * @return a reference to this tree's root node */ protected VPNode<E> getRoot() { return this.root; } /** * Returns the maximum number of points any leaf node of this tree should * contain. * * @return the maximum number of points any leaf node should contain */ public int getBinSize() { return this.binSize; } /** * Adds a single point to this vp-tree. Addition of a point executes in * O(log n) time in the best case (where n is the number of points in the * tree), but may also trigger a node partition that takes additional time. * * @param point * the point to add to this tree * * @return {@code true} if the tree was modified by the addition of this * point; vp-trees are always modified by adding points, so this * method always returns true */ @Override public boolean add(E point) { return this.root.add(point); } /** * Adds all of the points in the given collection to this vp-tree. * * @param points the points to add to this tree * * @return {@code true} if the tree was modified by the addition of the * points; vp-trees are always modified by adding points, so this * method always returns true */ @Override public boolean addAll(Collection<? extends E> points) { return this.root.addAll(points); } /** * Removes all points from this vp-tree. Clearing a vp-tree executes in O(1) * time. */ @Override public void clear() { this.root = new VPNode<E>(this.binSize); } /** * Tests whether this vp-tree contains the given point. Membership tests * execute in O(log n) time, where n is the number of points in the tree. * * @param o * the object to test for membership in this tree * * @return {@code true} if this tree contains the given point or * {@code false} otherwise */ @SuppressWarnings("unchecked") @Override public boolean contains(Object o) { try { return this.root.contains((E)o); } catch(ClassCastException e) { return false; } } /** * Tests whether this vp-tree contains all of the points in the given * collection. Group membership tests execute in O(m log n) time, where m is * the number of points in the given collection and n is the number of * points in the tree. * * @param c * the collection of points to test for membership in this tree * * @return {@code true} if this tree contains all of the members of the * given collection or {@code false} otherwise */ @Override public boolean containsAll(Collection<?> c) { for(Object o : c) { if(!this.contains(o)) { return false; } } return true; } /** * Tests whether this tree is empty. * * @return {@code true} if this tree contains no points or {@code false} * otherwise */ @Override public boolean isEmpty() { return this.root.isEmpty(); } /** * Returns an @{code Iterator} over all of the points contained in this * tree. The order of iteration is not defined, and the @{code Iterator} * returned by this method does not support the optional @{code remove} * method. The behavior of the returned {@code Iterator} is not defined if * the tree is modified after the {@code Iterator} is returned. * * @return an {@code Iterator} over the points contained in this tree */ @Override public Iterator<E> iterator() { return new TreeIterator<E>(this.root); } /** * Removes a point from this tree. * * @param o * the point to remove * * @return {@code true} if the tree was modified by removing this point * (i.e. if the point was present in the tree) or {@code false} * otherwise */ @Override public boolean remove(Object o) { try { @SuppressWarnings("unchecked") E point = (E)o; return this.remove(point, false, null); } catch(ClassCastException e) { // The object we were given wasn't the kind of thing we're storing, // so we definitely can't remove it. return false; } } /** * Removes a point from this tree and optionally defers pruning of nodes * left empty after the removal of their last point. If pruning is deferred, * it is the responsibility of the caller to prune nodes after this method * has executed. * * @param point * the point to remove * @param deferPruning * if {@code true} and the removal of the given point would leave * a node empty, pruning of the empty node is deferred until a * time chosen by the caller; otherwise, empty nodes are pruned * immediately * @param nodesToPrune * a @{code Set} to be populated with nodes left empty by the * removal of points; this may be {@code null} if * {@code deferPruning} if {@code false} * * @return {@code true} if the tree was modified by removing this point * (i.e. if the point was present in the tree) or {@code false} * otherwise */ protected boolean remove(E point, boolean deferPruning, Set<VPNode<E>> nodesToPrune) { ArrayDeque<VPNode<E>> stack = new ArrayDeque<VPNode<E>>(); this.root.findNodeContainingPoint(point, stack); VPNode<E> node = stack.pop(); boolean pointRemoved = node.remove(point); if(node.isEmpty()) { if(deferPruning) { nodesToPrune.add(node); } else { this.pruneEmptyNode(node); } } return pointRemoved; } /** * Removes all of the points in the given collection from this tree. * * @param c * the collection of points to remove from this true * * @return {@code true} if the tree was modified by removing the given * points (i.e. if any of the points were present in the tree) or * {@code false} otherwise */ @Override public boolean removeAll(Collection<?> c) { boolean anyChanged = false; HashSet<VPNode<E>> nodesToPrune = new HashSet<VPNode<E>>(); for(Object o : c) { try { @SuppressWarnings("unchecked") E point = (E)o; // The behavioral contact for Collections states, "After this // call returns, this collection will contain no elements in // common with the specified collection." Make sure we remove // all instances of each point in the collection of points to // remove. while(this.remove(point, true, nodesToPrune)) { anyChanged = true; } } catch(ClassCastException e) { // The object wasn't the kind of point we have in this tree; // just keep moving. } } // Avoid duplicating work by removing pruning targets that are children // of other pruning targets (since they would be implicitly pruned by // pruning the parent). HashSet<VPNode<E>> nodesToNotPrune = new HashSet<VPNode<E>>(); for(VPNode<E> node : nodesToPrune) { for(VPNode<E> potentialAncestor : nodesToPrune) { if(potentialAncestor.isAncestorOfNode(node)) { nodesToNotPrune.add(node); } } } nodesToPrune.removeAll(nodesToNotPrune); // Now the set of nodes to prune contains only the highest nodes in any // branch; prune (and potentially repartition) each of those // individually. for(VPNode<E> node : nodesToPrune) { this.pruneEmptyNode(node); if(node.isOverloaded()) { try { node.partition(); } catch(PartitionException e) { // These things happen. } } } return anyChanged; } /** * <p>"Prunes" an empty leaf node from the tree. When a node is pruned, its * parent absorbs the points from both of its child nodes (though only one * may actually contain points) and discards its child nodes. If the parent * node is empty after the absorption of its child nodes, it is also pruned; * this process continues until either an ancestor of the original node is * non-empty after absorbing its children or until the root of the tree is * reached.</p> * * <p>The pruning process may leave an ancestor node overly-full, in which * case it is the responsibility of the caller to repartition that node.</p> * * @param node the empty node to prune from the tree */ protected void pruneEmptyNode(VPNode<E> node) { // Only spend time working on this if the node is actually empty; it's // harmless to call this method on a non-empty node, though. if(node.isEmpty() && node != this.root) { ArrayDeque<VPNode<E>> stack = new ArrayDeque<VPNode<E>>(); this.root.findNodeContainingPoint(node.getCenter(), stack); // Immediately pop the first node off the stack (since we know it's // the empty leaf node we were handed as an argument). stack.pop(); // Work through the stack until we either have a non-empty parent or // we hit the root of the tree. while(stack.peek() != null) { VPNode<E> parent = stack.pop(); parent.absorbChildren(); // We're done as soon as we have a non-empty parent. if(!parent.isEmpty()) { break; } } } } /** * Retains only the points in this vp-tree that are contained in the * specified collection. In other words, removes from this tree all of its * points that are not contained in the specified collection. * * @param c * collection containing elements to be retained in this tree * * @return {@code true} if this tree was modified by calling this method or * {@code false} otherwise */ @Override public boolean retainAll(Collection<?> c) { // We need to build up a list of points to remove after the initial // search to avoid concurrent modification woes Vector<E> pointsToRemove = new Vector<E>(); for(E point : this) { if(!c.contains(point)) { pointsToRemove.add(point); } } return this.removeAll(pointsToRemove); } /** * Returns the total number of points stored in this vp-tree. * * @return the number of points stored in this vp-tree */ @Override public int size() { return this.root.size(); } /** * Returns an array containing all of the points in this vp-tree. The order * of the points in the array is not defined. * * @return an array containing all of the points in this vp-tree */ @Override public Object[] toArray() { Object[] array = new Object[this.size()]; this.root.addPointsToArray(array); return array; } /** * <p>Returns an array containing all of the points in this vp-tree; the * runtime type of the returned array is that of the specified array. If the * collection fits in the specified array, it is returned therein. * Otherwise, a new array is allocated with the runtime type of the * specified array and the size of this collection.</p> * * <p>If all of the points in this tree fit in the specified array with room * to spare (i.e., the array has more elements than this vp-tree), the * element in the array immediately following the end of the collection is * set to {@code null}.</p> * * @param a * the array into which the elements of this tree are to be * stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose * * @return an array containing all of the points in this vp-tree */ @SuppressWarnings("unchecked") @Override public <T> T[] toArray(T[] a) { int size = this.size(); if(a.length < this.size()) { return (T[])java.util.Arrays.copyOf(this.toArray(), size, a.getClass()); } else { System.arraycopy(this.toArray(), 0, a, 0, size); if(a.length > size) { a[size] = null; } return a; } } /* * (non-Javadoc) * @see com.eatthepath.jeospatial.GeospatialPointDatabase#getNearestNeighbors(com.eatthepath.jeospatial.GeospatialPoint, int) */ @Override public List<E> getNearestNeighbors(GeospatialPoint queryPoint, int maxResults) { SearchResults<E> results = new SearchResults<E>(queryPoint, maxResults); this.root.getNearestNeighbors(queryPoint, results); return results.toSortedList(); } /* * (non-Javadoc) * @see com.eatthepath.jeospatial.GeospatialPointDatabase#getNearestNeighbors(com.eatthepath.jeospatial.GeospatialPoint, int, double) */ @Override public List<E> getNearestNeighbors(GeospatialPoint queryPoint, int maxResults, double maxDistance) { SearchResults<E> results = new SearchResults<E>(queryPoint, maxResults, maxDistance); this.root.getNearestNeighbors(queryPoint, results); return results.toSortedList(); } /* * (non-Javadoc) * @see com.eatthepath.jeospatial.GeospatialPointDatabase#getNearestNeighbors(com.eatthepath.jeospatial.GeospatialPoint, int, com.eatthepath.jeospatial.SearchCriteria) */ @Override public List<E> getNearestNeighbors(GeospatialPoint queryPoint, int maxResults, SearchCriteria<E> searchCriteria) { SearchResults<E> results = new SearchResults<E>(queryPoint, maxResults, searchCriteria); this.root.getNearestNeighbors(queryPoint, results); return results.toSortedList(); } /* * (non-Javadoc) * @see com.eatthepath.jeospatial.GeospatialPointDatabase#getNearestNeighbors(com.eatthepath.jeospatial.GeospatialPoint, int, double, com.eatthepath.jeospatial.SearchCriteria) */ @Override public List<E> getNearestNeighbors(GeospatialPoint queryPoint, int maxResults, double maxDistance, SearchCriteria<E> searchCriteria) { SearchResults<E> results = new SearchResults<E>(queryPoint, maxResults, maxDistance, searchCriteria); this.root.getNearestNeighbors(queryPoint, results); return results.toSortedList(); } /* * (non-Javadoc) * @see com.eatthepath.jeospatial.GeospatialPointDatabase#getAllNeighborsWithinDistance(com.eatthepath.jeospatial.GeospatialPoint, double) */ @Override public List<E> getAllNeighborsWithinDistance(GeospatialPoint queryPoint, double maxDistance) { return this.getAllNeighborsWithinDistance(queryPoint, maxDistance, null); } /* * (non-Javadoc) * @see com.eatthepath.jeospatial.GeospatialPointDatabase#getAllNeighborsWithinDistance(com.eatthepath.jeospatial.GeospatialPoint, double, com.eatthepath.jeospatial.SearchCriteria) */ @Override public List<E> getAllNeighborsWithinDistance(GeospatialPoint queryPoint, double maxDistance, SearchCriteria<E> searchCriteria) { Vector<E> results = new Vector<E>(this.binSize); this.root.getAllWithinRange(new CachingGeospatialPoint(queryPoint), maxDistance, searchCriteria, results); java.util.Collections.sort(results, new GeospatialDistanceComparator<E>(queryPoint)); return results; } /* * (non-Javadoc) * @see com.eatthepath.jeospatial.GeospatialPointDatabase#getNearestNeighbor(com.eatthepath.jeospatial.GeospatialPoint) */ @Override public E getNearestNeighbor(GeospatialPoint queryPoint) { SearchResults<E> results = new SearchResults<E>(queryPoint, 1); this.root.getNearestNeighbors(queryPoint, results); return results.peek(); } /* * (non-Javadoc) * @see com.eatthepath.jeospatial.GeospatialPointDatabase#getNearestNeighbor(com.eatthepath.jeospatial.GeospatialPoint, double) */ @Override public E getNearestNeighbor(GeospatialPoint queryPoint, double maxDistance) { SearchResults<E> results = new SearchResults<E>(queryPoint, 1, maxDistance); this.root.getNearestNeighbors(queryPoint, results); return results.peek(); } /* * (non-Javadoc) * @see com.eatthepath.jeospatial.GeospatialPointDatabase#getNearestNeighbor(com.eatthepath.jeospatial.GeospatialPoint, com.eatthepath.jeospatial.SearchCriteria) */ @Override public E getNearestNeighbor(GeospatialPoint queryPoint, SearchCriteria<E> searchCriteria) { SearchResults<E> results = new SearchResults<E>(queryPoint, 1, searchCriteria); this.root.getNearestNeighbors(queryPoint, results); return results.peek(); } /* * (non-Javadoc) * @see com.eatthepath.jeospatial.GeospatialPointDatabase#getNearestNeighbor(com.eatthepath.jeospatial.GeospatialPoint, double, com.eatthepath.jeospatial.SearchCriteria) */ @Override public E getNearestNeighbor(GeospatialPoint queryPoint, double maxDistance, SearchCriteria<E> searchCriteria) { SearchResults<E> results = new SearchResults<E>(queryPoint, 1, maxDistance, searchCriteria); this.root.getNearestNeighbors(queryPoint, results); return results.peek(); } /* * (non-Javadoc) * @see com.eatthepath.jeospatial.GeospatialPointDatabase#movePoint(com.eatthepath.jeospatial.GeospatialPoint, double, double) */ @Override public void movePoint(E point, double latitude, double longitude) { this.movePoint(point, new SimpleGeospatialPoint(latitude, longitude)); } /* * (non-Javadoc) * @see com.eatthepath.jeospatial.GeospatialPointDatabase#movePoint(com.eatthepath.jeospatial.GeospatialPoint, com.eatthepath.jeospatial.GeospatialPoint) */ @Override public void movePoint(E point, GeospatialPoint destination) { // Moving points can trigger significant structural changes to a // tree. If a point's departure from a node would leave that node // empty, its parent needs to gather the nodes from its children and // potentially repartition itself. If the point's arrival in a node // would push that node over the bin size threshold, the node might // need to be partitioned. We want to avoid the case where we'd move // the point out of a node, regroup things in the parent, and then // put the node right back in the same place, so we do some work in // advance to see if the old and new positions would fall into the // same tree node. ArrayDeque<VPNode<E>> sourcePath = new ArrayDeque<VPNode<E>>(); ArrayDeque<VPNode<E>> destinationPath = new ArrayDeque<VPNode<E>>(); this.root.findNodeContainingPoint(point, sourcePath); this.root.findNodeContainingPoint(destination, destinationPath); if(sourcePath.equals(destinationPath)) { // Easy! We expect no structural changes, so we can modify the // point directly and immediately. point.setLatitude(destination.getLatitude()); point.setLongitude(destination.getLongitude()); } else { // We don't know that moving the point will cause structural // changes, but we have to assume it will. this.remove(point); point.setLatitude(destination.getLatitude()); point.setLongitude(destination.getLongitude()); this.add(point); } } }
src/com/eatthepath/jeospatial/vptree/VPTree.java
package com.eatthepath.jeospatial.vptree; import java.lang.reflect.Array; import java.util.ArrayDeque; import java.util.Collection; import java.util.Deque; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Vector; import com.eatthepath.jeospatial.CachingGeospatialPoint; import com.eatthepath.jeospatial.GeospatialPoint; import com.eatthepath.jeospatial.GeospatialPointDatabase; import com.eatthepath.jeospatial.SearchCriteria; import com.eatthepath.jeospatial.SimpleGeospatialPoint; import com.eatthepath.jeospatial.util.GeospatialDistanceComparator; import com.eatthepath.jeospatial.util.SearchResults; /** * <p>A geospatial database that uses a vantage point tree as its storage * mechanism.</p> * * <p>Vantage point trees (or "vp-trees") are a subclass of metric trees. * Vantage point trees use binary space partitioning to recursively divide * points among their nodes. Nodes in a vantage point tree have a center point * and a distance threshold; points with a distance less than or equal to the * threshold are assigned to the "left" child of a node and the others are * assigned to the "right" child.</p> * * <p>Queries in a vp-tree execute in O(log n) time in the best case, and tree * construction takes O(n log n) time.</p> * * <p>Vantage point trees may optionally be constructed with a * {@code nodeCapacity} argument. The node capacity dictates the maximum number * of points that <em>should</em> be stored in any given leaf node, although * nodes may hold more than that many points if its contents can't be * partitioned (i.e. all of the points in the node are coincident).</p> * * <p>When a search executed against a vp-tree reaches a leaf node, all of the * points in that node are considered for inclusion in the result set. It's * possible that a k-nearest-neighbor search will only need to visit one leaf * node if that node contains all of the k nearest neighbors to the query point. * A "good" node capacity for a vp-tree will be orders of magnitude smaller than * the size of the whole dataset and slightly larger (on the same order of * magnitude) than the "usual" number of nearest neighbors returned in a search; * a well-chosen node capacity will make searches more efficient by minimizing * the number of nodes that need to be visited while still minimizing the number * of "bad" points considered.</p> * * <p>The default node capacity for a vp-tree is {@value DEFAULT_BIN_SIZE} * points.</p> * * @author <a href="mailto:[email protected]">Jon Chambers</a> * * @see <a href="http://pnylab.com/pny/papers/vptree/main.html">Yianilos, Peter * N. "Data Structures and Algorithms for Nearest Neighbor Search in * General Metric Spaces". Proceedings of the Fifth Annual ACM-SIAM * Symposium on Discrete Algorithms (SODA). 1993.</a> */ public class VPTree<E extends GeospatialPoint> implements GeospatialPointDatabase<E> { /** * <p>{@code VPNodes} are the nodes of a vantage point tree. {@code VPNodes} * may or may not be leaf nodes; if they are leaf nodes, they have no * children (their child node members will be {@code null}) and they will * have a non-null {@code points} member that contains all of the points * stored in the node.</p> * * <p>Non-leaf nodes will have non-{@code null} children and contain no * points of their own.</p> */ protected class VPNode<T extends GeospatialPoint> { private CachingGeospatialPoint center; private double threshold; private VPNode<T> closer; private VPNode<T> farther; private Vector<T> points; private final int binSize; /** * Constructs a new, empty node with the given capacity. * * @param binSize the largest number of points this node should hold */ public VPNode(int binSize) { this.binSize = binSize; this.points = new Vector<T>(this.binSize); this.center = null; } /** * Constructs a new node that contains a subset of the given array of * points. If the subset of points is larger than the given bin * capacity, child nodes will be created recursively. * * @param points * the array of points from which to build this node * @param fromIndex * the starting index (inclusive) of the subset of the array * from which to build this node * @param toIndex * the end index (exclusive) of the subset of the array from * which to build this node * @param binSize * the largest number of points this node should hold */ public VPNode(T[] points, int fromIndex, int toIndex, int binSize) { this.binSize = binSize; if(toIndex - fromIndex <= binSize) { // All done! This is a leaf node. this.storePoints(points, fromIndex, toIndex); } else { // We have more points than we want to store in a single leaf // node; try to partition the nodes. try { this.partition(points, fromIndex, toIndex); } catch(PartitionException e) { // Partitioning failed; this is most likely because all of // the points we were given are coincident. this.storePoints(points, fromIndex, toIndex); } } } /** * Returns a reference to this node's child that contains points that * are closer to this node's center than this node's distance threshold. * * @return a reference to this node's "closer" child, or {@code null} if * this is a leaf node * * @see VPNode#isLeafNode() */ public VPNode<T> getCloserNode() { return this.closer; } /** * Returns a reference to this node's child that contains points that * are farther away from this node's center than this node's distance * threshold. * * @return a reference to this node's "farther" child, or {@code null} * if this is a leaf node * * @see VPNode#isLeafNode() */ public VPNode<T> getFartherNode() { return this.farther; } /** * Returns a point that is coincident with this node's center point. * * @return a point that is coincident with this node's center point */ public GeospatialPoint getCenter() { return new SimpleGeospatialPoint(this.center); } /** * Returns the distance threshold for this node if it is a non-leaf * node. Points that have a distance to this node's center less than or * equal to the distance threshold are stored in the "closer" child node * of this tree while points with a distance from the center greater * than the threshold are stored in the "farther" node. * * @return the distance threshold for this node * * @throws IllegalStateException if this node is a leaf node * * @see VPNode#getCenter() * @see VPNode#getCloserNode() * @see VPNode#getFartherNode() */ public double getThreshold() { if(this.isLeafNode()) { throw new IllegalStateException("Leaf nodes do not have a distance threshold."); } return this.threshold; } /** * <p>Adds all of the points in a collection to this node (if it is a * leaf node) or its children. If this node is a leaf node and the added * points push this node beyond its capacity, it is partitioned as * needed after all points have been added.</p> * * <p>This method defers partitioning of child nodes until all points * have been added.</p> * * @param points * the collection of points to add to this node or its * children * * @return {@code true} if this node or its children were modified or * {@code false} otherwise */ public boolean addAll(Collection<? extends T> points) { HashSet<VPNode<T>> nodesToPartition = new HashSet<VPNode<T>>(); for(T point : points) { this.add(point, true, nodesToPartition); } // Resolve all of the deferred partitioning for(VPNode<T> node : nodesToPartition) { try { node.partition(); } catch(PartitionException e) { // Nothing to do here; this just means some nodes are bigger // than they want to be. } } // The tree was definitely modified as long as we were given a // non-empty collection of points to add. return !points.isEmpty(); } /** * Adds a point to this node if it is a leaf node or one of its children * if not. If the node that ultimately holds the new point is loaded * beyond its capacity, it will be partitioned. * * @param point * the point to add to this node or one of its children * * @return {@code true} if this node or one of its children was modified * by the addition of this point or {@code false} otherwise */ public boolean add(T point) { return this.add(point, false, null); } /** * <p>Adds a point to this node if it is a leaf node or one of its * children if not. If the node that ultimately holds the new point is * loaded beyond its capacity, it will be partitioned.</p> * * <p>Partitioning may optionally be deferred, in which case it is the * responsibility of the caller to partition overloaded nodes.</p> * * @param point * the point to add to this node or one of its children * @param deferPartitioning * if {@code true}, defer partitioning of overloaded nodes * until the caller chooses to partition them; if * {@code false}, overloaded nodes are partitioned * immediately * @param nodesToPartition * a {@code Set} that collects overloaded nodes in need of * deferred partitioning; this may be {@code null} if * {@code deferPartitioning} is {@code false}; callers must * use this set to partition nodes later * * @return {@code true} if this node or any of its children were * modified by the addition of the new point or {@code false} * otherwise; note that adding points always results in * modification */ protected boolean add(T point, boolean deferPartitioning, Set<VPNode<T>> nodesToPartition) { if(this.isLeafNode()) { this.points.add(point); // Should we try to repartition? if(this.points.size() > this.binSize) { if(deferPartitioning) { nodesToPartition.add(this); } else { try { this.partition(); } catch(PartitionException e) { // Nothing to do here; just hold on to all of our // points. } } } } else { if(this.center.getDistanceTo(point) <= this.threshold) { return this.closer.add(point); } else { return this.farther.add(point); } } // There's no way to add a point and not modify the tree. return true; } /** * Tests whether this node or one of its children contains the given * point. * * @param point * the point whose presence is to be tested * * @return {@code true} if the given point is present in this node or * one of its children or {@code false} otherwise */ public boolean contains(T point) { if(this.isLeafNode()) { return this.points.contains(point); } else { if(this.center.getDistanceTo(point) <= this.threshold) { return this.closer.contains(point); } else { return this.farther.contains(point); } } } /** * Returns the number of points contained in this node and its child * nodes. * * @return the number of points in this node and its children */ public int size() { if(this.isLeafNode()) { return this.points.size(); } else { return this.closer.size() + this.farther.size(); } } /** * Stores a subset of an array of points in this node directly, making * this node a leaf node. * * @param points * the array of points from which to store a subset * @param fromIndex * the starting index (inclusive) of the subset of the array * to store * @param toIndex * the end index (exclusive) of the subset of the array to * store */ private void storePoints(T[] points, int fromIndex, int toIndex) { this.points = new Vector<T>(this.binSize); for(int i = fromIndex; i < toIndex; i++) { this.points.add(points[i]); } // Always choose a center point if we don't already have one if(this.center == null && !this.points.isEmpty()) { this.center = new CachingGeospatialPoint(this.points.get(0)); } this.closer = null; this.farther = null; } /** * Returns a collection of all the points stored directly in this node. * * @return a collection of all the points stored directly in this node * * @throws IllegalStateException if this node is not a leaf node */ public Collection<T> getPoints() { if(!this.isLeafNode()) { throw new IllegalStateException("Cannot retrieve points from a non-leaf node."); } return new Vector<T>(this.points); } /** * Attempts to partition the points contained in this node into two * child nodes. Partitioning this node may trigger recursive * partitioning attempts in the generated child nodes. * * @throws PartitionException * if this node is node a leaf node, if this node is empty, * or if no viable distance threshold could be found (i.e. * all points in this node have the same distance from the * node's center) */ public void partition() throws PartitionException { if(!this.isLeafNode()) { throw new PartitionException("Cannot partition a non-leaf node."); } if(!this.isEmpty()) { @SuppressWarnings("unchecked") T[] pointArray = this.points.toArray((T[])Array.newInstance(points.iterator().next().getClass(), 0)); this.partition(pointArray, 0, pointArray.length); } else { throw new PartitionException("Cannot partition an empty node."); } } /** * Attempts to partition the points in a subset of the given array into * two child nodes based on their distance from the center of this node. * This method chooses a center point if none exists and chooses a * distance threshold to use as the criterion for node partitioning. The * threshold is chosen to be as close to the median distance of the * points in the sub-array as possible while still partitioning the * points into two groups. The child nodes generated by this method may * be partitioned recursively. * * @param points * an array from which to partition a subset of points * @param fromIndex * the start index of the sub-array of points to partition * (inclusive) * @param toIndex * the end index of the sub-array of points to partition * (exclusive) * * @throws PartitionException * if the range specified by {@code fromIndex} and * {@code toIndex} includes fewer than two points or if no * viable distance threshold could be found (i.e. all of the * points in the subarray have the same distance from this * node's center point) */ protected void partition(T[] points, int fromIndex, int toIndex) throws PartitionException { // We can't partition fewer then two points. if(toIndex - fromIndex < 2) { throw new PartitionException("Cannot partition fewer than two points."); } // We start by choosing a center point and a distance threshold; the // median distance from our center to points in our set is a safe // bet. if(this.center == null) { this.center = new CachingGeospatialPoint(points[fromIndex]); } // TODO Consider optimizing this whole approach to partitioning java.util.Arrays.sort(points, fromIndex, toIndex, new GeospatialDistanceComparator<T>(this.center)); int medianIndex = (fromIndex + toIndex - 1) / 2; double medianDistance = this.center.getDistanceTo(points[medianIndex]); // Since we're picking a definite median value from the list, we're // guaranteed to have at least one point that is closer to or EQUAL TO // (via identity) the threshold; what we want to do now is make sure // there's at least one point that's farther away from the center // than the threshold. int partitionIndex = -1; for(int i = medianIndex + 1; i < toIndex; i++) { if(this.center.getDistanceTo(points[i]) > medianDistance) { // We found at least one point farther away than the median // distance. That means we can use the median as our // distance threshold and everything after that point in the // sorted array as members of the "farther" node. partitionIndex = i; this.threshold = medianDistance; break; } } // Did we find a point that's farther away than the median distance? // If so, great! // // If not, we know that all points after the median point in the // sorted array have the same distance from the center, and we need // to try to move the threshold back until we find a point that's // less distant than the median distance. If we find such a point, // we'll use its distance from the center as our distance threshold. // If the median distance is zero, though, and we've made it this // far, we know there's nothing MORE distant than that and shouldn't // spend time searching. if(partitionIndex == -1) { if(medianDistance != 0) { for(int i = medianIndex; i > fromIndex; i--) { if(this.center.getDistanceTo(points[i]) < medianDistance) { partitionIndex = i; this.threshold = this.center.getDistanceTo(points[i]); break; } } // Did we still fail to find anything? There's still one // special case that can save us. If we've made it here, we // know that everything except the center point has the same // non-zero distance from the center. We can and should // still partition by putting the center alone in the // "closer" node and everything else in the "farther" node. // This, of course, assumes there's more than one point to // work with. if(partitionIndex == -1) { partitionIndex = fromIndex + 1; } } } // Still nothing? Bail out. if(partitionIndex == -1) { throw new PartitionException( "No viable partition threshold found (all points have equal distance from center)."); } // Okay! Now actually use that partition index. this.closer = new VPNode<T>(points, fromIndex, partitionIndex, this.binSize); this.farther = new VPNode<T>(points, partitionIndex, toIndex, this.binSize); // We're definitely not a leaf node now, so clear out our internal // point vector (if we had one). this.points = null; } /** * Tests whether this is a leaf node. * * @return {@code true} if this node is a leaf node or {@code false} * otherwise */ public boolean isLeafNode() { return this.closer == null; } /** * Tests whether this node and all of its children are empty. * * @return {@code true} if this node and all of its children contain no * points or {@code false} otherwise */ public boolean isEmpty() { if(this.isLeafNode()) { return this.points.isEmpty(); } else { return (this.closer.isEmpty() && this.farther.isEmpty()); } } /** * Tests whether this node contains more points than its maximum * capacity. * * @return {@code true} if the number of points stored in this node is * greater than its capacity or {@code false} otherwise * * @throws IllegalStateException if this is not a leaf node */ public boolean isOverloaded() { if(!this.isLeafNode()) { throw new IllegalStateException("Non-leaf nodes cannot be overloaded."); } return this.points.size() > this.binSize; } /** * Populates the given search result set with points close to the query * point. If this node is a leaf node, all of its contained points are * "offered" to the search result set as potential nearest neighbors. If * this is not a leaf node, one or both of its children are searched * recursively. * * @param queryPoint the point for which to find nearby neighbors * @param results the result set to which to offer points */ public void getNearestNeighbors(final GeospatialPoint queryPoint, final SearchResults<T> results) { // If this is a leaf node, our job is easy. Offer all of our points // to the result set and bail out. if(this.isLeafNode()) { results.addAll(this.points); } else { // Descend through the tree recursively. boolean searchedCloserFirst; double distanceToCenter = this.center.getDistanceTo(queryPoint); if(distanceToCenter <= this.threshold) { this.closer.getNearestNeighbors(queryPoint, results); searchedCloserFirst = true; } else { this.farther.getNearestNeighbors(queryPoint, results); searchedCloserFirst = false; } // ...and now we're on our way back up. Decide if we need to search // whichever child we didn't search on the way down. if(searchedCloserFirst) { // We've already searched the node that contains points // within our threshold (which also implies that the query // point is inside our threshold); we also want to search // the node beyond our threshold if the distance from the // query point to the most distant match is longer than the // distance from the query point to our threshold, since // there could be a point outside our threshold that's // closer than the most distant match. double distanceToThreshold = this.threshold - distanceToCenter; if(results.getLongestDistanceFromQueryPoint() > distanceToThreshold) { this.farther.getNearestNeighbors(queryPoint, results); } } else { // We've already searched the node that contains points // beyond our threshold, and the query point itself is // beyond our threshold. We want to search the // within-threshold node if it's "easier" to get from the // query point to our region than it is to get from the // query point to the most distant match, since there could // be a point within our threshold that's closer than the // most distant match. double distanceToThreshold = distanceToCenter - this.threshold; if(distanceToThreshold <= results.getLongestDistanceFromQueryPoint()) { this.closer.getNearestNeighbors(queryPoint, results); } } } } /** * Populates the given {@code Vector} with all points within the given * range that match the given search criteria (if any). If this node is * a leaf node, all points contained within the node that are within the * given distance of the query point and match the search criteria are * added to the {@code Vector}. If this node is not a leaf node, its * children are searched recursively. * * @param queryPoint * the point for which to find nearby neighbors * @param maxDistance * the maximum distance within which points should be added * to the result set * @param criteria * the search criteria to apply to potential matches; if * {@code null}, only a point's distance from the query point * is considered when deciding to include it in the result * set * @param results * the {@code Vector} to populate */ public void getAllWithinRange(final CachingGeospatialPoint queryPoint, final double maxDistance, final SearchCriteria<T> criteria, final Vector<T> results) { // If this is a leaf node, just add all of our points to the list if // they fall within range and meet the search criteria (if any). if(this.isLeafNode()) { for(T point : this.points) { if(queryPoint.getDistanceTo(point) <= maxDistance) { if(criteria == null || criteria.matches(point)) { results.add(point); } } } } else { // We want to search whichever of our nodes intersect with the // query region, which remains static throughout an // "all within range" search. double distanceToQueryPoint = this.center.getDistanceTo(queryPoint); // Does any part of the query region fall within our threshold? if(distanceToQueryPoint <= this.threshold + maxDistance) { this.closer.getAllWithinRange(queryPoint, maxDistance, criteria, results); } // Does any part of the query region fall outside of our // threshold? Or, put differently, does our region fail to // completely enclose the query region? if(distanceToQueryPoint + maxDistance > this.threshold) { this.farther.getAllWithinRange(queryPoint, maxDistance, criteria, results); } } } /** * Adds all of the points from this node if it is a leaf node or its * children if it is not to an array. It is the responsibility of the * caller to ensure that the array has sufficient capacity to hold all * of the points in this node and its children. * * @param array * the array to which to add points * * @see VPNode#size() */ public void addPointsToArray(Object[] array) { this.addPointsToArray(array, 0); } /** * Adds all of the points from this node and its children to the given * array starting at the given offset. It is the responsibility of the * caller to ensure that the array has sufficient capacity to hold all * of the points in this node and its children. * * @param array * the array to which to ad points * @param offset * the starting index (inclusive) of the array to begin * adding points * * @return the number of points added to the array */ public int addPointsToArray(Object[] array, int offset) { if(this.isLeafNode()) { if(this.isEmpty()) { return 0; } System.arraycopy(this.points.toArray(), 0, array, offset, this.points.size()); return this.points.size(); } else { int nAddedFromCloser = this.closer.addPointsToArray(array, offset); int nAddedFromFarther = this.farther.addPointsToArray(array, offset + nAddedFromCloser); return nAddedFromCloser + nAddedFromFarther; } } /** * Finds the node at or below this node that contains (or would contain) * the given point. The given stack is populated with each node on the * path to the leaf node that contains the given point. * * @param p * the point for which to find the containing node * @param stack * the stack to populate with the chain of nodes leading to * the leaf node that contains or would contain the given * point */ public void findNodeContainingPoint(final GeospatialPoint p, final Deque<VPNode<T>> stack) { // First things first; add ourselves to the stack. stack.push(this); // If this is a leaf node, we don't need to do anything else. If // it's not a leaf node, recurse! if(!this.isLeafNode()) { if(this.center.getDistanceTo(p) <= this.threshold) { this.closer.findNodeContainingPoint(p, stack); } else { this.farther.findNodeContainingPoint(p, stack); } } } /** * Removes a point from this node's internal list of points. * * @param point * the point to remove from this node * * @return {@code true} if the point was removed from this node (i.e. * this node actually contained the given point) or * {@code false} otherwise * * @throws IllegalStateException if this node is not a leaf node */ public boolean remove(T point) { if(this.isLeafNode()) { return this.points.remove(point); } else { throw new IllegalStateException("Cannot remove points from a non-leaf node."); } } /** * Recursively absorbs the points contained in this node's children into * this node, making this node a leaf node in the process. * * @throws IllegalStateException * if this node is a leaf node (and thus has no children) */ public void absorbChildren() { if(this.isLeafNode()) { throw new IllegalStateException("Leaf nodes have no children."); } this.points = new Vector<T>(this.binSize); if(!this.closer.isLeafNode()) { this.closer.absorbChildren(); } if(!this.farther.isLeafNode()) { this.farther.absorbChildren(); } this.points.addAll(this.closer.getPoints()); this.points.addAll(this.farther.getPoints()); this.closer = null; this.farther = null; } /** * Populates the given {@code List} with all of the leaf nodes that are * descendants of this node. * * @param leafNodes the list to populate with leaf nodes */ public void gatherLeafNodes(List<VPNode<T>> leafNodes) { if(this.isLeafNode()) { leafNodes.add(this); } else { this.closer.gatherLeafNodes(leafNodes); this.farther.gatherLeafNodes(leafNodes); } } /** * Tests whether this node is an ancestor of the given node. * * @param node * the node for which to test ancestry * * @return {@code true} if the given node is a descendant of this node * or {@code false} otherwise */ public boolean isAncestorOfNode(VPNode<T> node) { // Obviously, leaf nodes can't be the ancestors of anything if(this.isLeafNode()) { return false; } // Find a path to the center of the node we've been given ArrayDeque<VPNode<T>> stack = new ArrayDeque<VPNode<T>>(); this.findNodeContainingPoint(node.getCenter(), stack); // We're an ancestor if we appear anywhere in the path to the given // node return stack.contains(this); } } public static final int DEFAULT_BIN_SIZE = 32; private final int binSize; private VPNode<E> root; /** * Constructs a new, empty vp-tree with a default node capacity. */ public VPTree() { this(DEFAULT_BIN_SIZE); } /** * Constructs a new, empty vp-tree with the specified node capacity. * * @param nodeCapacity * the maximum number of points to store in a leaf node of the * tree */ public VPTree(int nodeCapacity) { if(nodeCapacity < 1) { throw new IllegalArgumentException("Node capacity must be greater than zero."); } this.binSize = nodeCapacity; this.root = new VPNode<E>(this.binSize); } /** * Constructs a new vp-tree that contains (and indexes) all of the points in * the given collection. Nodes of the tree are created with a default * capacity. * * @param points * the points to use to populate this tree */ public VPTree(Collection<E> points) { this(points, DEFAULT_BIN_SIZE); } /** * Constructs a new vp-tree that contains (and indexes) all of the points in * the given collection and has leaf nodes with the given point capacity. * * @param points * the points to use to populate this tree * @param nodeCapacity * the largest number of points any leaf node of the tree should * contain */ public VPTree(Collection<E> points, int nodeCapacity) { if(nodeCapacity < 1) { throw new IllegalArgumentException("Node capacity must be greater than zero."); } this.binSize = nodeCapacity; if(!points.isEmpty()) { @SuppressWarnings("unchecked") E[] pointArray = points.toArray((E[])Array.newInstance(points.iterator().next().getClass(), 0)); this.root = new VPNode<E>(pointArray, 0, pointArray.length, this.binSize); } else { this.root = new VPNode<E>(this.binSize); } } /** * Returns a reference to this tree's root node. This method is intended for * testing purposes only. * * @return a reference to this tree's root node */ protected VPNode<E> getRoot() { return this.root; } /** * Returns the maximum number of points any leaf node of this tree should * contain. * * @return the maximum number of points any leaf node should contain */ public int getBinSize() { return this.binSize; } /** * Adds a single point to this vp-tree. Addition of a point executes in * O(log n) time in the best case (where n is the number of points in the * tree), but may also trigger a node partition that takes additional time. * * @param point * the point to add to this tree * * @return {@code true} if the tree was modified by the addition of this * point; vp-trees are always modified by adding points, so this * method always returns true */ @Override public boolean add(E point) { return this.root.add(point); } /** * Adds all of the points in the given collection to this vp-tree. * * @param points the points to add to this tree * * @return {@code true} if the tree was modified by the addition of the * points; vp-trees are always modified by adding points, so this * method always returns true */ @Override public boolean addAll(Collection<? extends E> points) { return this.root.addAll(points); } /** * Removes all points from this vp-tree. Clearing a vp-tree executes in O(1) * time. */ @Override public void clear() { this.root = new VPNode<E>(this.binSize); } /** * Tests whether this vp-tree contains the given point. Membership tests * execute in O(log n) time, where n is the number of points in the tree. * * @param o * the object to test for membership in this tree * * @return {@code true} if this tree contains the given point or * {@code false} otherwise */ @SuppressWarnings("unchecked") @Override public boolean contains(Object o) { try { return this.root.contains((E)o); } catch(ClassCastException e) { return false; } } /** * Tests whether this vp-tree contains all of the points in the given * collection. Group membership tests execute in O(m log n) time, where m is * the number of points in the given collection and n is the number of * points in the tree. * * @param c * the collection of points to test for membership in this tree * * @return {@code true} if this tree contains all of the members of the * given collection or {@code false} otherwise */ @Override public boolean containsAll(Collection<?> c) { for(Object o : c) { if(!this.contains(o)) { return false; } } return true; } /** * Tests whether this tree is empty. * * @return {@code true} if this tree contains no points or {@code false} * otherwise */ @Override public boolean isEmpty() { return this.root.isEmpty(); } /** * Returns an @{code Iterator} over all of the points contained in this * tree. The order of iteration is not defined, and the @{code Iterator} * returned by this method does not support the optional @{code remove} * method. The behavior of the returned {@code Iterator} is not defined if * the tree is modified after the {@code Iterator} is returned. * * @return an {@code Iterator} over the points contained in this tree */ @Override public Iterator<E> iterator() { return new TreeIterator<E>(this.root); } /** * Removes a point from this tree. * * @param o * the point to remove * * @return {@code true} if the tree was modified by removing this point * (i.e. if the point was present in the tree) or {@code false} * otherwise */ @Override public boolean remove(Object o) { try { @SuppressWarnings("unchecked") E point = (E)o; return this.remove(point, false, null); } catch(ClassCastException e) { // The object we were given wasn't the kind of thing we're storing, // so we definitely can't remove it. return false; } } /** * Removes a point from this tree and optionally defers pruning of nodes * left empty after the removal of their last point. If pruning is deferred, * it is the responsibility of the caller to prune nodes after this method * has executed. * * @param point * the point to remove * @param deferPruning * if {@code true} and the removal of the given point would leave * a node empty, pruning of the empty node is deferred until a * time chosen by the caller; otherwise, empty nodes are pruned * immediately * @param nodesToPrune * a @{code Set} to be populated with nodes left empty by the * removal of points; this may be {@code null} if * {@code deferPruning} if {@code false} * * @return {@code true} if the tree was modified by removing this point * (i.e. if the point was present in the tree) or {@code false} * otherwise */ protected boolean remove(E point, boolean deferPruning, Set<VPNode<E>> nodesToPrune) { ArrayDeque<VPNode<E>> stack = new ArrayDeque<VPNode<E>>(); this.root.findNodeContainingPoint(point, stack); VPNode<E> node = stack.pop(); boolean pointRemoved = node.remove(point); if(node.isEmpty()) { if(deferPruning) { nodesToPrune.add(node); } else { this.pruneEmptyNode(node); } } return pointRemoved; } /** * Removes all of the points in the given collection from this tree. * * @param c * the collection of points to remove from this true * * @return {@code true} if the tree was modified by removing the given * points (i.e. if any of the points were present in the tree) or * {@code false} otherwise */ @Override public boolean removeAll(Collection<?> c) { boolean anyChanged = false; HashSet<VPNode<E>> nodesToPrune = new HashSet<VPNode<E>>(); for(Object o : c) { try { @SuppressWarnings("unchecked") E point = (E)o; // The behavioral contact for Collections states, "After this // call returns, this collection will contain no elements in // common with the specified collection." Make sure we remove // all instances of each point in the collection of points to // remove. while(this.remove(point, true, nodesToPrune)) { anyChanged = true; } } catch(ClassCastException e) { // The object wasn't the kind of point we have in this tree; // just keep moving. } } // Avoid duplicating work by removing pruning targets that are children // of other pruning targets (since they would be implicitly pruned by // pruning the parent). HashSet<VPNode<E>> nodesToNotPrune = new HashSet<VPNode<E>>(); for(VPNode<E> node : nodesToPrune) { for(VPNode<E> potentialAncestor : nodesToPrune) { if(potentialAncestor.isAncestorOfNode(node)) { nodesToNotPrune.add(node); } } } nodesToPrune.removeAll(nodesToNotPrune); // Now the set of nodes to prune contains only the highest nodes in any // branch; prune (and potentially repartition) each of those // individually. for(VPNode<E> node : nodesToPrune) { this.pruneEmptyNode(node); if(node.isOverloaded()) { try { node.partition(); } catch(PartitionException e) { // These things happen. } } } return anyChanged; } /** * <p>"Prunes" an empty leaf node from the tree. When a node is pruned, its * parent absorbs the points from both of its child nodes (though only one * may actually contain points) and discards its child nodes. If the parent * node is empty after the absorption of its child nodes, it is also pruned; * this process continues until either an ancestor of the original node is * non-empty after absorbing its children or until the root of the tree is * reached.</p> * * <p>The pruning process may leave an ancestor node overly-full, in which * case it is the responsibility of the caller to repartition that node.</p> * * @param node the empty node to prune from the tree */ protected void pruneEmptyNode(VPNode<E> node) { // Only spend time working on this if the node is actually empty; it's // harmless to call this method on a non-empty node, though. if(node.isEmpty() && node != this.root) { ArrayDeque<VPNode<E>> stack = new ArrayDeque<VPNode<E>>(); this.root.findNodeContainingPoint(node.getCenter(), stack); // Immediately pop the first node off the stack (since we know it's // the empty leaf node we were handed as an argument). stack.pop(); // Work through the stack until we either have a non-empty parent or // we hit the root of the tree. while(stack.peek() != null) { VPNode<E> parent = stack.pop(); parent.absorbChildren(); // We're done as soon as we have a non-empty parent. if(!parent.isEmpty()) { break; } } } } /** * Retains only the points in this vp-tree that are contained in the * specified collection. In other words, removes from this tree all of its * points that are not contained in the specified collection. * * @param c * collection containing elements to be retained in this tree * * @return {@code true} if this tree was modified by calling this method or * {@code false} otherwise */ @Override public boolean retainAll(Collection<?> c) { // We need to build up a list of points to remove after the initial // search to avoid concurrent modification woes Vector<E> pointsToRemove = new Vector<E>(); for(E point : this) { if(!c.contains(point)) { pointsToRemove.add(point); } } return this.removeAll(pointsToRemove); } /** * Returns the total number of points stored in this vp-tree. * * @return the number of points stored in this vp-tree */ @Override public int size() { return this.root.size(); } /** * Returns an array containing all of the points in this vp-tree. The order * of the points in the array is not defined. * * @return an array containing all of the points in this vp-tree */ @Override public Object[] toArray() { Object[] array = new Object[this.size()]; this.root.addPointsToArray(array); return array; } /** * <p>Returns an array containing all of the points in this vp-tree; the * runtime type of the returned array is that of the specified array. If the * collection fits in the specified array, it is returned therein. * Otherwise, a new array is allocated with the runtime type of the * specified array and the size of this collection.</p> * * <p>If all of the points in this tree fit in the specified array with room * to spare (i.e., the array has more elements than this vp-tree), the * element in the array immediately following the end of the collection is * set to {@code null}.</p> * * @param a * the array into which the elements of this tree are to be * stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose * * @return an array containing all of the points in this vp-tree */ @SuppressWarnings("unchecked") @Override public <T> T[] toArray(T[] a) { int size = this.size(); if(a.length < this.size()) { return (T[])java.util.Arrays.copyOf(this.toArray(), size, a.getClass()); } else { System.arraycopy(this.toArray(), 0, a, 0, size); if(a.length > size) { a[size] = null; } return a; } } /* * (non-Javadoc) * @see com.eatthepath.jeospatial.GeospatialPointDatabase#getNearestNeighbors(com.eatthepath.jeospatial.GeospatialPoint, int) */ @Override public List<E> getNearestNeighbors(GeospatialPoint queryPoint, int maxResults) { SearchResults<E> results = new SearchResults<E>(queryPoint, maxResults); this.root.getNearestNeighbors(queryPoint, results); return results.toSortedList(); } /* * (non-Javadoc) * @see com.eatthepath.jeospatial.GeospatialPointDatabase#getNearestNeighbors(com.eatthepath.jeospatial.GeospatialPoint, int, double) */ @Override public List<E> getNearestNeighbors(GeospatialPoint queryPoint, int maxResults, double maxDistance) { SearchResults<E> results = new SearchResults<E>(queryPoint, maxResults, maxDistance); this.root.getNearestNeighbors(queryPoint, results); return results.toSortedList(); } /* * (non-Javadoc) * @see com.eatthepath.jeospatial.GeospatialPointDatabase#getNearestNeighbors(com.eatthepath.jeospatial.GeospatialPoint, int, com.eatthepath.jeospatial.SearchCriteria) */ @Override public List<E> getNearestNeighbors(GeospatialPoint queryPoint, int maxResults, SearchCriteria<E> searchCriteria) { SearchResults<E> results = new SearchResults<E>(queryPoint, maxResults, searchCriteria); this.root.getNearestNeighbors(queryPoint, results); return results.toSortedList(); } /* * (non-Javadoc) * @see com.eatthepath.jeospatial.GeospatialPointDatabase#getNearestNeighbors(com.eatthepath.jeospatial.GeospatialPoint, int, double, com.eatthepath.jeospatial.SearchCriteria) */ @Override public List<E> getNearestNeighbors(GeospatialPoint queryPoint, int maxResults, double maxDistance, SearchCriteria<E> searchCriteria) { SearchResults<E> results = new SearchResults<E>(queryPoint, maxResults, maxDistance, searchCriteria); this.root.getNearestNeighbors(queryPoint, results); return results.toSortedList(); } /* * (non-Javadoc) * @see com.eatthepath.jeospatial.GeospatialPointDatabase#getAllNeighborsWithinDistance(com.eatthepath.jeospatial.GeospatialPoint, double) */ @Override public List<E> getAllNeighborsWithinDistance(GeospatialPoint queryPoint, double maxDistance) { return this.getAllNeighborsWithinDistance(queryPoint, maxDistance, null); } /* * (non-Javadoc) * @see com.eatthepath.jeospatial.GeospatialPointDatabase#getAllNeighborsWithinDistance(com.eatthepath.jeospatial.GeospatialPoint, double, com.eatthepath.jeospatial.SearchCriteria) */ @Override public List<E> getAllNeighborsWithinDistance(GeospatialPoint queryPoint, double maxDistance, SearchCriteria<E> searchCriteria) { Vector<E> results = new Vector<E>(this.binSize); this.root.getAllWithinRange(new CachingGeospatialPoint(queryPoint), maxDistance, searchCriteria, results); java.util.Collections.sort(results, new GeospatialDistanceComparator<E>(queryPoint)); return results; } /* * (non-Javadoc) * @see com.eatthepath.jeospatial.GeospatialPointDatabase#getNearestNeighbor(com.eatthepath.jeospatial.GeospatialPoint) */ @Override public E getNearestNeighbor(GeospatialPoint queryPoint) { SearchResults<E> results = new SearchResults<E>(queryPoint, 1); this.root.getNearestNeighbors(queryPoint, results); return results.peek(); } /* * (non-Javadoc) * @see com.eatthepath.jeospatial.GeospatialPointDatabase#getNearestNeighbor(com.eatthepath.jeospatial.GeospatialPoint, double) */ @Override public E getNearestNeighbor(GeospatialPoint queryPoint, double maxDistance) { SearchResults<E> results = new SearchResults<E>(queryPoint, 1, maxDistance); this.root.getNearestNeighbors(queryPoint, results); return results.peek(); } /* * (non-Javadoc) * @see com.eatthepath.jeospatial.GeospatialPointDatabase#getNearestNeighbor(com.eatthepath.jeospatial.GeospatialPoint, com.eatthepath.jeospatial.SearchCriteria) */ @Override public E getNearestNeighbor(GeospatialPoint queryPoint, SearchCriteria<E> searchCriteria) { SearchResults<E> results = new SearchResults<E>(queryPoint, 1, searchCriteria); this.root.getNearestNeighbors(queryPoint, results); return results.peek(); } /* * (non-Javadoc) * @see com.eatthepath.jeospatial.GeospatialPointDatabase#getNearestNeighbor(com.eatthepath.jeospatial.GeospatialPoint, double, com.eatthepath.jeospatial.SearchCriteria) */ @Override public E getNearestNeighbor(GeospatialPoint queryPoint, double maxDistance, SearchCriteria<E> searchCriteria) { SearchResults<E> results = new SearchResults<E>(queryPoint, 1, maxDistance, searchCriteria); this.root.getNearestNeighbors(queryPoint, results); return results.peek(); } /* * (non-Javadoc) * @see com.eatthepath.jeospatial.GeospatialPointDatabase#movePoint(com.eatthepath.jeospatial.GeospatialPoint, double, double) */ @Override public void movePoint(E point, double latitude, double longitude) { this.movePoint(point, new SimpleGeospatialPoint(latitude, longitude)); } /* * (non-Javadoc) * @see com.eatthepath.jeospatial.GeospatialPointDatabase#movePoint(com.eatthepath.jeospatial.GeospatialPoint, com.eatthepath.jeospatial.GeospatialPoint) */ @Override public void movePoint(E point, GeospatialPoint destination) { // Moving points can trigger significant structural changes to a // tree. If a point's departure from a node would leave that node // empty, its parent needs to gather the nodes from its children and // potentially repartition itself. If the point's arrival in a node // would push that node over the bin size threshold, the node might // need to be partitioned. We want to avoid the case where we'd move // the point out of a node, regroup things in the parent, and then // put the node right back in the same place, so we do some work in // advance to see if the old and new positions would fall into the // same tree node. ArrayDeque<VPNode<E>> sourcePath = new ArrayDeque<VPNode<E>>(); ArrayDeque<VPNode<E>> destinationPath = new ArrayDeque<VPNode<E>>(); this.root.findNodeContainingPoint(point, sourcePath); this.root.findNodeContainingPoint(destination, destinationPath); if(sourcePath.equals(destinationPath)) { // Easy! We expect no structural changes, so we can modify the // point directly and immediately. point.setLatitude(destination.getLatitude()); point.setLongitude(destination.getLongitude()); } else { // We don't know that moving the point will cause structural // changes, but we have to assume it will. this.remove(point); point.setLatitude(destination.getLatitude()); point.setLongitude(destination.getLongitude()); this.add(point); } } }
Added docs for public constants.
src/com/eatthepath/jeospatial/vptree/VPTree.java
Added docs for public constants.
<ide><path>rc/com/eatthepath/jeospatial/vptree/VPTree.java <ide> * <p>The default node capacity for a vp-tree is {@value DEFAULT_BIN_SIZE} <ide> * points.</p> <ide> * <add> * <p>Note that the {@code VPTree} class is <strong>not</strong> thread-safe; <add> * because they forego any kind of synchronization or locking, {@code VPTree} <add> * instances can achieve slightly higher search throughput than their <add> * thread-safe counterparts. This makes the {@code VPTree} class a good choice <add> * for single-threaded applications or applications where the tree will not be <add> * modified after construction. For a thread-safe alternative, use the <add> * {@link LockingVPTree} class.</p> <add> * <ide> * @author <a href="mailto:[email protected]">Jon Chambers</a> <ide> * <ide> * @see <a href="http://pnylab.com/pny/papers/vptree/main.html">Yianilos, Peter <ide> } <ide> } <ide> <add> /** <add> * The default node capacity ({@value} points) for nodes in this tree. <add> */ <ide> public static final int DEFAULT_BIN_SIZE = 32; <add> <ide> private final int binSize; <ide> <ide> private VPNode<E> root;
Java
epl-1.0
56e627747e2d4fe398fd8504abbd9303ca4e1fc6
0
sebasbaumh/portfolio,buchen/portfolio,buchen/portfolio,sebasbaumh/portfolio,sebasbaumh/portfolio,buchen/portfolio,buchen/portfolio,sebasbaumh/portfolio
package name.abuchen.portfolio.online.impl; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.MessageFormat; import java.text.ParseException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Scanner; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.regex.Pattern; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import name.abuchen.portfolio.Messages; import name.abuchen.portfolio.model.Exchange; import name.abuchen.portfolio.model.LatestSecurityPrice; import name.abuchen.portfolio.model.Security; import name.abuchen.portfolio.model.SecurityPrice; import name.abuchen.portfolio.money.Values; import name.abuchen.portfolio.online.QuoteFeed; import name.abuchen.portfolio.online.impl.variableurl.Factory; import name.abuchen.portfolio.online.impl.variableurl.urls.VariableURL; import name.abuchen.portfolio.util.TextUtil; public class HTMLTableQuoteFeed implements QuoteFeed { protected abstract static class Column { static final ThreadLocal<DecimalFormat> DECIMAL_FORMAT_GERMAN = new ThreadLocal<DecimalFormat>() { @Override protected DecimalFormat initialValue() { return new DecimalFormat("#,##0.###", new DecimalFormatSymbols(Locale.GERMAN)); //$NON-NLS-1$ } }; static final ThreadLocal<DecimalFormat> DECIMAL_FORMAT_ENGLISH = new ThreadLocal<DecimalFormat>() { @Override protected DecimalFormat initialValue() { return new DecimalFormat("#,##0.###", new DecimalFormatSymbols(Locale.ENGLISH)); //$NON-NLS-1$ } }; static final ThreadLocal<DecimalFormat> DECIMAL_FORMAT_APOSTROPHE = new ThreadLocal<DecimalFormat>() { @Override protected DecimalFormat initialValue() { DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols(Locale.US); unusualSymbols.setGroupingSeparator('\''); return new DecimalFormat("#,##0.##", unusualSymbols); //$NON-NLS-1$ } }; private final Pattern[] patterns; protected Column(String[] strings) { this.patterns = new Pattern[strings.length]; for (int ii = 0; ii < strings.length; ii++) this.patterns[ii] = Pattern.compile(strings[ii]); } protected boolean matches(Element header) { String text = TextUtil.strip(header.text()); for (Pattern pattern : patterns) { if (pattern.matcher(text).matches()) return true; } return false; } abstract void setValue(Element value, LatestSecurityPrice price, String languageHint) throws ParseException; protected long asQuote(Element value, String languageHint) throws ParseException { String text = value.text().trim(); DecimalFormat format = null; if ("de".equals(languageHint)) //$NON-NLS-1$ format = DECIMAL_FORMAT_GERMAN.get(); else if ("en".equals(languageHint)) //$NON-NLS-1$ format = DECIMAL_FORMAT_ENGLISH.get(); if (format == null) { // check first for apostrophe int apostrophe = text.indexOf('\''); if (apostrophe >= 0) format = DECIMAL_FORMAT_APOSTROPHE.get(); } if (format == null) { // determine format based on the relative location of the last // comma and dot, e.g. the last comma indicates a German number // format int lastDot = text.lastIndexOf('.'); int lastComma = text.lastIndexOf(','); format = Math.max(lastDot, lastComma) == lastComma ? DECIMAL_FORMAT_GERMAN.get() : DECIMAL_FORMAT_ENGLISH.get(); } double quote = format.parse(text).doubleValue(); return Math.round(quote * Values.Quote.factor()); } } protected static class DateColumn extends Column { private DateTimeFormatter[] formatters; @SuppressWarnings("nls") public DateColumn() { this(new String[] { "Datum.*", "Date.*" }); } @SuppressWarnings("nls") public DateColumn(String[] patterns) { super(patterns); formatters = new DateTimeFormatter[] { DateTimeFormatter.ofPattern("y-M-d"), DateTimeFormatter.ofPattern("d.M.yy"), //$NON-NLS-1$ DateTimeFormatter.ofPattern("d.M.y"), //$NON-NLS-1$ DateTimeFormatter.ofPattern("d. MMM y"), //$NON-NLS-1$ DateTimeFormatter.ofPattern("d. MMMM y"), //$NON-NLS-1$ DateTimeFormatter.ofPattern("d. MMM. y"), //$NON-NLS-1$ DateTimeFormatter.ofPattern("MMM d, y", Locale.ENGLISH), //$NON-NLS-1$ DateTimeFormatter.ofPattern("MMM dd, y", Locale.ENGLISH), //$NON-NLS-1$ DateTimeFormatter.ofPattern("EEEE, MMMM dd, yEEE, MMM dd, y", Locale.ENGLISH) //$NON-NLS-1$ }; } @Override void setValue(Element value, LatestSecurityPrice price, String languageHint) throws ParseException { String text = TextUtil.strip(value.text()); for (int ii = 0; ii < formatters.length; ii++) { try { LocalDate date = LocalDate.parse(text, formatters[ii]); price.setDate(date); return; } catch (DateTimeParseException e) // NOSONAR { // continue with next pattern } } throw new ParseException(text, 0); } } protected static class CloseColumn extends Column { @SuppressWarnings("nls") public CloseColumn() { super(new String[] { "Schluss.*", "Schluß.*", "Rücknahmepreis.*", "Close.*", "Zuletzt", "Price", "akt. Kurs" }); } public CloseColumn(String[] patterns) { super(patterns); } @Override void setValue(Element value, LatestSecurityPrice price, String languageHint) throws ParseException { price.setValue(asQuote(value, languageHint)); } } protected static class HighColumn extends Column { @SuppressWarnings("nls") public HighColumn() { super(new String[] { "Hoch.*", "Tageshoch.*", "Max.*", "High.*" }); } public HighColumn(String[] patterns) { super(patterns); } @Override void setValue(Element value, LatestSecurityPrice price, String languageHint) throws ParseException { if ("-".equals(value.text().trim())) //$NON-NLS-1$ price.setHigh(LatestSecurityPrice.NOT_AVAILABLE); else price.setHigh(asQuote(value, languageHint)); } } protected static class LowColumn extends Column { @SuppressWarnings("nls") public LowColumn() { super(new String[] { "Tief.*", "Tagestief.*", "Low.*" }); } public LowColumn(String[] patterns) { super(patterns); } @Override void setValue(Element value, LatestSecurityPrice price, String languageHint) throws ParseException { if ("-".equals(value.text().trim())) //$NON-NLS-1$ price.setLow(LatestSecurityPrice.NOT_AVAILABLE); else price.setLow(asQuote(value, languageHint)); } } private static class Spec { private final Column column; private final int index; public Spec(Column column, int index) { this.column = column; this.index = index; } } private static class HeaderInfo { private final int rowIndex; private final int numberOfHeaderColumns; public HeaderInfo(int rowIndex, int numberOfHeaderColumns) { this.rowIndex = rowIndex; this.numberOfHeaderColumns = numberOfHeaderColumns; } } public static final String ID = "GENERIC_HTML_TABLE"; //$NON-NLS-1$ private static final Column[] COLUMNS = new Column[] { new DateColumn(), new CloseColumn(), new HighColumn(), new LowColumn() }; private final PageCache cache = new PageCache(); @Override public String getId() { return ID; } @Override public String getName() { return Messages.LabelHTMLTable; } @Override public boolean updateLatestQuotes(Security security, List<Exception> errors) { boolean isUpdated = false; // if latestFeed is null, then the policy is 'use same configuration // as historic quotes' String feedURL = security.getLatestFeed() == null ? security.getFeedURL() : security.getLatestFeedURL(); List<LatestSecurityPrice> quotes = internalGetQuotes(security, feedURL, errors); int size = quotes.size(); if (size > 0) { Collections.sort(quotes); LatestSecurityPrice latest = quotes.get(size - 1); LatestSecurityPrice previous = size > 1 ? quotes.get(size - 2) : null; latest.setPreviousClose(previous != null ? previous.getValue() : latest.getValue()); latest.setVolume(LatestSecurityPrice.NOT_AVAILABLE); isUpdated = security.setLatest(latest); } return isUpdated; } @Override public boolean updateHistoricalQuotes(Security security, List<Exception> errors) { List<LatestSecurityPrice> quotes = internalGetQuotes(security, security.getFeedURL(), errors); boolean isUpdated = false; for (LatestSecurityPrice quote : quotes) { boolean isAdded = security.addPrice(new SecurityPrice(quote.getDate(), quote.getValue())); isUpdated = isUpdated || isAdded; } return isUpdated; } @Override public List<LatestSecurityPrice> getHistoricalQuotes(Security security, LocalDate start, List<Exception> errors) { return internalGetQuotes(security, security.getFeedURL(), errors); } private List<LatestSecurityPrice> internalGetQuotes(Security security, String feedURL, List<Exception> errors) { if (feedURL == null || feedURL.length() == 0) { errors.add(new IOException(MessageFormat.format(Messages.MsgMissingFeedURL, security.getName()))); return Collections.emptyList(); } VariableURL variableURL = Factory.fromString(feedURL); variableURL.setSecurity(security); SortedSet<LatestSecurityPrice> newPricesByDate = new TreeSet<>(new SecurityPrice.ByDate()); long failedAttempts = 0; long maxFailedAttempts = variableURL.getMaxFailedAttempts(); for (String url : variableURL) { List<LatestSecurityPrice> answer = cache.lookup(url); if (answer == null) { answer = parseFromURL(url, errors); if (!answer.isEmpty()) cache.put(url, answer); } int sizeBefore = newPricesByDate.size(); newPricesByDate.addAll(answer); if (newPricesByDate.size() > sizeBefore) failedAttempts = 0; else if (++failedAttempts > maxFailedAttempts) break; } return new ArrayList<>(newPricesByDate); } @Override public List<LatestSecurityPrice> getHistoricalQuotes(String response, List<Exception> errors) { return parseFromHTML(response, errors); } @Override public List<Exchange> getExchanges(Security subject, List<Exception> errors) { return Collections.emptyList(); } protected List<LatestSecurityPrice> parseFromURL(String url, List<Exception> errors) { try { String escapedUrl = new URI(url).toASCIIString(); return parse(escapedUrl, Jsoup.connect(escapedUrl).userAgent(OnlineHelper.getUserAgent()).timeout(30000).get(), errors); } catch (URISyntaxException | IOException e) { errors.add(new IOException(url + '\n' + e.getMessage(), e)); return Collections.emptyList(); } } protected List<LatestSecurityPrice> parseFromHTML(String html, List<Exception> errors) { return parse("n/a", Jsoup.parse(html), errors); //$NON-NLS-1$ } private List<LatestSecurityPrice> parse(String url, Document document, List<Exception> errors) { // check if language is provided String language = document.select("html").attr("lang"); //$NON-NLS-1$ //$NON-NLS-2$ List<LatestSecurityPrice> prices = new ArrayList<>(); // first: find tables Elements tables = document.getElementsByTag("table"); //$NON-NLS-1$ for (Element table : tables) { List<Spec> specs = new ArrayList<>(); HeaderInfo headerInfo = buildSpecFromTable(table, specs); int rowIndex = headerInfo.rowIndex; if (isSpecValid(specs)) { Elements rows = table.select("> tbody > tr"); //$NON-NLS-1$ int size = rows.size(); for (; rowIndex < size; rowIndex++) { Element row = rows.get(rowIndex); try { LatestSecurityPrice price = extractPrice(row, specs, language, headerInfo.numberOfHeaderColumns); if (price != null) prices.add(price); } catch (Exception e) { errors.add(new IOException(url + '\n' + e.getMessage(), e)); } } // skip all other tables break; } } // if no quotes could be extract, log HTML for further analysis if (prices.isEmpty()) errors.add(new IOException(MessageFormat.format(Messages.MsgNoQuotesFoundInHTML, url, document.html()))); return prices; } @SuppressWarnings("nls") private HeaderInfo buildSpecFromTable(Element table, List<Spec> specs) { // check if thead exists Elements header = table.select("> thead > tr > th"); if (!header.isEmpty()) { buildSpecFromRow(header, specs); return new HeaderInfo(0, header.size()); } header = table.select("> thead > tr > td"); if (!header.isEmpty()) { buildSpecFromRow(header, specs); return new HeaderInfo(0, header.size()); } // check if th exist in body header = table.select("> tbody > tr > th"); if (!header.isEmpty()) { buildSpecFromRow(header, specs); return new HeaderInfo(0, header.size()); } // then check first two regular rows int rowIndex = 0; Elements rows = table.select("> tbody > tr"); Elements headerRow = null; if (!rows.isEmpty()) { Element firstRow = rows.get(0); headerRow = firstRow.select("> td"); buildSpecFromRow(headerRow, specs); rowIndex++; } if (specs.isEmpty() && rows.size() > 1) { Element secondRow = rows.get(1); headerRow = secondRow.select("> td"); buildSpecFromRow(headerRow, specs); rowIndex++; } return new HeaderInfo(rowIndex, headerRow != null ? headerRow.size() : 0); } protected Column[] getColumns() { return COLUMNS; } private void buildSpecFromRow(Elements row, List<Spec> specs) { Set<Column> available = new HashSet<>(); for (Column column : getColumns()) available.add(column); for (int ii = 0; ii < row.size(); ii++) { Element element = row.get(ii); for (Column column : available) { if (column.matches(element)) { specs.add(new Spec(column, ii)); available.remove(column); break; } } } } private boolean isSpecValid(List<Spec> specs) { if (specs == null || specs.isEmpty()) return false; boolean hasDate = false; boolean hasClose = false; for (Spec spec : specs) { hasDate = hasDate || spec.column instanceof DateColumn; hasClose = hasClose || spec.column instanceof CloseColumn; } return hasDate && hasClose; } private LatestSecurityPrice extractPrice(Element row, List<Spec> specs, String languageHint, int numberOfHeaderColumns) throws ParseException { Elements cells = row.select("> td"); //$NON-NLS-1$ // we're only looking at rows having the same size as the header row if (cells.size() != numberOfHeaderColumns) return null; LatestSecurityPrice price = new LatestSecurityPrice(); for (Spec spec : specs) spec.column.setValue(cells.get(spec.index), price, languageHint); return price; } /** * Test method to parse HTML tables * * @param args * list of URLs and/or local files */ public static void main(String[] args) throws IOException { PrintWriter writer = new PrintWriter(System.out); // NOSONAR for (String arg : args) if (arg.charAt(0) != '#') doLoad(arg, writer); writer.flush(); } @SuppressWarnings("nls") private static void doLoad(String source, PrintWriter writer) throws IOException { writer.println("--------"); writer.println(source); writer.println("--------"); List<LatestSecurityPrice> prices; List<Exception> errors = new ArrayList<>(); if (source.startsWith("http")) { prices = new HTMLTableQuoteFeed().parseFromURL(source, errors); } else { try (Scanner scanner = new Scanner(new File(source), StandardCharsets.UTF_8.name())) { String html = scanner.useDelimiter("\\A").next(); prices = new HTMLTableQuoteFeed().parseFromHTML(html, errors); } } for (Exception error : errors) error.printStackTrace(writer); // NOSONAR for (LatestSecurityPrice p : prices) { writer.print(Values.Date.format(p.getDate())); writer.print("\t"); writer.print(Values.Quote.format(p.getValue())); writer.print("\t"); writer.print(Values.Quote.format(p.getLow())); writer.print("\t"); writer.println(Values.Quote.format(p.getHigh())); } } }
name.abuchen.portfolio/src/name/abuchen/portfolio/online/impl/HTMLTableQuoteFeed.java
package name.abuchen.portfolio.online.impl; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.MessageFormat; import java.text.ParseException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Scanner; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.regex.Pattern; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import name.abuchen.portfolio.Messages; import name.abuchen.portfolio.model.Exchange; import name.abuchen.portfolio.model.LatestSecurityPrice; import name.abuchen.portfolio.model.Security; import name.abuchen.portfolio.model.SecurityPrice; import name.abuchen.portfolio.money.Values; import name.abuchen.portfolio.online.QuoteFeed; import name.abuchen.portfolio.online.impl.variableurl.Factory; import name.abuchen.portfolio.online.impl.variableurl.urls.VariableURL; import name.abuchen.portfolio.util.TextUtil; public class HTMLTableQuoteFeed implements QuoteFeed { protected abstract static class Column { static final ThreadLocal<DecimalFormat> DECIMAL_FORMAT_GERMAN = new ThreadLocal<DecimalFormat>() { @Override protected DecimalFormat initialValue() { return new DecimalFormat("#,##0.###", new DecimalFormatSymbols(Locale.GERMAN)); //$NON-NLS-1$ } }; static final ThreadLocal<DecimalFormat> DECIMAL_FORMAT_ENGLISH = new ThreadLocal<DecimalFormat>() { @Override protected DecimalFormat initialValue() { return new DecimalFormat("#,##0.###", new DecimalFormatSymbols(Locale.ENGLISH)); //$NON-NLS-1$ } }; static final ThreadLocal<DecimalFormat> DECIMAL_FORMAT_APOSTROPHE = new ThreadLocal<DecimalFormat>() { @Override protected DecimalFormat initialValue() { DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols(Locale.US); unusualSymbols.setGroupingSeparator('\''); return new DecimalFormat("#,##0.##", unusualSymbols); //$NON-NLS-1$ } }; private final Pattern[] patterns; protected Column(String[] strings) { this.patterns = new Pattern[strings.length]; for (int ii = 0; ii < strings.length; ii++) this.patterns[ii] = Pattern.compile(strings[ii]); } protected boolean matches(Element header) { String text = TextUtil.strip(header.text()); for (Pattern pattern : patterns) { if (pattern.matcher(text).matches()) return true; } return false; } abstract void setValue(Element value, LatestSecurityPrice price, String languageHint) throws ParseException; protected long asQuote(Element value, String languageHint) throws ParseException { String text = value.text().trim(); DecimalFormat format = null; if ("de".equals(languageHint)) //$NON-NLS-1$ format = DECIMAL_FORMAT_GERMAN.get(); else if ("en".equals(languageHint)) //$NON-NLS-1$ format = DECIMAL_FORMAT_ENGLISH.get(); if (format == null) { // check first for apostrophe int apostrophe = text.indexOf('\''); if (apostrophe >= 0) format = DECIMAL_FORMAT_APOSTROPHE.get(); } if (format == null) { // determine format based on the relative location of the last // comma and dot, e.g. the last comma indicates a German number // format int lastDot = text.lastIndexOf('.'); int lastComma = text.lastIndexOf(','); format = Math.max(lastDot, lastComma) == lastComma ? DECIMAL_FORMAT_GERMAN.get() : DECIMAL_FORMAT_ENGLISH.get(); } double quote = format.parse(text).doubleValue(); return Math.round(quote * Values.Quote.factor()); } } protected static class DateColumn extends Column { private DateTimeFormatter[] formatters; @SuppressWarnings("nls") public DateColumn() { this(new String[] { "Datum.*", "Date.*" }); } @SuppressWarnings("nls") public DateColumn(String[] patterns) { super(patterns); formatters = new DateTimeFormatter[] { DateTimeFormatter.ofPattern("y-M-d"), DateTimeFormatter.ofPattern("d.M.yy"), //$NON-NLS-1$ DateTimeFormatter.ofPattern("d.M.y"), //$NON-NLS-1$ DateTimeFormatter.ofPattern("d. MMM y"), //$NON-NLS-1$ DateTimeFormatter.ofPattern("d. MMMM y"), //$NON-NLS-1$ DateTimeFormatter.ofPattern("d. MMM. y"), //$NON-NLS-1$ DateTimeFormatter.ofPattern("MMM d, y", Locale.ENGLISH), //$NON-NLS-1$ DateTimeFormatter.ofPattern("MMM dd, y", Locale.ENGLISH), //$NON-NLS-1$ DateTimeFormatter.ofPattern("EEEE, MMMM dd, yEEE, MMM dd, y", Locale.ENGLISH) //$NON-NLS-1$ }; } @Override void setValue(Element value, LatestSecurityPrice price, String languageHint) throws ParseException { String text = TextUtil.strip(value.text()); for (int ii = 0; ii < formatters.length; ii++) { try { LocalDate date = LocalDate.parse(text, formatters[ii]); price.setDate(date); return; } catch (DateTimeParseException e) // NOSONAR { // continue with next pattern } } throw new ParseException(text, 0); } } protected static class CloseColumn extends Column { @SuppressWarnings("nls") public CloseColumn() { super(new String[] { "Schluss.*", "Schluß.*", "Rücknahmepreis.*", "Close.*", "Zuletzt", "Price", "akt. Kurs" }); } public CloseColumn(String[] patterns) { super(patterns); } @Override void setValue(Element value, LatestSecurityPrice price, String languageHint) throws ParseException { price.setValue(asQuote(value, languageHint)); } } protected static class HighColumn extends Column { @SuppressWarnings("nls") public HighColumn() { super(new String[] { "Hoch.*", "Tageshoch.*", "Max.*", "High.*" }); } public HighColumn(String[] patterns) { super(patterns); } @Override void setValue(Element value, LatestSecurityPrice price, String languageHint) throws ParseException { if ("-".equals(value.text().trim())) //$NON-NLS-1$ price.setHigh(LatestSecurityPrice.NOT_AVAILABLE); else price.setHigh(asQuote(value, languageHint)); } } protected static class LowColumn extends Column { @SuppressWarnings("nls") public LowColumn() { super(new String[] { "Tief.*", "Tagestief.*", "Low.*" }); } public LowColumn(String[] patterns) { super(patterns); } @Override void setValue(Element value, LatestSecurityPrice price, String languageHint) throws ParseException { if ("-".equals(value.text().trim())) //$NON-NLS-1$ price.setLow(LatestSecurityPrice.NOT_AVAILABLE); else price.setLow(asQuote(value, languageHint)); } } private static class Spec { private final Column column; private final int index; public Spec(Column column, int index) { this.column = column; this.index = index; } } private static class HeaderInfo { private final int rowIndex; private final int numberOfHeaderColumns; public HeaderInfo(int rowIndex, int numberOfHeaderColumns) { super(); this.rowIndex = rowIndex; this.numberOfHeaderColumns = numberOfHeaderColumns; } } public static final String ID = "GENERIC_HTML_TABLE"; //$NON-NLS-1$ private static final Column[] COLUMNS = new Column[] { new DateColumn(), new CloseColumn(), new HighColumn(), new LowColumn() }; private final PageCache cache = new PageCache(); @Override public String getId() { return ID; } @Override public String getName() { return Messages.LabelHTMLTable; } @Override public boolean updateLatestQuotes(Security security, List<Exception> errors) { boolean isUpdated = false; // if latestFeed is null, then the policy is 'use same configuration // as historic quotes' String feedURL = security.getLatestFeed() == null ? security.getFeedURL() : security.getLatestFeedURL(); List<LatestSecurityPrice> quotes = internalGetQuotes(security, feedURL, errors); int size = quotes.size(); if (size > 0) { Collections.sort(quotes); LatestSecurityPrice latest = quotes.get(size - 1); LatestSecurityPrice previous = size > 1 ? quotes.get(size - 2) : null; latest.setPreviousClose(previous != null ? previous.getValue() : latest.getValue()); latest.setVolume(LatestSecurityPrice.NOT_AVAILABLE); isUpdated = security.setLatest(latest); } return isUpdated; } @Override public boolean updateHistoricalQuotes(Security security, List<Exception> errors) { List<LatestSecurityPrice> quotes = internalGetQuotes(security, security.getFeedURL(), errors); boolean isUpdated = false; for (LatestSecurityPrice quote : quotes) { boolean isAdded = security.addPrice(new SecurityPrice(quote.getDate(), quote.getValue())); isUpdated = isUpdated || isAdded; } return isUpdated; } @Override public List<LatestSecurityPrice> getHistoricalQuotes(Security security, LocalDate start, List<Exception> errors) { return internalGetQuotes(security, security.getFeedURL(), errors); } private List<LatestSecurityPrice> internalGetQuotes(Security security, String feedURL, List<Exception> errors) { if (feedURL == null || feedURL.length() == 0) { errors.add(new IOException(MessageFormat.format(Messages.MsgMissingFeedURL, security.getName()))); return Collections.emptyList(); } VariableURL variableURL = Factory.fromString(feedURL); variableURL.setSecurity(security); SortedSet<LatestSecurityPrice> newPricesByDate = new TreeSet<>(new SecurityPrice.ByDate()); long failedAttempts = 0; long maxFailedAttempts = variableURL.getMaxFailedAttempts(); for (String url : variableURL) { List<LatestSecurityPrice> answer = cache.lookup(url); if (answer == null) { answer = parseFromURL(url, errors); if (!answer.isEmpty()) cache.put(url, answer); } int sizeBefore = newPricesByDate.size(); newPricesByDate.addAll(answer); if (newPricesByDate.size() > sizeBefore) failedAttempts = 0; else if (++failedAttempts > maxFailedAttempts) break; } return new ArrayList<>(newPricesByDate); } @Override public List<LatestSecurityPrice> getHistoricalQuotes(String response, List<Exception> errors) { return parseFromHTML(response, errors); } @Override public List<Exchange> getExchanges(Security subject, List<Exception> errors) { return Collections.emptyList(); } protected List<LatestSecurityPrice> parseFromURL(String url, List<Exception> errors) { try { String escapedUrl = new URI(url).toASCIIString(); return parse(escapedUrl, Jsoup.connect(escapedUrl).userAgent(OnlineHelper.getUserAgent()).timeout(30000).get(), errors); } catch (URISyntaxException | IOException e) { errors.add(new IOException(url + '\n' + e.getMessage(), e)); return Collections.emptyList(); } } protected List<LatestSecurityPrice> parseFromHTML(String html, List<Exception> errors) { return parse("n/a", Jsoup.parse(html), errors); //$NON-NLS-1$ } private List<LatestSecurityPrice> parse(String url, Document document, List<Exception> errors) { // check if language is provided String language = document.select("html").attr("lang"); //$NON-NLS-1$ //$NON-NLS-2$ List<LatestSecurityPrice> prices = new ArrayList<>(); // first: find tables Elements tables = document.getElementsByTag("table"); //$NON-NLS-1$ for (Element table : tables) { List<Spec> specs = new ArrayList<>(); HeaderInfo headerInfo = buildSpecFromTable(table, specs); int rowIndex = headerInfo.rowIndex; if (isSpecValid(specs)) { Elements rows = table.select("> tbody > tr"); //$NON-NLS-1$ int size = rows.size(); for (; rowIndex < size; rowIndex++) { Element row = rows.get(rowIndex); try { LatestSecurityPrice price = extractPrice(row, specs, language, headerInfo.numberOfHeaderColumns); if (price != null) prices.add(price); } catch (Exception e) { errors.add(new IOException(url + '\n' + e.getMessage(), e)); } } // skip all other tables break; } } // if no quotes could be extract, log HTML for further analysis if (prices.isEmpty()) errors.add(new IOException(MessageFormat.format(Messages.MsgNoQuotesFoundInHTML, url, document.html()))); return prices; } @SuppressWarnings("nls") private HeaderInfo buildSpecFromTable(Element table, List<Spec> specs) { // check if thead exists Elements header = table.select("> thead > tr > th"); if (!header.isEmpty()) { buildSpecFromRow(header, specs); return new HeaderInfo(0, header.size()); } header = table.select("> thead > tr > td"); if (!header.isEmpty()) { buildSpecFromRow(header, specs); return new HeaderInfo(0, header.size()); } // check if th exist in body header = table.select("> tbody > tr > th"); if (!header.isEmpty()) { buildSpecFromRow(header, specs); return new HeaderInfo(0, header.size()); } // then check first two regular rows int rowIndex = 0; Elements rows = table.select("> tbody > tr"); Elements headerRow = null; if (!rows.isEmpty()) { Element firstRow = rows.get(0); headerRow = firstRow.select("> td"); buildSpecFromRow(headerRow, specs); rowIndex++; } if (specs.isEmpty() && rows.size() > 1) { Element secondRow = rows.get(1); headerRow = secondRow.select("> td"); buildSpecFromRow(headerRow, specs); rowIndex++; } return new HeaderInfo(rowIndex, headerRow != null ? headerRow.size() : 0); } protected Column[] getColumns() { return COLUMNS; } private void buildSpecFromRow(Elements row, List<Spec> specs) { Set<Column> available = new HashSet<>(); for (Column column : getColumns()) available.add(column); for (int ii = 0; ii < row.size(); ii++) { Element element = row.get(ii); for (Column column : available) { if (column.matches(element)) { specs.add(new Spec(column, ii)); available.remove(column); break; } } } } private boolean isSpecValid(List<Spec> specs) { if (specs == null || specs.isEmpty()) return false; boolean hasDate = false; boolean hasClose = false; for (Spec spec : specs) { hasDate = hasDate || spec.column instanceof DateColumn; hasClose = hasClose || spec.column instanceof CloseColumn; } return hasDate && hasClose; } private LatestSecurityPrice extractPrice(Element row, List<Spec> specs, String languageHint, int numberOfHeaderColumns) throws ParseException { Elements cells = row.select("> td"); //$NON-NLS-1$ // we're only looking at rows having the same size as the header row if (cells.size() != numberOfHeaderColumns) return null; LatestSecurityPrice price = new LatestSecurityPrice(); for (Spec spec : specs) spec.column.setValue(cells.get(spec.index), price, languageHint); return price; } /** * Test method to parse HTML tables * * @param args * list of URLs and/or local files */ public static void main(String[] args) throws IOException { PrintWriter writer = new PrintWriter(System.out); // NOSONAR for (String arg : args) if (arg.charAt(0) != '#') doLoad(arg, writer); writer.flush(); } @SuppressWarnings("nls") private static void doLoad(String source, PrintWriter writer) throws IOException { writer.println("--------"); writer.println(source); writer.println("--------"); List<LatestSecurityPrice> prices; List<Exception> errors = new ArrayList<>(); if (source.startsWith("http")) { prices = new HTMLTableQuoteFeed().parseFromURL(source, errors); } else { try (Scanner scanner = new Scanner(new File(source), StandardCharsets.UTF_8.name())) { String html = scanner.useDelimiter("\\A").next(); prices = new HTMLTableQuoteFeed().parseFromHTML(html, errors); } } for (Exception error : errors) error.printStackTrace(writer); // NOSONAR for (LatestSecurityPrice p : prices) { writer.print(Values.Date.format(p.getDate())); writer.print("\t"); writer.print(Values.Quote.format(p.getValue())); writer.print("\t"); writer.print(Values.Quote.format(p.getLow())); writer.print("\t"); writer.println(Values.Quote.format(p.getHigh())); } } }
Remove unnecessary call to super constructor
name.abuchen.portfolio/src/name/abuchen/portfolio/online/impl/HTMLTableQuoteFeed.java
Remove unnecessary call to super constructor
<ide><path>ame.abuchen.portfolio/src/name/abuchen/portfolio/online/impl/HTMLTableQuoteFeed.java <ide> <ide> public HeaderInfo(int rowIndex, int numberOfHeaderColumns) <ide> { <del> super(); <ide> this.rowIndex = rowIndex; <ide> this.numberOfHeaderColumns = numberOfHeaderColumns; <ide> }
Java
lgpl-2.1
fc3f62a19f39daba397f7911483dbaadc86f6dde
0
languagetool-org/languagetool,lopescan/languagetool,janissl/languagetool,languagetool-org/languagetool,meg0man/languagetool,jimregan/languagetool,languagetool-org/languagetool,janissl/languagetool,lopescan/languagetool,meg0man/languagetool,janissl/languagetool,meg0man/languagetool,meg0man/languagetool,lopescan/languagetool,languagetool-org/languagetool,meg0man/languagetool,jimregan/languagetool,jimregan/languagetool,janissl/languagetool,janissl/languagetool,jimregan/languagetool,lopescan/languagetool,jimregan/languagetool,languagetool-org/languagetool,lopescan/languagetool,janissl/languagetool
/* LanguageTool, a natural language style checker * Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package de.danielnaber.languagetool; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.PrintStream; import java.net.URISyntaxException; import java.net.URI; import java.net.URL; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; /** * Tests the basic features of the command-line interface. * * @author Marcin Miłkowski */ public class MainTest extends AbstractSecurityTestCase { private static final String ENGLISH_TEST_FILE = "test-en.txt"; private ByteArrayOutputStream out; private ByteArrayOutputStream err; private PrintStream stdout; private PrintStream stderr; public MainTest(String testName) { super(testName); } public void setUp() throws Exception { super.setUp(); this.stdout = System.out; this.stderr = System.err; this.out = new ByteArrayOutputStream(); this.err = new ByteArrayOutputStream(); System.setOut(new PrintStream(this.out)); System.setErr(new PrintStream(this.err)); } public void tearDown() throws Exception { super.tearDown(); System.setOut(this.stdout); System.setErr(this.stderr); } public void testUsageMessage() throws IOException, ParserConfigurationException, SAXException { try { String[] args = new String[] {"-h"}; Main.main(args); fail("LT should have exited with status 0!"); } catch (ExitException e) { String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Usage: java de.danielnaber.languagetool.Main [-r|--recursive] [-v|--verbose") != -1); assertEquals("Exit status", 1, e.status); } } public void testEnglishFile() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); //System.err.println("###"+url); final URI uri = new URI (url.toString()); String[] args = new String[] {"-l", "en", uri.getPath()}; Main.main(args); String output = new String(this.out.toByteArray()); //System.out.println("#>"+output); assertTrue(output.indexOf("Expected text language: English") == 0); assertTrue(output.indexOf("1.) Line 1, column 9, Rule ID: EN_A_VS_AN") != -1); } public void testEnglishFileVerbose() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); final URI uri = new URI (url.toString()); String[] args = new String[] {"-l", "en", "-v", uri.getPath()}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Expected text language: English") == 0); assertTrue(output.indexOf("1.) Line 1, column 9, Rule ID: EN_A_VS_AN") != -1); String tagText = new String(this.err.toByteArray()); assertTrue(tagText.indexOf("<S> This[this/DT] is[be/VBZ] an[a/DT] test[test/NN].[./.,</S>]") != -1); } public void testEnglishFileApplySuggestions() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); final URI uri = new URI (url.toString()); String[] args = new String[] {"-l", "en", "--apply", uri.getPath()}; Main.main(args); String output = new String(this.out.toByteArray()); assertEquals("This is a test.\n", output); } public void testEnglishStdIn1() throws IOException, ParserConfigurationException, SAXException { final String test = "This is an test."; final byte[] b = test.getBytes(); System.setIn(new ByteArrayInputStream(b)); String[] args = new String[] {"-l", "en"}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Expected text language: English") == 0); assertTrue(output.indexOf("1.) Line 1, column 9, Rule ID: EN_A_VS_AN") != -1); } public void testEnglishStdIn2() throws IOException, ParserConfigurationException, SAXException { final String test = "This is an test."; final byte[] b = test.getBytes(); System.setIn(new ByteArrayInputStream(b)); String[] args = new String[] {"-l", "en", "-"}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Expected text language: English") == 0); assertTrue(output.indexOf("1.) Line 1, column 9, Rule ID: EN_A_VS_AN") != -1); } public void testEnglishStdIn3() throws IOException, ParserConfigurationException, SAXException { final String test = "This is an test."; final byte[] b = test.getBytes(); System.setIn(new ByteArrayInputStream(b)); String[] args = new String[] {"-l", "en", "-a", "-"}; Main.main(args); String output = new String(this.out.toByteArray()); assertEquals("This is a test.\n", output); } //test line mode vs. para mode //first line mode public void testEnglishLineMode() throws IOException, ParserConfigurationException, SAXException { final String test = "This is what I mean\nand you know it."; final byte[] b = test.getBytes(); System.setIn(new ByteArrayInputStream(b)); String[] args = new String[] {"-l", "en", "-a", "-b", "-"}; Main.main(args); String output = new String(this.out.toByteArray()); assertEquals("This is what I mean\nAnd you know it.\n", output); } //first line mode public void testEnglishParaMode() throws IOException, ParserConfigurationException, SAXException { final String test = "This is what I mean\nand you know it."; final byte[] b = test.getBytes(); System.setIn(new ByteArrayInputStream(b)); String[] args = new String[] {"-l", "en", "-a", "-"}; Main.main(args); String output = new String(this.out.toByteArray()); assertEquals("This is what I mean\nand you know it.\n", output); } public void testPolishStdInDefaultOff() throws IOException, ParserConfigurationException, SAXException { final String test = "To jest test, który zrobiłem, który mi się podoba."; final byte[] b = test.getBytes(); System.setIn(new ByteArrayInputStream(b)); String[] args = new String[] {"-l", "pl", "-e", "PL_WORD_REPEAT", "-"}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Expected text language: Polish") == 0); assertTrue(output.indexOf("Working on STDIN...") != -1); assertTrue(output.indexOf("1.) Line 1, column 31, Rule ID: PL_WORD_REPEAT") != -1); } public void testEnglishFileRuleDisabled() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); final URI uri = new URI (url.toString()); String[] args = new String[] {"-l", "en", "-d", "EN_A_VS_AN", uri.getPath()}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Expected text language: English") == 0); assertTrue(output.indexOf("Rule ID: EN_A_VS_AN") == -1); } public void testEnglishFileRuleEnabled() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); final URI uri = new URI (url.toString()); String[] args = new String[] {"-l", "en", "-e", "EN_A_VS_AN", uri.getPath()}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Expected text language: English") == 0); assertTrue(output.indexOf("Rule ID: EN_A_VS_AN") != -1); } public void testEnglishFileAPI() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); final URI uri = new URI (url.toString()); String[] args = new String[] {"-l", "en", "--api", uri.getPath()}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") == 0); assertTrue(output.indexOf("<error fromy=\"0\" fromx=\"8\" toy=\"0\" tox=\"11\" ruleId=\"EN_A_VS_AN\" msg=\"Use 'a' instead of 'an' if the following word doesn't start with a vowel sound, e.g. 'a sentence', 'a university'\" replacements=\"a\" context=\"This is an test. \" contextoffset=\"8\" errorlength=\"2\"/>") != -1); } public void testPolishFileAPI() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { // Create a simple plain text file. File input = File.createTempFile("input", "txt"); input.deleteOnExit(); // Populate the file with data. PrintWriter w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(input), "UTF-8")); w.println("To jest świnia która się ślini."); w.close(); String[] args = new String[] {"-l", "pl", "--api", input.getAbsolutePath()}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") == 0); assertTrue(output.indexOf("<error fromy=\"0\" fromx=\"8\" toy=\"0\" tox=\"21\" ruleId=\"BRAK_PRZECINKA_KTORY\" subId=\"5\"") != -1); //This tests whether XML encoding is actually UTF-8: assertTrue(output.indexOf("msg=\"Brak przecinka w tym fragmencie zdania. Przecinek prawdopodobnie należy postawić tak: 'świnia, która'.\" replacements=\"świnia, która\" ") != -1); assertTrue(output.indexOf("context=\"To jest świnia która się ślini. \" contextoffset=\"8\" errorlength=\"12\"/>") != -1); } public void testPolishLineNumbers() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { // Create a simple plain text file. File input = File.createTempFile("input", "txt"); input.deleteOnExit(); // Populate the file with data. PrintWriter w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(input), "UTF-8")); w.println("Test."); w.println("Test."); w.println("Test."); w.println("Test."); w.println("Test."); w.println("Test."); w.println(""); w.println("Test który wykaże błąd."); w.close(); String[] args = new String[] {"-l", "pl", input.getAbsolutePath()}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Expected text language: Polish") == 0); assertTrue(output.indexOf("Line 8, column 1, Rule ID: BRAK_PRZECINKA_KTORY") != -1); } public void testEnglishTagger() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); final URI uri = new URI (url.toString()); String[] args = new String[] {"-l", "en", "--taggeronly", uri.getPath()}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Expected text language: English") == 0); assertTrue(output.indexOf("<S> This[this/DT] is[be/VBZ] an[a/DT] test[test/NN].[./.,</S>]") != -1); } public void testBitextMode() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { // Create a simple plain text file. File input = File.createTempFile("input", "txt"); input.deleteOnExit(); // Populate the file with data. PrintWriter w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(input), "UTF-8")); w.println("This is not actual.\tTo nie jest aktualne."); w.println("Test\tTest"); w.println("ab\tVery strange data indeed, much longer than input"); w.close(); String[] args = new String[] {"-l", "pl", "--bitext", "-m", "en", input.getAbsolutePath()}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Expected text language: Polish") == 0); assertTrue(output.indexOf( "Message: Hint: \"aktualny\" (Polish) means \"current\", \"(the) latest\", \"up-to-date\" (English). Did you mean 'rzeczywisty'?") != -1); assertTrue(output.indexOf("Line 1, column 32, Rule ID: ACTUAL") != -1); assertTrue(output.indexOf("Line 3, column 4, Rule ID: TRANSLATION_LENGTH") != -1); } public void testBitextModeWithDisabledRule() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { // Create a simple plain text file. File input = File.createTempFile("input", "txt"); input.deleteOnExit(); // Populate the file with data. PrintWriter w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(input), "UTF-8")); w.println("this is not actual.\tTo nie jest aktualne."); w.println("test\tTest"); w.println("ab\tVery strange data indeed, much longer than input"); w.close(); String[] args = new String[] {"-l", "pl", "--bitext", "-m", "en", "-d", "UPPERCASE_SENTENCE_START,TRANSLATION_LENGTH", input.getAbsolutePath()}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Expected text language: Polish") == 0); assertTrue(output.indexOf( "Message: Hint: \"aktualny\" (Polish) means \"current\", \"(the) latest\", \"up-to-date\" (English). Did you mean 'rzeczywisty'?") != -1); assertTrue(output.indexOf("Line 1, column 32, Rule ID: ACTUAL") != -1); assertTrue(output.indexOf("Rule ID: TRANSLATION_LENGTH") == -1); } public void testBitextModeWithEnabledRule() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { // Create a simple plain text file. File input = File.createTempFile("input", "txt"); input.deleteOnExit(); // Populate the file with data. PrintWriter w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(input), "UTF-8")); w.println("this is not actual.\tTo nie jest aktualne."); w.println("test\tTest"); w.println("ab\tVery strange data indeed, much longer than input"); w.close(); String[] args = new String[] {"-l", "pl", "--bitext", "-m", "en", "-e", "TRANSLATION_LENGTH", input.getAbsolutePath()}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Expected text language: Polish") == 0); assertTrue(output.indexOf( "Message: Hint: \"aktualny\" (Polish) means \"current\", \"(the) latest\", \"up-to-date\" (English). Did you mean 'rzeczywisty'?") == -1); assertTrue(output.indexOf("Line 1, column 32, Rule ID: ACTUAL") == -1); assertTrue(output.indexOf("Rule ID: TRANSLATION_LENGTH") != -1); } public void testListUnknown() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); final URI uri = new URI (url.toString()); String[] args = new String[] {"-l", "pl", "-u", uri.getPath()}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Expected text language: Polish") == 0); assertTrue(output.indexOf("Unknown words: [This, is]") != -1); } public void testNoListUnknown() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); final URI uri = new URI (url.toString()); String[] args = new String[] {"-l", "pl", uri.getPath()}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Expected text language: Polish") == 0); assertTrue(output.indexOf("Unknown words: [This, is]") == -1); } }
trunk/JLanguageTool/src/test/de/danielnaber/languagetool/MainTest.java
/* LanguageTool, a natural language style checker * Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package de.danielnaber.languagetool; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.PrintStream; import java.net.URISyntaxException; import java.net.URI; import java.net.URL; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; /** * * @author Marcin Miłkowski * Tests the basic features of the command-line interface. * */ public class MainTest extends AbstractSecurityTestCase { private static final String ENGLISH_TEST_FILE = "test-en.txt"; private ByteArrayOutputStream out; private ByteArrayOutputStream err; private PrintStream stdout; private PrintStream stderr; public MainTest(String testName) { super(testName); } public void setUp() throws Exception { super.setUp(); this.stdout = System.out; this.stderr = System.err; this.out = new ByteArrayOutputStream(); this.err = new ByteArrayOutputStream(); System.setOut(new PrintStream(this.out)); System.setErr(new PrintStream(this.err)); } public void tearDown() throws Exception { super.tearDown(); System.setOut(this.stdout); System.setErr(this.stderr); } public void testUsageMessage() throws IOException, ParserConfigurationException, SAXException { try { String[] args = new String[] {"-h"}; Main.main(args); fail("LT should have exited with status 0!"); } catch (ExitException e) { String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Usage: java de.danielnaber.languagetool.Main [-r|--recursive] [-v|--verbose") != -1); assertEquals("Exit status", 1, e.status); } } public void testEnglishFile() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { try { final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); //System.err.println("###"+url); final URI uri = new URI (url.toString()); String[] args = new String[] {"-l", "en", uri.getPath()}; Main.main(args); String output = new String(this.out.toByteArray()); //System.out.println("#>"+output); assertTrue(output.indexOf("Expected text language: English") == 0); assertTrue(output.indexOf("1.) Line 1, column 9, Rule ID: EN_A_VS_AN") != -1); } catch (ExitException e) { assertEquals("Exit status", 1, e.status); } } public void testEnglishFileVerbose() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { try { final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); final URI uri = new URI (url.toString()); String[] args = new String[] {"-l", "en", "-v", uri.getPath()}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Expected text language: English") == 0); assertTrue(output.indexOf("1.) Line 1, column 9, Rule ID: EN_A_VS_AN") != -1); String tagText = new String(this.err.toByteArray()); assertTrue(tagText.indexOf("<S> This[this/DT] is[be/VBZ] an[a/DT] test[test/NN].[./.,</S>]") != -1); } catch (ExitException e) { assertEquals("Exit status", 1, e.status); } } public void testEnglishFileApplySuggestions() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { try { final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); final URI uri = new URI (url.toString()); String[] args = new String[] {"-l", "en", "--apply", uri.getPath()}; Main.main(args); String output = new String(this.out.toByteArray()); assertEquals("This is a test.\n", output); } catch (ExitException e) { assertEquals("Exit status", 1, e.status); } } public void testEnglishStdIn1() throws IOException, ParserConfigurationException, SAXException { try { final String test = "This is an test."; final byte[] b = test.getBytes(); System.setIn(new ByteArrayInputStream(b)); String[] args = new String[] {"-l", "en"}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Expected text language: English") == 0); assertTrue(output.indexOf("1.) Line 1, column 9, Rule ID: EN_A_VS_AN") != -1); } catch (ExitException e) { assertEquals("Exit status", 1, e.status); } } public void testEnglishStdIn2() throws IOException, ParserConfigurationException, SAXException { try { final String test = "This is an test."; final byte[] b = test.getBytes(); System.setIn(new ByteArrayInputStream(b)); String[] args = new String[] {"-l", "en", "-"}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Expected text language: English") == 0); assertTrue(output.indexOf("1.) Line 1, column 9, Rule ID: EN_A_VS_AN") != -1); } catch (ExitException e) { assertEquals("Exit status", 1, e.status); } } public void testEnglishStdIn3() throws IOException, ParserConfigurationException, SAXException { try { final String test = "This is an test."; final byte[] b = test.getBytes(); System.setIn(new ByteArrayInputStream(b)); String[] args = new String[] {"-l", "en", "-a", "-"}; Main.main(args); String output = new String(this.out.toByteArray()); assertEquals("This is a test.\n", output); } catch (ExitException e) { assertEquals("Exit status", 1, e.status); } } //test line mode vs. para mode //first line mode public void testEnglishLineMode() throws IOException, ParserConfigurationException, SAXException { try { final String test = "This is what I mean\nand you know it."; final byte[] b = test.getBytes(); System.setIn(new ByteArrayInputStream(b)); String[] args = new String[] {"-l", "en", "-a", "-b", "-"}; Main.main(args); String output = new String(this.out.toByteArray()); assertEquals("This is what I mean\nAnd you know it.\n", output); } catch (ExitException e) { assertEquals("Exit status", 1, e.status); } } //first line mode public void testEnglishParaMode() throws IOException, ParserConfigurationException, SAXException { try { final String test = "This is what I mean\nand you know it."; final byte[] b = test.getBytes(); System.setIn(new ByteArrayInputStream(b)); String[] args = new String[] {"-l", "en", "-a", "-"}; Main.main(args); String output = new String(this.out.toByteArray()); assertEquals("This is what I mean\nand you know it.\n", output); } catch (ExitException e) { assertEquals("Exit status", 1, e.status); } } public void testPolishStdInDefaultOff() throws IOException, ParserConfigurationException, SAXException { try { final String test = "To jest test, który zrobiłem, który mi się podoba."; final byte[] b = test.getBytes(); System.setIn(new ByteArrayInputStream(b)); String[] args = new String[] {"-l", "pl", "-e", "PL_WORD_REPEAT", "-"}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Expected text language: Polish") == 0); assertTrue(output.indexOf("Working on STDIN...") != -1); assertTrue(output.indexOf("1.) Line 1, column 31, Rule ID: PL_WORD_REPEAT") != -1); } catch (ExitException e) { assertEquals("Exit status", 1, e.status); } } public void testEnglishFileRuleDisabled() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { try { final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); final URI uri = new URI (url.toString()); String[] args = new String[] {"-l", "en", "-d", "EN_A_VS_AN", uri.getPath()}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Expected text language: English") == 0); assertTrue(output.indexOf("Rule ID: EN_A_VS_AN") == -1); } catch (ExitException e) { assertEquals("Exit status", 1, e.status); } } public void testEnglishFileRuleEnabled() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { try { final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); final URI uri = new URI (url.toString()); String[] args = new String[] {"-l", "en", "-e", "EN_A_VS_AN", uri.getPath()}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Expected text language: English") == 0); assertTrue(output.indexOf("Rule ID: EN_A_VS_AN") != -1); } catch (ExitException e) { assertEquals("Exit status", 1, e.status); } } public void testEnglishFileAPI() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { try { final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); final URI uri = new URI (url.toString()); String[] args = new String[] {"-l", "en", "--api", uri.getPath()}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") == 0); assertTrue(output.indexOf("<error fromy=\"0\" fromx=\"8\" toy=\"0\" tox=\"11\" ruleId=\"EN_A_VS_AN\" msg=\"Use 'a' instead of 'an' if the following word doesn't start with a vowel sound, e.g. 'a sentence', 'a university'\" replacements=\"a\" context=\"This is an test. \" contextoffset=\"8\" errorlength=\"2\"/>") != -1); } catch (ExitException e) { assertEquals("Exit status", 1, e.status); } } public void testPolishFileAPI() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { try { // Create a simple plain text file. File input = File.createTempFile("input", "txt"); input.deleteOnExit(); // Populate the file with data. PrintWriter w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(input), "UTF-8")); w.println("To jest świnia która się ślini."); w.close(); String[] args = new String[] {"-l", "pl", "--api", input.getAbsolutePath()}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") == 0); assertTrue(output.indexOf("<error fromy=\"0\" fromx=\"8\" toy=\"0\" tox=\"21\" ruleId=\"BRAK_PRZECINKA_KTORY\" subId=\"5\"") != -1); //This tests whether XML encoding is actually UTF-8: assertTrue(output.indexOf("msg=\"Brak przecinka w tym fragmencie zdania. Przecinek prawdopodobnie należy postawić tak: 'świnia, która'.\" replacements=\"świnia, która\" ") != -1); assertTrue(output.indexOf("context=\"To jest świnia która się ślini. \" contextoffset=\"8\" errorlength=\"12\"/>") != -1); } catch (ExitException e) { assertEquals("Exit status", 1, e.status); } } public void testPolishLineNumbers() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { try { // Create a simple plain text file. File input = File.createTempFile("input", "txt"); input.deleteOnExit(); // Populate the file with data. PrintWriter w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(input), "UTF-8")); w.println("Test."); w.println("Test."); w.println("Test."); w.println("Test."); w.println("Test."); w.println("Test."); w.println(""); w.println("Test który wykaże błąd."); w.close(); String[] args = new String[] {"-l", "pl", input.getAbsolutePath()}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Expected text language: Polish") == 0); assertTrue(output.indexOf("Line 8, column 1, Rule ID: BRAK_PRZECINKA_KTORY") != -1); } catch (ExitException e) { assertEquals("Exit status", 1, e.status); } } public void testEnglishTagger() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { try { final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); final URI uri = new URI (url.toString()); String[] args = new String[] {"-l", "en", "--taggeronly", uri.getPath()}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Expected text language: English") == 0); assertTrue(output.indexOf("<S> This[this/DT] is[be/VBZ] an[a/DT] test[test/NN].[./.,</S>]") != -1); } catch (ExitException e) { assertEquals("Exit status", 1, e.status); } } public void testBitextMode() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { try { // Create a simple plain text file. File input = File.createTempFile("input", "txt"); input.deleteOnExit(); // Populate the file with data. PrintWriter w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(input), "UTF-8")); w.println("This is not actual.\tTo nie jest aktualne."); w.println("Test\tTest"); w.println("ab\tVery strange data indeed, much longer than input"); w.close(); String[] args = new String[] {"-l", "pl", "--bitext", "-m", "en", input.getAbsolutePath()}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Expected text language: Polish") == 0); assertTrue(output.indexOf( "Message: Hint: \"aktualny\" (Polish) means \"current\", \"(the) latest\", \"up-to-date\" (English). Did you mean 'rzeczywisty'?") != -1); assertTrue(output.indexOf("Line 1, column 32, Rule ID: ACTUAL") != -1); assertTrue(output.indexOf("Line 3, column 4, Rule ID: TRANSLATION_LENGTH") != -1); } catch (ExitException e) { assertEquals("Exit status", 1, e.status); } } public void testBitextModeWithDisabledRule() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { try { // Create a simple plain text file. File input = File.createTempFile("input", "txt"); input.deleteOnExit(); // Populate the file with data. PrintWriter w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(input), "UTF-8")); w.println("this is not actual.\tTo nie jest aktualne."); w.println("test\tTest"); w.println("ab\tVery strange data indeed, much longer than input"); w.close(); String[] args = new String[] {"-l", "pl", "--bitext", "-m", "en", "-d", "UPPERCASE_SENTENCE_START,TRANSLATION_LENGTH", input.getAbsolutePath()}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Expected text language: Polish") == 0); assertTrue(output.indexOf( "Message: Hint: \"aktualny\" (Polish) means \"current\", \"(the) latest\", \"up-to-date\" (English). Did you mean 'rzeczywisty'?") != -1); assertTrue(output.indexOf("Line 1, column 32, Rule ID: ACTUAL") != -1); assertTrue(output.indexOf("Rule ID: TRANSLATION_LENGTH") == -1); } catch (ExitException e) { assertEquals("Exit status", 1, e.status); } } public void testBitextModeWithEnabledRule() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { try { // Create a simple plain text file. File input = File.createTempFile("input", "txt"); input.deleteOnExit(); // Populate the file with data. PrintWriter w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(input), "UTF-8")); w.println("this is not actual.\tTo nie jest aktualne."); w.println("test\tTest"); w.println("ab\tVery strange data indeed, much longer than input"); w.close(); String[] args = new String[] {"-l", "pl", "--bitext", "-m", "en", "-e", "TRANSLATION_LENGTH", input.getAbsolutePath()}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Expected text language: Polish") == 0); assertTrue(output.indexOf( "Message: Hint: \"aktualny\" (Polish) means \"current\", \"(the) latest\", \"up-to-date\" (English). Did you mean 'rzeczywisty'?") == -1); assertTrue(output.indexOf("Line 1, column 32, Rule ID: ACTUAL") == -1); assertTrue(output.indexOf("Rule ID: TRANSLATION_LENGTH") != -1); } catch (ExitException e) { assertEquals("Exit status", 1, e.status); } } public void testListUnknown() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { try { final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); final URI uri = new URI (url.toString()); String[] args = new String[] {"-l", "pl", "-u", uri.getPath()}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Expected text language: Polish") == 0); assertTrue(output.indexOf("Unknown words: [This, is]") != -1); } catch (ExitException e) { assertEquals("Exit status", 1, e.status); } } public void testNoListUnknown() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { try { final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); final URI uri = new URI (url.toString()); String[] args = new String[] {"-l", "pl", uri.getPath()}; Main.main(args); String output = new String(this.out.toByteArray()); assertTrue(output.indexOf("Expected text language: Polish") == 0); assertTrue(output.indexOf("Unknown words: [This, is]") == -1); } catch (ExitException e) { assertEquals("Exit status", 1, e.status); } } }
remove catch blocks where not needed
trunk/JLanguageTool/src/test/de/danielnaber/languagetool/MainTest.java
remove catch blocks where not needed
<ide><path>runk/JLanguageTool/src/test/de/danielnaber/languagetool/MainTest.java <ide> import org.xml.sax.SAXException; <ide> <ide> /** <del> * <del> * @author Marcin Miłkowski <ide> * Tests the basic features of the command-line interface. <ide> * <add> * @author Marcin Miłkowski <ide> */ <ide> public class MainTest extends AbstractSecurityTestCase { <ide> <ide> Main.main(args); <ide> fail("LT should have exited with status 0!"); <ide> } <del> <ide> catch (ExitException e) { <ide> String output = new String(this.out.toByteArray()); <ide> assertTrue(output.indexOf("Usage: java de.danielnaber.languagetool.Main [-r|--recursive] [-v|--verbose") != -1); <ide> } <ide> <ide> public void testEnglishFile() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { <del> try { <del> final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); <del> //System.err.println("###"+url); <del> final URI uri = new URI (url.toString()); <del> String[] args = new String[] {"-l", "en", uri.getPath()}; <del> <del> Main.main(args); <del> String output = new String(this.out.toByteArray()); <del> //System.out.println("#>"+output); <del> assertTrue(output.indexOf("Expected text language: English") == 0); <del> assertTrue(output.indexOf("1.) Line 1, column 9, Rule ID: EN_A_VS_AN") != -1); <del> } <del> catch (ExitException e) { <del> assertEquals("Exit status", 1, e.status); <del> } <add> final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); <add> //System.err.println("###"+url); <add> final URI uri = new URI (url.toString()); <add> String[] args = new String[] {"-l", "en", uri.getPath()}; <add> <add> Main.main(args); <add> String output = new String(this.out.toByteArray()); <add> //System.out.println("#>"+output); <add> assertTrue(output.indexOf("Expected text language: English") == 0); <add> assertTrue(output.indexOf("1.) Line 1, column 9, Rule ID: EN_A_VS_AN") != -1); <ide> } <ide> <ide> public void testEnglishFileVerbose() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { <del> try { <del> final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); <del> final URI uri = new URI (url.toString()); <del> String[] args = new String[] {"-l", "en", "-v", uri.getPath()}; <del> <del> Main.main(args); <del> String output = new String(this.out.toByteArray()); <del> assertTrue(output.indexOf("Expected text language: English") == 0); <del> assertTrue(output.indexOf("1.) Line 1, column 9, Rule ID: EN_A_VS_AN") != -1); <del> String tagText = new String(this.err.toByteArray()); <del> assertTrue(tagText.indexOf("<S> This[this/DT] is[be/VBZ] an[a/DT] test[test/NN].[./.,</S>]") != -1); <del> } <del> catch (ExitException e) { <del> assertEquals("Exit status", 1, e.status); <del> } <add> final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); <add> final URI uri = new URI (url.toString()); <add> String[] args = new String[] {"-l", "en", "-v", uri.getPath()}; <add> <add> Main.main(args); <add> String output = new String(this.out.toByteArray()); <add> assertTrue(output.indexOf("Expected text language: English") == 0); <add> assertTrue(output.indexOf("1.) Line 1, column 9, Rule ID: EN_A_VS_AN") != -1); <add> String tagText = new String(this.err.toByteArray()); <add> assertTrue(tagText.indexOf("<S> This[this/DT] is[be/VBZ] an[a/DT] test[test/NN].[./.,</S>]") != -1); <ide> } <ide> <ide> public void testEnglishFileApplySuggestions() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { <del> try { <del> final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); <del> final URI uri = new URI (url.toString()); <del> String[] args = new String[] {"-l", "en", "--apply", uri.getPath()}; <del> <del> Main.main(args); <del> String output = new String(this.out.toByteArray()); <del> assertEquals("This is a test.\n", output); <del> } <del> catch (ExitException e) { <del> assertEquals("Exit status", 1, e.status); <del> } <add> final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); <add> final URI uri = new URI (url.toString()); <add> String[] args = new String[] {"-l", "en", "--apply", uri.getPath()}; <add> <add> Main.main(args); <add> String output = new String(this.out.toByteArray()); <add> assertEquals("This is a test.\n", output); <ide> } <ide> <ide> <ide> public void testEnglishStdIn1() throws IOException, ParserConfigurationException, SAXException { <del> try { <del> final String test = "This is an test."; <del> final byte[] b = test.getBytes(); <del> System.setIn(new ByteArrayInputStream(b)); <del> String[] args = new String[] {"-l", "en"}; <del> <del> Main.main(args); <del> String output = new String(this.out.toByteArray()); <del> assertTrue(output.indexOf("Expected text language: English") == 0); <del> assertTrue(output.indexOf("1.) Line 1, column 9, Rule ID: EN_A_VS_AN") != -1); <del> <del> } <del> catch (ExitException e) { <del> assertEquals("Exit status", 1, e.status); <del> } <add> final String test = "This is an test."; <add> final byte[] b = test.getBytes(); <add> System.setIn(new ByteArrayInputStream(b)); <add> String[] args = new String[] {"-l", "en"}; <add> <add> Main.main(args); <add> String output = new String(this.out.toByteArray()); <add> assertTrue(output.indexOf("Expected text language: English") == 0); <add> assertTrue(output.indexOf("1.) Line 1, column 9, Rule ID: EN_A_VS_AN") != -1); <ide> } <ide> <ide> public void testEnglishStdIn2() throws IOException, ParserConfigurationException, SAXException { <del> try { <del> final String test = "This is an test."; <del> final byte[] b = test.getBytes(); <del> System.setIn(new ByteArrayInputStream(b)); <del> String[] args = new String[] {"-l", "en", "-"}; <del> <del> Main.main(args); <del> String output = new String(this.out.toByteArray()); <del> assertTrue(output.indexOf("Expected text language: English") == 0); <del> assertTrue(output.indexOf("1.) Line 1, column 9, Rule ID: EN_A_VS_AN") != -1); <del> } <del> catch (ExitException e) { <del> assertEquals("Exit status", 1, e.status); <del> } <add> final String test = "This is an test."; <add> final byte[] b = test.getBytes(); <add> System.setIn(new ByteArrayInputStream(b)); <add> String[] args = new String[] {"-l", "en", "-"}; <add> <add> Main.main(args); <add> String output = new String(this.out.toByteArray()); <add> assertTrue(output.indexOf("Expected text language: English") == 0); <add> assertTrue(output.indexOf("1.) Line 1, column 9, Rule ID: EN_A_VS_AN") != -1); <ide> } <ide> <ide> public void testEnglishStdIn3() throws IOException, ParserConfigurationException, SAXException { <del> try { <del> final String test = "This is an test."; <del> final byte[] b = test.getBytes(); <del> System.setIn(new ByteArrayInputStream(b)); <del> String[] args = new String[] {"-l", "en", "-a", "-"}; <del> <del> Main.main(args); <del> String output = new String(this.out.toByteArray()); <del> assertEquals("This is a test.\n", output); <del> } <del> catch (ExitException e) { <del> assertEquals("Exit status", 1, e.status); <del> } <add> final String test = "This is an test."; <add> final byte[] b = test.getBytes(); <add> System.setIn(new ByteArrayInputStream(b)); <add> String[] args = new String[] {"-l", "en", "-a", "-"}; <add> <add> Main.main(args); <add> String output = new String(this.out.toByteArray()); <add> assertEquals("This is a test.\n", output); <ide> } <ide> <ide> //test line mode vs. para mode <ide> //first line mode <ide> public void testEnglishLineMode() throws IOException, ParserConfigurationException, SAXException { <del> try { <del> final String test = "This is what I mean\nand you know it."; <del> final byte[] b = test.getBytes(); <del> System.setIn(new ByteArrayInputStream(b)); <del> String[] args = new String[] {"-l", "en", "-a", "-b", "-"}; <del> <del> Main.main(args); <del> String output = new String(this.out.toByteArray()); <del> assertEquals("This is what I mean\nAnd you know it.\n", output); <del> } <del> catch (ExitException e) { <del> assertEquals("Exit status", 1, e.status); <del> } <del> } <add> final String test = "This is what I mean\nand you know it."; <add> final byte[] b = test.getBytes(); <add> System.setIn(new ByteArrayInputStream(b)); <add> String[] args = new String[] {"-l", "en", "-a", "-b", "-"}; <add> <add> Main.main(args); <add> String output = new String(this.out.toByteArray()); <add> assertEquals("This is what I mean\nAnd you know it.\n", output); <add> } <ide> <ide> //first line mode <ide> public void testEnglishParaMode() throws IOException, ParserConfigurationException, SAXException { <del> try { <del> final String test = "This is what I mean\nand you know it."; <del> final byte[] b = test.getBytes(); <del> System.setIn(new ByteArrayInputStream(b)); <del> String[] args = new String[] {"-l", "en", "-a", "-"}; <del> <del> Main.main(args); <del> String output = new String(this.out.toByteArray()); <del> assertEquals("This is what I mean\nand you know it.\n", output); <del> } <del> catch (ExitException e) { <del> assertEquals("Exit status", 1, e.status); <del> } <del> } <add> final String test = "This is what I mean\nand you know it."; <add> final byte[] b = test.getBytes(); <add> System.setIn(new ByteArrayInputStream(b)); <add> String[] args = new String[] {"-l", "en", "-a", "-"}; <add> <add> Main.main(args); <add> String output = new String(this.out.toByteArray()); <add> assertEquals("This is what I mean\nand you know it.\n", output); <add> } <ide> <ide> public void testPolishStdInDefaultOff() throws IOException, ParserConfigurationException, SAXException { <del> try { <del> final String test = "To jest test, który zrobiłem, który mi się podoba."; <del> final byte[] b = test.getBytes(); <del> System.setIn(new ByteArrayInputStream(b)); <del> String[] args = new String[] {"-l", "pl", "-e", "PL_WORD_REPEAT", "-"}; <del> <del> Main.main(args); <del> String output = new String(this.out.toByteArray()); <del> assertTrue(output.indexOf("Expected text language: Polish") == 0); <del> assertTrue(output.indexOf("Working on STDIN...") != -1); <del> assertTrue(output.indexOf("1.) Line 1, column 31, Rule ID: PL_WORD_REPEAT") != -1); <del> } <del> catch (ExitException e) { <del> assertEquals("Exit status", 1, e.status); <del> } <add> final String test = "To jest test, który zrobiłem, który mi się podoba."; <add> final byte[] b = test.getBytes(); <add> System.setIn(new ByteArrayInputStream(b)); <add> String[] args = new String[] {"-l", "pl", "-e", "PL_WORD_REPEAT", "-"}; <add> <add> Main.main(args); <add> String output = new String(this.out.toByteArray()); <add> assertTrue(output.indexOf("Expected text language: Polish") == 0); <add> assertTrue(output.indexOf("Working on STDIN...") != -1); <add> assertTrue(output.indexOf("1.) Line 1, column 31, Rule ID: PL_WORD_REPEAT") != -1); <ide> } <ide> <ide> public void testEnglishFileRuleDisabled() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { <del> try { <del> final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); <del> final URI uri = new URI (url.toString()); <del> String[] args = new String[] {"-l", "en", "-d", "EN_A_VS_AN", uri.getPath()}; <del> <del> Main.main(args); <del> String output = new String(this.out.toByteArray()); <del> assertTrue(output.indexOf("Expected text language: English") == 0); <del> assertTrue(output.indexOf("Rule ID: EN_A_VS_AN") == -1); <del> } <del> catch (ExitException e) { <del> assertEquals("Exit status", 1, e.status); <del> } <add> final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); <add> final URI uri = new URI (url.toString()); <add> String[] args = new String[] {"-l", "en", "-d", "EN_A_VS_AN", uri.getPath()}; <add> <add> Main.main(args); <add> String output = new String(this.out.toByteArray()); <add> assertTrue(output.indexOf("Expected text language: English") == 0); <add> assertTrue(output.indexOf("Rule ID: EN_A_VS_AN") == -1); <ide> } <ide> <ide> public void testEnglishFileRuleEnabled() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { <del> try { <del> final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); <del> final URI uri = new URI (url.toString()); <del> String[] args = new String[] {"-l", "en", "-e", "EN_A_VS_AN", uri.getPath()}; <del> <del> Main.main(args); <del> String output = new String(this.out.toByteArray()); <del> assertTrue(output.indexOf("Expected text language: English") == 0); <del> assertTrue(output.indexOf("Rule ID: EN_A_VS_AN") != -1); <del> } <del> catch (ExitException e) { <del> assertEquals("Exit status", 1, e.status); <del> } <add> final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); <add> final URI uri = new URI (url.toString()); <add> String[] args = new String[] {"-l", "en", "-e", "EN_A_VS_AN", uri.getPath()}; <add> <add> Main.main(args); <add> String output = new String(this.out.toByteArray()); <add> assertTrue(output.indexOf("Expected text language: English") == 0); <add> assertTrue(output.indexOf("Rule ID: EN_A_VS_AN") != -1); <ide> } <ide> <ide> public void testEnglishFileAPI() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { <del> try { <del> final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); <del> final URI uri = new URI (url.toString()); <del> String[] args = new String[] {"-l", "en", "--api", uri.getPath()}; <del> <del> Main.main(args); <del> String output = new String(this.out.toByteArray()); <del> assertTrue(output.indexOf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") == 0); <del> assertTrue(output.indexOf("<error fromy=\"0\" fromx=\"8\" toy=\"0\" tox=\"11\" ruleId=\"EN_A_VS_AN\" msg=\"Use 'a' instead of 'an' if the following word doesn't start with a vowel sound, e.g. 'a sentence', 'a university'\" replacements=\"a\" context=\"This is an test. \" contextoffset=\"8\" errorlength=\"2\"/>") != -1); <del> } <del> catch (ExitException e) { <del> assertEquals("Exit status", 1, e.status); <del> } <add> final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); <add> final URI uri = new URI (url.toString()); <add> String[] args = new String[] {"-l", "en", "--api", uri.getPath()}; <add> <add> Main.main(args); <add> String output = new String(this.out.toByteArray()); <add> assertTrue(output.indexOf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") == 0); <add> assertTrue(output.indexOf("<error fromy=\"0\" fromx=\"8\" toy=\"0\" tox=\"11\" ruleId=\"EN_A_VS_AN\" msg=\"Use 'a' instead of 'an' if the following word doesn't start with a vowel sound, e.g. 'a sentence', 'a university'\" replacements=\"a\" context=\"This is an test. \" contextoffset=\"8\" errorlength=\"2\"/>") != -1); <ide> } <ide> <ide> public void testPolishFileAPI() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { <del> try { <del> // Create a simple plain text file. <del> File input = File.createTempFile("input", "txt"); <del> input.deleteOnExit(); <del> <del> // Populate the file with data. <del> PrintWriter w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(input), "UTF-8")); <del> w.println("To jest świnia która się ślini."); <del> w.close(); <del> <del> String[] args = new String[] {"-l", "pl", "--api", input.getAbsolutePath()}; <del> <del> Main.main(args); <del> String output = new String(this.out.toByteArray()); <del> assertTrue(output.indexOf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") == 0); <del> assertTrue(output.indexOf("<error fromy=\"0\" fromx=\"8\" toy=\"0\" tox=\"21\" ruleId=\"BRAK_PRZECINKA_KTORY\" subId=\"5\"") != -1); <del> //This tests whether XML encoding is actually UTF-8: <del> assertTrue(output.indexOf("msg=\"Brak przecinka w tym fragmencie zdania. Przecinek prawdopodobnie należy postawić tak: 'świnia, która'.\" replacements=\"świnia, która\" ") != -1); <del> assertTrue(output.indexOf("context=\"To jest świnia która się ślini. \" contextoffset=\"8\" errorlength=\"12\"/>") != -1); <del> } <del> catch (ExitException e) { <del> assertEquals("Exit status", 1, e.status); <del> } <add> // Create a simple plain text file. <add> File input = File.createTempFile("input", "txt"); <add> input.deleteOnExit(); <add> <add> // Populate the file with data. <add> PrintWriter w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(input), "UTF-8")); <add> w.println("To jest świnia która się ślini."); <add> w.close(); <add> <add> String[] args = new String[] {"-l", "pl", "--api", input.getAbsolutePath()}; <add> <add> Main.main(args); <add> String output = new String(this.out.toByteArray()); <add> assertTrue(output.indexOf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") == 0); <add> assertTrue(output.indexOf("<error fromy=\"0\" fromx=\"8\" toy=\"0\" tox=\"21\" ruleId=\"BRAK_PRZECINKA_KTORY\" subId=\"5\"") != -1); <add> //This tests whether XML encoding is actually UTF-8: <add> assertTrue(output.indexOf("msg=\"Brak przecinka w tym fragmencie zdania. Przecinek prawdopodobnie należy postawić tak: 'świnia, która'.\" replacements=\"świnia, która\" ") != -1); <add> assertTrue(output.indexOf("context=\"To jest świnia która się ślini. \" contextoffset=\"8\" errorlength=\"12\"/>") != -1); <ide> } <ide> <ide> public void testPolishLineNumbers() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { <del> try { <del> // Create a simple plain text file. <del> File input = File.createTempFile("input", "txt"); <del> input.deleteOnExit(); <del> <del> // Populate the file with data. <del> PrintWriter w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(input), "UTF-8")); <del> w.println("Test."); <del> w.println("Test."); <del> w.println("Test."); <del> w.println("Test."); <del> w.println("Test."); <del> w.println("Test."); <del> w.println(""); <del> w.println("Test który wykaże błąd."); <del> w.close(); <del> <del> String[] args = new String[] {"-l", "pl", input.getAbsolutePath()}; <del> <del> Main.main(args); <del> String output = new String(this.out.toByteArray()); <del> assertTrue(output.indexOf("Expected text language: Polish") == 0); <del> assertTrue(output.indexOf("Line 8, column 1, Rule ID: BRAK_PRZECINKA_KTORY") != -1); <del> } <del> catch (ExitException e) { <del> assertEquals("Exit status", 1, e.status); <del> } <add> // Create a simple plain text file. <add> File input = File.createTempFile("input", "txt"); <add> input.deleteOnExit(); <add> <add> // Populate the file with data. <add> PrintWriter w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(input), "UTF-8")); <add> w.println("Test."); <add> w.println("Test."); <add> w.println("Test."); <add> w.println("Test."); <add> w.println("Test."); <add> w.println("Test."); <add> w.println(""); <add> w.println("Test który wykaże błąd."); <add> w.close(); <add> <add> String[] args = new String[] {"-l", "pl", input.getAbsolutePath()}; <add> <add> Main.main(args); <add> String output = new String(this.out.toByteArray()); <add> assertTrue(output.indexOf("Expected text language: Polish") == 0); <add> assertTrue(output.indexOf("Line 8, column 1, Rule ID: BRAK_PRZECINKA_KTORY") != -1); <ide> } <ide> <ide> public void testEnglishTagger() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { <del> try { <del> final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); <del> final URI uri = new URI (url.toString()); <del> String[] args = new String[] {"-l", "en", "--taggeronly", uri.getPath()}; <del> Main.main(args); <del> String output = new String(this.out.toByteArray()); <del> assertTrue(output.indexOf("Expected text language: English") == 0); <del> assertTrue(output.indexOf("<S> This[this/DT] is[be/VBZ] an[a/DT] test[test/NN].[./.,</S>]") != -1); <del> } <del> catch (ExitException e) { <del> assertEquals("Exit status", 1, e.status); <del> } <add> final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); <add> final URI uri = new URI (url.toString()); <add> String[] args = new String[] {"-l", "en", "--taggeronly", uri.getPath()}; <add> Main.main(args); <add> String output = new String(this.out.toByteArray()); <add> assertTrue(output.indexOf("Expected text language: English") == 0); <add> assertTrue(output.indexOf("<S> This[this/DT] is[be/VBZ] an[a/DT] test[test/NN].[./.,</S>]") != -1); <ide> } <ide> <ide> public void testBitextMode() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { <del> try { <del> // Create a simple plain text file. <del> File input = File.createTempFile("input", "txt"); <del> input.deleteOnExit(); <del> <del> // Populate the file with data. <del> PrintWriter w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(input), "UTF-8")); <del> w.println("This is not actual.\tTo nie jest aktualne."); <del> w.println("Test\tTest"); <del> w.println("ab\tVery strange data indeed, much longer than input"); <del> w.close(); <del> <del> String[] args = new String[] {"-l", "pl", "--bitext", "-m", "en", input.getAbsolutePath()}; <del> Main.main(args); <del> String output = new String(this.out.toByteArray()); <del> assertTrue(output.indexOf("Expected text language: Polish") == 0); <del> assertTrue(output.indexOf( <del> "Message: Hint: \"aktualny\" (Polish) means \"current\", \"(the) latest\", \"up-to-date\" (English). Did you mean 'rzeczywisty'?") != -1); <del> assertTrue(output.indexOf("Line 1, column 32, Rule ID: ACTUAL") != -1); <del> assertTrue(output.indexOf("Line 3, column 4, Rule ID: TRANSLATION_LENGTH") != -1); <del> } <del> catch (ExitException e) { <del> assertEquals("Exit status", 1, e.status); <del> } <add> // Create a simple plain text file. <add> File input = File.createTempFile("input", "txt"); <add> input.deleteOnExit(); <add> <add> // Populate the file with data. <add> PrintWriter w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(input), "UTF-8")); <add> w.println("This is not actual.\tTo nie jest aktualne."); <add> w.println("Test\tTest"); <add> w.println("ab\tVery strange data indeed, much longer than input"); <add> w.close(); <add> <add> String[] args = new String[] {"-l", "pl", "--bitext", "-m", "en", input.getAbsolutePath()}; <add> Main.main(args); <add> String output = new String(this.out.toByteArray()); <add> assertTrue(output.indexOf("Expected text language: Polish") == 0); <add> assertTrue(output.indexOf( <add> "Message: Hint: \"aktualny\" (Polish) means \"current\", \"(the) latest\", \"up-to-date\" (English). Did you mean 'rzeczywisty'?") != -1); <add> assertTrue(output.indexOf("Line 1, column 32, Rule ID: ACTUAL") != -1); <add> assertTrue(output.indexOf("Line 3, column 4, Rule ID: TRANSLATION_LENGTH") != -1); <ide> } <ide> <ide> public void testBitextModeWithDisabledRule() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { <del> try { <del> // Create a simple plain text file. <del> File input = File.createTempFile("input", "txt"); <del> input.deleteOnExit(); <del> <del> // Populate the file with data. <del> PrintWriter w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(input), "UTF-8")); <del> w.println("this is not actual.\tTo nie jest aktualne."); <del> w.println("test\tTest"); <del> w.println("ab\tVery strange data indeed, much longer than input"); <del> w.close(); <del> <del> String[] args = new String[] {"-l", "pl", "--bitext", "-m", "en", "-d", "UPPERCASE_SENTENCE_START,TRANSLATION_LENGTH", input.getAbsolutePath()}; <del> Main.main(args); <del> String output = new String(this.out.toByteArray()); <del> assertTrue(output.indexOf("Expected text language: Polish") == 0); <del> assertTrue(output.indexOf( <del> "Message: Hint: \"aktualny\" (Polish) means \"current\", \"(the) latest\", \"up-to-date\" (English). Did you mean 'rzeczywisty'?") != -1); <del> assertTrue(output.indexOf("Line 1, column 32, Rule ID: ACTUAL") != -1); <del> assertTrue(output.indexOf("Rule ID: TRANSLATION_LENGTH") == -1); <del> } <del> catch (ExitException e) { <del> assertEquals("Exit status", 1, e.status); <del> } <add> // Create a simple plain text file. <add> File input = File.createTempFile("input", "txt"); <add> input.deleteOnExit(); <add> <add> // Populate the file with data. <add> PrintWriter w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(input), "UTF-8")); <add> w.println("this is not actual.\tTo nie jest aktualne."); <add> w.println("test\tTest"); <add> w.println("ab\tVery strange data indeed, much longer than input"); <add> w.close(); <add> <add> String[] args = new String[] {"-l", "pl", "--bitext", "-m", "en", "-d", "UPPERCASE_SENTENCE_START,TRANSLATION_LENGTH", input.getAbsolutePath()}; <add> Main.main(args); <add> String output = new String(this.out.toByteArray()); <add> assertTrue(output.indexOf("Expected text language: Polish") == 0); <add> assertTrue(output.indexOf( <add> "Message: Hint: \"aktualny\" (Polish) means \"current\", \"(the) latest\", \"up-to-date\" (English). Did you mean 'rzeczywisty'?") != -1); <add> assertTrue(output.indexOf("Line 1, column 32, Rule ID: ACTUAL") != -1); <add> assertTrue(output.indexOf("Rule ID: TRANSLATION_LENGTH") == -1); <ide> } <ide> <ide> public void testBitextModeWithEnabledRule() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { <del> try { <del> // Create a simple plain text file. <del> File input = File.createTempFile("input", "txt"); <del> input.deleteOnExit(); <del> <del> // Populate the file with data. <del> PrintWriter w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(input), "UTF-8")); <del> w.println("this is not actual.\tTo nie jest aktualne."); <del> w.println("test\tTest"); <del> w.println("ab\tVery strange data indeed, much longer than input"); <del> w.close(); <del> <del> String[] args = new String[] {"-l", "pl", "--bitext", "-m", "en", "-e", "TRANSLATION_LENGTH", input.getAbsolutePath()}; <del> Main.main(args); <del> String output = new String(this.out.toByteArray()); <del> assertTrue(output.indexOf("Expected text language: Polish") == 0); <del> assertTrue(output.indexOf( <del> "Message: Hint: \"aktualny\" (Polish) means \"current\", \"(the) latest\", \"up-to-date\" (English). Did you mean 'rzeczywisty'?") == -1); <del> assertTrue(output.indexOf("Line 1, column 32, Rule ID: ACTUAL") == -1); <del> assertTrue(output.indexOf("Rule ID: TRANSLATION_LENGTH") != -1); <del> } <del> catch (ExitException e) { <del> assertEquals("Exit status", 1, e.status); <del> } <add> // Create a simple plain text file. <add> File input = File.createTempFile("input", "txt"); <add> input.deleteOnExit(); <add> <add> // Populate the file with data. <add> PrintWriter w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(input), "UTF-8")); <add> w.println("this is not actual.\tTo nie jest aktualne."); <add> w.println("test\tTest"); <add> w.println("ab\tVery strange data indeed, much longer than input"); <add> w.close(); <add> <add> String[] args = new String[] {"-l", "pl", "--bitext", "-m", "en", "-e", "TRANSLATION_LENGTH", input.getAbsolutePath()}; <add> Main.main(args); <add> String output = new String(this.out.toByteArray()); <add> assertTrue(output.indexOf("Expected text language: Polish") == 0); <add> assertTrue(output.indexOf( <add> "Message: Hint: \"aktualny\" (Polish) means \"current\", \"(the) latest\", \"up-to-date\" (English). Did you mean 'rzeczywisty'?") == -1); <add> assertTrue(output.indexOf("Line 1, column 32, Rule ID: ACTUAL") == -1); <add> assertTrue(output.indexOf("Rule ID: TRANSLATION_LENGTH") != -1); <ide> } <ide> <ide> public void testListUnknown() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { <del> try { <del> final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); <del> final URI uri = new URI (url.toString()); <del> String[] args = new String[] {"-l", "pl", "-u", uri.getPath()}; <del> Main.main(args); <del> String output = new String(this.out.toByteArray()); <del> assertTrue(output.indexOf("Expected text language: Polish") == 0); <del> assertTrue(output.indexOf("Unknown words: [This, is]") != -1); <del> } <del> catch (ExitException e) { <del> assertEquals("Exit status", 1, e.status); <del> } <add> final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); <add> final URI uri = new URI (url.toString()); <add> String[] args = new String[] {"-l", "pl", "-u", uri.getPath()}; <add> Main.main(args); <add> String output = new String(this.out.toByteArray()); <add> assertTrue(output.indexOf("Expected text language: Polish") == 0); <add> assertTrue(output.indexOf("Unknown words: [This, is]") != -1); <ide> } <ide> <ide> public void testNoListUnknown() throws URISyntaxException, IOException, ParserConfigurationException, SAXException { <del> try { <del> final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); <del> final URI uri = new URI (url.toString()); <del> String[] args = new String[] {"-l", "pl", uri.getPath()}; <del> Main.main(args); <del> String output = new String(this.out.toByteArray()); <del> assertTrue(output.indexOf("Expected text language: Polish") == 0); <del> assertTrue(output.indexOf("Unknown words: [This, is]") == -1); <del> } <del> catch (ExitException e) { <del> assertEquals("Exit status", 1, e.status); <del> } <add> final URL url = this.getClass().getResource(ENGLISH_TEST_FILE); <add> final URI uri = new URI (url.toString()); <add> String[] args = new String[] {"-l", "pl", uri.getPath()}; <add> Main.main(args); <add> String output = new String(this.out.toByteArray()); <add> assertTrue(output.indexOf("Expected text language: Polish") == 0); <add> assertTrue(output.indexOf("Unknown words: [This, is]") == -1); <ide> } <ide> <ide> }
Java
apache-2.0
c6c2cd0f21f2f5e3c49cfd23849fc79bd3818fa6
0
wso2-extensions/identity-inbound-provisioning-scim2
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.scim2.common.impl; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException; import org.wso2.carbon.identity.application.common.model.ServiceProvider; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.mgt.policy.PolicyViolationException; import org.wso2.carbon.identity.scim2.common.exceptions.IdentitySCIMException; import org.wso2.carbon.identity.scim2.common.group.SCIMGroupHandler; import org.wso2.carbon.identity.scim2.common.utils.AttributeMapper; import org.wso2.carbon.identity.scim2.common.utils.SCIMCommonConstants; import org.wso2.carbon.identity.scim2.common.utils.SCIMCommonUtils; import org.wso2.carbon.user.api.ClaimMapping; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.core.PaginatedUserStoreManager; import org.wso2.carbon.user.core.UserCoreConstants; import org.wso2.carbon.user.core.UserStoreManager; import org.wso2.carbon.user.core.claim.ClaimManager; import org.wso2.carbon.user.core.common.AbstractUserStoreManager; import org.wso2.carbon.user.core.model.Condition; import org.wso2.carbon.user.core.model.ExpressionAttribute; import org.wso2.carbon.user.core.model.ExpressionCondition; import org.wso2.carbon.user.core.model.ExpressionOperation; import org.wso2.carbon.user.core.model.OperationalCondition; import org.wso2.carbon.user.core.model.OperationalOperation; import org.wso2.carbon.user.core.model.UserClaimSearchEntry; import org.wso2.carbon.user.core.util.UserCoreUtil; import org.wso2.charon3.core.attributes.Attribute; import org.wso2.charon3.core.attributes.MultiValuedAttribute; import org.wso2.charon3.core.attributes.SimpleAttribute; import org.wso2.charon3.core.config.SCIMUserSchemaExtensionBuilder; import org.wso2.charon3.core.exceptions.BadRequestException; import org.wso2.charon3.core.exceptions.CharonException; import org.wso2.charon3.core.exceptions.ConflictException; import org.wso2.charon3.core.exceptions.NotFoundException; import org.wso2.charon3.core.exceptions.NotImplementedException; import org.wso2.charon3.core.extensions.UserManager; import org.wso2.charon3.core.objects.Group; import org.wso2.charon3.core.objects.User; import org.wso2.charon3.core.protocol.ResponseCodeConstants; import org.wso2.charon3.core.schema.SCIMConstants; import org.wso2.charon3.core.schema.SCIMResourceSchemaManager; import org.wso2.charon3.core.schema.SCIMResourceTypeSchema; import org.wso2.charon3.core.utils.AttributeUtil; import org.wso2.charon3.core.utils.ResourceManagerUtil; import org.wso2.charon3.core.utils.codeutils.ExpressionNode; import org.wso2.charon3.core.utils.codeutils.Node; import org.wso2.charon3.core.utils.codeutils.OperationNode; import org.wso2.charon3.core.utils.codeutils.SearchRequest; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class SCIMUserManager implements UserManager { public static final String FILTERING_DELIMITER = "*"; public static final String SQL_FILTERING_DELIMITER = "%"; private static final String ERROR_CODE_INVALID_USERNAME = "31301"; private static final String ERROR_CODE_INVALID_CREDENTIAL = "30003"; private static Log log = LogFactory.getLog(SCIMUserManager.class); private UserStoreManager carbonUM = null; private ClaimManager carbonClaimManager = null; private static final int MAX_ITEM_LIMIT_UNLIMITED = -1; private static final String ENABLE_PAGINATED_USER_STORE = "SCIM.EnablePaginatedUserStore"; public SCIMUserManager(UserStoreManager carbonUserStoreManager, ClaimManager claimManager) { carbonUM = carbonUserStoreManager; carbonClaimManager = claimManager; } @Override public User createUser(User user, Map<String, Boolean> requiredAttributes) throws CharonException, ConflictException, BadRequestException { String userStoreName = null; try { String userStoreDomainFromSP = getUserStoreDomainFromSP(); if (userStoreDomainFromSP != null) { userStoreName = userStoreDomainFromSP; } } catch (IdentityApplicationManagementException e) { throw new CharonException("Error retrieving User Store name. ", e); } StringBuilder userName = new StringBuilder(); if (StringUtils.isNotBlank(userStoreName)) { // if we have set a user store under provisioning configuration - we should only use that. String currentUserName = user.getUserName(); currentUserName = UserCoreUtil.removeDomainFromName(currentUserName); user.setUserName(userName.append(userStoreName) .append(CarbonConstants.DOMAIN_SEPARATOR).append(currentUserName) .toString()); } String userStoreDomainName = IdentityUtil.extractDomainFromName(user.getUserName()); if (!user.getUserName().contains(CarbonConstants.DOMAIN_SEPARATOR) && !UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME.equalsIgnoreCase(userStoreDomainName)) { user.setUserName(IdentityUtil.addDomainToName(user.getUserName(), userStoreDomainName)); } if(StringUtils.isNotBlank(userStoreDomainName) && !isSCIMEnabled(userStoreDomainName)){ throw new CharonException("Cannot add user through scim to user store " + ". SCIM is not " + "enabled for user store " + userStoreDomainName); } try { //Persist in carbon user store if (log.isDebugEnabled()) { log.debug("Creating user: " + user.getUserName()); } /*set thread local property to signal the downstream SCIMUserOperationListener about the provisioning route.*/ SCIMCommonUtils.setThreadLocalIsManagedThroughSCIMEP(true); Map<String, String> claimsMap = AttributeMapper.getClaimsMap(user); /*skip groups attribute since we map groups attribute to actual groups in ldap. and do not update it as an attribute in user schema*/ if (claimsMap.containsKey(SCIMConstants.UserSchemaConstants.GROUP_URI)) { claimsMap.remove(SCIMConstants.UserSchemaConstants.GROUP_URI); } /* Skip roles list since we map SCIM groups to local roles internally. It shouldn't be allowed to manipulate SCIM groups from user endpoint as this attribute has a mutability of "readOnly". Group changes must be applied via Group Resource */ if (claimsMap.containsKey(SCIMConstants.UserSchemaConstants.ROLES_URI + "." + SCIMConstants.DEFAULT)) { claimsMap.remove(SCIMConstants.UserSchemaConstants.ROLES_URI); } if (carbonUM.isExistingUser(user.getUserName())) { String error = "User with the name: " + user.getUserName() + " already exists in the system."; throw new ConflictException(error); } if (claimsMap.containsKey(SCIMConstants.UserSchemaConstants.USER_NAME_URI)) { claimsMap.remove(SCIMConstants.UserSchemaConstants.USER_NAME_URI); } Map<String, String> claimsInLocalDialect = SCIMCommonUtils.convertSCIMtoLocalDialect(claimsMap); carbonUM.addUser(user.getUserName(), user.getPassword(), null, claimsInLocalDialect, null); log.info("User: " + user.getUserName() + " is created through SCIM."); // Get Claims related to SCIM claim dialect Map<String, String> scimToLocalClaimsMap = SCIMCommonUtils.getSCIMtoLocalMappings(); // Get required SCIM Claims in local claim dialect. List<String> requiredClaimsInLocalDialect = getRequiredClaimsInLocalDialect(scimToLocalClaimsMap, requiredAttributes); // Get the user from the user store in order to get the default attributes during the user creation // response. user = this.getSCIMUser(user.getUserName(), requiredClaimsInLocalDialect, scimToLocalClaimsMap); // Set the schemas of the scim user. user.setSchemas(); } catch (UserStoreException e) { handleErrorsOnUserNameAndPasswordPolicy(e); String errMsg = "Error in adding the user: " + user.getUserName() + " to the user store. "; errMsg += e.getMessage(); throw new CharonException(errMsg, e); } return user; } private void handleErrorsOnUserNameAndPasswordPolicy(Throwable e) throws BadRequestException { int i = 0; // this variable is used to avoid endless loop if the e.getCause never becomes null. while (e != null && i < 10) { if (e instanceof UserStoreException && (e.getMessage().contains(ERROR_CODE_INVALID_USERNAME) || e.getMessage().contains(ERROR_CODE_INVALID_CREDENTIAL))) { throw new BadRequestException(e.getMessage(), ResponseCodeConstants.INVALID_VALUE); } if (e instanceof PolicyViolationException) { throw new BadRequestException(e.getMessage(), ResponseCodeConstants.INVALID_VALUE); } e = e.getCause(); i++; } } @Override public User getUser(String userId, Map<String, Boolean> requiredAttributes) throws CharonException { if (log.isDebugEnabled()) { log.debug("Retrieving user: " + userId); } User scimUser; try { //get the user name of the user with this id String userIdLocalClaim = SCIMCommonUtils.getSCIMtoLocalMappings().get(SCIMConstants .CommonSchemaConstants.ID_URI); String[] userNames = null; if (StringUtils.isNotBlank(userIdLocalClaim)) { userNames = carbonUM.getUserList(userIdLocalClaim, userId, UserCoreConstants.DEFAULT_PROFILE); } if (userNames == null || userNames.length == 0) { if (log.isDebugEnabled()) { log.debug("User with SCIM id: " + userId + " does not exist in the system."); } return null; } else { //get Claims related to SCIM claim dialect Map<String, String> scimToLocalClaimsMap = SCIMCommonUtils.getSCIMtoLocalMappings(); List<String> requiredClaimsInLocalDialect = getRequiredClaimsInLocalDialect(scimToLocalClaimsMap, requiredAttributes); //we assume (since id is unique per user) only one user exists for a given id scimUser = this.getSCIMUser(userNames[0], requiredClaimsInLocalDialect, scimToLocalClaimsMap); //set the schemas of the scim user scimUser.setSchemas(); log.info("User: " + scimUser.getUserName() + " is retrieved through SCIM."); } } catch (UserStoreException e) { throw new CharonException("Error in getting user information from Carbon User Store for" + "user: " + userId, e); } return scimUser; } @Override public void deleteUser(String userId) throws NotFoundException, CharonException { if (log.isDebugEnabled()) { log.debug("Deleting user: " + userId); } //get the user name of the user with this id String[] userNames = null; String userName = null; try { /*set thread local property to signal the downstream SCIMUserOperationListener about the provisioning route.*/ SCIMCommonUtils.setThreadLocalIsManagedThroughSCIMEP(true); String userIdLocalClaim = SCIMCommonUtils.getSCIMtoLocalMappings().get(SCIMConstants .CommonSchemaConstants.ID_URI); if (StringUtils.isNotBlank(userIdLocalClaim)) { userNames = carbonUM.getUserList(userIdLocalClaim, userId, UserCoreConstants.DEFAULT_PROFILE); } String userStoreDomainFromSP = null; try { userStoreDomainFromSP = getUserStoreDomainFromSP(); } catch (IdentityApplicationManagementException e) { throw new CharonException("Error retrieving User Store name. ", e); } if (userNames == null || userNames.length == 0) { //resource with given id not found if (log.isDebugEnabled()) { log.debug("User with id: " + userId + " not found."); } throw new NotFoundException(); } else if (userStoreDomainFromSP != null && !(userStoreDomainFromSP .equalsIgnoreCase(IdentityUtil.extractDomainFromName(userNames[0])))) { throw new CharonException("User :" + userNames[0] + "is not belong to user store " + userStoreDomainFromSP + "Hence user updating fail"); } else { //we assume (since id is unique per user) only one user exists for a given id userName = userNames[0]; String userStoreDomainName = IdentityUtil.extractDomainFromName(userName); //check if SCIM is enabled for the user store if (!isSCIMEnabled(userStoreDomainName)) { throw new CharonException("Cannot delete user: " + userName + " through SCIM from user store: " + userStoreDomainName + ". SCIM is not enabled for user store: " + userStoreDomainName); } carbonUM.deleteUser(userName); log.info("User: " + userName + " is deleted through SCIM."); } } catch (org.wso2.carbon.user.core.UserStoreException e) { throw new CharonException("Error in deleting user: " + userName, e); } } @Override public List<Object> listUsersWithGET(Node rootNode, int startIndex, int count, String sortBy, String sortOrder, String domainName, Map<String, Boolean> requiredAttributes) throws CharonException, NotImplementedException { if (sortBy != null || sortOrder != null) { throw new NotImplementedException("Sorting is not supported"); } else if (rootNode != null) { return filterUsers(rootNode, requiredAttributes, startIndex, count, sortBy, sortOrder, domainName); } else { return listUsers(requiredAttributes, startIndex, count, sortBy, sortOrder, domainName); } } @Override public List<Object> listUsersWithPost(SearchRequest searchRequest, Map<String, Boolean> requiredAttributes) throws CharonException, NotImplementedException, BadRequestException { return listUsersWithGET(searchRequest.getFilter(), searchRequest.getStartIndex(), searchRequest.getCount(), searchRequest.getSortBy(), searchRequest.getSortOder(), searchRequest.getDomainName(), requiredAttributes); } /** * Method to list users for given conditions. * * @param requiredAttributes Required attributes for the response * @param offset Starting index of the count * @param limit Counting value * @param sortBy SortBy * @param sortOrder Sorting order * @param domainName Name of the user store * @return User list with detailed attributes * @throws CharonException Error while listing users */ private List<Object> listUsers(Map<String, Boolean> requiredAttributes, int offset, int limit, String sortBy, String sortOrder, String domainName) throws CharonException { List<Object> users = new ArrayList<>(); //0th index is to store total number of results. users.add(0); String[] userNames; if (StringUtils.isNotEmpty(domainName)) { if (canPaginate(offset, limit)) { userNames = listUsernames(offset, limit, sortBy, sortOrder, domainName); } else { userNames = listUsernamesUsingLegacyAPIs(domainName); } } else { if (canPaginate(offset, limit)) { userNames = listUsernamesAcrossAllDomains(offset, limit, sortBy, sortOrder); } else { userNames = listUsernamesAcrossAllDomainsUsingLegacyAPIs(); } } if (ArrayUtils.isEmpty(userNames)) { if (log.isDebugEnabled()) { String message = String.format("There are no users who comply with the requested conditions: " + "startIndex = %d, count = %d", offset, limit); if (StringUtils.isNotEmpty(domainName)) { message = String.format(message + ", domain = %s", domainName); } log.debug(message); } } else { List<Object> scimUsers = getUserDetails(userNames, requiredAttributes); users.set(0, scimUsers.size()); // Set total number of results to 0th index. users.addAll(scimUsers); // Set user details from index 1. } return users; } /** * Method to decide whether to paginate based on the offset and the limit in the request. * * @param offset Starting index of the count * @param limit Counting value * @return true if pagination is possible, false otherwise */ private boolean canPaginate(int offset, int limit) { return (offset != 1 || limit != 0); } /** * Method to list paginated usernames from a specific user store using new APIs. * * @param offset Starting index of the count * @param limit Counting value * @param sortBy SortBy * @param sortOrder Sorting order * @param domainName Name of the user store * @return Paginated usernames list * @throws CharonException Error while listing usernames */ private String[] listUsernames(int offset, int limit, String sortBy, String sortOrder, String domainName) throws CharonException { if (isPaginatedUserStoreAvailable() && carbonUM instanceof PaginatedUserStoreManager) { if (limit == 0) { limit = getMaxLimit(domainName); } // Operator SW set with USERNAME and empty string to get all users. ExpressionCondition exCond = new ExpressionCondition(ExpressionOperation.SW.toString(), ExpressionAttribute.USERNAME.toString(), ""); return filterUsernames(exCond, offset, limit, sortBy, sortOrder, domainName); } else { if (log.isDebugEnabled()) { log.debug(String.format( "%s is not an instance of PaginatedUserStoreManager. Therefore pagination is not supported.", domainName)); } throw new CharonException(String.format("Pagination is not supported for %s.", domainName)); } } /** * Method to list usernames of all users from a specific user store using legacy APIs. * * @param domainName Name of the user store * @return Usernames list * @throws CharonException Error while listing usernames */ private String[] listUsernamesUsingLegacyAPIs(String domainName) throws CharonException { String[] userNames = null; try { Map<String, String> scimToLocalClaimsMap = SCIMCommonUtils.getSCIMtoLocalMappings(); String userIdLocalClaim = scimToLocalClaimsMap.get(SCIMConstants.CommonSchemaConstants.ID_URI); String claimValue = domainName.toUpperCase() + CarbonConstants.DOMAIN_SEPARATOR + SCIMCommonConstants.ANY; if (StringUtils.isNotBlank(userIdLocalClaim)) { userNames = carbonUM.getUserList(userIdLocalClaim, claimValue, null); } return userNames; } catch (UserStoreException e) { throw new CharonException(String.format("Error while listing usernames from domain: %s.", domainName), e); } } /** * Method to list paginated usernames from all user stores using new APIs. * * @param offset Starting index of the count * @param limit Counting value * @param sortBy SortBy * @param sortOrder Sorting order * @return Paginated usernames list * @throws CharonException Pagination not support */ private String[] listUsernamesAcrossAllDomains(int offset, int limit, String sortBy, String sortOrder) throws CharonException { String[] usernames; if (isPaginatedUserStoreAvailable() && carbonUM instanceof PaginatedUserStoreManager) { if (limit == 0) { usernames = listUsernamesAcrossAllDomainsUsingLegacyAPIs(); usernames = paginateUsers(usernames, limit, offset); } else { ExpressionCondition condition = new ExpressionCondition(ExpressionOperation.SW.toString(), ExpressionAttribute.USERNAME.toString(), ""); usernames = filterUsersFromMultipleDomains(null, offset, limit, sortBy, sortOrder, condition); } } else { if (log.isDebugEnabled()) { log.debug(" The user store is not a paginated user store manager. Therefore pagination " + "is not supported."); } throw new CharonException("Pagination is not supported."); } return usernames; } /** * Method to list usernames of all users across all user stores using legacy APIs. * * @return Usernames list * @throws CharonException Error while listing usernames */ private String[] listUsernamesAcrossAllDomainsUsingLegacyAPIs() throws CharonException { String[] userNames = null; try { Map<String, String> scimToLocalClaimsMap = SCIMCommonUtils.getSCIMtoLocalMappings(); String userIdLocalClaim = scimToLocalClaimsMap.get(SCIMConstants.CommonSchemaConstants.ID_URI); if (StringUtils.isNotBlank(userIdLocalClaim)) { userNames = carbonUM.getUserList(userIdLocalClaim, SCIMCommonConstants.ANY, null); } return userNames; } catch (UserStoreException e) { throw new CharonException("Error while listing usernames across all domains. ", e); } } /** * Method to get user details of usernames. * * @param userNames Array of usernames * @param requiredAttributes Required attributes for the response * @return User list with detailed attributes * @throws CharonException Error while retrieving users */ private List<Object> getUserDetails(String[] userNames, Map<String, Boolean> requiredAttributes) throws CharonException { List<Object> users = new ArrayList<>(); try { Map<String, String> scimToLocalClaimsMap = SCIMCommonUtils.getSCIMtoLocalMappings(); List<String> requiredClaims = getOnlyRequiredClaims(scimToLocalClaimsMap.keySet(), requiredAttributes); List<String> requiredClaimsInLocalDialect; if (MapUtils.isNotEmpty(scimToLocalClaimsMap)) { scimToLocalClaimsMap.keySet().retainAll(requiredClaims); requiredClaimsInLocalDialect = new ArrayList<>(scimToLocalClaimsMap.values()); } else { requiredClaimsInLocalDialect = new ArrayList<>(); } User[] scimUsers; if (isPaginatedUserStoreAvailable() && carbonUM instanceof PaginatedUserStoreManager) { // Retrieve all SCIM users at once. scimUsers = this.getSCIMUsers(userNames, requiredClaimsInLocalDialect, scimToLocalClaimsMap); users.addAll(Arrays.asList(scimUsers)); } else { // Retrieve SCIM users one by one. retriveSCIMUsers(users, userNames, requiredClaimsInLocalDialect, scimToLocalClaimsMap); } } catch (UserStoreException e) { throw new CharonException("Error while retrieving users from user store.", e); } return users; } private void retriveSCIMUsers(List<Object> users, String[] userNames, List<String> requiredClaims, Map<String, String> scimToLocalClaimsMap) throws CharonException { for (String userName : userNames) { if (userName.contains(UserCoreConstants.NAME_COMBINER)) { userName = userName.split("\\" + UserCoreConstants.NAME_COMBINER)[0]; } String userStoreDomainName = IdentityUtil.extractDomainFromName(userName); if (isSCIMEnabled(userStoreDomainName)) { if (log.isDebugEnabled()) { log.debug("SCIM is enabled for the user-store domain : " + userStoreDomainName + ". " + "Including user : " + userName + " in the response."); } User scimUser = this.getSCIMUser(userName, requiredClaims, scimToLocalClaimsMap); if (scimUser != null) { Map<String, Attribute> attrMap = scimUser.getAttributeList(); if (attrMap != null && !attrMap.isEmpty()) { users.add(scimUser); } } } else { if (log.isDebugEnabled()) { log.debug("SCIM is disabled for the user-store domain : " + userStoreDomainName + ". " + "Hence user : " + userName + " in this domain is excluded in the response."); } } } } @Override public User updateUser(User user, Map<String, Boolean> requiredAttributes) throws CharonException, BadRequestException { try { if (log.isDebugEnabled()) { log.debug("Updating user: " + user.getUserName()); } /*set thread local property to signal the downstream SCIMUserOperationListener about the provisioning route.*/ SCIMCommonUtils.setThreadLocalIsManagedThroughSCIMEP(true); //get user claim values Map<String, String> claims = AttributeMapper.getClaimsMap(user); //check if username of the updating user existing in the userstore. try { String userStoreDomainFromSP = getUserStoreDomainFromSP(); SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getUserResourceSchema(); User oldUser = this.getUser(user.getId(), ResourceManagerUtil.getAllAttributeURIs(schema)); if (userStoreDomainFromSP != null && !userStoreDomainFromSP .equalsIgnoreCase(IdentityUtil.extractDomainFromName(oldUser.getUserName()))) { throw new CharonException("User :" + oldUser.getUserName() + "is not belong to user store " + userStoreDomainFromSP + "Hence user updating fail"); } if (getUserStoreDomainFromSP() != null && !UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME.equalsIgnoreCase(getUserStoreDomainFromSP())) { user.setUserName(IdentityUtil .addDomainToName(UserCoreUtil.removeDomainFromName(user.getUserName()), getUserStoreDomainFromSP())); } } catch (IdentityApplicationManagementException e) { throw new CharonException("Error retrieving User Store name. ", e); } if (!carbonUM.isExistingUser(user.getUserName())) { throw new CharonException("User name is immutable in carbon user store."); } /*skip groups attribute since we map groups attribute to actual groups in ldap. and do not update it as an attribute in user schema*/ if (claims.containsKey(SCIMConstants.UserSchemaConstants.GROUP_URI)) { claims.remove(SCIMConstants.UserSchemaConstants.GROUP_URI); } /* Skip roles list since we map SCIM groups to local roles internally. It shouldn't be allowed to manipulate SCIM groups from user endpoint as this attribute has a mutability of "readOnly". Group changes must be applied via Group Resource */ if (claims.containsKey(SCIMConstants.UserSchemaConstants.ROLES_URI + "." + SCIMConstants.DEFAULT)) { claims.remove(SCIMConstants.UserSchemaConstants.ROLES_URI); } if (claims.containsKey(SCIMConstants.UserSchemaConstants.USER_NAME_URI)) { claims.remove(SCIMConstants.UserSchemaConstants.USER_NAME_URI); } Map<String, String> scimToLocalClaimsMap = SCIMCommonUtils.getSCIMtoLocalMappings(); List<String> requiredClaims = getOnlyRequiredClaims(scimToLocalClaimsMap.keySet(), requiredAttributes); List<String> requiredClaimsInLocalDialect; if (MapUtils.isNotEmpty(scimToLocalClaimsMap)) { scimToLocalClaimsMap.keySet().retainAll(requiredClaims); requiredClaimsInLocalDialect = new ArrayList<>(scimToLocalClaimsMap.values()); } else { if (log.isDebugEnabled()) { log.debug("SCIM to Local Claim mappings list is empty."); } requiredClaimsInLocalDialect = new ArrayList<>(); } Map<String, String> oldClaimList = carbonUM.getUserClaimValues(user.getUserName(), requiredClaimsInLocalDialect .toArray(new String[requiredClaims.size()]), null); for (Map.Entry<String, String> entry : oldClaimList.entrySet()) { if (!isImmutableClaim(entry.getKey())) { carbonUM.deleteUserClaimValue(user.getUserName(), entry.getKey(), null); } } // Get user claims mapped from SCIM dialect to WSO2 dialect. Map<String, String> claimValuesInLocalDialect = SCIMCommonUtils.convertSCIMtoLocalDialect(claims); //set user claim values carbonUM.setUserClaimValues(user.getUserName(), claimValuesInLocalDialect, null); //if password is updated, set it separately if (user.getPassword() != null) { carbonUM.updateCredentialByAdmin(user.getUserName(), user.getPassword()); } log.info("User: " + user.getUserName() + " updated through SCIM."); return getUser(user.getId(),requiredAttributes); } catch (UserStoreException e) { handleErrorsOnUserNameAndPasswordPolicy(e); throw new CharonException("Error while updating attributes of user: " + user.getUserName(), e); } catch (BadRequestException | CharonException e) { throw new CharonException("Error occured while trying to update the user", e); } } /** * Filter users using multi-attribute filters or single attribute filters with pagination. * * @param node Node * @param requiredAttributes Required attributes * @param offset Starting index of the count * @param limit Number of required results (count) * @param sortBy Sortby * @param sortOrder Sort order * @param domainName Domain that the filter should perform * @return Detailed user list * @throws CharonException */ private List<Object> filterUsers(Node node, Map<String, Boolean> requiredAttributes, int offset, int limit, String sortBy, String sortOrder, String domainName) throws CharonException { // Handle single attribute search. if (node instanceof ExpressionNode) { return filterUsersBySingleAttribute((ExpressionNode) node, requiredAttributes, offset, limit, sortBy, sortOrder, domainName); } else if (node instanceof OperationNode) { if (log.isDebugEnabled()) log.debug("Listing users by multi attribute filter"); List<Object> filteredUsers = new ArrayList<>(); // 0th index is to store total number of results. filteredUsers.add(0); // Support multi attribute filtering. return getMultiAttributeFilteredUsers(node, requiredAttributes, offset, limit, sortBy, sortOrder, domainName, filteredUsers); } else { throw new CharonException("Unknown operation. Not either an expression node or an operation node."); } } /** * Method to filter users for a filter with a single attribute. * * @param node Expression node for single attribute filtering * @param requiredAttributes Required attributes for the response * @param offset Starting index of the count * @param limit Counting value * @param sortBy SortBy * @param sortOrder Sorting order * @param domainName Domain to run the filter * @return User list with detailed attributes * @throws CharonException Error while filtering */ private List<Object> filterUsersBySingleAttribute(ExpressionNode node, Map<String, Boolean> requiredAttributes, int offset, int limit, String sortBy, String sortOrder, String domainName) throws CharonException { String[] userNames; if (log.isDebugEnabled()) { log.debug(String.format("Listing users by filter: %s %s %s", node.getAttributeValue(), node.getOperation(), node.getValue())); } // Apply filter enhancements for username and update expression node value. applyFilterEnhancementsForUsernameInNode(node); try { // Extract he domain name if the domain name is embedded in the filter attribute value. domainName = resolveDomainNameInAttributeValue(domainName, node); } catch (BadRequestException e) { String errorMessage = String .format("Domain parameter: %s in request does not match with the domain name in the attribute " + "value: %s ", domainName, node.getValue()); throw new CharonException(errorMessage, e); } try { // Check which APIs should the filter needs to follow. if (isUseLegacyAPIs(limit)) { userNames = filterUsersUsingLegacyAPIs(node, limit, offset, domainName); } else { userNames = filterUsers(node, offset, limit, sortBy, sortOrder, domainName); } } catch (NotImplementedException e) { String errorMessage = String.format("System does not support filter operator: %s", node.getOperation()); throw new CharonException(errorMessage, e); } return getDetailedUsers(userNames, requiredAttributes); } /** * Method to decide whether to use new APIs or legacy APIs. * * @param limit Number of results required for the filter request. * @return True if legacy API filtering is needed. */ private boolean isUseLegacyAPIs(int limit) { // If the limit is not specified, list all the users using old APIs since the new APIs must have a // limit larger than zero. if (limit <= 0) { return true; } else if (!isPaginatedUserStoreAvailable() && !(carbonUM instanceof PaginatedUserStoreManager)) { // If the userStore does not support above conditions, filter should use old APIs. return true; } return false; } /** * Validate whether filter enhancements are enabled and then append the primary domain name in front of the * attribute value to be searched. Finally update the attribute value in Expression node to new attribute value. * * @param node Expression node * @return Modified attribute value */ private void applyFilterEnhancementsForUsernameInNode(ExpressionNode node) { // Set filter values. String attributeName = node.getAttributeValue(); String filterOperation = node.getOperation(); String attributeValue = node.getValue(); if (SCIMCommonUtils.isFilteringEnhancementsEnabled()) if (SCIMCommonConstants.EQ.equalsIgnoreCase(filterOperation)) if (StringUtils.equals(attributeName, SCIMConstants.UserSchemaConstants.USER_NAME_URI) && !StringUtils .contains(attributeValue, CarbonConstants.DOMAIN_SEPARATOR)) node.setValue(UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME + CarbonConstants.DOMAIN_SEPARATOR + attributeValue); } /** * Update the domain parameter from the domain in attribute value and update the value in the expression node to the * newly extracted value. * * @param domainName Domain name in the filter request * @param node Expression node * @return Domain name extracted from the attribute value * @throws BadRequestException Domain miss match in domain parameter and attribute value */ private String resolveDomainNameInAttributeValue(String domainName, ExpressionNode node) throws BadRequestException { String extractedDomain; String attributeName = node.getAttributeValue(); String filterOperation = node.getOperation(); String attributeValue = node.getValue(); if (isDomainNameEmbeddedInAttributeValue(filterOperation, attributeName, attributeValue)) { int indexOfDomainSeparator = attributeValue.indexOf(CarbonConstants.DOMAIN_SEPARATOR); extractedDomain = attributeValue.substring(0, indexOfDomainSeparator).toUpperCase(); // Update then newly extracted attribute value in the expression node. int startingIndexOfAttributeValue = indexOfDomainSeparator + 1; node.setValue(attributeValue.substring(startingIndexOfAttributeValue)); // Check whether the domain name is equal to the extracted domain name from attribute value. if (StringUtils.isNotEmpty(domainName) && StringUtils.isNotEmpty(extractedDomain) && !extractedDomain .equalsIgnoreCase(domainName)) throw new BadRequestException(String.format( " Domain name %s in the domain parameter does not match with the domain name %s in search " + "attribute value of %s claim.", domainName, extractedDomain, attributeName)); if (StringUtils.isEmpty(domainName) && StringUtils.isNotEmpty(extractedDomain)) { if (log.isDebugEnabled()) log.debug(String.format("Domain name %s set from the domain name in the attribute value %s ", extractedDomain, attributeValue)); return extractedDomain; } } return domainName; } /** * Method to verify whether there is a domain in the attribute value. * * @param filterOperation Operation of the expression node * @param attributeName Attribute name of the expression node * @param attributeValue Value of the expression node * @return Whether there is a domain embedded to the attribute value */ private boolean isDomainNameEmbeddedInAttributeValue(String filterOperation, String attributeName, String attributeValue) { // Checks whether the domain separator is in the attribute value. if (StringUtils.contains(attributeValue, CarbonConstants.DOMAIN_SEPARATOR)) { // Checks whether the attribute name is username or group uri. if (StringUtils.equals(attributeName, SCIMConstants.UserSchemaConstants.USER_NAME_URI) || StringUtils .equals(attributeName, SCIMConstants.UserSchemaConstants.GROUP_URI)) { // Checks whether the operator is equal to EQ, SW, EW, CO. if (SCIMCommonConstants.EQ.equalsIgnoreCase(filterOperation) || SCIMCommonConstants.SW .equalsIgnoreCase(filterOperation) || SCIMCommonConstants.CO.equalsIgnoreCase(filterOperation) || SCIMCommonConstants.EW.equalsIgnoreCase(filterOperation)) { if (log.isDebugEnabled()) log.debug(String.format("Attribute value %s is embedded with a domain in %s claim, ", attributeValue, attributeName)); // If all the above conditions are true, then a domain is embedded to the attribute value. return true; } } } // If no domain name in the attribute value, return false. return false; } /** * Method to get users when a filter is used with a single attribute and when the user store is an instance of * PaginatedUserStoreManager since the filter API supports an instance of PaginatedUserStoreManager. * * @param node Expression or Operation node * @param offset Start index value * @param limit Count value * @param sortBy SortBy * @param sortOrder Sort order * @param domainName Domain to perform the search * @return User names of the filtered users * @throws CharonException Error while filtering */ private String[] filterUsers(Node node, int offset, int limit, String sortBy, String sortOrder, String domainName) throws CharonException { // Filter users when the domain is specified in the request. if (StringUtils.isNotEmpty(domainName)) { return filterUsernames(createConditionForSingleAttributeFilter(domainName, node), offset, limit, sortBy, sortOrder, domainName); } else { return filterUsersFromMultipleDomains(node, offset, limit, sortBy, sortOrder, null); } } /** * Method to perform a multiple domain search when the domain is not specified in the request. The same function * can be used to listing users by passing a condition for conditionForListingUsers parameter. * * @param node Expression or Operation node (set the value to null when method is used for * list users) * @param offset Start index value * @param limit Count value * @param sortBy SortBy * @param sortOrder Sort order * @param conditionForListingUsers Condition for listing users when the function is used to list users except for * filtering. For filtering this value should be set to NULL. * @return User names of the filtered users */ private String[] filterUsersFromMultipleDomains(Node node, int offset, int limit, String sortBy, String sortOrder, Condition conditionForListingUsers) throws CharonException { // Filter users when the domain is not set in the request. Then filter through multiple domains. String[] userStoreDomainNames = getDomainNames(); ArrayList<String> filteredUsernames = new ArrayList<>(); Condition condition; for (String userStoreDomainName : userStoreDomainNames) { // Check whether the used case is for listing users. if (conditionForListingUsers == null) { // Create filter condition for each domain for single attribute filter. condition = createConditionForSingleAttributeFilter(userStoreDomainName, node); } else { condition = conditionForListingUsers; } // Filter users for given condition and domain. String[] userNames = filterUsernames(condition, offset, limit, sortBy, sortOrder, userStoreDomainName); if (userNames == null) { userNames = new String[0]; } // Calculating new offset and limit parameters. int numberOfFilteredUsers = userNames.length; if (numberOfFilteredUsers <= 0 && offset > 1) { if (log.isDebugEnabled()) { log.debug(String.format("Filter returned no results for original offset: %d.", offset)); } offset = calculateOffset(condition, offset, sortBy, sortOrder, userStoreDomainName); } else { // Returned user names size > 0 implies there are users in that domain which is larger than // the offset. offset = 1; limit = calculateLimit(limit, numberOfFilteredUsers); } filteredUsernames.addAll(Arrays.asList(userNames)); // If the limit is changed then filtering needs to be stopped. if (limit == 0) { break; } } return filteredUsernames.toArray(new String[0]); } /** * Method to update the count(limit) when iterating a filter across all domains. * * @param limit Counting value (limit) * @param numberOfFilteredUsers Amount of users filtered in the search * @return Calculated new limit (count) */ private int calculateLimit(int limit, int numberOfFilteredUsers) { int newLimit = limit - numberOfFilteredUsers; if (limit < 0) { newLimit = 0; } if (log.isDebugEnabled()) { log.debug(String.format("New limit: %d calculated using initial offset: %d and filtered user count: %d. ", newLimit, limit, numberOfFilteredUsers)); } return newLimit; } /** * Method to update the offset when iterating a filter across all domains. * * @param condition Condition of the single attribute filter * @param offset Starting index * @param sortBy Sort by * @param sortOrder Sort order * @param domainName Domain to be filtered * @return New calculated offset * @throws CharonException Error while filtering the domain from index 1 to offset */ private int calculateOffset(Condition condition, int offset, String sortBy, String sortOrder, String domainName) throws CharonException { if (log.isDebugEnabled()) { log.debug(String.format("Checking for number of matches from the beginning to the original offset: %d for " + "the same filter and updating the new offset.", offset)); } // Starting index of the filter int initialOffset = 1; // Checking the number of matches till the original offset. int skippedUserCount; String[] skippedUsers = filterUsernames(condition, initialOffset, offset, sortBy, sortOrder, domainName); if (skippedUsers == null) { skippedUserCount = 0; } else { skippedUserCount = skippedUsers.length; } // Calculate the new offset and return return offset - skippedUserCount; } /** * Method to get users when a filter domain is known. * * @param condition Condition of the single attribute filter * @param offset Start index value * @param limit Count value * @param sortBy SortBy * @param sortOrder Sort order * @param domainName Domain to perform the search * @return User names of the filtered users * @throws CharonException Error while filtering */ private String[] filterUsernames(Condition condition, int offset, int limit, String sortBy, String sortOrder, String domainName) throws CharonException { if (log.isDebugEnabled()) { log.debug(String.format("Filtering users in domain : %s with limit: %d and offset: %d.", domainName, limit, offset)); } try { return ((PaginatedUserStoreManager) carbonUM) .getUserList(condition, domainName, UserCoreConstants.DEFAULT_PROFILE, limit, offset, sortBy, sortOrder); } catch (UserStoreException e) { String errorMessage = String .format("Error while retrieving users for the domain: %s with limit: %d and offset: %d.", domainName, limit, offset); throw new CharonException(errorMessage, e); } } /** * Method is to create a condition for a single attribute filter when the node and the domain name is passed. * * @param domainName Domain name of the user store to be filtered * @param node Node of the single attribute filter * @return Condition for the single attribute filter * @throws CharonException */ private Condition createConditionForSingleAttributeFilter(String domainName, Node node) throws CharonException { if (log.isDebugEnabled()) { log.debug("Creating condition for domain : " + domainName); } Map<String, String> attributes; try { attributes = getAllAttributes(domainName); } catch (UserStoreException e) { String errorMessage = String.format("Error while retrieving attributes for the domain %s.", domainName); throw new CharonException(errorMessage, e); } return getCondition(node, attributes); } /** * Get all the domain names related to user stores. * * @return A list of all the available domain names */ private String[] getDomainNames() { String domainName; ArrayList<String> domainsOfUserStores = new ArrayList<>(); UserStoreManager secondaryUserStore = carbonUM.getSecondaryUserStoreManager(); while (secondaryUserStore != null) { domainName = secondaryUserStore.getRealmConfiguration(). getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME).toUpperCase(); secondaryUserStore = secondaryUserStore.getSecondaryUserStoreManager(); domainsOfUserStores.add(domainName); } // Sorting the secondary user stores to maintain an order fo domains so that pagination is consistent. Collections.sort(domainsOfUserStores); // Append the primary domain name to the front of the domain list since the first iteration of multiple // domain filtering should happen for the primary user store. domainsOfUserStores.add(0, UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME); return domainsOfUserStores.toArray(new String[0]); } /** * Method to filter users if the user store is not an instance of PaginatedUserStoreManager and * ENABLE_PAGINATED_USER_STORE is not enabled. * * @param node Expression node * @param limit Number of users required for counting * @param offset Starting user index for start counting * @return List of paginated set of users. * @throws NotImplementedException Not supported filter operation * @throws UserStoreException */ private String[] filterUsersUsingLegacyAPIs(ExpressionNode node, int limit, int offset, String domainName) throws NotImplementedException, CharonException { String[] userNames; // Set filter values. String attributeName = node.getAttributeValue(); String filterOperation = node.getOperation(); String attributeValue = node.getValue(); // If there is a domain, append the domain with the domain separator in front of the new attribute value if // domain separator is not found in the attribute value. if (StringUtils.isNotEmpty(domainName) && StringUtils .containsNone(attributeValue, CarbonConstants.DOMAIN_SEPARATOR)) { attributeValue = domainName.toUpperCase() + CarbonConstants.DOMAIN_SEPARATOR + node.getValue(); } try { if (SCIMConstants.UserSchemaConstants.GROUP_URI.equals(attributeName)) { if (carbonUM instanceof AbstractUserStoreManager) { String[] roleNames = getRoleNames(filterOperation, attributeValue); userNames = getUserListOfRoles(roleNames); } else { String errorMessage = String .format("Filter operator %s is not supported by the user store.", filterOperation); throw new NotImplementedException(errorMessage); } } else { // Get the user name of the user with this id. userNames = getUserNames(attributeName, filterOperation, attributeValue); } } catch (UserStoreException e) { String errorMessage = String.format("Error while filtering the users for filter with attribute name: %s ," + " filter operation: %s and attribute value: %s. ", attributeName, filterOperation, attributeValue); throw new CharonException(errorMessage, e); } userNames = paginateUsers(userNames, limit, offset); return userNames; } /** * Method to remove duplicate users and get the user details. * * @param userNames Filtered user names * @param requiredAttributes Required attributes in the response * @return Users list with populated attributes * @throws CharonException Error in retrieving user details */ private List<Object> getDetailedUsers(String[] userNames, Map<String, Boolean> requiredAttributes) throws CharonException { List<Object> filteredUsers = new ArrayList<>(); // 0th index is to store total number of results. filteredUsers.add(0); // Remove duplicate users. HashSet<String> userNamesSet = new HashSet<>(Arrays.asList(userNames)); userNames = userNamesSet.toArray(new String[0]); // Set total number of filtered results. filteredUsers.set(0, userNames.length); // Get details of the finalized user list. filteredUsers.addAll(getFilteredUserDetails(userNames, requiredAttributes)); return filteredUsers; } /** * This method support multi-attribute filters with paginated search for user(s). * * @param node * @param requiredAttributes * @param offset * @param limit * @param sortBy * @param sortOrder * @param domainName * @param filteredUsers * @return * @throws CharonException */ private List<Object> getMultiAttributeFilteredUsers(Node node, Map<String, Boolean> requiredAttributes, int offset, int limit, String sortBy, String sortOrder, String domainName, List<Object> filteredUsers) throws CharonException { String[] userNames; // Handle pagination. if (limit > 0) { userNames = getFilteredUsersFromMultiAttributeFiltering(node, offset, limit, sortBy, sortOrder, domainName); filteredUsers.set(0, userNames.length); filteredUsers.addAll(getFilteredUserDetails(userNames, requiredAttributes)); } else { int maxLimit = getMaxLimit(domainName); if (StringUtils.isNotEmpty(domainName)) { userNames = getFilteredUsersFromMultiAttributeFiltering(node, offset, maxLimit, sortBy, sortOrder, domainName); filteredUsers.set(0, userNames.length); filteredUsers.addAll(getFilteredUserDetails(userNames, requiredAttributes)); } else { int totalUserCount = 0; // If pagination and domain name are not given, then perform filtering on all available user stores. while (carbonUM != null) { // If carbonUM is not an instance of Abstract User Store Manger we can't get the domain name. if (carbonUM instanceof AbstractUserStoreManager) { domainName = carbonUM.getRealmConfiguration().getUserStoreProperty("DomainName"); userNames = getFilteredUsersFromMultiAttributeFiltering(node, offset, maxLimit, sortBy, sortOrder, domainName); totalUserCount += userNames.length; filteredUsers.addAll(getFilteredUserDetails(userNames, requiredAttributes)); } carbonUM = carbonUM.getSecondaryUserStoreManager(); } //set the total results filteredUsers.set(0, totalUserCount); } } return filteredUsers; } /** * Get maximum user limit to retrieve. * * @param domainName Name of the user store * @return */ private int getMaxLimit(String domainName) { int givenMax = UserCoreConstants.MAX_USER_ROLE_LIST; if (StringUtils.isEmpty(domainName)) { domainName = UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME; } if (carbonUM.getSecondaryUserStoreManager(domainName).getRealmConfiguration() .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST) != null) { givenMax = Integer.parseInt(carbonUM.getSecondaryUserStoreManager(domainName).getRealmConfiguration() .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST)); } return givenMax; } /** * Generate condition tree for given filters. * * @param node * @param attributes * @return * @throws CharonException */ private Condition getCondition(Node node, Map<String, String> attributes) throws CharonException { if (node instanceof ExpressionNode) { String operation = ((ExpressionNode) node).getOperation(); String attributeName = ((ExpressionNode) node).getAttributeValue(); String attributeValue = ((ExpressionNode) node).getValue(); String conditionOperation; String conditionAttributeName; if (SCIMCommonConstants.EQ.equals(operation)) { conditionOperation = ExpressionOperation.EQ.toString(); } else if (SCIMCommonConstants.SW.equals(operation)) { conditionOperation = ExpressionOperation.SW.toString(); } else if (SCIMCommonConstants.EW.equals(operation)) { conditionOperation = ExpressionOperation.EW.toString(); } else if (SCIMCommonConstants.CO.equals(operation)) { conditionOperation = ExpressionOperation.CO.toString(); } else { conditionOperation = operation; } if (SCIMConstants.UserSchemaConstants.GROUP_URI.equals(attributeName)) { conditionAttributeName = ExpressionAttribute.ROLE.toString(); } else if (SCIMConstants.UserSchemaConstants.USER_NAME_URI.equals(attributeName)) { conditionAttributeName = ExpressionAttribute.USERNAME.toString(); } else if (attributes != null && attributes.get(attributeName) != null) { conditionAttributeName = attributes.get(attributeName); } else { throw new CharonException("Unsupported attribute: " + attributeName); } return new ExpressionCondition(conditionOperation, conditionAttributeName, attributeValue); } else if (node instanceof OperationNode) { Condition leftCondition = getCondition(node.getLeftNode(), attributes); Condition rightCondition = getCondition(node.getRightNode(), attributes); String operation = ((OperationNode) node).getOperation(); if (OperationalOperation.AND.toString().equalsIgnoreCase(operation)) { return new OperationalCondition(OperationalOperation.AND.toString(), leftCondition, rightCondition); } else { throw new CharonException("Unsupported Operation: " + operation); } } else { throw new CharonException("Unsupported Operation"); } } /** * Get all attributes for given domain. * * @param domainName * @return * @throws UserStoreException */ private Map<String, String> getAllAttributes(String domainName) throws UserStoreException { ClaimMapping[] userClaims; ClaimMapping[] coreClaims; ClaimMapping[] extensionClaims = null; try { coreClaims = carbonClaimManager.getAllClaimMappings(SCIMCommonConstants.SCIM_CORE_CLAIM_DIALECT); userClaims = carbonClaimManager.getAllClaimMappings(SCIMCommonConstants.SCIM_USER_CLAIM_DIALECT); if (SCIMUserSchemaExtensionBuilder.getInstance().getExtensionSchema() != null) { extensionClaims = carbonClaimManager.getAllClaimMappings( SCIMUserSchemaExtensionBuilder.getInstance().getExtensionSchema().getURI()); } Map<String, String> attributes = new HashMap<>(); for (ClaimMapping claim : coreClaims) { attributes.put(claim.getClaim().getClaimUri(), claim.getMappedAttribute(domainName)); } for (ClaimMapping claim : userClaims) { attributes.put(claim.getClaim().getClaimUri(), claim.getMappedAttribute(domainName)); } if (extensionClaims != null) { for (ClaimMapping claim : extensionClaims) { attributes.put(claim.getClaim().getClaimUri(), claim.getMappedAttribute(domainName)); } } return attributes; } catch (UserStoreException e) { throw new UserStoreException("Error in filtering users by multi attributes ", e); } } /** * Perform multi attribute filtering. * * @param node * @param offset * @param limit * @param sortBy * @param sortOrder * @param domainName * @return * @throws CharonException */ private String[] getFilteredUsersFromMultiAttributeFiltering(Node node, int offset, int limit, String sortBy, String sortOrder, String domainName) throws CharonException { String[] userNames; try { if (StringUtils.isEmpty(domainName)) { domainName = "PRIMARY"; } Map<String, String> attributes = getAllAttributes(domainName); if (log.isDebugEnabled()) { log.debug("Invoking the do get user list for domain: " + domainName); } userNames = ((PaginatedUserStoreManager) carbonUM).getUserList(getCondition(node, attributes), domainName, UserCoreConstants.DEFAULT_PROFILE, limit, offset, sortBy, sortOrder); return userNames; } catch (UserStoreException e) { throw new CharonException("Error in filtering users by multi attributes ", e); } } /** * Get required claim details for filtered user. * * @param userNames * @param requiredAttributes * @return * @throws CharonException */ private List<Object> getFilteredUserDetails(String[] userNames, Map<String, Boolean> requiredAttributes) throws CharonException { List<Object> filteredUsers = new ArrayList<>(); if (userNames == null || userNames.length == 0) { if (log.isDebugEnabled()) { log.debug("Users for this filter does not exist in the system."); } return filteredUsers; } else { try { Map<String, String> scimToLocalClaimsMap = SCIMCommonUtils.getSCIMtoLocalMappings(); List<String> requiredClaims = getOnlyRequiredClaims(scimToLocalClaimsMap.keySet(), requiredAttributes); List<String> requiredClaimsInLocalDialect; if (MapUtils.isNotEmpty(scimToLocalClaimsMap)) { scimToLocalClaimsMap.keySet().retainAll(requiredClaims); requiredClaimsInLocalDialect = new ArrayList<>(scimToLocalClaimsMap.values()); } else { if (log.isDebugEnabled()) { log.debug("SCIM to Local Claim mappings list is empty."); } requiredClaimsInLocalDialect = new ArrayList<>(); } User[] scimUsers; if (isPaginatedUserStoreAvailable()) { if (carbonUM instanceof PaginatedUserStoreManager) { scimUsers = this.getSCIMUsers(userNames, requiredClaimsInLocalDialect, scimToLocalClaimsMap); filteredUsers.addAll(Arrays.asList(scimUsers)); } else { addSCIMUsers(filteredUsers, userNames, requiredClaimsInLocalDialect, scimToLocalClaimsMap); } } else { addSCIMUsers(filteredUsers, userNames, requiredClaimsInLocalDialect, scimToLocalClaimsMap); } } catch (UserStoreException e) { throw new CharonException("Error in retrieve user details. ", e); } } return filteredUsers; } private void addSCIMUsers(List<Object> filteredUsers, String[] userNames, List<String> requiredClaims, Map<String, String> scimToLocalClaimsMap) throws CharonException { User scimUser; for (String userName : userNames) { if (CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME.equals(userName)) { continue; } String userStoreDomainName = IdentityUtil.extractDomainFromName(userName); if (isSCIMEnabled(userStoreDomainName)) { if (log.isDebugEnabled()) { log.debug("SCIM is enabled for the user-store domain : " + userStoreDomainName + ". " + "Including user : " + userName + " in the response."); } scimUser = this.getSCIMUser(userName, requiredClaims, scimToLocalClaimsMap); //if SCIM-ID is not present in the attributes, skip if (scimUser != null && StringUtils.isBlank(scimUser.getId())) { continue; } filteredUsers.add(scimUser); } else { if (log.isDebugEnabled()) { log.debug("SCIM is disabled for the user-store domain : " + userStoreDomainName + ". " + "Hence user : "+ userName + " in this domain is excluded in the response."); } } } } @Override public User getMe(String userName, Map<String, Boolean> requiredAttributes) throws CharonException, NotFoundException { if (log.isDebugEnabled()) { log.debug("Getting user: " + userName); } User scimUser; try { //get Claims related to SCIM claim dialect Map<String, String> scimToLocalClaimsMap = SCIMCommonUtils.getSCIMtoLocalMappings(); List<String> requiredClaims = getOnlyRequiredClaims(scimToLocalClaimsMap.keySet(), requiredAttributes); List<String> requiredClaimsInLocalDialect; if (MapUtils.isNotEmpty(scimToLocalClaimsMap)) { scimToLocalClaimsMap.keySet().retainAll(requiredClaims); requiredClaimsInLocalDialect = new ArrayList<>(scimToLocalClaimsMap.values()); } else { if (log.isDebugEnabled()) { log.debug("SCIM to Local Claim mappings list is empty."); } requiredClaimsInLocalDialect = new ArrayList<>(); } //we assume (since id is unique per user) only one user exists for a given id scimUser = this.getSCIMUser(userName, requiredClaimsInLocalDialect, scimToLocalClaimsMap); if (scimUser == null) { if (log.isDebugEnabled()) { log.debug("User with userName : " + userName + " does not exist in the system."); } throw new NotFoundException("No such user exist"); } else { //set the schemas of the scim user scimUser.setSchemas(); log.info("User: " + scimUser.getUserName() + " is retrieved through SCIM."); return scimUser; } } catch (UserStoreException e) { throw new CharonException("Error from getting the authenticated user", e); } } @Override public User createMe(User user, Map<String, Boolean> requiredAttributes) throws CharonException, ConflictException, BadRequestException { return createUser(user, requiredAttributes); } @Override public void deleteMe(String userName) throws NotFoundException, CharonException, NotImplementedException { String error = "Self delete is not supported"; throw new NotImplementedException(error); } @Override public User updateMe(User user, Map<String, Boolean> requiredAttributes) throws NotImplementedException, CharonException, BadRequestException { return updateUser(user, requiredAttributes); } @Override public Group createGroup(Group group, Map<String, Boolean> requiredAttributes) throws CharonException, ConflictException, BadRequestException { if (log.isDebugEnabled()) { log.debug("Creating group: " + group.getDisplayName()); } try { //modify display name if no domain is specified, in order to support multiple user store feature String originalName = group.getDisplayName(); String roleNameWithDomain = null; String domainName = ""; try { if (getUserStoreDomainFromSP() != null) { domainName = getUserStoreDomainFromSP(); roleNameWithDomain = IdentityUtil .addDomainToName(UserCoreUtil.removeDomainFromName(originalName), domainName); } else if (originalName.indexOf(CarbonConstants.DOMAIN_SEPARATOR) > 0) { domainName = IdentityUtil.extractDomainFromName(originalName); roleNameWithDomain = IdentityUtil .addDomainToName(UserCoreUtil.removeDomainFromName(originalName), domainName); } else { domainName = UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME; roleNameWithDomain = SCIMCommonUtils.getGroupNameWithDomain(originalName); } } catch (IdentityApplicationManagementException e) { throw new CharonException("Error retrieving User Store name. ", e); } if(!isInternalOrApplicationGroup(domainName) && StringUtils.isNotBlank(domainName) && !isSCIMEnabled (domainName)){ throw new CharonException("Cannot create group through scim to user store " + ". SCIM is not " + "enabled for user store " + domainName); } group.setDisplayName(roleNameWithDomain); //check if the group already exists if (carbonUM.isExistingRole(group.getDisplayName(), false)) { String error = "Group with name: " + group.getDisplayName() +" already exists in the system."; throw new ConflictException(error); } /*set thread local property to signal the downstream SCIMUserOperationListener about the provisioning route.*/ SCIMCommonUtils.setThreadLocalIsManagedThroughSCIMEP(true); /*if members are sent when creating the group, check whether users already exist in the user store*/ List<Object> userIds = group.getMembers(); List<String> userDisplayNames = group.getMembersWithDisplayName(); if (CollectionUtils.isNotEmpty(userIds)) { List<String> members = new ArrayList<>(); for (Object userId : userIds) { String userIdLocalClaim = SCIMCommonUtils.getSCIMtoLocalMappings().get(SCIMConstants .CommonSchemaConstants.ID_URI); String[] userNames = null; if (StringUtils.isNotBlank(userIdLocalClaim)) { userNames = carbonUM.getUserList(userIdLocalClaim, (String) userId, UserCoreConstants .DEFAULT_PROFILE); } if (userNames == null || userNames.length == 0) { String error = "User: " + userId + " doesn't exist in the user store. " + "Hence, can not create the group: " + group.getDisplayName(); throw new IdentitySCIMException(error); } else if (userNames[0].indexOf(UserCoreConstants.DOMAIN_SEPARATOR) > 0 && !StringUtils.containsIgnoreCase(userNames[0], domainName)) { String error = "User: " + userId + " doesn't exist in the same user store. " + "Hence, can not create the group: " + group.getDisplayName(); throw new IdentitySCIMException(error); } else { members.add(userNames[0]); if (CollectionUtils.isNotEmpty(userDisplayNames)) { boolean userContains = false; for (String user : userDisplayNames) { user = user.indexOf(UserCoreConstants.DOMAIN_SEPARATOR) > 0 ? user.split(UserCoreConstants.DOMAIN_SEPARATOR)[1] : user; if (user.equalsIgnoreCase(userNames[0].indexOf(UserCoreConstants.DOMAIN_SEPARATOR) > 0 ? userNames[0].split(UserCoreConstants.DOMAIN_SEPARATOR)[1] : userNames[0])) { userContains = true; break; } } if (!userContains) { throw new IdentitySCIMException("Given SCIM user Id and name does not match.."); } } } } //add other scim attributes in the identity DB since user store doesn't support some attributes. SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(carbonUM.getTenantId()); scimGroupHandler.createSCIMAttributes(group); carbonUM.addRole(group.getDisplayName(), members.toArray(new String[members.size()]), null, false); log.info("Group: " + group.getDisplayName() + " is created through SCIM."); } else { //add other scim attributes in the identity DB since user store doesn't support some attributes. SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(carbonUM.getTenantId()); scimGroupHandler.createSCIMAttributes(group); carbonUM.addRole(group.getDisplayName(), null, null, false); log.info("Group: " + group.getDisplayName() + " is created through SCIM."); } } catch (UserStoreException e) { try { SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(carbonUM.getTenantId()); scimGroupHandler.deleteGroupAttributes(group.getDisplayName()); } catch (UserStoreException | IdentitySCIMException ex) { log.error("Error occurred while doing rollback operation of the SCIM table entry for role: " + group.getDisplayName(), ex); throw new CharonException("Error occurred while doing rollback operation of the SCIM table entry for role: " + group.getDisplayName(), e); } throw new CharonException("Error occurred while adding role : " + group.getDisplayName(), e); } catch (IdentitySCIMException | BadRequestException e) { String error = "One or more group members do not exist in the same user store. " + "Hence, can not create the group: " + group.getDisplayName(); if (log.isDebugEnabled()) { log.debug(error, e); } throw new BadRequestException(error, ResponseCodeConstants.INVALID_VALUE); } return group; } @Override public Group getGroup(String id, Map<String, Boolean> requiredAttributes) throws CharonException { if (log.isDebugEnabled()) { log.debug("Retrieving group with id: " + id); } Group group = null; try { SCIMGroupHandler groupHandler = new SCIMGroupHandler(carbonUM.getTenantId()); //get group name by Id String groupName = groupHandler.getGroupName(id); if (groupName != null) { group = getGroupWithName(groupName); group.setSchemas(); return group; } else { //returning null will send a resource not found error to client by Charon. return null; } } catch (org.wso2.carbon.user.core.UserStoreException e) { throw new CharonException("Error in retrieving group : " + id, e); } catch (IdentitySCIMException e) { throw new CharonException("Error in retrieving SCIM Group information from database.", e); } catch (CharonException | BadRequestException e) { throw new CharonException("Error in retrieving the group", e); } } @Override public void deleteGroup(String groupId) throws NotFoundException, CharonException { if (log.isDebugEnabled()) { log.debug("Deleting group: " + groupId); } try { /*set thread local property to signal the downstream SCIMUserOperationListener about the provisioning route.*/ SCIMCommonUtils.setThreadLocalIsManagedThroughSCIMEP(true); //get group name by id SCIMGroupHandler groupHandler = new SCIMGroupHandler(carbonUM.getTenantId()); String groupName = groupHandler.getGroupName(groupId); if (groupName != null) { String userStoreDomainFromSP = null; try { userStoreDomainFromSP = getUserStoreDomainFromSP(); } catch (IdentityApplicationManagementException e) { throw new CharonException("Error retrieving User Store name. ", e); } if (userStoreDomainFromSP != null && !(userStoreDomainFromSP.equalsIgnoreCase(IdentityUtil.extractDomainFromName(groupName)))) { throw new CharonException("Group :" + groupName + "is not belong to user store " + userStoreDomainFromSP + "Hence group updating fail"); } String userStoreDomainName = IdentityUtil.extractDomainFromName(groupName); if (!isInternalOrApplicationGroup(userStoreDomainName) && StringUtils.isNotBlank(userStoreDomainName) && !isSCIMEnabled (userStoreDomainName)) { throw new CharonException("Cannot delete group: " + groupName + " through scim from user store: " + userStoreDomainName + ". SCIM is not enabled for user store: " + userStoreDomainName); } //delete group in carbon UM carbonUM.deleteRole(groupName); //we do not update Identity_SCIM DB here since it is updated in SCIMUserOperationListener's methods. log.info("Group: " + groupName + " is deleted through SCIM."); } else { if (log.isDebugEnabled()) { log.debug("Group with SCIM id: " + groupId + " doesn't exist in the system."); } throw new NotFoundException(); } } catch (UserStoreException | IdentitySCIMException e) { throw new CharonException("Error occurred while deleting group " + groupId, e); } } @Override public List<Object> listGroupsWithGET(Node rootNode, int startIndex, int count, String sortBy, String sortOrder, String domainName, Map<String, Boolean> requiredAttributes) throws CharonException, NotImplementedException, BadRequestException { if (sortBy != null || sortOrder != null) { throw new NotImplementedException("Sorting is not supported"); } else if (startIndex != 1) { throw new NotImplementedException("Pagination is not supported"); } else if (rootNode != null) { return filterGroups(rootNode, requiredAttributes); } else { return listGroups(requiredAttributes); } } private List<Object> listGroups(Map<String, Boolean> requiredAttributes) throws CharonException { List<Object> groupList = new ArrayList<>(); //0th index is to store total number of results; groupList.add(0); try { SCIMGroupHandler groupHandler = new SCIMGroupHandler(carbonUM.getTenantId()); Set<String> roleNames = groupHandler.listSCIMRoles(); for (String roleName : roleNames) { String userStoreDomainName = IdentityUtil.extractDomainFromName(roleName); if (isInternalOrApplicationGroup(userStoreDomainName) || isSCIMEnabled(userStoreDomainName)) { if (log.isDebugEnabled()) { log.debug("SCIM is enabled for the user-store domain : " + userStoreDomainName + ". " + "Including group with name : " + roleName + " in the response."); } Group group = this.getGroupWithName(roleName); if (group.getId() != null) { groupList.add(group); } } else { if (log.isDebugEnabled()) { log.debug("SCIM is disabled for the user-store domain : " + userStoreDomainName + ". Hence " + "group with name : " + roleName + " is excluded in the response."); } } } } catch (org.wso2.carbon.user.core.UserStoreException e) { String errMsg = "Error in obtaining role names from user store."; errMsg += e.getMessage(); throw new CharonException(errMsg, e); } catch (IdentitySCIMException | BadRequestException e) { throw new CharonException("Error in retrieving SCIM Group information from database.", e); } //set the totalResults value in index 0 groupList.set(0, groupList.size()-1); return groupList; } private List<Object> filterGroups(Node node, Map<String, Boolean> requiredAttributes) throws NotImplementedException, CharonException { if(node.getLeftNode() != null || node.getRightNode() != null){ String error = "Complex filters are not supported yet"; throw new NotImplementedException(error); } String attributeName = ((ExpressionNode)node).getAttributeValue(); String filterOperation = ((ExpressionNode)node).getOperation(); String attributeValue = ((ExpressionNode)node).getValue(); if (isNotFilteringSupported(filterOperation)) { String error = "System does not support filter operator: " + filterOperation; throw new NotImplementedException(error); } if (SCIMCommonUtils.isFilteringEnhancementsEnabled()) { if (SCIMCommonConstants.EQ.equalsIgnoreCase(filterOperation)) { if (StringUtils.equals(attributeName, SCIMConstants.GroupSchemaConstants.DISPLAY_NAME_URI) && !StringUtils.contains(attributeValue, CarbonConstants.DOMAIN_SEPARATOR)) { attributeValue = UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME + CarbonConstants.DOMAIN_SEPARATOR + attributeValue; } } } if (log.isDebugEnabled()) { log.debug("Listing groups with filter: " + attributeName + filterOperation + attributeValue); } List<Object> filteredGroups = new ArrayList<>(); //0th index is to store total number of results; filteredGroups.add(0); try { String[] roleList = getGroupList(attributeName, filterOperation, attributeValue); if (roleList != null) { for (String roleName : roleList) { if (roleName != null && carbonUM.isExistingRole(roleName, false)) { //skip internal roles if ((CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME.equals(roleName)) || UserCoreUtil.isEveryoneRole(roleName, carbonUM.getRealmConfiguration())) { continue; } /**construct the group name with domain -if not already provided, in order to support multiple user store feature with SCIM.**/ String groupNameWithDomain = null; if (roleName.indexOf(CarbonConstants.DOMAIN_SEPARATOR) > 0) { groupNameWithDomain = roleName; } else { groupNameWithDomain = UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME + CarbonConstants.DOMAIN_SEPARATOR + roleName; } String userStoreDomainName = IdentityUtil.extractDomainFromName(roleName); if (isInternalOrApplicationGroup(userStoreDomainName) || isSCIMEnabled(userStoreDomainName)) { if (log.isDebugEnabled()) { log.debug("SCIM is enabled for the user-store domain : " + userStoreDomainName + ". " + "Including group with name : " + roleName + " in the response."); } Group group = getGroupWithName(groupNameWithDomain); filteredGroups.add(group); } else { if (log.isDebugEnabled()) { log.debug("SCIM is disabled for the user-store domain : " + userStoreDomainName + ". Hence " + "group with name : " + roleName + " is excluded in the response."); } } } else { //returning null will send a resource not found error to client by Charon. filteredGroups.clear(); filteredGroups.add(0); return filteredGroups; } } } } catch (org.wso2.carbon.user.core.UserStoreException e) { throw new CharonException("Error in filtering groups by attribute name : " + attributeName + ", " + "attribute value : " + attributeValue + " and filter operation " + filterOperation, e); } catch (org.wso2.carbon.user.api.UserStoreException e) { throw new CharonException("Error in filtering group with filter: " + attributeName + filterOperation + attributeValue, e); } catch (IdentitySCIMException e) { throw new CharonException("Error in retrieving SCIM Group information from database.", e); } catch (BadRequestException e) { throw new CharonException("Error in retrieving SCIM Group.", e); } //set the totalResults value in index 0 filteredGroups.set(0, filteredGroups.size() - 1); return filteredGroups; } @Override public Group updateGroup(Group oldGroup, Group newGroup, Map<String, Boolean> requiredAttributes) throws CharonException { try { String userStoreDomainFromSP = getUserStoreDomainFromSP(); if(userStoreDomainFromSP != null && !userStoreDomainFromSP.equalsIgnoreCase( IdentityUtil.extractDomainFromName(oldGroup.getDisplayName()))) { throw new CharonException("Group :" + oldGroup.getDisplayName() + "is not belong to user store " + userStoreDomainFromSP + "Hence group updating fail"); } oldGroup.setDisplayName(IdentityUtil.addDomainToName(UserCoreUtil.removeDomainFromName(oldGroup.getDisplayName()), IdentityUtil.extractDomainFromName(oldGroup.getDisplayName()))); newGroup.setDisplayName(IdentityUtil.addDomainToName(UserCoreUtil.removeDomainFromName(newGroup.getDisplayName()), IdentityUtil.extractDomainFromName(newGroup.getDisplayName()))); String primaryDomain = IdentityUtil.getPrimaryDomainName(); if (IdentityUtil.extractDomainFromName(newGroup.getDisplayName()).equals(primaryDomain) && !(IdentityUtil .extractDomainFromName(oldGroup.getDisplayName()) .equals(primaryDomain))) { String userStoreDomain = IdentityUtil.extractDomainFromName(oldGroup.getDisplayName()); newGroup.setDisplayName(IdentityUtil.addDomainToName(newGroup.getDisplayName(), userStoreDomain)); } else if (!IdentityUtil.extractDomainFromName(oldGroup.getDisplayName()) .equals(IdentityUtil.extractDomainFromName(newGroup.getDisplayName()))) { throw new IdentitySCIMException( "User store domain of the group is not matching with the given SCIM group Id."); } newGroup.setDisplayName(SCIMCommonUtils.getGroupNameWithDomain(newGroup.getDisplayName())); oldGroup.setDisplayName(SCIMCommonUtils.getGroupNameWithDomain(oldGroup.getDisplayName())); if (log.isDebugEnabled()) { log.debug("Updating group: " + oldGroup.getDisplayName()); } String groupName = newGroup.getDisplayName(); String userStoreDomainForGroup = IdentityUtil.extractDomainFromName(groupName); if (newGroup.getMembers() != null && !(newGroup.getMembers().isEmpty()) && !isInternalOrApplicationGroup(userStoreDomainForGroup)) { newGroup = addDomainToUserMembers(newGroup, userStoreDomainForGroup); } boolean updated = false; /*set thread local property to signal the downstream SCIMUserOperationListener about the provisioning route.*/ SCIMCommonUtils.setThreadLocalIsManagedThroughSCIMEP(true); //check if the user ids sent in updated group exist in the user store and the associated user name //also a matching one. List<Object> userIds = newGroup.getMembers(); List<String> userDisplayNames = newGroup.getMembersWithDisplayName(); /* compare user store domain of group and user store domain of user name , if there is a mismatch do not update the group */ if (userDisplayNames != null && userDisplayNames.size() > 0) { for (String userDisplayName : userDisplayNames) { String userStoreDomainForUser = IdentityUtil.extractDomainFromName(userDisplayName); if (!isInternalOrApplicationGroup(userStoreDomainForGroup) && !userStoreDomainForGroup.equalsIgnoreCase (userStoreDomainForUser)) { throw new IdentitySCIMException( userDisplayName + " does not " + "belongs to user store " + userStoreDomainForGroup); } } } if (CollectionUtils.isNotEmpty(userIds)) { String[] userNames = null; for (Object userId : userIds) { if (userId != null) { String userIdLocalClaim = SCIMCommonUtils.getSCIMtoLocalMappings().get(SCIMConstants .CommonSchemaConstants.ID_URI); if (StringUtils.isNotBlank(userIdLocalClaim)) { userNames = carbonUM.getUserList(userIdLocalClaim, IdentityUtil.addDomainToName((String) userId, userStoreDomainForGroup), UserCoreConstants.DEFAULT_PROFILE); } if (userNames == null || userNames.length == 0) { String error = "User: " + userId + " doesn't exist in the user store. " + "Hence, can not update the group: " + oldGroup.getDisplayName(); throw new IdentitySCIMException(error); } else { if (!UserCoreUtil.isContain(UserCoreUtil.removeDomainFromName(userNames[0]), UserCoreUtil.removeDomainFromNames(userDisplayNames.toArray( new String[userDisplayNames.size()])))) { throw new IdentitySCIMException("Given SCIM user Id and name not matching.."); } } } } } //we do not update Identity_SCIM DB here since it is updated in SCIMUserOperationListener's methods. //update name if it is changed if (!(oldGroup.getDisplayName().equalsIgnoreCase(newGroup.getDisplayName()))) { //update group name in carbon UM carbonUM.updateRoleName(oldGroup.getDisplayName(), newGroup.getDisplayName()); updated = true; } //find out added members and deleted members.. List<String> oldMembers = oldGroup.getMembersWithDisplayName(); List<String> newMembers = newGroup.getMembersWithDisplayName(); if (newMembers != null) { List<String> addedMembers = new ArrayList<>(); List<String> deletedMembers = new ArrayList<>(); //check for deleted members if (CollectionUtils.isNotEmpty(oldMembers)) { for (String oldMember : oldMembers) { if (newMembers != null && newMembers.contains(oldMember)) { continue; } deletedMembers.add(oldMember); } } //check for added members if (CollectionUtils.isNotEmpty(newMembers)) { for (String newMember : newMembers) { if (oldMembers != null && oldMembers.contains(newMember)) { continue; } addedMembers.add(newMember); } } if (CollectionUtils.isNotEmpty(addedMembers) || CollectionUtils.isNotEmpty(deletedMembers)) { carbonUM.updateUserListOfRole(newGroup.getDisplayName(), deletedMembers.toArray(new String[deletedMembers.size()]), addedMembers.toArray(new String[addedMembers.size()])); updated = true; } } if (updated) { log.info("Group: " + oldGroup.getDisplayName() + " is updated through SCIM."); } else { log.warn("There is no updated field in the group: " + oldGroup.getDisplayName() + ". Therefore ignoring the provisioning."); } } catch (UserStoreException | IdentitySCIMException e) { throw new CharonException(e.getMessage(), e); } catch (IdentityApplicationManagementException e){ throw new CharonException("Error retrieving User Store name. ", e); } catch (BadRequestException | CharonException e) { throw new CharonException("Error in updating the group", e); } return newGroup; } @Override public List<Object> listGroupsWithPost(SearchRequest searchRequest, Map<String, Boolean> requiredAttributes) throws BadRequestException, NotImplementedException, CharonException { return listGroupsWithGET(searchRequest.getFilter(), searchRequest.getStartIndex(), searchRequest.getCount(), searchRequest.getSortBy(), searchRequest.getSortOder(), searchRequest.getDomainName(), requiredAttributes); } private String getUserStoreDomainFromSP() throws IdentityApplicationManagementException { ServiceProvider serviceProvider = null; if (serviceProvider != null && serviceProvider.getInboundProvisioningConfig() != null && !StringUtils.isBlank(serviceProvider.getInboundProvisioningConfig().getProvisioningUserStore())) { return serviceProvider.getInboundProvisioningConfig().getProvisioningUserStore(); } return null; } /** * This method will return whether SCIM is enabled or not for a particular userStore. (from SCIMEnabled user * store property) * @param userStoreName user store name * @return whether scim is enabled or not for the particular user store */ private boolean isSCIMEnabled(String userStoreName) { UserStoreManager userStoreManager = carbonUM.getSecondaryUserStoreManager(userStoreName); if (userStoreManager != null) { try { return userStoreManager.isSCIMEnabled(); } catch (UserStoreException e) { log.error("Error while evaluating isSCIMEnalbed for user store " + userStoreName, e); } } return false; } /** * get the specfied user from the store * @param userName * @param claimURIList * @return * @throws CharonException */ private User getSCIMUser(String userName, List<String> claimURIList, Map<String, String> scimToLocalClaimsMap) throws CharonException { User scimUser = null; String userStoreDomainName = IdentityUtil.extractDomainFromName(userName); if(StringUtils.isNotBlank(userStoreDomainName) && !isSCIMEnabled(userStoreDomainName)){ throw new CharonException("Cannot get user through scim to user store " + ". SCIM is not " + "enabled for user store " + userStoreDomainName); } try { //obtain user claim values Map<String, String> userClaimValues = carbonUM.getUserClaimValues( userName, claimURIList.toArray(new String[claimURIList.size()]), null); Map<String, String> attributes = SCIMCommonUtils.convertLocalToSCIMDialect(userClaimValues, scimToLocalClaimsMap); if (!attributes.containsKey(SCIMConstants.CommonSchemaConstants.ID_URI)) { return scimUser; } //skip simple type addresses claim because it is complex with sub types in the schema if (attributes.containsKey(SCIMConstants.UserSchemaConstants.ADDRESSES_URI)) { attributes.remove(SCIMConstants.UserSchemaConstants.ADDRESSES_URI); } // Add username with domain name attributes.put(SCIMConstants.UserSchemaConstants.USER_NAME_URI, userName); //get groups of user and add it as groups attribute String[] roles = carbonUM.getRoleListOfUser(userName); //construct the SCIM Object from the attributes scimUser = (User) AttributeMapper.constructSCIMObjectFromAttributes(attributes, 1); Map<String, Group> groupMetaAttributesCache = new HashMap<>(); //add groups of user: for (String role : roles) { if (UserCoreUtil.isEveryoneRole(role, carbonUM.getRealmConfiguration()) || CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME.equalsIgnoreCase(role) || role.toLowerCase().startsWith((UserCoreConstants.INTERNAL_DOMAIN + CarbonConstants.DOMAIN_SEPARATOR).toLowerCase())) { // carbon specific roles do not possess SCIM info, hence // skipping them. // skip intenal roles continue; } if (SCIMCommonUtils.isFilteringEnhancementsEnabled()) { if (!StringUtils.contains(role, CarbonConstants.DOMAIN_SEPARATOR)) { role = UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME + CarbonConstants.DOMAIN_SEPARATOR + role; } } Group group = groupMetaAttributesCache.get(role); if (group == null && !groupMetaAttributesCache.containsKey(role)) { group = getGroupOnlyWithMetaAttributes(role); groupMetaAttributesCache.put(role, group); } if (group != null) { // can be null for non SCIM groups scimUser.setGroup(null, group.getId(), role); } } } catch (UserStoreException | CharonException | NotFoundException | IdentitySCIMException |BadRequestException e) { throw new CharonException("Error in getting user information for user: " + userName, e); } return scimUser; } /** * get the specified user from the store * * @param userNames Array of usernames * @param claimURIList Requested claim list * @return Array of SCIM User * @throws CharonException CharonException */ private User[] getSCIMUsers(String[] userNames, List<String> claimURIList, Map<String, String> scimToLocalClaimsMap) throws CharonException { List<User> scimUsers = new ArrayList<>(); //obtain user claim values UserClaimSearchEntry[] searchEntries; Map<String, List<String>> usersRoles; try { searchEntries = ((AbstractUserStoreManager) carbonUM).getUsersClaimValues( userNames, claimURIList.toArray(new String[claimURIList.size()]), null); usersRoles = ((AbstractUserStoreManager) carbonUM).getRoleListOfUsers(userNames); } catch (org.wso2.carbon.user.core.UserStoreException e) { throw new CharonException("Error occurred while retrieving SCIM user information", e); } Map<String, Group> groupMetaAttributesCache = new HashMap<>(); for (String userName : userNames) { String userStoreDomainName = IdentityUtil.extractDomainFromName(userName); if (isSCIMEnabled(userStoreDomainName)) { if (log.isDebugEnabled()) { log.debug("SCIM is enabled for the user-store domain : " + userStoreDomainName + ". " + "Including user : " + userName + " in the response."); } User scimUser; Map<String, String> userClaimValues = new HashMap<>(); for (UserClaimSearchEntry entry : searchEntries) { if (StringUtils.isNotBlank(entry.getUserName()) && entry.getUserName().equals(userName)) { userClaimValues = entry.getClaims(); } } Map<String, String> attributes; try { attributes = SCIMCommonUtils.convertLocalToSCIMDialect(userClaimValues, scimToLocalClaimsMap); } catch (UserStoreException e) { throw new CharonException("Error in converting local claims to SCIM dialect for user: " + userName, e); } try { if (!attributes.containsKey(SCIMConstants.CommonSchemaConstants.ID_URI)) { continue; } //skip simple type addresses claim because it is complex with sub types in the schema if (attributes.containsKey(SCIMConstants.UserSchemaConstants.ADDRESSES_URI)) { attributes.remove(SCIMConstants.UserSchemaConstants.ADDRESSES_URI); } // Add username with domain name attributes.put(SCIMConstants.UserSchemaConstants.USER_NAME_URI, userName); //get groups of user and add it as groups attribute List<String> roleList = usersRoles.get(userName); String[] roles = new String[0]; if (CollectionUtils.isNotEmpty(roleList)) { roles = roleList.toArray(new String[0]); } //construct the SCIM Object from the attributes scimUser = (User) AttributeMapper.constructSCIMObjectFromAttributes(attributes, 1); //add groups of user for (String role : roles) { if (UserCoreUtil.isEveryoneRole(role, carbonUM.getRealmConfiguration()) || CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME.equalsIgnoreCase(role) || role.toLowerCase().startsWith((UserCoreConstants.INTERNAL_DOMAIN + CarbonConstants.DOMAIN_SEPARATOR).toLowerCase())) { // carbon specific roles do not possess SCIM info, hence // skipping them. // skip internal roles continue; } if (SCIMCommonUtils.isFilteringEnhancementsEnabled()) { if (!StringUtils.contains(role, CarbonConstants.DOMAIN_SEPARATOR)) { role = UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME + CarbonConstants.DOMAIN_SEPARATOR + role; } } Group group = groupMetaAttributesCache.get(role); if (group == null && !groupMetaAttributesCache.containsKey(role)) { group = getGroupOnlyWithMetaAttributes(role); groupMetaAttributesCache.put(role, group); } if (group != null) { // can be null for non SCIM groups scimUser.setGroup(null, group.getId(), role); } } } catch (UserStoreException | CharonException | NotFoundException | IdentitySCIMException | BadRequestException e) { throw new CharonException("Error in getting user information for user: " + userName, e); } if (scimUser != null) { scimUsers.add(scimUser); } } else { if (log.isDebugEnabled()) { log.debug("SCIM is disabled for the user-store domain : " + userStoreDomainName + ". " + "Hence user : "+ userName + " in this domain is excluded in the response."); } } } return scimUsers.toArray(new User[0]); } /** * Get group with only meta attributes. * * @param groupName * @return * @throws CharonException * @throws IdentitySCIMException * @throws org.wso2.carbon.user.core.UserStoreException */ private Group getGroupOnlyWithMetaAttributes(String groupName) throws CharonException, IdentitySCIMException, org.wso2.carbon.user.core.UserStoreException, BadRequestException { //get other group attributes and set. Group group = new Group(); group.setDisplayName(groupName); SCIMGroupHandler groupHandler = new SCIMGroupHandler(carbonUM.getTenantId()); return groupHandler.getGroupWithAttributes(group, groupName); } /** * returns whether particular user store domain is application or internal. * @param userstoreDomain user store domain * @return whether passed domain name is "internal" or "application" */ private boolean isInternalOrApplicationGroup(String userstoreDomain){ if(StringUtils.isNotBlank(userstoreDomain) && (SCIMCommonConstants.APPLICATION_DOMAIN.equalsIgnoreCase(userstoreDomain) || SCIMCommonConstants.INTERNAL_DOMAIN.equalsIgnoreCase(userstoreDomain))){ return true; } return false; } /** * Get the full group with all the details including users. * * @param groupName * @return * @throws CharonException * @throws org.wso2.carbon.user.core.UserStoreException * @throws IdentitySCIMException */ private Group getGroupWithName(String groupName) throws CharonException, org.wso2.carbon.user.core.UserStoreException, IdentitySCIMException, BadRequestException { String userStoreDomainName = IdentityUtil.extractDomainFromName(groupName); if(!isInternalOrApplicationGroup(userStoreDomainName) && StringUtils.isNotBlank(userStoreDomainName) && !isSCIMEnabled(userStoreDomainName)){ throw new CharonException("Cannot retrieve group through scim to user store " + ". SCIM is not " + "enabled for user store " + userStoreDomainName); } Group group = new Group(); group.setDisplayName(groupName); String[] userNames = carbonUM.getUserListOfRole(groupName); //get the ids of the users and set them in the group with id + display name if (userNames != null && userNames.length != 0) { for (String userName : userNames) { String userId = carbonUM.getUserClaimValue(userName, SCIMConstants.CommonSchemaConstants.ID_URI, null); group.setMember(userId, userName); } } //get other group attributes and set. SCIMGroupHandler groupHandler = new SCIMGroupHandler(carbonUM.getTenantId()); group = groupHandler.getGroupWithAttributes(group, groupName); return group; } /** * This is used to add domain name to the members of a group * * @param group * @param userStoreDomain * @return * @throws CharonException */ private Group addDomainToUserMembers(Group group, String userStoreDomain) throws CharonException { List<Object> membersId = group.getMembers(); if (StringUtils.isBlank(userStoreDomain) || membersId == null || membersId.isEmpty()) { return group; } if (group.isAttributeExist(SCIMConstants.GroupSchemaConstants.MEMBERS)) { MultiValuedAttribute members = (MultiValuedAttribute) group.getAttributeList().get( SCIMConstants.GroupSchemaConstants.MEMBERS); List<Attribute> attributeValues = members.getAttributeValues(); if (attributeValues != null && !attributeValues.isEmpty()) { for (Attribute attributeValue : attributeValues) { SimpleAttribute displayNameAttribute = (SimpleAttribute) attributeValue.getSubAttribute( SCIMConstants.CommonSchemaConstants.DISPLAY); String displayName = AttributeUtil.getStringValueOfAttribute(displayNameAttribute.getValue(), displayNameAttribute.getType()); displayNameAttribute.setValue(IdentityUtil.addDomainToName( UserCoreUtil.removeDomainFromName(displayName), userStoreDomain)); } } } return group; } private List<String> getMappedClaimList(Map<String, Boolean> requiredAttributes){ ArrayList<String> claimsList = new ArrayList<>(); for(Map.Entry<String, Boolean> claim : requiredAttributes.entrySet()){ if(claim.getValue().equals(true)){ } else { claimsList.add(claim.getKey()); } } return claimsList; } /* * This returns the only required attributes for value querying * @param claimURIList * @param requiredAttributes * @return */ private List<String> getOnlyRequiredClaims(Set<String> claimURIList, Map<String, Boolean> requiredAttributes) { List<String> requiredClaimList = new ArrayList<>(); for(String requiredClaim : requiredAttributes.keySet()) { if(requiredAttributes.get(requiredClaim)) { if (claimURIList.contains(requiredClaim)) { requiredClaimList.add(requiredClaim); } else { String[] parts = requiredClaim.split("[.]"); for (String claim : claimURIList) { if (parts.length == 3) { if (claim.contains(parts[0] +"." + parts[1])) { if (!requiredClaimList.contains(claim)) { requiredClaimList.add(claim); } } } else if (parts.length == 2) { if (claim.contains(parts[0])) { if (!requiredClaimList.contains(claim)) { requiredClaimList.add(claim); } } } } } } else { if (!requiredClaimList.contains(requiredClaim)) { requiredClaimList.add(requiredClaim); } } } return requiredClaimList; } /** * Paginate a list of users names according to a given offset and a count. * * @param users A list of unpaginated users. * @param limit The total number of results required (Zero will return all the users). * @param offset The starting index of the count (limit). * @return A list of paginated users */ private String[] paginateUsers(String[] users, int limit, int offset) { // If the results are empty, an empty list should be returned. if (users == null) { return new String[0]; } Arrays.sort(users); // Validate offset value. if (offset <= 0) { offset = 1; } // If the results is less than the offset return an empty user list. if (offset > users.length) { return new String[0]; } // If the limit is zero, all the users needs to be returned after verifying the offset. if (limit <= 0) { if (offset == 1) { // This is to support backward compatibility. return users; } else { return Arrays.copyOfRange(users, offset - 1, users.length); } } else { // If users.length > limit + offset, then return only the users bounded by the offset and the limit. if (users.length > limit + offset) { return Arrays.copyOfRange(users, offset - 1, limit + offset - 1); } else { // Return all the users from the offset. return Arrays.copyOfRange(users, offset - 1, users.length); } } } /** * check whether the filtering is supported * @param filterOperation operator use for filtering * @return boolean to check whether operator is supported */ private boolean isNotFilteringSupported(String filterOperation) { return !filterOperation.equalsIgnoreCase(SCIMCommonConstants.EQ) && !filterOperation.equalsIgnoreCase(SCIMCommonConstants.CO) && !filterOperation.equalsIgnoreCase(SCIMCommonConstants.SW) && !filterOperation.equalsIgnoreCase(SCIMCommonConstants.EW); } private String[] getUserListOfRoles(String[] roleNames) throws org.wso2.carbon.user.core.UserStoreException { String[] userNames; Set<String> users = new HashSet<>(); if (roleNames != null) { for (String roleName : roleNames) { users.addAll(Arrays.asList(carbonUM.getUserListOfRole(roleName))); } } userNames = users.toArray(new String[0]); return userNames; } /** * get the search value after appending the delimiters * @param filterOperation operator value * @param attributeValue search value * @param delimiter delimiter for based on search type * @return search attribute */ private String getSearchAttribute(String filterOperation, String attributeValue, String delimiter) { String searchAttribute = null; if (filterOperation.equalsIgnoreCase(SCIMCommonConstants.CO)) { String[] attributeItems = attributeValue.split(CarbonConstants.DOMAIN_SEPARATOR); if(attributeItems.length == 2) { searchAttribute = attributeItems[0] + CarbonConstants.DOMAIN_SEPARATOR + delimiter + attributeItems[1] + delimiter; } else { searchAttribute = delimiter + attributeValue + delimiter; } } else if (filterOperation.equalsIgnoreCase(SCIMCommonConstants.SW)) { searchAttribute = attributeValue + delimiter; } else if (filterOperation.equalsIgnoreCase(SCIMCommonConstants.EW)) { // Extract the domain attached to the attribute value and then append the delimiter. String[] attributeItems = attributeValue.split(CarbonConstants.DOMAIN_SEPARATOR); if (attributeItems.length == 2) { searchAttribute = attributeItems[0] + CarbonConstants.DOMAIN_SEPARATOR + delimiter + attributeItems[1]; } else { searchAttribute = delimiter + attributeValue; } } else if (filterOperation.equalsIgnoreCase(SCIMCommonConstants.EQ)) { searchAttribute = attributeValue; } return searchAttribute; } /** * get list of roles that matches the search criteria * @param filterOperation operator value * @param attributeValue search value * @return list of role names * @throws org.wso2.carbon.user.core .UserStoreException */ private String[] getRoleNames(String filterOperation, String attributeValue) throws org.wso2.carbon.user.core .UserStoreException { String searchAttribute = getSearchAttribute(filterOperation, attributeValue, FILTERING_DELIMITER); return ((AbstractUserStoreManager) carbonUM).getRoleNames(searchAttribute, MAX_ITEM_LIMIT_UNLIMITED, true, true, true); } /** * get list of user that matches the search criteria * @param attributeName field name for search * @param filterOperation operator * @param attributeValue search value * @return list of users * @throws org.wso2.carbon.user.core.UserStoreException */ private String[] getUserNames(String attributeName, String filterOperation, String attributeValue) throws org.wso2.carbon.user.core.UserStoreException { String searchAttribute = getSearchAttribute(filterOperation, attributeValue, FILTERING_DELIMITER); String attributeNameInLocalDialect = SCIMCommonUtils.getSCIMtoLocalMappings().get(attributeName); if (StringUtils.isBlank(attributeNameInLocalDialect)) { attributeNameInLocalDialect = attributeName; } return carbonUM.getUserList(attributeNameInLocalDialect, searchAttribute, UserCoreConstants.DEFAULT_PROFILE); } /** * get the list of groups that matches the search criteria * @param attributeName attribute which is used to search * @param filterOperation operator value * @param attributeValue search value * @return list of user groups * @throws org.wso2.carbon.user.core.UserStoreException * @throws IdentitySCIMException */ private String[] getGroupList(String attributeName, String filterOperation, String attributeValue) throws org.wso2.carbon.user.core.UserStoreException, IdentitySCIMException { String[] userRoleList; if (attributeName.equals(SCIMConstants.GroupSchemaConstants.DISPLAY_URI) || attributeName.equals(SCIMConstants.GroupSchemaConstants.VALUE_URI)) { String[] userList; if (attributeName.equals(SCIMConstants.GroupSchemaConstants.DISPLAY_URI)) { userList = getUserNames(SCIMConstants.UserSchemaConstants.USER_NAME_URI, filterOperation, attributeValue); } else { userList = getUserNames(SCIMConstants.CommonSchemaConstants.ID_URI, filterOperation, attributeValue); } Set<String> fullRoleList = new HashSet<>(); List<String> currentRoleList; if (userList != null) { for (String userName : userList) { String[] roles = carbonUM.getRoleListOfUser(userName); currentRoleList = Arrays.asList(roles); fullRoleList.addAll(currentRoleList); } } userRoleList = fullRoleList.toArray(new String[fullRoleList.size()]); } else if (attributeName.equals(SCIMConstants.GroupSchemaConstants.DISPLAY_NAME_URI)) { userRoleList = getRoleNames(filterOperation, attributeValue); } else { userRoleList = getGroupNamesFromDB(attributeName, filterOperation, attributeValue); } return userRoleList; } /** * return when search using meta data; list of groups * @param attributeName attribute which is used to search * @param filterOperation operator value * @param attributeValue search value * @return list of groups * @throws org.wso2.carbon.user.core.UserStoreException * @throws IdentitySCIMException */ private String[] getGroupNamesFromDB(String attributeName, String filterOperation, String attributeValue) throws org.wso2.carbon.user.core.UserStoreException, IdentitySCIMException { String searchAttribute = getSearchAttribute(filterOperation, attributeValue, SQL_FILTERING_DELIMITER); SCIMGroupHandler groupHandler = new SCIMGroupHandler(carbonUM.getTenantId()); return groupHandler.getGroupListFromAttributeName(attributeName, searchAttribute); } private boolean isPaginatedUserStoreAvailable() { String enablePaginatedUserStore = IdentityUtil.getProperty(ENABLE_PAGINATED_USER_STORE); if (StringUtils.isNotBlank(enablePaginatedUserStore)) { return Boolean.parseBoolean(enablePaginatedUserStore); } return true; } /** * Check whether claim is an immutable claim. * * @param claim claim URI. * @return */ private boolean isImmutableClaim(String claim) throws UserStoreException { Map<String, String> claimMappings = SCIMCommonUtils.getSCIMtoLocalMappings(); return claim.equals(claimMappings.get(SCIMConstants.CommonSchemaConstants.ID_URI)) || claim.equals(claimMappings.get(SCIMConstants.UserSchemaConstants.USER_NAME_URI)) || claim.equals(claimMappings.get(SCIMConstants.UserSchemaConstants.ROLES_URI + "." + SCIMConstants.DEFAULT)) || claim.equals(claimMappings.get(SCIMConstants.CommonSchemaConstants.CREATED_URI)) || claim.equals(claimMappings.get(SCIMConstants.CommonSchemaConstants.LAST_MODIFIED_URI)) || claim.equals(claimMappings.get(SCIMConstants.CommonSchemaConstants.LOCATION_URI)) || claim.equals(claimMappings.get(SCIMConstants.UserSchemaConstants.FAMILY_NAME_URI)) || claim.contains(UserCoreConstants.ClaimTypeURIs.IDENTITY_CLAIM_URI); } /** * Get the local claims mapped to the required scim claims. */ private List<String> getRequiredClaimsInLocalDialect(Map<String, String> scimToLocalClaimsMap, Map<String, Boolean> requiredAttributes) throws UserStoreException { List<String> requiredClaims = getOnlyRequiredClaims(scimToLocalClaimsMap.keySet(), requiredAttributes); List<String> requiredClaimsInLocalDialect; if (MapUtils.isNotEmpty(scimToLocalClaimsMap)) { scimToLocalClaimsMap.keySet().retainAll(requiredClaims); requiredClaimsInLocalDialect = new ArrayList<>(scimToLocalClaimsMap.values()); } else { if (log.isDebugEnabled()) { log.debug("SCIM to Local Claim mappings list is empty."); } requiredClaimsInLocalDialect = new ArrayList<>(); } return requiredClaimsInLocalDialect; } }
components/org.wso2.carbon.identity.scim2.common/src/main/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManager.java
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.scim2.common.impl; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException; import org.wso2.carbon.identity.application.common.model.ServiceProvider; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.mgt.policy.PolicyViolationException; import org.wso2.carbon.identity.scim2.common.exceptions.IdentitySCIMException; import org.wso2.carbon.identity.scim2.common.group.SCIMGroupHandler; import org.wso2.carbon.identity.scim2.common.utils.AttributeMapper; import org.wso2.carbon.identity.scim2.common.utils.SCIMCommonConstants; import org.wso2.carbon.identity.scim2.common.utils.SCIMCommonUtils; import org.wso2.carbon.user.api.ClaimMapping; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.core.PaginatedUserStoreManager; import org.wso2.carbon.user.core.UserCoreConstants; import org.wso2.carbon.user.core.UserStoreManager; import org.wso2.carbon.user.core.claim.ClaimManager; import org.wso2.carbon.user.core.common.AbstractUserStoreManager; import org.wso2.carbon.user.core.model.Condition; import org.wso2.carbon.user.core.model.ExpressionAttribute; import org.wso2.carbon.user.core.model.ExpressionCondition; import org.wso2.carbon.user.core.model.ExpressionOperation; import org.wso2.carbon.user.core.model.OperationalCondition; import org.wso2.carbon.user.core.model.OperationalOperation; import org.wso2.carbon.user.core.model.UserClaimSearchEntry; import org.wso2.carbon.user.core.util.UserCoreUtil; import org.wso2.charon3.core.attributes.Attribute; import org.wso2.charon3.core.attributes.MultiValuedAttribute; import org.wso2.charon3.core.attributes.SimpleAttribute; import org.wso2.charon3.core.config.SCIMUserSchemaExtensionBuilder; import org.wso2.charon3.core.exceptions.BadRequestException; import org.wso2.charon3.core.exceptions.CharonException; import org.wso2.charon3.core.exceptions.ConflictException; import org.wso2.charon3.core.exceptions.NotFoundException; import org.wso2.charon3.core.exceptions.NotImplementedException; import org.wso2.charon3.core.extensions.UserManager; import org.wso2.charon3.core.objects.Group; import org.wso2.charon3.core.objects.User; import org.wso2.charon3.core.protocol.ResponseCodeConstants; import org.wso2.charon3.core.schema.SCIMConstants; import org.wso2.charon3.core.schema.SCIMResourceSchemaManager; import org.wso2.charon3.core.schema.SCIMResourceTypeSchema; import org.wso2.charon3.core.utils.AttributeUtil; import org.wso2.charon3.core.utils.ResourceManagerUtil; import org.wso2.charon3.core.utils.codeutils.ExpressionNode; import org.wso2.charon3.core.utils.codeutils.Node; import org.wso2.charon3.core.utils.codeutils.OperationNode; import org.wso2.charon3.core.utils.codeutils.SearchRequest; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class SCIMUserManager implements UserManager { public static final String FILTERING_DELIMITER = "*"; public static final String SQL_FILTERING_DELIMITER = "%"; private static final String ERROR_CODE_INVALID_USERNAME = "31301"; private static final String ERROR_CODE_INVALID_CREDENTIAL = "30003"; private static Log log = LogFactory.getLog(SCIMUserManager.class); private UserStoreManager carbonUM = null; private ClaimManager carbonClaimManager = null; private static final int MAX_ITEM_LIMIT_UNLIMITED = -1; private static final String ENABLE_PAGINATED_USER_STORE = "SCIM.EnablePaginatedUserStore"; public SCIMUserManager(UserStoreManager carbonUserStoreManager, ClaimManager claimManager) { carbonUM = carbonUserStoreManager; carbonClaimManager = claimManager; } @Override public User createUser(User user, Map<String, Boolean> requiredAttributes) throws CharonException, ConflictException, BadRequestException { String userStoreName = null; try { String userStoreDomainFromSP = getUserStoreDomainFromSP(); if (userStoreDomainFromSP != null) { userStoreName = userStoreDomainFromSP; } } catch (IdentityApplicationManagementException e) { throw new CharonException("Error retrieving User Store name. ", e); } StringBuilder userName = new StringBuilder(); if (StringUtils.isNotBlank(userStoreName)) { // if we have set a user store under provisioning configuration - we should only use that. String currentUserName = user.getUserName(); currentUserName = UserCoreUtil.removeDomainFromName(currentUserName); user.setUserName(userName.append(userStoreName) .append(CarbonConstants.DOMAIN_SEPARATOR).append(currentUserName) .toString()); } String userStoreDomainName = IdentityUtil.extractDomainFromName(user.getUserName()); if (!user.getUserName().contains(CarbonConstants.DOMAIN_SEPARATOR) && !UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME.equalsIgnoreCase(userStoreDomainName)) { user.setUserName(IdentityUtil.addDomainToName(user.getUserName(), userStoreDomainName)); } if(StringUtils.isNotBlank(userStoreDomainName) && !isSCIMEnabled(userStoreDomainName)){ throw new CharonException("Cannot add user through scim to user store " + ". SCIM is not " + "enabled for user store " + userStoreDomainName); } try { //Persist in carbon user store if (log.isDebugEnabled()) { log.debug("Creating user: " + user.getUserName()); } /*set thread local property to signal the downstream SCIMUserOperationListener about the provisioning route.*/ SCIMCommonUtils.setThreadLocalIsManagedThroughSCIMEP(true); Map<String, String> claimsMap = AttributeMapper.getClaimsMap(user); /*skip groups attribute since we map groups attribute to actual groups in ldap. and do not update it as an attribute in user schema*/ if (claimsMap.containsKey(SCIMConstants.UserSchemaConstants.GROUP_URI)) { claimsMap.remove(SCIMConstants.UserSchemaConstants.GROUP_URI); } /* Skip roles list since we map SCIM groups to local roles internally. It shouldn't be allowed to manipulate SCIM groups from user endpoint as this attribute has a mutability of "readOnly". Group changes must be applied via Group Resource */ if (claimsMap.containsKey(SCIMConstants.UserSchemaConstants.ROLES_URI + "." + SCIMConstants.DEFAULT)) { claimsMap.remove(SCIMConstants.UserSchemaConstants.ROLES_URI); } if (carbonUM.isExistingUser(user.getUserName())) { String error = "User with the name: " + user.getUserName() + " already exists in the system."; throw new ConflictException(error); } if (claimsMap.containsKey(SCIMConstants.UserSchemaConstants.USER_NAME_URI)) { claimsMap.remove(SCIMConstants.UserSchemaConstants.USER_NAME_URI); } Map<String, String> claimsInLocalDialect = SCIMCommonUtils.convertSCIMtoLocalDialect(claimsMap); carbonUM.addUser(user.getUserName(), user.getPassword(), null, claimsInLocalDialect, null); log.info("User: " + user.getUserName() + " is created through SCIM."); } catch (UserStoreException e) { handleErrorsOnUserNameAndPasswordPolicy(e); String errMsg = "Error in adding the user: " + user.getUserName() + " to the user store. "; errMsg += e.getMessage(); throw new CharonException(errMsg, e); } return user; } private void handleErrorsOnUserNameAndPasswordPolicy(Throwable e) throws BadRequestException { int i = 0; // this variable is used to avoid endless loop if the e.getCause never becomes null. while (e != null && i < 10) { if (e instanceof UserStoreException && (e.getMessage().contains(ERROR_CODE_INVALID_USERNAME) || e.getMessage().contains(ERROR_CODE_INVALID_CREDENTIAL))) { throw new BadRequestException(e.getMessage(), ResponseCodeConstants.INVALID_VALUE); } if (e instanceof PolicyViolationException) { throw new BadRequestException(e.getMessage(), ResponseCodeConstants.INVALID_VALUE); } e = e.getCause(); i++; } } @Override public User getUser(String userId, Map<String, Boolean> requiredAttributes) throws CharonException { if (log.isDebugEnabled()) { log.debug("Retrieving user: " + userId); } User scimUser; try { //get the user name of the user with this id String userIdLocalClaim = SCIMCommonUtils.getSCIMtoLocalMappings().get(SCIMConstants .CommonSchemaConstants.ID_URI); String[] userNames = null; if (StringUtils.isNotBlank(userIdLocalClaim)) { userNames = carbonUM.getUserList(userIdLocalClaim, userId, UserCoreConstants.DEFAULT_PROFILE); } if (userNames == null || userNames.length == 0) { if (log.isDebugEnabled()) { log.debug("User with SCIM id: " + userId + " does not exist in the system."); } return null; } else { //get Claims related to SCIM claim dialect Map<String, String> scimToLocalClaimsMap = SCIMCommonUtils.getSCIMtoLocalMappings(); List<String> requiredClaims = getOnlyRequiredClaims(scimToLocalClaimsMap.keySet(), requiredAttributes); List<String> requiredClaimsInLocalDialect; if (MapUtils.isNotEmpty(scimToLocalClaimsMap)) { scimToLocalClaimsMap.keySet().retainAll(requiredClaims); requiredClaimsInLocalDialect = new ArrayList<>(scimToLocalClaimsMap.values()); } else { if (log.isDebugEnabled()) { log.debug("SCIM to Local Claim mappings list is empty."); } requiredClaimsInLocalDialect = new ArrayList<>(); } //we assume (since id is unique per user) only one user exists for a given id scimUser = this.getSCIMUser(userNames[0], requiredClaimsInLocalDialect, scimToLocalClaimsMap); //set the schemas of the scim user scimUser.setSchemas(); log.info("User: " + scimUser.getUserName() + " is retrieved through SCIM."); } } catch (UserStoreException e) { throw new CharonException("Error in getting user information from Carbon User Store for" + "user: " + userId, e); } return scimUser; } @Override public void deleteUser(String userId) throws NotFoundException, CharonException { if (log.isDebugEnabled()) { log.debug("Deleting user: " + userId); } //get the user name of the user with this id String[] userNames = null; String userName = null; try { /*set thread local property to signal the downstream SCIMUserOperationListener about the provisioning route.*/ SCIMCommonUtils.setThreadLocalIsManagedThroughSCIMEP(true); String userIdLocalClaim = SCIMCommonUtils.getSCIMtoLocalMappings().get(SCIMConstants .CommonSchemaConstants.ID_URI); if (StringUtils.isNotBlank(userIdLocalClaim)) { userNames = carbonUM.getUserList(userIdLocalClaim, userId, UserCoreConstants.DEFAULT_PROFILE); } String userStoreDomainFromSP = null; try { userStoreDomainFromSP = getUserStoreDomainFromSP(); } catch (IdentityApplicationManagementException e) { throw new CharonException("Error retrieving User Store name. ", e); } if (userNames == null || userNames.length == 0) { //resource with given id not found if (log.isDebugEnabled()) { log.debug("User with id: " + userId + " not found."); } throw new NotFoundException(); } else if (userStoreDomainFromSP != null && !(userStoreDomainFromSP .equalsIgnoreCase(IdentityUtil.extractDomainFromName(userNames[0])))) { throw new CharonException("User :" + userNames[0] + "is not belong to user store " + userStoreDomainFromSP + "Hence user updating fail"); } else { //we assume (since id is unique per user) only one user exists for a given id userName = userNames[0]; String userStoreDomainName = IdentityUtil.extractDomainFromName(userName); //check if SCIM is enabled for the user store if (!isSCIMEnabled(userStoreDomainName)) { throw new CharonException("Cannot delete user: " + userName + " through SCIM from user store: " + userStoreDomainName + ". SCIM is not enabled for user store: " + userStoreDomainName); } carbonUM.deleteUser(userName); log.info("User: " + userName + " is deleted through SCIM."); } } catch (org.wso2.carbon.user.core.UserStoreException e) { throw new CharonException("Error in deleting user: " + userName, e); } } @Override public List<Object> listUsersWithGET(Node rootNode, int startIndex, int count, String sortBy, String sortOrder, String domainName, Map<String, Boolean> requiredAttributes) throws CharonException, NotImplementedException { if (sortBy != null || sortOrder != null) { throw new NotImplementedException("Sorting is not supported"); } else if (rootNode != null) { return filterUsers(rootNode, requiredAttributes, startIndex, count, sortBy, sortOrder, domainName); } else { return listUsers(requiredAttributes, startIndex, count, sortBy, sortOrder, domainName); } } @Override public List<Object> listUsersWithPost(SearchRequest searchRequest, Map<String, Boolean> requiredAttributes) throws CharonException, NotImplementedException, BadRequestException { return listUsersWithGET(searchRequest.getFilter(), searchRequest.getStartIndex(), searchRequest.getCount(), searchRequest.getSortBy(), searchRequest.getSortOder(), searchRequest.getDomainName(), requiredAttributes); } /** * Method to list users for given conditions. * * @param requiredAttributes Required attributes for the response * @param offset Starting index of the count * @param limit Counting value * @param sortBy SortBy * @param sortOrder Sorting order * @param domainName Name of the user store * @return User list with detailed attributes * @throws CharonException Error while listing users */ private List<Object> listUsers(Map<String, Boolean> requiredAttributes, int offset, int limit, String sortBy, String sortOrder, String domainName) throws CharonException { List<Object> users = new ArrayList<>(); //0th index is to store total number of results. users.add(0); String[] userNames; if (StringUtils.isNotEmpty(domainName)) { if (canPaginate(offset, limit)) { userNames = listUsernames(offset, limit, sortBy, sortOrder, domainName); } else { userNames = listUsernamesUsingLegacyAPIs(domainName); } } else { if (canPaginate(offset, limit)) { userNames = listUsernamesAcrossAllDomains(offset, limit, sortBy, sortOrder); } else { userNames = listUsernamesAcrossAllDomainsUsingLegacyAPIs(); } } if (ArrayUtils.isEmpty(userNames)) { if (log.isDebugEnabled()) { String message = String.format("There are no users who comply with the requested conditions: " + "startIndex = %d, count = %d", offset, limit); if (StringUtils.isNotEmpty(domainName)) { message = String.format(message + ", domain = %s", domainName); } log.debug(message); } } else { List<Object> scimUsers = getUserDetails(userNames, requiredAttributes); users.set(0, scimUsers.size()); // Set total number of results to 0th index. users.addAll(scimUsers); // Set user details from index 1. } return users; } /** * Method to decide whether to paginate based on the offset and the limit in the request. * * @param offset Starting index of the count * @param limit Counting value * @return true if pagination is possible, false otherwise */ private boolean canPaginate(int offset, int limit) { return (offset != 1 || limit != 0); } /** * Method to list paginated usernames from a specific user store using new APIs. * * @param offset Starting index of the count * @param limit Counting value * @param sortBy SortBy * @param sortOrder Sorting order * @param domainName Name of the user store * @return Paginated usernames list * @throws CharonException Error while listing usernames */ private String[] listUsernames(int offset, int limit, String sortBy, String sortOrder, String domainName) throws CharonException { if (isPaginatedUserStoreAvailable() && carbonUM instanceof PaginatedUserStoreManager) { if (limit == 0) { limit = getMaxLimit(domainName); } // Operator SW set with USERNAME and empty string to get all users. ExpressionCondition exCond = new ExpressionCondition(ExpressionOperation.SW.toString(), ExpressionAttribute.USERNAME.toString(), ""); return filterUsernames(exCond, offset, limit, sortBy, sortOrder, domainName); } else { if (log.isDebugEnabled()) { log.debug(String.format( "%s is not an instance of PaginatedUserStoreManager. Therefore pagination is not supported.", domainName)); } throw new CharonException(String.format("Pagination is not supported for %s.", domainName)); } } /** * Method to list usernames of all users from a specific user store using legacy APIs. * * @param domainName Name of the user store * @return Usernames list * @throws CharonException Error while listing usernames */ private String[] listUsernamesUsingLegacyAPIs(String domainName) throws CharonException { String[] userNames = null; try { Map<String, String> scimToLocalClaimsMap = SCIMCommonUtils.getSCIMtoLocalMappings(); String userIdLocalClaim = scimToLocalClaimsMap.get(SCIMConstants.CommonSchemaConstants.ID_URI); String claimValue = domainName.toUpperCase() + CarbonConstants.DOMAIN_SEPARATOR + SCIMCommonConstants.ANY; if (StringUtils.isNotBlank(userIdLocalClaim)) { userNames = carbonUM.getUserList(userIdLocalClaim, claimValue, null); } return userNames; } catch (UserStoreException e) { throw new CharonException(String.format("Error while listing usernames from domain: %s.", domainName), e); } } /** * Method to list paginated usernames from all user stores using new APIs. * * @param offset Starting index of the count * @param limit Counting value * @param sortBy SortBy * @param sortOrder Sorting order * @return Paginated usernames list * @throws CharonException Pagination not support */ private String[] listUsernamesAcrossAllDomains(int offset, int limit, String sortBy, String sortOrder) throws CharonException { String[] usernames; if (isPaginatedUserStoreAvailable() && carbonUM instanceof PaginatedUserStoreManager) { if (limit == 0) { usernames = listUsernamesAcrossAllDomainsUsingLegacyAPIs(); usernames = paginateUsers(usernames, limit, offset); } else { ExpressionCondition condition = new ExpressionCondition(ExpressionOperation.SW.toString(), ExpressionAttribute.USERNAME.toString(), ""); usernames = filterUsersFromMultipleDomains(null, offset, limit, sortBy, sortOrder, condition); } } else { if (log.isDebugEnabled()) { log.debug(" The user store is not a paginated user store manager. Therefore pagination " + "is not supported."); } throw new CharonException("Pagination is not supported."); } return usernames; } /** * Method to list usernames of all users across all user stores using legacy APIs. * * @return Usernames list * @throws CharonException Error while listing usernames */ private String[] listUsernamesAcrossAllDomainsUsingLegacyAPIs() throws CharonException { String[] userNames = null; try { Map<String, String> scimToLocalClaimsMap = SCIMCommonUtils.getSCIMtoLocalMappings(); String userIdLocalClaim = scimToLocalClaimsMap.get(SCIMConstants.CommonSchemaConstants.ID_URI); if (StringUtils.isNotBlank(userIdLocalClaim)) { userNames = carbonUM.getUserList(userIdLocalClaim, SCIMCommonConstants.ANY, null); } return userNames; } catch (UserStoreException e) { throw new CharonException("Error while listing usernames across all domains. ", e); } } /** * Method to get user details of usernames. * * @param userNames Array of usernames * @param requiredAttributes Required attributes for the response * @return User list with detailed attributes * @throws CharonException Error while retrieving users */ private List<Object> getUserDetails(String[] userNames, Map<String, Boolean> requiredAttributes) throws CharonException { List<Object> users = new ArrayList<>(); try { Map<String, String> scimToLocalClaimsMap = SCIMCommonUtils.getSCIMtoLocalMappings(); List<String> requiredClaims = getOnlyRequiredClaims(scimToLocalClaimsMap.keySet(), requiredAttributes); List<String> requiredClaimsInLocalDialect; if (MapUtils.isNotEmpty(scimToLocalClaimsMap)) { scimToLocalClaimsMap.keySet().retainAll(requiredClaims); requiredClaimsInLocalDialect = new ArrayList<>(scimToLocalClaimsMap.values()); } else { requiredClaimsInLocalDialect = new ArrayList<>(); } User[] scimUsers; if (isPaginatedUserStoreAvailable() && carbonUM instanceof PaginatedUserStoreManager) { // Retrieve all SCIM users at once. scimUsers = this.getSCIMUsers(userNames, requiredClaimsInLocalDialect, scimToLocalClaimsMap); users.addAll(Arrays.asList(scimUsers)); } else { // Retrieve SCIM users one by one. retriveSCIMUsers(users, userNames, requiredClaimsInLocalDialect, scimToLocalClaimsMap); } } catch (UserStoreException e) { throw new CharonException("Error while retrieving users from user store.", e); } return users; } private void retriveSCIMUsers(List<Object> users, String[] userNames, List<String> requiredClaims, Map<String, String> scimToLocalClaimsMap) throws CharonException { for (String userName : userNames) { if (userName.contains(UserCoreConstants.NAME_COMBINER)) { userName = userName.split("\\" + UserCoreConstants.NAME_COMBINER)[0]; } String userStoreDomainName = IdentityUtil.extractDomainFromName(userName); if (isSCIMEnabled(userStoreDomainName)) { if (log.isDebugEnabled()) { log.debug("SCIM is enabled for the user-store domain : " + userStoreDomainName + ". " + "Including user : " + userName + " in the response."); } User scimUser = this.getSCIMUser(userName, requiredClaims, scimToLocalClaimsMap); if (scimUser != null) { Map<String, Attribute> attrMap = scimUser.getAttributeList(); if (attrMap != null && !attrMap.isEmpty()) { users.add(scimUser); } } } else { if (log.isDebugEnabled()) { log.debug("SCIM is disabled for the user-store domain : " + userStoreDomainName + ". " + "Hence user : " + userName + " in this domain is excluded in the response."); } } } } @Override public User updateUser(User user, Map<String, Boolean> requiredAttributes) throws CharonException, BadRequestException { try { if (log.isDebugEnabled()) { log.debug("Updating user: " + user.getUserName()); } /*set thread local property to signal the downstream SCIMUserOperationListener about the provisioning route.*/ SCIMCommonUtils.setThreadLocalIsManagedThroughSCIMEP(true); //get user claim values Map<String, String> claims = AttributeMapper.getClaimsMap(user); //check if username of the updating user existing in the userstore. try { String userStoreDomainFromSP = getUserStoreDomainFromSP(); SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getUserResourceSchema(); User oldUser = this.getUser(user.getId(), ResourceManagerUtil.getAllAttributeURIs(schema)); if (userStoreDomainFromSP != null && !userStoreDomainFromSP .equalsIgnoreCase(IdentityUtil.extractDomainFromName(oldUser.getUserName()))) { throw new CharonException("User :" + oldUser.getUserName() + "is not belong to user store " + userStoreDomainFromSP + "Hence user updating fail"); } if (getUserStoreDomainFromSP() != null && !UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME.equalsIgnoreCase(getUserStoreDomainFromSP())) { user.setUserName(IdentityUtil .addDomainToName(UserCoreUtil.removeDomainFromName(user.getUserName()), getUserStoreDomainFromSP())); } } catch (IdentityApplicationManagementException e) { throw new CharonException("Error retrieving User Store name. ", e); } if (!carbonUM.isExistingUser(user.getUserName())) { throw new CharonException("User name is immutable in carbon user store."); } /*skip groups attribute since we map groups attribute to actual groups in ldap. and do not update it as an attribute in user schema*/ if (claims.containsKey(SCIMConstants.UserSchemaConstants.GROUP_URI)) { claims.remove(SCIMConstants.UserSchemaConstants.GROUP_URI); } /* Skip roles list since we map SCIM groups to local roles internally. It shouldn't be allowed to manipulate SCIM groups from user endpoint as this attribute has a mutability of "readOnly". Group changes must be applied via Group Resource */ if (claims.containsKey(SCIMConstants.UserSchemaConstants.ROLES_URI + "." + SCIMConstants.DEFAULT)) { claims.remove(SCIMConstants.UserSchemaConstants.ROLES_URI); } if (claims.containsKey(SCIMConstants.UserSchemaConstants.USER_NAME_URI)) { claims.remove(SCIMConstants.UserSchemaConstants.USER_NAME_URI); } Map<String, String> scimToLocalClaimsMap = SCIMCommonUtils.getSCIMtoLocalMappings(); List<String> requiredClaims = getOnlyRequiredClaims(scimToLocalClaimsMap.keySet(), requiredAttributes); List<String> requiredClaimsInLocalDialect; if (MapUtils.isNotEmpty(scimToLocalClaimsMap)) { scimToLocalClaimsMap.keySet().retainAll(requiredClaims); requiredClaimsInLocalDialect = new ArrayList<>(scimToLocalClaimsMap.values()); } else { if (log.isDebugEnabled()) { log.debug("SCIM to Local Claim mappings list is empty."); } requiredClaimsInLocalDialect = new ArrayList<>(); } Map<String, String> oldClaimList = carbonUM.getUserClaimValues(user.getUserName(), requiredClaimsInLocalDialect .toArray(new String[requiredClaims.size()]), null); for (Map.Entry<String, String> entry : oldClaimList.entrySet()) { if (!isImmutableClaim(entry.getKey())) { carbonUM.deleteUserClaimValue(user.getUserName(), entry.getKey(), null); } } // Get user claims mapped from SCIM dialect to WSO2 dialect. Map<String, String> claimValuesInLocalDialect = SCIMCommonUtils.convertSCIMtoLocalDialect(claims); //set user claim values carbonUM.setUserClaimValues(user.getUserName(), claimValuesInLocalDialect, null); //if password is updated, set it separately if (user.getPassword() != null) { carbonUM.updateCredentialByAdmin(user.getUserName(), user.getPassword()); } log.info("User: " + user.getUserName() + " updated through SCIM."); return getUser(user.getId(),requiredAttributes); } catch (UserStoreException e) { handleErrorsOnUserNameAndPasswordPolicy(e); throw new CharonException("Error while updating attributes of user: " + user.getUserName(), e); } catch (BadRequestException | CharonException e) { throw new CharonException("Error occured while trying to update the user", e); } } /** * Filter users using multi-attribute filters or single attribute filters with pagination. * * @param node Node * @param requiredAttributes Required attributes * @param offset Starting index of the count * @param limit Number of required results (count) * @param sortBy Sortby * @param sortOrder Sort order * @param domainName Domain that the filter should perform * @return Detailed user list * @throws CharonException */ private List<Object> filterUsers(Node node, Map<String, Boolean> requiredAttributes, int offset, int limit, String sortBy, String sortOrder, String domainName) throws CharonException { // Handle single attribute search. if (node instanceof ExpressionNode) { return filterUsersBySingleAttribute((ExpressionNode) node, requiredAttributes, offset, limit, sortBy, sortOrder, domainName); } else if (node instanceof OperationNode) { if (log.isDebugEnabled()) log.debug("Listing users by multi attribute filter"); List<Object> filteredUsers = new ArrayList<>(); // 0th index is to store total number of results. filteredUsers.add(0); // Support multi attribute filtering. return getMultiAttributeFilteredUsers(node, requiredAttributes, offset, limit, sortBy, sortOrder, domainName, filteredUsers); } else { throw new CharonException("Unknown operation. Not either an expression node or an operation node."); } } /** * Method to filter users for a filter with a single attribute. * * @param node Expression node for single attribute filtering * @param requiredAttributes Required attributes for the response * @param offset Starting index of the count * @param limit Counting value * @param sortBy SortBy * @param sortOrder Sorting order * @param domainName Domain to run the filter * @return User list with detailed attributes * @throws CharonException Error while filtering */ private List<Object> filterUsersBySingleAttribute(ExpressionNode node, Map<String, Boolean> requiredAttributes, int offset, int limit, String sortBy, String sortOrder, String domainName) throws CharonException { String[] userNames; if (log.isDebugEnabled()) { log.debug(String.format("Listing users by filter: %s %s %s", node.getAttributeValue(), node.getOperation(), node.getValue())); } // Apply filter enhancements for username and update expression node value. applyFilterEnhancementsForUsernameInNode(node); try { // Extract he domain name if the domain name is embedded in the filter attribute value. domainName = resolveDomainNameInAttributeValue(domainName, node); } catch (BadRequestException e) { String errorMessage = String .format("Domain parameter: %s in request does not match with the domain name in the attribute " + "value: %s ", domainName, node.getValue()); throw new CharonException(errorMessage, e); } try { // Check which APIs should the filter needs to follow. if (isUseLegacyAPIs(limit)) { userNames = filterUsersUsingLegacyAPIs(node, limit, offset, domainName); } else { userNames = filterUsers(node, offset, limit, sortBy, sortOrder, domainName); } } catch (NotImplementedException e) { String errorMessage = String.format("System does not support filter operator: %s", node.getOperation()); throw new CharonException(errorMessage, e); } return getDetailedUsers(userNames, requiredAttributes); } /** * Method to decide whether to use new APIs or legacy APIs. * * @param limit Number of results required for the filter request. * @return True if legacy API filtering is needed. */ private boolean isUseLegacyAPIs(int limit) { // If the limit is not specified, list all the users using old APIs since the new APIs must have a // limit larger than zero. if (limit <= 0) { return true; } else if (!isPaginatedUserStoreAvailable() && !(carbonUM instanceof PaginatedUserStoreManager)) { // If the userStore does not support above conditions, filter should use old APIs. return true; } return false; } /** * Validate whether filter enhancements are enabled and then append the primary domain name in front of the * attribute value to be searched. Finally update the attribute value in Expression node to new attribute value. * * @param node Expression node * @return Modified attribute value */ private void applyFilterEnhancementsForUsernameInNode(ExpressionNode node) { // Set filter values. String attributeName = node.getAttributeValue(); String filterOperation = node.getOperation(); String attributeValue = node.getValue(); if (SCIMCommonUtils.isFilteringEnhancementsEnabled()) if (SCIMCommonConstants.EQ.equalsIgnoreCase(filterOperation)) if (StringUtils.equals(attributeName, SCIMConstants.UserSchemaConstants.USER_NAME_URI) && !StringUtils .contains(attributeValue, CarbonConstants.DOMAIN_SEPARATOR)) node.setValue(UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME + CarbonConstants.DOMAIN_SEPARATOR + attributeValue); } /** * Update the domain parameter from the domain in attribute value and update the value in the expression node to the * newly extracted value. * * @param domainName Domain name in the filter request * @param node Expression node * @return Domain name extracted from the attribute value * @throws BadRequestException Domain miss match in domain parameter and attribute value */ private String resolveDomainNameInAttributeValue(String domainName, ExpressionNode node) throws BadRequestException { String extractedDomain; String attributeName = node.getAttributeValue(); String filterOperation = node.getOperation(); String attributeValue = node.getValue(); if (isDomainNameEmbeddedInAttributeValue(filterOperation, attributeName, attributeValue)) { int indexOfDomainSeparator = attributeValue.indexOf(CarbonConstants.DOMAIN_SEPARATOR); extractedDomain = attributeValue.substring(0, indexOfDomainSeparator).toUpperCase(); // Update then newly extracted attribute value in the expression node. int startingIndexOfAttributeValue = indexOfDomainSeparator + 1; node.setValue(attributeValue.substring(startingIndexOfAttributeValue)); // Check whether the domain name is equal to the extracted domain name from attribute value. if (StringUtils.isNotEmpty(domainName) && StringUtils.isNotEmpty(extractedDomain) && !extractedDomain .equalsIgnoreCase(domainName)) throw new BadRequestException(String.format( " Domain name %s in the domain parameter does not match with the domain name %s in search " + "attribute value of %s claim.", domainName, extractedDomain, attributeName)); if (StringUtils.isEmpty(domainName) && StringUtils.isNotEmpty(extractedDomain)) { if (log.isDebugEnabled()) log.debug(String.format("Domain name %s set from the domain name in the attribute value %s ", extractedDomain, attributeValue)); return extractedDomain; } } return domainName; } /** * Method to verify whether there is a domain in the attribute value. * * @param filterOperation Operation of the expression node * @param attributeName Attribute name of the expression node * @param attributeValue Value of the expression node * @return Whether there is a domain embedded to the attribute value */ private boolean isDomainNameEmbeddedInAttributeValue(String filterOperation, String attributeName, String attributeValue) { // Checks whether the domain separator is in the attribute value. if (StringUtils.contains(attributeValue, CarbonConstants.DOMAIN_SEPARATOR)) { // Checks whether the attribute name is username or group uri. if (StringUtils.equals(attributeName, SCIMConstants.UserSchemaConstants.USER_NAME_URI) || StringUtils .equals(attributeName, SCIMConstants.UserSchemaConstants.GROUP_URI)) { // Checks whether the operator is equal to EQ, SW, EW, CO. if (SCIMCommonConstants.EQ.equalsIgnoreCase(filterOperation) || SCIMCommonConstants.SW .equalsIgnoreCase(filterOperation) || SCIMCommonConstants.CO.equalsIgnoreCase(filterOperation) || SCIMCommonConstants.EW.equalsIgnoreCase(filterOperation)) { if (log.isDebugEnabled()) log.debug(String.format("Attribute value %s is embedded with a domain in %s claim, ", attributeValue, attributeName)); // If all the above conditions are true, then a domain is embedded to the attribute value. return true; } } } // If no domain name in the attribute value, return false. return false; } /** * Method to get users when a filter is used with a single attribute and when the user store is an instance of * PaginatedUserStoreManager since the filter API supports an instance of PaginatedUserStoreManager. * * @param node Expression or Operation node * @param offset Start index value * @param limit Count value * @param sortBy SortBy * @param sortOrder Sort order * @param domainName Domain to perform the search * @return User names of the filtered users * @throws CharonException Error while filtering */ private String[] filterUsers(Node node, int offset, int limit, String sortBy, String sortOrder, String domainName) throws CharonException { // Filter users when the domain is specified in the request. if (StringUtils.isNotEmpty(domainName)) { return filterUsernames(createConditionForSingleAttributeFilter(domainName, node), offset, limit, sortBy, sortOrder, domainName); } else { return filterUsersFromMultipleDomains(node, offset, limit, sortBy, sortOrder, null); } } /** * Method to perform a multiple domain search when the domain is not specified in the request. The same function * can be used to listing users by passing a condition for conditionForListingUsers parameter. * * @param node Expression or Operation node (set the value to null when method is used for * list users) * @param offset Start index value * @param limit Count value * @param sortBy SortBy * @param sortOrder Sort order * @param conditionForListingUsers Condition for listing users when the function is used to list users except for * filtering. For filtering this value should be set to NULL. * @return User names of the filtered users */ private String[] filterUsersFromMultipleDomains(Node node, int offset, int limit, String sortBy, String sortOrder, Condition conditionForListingUsers) throws CharonException { // Filter users when the domain is not set in the request. Then filter through multiple domains. String[] userStoreDomainNames = getDomainNames(); ArrayList<String> filteredUsernames = new ArrayList<>(); Condition condition; for (String userStoreDomainName : userStoreDomainNames) { // Check whether the used case is for listing users. if (conditionForListingUsers == null) { // Create filter condition for each domain for single attribute filter. condition = createConditionForSingleAttributeFilter(userStoreDomainName, node); } else { condition = conditionForListingUsers; } // Filter users for given condition and domain. String[] userNames = filterUsernames(condition, offset, limit, sortBy, sortOrder, userStoreDomainName); if (userNames == null) { userNames = new String[0]; } // Calculating new offset and limit parameters. int numberOfFilteredUsers = userNames.length; if (numberOfFilteredUsers <= 0 && offset > 1) { if (log.isDebugEnabled()) { log.debug(String.format("Filter returned no results for original offset: %d.", offset)); } offset = calculateOffset(condition, offset, sortBy, sortOrder, userStoreDomainName); } else { // Returned user names size > 0 implies there are users in that domain which is larger than // the offset. offset = 1; limit = calculateLimit(limit, numberOfFilteredUsers); } filteredUsernames.addAll(Arrays.asList(userNames)); // If the limit is changed then filtering needs to be stopped. if (limit == 0) { break; } } return filteredUsernames.toArray(new String[0]); } /** * Method to update the count(limit) when iterating a filter across all domains. * * @param limit Counting value (limit) * @param numberOfFilteredUsers Amount of users filtered in the search * @return Calculated new limit (count) */ private int calculateLimit(int limit, int numberOfFilteredUsers) { int newLimit = limit - numberOfFilteredUsers; if (limit < 0) { newLimit = 0; } if (log.isDebugEnabled()) { log.debug(String.format("New limit: %d calculated using initial offset: %d and filtered user count: %d. ", newLimit, limit, numberOfFilteredUsers)); } return newLimit; } /** * Method to update the offset when iterating a filter across all domains. * * @param condition Condition of the single attribute filter * @param offset Starting index * @param sortBy Sort by * @param sortOrder Sort order * @param domainName Domain to be filtered * @return New calculated offset * @throws CharonException Error while filtering the domain from index 1 to offset */ private int calculateOffset(Condition condition, int offset, String sortBy, String sortOrder, String domainName) throws CharonException { if (log.isDebugEnabled()) { log.debug(String.format("Checking for number of matches from the beginning to the original offset: %d for " + "the same filter and updating the new offset.", offset)); } // Starting index of the filter int initialOffset = 1; // Checking the number of matches till the original offset. int skippedUserCount; String[] skippedUsers = filterUsernames(condition, initialOffset, offset, sortBy, sortOrder, domainName); if (skippedUsers == null) { skippedUserCount = 0; } else { skippedUserCount = skippedUsers.length; } // Calculate the new offset and return return offset - skippedUserCount; } /** * Method to get users when a filter domain is known. * * @param condition Condition of the single attribute filter * @param offset Start index value * @param limit Count value * @param sortBy SortBy * @param sortOrder Sort order * @param domainName Domain to perform the search * @return User names of the filtered users * @throws CharonException Error while filtering */ private String[] filterUsernames(Condition condition, int offset, int limit, String sortBy, String sortOrder, String domainName) throws CharonException { if (log.isDebugEnabled()) { log.debug(String.format("Filtering users in domain : %s with limit: %d and offset: %d.", domainName, limit, offset)); } try { return ((PaginatedUserStoreManager) carbonUM) .getUserList(condition, domainName, UserCoreConstants.DEFAULT_PROFILE, limit, offset, sortBy, sortOrder); } catch (UserStoreException e) { String errorMessage = String .format("Error while retrieving users for the domain: %s with limit: %d and offset: %d.", domainName, limit, offset); throw new CharonException(errorMessage, e); } } /** * Method is to create a condition for a single attribute filter when the node and the domain name is passed. * * @param domainName Domain name of the user store to be filtered * @param node Node of the single attribute filter * @return Condition for the single attribute filter * @throws CharonException */ private Condition createConditionForSingleAttributeFilter(String domainName, Node node) throws CharonException { if (log.isDebugEnabled()) { log.debug("Creating condition for domain : " + domainName); } Map<String, String> attributes; try { attributes = getAllAttributes(domainName); } catch (UserStoreException e) { String errorMessage = String.format("Error while retrieving attributes for the domain %s.", domainName); throw new CharonException(errorMessage, e); } return getCondition(node, attributes); } /** * Get all the domain names related to user stores. * * @return A list of all the available domain names */ private String[] getDomainNames() { String domainName; ArrayList<String> domainsOfUserStores = new ArrayList<>(); UserStoreManager secondaryUserStore = carbonUM.getSecondaryUserStoreManager(); while (secondaryUserStore != null) { domainName = secondaryUserStore.getRealmConfiguration(). getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME).toUpperCase(); secondaryUserStore = secondaryUserStore.getSecondaryUserStoreManager(); domainsOfUserStores.add(domainName); } // Sorting the secondary user stores to maintain an order fo domains so that pagination is consistent. Collections.sort(domainsOfUserStores); // Append the primary domain name to the front of the domain list since the first iteration of multiple // domain filtering should happen for the primary user store. domainsOfUserStores.add(0, UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME); return domainsOfUserStores.toArray(new String[0]); } /** * Method to filter users if the user store is not an instance of PaginatedUserStoreManager and * ENABLE_PAGINATED_USER_STORE is not enabled. * * @param node Expression node * @param limit Number of users required for counting * @param offset Starting user index for start counting * @return List of paginated set of users. * @throws NotImplementedException Not supported filter operation * @throws UserStoreException */ private String[] filterUsersUsingLegacyAPIs(ExpressionNode node, int limit, int offset, String domainName) throws NotImplementedException, CharonException { String[] userNames; // Set filter values. String attributeName = node.getAttributeValue(); String filterOperation = node.getOperation(); String attributeValue = node.getValue(); // If there is a domain, append the domain with the domain separator in front of the new attribute value if // domain separator is not found in the attribute value. if (StringUtils.isNotEmpty(domainName) && StringUtils .containsNone(attributeValue, CarbonConstants.DOMAIN_SEPARATOR)) { attributeValue = domainName.toUpperCase() + CarbonConstants.DOMAIN_SEPARATOR + node.getValue(); } try { if (SCIMConstants.UserSchemaConstants.GROUP_URI.equals(attributeName)) { if (carbonUM instanceof AbstractUserStoreManager) { String[] roleNames = getRoleNames(filterOperation, attributeValue); userNames = getUserListOfRoles(roleNames); } else { String errorMessage = String .format("Filter operator %s is not supported by the user store.", filterOperation); throw new NotImplementedException(errorMessage); } } else { // Get the user name of the user with this id. userNames = getUserNames(attributeName, filterOperation, attributeValue); } } catch (UserStoreException e) { String errorMessage = String.format("Error while filtering the users for filter with attribute name: %s ," + " filter operation: %s and attribute value: %s. ", attributeName, filterOperation, attributeValue); throw new CharonException(errorMessage, e); } userNames = paginateUsers(userNames, limit, offset); return userNames; } /** * Method to remove duplicate users and get the user details. * * @param userNames Filtered user names * @param requiredAttributes Required attributes in the response * @return Users list with populated attributes * @throws CharonException Error in retrieving user details */ private List<Object> getDetailedUsers(String[] userNames, Map<String, Boolean> requiredAttributes) throws CharonException { List<Object> filteredUsers = new ArrayList<>(); // 0th index is to store total number of results. filteredUsers.add(0); // Remove duplicate users. HashSet<String> userNamesSet = new HashSet<>(Arrays.asList(userNames)); userNames = userNamesSet.toArray(new String[0]); // Set total number of filtered results. filteredUsers.set(0, userNames.length); // Get details of the finalized user list. filteredUsers.addAll(getFilteredUserDetails(userNames, requiredAttributes)); return filteredUsers; } /** * This method support multi-attribute filters with paginated search for user(s). * * @param node * @param requiredAttributes * @param offset * @param limit * @param sortBy * @param sortOrder * @param domainName * @param filteredUsers * @return * @throws CharonException */ private List<Object> getMultiAttributeFilteredUsers(Node node, Map<String, Boolean> requiredAttributes, int offset, int limit, String sortBy, String sortOrder, String domainName, List<Object> filteredUsers) throws CharonException { String[] userNames; // Handle pagination. if (limit > 0) { userNames = getFilteredUsersFromMultiAttributeFiltering(node, offset, limit, sortBy, sortOrder, domainName); filteredUsers.set(0, userNames.length); filteredUsers.addAll(getFilteredUserDetails(userNames, requiredAttributes)); } else { int maxLimit = getMaxLimit(domainName); if (StringUtils.isNotEmpty(domainName)) { userNames = getFilteredUsersFromMultiAttributeFiltering(node, offset, maxLimit, sortBy, sortOrder, domainName); filteredUsers.set(0, userNames.length); filteredUsers.addAll(getFilteredUserDetails(userNames, requiredAttributes)); } else { int totalUserCount = 0; // If pagination and domain name are not given, then perform filtering on all available user stores. while (carbonUM != null) { // If carbonUM is not an instance of Abstract User Store Manger we can't get the domain name. if (carbonUM instanceof AbstractUserStoreManager) { domainName = carbonUM.getRealmConfiguration().getUserStoreProperty("DomainName"); userNames = getFilteredUsersFromMultiAttributeFiltering(node, offset, maxLimit, sortBy, sortOrder, domainName); totalUserCount += userNames.length; filteredUsers.addAll(getFilteredUserDetails(userNames, requiredAttributes)); } carbonUM = carbonUM.getSecondaryUserStoreManager(); } //set the total results filteredUsers.set(0, totalUserCount); } } return filteredUsers; } /** * Get maximum user limit to retrieve. * * @param domainName Name of the user store * @return */ private int getMaxLimit(String domainName) { int givenMax = UserCoreConstants.MAX_USER_ROLE_LIST; if (StringUtils.isEmpty(domainName)) { domainName = UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME; } if (carbonUM.getSecondaryUserStoreManager(domainName).getRealmConfiguration() .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST) != null) { givenMax = Integer.parseInt(carbonUM.getSecondaryUserStoreManager(domainName).getRealmConfiguration() .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST)); } return givenMax; } /** * Generate condition tree for given filters. * * @param node * @param attributes * @return * @throws CharonException */ private Condition getCondition(Node node, Map<String, String> attributes) throws CharonException { if (node instanceof ExpressionNode) { String operation = ((ExpressionNode) node).getOperation(); String attributeName = ((ExpressionNode) node).getAttributeValue(); String attributeValue = ((ExpressionNode) node).getValue(); String conditionOperation; String conditionAttributeName; if (SCIMCommonConstants.EQ.equals(operation)) { conditionOperation = ExpressionOperation.EQ.toString(); } else if (SCIMCommonConstants.SW.equals(operation)) { conditionOperation = ExpressionOperation.SW.toString(); } else if (SCIMCommonConstants.EW.equals(operation)) { conditionOperation = ExpressionOperation.EW.toString(); } else if (SCIMCommonConstants.CO.equals(operation)) { conditionOperation = ExpressionOperation.CO.toString(); } else { conditionOperation = operation; } if (SCIMConstants.UserSchemaConstants.GROUP_URI.equals(attributeName)) { conditionAttributeName = ExpressionAttribute.ROLE.toString(); } else if (SCIMConstants.UserSchemaConstants.USER_NAME_URI.equals(attributeName)) { conditionAttributeName = ExpressionAttribute.USERNAME.toString(); } else if (attributes != null && attributes.get(attributeName) != null) { conditionAttributeName = attributes.get(attributeName); } else { throw new CharonException("Unsupported attribute: " + attributeName); } return new ExpressionCondition(conditionOperation, conditionAttributeName, attributeValue); } else if (node instanceof OperationNode) { Condition leftCondition = getCondition(node.getLeftNode(), attributes); Condition rightCondition = getCondition(node.getRightNode(), attributes); String operation = ((OperationNode) node).getOperation(); if (OperationalOperation.AND.toString().equalsIgnoreCase(operation)) { return new OperationalCondition(OperationalOperation.AND.toString(), leftCondition, rightCondition); } else { throw new CharonException("Unsupported Operation: " + operation); } } else { throw new CharonException("Unsupported Operation"); } } /** * Get all attributes for given domain. * * @param domainName * @return * @throws UserStoreException */ private Map<String, String> getAllAttributes(String domainName) throws UserStoreException { ClaimMapping[] userClaims; ClaimMapping[] coreClaims; ClaimMapping[] extensionClaims = null; try { coreClaims = carbonClaimManager.getAllClaimMappings(SCIMCommonConstants.SCIM_CORE_CLAIM_DIALECT); userClaims = carbonClaimManager.getAllClaimMappings(SCIMCommonConstants.SCIM_USER_CLAIM_DIALECT); if (SCIMUserSchemaExtensionBuilder.getInstance().getExtensionSchema() != null) { extensionClaims = carbonClaimManager.getAllClaimMappings( SCIMUserSchemaExtensionBuilder.getInstance().getExtensionSchema().getURI()); } Map<String, String> attributes = new HashMap<>(); for (ClaimMapping claim : coreClaims) { attributes.put(claim.getClaim().getClaimUri(), claim.getMappedAttribute(domainName)); } for (ClaimMapping claim : userClaims) { attributes.put(claim.getClaim().getClaimUri(), claim.getMappedAttribute(domainName)); } if (extensionClaims != null) { for (ClaimMapping claim : extensionClaims) { attributes.put(claim.getClaim().getClaimUri(), claim.getMappedAttribute(domainName)); } } return attributes; } catch (UserStoreException e) { throw new UserStoreException("Error in filtering users by multi attributes ", e); } } /** * Perform multi attribute filtering. * * @param node * @param offset * @param limit * @param sortBy * @param sortOrder * @param domainName * @return * @throws CharonException */ private String[] getFilteredUsersFromMultiAttributeFiltering(Node node, int offset, int limit, String sortBy, String sortOrder, String domainName) throws CharonException { String[] userNames; try { if (StringUtils.isEmpty(domainName)) { domainName = "PRIMARY"; } Map<String, String> attributes = getAllAttributes(domainName); if (log.isDebugEnabled()) { log.debug("Invoking the do get user list for domain: " + domainName); } userNames = ((PaginatedUserStoreManager) carbonUM).getUserList(getCondition(node, attributes), domainName, UserCoreConstants.DEFAULT_PROFILE, limit, offset, sortBy, sortOrder); return userNames; } catch (UserStoreException e) { throw new CharonException("Error in filtering users by multi attributes ", e); } } /** * Get required claim details for filtered user. * * @param userNames * @param requiredAttributes * @return * @throws CharonException */ private List<Object> getFilteredUserDetails(String[] userNames, Map<String, Boolean> requiredAttributes) throws CharonException { List<Object> filteredUsers = new ArrayList<>(); if (userNames == null || userNames.length == 0) { if (log.isDebugEnabled()) { log.debug("Users for this filter does not exist in the system."); } return filteredUsers; } else { try { Map<String, String> scimToLocalClaimsMap = SCIMCommonUtils.getSCIMtoLocalMappings(); List<String> requiredClaims = getOnlyRequiredClaims(scimToLocalClaimsMap.keySet(), requiredAttributes); List<String> requiredClaimsInLocalDialect; if (MapUtils.isNotEmpty(scimToLocalClaimsMap)) { scimToLocalClaimsMap.keySet().retainAll(requiredClaims); requiredClaimsInLocalDialect = new ArrayList<>(scimToLocalClaimsMap.values()); } else { if (log.isDebugEnabled()) { log.debug("SCIM to Local Claim mappings list is empty."); } requiredClaimsInLocalDialect = new ArrayList<>(); } User[] scimUsers; if (isPaginatedUserStoreAvailable()) { if (carbonUM instanceof PaginatedUserStoreManager) { scimUsers = this.getSCIMUsers(userNames, requiredClaimsInLocalDialect, scimToLocalClaimsMap); filteredUsers.addAll(Arrays.asList(scimUsers)); } else { addSCIMUsers(filteredUsers, userNames, requiredClaimsInLocalDialect, scimToLocalClaimsMap); } } else { addSCIMUsers(filteredUsers, userNames, requiredClaimsInLocalDialect, scimToLocalClaimsMap); } } catch (UserStoreException e) { throw new CharonException("Error in retrieve user details. ", e); } } return filteredUsers; } private void addSCIMUsers(List<Object> filteredUsers, String[] userNames, List<String> requiredClaims, Map<String, String> scimToLocalClaimsMap) throws CharonException { User scimUser; for (String userName : userNames) { if (CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME.equals(userName)) { continue; } String userStoreDomainName = IdentityUtil.extractDomainFromName(userName); if (isSCIMEnabled(userStoreDomainName)) { if (log.isDebugEnabled()) { log.debug("SCIM is enabled for the user-store domain : " + userStoreDomainName + ". " + "Including user : " + userName + " in the response."); } scimUser = this.getSCIMUser(userName, requiredClaims, scimToLocalClaimsMap); //if SCIM-ID is not present in the attributes, skip if (scimUser != null && StringUtils.isBlank(scimUser.getId())) { continue; } filteredUsers.add(scimUser); } else { if (log.isDebugEnabled()) { log.debug("SCIM is disabled for the user-store domain : " + userStoreDomainName + ". " + "Hence user : "+ userName + " in this domain is excluded in the response."); } } } } @Override public User getMe(String userName, Map<String, Boolean> requiredAttributes) throws CharonException, NotFoundException { if (log.isDebugEnabled()) { log.debug("Getting user: " + userName); } User scimUser; try { //get Claims related to SCIM claim dialect Map<String, String> scimToLocalClaimsMap = SCIMCommonUtils.getSCIMtoLocalMappings(); List<String> requiredClaims = getOnlyRequiredClaims(scimToLocalClaimsMap.keySet(), requiredAttributes); List<String> requiredClaimsInLocalDialect; if (MapUtils.isNotEmpty(scimToLocalClaimsMap)) { scimToLocalClaimsMap.keySet().retainAll(requiredClaims); requiredClaimsInLocalDialect = new ArrayList<>(scimToLocalClaimsMap.values()); } else { if (log.isDebugEnabled()) { log.debug("SCIM to Local Claim mappings list is empty."); } requiredClaimsInLocalDialect = new ArrayList<>(); } //we assume (since id is unique per user) only one user exists for a given id scimUser = this.getSCIMUser(userName, requiredClaimsInLocalDialect, scimToLocalClaimsMap); if (scimUser == null) { if (log.isDebugEnabled()) { log.debug("User with userName : " + userName + " does not exist in the system."); } throw new NotFoundException("No such user exist"); } else { //set the schemas of the scim user scimUser.setSchemas(); log.info("User: " + scimUser.getUserName() + " is retrieved through SCIM."); return scimUser; } } catch (UserStoreException e) { throw new CharonException("Error from getting the authenticated user", e); } } @Override public User createMe(User user, Map<String, Boolean> requiredAttributes) throws CharonException, ConflictException, BadRequestException { return createUser(user, requiredAttributes); } @Override public void deleteMe(String userName) throws NotFoundException, CharonException, NotImplementedException { String error = "Self delete is not supported"; throw new NotImplementedException(error); } @Override public User updateMe(User user, Map<String, Boolean> requiredAttributes) throws NotImplementedException, CharonException, BadRequestException { return updateUser(user, requiredAttributes); } @Override public Group createGroup(Group group, Map<String, Boolean> requiredAttributes) throws CharonException, ConflictException, BadRequestException { if (log.isDebugEnabled()) { log.debug("Creating group: " + group.getDisplayName()); } try { //modify display name if no domain is specified, in order to support multiple user store feature String originalName = group.getDisplayName(); String roleNameWithDomain = null; String domainName = ""; try { if (getUserStoreDomainFromSP() != null) { domainName = getUserStoreDomainFromSP(); roleNameWithDomain = IdentityUtil .addDomainToName(UserCoreUtil.removeDomainFromName(originalName), domainName); } else if (originalName.indexOf(CarbonConstants.DOMAIN_SEPARATOR) > 0) { domainName = IdentityUtil.extractDomainFromName(originalName); roleNameWithDomain = IdentityUtil .addDomainToName(UserCoreUtil.removeDomainFromName(originalName), domainName); } else { domainName = UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME; roleNameWithDomain = SCIMCommonUtils.getGroupNameWithDomain(originalName); } } catch (IdentityApplicationManagementException e) { throw new CharonException("Error retrieving User Store name. ", e); } if(!isInternalOrApplicationGroup(domainName) && StringUtils.isNotBlank(domainName) && !isSCIMEnabled (domainName)){ throw new CharonException("Cannot create group through scim to user store " + ". SCIM is not " + "enabled for user store " + domainName); } group.setDisplayName(roleNameWithDomain); //check if the group already exists if (carbonUM.isExistingRole(group.getDisplayName(), false)) { String error = "Group with name: " + group.getDisplayName() +" already exists in the system."; throw new ConflictException(error); } /*set thread local property to signal the downstream SCIMUserOperationListener about the provisioning route.*/ SCIMCommonUtils.setThreadLocalIsManagedThroughSCIMEP(true); /*if members are sent when creating the group, check whether users already exist in the user store*/ List<Object> userIds = group.getMembers(); List<String> userDisplayNames = group.getMembersWithDisplayName(); if (CollectionUtils.isNotEmpty(userIds)) { List<String> members = new ArrayList<>(); for (Object userId : userIds) { String userIdLocalClaim = SCIMCommonUtils.getSCIMtoLocalMappings().get(SCIMConstants .CommonSchemaConstants.ID_URI); String[] userNames = null; if (StringUtils.isNotBlank(userIdLocalClaim)) { userNames = carbonUM.getUserList(userIdLocalClaim, (String) userId, UserCoreConstants .DEFAULT_PROFILE); } if (userNames == null || userNames.length == 0) { String error = "User: " + userId + " doesn't exist in the user store. " + "Hence, can not create the group: " + group.getDisplayName(); throw new IdentitySCIMException(error); } else if (userNames[0].indexOf(UserCoreConstants.DOMAIN_SEPARATOR) > 0 && !StringUtils.containsIgnoreCase(userNames[0], domainName)) { String error = "User: " + userId + " doesn't exist in the same user store. " + "Hence, can not create the group: " + group.getDisplayName(); throw new IdentitySCIMException(error); } else { members.add(userNames[0]); if (CollectionUtils.isNotEmpty(userDisplayNames)) { boolean userContains = false; for (String user : userDisplayNames) { user = user.indexOf(UserCoreConstants.DOMAIN_SEPARATOR) > 0 ? user.split(UserCoreConstants.DOMAIN_SEPARATOR)[1] : user; if (user.equalsIgnoreCase(userNames[0].indexOf(UserCoreConstants.DOMAIN_SEPARATOR) > 0 ? userNames[0].split(UserCoreConstants.DOMAIN_SEPARATOR)[1] : userNames[0])) { userContains = true; break; } } if (!userContains) { throw new IdentitySCIMException("Given SCIM user Id and name does not match.."); } } } } //add other scim attributes in the identity DB since user store doesn't support some attributes. SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(carbonUM.getTenantId()); scimGroupHandler.createSCIMAttributes(group); carbonUM.addRole(group.getDisplayName(), members.toArray(new String[members.size()]), null, false); log.info("Group: " + group.getDisplayName() + " is created through SCIM."); } else { //add other scim attributes in the identity DB since user store doesn't support some attributes. SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(carbonUM.getTenantId()); scimGroupHandler.createSCIMAttributes(group); carbonUM.addRole(group.getDisplayName(), null, null, false); log.info("Group: " + group.getDisplayName() + " is created through SCIM."); } } catch (UserStoreException e) { try { SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(carbonUM.getTenantId()); scimGroupHandler.deleteGroupAttributes(group.getDisplayName()); } catch (UserStoreException | IdentitySCIMException ex) { log.error("Error occurred while doing rollback operation of the SCIM table entry for role: " + group.getDisplayName(), ex); throw new CharonException("Error occurred while doing rollback operation of the SCIM table entry for role: " + group.getDisplayName(), e); } throw new CharonException("Error occurred while adding role : " + group.getDisplayName(), e); } catch (IdentitySCIMException | BadRequestException e) { String error = "One or more group members do not exist in the same user store. " + "Hence, can not create the group: " + group.getDisplayName(); if (log.isDebugEnabled()) { log.debug(error, e); } throw new BadRequestException(error, ResponseCodeConstants.INVALID_VALUE); } return group; } @Override public Group getGroup(String id, Map<String, Boolean> requiredAttributes) throws CharonException { if (log.isDebugEnabled()) { log.debug("Retrieving group with id: " + id); } Group group = null; try { SCIMGroupHandler groupHandler = new SCIMGroupHandler(carbonUM.getTenantId()); //get group name by Id String groupName = groupHandler.getGroupName(id); if (groupName != null) { group = getGroupWithName(groupName); group.setSchemas(); return group; } else { //returning null will send a resource not found error to client by Charon. return null; } } catch (org.wso2.carbon.user.core.UserStoreException e) { throw new CharonException("Error in retrieving group : " + id, e); } catch (IdentitySCIMException e) { throw new CharonException("Error in retrieving SCIM Group information from database.", e); } catch (CharonException | BadRequestException e) { throw new CharonException("Error in retrieving the group", e); } } @Override public void deleteGroup(String groupId) throws NotFoundException, CharonException { if (log.isDebugEnabled()) { log.debug("Deleting group: " + groupId); } try { /*set thread local property to signal the downstream SCIMUserOperationListener about the provisioning route.*/ SCIMCommonUtils.setThreadLocalIsManagedThroughSCIMEP(true); //get group name by id SCIMGroupHandler groupHandler = new SCIMGroupHandler(carbonUM.getTenantId()); String groupName = groupHandler.getGroupName(groupId); if (groupName != null) { String userStoreDomainFromSP = null; try { userStoreDomainFromSP = getUserStoreDomainFromSP(); } catch (IdentityApplicationManagementException e) { throw new CharonException("Error retrieving User Store name. ", e); } if (userStoreDomainFromSP != null && !(userStoreDomainFromSP.equalsIgnoreCase(IdentityUtil.extractDomainFromName(groupName)))) { throw new CharonException("Group :" + groupName + "is not belong to user store " + userStoreDomainFromSP + "Hence group updating fail"); } String userStoreDomainName = IdentityUtil.extractDomainFromName(groupName); if (!isInternalOrApplicationGroup(userStoreDomainName) && StringUtils.isNotBlank(userStoreDomainName) && !isSCIMEnabled (userStoreDomainName)) { throw new CharonException("Cannot delete group: " + groupName + " through scim from user store: " + userStoreDomainName + ". SCIM is not enabled for user store: " + userStoreDomainName); } //delete group in carbon UM carbonUM.deleteRole(groupName); //we do not update Identity_SCIM DB here since it is updated in SCIMUserOperationListener's methods. log.info("Group: " + groupName + " is deleted through SCIM."); } else { if (log.isDebugEnabled()) { log.debug("Group with SCIM id: " + groupId + " doesn't exist in the system."); } throw new NotFoundException(); } } catch (UserStoreException | IdentitySCIMException e) { throw new CharonException("Error occurred while deleting group " + groupId, e); } } @Override public List<Object> listGroupsWithGET(Node rootNode, int startIndex, int count, String sortBy, String sortOrder, String domainName, Map<String, Boolean> requiredAttributes) throws CharonException, NotImplementedException, BadRequestException { if (sortBy != null || sortOrder != null) { throw new NotImplementedException("Sorting is not supported"); } else if (startIndex != 1) { throw new NotImplementedException("Pagination is not supported"); } else if (rootNode != null) { return filterGroups(rootNode, requiredAttributes); } else { return listGroups(requiredAttributes); } } private List<Object> listGroups(Map<String, Boolean> requiredAttributes) throws CharonException { List<Object> groupList = new ArrayList<>(); //0th index is to store total number of results; groupList.add(0); try { SCIMGroupHandler groupHandler = new SCIMGroupHandler(carbonUM.getTenantId()); Set<String> roleNames = groupHandler.listSCIMRoles(); for (String roleName : roleNames) { String userStoreDomainName = IdentityUtil.extractDomainFromName(roleName); if (isInternalOrApplicationGroup(userStoreDomainName) || isSCIMEnabled(userStoreDomainName)) { if (log.isDebugEnabled()) { log.debug("SCIM is enabled for the user-store domain : " + userStoreDomainName + ". " + "Including group with name : " + roleName + " in the response."); } Group group = this.getGroupWithName(roleName); if (group.getId() != null) { groupList.add(group); } } else { if (log.isDebugEnabled()) { log.debug("SCIM is disabled for the user-store domain : " + userStoreDomainName + ". Hence " + "group with name : " + roleName + " is excluded in the response."); } } } } catch (org.wso2.carbon.user.core.UserStoreException e) { String errMsg = "Error in obtaining role names from user store."; errMsg += e.getMessage(); throw new CharonException(errMsg, e); } catch (IdentitySCIMException | BadRequestException e) { throw new CharonException("Error in retrieving SCIM Group information from database.", e); } //set the totalResults value in index 0 groupList.set(0, groupList.size()-1); return groupList; } private List<Object> filterGroups(Node node, Map<String, Boolean> requiredAttributes) throws NotImplementedException, CharonException { if(node.getLeftNode() != null || node.getRightNode() != null){ String error = "Complex filters are not supported yet"; throw new NotImplementedException(error); } String attributeName = ((ExpressionNode)node).getAttributeValue(); String filterOperation = ((ExpressionNode)node).getOperation(); String attributeValue = ((ExpressionNode)node).getValue(); if (isNotFilteringSupported(filterOperation)) { String error = "System does not support filter operator: " + filterOperation; throw new NotImplementedException(error); } if (SCIMCommonUtils.isFilteringEnhancementsEnabled()) { if (SCIMCommonConstants.EQ.equalsIgnoreCase(filterOperation)) { if (StringUtils.equals(attributeName, SCIMConstants.GroupSchemaConstants.DISPLAY_NAME_URI) && !StringUtils.contains(attributeValue, CarbonConstants.DOMAIN_SEPARATOR)) { attributeValue = UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME + CarbonConstants.DOMAIN_SEPARATOR + attributeValue; } } } if (log.isDebugEnabled()) { log.debug("Listing groups with filter: " + attributeName + filterOperation + attributeValue); } List<Object> filteredGroups = new ArrayList<>(); //0th index is to store total number of results; filteredGroups.add(0); try { String[] roleList = getGroupList(attributeName, filterOperation, attributeValue); if (roleList != null) { for (String roleName : roleList) { if (roleName != null && carbonUM.isExistingRole(roleName, false)) { //skip internal roles if ((CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME.equals(roleName)) || UserCoreUtil.isEveryoneRole(roleName, carbonUM.getRealmConfiguration())) { continue; } /**construct the group name with domain -if not already provided, in order to support multiple user store feature with SCIM.**/ String groupNameWithDomain = null; if (roleName.indexOf(CarbonConstants.DOMAIN_SEPARATOR) > 0) { groupNameWithDomain = roleName; } else { groupNameWithDomain = UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME + CarbonConstants.DOMAIN_SEPARATOR + roleName; } String userStoreDomainName = IdentityUtil.extractDomainFromName(roleName); if (isInternalOrApplicationGroup(userStoreDomainName) || isSCIMEnabled(userStoreDomainName)) { if (log.isDebugEnabled()) { log.debug("SCIM is enabled for the user-store domain : " + userStoreDomainName + ". " + "Including group with name : " + roleName + " in the response."); } Group group = getGroupWithName(groupNameWithDomain); filteredGroups.add(group); } else { if (log.isDebugEnabled()) { log.debug("SCIM is disabled for the user-store domain : " + userStoreDomainName + ". Hence " + "group with name : " + roleName + " is excluded in the response."); } } } else { //returning null will send a resource not found error to client by Charon. filteredGroups.clear(); filteredGroups.add(0); return filteredGroups; } } } } catch (org.wso2.carbon.user.core.UserStoreException e) { throw new CharonException("Error in filtering groups by attribute name : " + attributeName + ", " + "attribute value : " + attributeValue + " and filter operation " + filterOperation, e); } catch (org.wso2.carbon.user.api.UserStoreException e) { throw new CharonException("Error in filtering group with filter: " + attributeName + filterOperation + attributeValue, e); } catch (IdentitySCIMException e) { throw new CharonException("Error in retrieving SCIM Group information from database.", e); } catch (BadRequestException e) { throw new CharonException("Error in retrieving SCIM Group.", e); } //set the totalResults value in index 0 filteredGroups.set(0, filteredGroups.size() - 1); return filteredGroups; } @Override public Group updateGroup(Group oldGroup, Group newGroup, Map<String, Boolean> requiredAttributes) throws CharonException { try { String userStoreDomainFromSP = getUserStoreDomainFromSP(); if(userStoreDomainFromSP != null && !userStoreDomainFromSP.equalsIgnoreCase( IdentityUtil.extractDomainFromName(oldGroup.getDisplayName()))) { throw new CharonException("Group :" + oldGroup.getDisplayName() + "is not belong to user store " + userStoreDomainFromSP + "Hence group updating fail"); } oldGroup.setDisplayName(IdentityUtil.addDomainToName(UserCoreUtil.removeDomainFromName(oldGroup.getDisplayName()), IdentityUtil.extractDomainFromName(oldGroup.getDisplayName()))); newGroup.setDisplayName(IdentityUtil.addDomainToName(UserCoreUtil.removeDomainFromName(newGroup.getDisplayName()), IdentityUtil.extractDomainFromName(newGroup.getDisplayName()))); String primaryDomain = IdentityUtil.getPrimaryDomainName(); if (IdentityUtil.extractDomainFromName(newGroup.getDisplayName()).equals(primaryDomain) && !(IdentityUtil .extractDomainFromName(oldGroup.getDisplayName()) .equals(primaryDomain))) { String userStoreDomain = IdentityUtil.extractDomainFromName(oldGroup.getDisplayName()); newGroup.setDisplayName(IdentityUtil.addDomainToName(newGroup.getDisplayName(), userStoreDomain)); } else if (!IdentityUtil.extractDomainFromName(oldGroup.getDisplayName()) .equals(IdentityUtil.extractDomainFromName(newGroup.getDisplayName()))) { throw new IdentitySCIMException( "User store domain of the group is not matching with the given SCIM group Id."); } newGroup.setDisplayName(SCIMCommonUtils.getGroupNameWithDomain(newGroup.getDisplayName())); oldGroup.setDisplayName(SCIMCommonUtils.getGroupNameWithDomain(oldGroup.getDisplayName())); if (log.isDebugEnabled()) { log.debug("Updating group: " + oldGroup.getDisplayName()); } String groupName = newGroup.getDisplayName(); String userStoreDomainForGroup = IdentityUtil.extractDomainFromName(groupName); if (newGroup.getMembers() != null && !(newGroup.getMembers().isEmpty()) && !isInternalOrApplicationGroup(userStoreDomainForGroup)) { newGroup = addDomainToUserMembers(newGroup, userStoreDomainForGroup); } boolean updated = false; /*set thread local property to signal the downstream SCIMUserOperationListener about the provisioning route.*/ SCIMCommonUtils.setThreadLocalIsManagedThroughSCIMEP(true); //check if the user ids sent in updated group exist in the user store and the associated user name //also a matching one. List<Object> userIds = newGroup.getMembers(); List<String> userDisplayNames = newGroup.getMembersWithDisplayName(); /* compare user store domain of group and user store domain of user name , if there is a mismatch do not update the group */ if (userDisplayNames != null && userDisplayNames.size() > 0) { for (String userDisplayName : userDisplayNames) { String userStoreDomainForUser = IdentityUtil.extractDomainFromName(userDisplayName); if (!isInternalOrApplicationGroup(userStoreDomainForGroup) && !userStoreDomainForGroup.equalsIgnoreCase (userStoreDomainForUser)) { throw new IdentitySCIMException( userDisplayName + " does not " + "belongs to user store " + userStoreDomainForGroup); } } } if (CollectionUtils.isNotEmpty(userIds)) { String[] userNames = null; for (Object userId : userIds) { if (userId != null) { String userIdLocalClaim = SCIMCommonUtils.getSCIMtoLocalMappings().get(SCIMConstants .CommonSchemaConstants.ID_URI); if (StringUtils.isNotBlank(userIdLocalClaim)) { userNames = carbonUM.getUserList(userIdLocalClaim, IdentityUtil.addDomainToName((String) userId, userStoreDomainForGroup), UserCoreConstants.DEFAULT_PROFILE); } if (userNames == null || userNames.length == 0) { String error = "User: " + userId + " doesn't exist in the user store. " + "Hence, can not update the group: " + oldGroup.getDisplayName(); throw new IdentitySCIMException(error); } else { if (!UserCoreUtil.isContain(UserCoreUtil.removeDomainFromName(userNames[0]), UserCoreUtil.removeDomainFromNames(userDisplayNames.toArray( new String[userDisplayNames.size()])))) { throw new IdentitySCIMException("Given SCIM user Id and name not matching.."); } } } } } //we do not update Identity_SCIM DB here since it is updated in SCIMUserOperationListener's methods. //update name if it is changed if (!(oldGroup.getDisplayName().equalsIgnoreCase(newGroup.getDisplayName()))) { //update group name in carbon UM carbonUM.updateRoleName(oldGroup.getDisplayName(), newGroup.getDisplayName()); updated = true; } //find out added members and deleted members.. List<String> oldMembers = oldGroup.getMembersWithDisplayName(); List<String> newMembers = newGroup.getMembersWithDisplayName(); if (newMembers != null) { List<String> addedMembers = new ArrayList<>(); List<String> deletedMembers = new ArrayList<>(); //check for deleted members if (CollectionUtils.isNotEmpty(oldMembers)) { for (String oldMember : oldMembers) { if (newMembers != null && newMembers.contains(oldMember)) { continue; } deletedMembers.add(oldMember); } } //check for added members if (CollectionUtils.isNotEmpty(newMembers)) { for (String newMember : newMembers) { if (oldMembers != null && oldMembers.contains(newMember)) { continue; } addedMembers.add(newMember); } } if (CollectionUtils.isNotEmpty(addedMembers) || CollectionUtils.isNotEmpty(deletedMembers)) { carbonUM.updateUserListOfRole(newGroup.getDisplayName(), deletedMembers.toArray(new String[deletedMembers.size()]), addedMembers.toArray(new String[addedMembers.size()])); updated = true; } } if (updated) { log.info("Group: " + oldGroup.getDisplayName() + " is updated through SCIM."); } else { log.warn("There is no updated field in the group: " + oldGroup.getDisplayName() + ". Therefore ignoring the provisioning."); } } catch (UserStoreException | IdentitySCIMException e) { throw new CharonException(e.getMessage(), e); } catch (IdentityApplicationManagementException e){ throw new CharonException("Error retrieving User Store name. ", e); } catch (BadRequestException | CharonException e) { throw new CharonException("Error in updating the group", e); } return newGroup; } @Override public List<Object> listGroupsWithPost(SearchRequest searchRequest, Map<String, Boolean> requiredAttributes) throws BadRequestException, NotImplementedException, CharonException { return listGroupsWithGET(searchRequest.getFilter(), searchRequest.getStartIndex(), searchRequest.getCount(), searchRequest.getSortBy(), searchRequest.getSortOder(), searchRequest.getDomainName(), requiredAttributes); } private String getUserStoreDomainFromSP() throws IdentityApplicationManagementException { ServiceProvider serviceProvider = null; if (serviceProvider != null && serviceProvider.getInboundProvisioningConfig() != null && !StringUtils.isBlank(serviceProvider.getInboundProvisioningConfig().getProvisioningUserStore())) { return serviceProvider.getInboundProvisioningConfig().getProvisioningUserStore(); } return null; } /** * This method will return whether SCIM is enabled or not for a particular userStore. (from SCIMEnabled user * store property) * @param userStoreName user store name * @return whether scim is enabled or not for the particular user store */ private boolean isSCIMEnabled(String userStoreName) { UserStoreManager userStoreManager = carbonUM.getSecondaryUserStoreManager(userStoreName); if (userStoreManager != null) { try { return userStoreManager.isSCIMEnabled(); } catch (UserStoreException e) { log.error("Error while evaluating isSCIMEnalbed for user store " + userStoreName, e); } } return false; } /** * get the specfied user from the store * @param userName * @param claimURIList * @return * @throws CharonException */ private User getSCIMUser(String userName, List<String> claimURIList, Map<String, String> scimToLocalClaimsMap) throws CharonException { User scimUser = null; String userStoreDomainName = IdentityUtil.extractDomainFromName(userName); if(StringUtils.isNotBlank(userStoreDomainName) && !isSCIMEnabled(userStoreDomainName)){ throw new CharonException("Cannot get user through scim to user store " + ". SCIM is not " + "enabled for user store " + userStoreDomainName); } try { //obtain user claim values Map<String, String> userClaimValues = carbonUM.getUserClaimValues( userName, claimURIList.toArray(new String[claimURIList.size()]), null); Map<String, String> attributes = SCIMCommonUtils.convertLocalToSCIMDialect(userClaimValues, scimToLocalClaimsMap); if (!attributes.containsKey(SCIMConstants.CommonSchemaConstants.ID_URI)) { return scimUser; } //skip simple type addresses claim because it is complex with sub types in the schema if (attributes.containsKey(SCIMConstants.UserSchemaConstants.ADDRESSES_URI)) { attributes.remove(SCIMConstants.UserSchemaConstants.ADDRESSES_URI); } // Add username with domain name attributes.put(SCIMConstants.UserSchemaConstants.USER_NAME_URI, userName); //get groups of user and add it as groups attribute String[] roles = carbonUM.getRoleListOfUser(userName); //construct the SCIM Object from the attributes scimUser = (User) AttributeMapper.constructSCIMObjectFromAttributes(attributes, 1); Map<String, Group> groupMetaAttributesCache = new HashMap<>(); //add groups of user: for (String role : roles) { if (UserCoreUtil.isEveryoneRole(role, carbonUM.getRealmConfiguration()) || CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME.equalsIgnoreCase(role) || role.toLowerCase().startsWith((UserCoreConstants.INTERNAL_DOMAIN + CarbonConstants.DOMAIN_SEPARATOR).toLowerCase())) { // carbon specific roles do not possess SCIM info, hence // skipping them. // skip intenal roles continue; } if (SCIMCommonUtils.isFilteringEnhancementsEnabled()) { if (!StringUtils.contains(role, CarbonConstants.DOMAIN_SEPARATOR)) { role = UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME + CarbonConstants.DOMAIN_SEPARATOR + role; } } Group group = groupMetaAttributesCache.get(role); if (group == null && !groupMetaAttributesCache.containsKey(role)) { group = getGroupOnlyWithMetaAttributes(role); groupMetaAttributesCache.put(role, group); } if (group != null) { // can be null for non SCIM groups scimUser.setGroup(null, group.getId(), role); } } } catch (UserStoreException | CharonException | NotFoundException | IdentitySCIMException |BadRequestException e) { throw new CharonException("Error in getting user information for user: " + userName, e); } return scimUser; } /** * get the specified user from the store * * @param userNames Array of usernames * @param claimURIList Requested claim list * @return Array of SCIM User * @throws CharonException CharonException */ private User[] getSCIMUsers(String[] userNames, List<String> claimURIList, Map<String, String> scimToLocalClaimsMap) throws CharonException { List<User> scimUsers = new ArrayList<>(); //obtain user claim values UserClaimSearchEntry[] searchEntries; Map<String, List<String>> usersRoles; try { searchEntries = ((AbstractUserStoreManager) carbonUM).getUsersClaimValues( userNames, claimURIList.toArray(new String[claimURIList.size()]), null); usersRoles = ((AbstractUserStoreManager) carbonUM).getRoleListOfUsers(userNames); } catch (org.wso2.carbon.user.core.UserStoreException e) { throw new CharonException("Error occurred while retrieving SCIM user information", e); } Map<String, Group> groupMetaAttributesCache = new HashMap<>(); for (String userName : userNames) { String userStoreDomainName = IdentityUtil.extractDomainFromName(userName); if (isSCIMEnabled(userStoreDomainName)) { if (log.isDebugEnabled()) { log.debug("SCIM is enabled for the user-store domain : " + userStoreDomainName + ". " + "Including user : " + userName + " in the response."); } User scimUser; Map<String, String> userClaimValues = new HashMap<>(); for (UserClaimSearchEntry entry : searchEntries) { if (StringUtils.isNotBlank(entry.getUserName()) && entry.getUserName().equals(userName)) { userClaimValues = entry.getClaims(); } } Map<String, String> attributes; try { attributes = SCIMCommonUtils.convertLocalToSCIMDialect(userClaimValues, scimToLocalClaimsMap); } catch (UserStoreException e) { throw new CharonException("Error in converting local claims to SCIM dialect for user: " + userName, e); } try { if (!attributes.containsKey(SCIMConstants.CommonSchemaConstants.ID_URI)) { continue; } //skip simple type addresses claim because it is complex with sub types in the schema if (attributes.containsKey(SCIMConstants.UserSchemaConstants.ADDRESSES_URI)) { attributes.remove(SCIMConstants.UserSchemaConstants.ADDRESSES_URI); } // Add username with domain name attributes.put(SCIMConstants.UserSchemaConstants.USER_NAME_URI, userName); //get groups of user and add it as groups attribute List<String> roleList = usersRoles.get(userName); String[] roles = new String[0]; if (CollectionUtils.isNotEmpty(roleList)) { roles = roleList.toArray(new String[0]); } //construct the SCIM Object from the attributes scimUser = (User) AttributeMapper.constructSCIMObjectFromAttributes(attributes, 1); //add groups of user for (String role : roles) { if (UserCoreUtil.isEveryoneRole(role, carbonUM.getRealmConfiguration()) || CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME.equalsIgnoreCase(role) || role.toLowerCase().startsWith((UserCoreConstants.INTERNAL_DOMAIN + CarbonConstants.DOMAIN_SEPARATOR).toLowerCase())) { // carbon specific roles do not possess SCIM info, hence // skipping them. // skip internal roles continue; } if (SCIMCommonUtils.isFilteringEnhancementsEnabled()) { if (!StringUtils.contains(role, CarbonConstants.DOMAIN_SEPARATOR)) { role = UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME + CarbonConstants.DOMAIN_SEPARATOR + role; } } Group group = groupMetaAttributesCache.get(role); if (group == null && !groupMetaAttributesCache.containsKey(role)) { group = getGroupOnlyWithMetaAttributes(role); groupMetaAttributesCache.put(role, group); } if (group != null) { // can be null for non SCIM groups scimUser.setGroup(null, group.getId(), role); } } } catch (UserStoreException | CharonException | NotFoundException | IdentitySCIMException | BadRequestException e) { throw new CharonException("Error in getting user information for user: " + userName, e); } if (scimUser != null) { scimUsers.add(scimUser); } } else { if (log.isDebugEnabled()) { log.debug("SCIM is disabled for the user-store domain : " + userStoreDomainName + ". " + "Hence user : "+ userName + " in this domain is excluded in the response."); } } } return scimUsers.toArray(new User[0]); } /** * Get group with only meta attributes. * * @param groupName * @return * @throws CharonException * @throws IdentitySCIMException * @throws org.wso2.carbon.user.core.UserStoreException */ private Group getGroupOnlyWithMetaAttributes(String groupName) throws CharonException, IdentitySCIMException, org.wso2.carbon.user.core.UserStoreException, BadRequestException { //get other group attributes and set. Group group = new Group(); group.setDisplayName(groupName); SCIMGroupHandler groupHandler = new SCIMGroupHandler(carbonUM.getTenantId()); return groupHandler.getGroupWithAttributes(group, groupName); } /** * returns whether particular user store domain is application or internal. * @param userstoreDomain user store domain * @return whether passed domain name is "internal" or "application" */ private boolean isInternalOrApplicationGroup(String userstoreDomain){ if(StringUtils.isNotBlank(userstoreDomain) && (SCIMCommonConstants.APPLICATION_DOMAIN.equalsIgnoreCase(userstoreDomain) || SCIMCommonConstants.INTERNAL_DOMAIN.equalsIgnoreCase(userstoreDomain))){ return true; } return false; } /** * Get the full group with all the details including users. * * @param groupName * @return * @throws CharonException * @throws org.wso2.carbon.user.core.UserStoreException * @throws IdentitySCIMException */ private Group getGroupWithName(String groupName) throws CharonException, org.wso2.carbon.user.core.UserStoreException, IdentitySCIMException, BadRequestException { String userStoreDomainName = IdentityUtil.extractDomainFromName(groupName); if(!isInternalOrApplicationGroup(userStoreDomainName) && StringUtils.isNotBlank(userStoreDomainName) && !isSCIMEnabled(userStoreDomainName)){ throw new CharonException("Cannot retrieve group through scim to user store " + ". SCIM is not " + "enabled for user store " + userStoreDomainName); } Group group = new Group(); group.setDisplayName(groupName); String[] userNames = carbonUM.getUserListOfRole(groupName); //get the ids of the users and set them in the group with id + display name if (userNames != null && userNames.length != 0) { for (String userName : userNames) { String userId = carbonUM.getUserClaimValue(userName, SCIMConstants.CommonSchemaConstants.ID_URI, null); group.setMember(userId, userName); } } //get other group attributes and set. SCIMGroupHandler groupHandler = new SCIMGroupHandler(carbonUM.getTenantId()); group = groupHandler.getGroupWithAttributes(group, groupName); return group; } /** * This is used to add domain name to the members of a group * * @param group * @param userStoreDomain * @return * @throws CharonException */ private Group addDomainToUserMembers(Group group, String userStoreDomain) throws CharonException { List<Object> membersId = group.getMembers(); if (StringUtils.isBlank(userStoreDomain) || membersId == null || membersId.isEmpty()) { return group; } if (group.isAttributeExist(SCIMConstants.GroupSchemaConstants.MEMBERS)) { MultiValuedAttribute members = (MultiValuedAttribute) group.getAttributeList().get( SCIMConstants.GroupSchemaConstants.MEMBERS); List<Attribute> attributeValues = members.getAttributeValues(); if (attributeValues != null && !attributeValues.isEmpty()) { for (Attribute attributeValue : attributeValues) { SimpleAttribute displayNameAttribute = (SimpleAttribute) attributeValue.getSubAttribute( SCIMConstants.CommonSchemaConstants.DISPLAY); String displayName = AttributeUtil.getStringValueOfAttribute(displayNameAttribute.getValue(), displayNameAttribute.getType()); displayNameAttribute.setValue(IdentityUtil.addDomainToName( UserCoreUtil.removeDomainFromName(displayName), userStoreDomain)); } } } return group; } private List<String> getMappedClaimList(Map<String, Boolean> requiredAttributes){ ArrayList<String> claimsList = new ArrayList<>(); for(Map.Entry<String, Boolean> claim : requiredAttributes.entrySet()){ if(claim.getValue().equals(true)){ } else { claimsList.add(claim.getKey()); } } return claimsList; } /* * This returns the only required attributes for value querying * @param claimURIList * @param requiredAttributes * @return */ private List<String> getOnlyRequiredClaims(Set<String> claimURIList, Map<String, Boolean> requiredAttributes) { List<String> requiredClaimList = new ArrayList<>(); for(String requiredClaim : requiredAttributes.keySet()) { if(requiredAttributes.get(requiredClaim)) { if (claimURIList.contains(requiredClaim)) { requiredClaimList.add(requiredClaim); } else { String[] parts = requiredClaim.split("[.]"); for (String claim : claimURIList) { if (parts.length == 3) { if (claim.contains(parts[0] +"." + parts[1])) { if (!requiredClaimList.contains(claim)) { requiredClaimList.add(claim); } } } else if (parts.length == 2) { if (claim.contains(parts[0])) { if (!requiredClaimList.contains(claim)) { requiredClaimList.add(claim); } } } } } } else { if (!requiredClaimList.contains(requiredClaim)) { requiredClaimList.add(requiredClaim); } } } return requiredClaimList; } /** * Paginate a list of users names according to a given offset and a count. * * @param users A list of unpaginated users. * @param limit The total number of results required (Zero will return all the users). * @param offset The starting index of the count (limit). * @return A list of paginated users */ private String[] paginateUsers(String[] users, int limit, int offset) { // If the results are empty, an empty list should be returned. if (users == null) { return new String[0]; } Arrays.sort(users); // Validate offset value. if (offset <= 0) { offset = 1; } // If the results is less than the offset return an empty user list. if (offset > users.length) { return new String[0]; } // If the limit is zero, all the users needs to be returned after verifying the offset. if (limit <= 0) { if (offset == 1) { // This is to support backward compatibility. return users; } else { return Arrays.copyOfRange(users, offset - 1, users.length); } } else { // If users.length > limit + offset, then return only the users bounded by the offset and the limit. if (users.length > limit + offset) { return Arrays.copyOfRange(users, offset - 1, limit + offset - 1); } else { // Return all the users from the offset. return Arrays.copyOfRange(users, offset - 1, users.length); } } } /** * check whether the filtering is supported * @param filterOperation operator use for filtering * @return boolean to check whether operator is supported */ private boolean isNotFilteringSupported(String filterOperation) { return !filterOperation.equalsIgnoreCase(SCIMCommonConstants.EQ) && !filterOperation.equalsIgnoreCase(SCIMCommonConstants.CO) && !filterOperation.equalsIgnoreCase(SCIMCommonConstants.SW) && !filterOperation.equalsIgnoreCase(SCIMCommonConstants.EW); } private String[] getUserListOfRoles(String[] roleNames) throws org.wso2.carbon.user.core.UserStoreException { String[] userNames; Set<String> users = new HashSet<>(); if (roleNames != null) { for (String roleName : roleNames) { users.addAll(Arrays.asList(carbonUM.getUserListOfRole(roleName))); } } userNames = users.toArray(new String[0]); return userNames; } /** * get the search value after appending the delimiters * @param filterOperation operator value * @param attributeValue search value * @param delimiter delimiter for based on search type * @return search attribute */ private String getSearchAttribute(String filterOperation, String attributeValue, String delimiter) { String searchAttribute = null; if (filterOperation.equalsIgnoreCase(SCIMCommonConstants.CO)) { String[] attributeItems = attributeValue.split(CarbonConstants.DOMAIN_SEPARATOR); if(attributeItems.length == 2) { searchAttribute = attributeItems[0] + CarbonConstants.DOMAIN_SEPARATOR + delimiter + attributeItems[1] + delimiter; } else { searchAttribute = delimiter + attributeValue + delimiter; } } else if (filterOperation.equalsIgnoreCase(SCIMCommonConstants.SW)) { searchAttribute = attributeValue + delimiter; } else if (filterOperation.equalsIgnoreCase(SCIMCommonConstants.EW)) { // Extract the domain attached to the attribute value and then append the delimiter. String[] attributeItems = attributeValue.split(CarbonConstants.DOMAIN_SEPARATOR); if (attributeItems.length == 2) { searchAttribute = attributeItems[0] + CarbonConstants.DOMAIN_SEPARATOR + delimiter + attributeItems[1]; } else { searchAttribute = delimiter + attributeValue; } } else if (filterOperation.equalsIgnoreCase(SCIMCommonConstants.EQ)) { searchAttribute = attributeValue; } return searchAttribute; } /** * get list of roles that matches the search criteria * @param filterOperation operator value * @param attributeValue search value * @return list of role names * @throws org.wso2.carbon.user.core .UserStoreException */ private String[] getRoleNames(String filterOperation, String attributeValue) throws org.wso2.carbon.user.core .UserStoreException { String searchAttribute = getSearchAttribute(filterOperation, attributeValue, FILTERING_DELIMITER); return ((AbstractUserStoreManager) carbonUM).getRoleNames(searchAttribute, MAX_ITEM_LIMIT_UNLIMITED, true, true, true); } /** * get list of user that matches the search criteria * @param attributeName field name for search * @param filterOperation operator * @param attributeValue search value * @return list of users * @throws org.wso2.carbon.user.core.UserStoreException */ private String[] getUserNames(String attributeName, String filterOperation, String attributeValue) throws org.wso2.carbon.user.core.UserStoreException { String searchAttribute = getSearchAttribute(filterOperation, attributeValue, FILTERING_DELIMITER); String attributeNameInLocalDialect = SCIMCommonUtils.getSCIMtoLocalMappings().get(attributeName); if (StringUtils.isBlank(attributeNameInLocalDialect)) { attributeNameInLocalDialect = attributeName; } return carbonUM.getUserList(attributeNameInLocalDialect, searchAttribute, UserCoreConstants.DEFAULT_PROFILE); } /** * get the list of groups that matches the search criteria * @param attributeName attribute which is used to search * @param filterOperation operator value * @param attributeValue search value * @return list of user groups * @throws org.wso2.carbon.user.core.UserStoreException * @throws IdentitySCIMException */ private String[] getGroupList(String attributeName, String filterOperation, String attributeValue) throws org.wso2.carbon.user.core.UserStoreException, IdentitySCIMException { String[] userRoleList; if (attributeName.equals(SCIMConstants.GroupSchemaConstants.DISPLAY_URI) || attributeName.equals(SCIMConstants.GroupSchemaConstants.VALUE_URI)) { String[] userList; if (attributeName.equals(SCIMConstants.GroupSchemaConstants.DISPLAY_URI)) { userList = getUserNames(SCIMConstants.UserSchemaConstants.USER_NAME_URI, filterOperation, attributeValue); } else { userList = getUserNames(SCIMConstants.CommonSchemaConstants.ID_URI, filterOperation, attributeValue); } Set<String> fullRoleList = new HashSet<>(); List<String> currentRoleList; if (userList != null) { for (String userName : userList) { String[] roles = carbonUM.getRoleListOfUser(userName); currentRoleList = Arrays.asList(roles); fullRoleList.addAll(currentRoleList); } } userRoleList = fullRoleList.toArray(new String[fullRoleList.size()]); } else if (attributeName.equals(SCIMConstants.GroupSchemaConstants.DISPLAY_NAME_URI)) { userRoleList = getRoleNames(filterOperation, attributeValue); } else { userRoleList = getGroupNamesFromDB(attributeName, filterOperation, attributeValue); } return userRoleList; } /** * return when search using meta data; list of groups * @param attributeName attribute which is used to search * @param filterOperation operator value * @param attributeValue search value * @return list of groups * @throws org.wso2.carbon.user.core.UserStoreException * @throws IdentitySCIMException */ private String[] getGroupNamesFromDB(String attributeName, String filterOperation, String attributeValue) throws org.wso2.carbon.user.core.UserStoreException, IdentitySCIMException { String searchAttribute = getSearchAttribute(filterOperation, attributeValue, SQL_FILTERING_DELIMITER); SCIMGroupHandler groupHandler = new SCIMGroupHandler(carbonUM.getTenantId()); return groupHandler.getGroupListFromAttributeName(attributeName, searchAttribute); } private boolean isPaginatedUserStoreAvailable() { String enablePaginatedUserStore = IdentityUtil.getProperty(ENABLE_PAGINATED_USER_STORE); if (StringUtils.isNotBlank(enablePaginatedUserStore)) { return Boolean.parseBoolean(enablePaginatedUserStore); } return true; } /** * Check whether claim is an immutable claim. * * @param claim claim URI. * @return */ private boolean isImmutableClaim(String claim) throws UserStoreException { Map<String, String> claimMappings = SCIMCommonUtils.getSCIMtoLocalMappings(); return claim.equals(claimMappings.get(SCIMConstants.CommonSchemaConstants.ID_URI)) || claim.equals(claimMappings.get(SCIMConstants.UserSchemaConstants.USER_NAME_URI)) || claim.equals(claimMappings.get(SCIMConstants.UserSchemaConstants.ROLES_URI + "." + SCIMConstants.DEFAULT)) || claim.equals(claimMappings.get(SCIMConstants.CommonSchemaConstants.CREATED_URI)) || claim.equals(claimMappings.get(SCIMConstants.CommonSchemaConstants.LAST_MODIFIED_URI)) || claim.equals(claimMappings.get(SCIMConstants.CommonSchemaConstants.LOCATION_URI)) || claim.equals(claimMappings.get(SCIMConstants.UserSchemaConstants.FAMILY_NAME_URI)) || claim.contains(UserCoreConstants.ClaimTypeURIs.IDENTITY_CLAIM_URI); } }
Change user creation reponse Get the user details from the userstore and send back the response for user creation. By doing this we could make scim get response and user creation response to be ideal.
components/org.wso2.carbon.identity.scim2.common/src/main/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManager.java
Change user creation reponse
<ide><path>omponents/org.wso2.carbon.identity.scim2.common/src/main/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManager.java <ide> carbonUM.addUser(user.getUserName(), user.getPassword(), null, claimsInLocalDialect, null); <ide> log.info("User: " + user.getUserName() + " is created through SCIM."); <ide> <add> // Get Claims related to SCIM claim dialect <add> Map<String, String> scimToLocalClaimsMap = SCIMCommonUtils.getSCIMtoLocalMappings(); <add> // Get required SCIM Claims in local claim dialect. <add> List<String> requiredClaimsInLocalDialect = getRequiredClaimsInLocalDialect(scimToLocalClaimsMap, <add> requiredAttributes); <add> // Get the user from the user store in order to get the default attributes during the user creation <add> // response. <add> user = this.getSCIMUser(user.getUserName(), requiredClaimsInLocalDialect, scimToLocalClaimsMap); <add> // Set the schemas of the scim user. <add> user.setSchemas(); <ide> } catch (UserStoreException e) { <ide> handleErrorsOnUserNameAndPasswordPolicy(e); <ide> String errMsg = "Error in adding the user: " + user.getUserName() + " to the user store. "; <ide> } else { <ide> //get Claims related to SCIM claim dialect <ide> Map<String, String> scimToLocalClaimsMap = SCIMCommonUtils.getSCIMtoLocalMappings(); <del> List<String> requiredClaims = getOnlyRequiredClaims(scimToLocalClaimsMap.keySet(), requiredAttributes); <del> List<String> requiredClaimsInLocalDialect; <del> if (MapUtils.isNotEmpty(scimToLocalClaimsMap)) { <del> scimToLocalClaimsMap.keySet().retainAll(requiredClaims); <del> requiredClaimsInLocalDialect = new ArrayList<>(scimToLocalClaimsMap.values()); <del> } else { <del> if (log.isDebugEnabled()) { <del> log.debug("SCIM to Local Claim mappings list is empty."); <del> } <del> requiredClaimsInLocalDialect = new ArrayList<>(); <del> } <add> List<String> requiredClaimsInLocalDialect = getRequiredClaimsInLocalDialect(scimToLocalClaimsMap, <add> requiredAttributes); <ide> //we assume (since id is unique per user) only one user exists for a given id <ide> scimUser = this.getSCIMUser(userNames[0], requiredClaimsInLocalDialect, scimToLocalClaimsMap); <ide> //set the schemas of the scim user <ide> claim.equals(claimMappings.get(SCIMConstants.UserSchemaConstants.FAMILY_NAME_URI)) || <ide> claim.contains(UserCoreConstants.ClaimTypeURIs.IDENTITY_CLAIM_URI); <ide> } <add> <add> /** <add> * Get the local claims mapped to the required scim claims. <add> */ <add> private List<String> getRequiredClaimsInLocalDialect(Map<String, String> scimToLocalClaimsMap, Map<String, <add> Boolean> requiredAttributes) <add> throws UserStoreException { <add> <add> List<String> requiredClaims = getOnlyRequiredClaims(scimToLocalClaimsMap.keySet(), requiredAttributes); <add> List<String> requiredClaimsInLocalDialect; <add> if (MapUtils.isNotEmpty(scimToLocalClaimsMap)) { <add> scimToLocalClaimsMap.keySet().retainAll(requiredClaims); <add> requiredClaimsInLocalDialect = new ArrayList<>(scimToLocalClaimsMap.values()); <add> } else { <add> if (log.isDebugEnabled()) { <add> log.debug("SCIM to Local Claim mappings list is empty."); <add> } <add> requiredClaimsInLocalDialect = new ArrayList<>(); <add> } <add> return requiredClaimsInLocalDialect; <add> } <ide> }
Java
epl-1.0
e13230e0f77fc038e089d77cd6f28783ffa1581b
0
arcanefoam/jgrapht,mt0803/jgrapht,lingeringsocket/jgrapht,alexeykudinkin/jgrapht,cthiebaud/jgrapht,kashak79/jgrapht,AidanDelaney/jgrapht,Infeligo/jgrapht,hal/jgrapht,wselwood/jgrapht,WorstCase00/jgrapht,Infeligo/jgrapht,arcanefoam/jgrapht,AidanDelaney/jgrapht,alexeykudinkin/jgrapht,rcpoison/jgrapht,hal/jgrapht,wselwood/jgrapht,feilong0309/jgrapht,WorstCase00/jgrapht,mt0803/jgrapht,WorstCase00/jgrapht,feilong0309/jgrapht,VoVanHai/jgrapht,gjroelofs/jgrapht,WorstCase00/jgrapht,kashak79/jgrapht,cthiebaud/jgrapht,gjroelofs/jgrapht
/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Lead: Barak Naveh ([email protected]) * * (C) Copyright 2003, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------ * AbstractGraph.java * ------------------ * (C) Copyright 2003, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): - * * $Id$ * * Changes * ------- * 24-Jul-2003 : Initial revision (BN); * */ package org._3pq.jgrapht.graph; import java.util.Collection; import java.util.Iterator; import java.util.List; import org._3pq.jgrapht.Edge; import org._3pq.jgrapht.Graph; /** * A skeletal implementation of the <tt>Graph</tt> interface, to minimize the * effort required to implement graph interfaces. This implementation is * applicable to both: directed graphs and undirected graphs. * * @author Barak Naveh * * @see org._3pq.jgrapht.Graph * @see org._3pq.jgrapht.DirectedGraph * @see org._3pq.jgrapht.UndirectedGraph */ public abstract class AbstractGraph implements Graph { /** * Construct a new empty graph object. */ public AbstractGraph( ) {} /** * @see Graph#addAllEdges(Collection) */ public boolean addAllEdges( Collection edges ) { boolean modified = false; for( Iterator iter = edges.iterator( ); iter.hasNext( ); ) { modified |= addEdge( (Edge) iter.next( ) ); } return modified; } /** * @see Graph#addAllVertices(Collection) */ public boolean addAllVertices( Collection vertices ) { boolean modified = false; for( Iterator iter = vertices.iterator( ); iter.hasNext( ); ) { modified |= addVertex( iter.next( ) ); } return modified; } /** * @see Graph#containsEdge(Object, Object) */ public boolean containsEdge( Object sourceVertex, Object targetVertex ) { return getEdge( sourceVertex, targetVertex ) != null; } /** * @see Graph#removeAllEdges(Collection) */ public boolean removeAllEdges( Collection edges ) { boolean modified = false; for( Iterator iter = edges.iterator( ); iter.hasNext( ); ) { modified |= removeEdge( (Edge) iter.next( ) ); } return modified; } /** * @see Graph#removeAllEdges(Object, Object) */ public List removeAllEdges( Object sourceVertex, Object targetVertex ) { List removed = getAllEdges( sourceVertex, targetVertex ); removeAllEdges( removed ); return removed; } /** * @see Graph#removeAllVertices(Collection) */ public boolean removeAllVertices( Collection vertices ) { boolean modified = false; for( Iterator iter = vertices.iterator( ); iter.hasNext( ); ) { modified |= removeVertex( iter.next( ) ); } return modified; } /** * Ensures that the specified vertex exists in this graph, or else throws * exception. * * @param v vertex * * @throws NullPointerException if specified vertex is <code>null</code>. * @throws IllegalArgumentException if specified vertex does not exist in * this graph. */ protected boolean assertVertexExist( Object v ) { if( containsVertex( v ) ) { return true; } else if( v == null ) { throw new NullPointerException( ); } else { throw new IllegalArgumentException( "no such vertex in graph" ); } } }
src/org/_3pq/jgrapht/graph/AbstractGraph.java
/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Lead: Barak Naveh ([email protected]) * * (C) Copyright 2003, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------ * AbstractGraph.java * ------------------ * (C) Copyright 2003, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): - * * $Id$ * * Changes * ------- * 24-Jul-2003 : Initial revision (BN); * */ package org._3pq.jgrapht.graph; import java.util.Collection; import java.util.Iterator; import java.util.List; import org._3pq.jgrapht.Edge; import org._3pq.jgrapht.Graph; /** * A skeletal implementation of the <tt>Graph</tt> interface, to minimize the * effort required to implement graph interfaces. This implementation is * applicable to both: directed graphs and undirected graphs. * * @author Barak Naveh * * @see org._3pq.jgrapht.Graph * @see org._3pq.jgrapht.DirectedGraph * @see org._3pq.jgrapht.UndirectedGraph */ public abstract class AbstractGraph implements Graph { /** * Construct a new empty graph object. */ public AbstractGraph( ) {} /** * @see Graph#addAllEdges(Collection) */ public boolean addAllEdges( Collection edges ) { boolean modified = false; for( Iterator iter = edges.iterator( ); iter.hasNext( ); ) { modified |= addEdge( (Edge) iter.next( ) ); } return modified; } /** * @see Graph#addAllVertices(Collection) */ public boolean addAllVertices( Collection vertices ) { boolean modified = false; for( Iterator iter = vertices.iterator( ); iter.hasNext( ); ) { modified |= addVertex( iter.next( ) ); } return modified; } /** * @see Graph#containsEdge(Object, Object) */ public boolean containsEdge( Object sourceVertex, Object targetVertex ) { return getEdge( sourceVertex, targetVertex ) != null; } /** * @see Graph#removeAllEdges(Collection) */ public boolean removeAllEdges( Collection edges ) { boolean modified = false; for( Iterator iter = edges.iterator( ); iter.hasNext( ); ) { modified |= removeEdge( (Edge) iter.next( ) ); } return modified; } /** * @see Graph#removeAllEdges(Object, Object) */ public List removeAllEdges( Object sourceVertex, Object targetVertex ) { List removed = getAllEdges( sourceVertex, targetVertex ); removeAllEdges( removed ); return removed; } /** * @see Graph#removeAllVertices(Collection) */ public boolean removeAllVertices( Collection vertices ) { boolean modified = false; for( Iterator iter = vertices.iterator( ); iter.hasNext( ); ) { modified |= removeVertex( iter.next( ) ); } return modified; } /** * Ensures that the specified vertex exists in this graph, or else throws * exception. * * @param v vertex * * @throws NullPointerException if specified vertex is <code>null</code>. * @throws IllegalArgumentException if specified vertex does not exist in * this graph. */ protected void assertVertexExist( Object v ) { if( containsVertex( v ) ) { return; } else if( v == null ) { throw new NullPointerException( ); } else { throw new IllegalArgumentException( "no such vertex in graph" ); } } }
made assertions return boolean, to prep to use as: assert <assertion-method> git-svn-id: ea8dc44323ac57449cbfb89d58b37d570afecc0a@134 4a7320f3-3611-0410-a4d0-ef7ff04b8906
src/org/_3pq/jgrapht/graph/AbstractGraph.java
made assertions return boolean, to prep to use as: assert <assertion-method>
<ide><path>rc/org/_3pq/jgrapht/graph/AbstractGraph.java <ide> * @throws IllegalArgumentException if specified vertex does not exist in <ide> * this graph. <ide> */ <del> protected void assertVertexExist( Object v ) { <add> protected boolean assertVertexExist( Object v ) { <ide> if( containsVertex( v ) ) { <del> return; <add> return true; <ide> } <ide> else if( v == null ) { <ide> throw new NullPointerException( );
Java
apache-2.0
c4717f849b4c21636bf5addb33a36e101115645b
0
wro4j/wro4j,wro4j/wro4j,wro4j/wro4j
/** * Copyright Alex Objelean */ package ro.isdc.wro.extensions.processor.support; import static org.apache.commons.lang3.Validate.notNull; import org.apache.commons.lang3.time.DateUtils; import org.apache.commons.pool2.BasePooledObjectFactory; import org.apache.commons.pool2.PooledObject; import org.apache.commons.pool2.impl.DefaultPooledObject; import org.apache.commons.pool2.impl.GenericObjectPool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ro.isdc.wro.util.ObjectFactory; /** * A generic aware object pool wrapper. Probably not the best name, but it can be changed later. It helps you to avoid * the cast and hides the exception handling by throwing {@link RuntimeException} when borrowing or returning object to * the pool fails. * * @author Alex Objelean * @created 10 Nov 2011 * @since 1.4.2 */ public class ObjectPoolHelper<T> { private static final Logger LOG = LoggerFactory.getLogger(ObjectPoolHelper.class); private static final int MAX_IDLE = 5; private static final long MAX_WAIT = 10L * DateUtils.MILLIS_PER_SECOND; private static final long EVICTABLE_IDLE_TIME = 30L * DateUtils.MILLIS_PER_SECOND; // Allows using the objects from the pool in a thread-safe fashion. private GenericObjectPool<T> objectPool; public ObjectPoolHelper(final ObjectFactory<T> objectFactory) { notNull(objectFactory); objectPool = createObjectPool(objectFactory); notNull(objectPool); } /** * Ensure that a not null pool will be created. */ private GenericObjectPool<T> createObjectPool(final ObjectFactory<T> objectFactory) { final GenericObjectPool<T> pool = newObjectPool(objectFactory); notNull(pool); return pool; } /** * Creates a {@link GenericObjectPool}. Override this method to set custom objectPool configurations. */ protected GenericObjectPool<T> newObjectPool(final ObjectFactory<T> objectFactory) { final int maxActive = Math.max(2, Runtime.getRuntime().availableProcessors()); final GenericObjectPool<T> pool = new GenericObjectPool<T>(new BasePooledObjectFactory<T>() { @Override public T create() throws Exception { return objectFactory.create(); } @Override public PooledObject<T> wrap(T obj) { return new DefaultPooledObject<T>(obj); } }); pool.setMaxTotal(maxActive); pool.setMaxIdle(MAX_IDLE); pool.setMaxWaitMillis(MAX_WAIT); /** * Block when exhausted, otherwise the pool object retrieval can fail. More details here: * <a>http://code.google.com/p/wro4j/issues/detail?id=364</a> */ pool.setBlockWhenExhausted(true); // make object eligible for eviction after a predefined amount of time. pool.setSoftMinEvictableIdleTimeMillis(EVICTABLE_IDLE_TIME); pool.setTimeBetweenEvictionRunsMillis(EVICTABLE_IDLE_TIME); return pool; } /** * @return object from the pool. */ public T getObject() { try { return objectPool.borrowObject(); } catch (final Exception e) { // should never happen throw new RuntimeException("Cannot get object from the pool", e); } } public void returnObject(final T engine) { notNull(engine); try { objectPool.returnObject(engine); } catch (final Exception e) { // should never happen throw new RuntimeException("Cannot get object from the pool", e); } } /** * Use a custom {@link GenericObjectPool}. * * @param objectPool * to use. */ public final void setObjectPool(final GenericObjectPool<T> objectPool) { notNull(objectPool); this.objectPool = objectPool; } /** * Close the object pool to avoid the memory leak. * * @throws Exception * if the close operation failed. */ public void destroy() throws Exception { LOG.debug("closing objectPool"); objectPool.close(); } }
wro4j-extensions/src/main/java/ro/isdc/wro/extensions/processor/support/ObjectPoolHelper.java
/** * Copyright Alex Objelean */ package ro.isdc.wro.extensions.processor.support; import static org.apache.commons.lang3.Validate.notNull; import org.apache.commons.pool2.BasePooledObjectFactory; import org.apache.commons.pool2.PooledObject; import org.apache.commons.pool2.impl.DefaultPooledObject; import org.apache.commons.pool2.impl.GenericObjectPool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ro.isdc.wro.util.ObjectFactory; /** * A generic aware object pool wrapper. Probably not the best name, but it can be changed later. It helps you to avoid * the cast and hides the exception handling by throwing {@link RuntimeException} when borrowing or returning object to * the pool fails. * * @author Alex Objelean * @created 10 Nov 2011 * @since 1.4.2 */ public class ObjectPoolHelper<T> { private static final Logger LOG = LoggerFactory.getLogger(ObjectPoolHelper.class); private static final int MAX_IDLE = 2; private static final long MAX_WAIT = 5L * 1000L; private static final long EVICTABLE_IDLE_TIME = 30 * 1000L; // Allows using the objects from the pool in a thread-safe fashion. private GenericObjectPool<T> objectPool; public ObjectPoolHelper(final ObjectFactory<T> objectFactory) { notNull(objectFactory); objectPool = createObjectPool(objectFactory); notNull(objectPool); } /** * Ensure that a not null pool will be created. */ private GenericObjectPool<T> createObjectPool(final ObjectFactory<T> objectFactory) { final GenericObjectPool<T> pool = newObjectPool(objectFactory); notNull(pool); return pool; } /** * Creates a {@link GenericObjectPool}. Override this method to set custom objectPool configurations. */ protected GenericObjectPool<T> newObjectPool(final ObjectFactory<T> objectFactory) { final int maxActive = Math.max(2, Runtime.getRuntime().availableProcessors()); final GenericObjectPool<T> pool = new GenericObjectPool<T>(new BasePooledObjectFactory<T>() { @Override public T create() throws Exception { return objectFactory.create(); } @Override public PooledObject<T> wrap(T obj) { return new DefaultPooledObject<T>(obj); } }); pool.setMaxTotal(maxActive); pool.setMaxIdle(MAX_IDLE); pool.setMaxWaitMillis(MAX_WAIT); /** * Block when exhausted, otherwise the pool object retrieval can fail. More details here: * <a>http://code.google.com/p/wro4j/issues/detail?id=364</a> */ pool.setBlockWhenExhausted(true); // make object eligible for eviction after a predefined amount of time. pool.setSoftMinEvictableIdleTimeMillis(EVICTABLE_IDLE_TIME); pool.setTimeBetweenEvictionRunsMillis(EVICTABLE_IDLE_TIME); return pool; } /** * @return object from the pool. */ public T getObject() { try { return objectPool.borrowObject(); } catch (final Exception e) { // should never happen throw new RuntimeException("Cannot get object from the pool", e); } } public void returnObject(final T engine) { notNull(engine); try { objectPool.returnObject(engine); } catch (final Exception e) { // should never happen throw new RuntimeException("Cannot get object from the pool", e); } } /** * Use a custom {@link GenericObjectPool}. * * @param objectPool * to use. */ public final void setObjectPool(final GenericObjectPool<T> objectPool) { notNull(objectPool); this.objectPool = objectPool; } /** * Close the object pool to avoid the memory leak. * * @throws Exception * if the close operation failed. */ public void destroy() throws Exception { LOG.debug("closing objectPool"); objectPool.close(); } }
Issue #1081 - Inconsistent build failures due to pool timeout
wro4j-extensions/src/main/java/ro/isdc/wro/extensions/processor/support/ObjectPoolHelper.java
Issue #1081 - Inconsistent build failures due to pool timeout
<ide><path>ro4j-extensions/src/main/java/ro/isdc/wro/extensions/processor/support/ObjectPoolHelper.java <ide> <ide> import static org.apache.commons.lang3.Validate.notNull; <ide> <add>import org.apache.commons.lang3.time.DateUtils; <ide> import org.apache.commons.pool2.BasePooledObjectFactory; <ide> import org.apache.commons.pool2.PooledObject; <ide> import org.apache.commons.pool2.impl.DefaultPooledObject; <ide> * @since 1.4.2 <ide> */ <ide> public class ObjectPoolHelper<T> { <add> <ide> private static final Logger LOG = LoggerFactory.getLogger(ObjectPoolHelper.class); <del> private static final int MAX_IDLE = 2; <del> private static final long MAX_WAIT = 5L * 1000L; <del> private static final long EVICTABLE_IDLE_TIME = 30 * 1000L; <add> <add> private static final int MAX_IDLE = 5; <add> private static final long MAX_WAIT = 10L * DateUtils.MILLIS_PER_SECOND; <add> private static final long EVICTABLE_IDLE_TIME = 30L * DateUtils.MILLIS_PER_SECOND; <add> <ide> // Allows using the objects from the pool in a thread-safe fashion. <ide> private GenericObjectPool<T> objectPool; <del> <ide> <ide> public ObjectPoolHelper(final ObjectFactory<T> objectFactory) { <ide> notNull(objectFactory);
Java
apache-2.0
a3696d38df30781967eb379b1ed1682ac29f5551
0
thescouser89/pnc,alexcreasy/pnc,pkocandr/pnc,matedo1/pnc,rnc/pnc,matedo1/pnc,alexcreasy/pnc,matedo1/pnc,project-ncl/pnc,alexcreasy/pnc,matejonnet/pnc
/** * JBoss, Home of Professional Open Source. * Copyright 2014-2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.pnc.coordinator.notifications.buildTask; import org.jboss.pnc.dto.BuildConfigurationRevisionRef; import org.jboss.pnc.messaging.spi.BuildStatusChanged; import org.jboss.pnc.messaging.spi.Message; import org.jboss.pnc.messaging.spi.MessageSender; import org.jboss.pnc.messaging.spi.Status; import org.jboss.pnc.enums.BuildCoordinationStatus; import org.jboss.pnc.spi.events.BuildCoordinationStatusChangedEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.Dependent; import javax.enterprise.event.Observes; import javax.enterprise.inject.Instance; import javax.inject.Inject; import java.util.HashMap; import java.util.Map; import java.util.Optional; /** * @author <a href="mailto:[email protected]">Matej Lazar</a> */ @Dependent public class BuildStatusMQNotifications { private Logger logger = LoggerFactory.getLogger(BuildStatusMQNotifications.class); final Optional<MessageSender> messageSender; @Inject public BuildStatusMQNotifications(Instance<MessageSender> messageSender) { if (messageSender.isUnsatisfied()) { logger.warn("Messaging to MQ is disabled. There is no message sender available to inject."); this.messageSender = Optional.empty(); } else { this.messageSender = Optional.of(messageSender.get()); } } public void observeEvent(@Observes BuildCoordinationStatusChangedEvent event) { logger.debug("Observed new status changed event {}.", event); messageSender.ifPresent(ms -> send(ms, event)); logger.debug("Status changed event processed {}.", event); } private void send(MessageSender ms, BuildCoordinationStatusChangedEvent event) { Status newStatus = toMqStatus(event.getBuild().getStatus()); if (newStatus != null) { Message message = BuildStatusChanged.builder() .oldStatus(toStringStatus(getOldStatus(event.getOldStatus()))) .build(event.getBuild()) .buildMe(); ms.sendToTopic(message, prepareHeaders(event)); } } private Status getOldStatus(BuildCoordinationStatus oldStatus) { Status mqOldStatus; if (BuildCoordinationStatus.WAITING_FOR_DEPENDENCIES.equals(oldStatus)) { mqOldStatus = Status.ACCEPTED; } else if (BuildCoordinationStatus.BUILD_COMPLETED.equals(oldStatus)) { mqOldStatus = Status.BUILDING; } else { mqOldStatus = toMqStatus(oldStatus); } return mqOldStatus; } private Map<String, String> prepareHeaders(BuildCoordinationStatusChangedEvent event) { BuildConfigurationRevisionRef buildConfigurationAudited = event.getBuild().getBuildConfigurationAudited(); Map<String, String> headers = new HashMap<>(); headers.put("type", "BuildStateChange"); headers.put("attribute", "state-change"); headers.put("name", buildConfigurationAudited.getName()); headers.put("configurationId", buildConfigurationAudited.getId().toString()); headers.put("configurationRevision", buildConfigurationAudited.getRev().toString()); headers.put("oldStatus", toStringStatus(getOldStatus(event.getOldStatus()))); headers.put("newStatus", toStringStatus(toMqStatus(event.getBuild().getStatus()))); return headers; } private String toStringStatus(Status status) { if (status == null) { return ""; } else { return status.lowercase(); } } /** * * @return Status or null is status is ignored */ private Status toMqStatus(BuildCoordinationStatus status) { switch (status) { case NEW: return null; case ENQUEUED: return Status.ACCEPTED; case WAITING_FOR_DEPENDENCIES: return null; case BUILDING: return Status.BUILDING; case BUILD_COMPLETED: return null; case DONE: return Status.SUCCESS; case REJECTED: return Status.REJECTED; case REJECTED_FAILED_DEPENDENCIES: return Status.REJECTED; case REJECTED_ALREADY_BUILT: return Status.REJECTED; case SYSTEM_ERROR: return Status.FAILED; case DONE_WITH_ERRORS: return Status.FAILED; case CANCELLED: return Status.CANCELED; } throw new IllegalArgumentException("Invalid status " + status); } }
build-coordinator/src/main/java/org/jboss/pnc/coordinator/notifications/buildTask/BuildStatusMQNotifications.java
/** * JBoss, Home of Professional Open Source. * Copyright 2014-2018 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.pnc.coordinator.notifications.buildTask; import org.jboss.pnc.dto.BuildConfigurationRevisionRef; import org.jboss.pnc.messaging.spi.BuildStatusChanged; import org.jboss.pnc.messaging.spi.Message; import org.jboss.pnc.messaging.spi.MessageSender; import org.jboss.pnc.messaging.spi.Status; import org.jboss.pnc.enums.BuildCoordinationStatus; import org.jboss.pnc.spi.events.BuildCoordinationStatusChangedEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.enterprise.context.Dependent; import javax.enterprise.event.Observes; import javax.enterprise.inject.Instance; import javax.inject.Inject; import java.util.HashMap; import java.util.Map; import java.util.Optional; /** * @author <a href="mailto:[email protected]">Matej Lazar</a> */ @Dependent public class BuildStatusMQNotifications { private Logger logger = LoggerFactory.getLogger(BuildStatusMQNotifications.class); final Optional<MessageSender> messageSender; @Inject public BuildStatusMQNotifications(Instance<MessageSender> messageSender) { if (messageSender.isUnsatisfied()) { logger.warn("Messaging to MQ is disabled. There is no message sender available to inject."); this.messageSender = Optional.empty(); } else { this.messageSender = Optional.of(messageSender.get()); } } public void observeEvent(@Observes BuildCoordinationStatusChangedEvent event) { logger.debug("Observed new status changed event {}.", event); messageSender.ifPresent(ms -> send(ms, event)); logger.debug("Status changed event processed {}.", event); } private void send(MessageSender ms, BuildCoordinationStatusChangedEvent event) { Status newStatus = toMqStatus(event.getBuild().getStatus()); if (newStatus != null) { Message message = BuildStatusChanged.builder() .oldStatus(toStringStatus(getOldStatus(event.getOldStatus()))) .build(event.getBuild()) .buildMe(); ms.sendToTopic(message, prepareHeaders(event)); } } private Status getOldStatus(BuildCoordinationStatus oldStatus) { Status mqOldStatus; if (BuildCoordinationStatus.WAITING_FOR_DEPENDENCIES.equals(oldStatus)) { mqOldStatus = Status.ACCEPTED; } else if (BuildCoordinationStatus.BUILD_COMPLETED.equals(oldStatus)) { mqOldStatus = Status.BUILDING; } else { mqOldStatus = toMqStatus(oldStatus); } return mqOldStatus; } private Map<String, String> prepareHeaders(BuildCoordinationStatusChangedEvent event) { BuildConfigurationRevisionRef buildConfigurationAudited = event.getBuild().getBuildConfigurationAudited(); Map<String, String> headers = new HashMap<>(); headers.put("type", "BuildStateChange"); headers.put("attribute", "state"); headers.put("name", buildConfigurationAudited.getName()); headers.put("configurationId", buildConfigurationAudited.getId().toString()); headers.put("configurationRevision", buildConfigurationAudited.getRev().toString()); headers.put("oldStatus", toStringStatus(getOldStatus(event.getOldStatus()))); headers.put("newStatus", toStringStatus(toMqStatus(event.getBuild().getStatus()))); return headers; } private String toStringStatus(Status status) { if (status == null) { return ""; } else { return status.lowercase(); } } /** * * @return Status or null is status is ignored */ private Status toMqStatus(BuildCoordinationStatus status) { switch (status) { case NEW: return null; case ENQUEUED: return Status.ACCEPTED; case WAITING_FOR_DEPENDENCIES: return null; case BUILDING: return Status.BUILDING; case BUILD_COMPLETED: return null; case DONE: return Status.SUCCESS; case REJECTED: return Status.REJECTED; case REJECTED_FAILED_DEPENDENCIES: return Status.REJECTED; case REJECTED_ALREADY_BUILT: return Status.REJECTED; case SYSTEM_ERROR: return Status.FAILED; case DONE_WITH_ERRORS: return Status.FAILED; case CANCELLED: return Status.CANCELED; } throw new IllegalArgumentException("Invalid status " + status); } }
Update UMB message header.
build-coordinator/src/main/java/org/jboss/pnc/coordinator/notifications/buildTask/BuildStatusMQNotifications.java
Update UMB message header.
<ide><path>uild-coordinator/src/main/java/org/jboss/pnc/coordinator/notifications/buildTask/BuildStatusMQNotifications.java <ide> BuildConfigurationRevisionRef buildConfigurationAudited = event.getBuild().getBuildConfigurationAudited(); <ide> Map<String, String> headers = new HashMap<>(); <ide> headers.put("type", "BuildStateChange"); <del> headers.put("attribute", "state"); <add> headers.put("attribute", "state-change"); <ide> headers.put("name", buildConfigurationAudited.getName()); <ide> headers.put("configurationId", buildConfigurationAudited.getId().toString()); <ide> headers.put("configurationRevision", buildConfigurationAudited.getRev().toString());
Java
apache-2.0
278d2577fd74ddb5a1394ae5f3ad064451ffd75f
0
pax95/camel,pmoerenhout/camel,ullgren/camel,zregvart/camel,zregvart/camel,pax95/camel,christophd/camel,adessaigne/camel,pax95/camel,DariusX/camel,tdiesler/camel,cunningt/camel,nicolaferraro/camel,mcollovati/camel,apache/camel,CodeSmell/camel,nikhilvibhav/camel,apache/camel,gnodet/camel,zregvart/camel,christophd/camel,mcollovati/camel,DariusX/camel,alvinkwekel/camel,nicolaferraro/camel,zregvart/camel,ullgren/camel,alvinkwekel/camel,cunningt/camel,tdiesler/camel,pmoerenhout/camel,pax95/camel,adessaigne/camel,christophd/camel,tdiesler/camel,pax95/camel,nicolaferraro/camel,ullgren/camel,nicolaferraro/camel,christophd/camel,christophd/camel,apache/camel,ullgren/camel,apache/camel,cunningt/camel,tadayosi/camel,pmoerenhout/camel,tadayosi/camel,cunningt/camel,nikhilvibhav/camel,tadayosi/camel,CodeSmell/camel,alvinkwekel/camel,tdiesler/camel,mcollovati/camel,adessaigne/camel,gnodet/camel,gnodet/camel,cunningt/camel,alvinkwekel/camel,tadayosi/camel,adessaigne/camel,CodeSmell/camel,pax95/camel,objectiser/camel,pmoerenhout/camel,objectiser/camel,DariusX/camel,tdiesler/camel,tadayosi/camel,nikhilvibhav/camel,CodeSmell/camel,gnodet/camel,tdiesler/camel,mcollovati/camel,cunningt/camel,objectiser/camel,pmoerenhout/camel,apache/camel,objectiser/camel,nikhilvibhav/camel,apache/camel,adessaigne/camel,gnodet/camel,pmoerenhout/camel,christophd/camel,adessaigne/camel,tadayosi/camel,DariusX/camel
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.netty.http; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.ObjectOutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLDecoder; import java.nio.charset.Charset; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpHeaderValues; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import io.netty.util.ReferenceCountUtil; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.RuntimeCamelException; import org.apache.camel.TypeConverter; import org.apache.camel.component.netty.NettyConstants; import org.apache.camel.component.netty.NettyConverter; import org.apache.camel.spi.HeaderFilterStrategy; import org.apache.camel.support.ExchangeHelper; import org.apache.camel.support.MessageHelper; import org.apache.camel.support.ObjectHelper; import org.apache.camel.support.SynchronizationAdapter; import org.apache.camel.util.IOHelper; import org.apache.camel.util.StringHelper; import org.apache.camel.util.URISupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static io.netty.handler.codec.http.HttpHeaderNames.TRANSFER_ENCODING; import static io.netty.handler.codec.http.HttpHeaderValues.CHUNKED; /** * Default {@link NettyHttpBinding}. */ public class DefaultNettyHttpBinding implements NettyHttpBinding, Cloneable { private static final Logger LOG = LoggerFactory.getLogger(DefaultNettyHttpBinding.class); private HeaderFilterStrategy headerFilterStrategy = new NettyHttpHeaderFilterStrategy(); public DefaultNettyHttpBinding() { } public DefaultNettyHttpBinding(HeaderFilterStrategy headerFilterStrategy) { this.headerFilterStrategy = headerFilterStrategy; } public DefaultNettyHttpBinding copy() { try { return (DefaultNettyHttpBinding)this.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } @Override public Message toCamelMessage(FullHttpRequest request, Exchange exchange, NettyHttpConfiguration configuration) throws Exception { LOG.trace("toCamelMessage: {}", request); NettyHttpMessage answer = new NettyHttpMessage(exchange.getContext(), request, null); answer.setExchange(exchange); if (configuration.isMapHeaders()) { populateCamelHeaders(request, answer.getHeaders(), exchange, configuration); } if (configuration.isHttpProxy() || configuration.isDisableStreamCache()) { // keep the body as is, and use type converters // for proxy use case pass the request body buffer directly to the response to avoid additional processing // we need to retain it so that the request can be released and we can keep the content answer.setBody(request.content().retain()); exchange.addOnCompletion(new SynchronizationAdapter() { @Override public void onDone(Exchange exchange) { ReferenceCountUtil.release(request.content()); } }); } else { // turn the body into stream cached (on the client/consumer side we can facade the netty stream instead of converting to byte array) NettyChannelBufferStreamCache cache = new NettyChannelBufferStreamCache(request.content()); // add on completion to the cache which is needed for Camel to keep track of the lifecycle of the cache exchange.addOnCompletion(new NettyChannelBufferStreamCacheOnCompletion(cache)); answer.setBody(cache); } return answer; } @Override public Message toCamelMessage(InboundStreamHttpRequest request, Exchange exchange, NettyHttpConfiguration configuration) throws Exception { LOG.trace("toCamelMessage: {}", request); NettyHttpMessage answer = new NettyHttpMessage(exchange.getContext(), null, null); answer.setExchange(exchange); if (configuration.isMapHeaders()) { populateCamelHeaders(request.getHttpRequest(), answer.getHeaders(), exchange, configuration); } answer.setBody(request.getInputStream()); return answer; } @Override public void populateCamelHeaders(HttpRequest request, Map<String, Object> headers, Exchange exchange, NettyHttpConfiguration configuration) throws Exception { LOG.trace("populateCamelHeaders: {}", request); // NOTE: these headers is applied using the same logic as camel-http/camel-jetty to be consistent headers.put(Exchange.HTTP_METHOD, request.method().name()); // strip query parameters from the uri String s = request.uri(); if (s.contains("?")) { s = StringHelper.before(s, "?"); } // we want the full path for the url, as the client may provide the url in the HTTP headers as absolute or relative, eg // /foo // http://servername/foo String http = configuration.isSsl() ? "https://" : "http://"; if (!s.startsWith(http)) { if (configuration.getPort() != 80) { s = http + configuration.getHost() + ":" + configuration.getPort() + s; } else { s = http + configuration.getHost() + s; } } headers.put(Exchange.HTTP_URL, s); // uri is without the host and port URI uri = new URI(request.uri()); // uri is path and query parameters headers.put(Exchange.HTTP_URI, uri.getPath()); headers.put(Exchange.HTTP_QUERY, uri.getQuery()); headers.put(Exchange.HTTP_RAW_QUERY, uri.getRawQuery()); headers.put(Exchange.HTTP_SCHEME, uri.getScheme()); headers.put(Exchange.HTTP_HOST, uri.getHost()); final int port = uri.getPort(); headers.put(Exchange.HTTP_PORT, port > 0 ? port : 80); // strip the starting endpoint path so the path is relative to the endpoint uri String path = uri.getRawPath(); if (configuration.getPath() != null) { // need to match by lower case as we want to ignore case on context-path String matchPath = path.toLowerCase(Locale.US); String match = configuration.getPath() != null ? configuration.getPath().toLowerCase(Locale.US) : null; if (match != null && matchPath.startsWith(match)) { path = path.substring(configuration.getPath().length()); } } // keep the path uri using the case the request provided (do not convert to lower case) headers.put(Exchange.HTTP_PATH, path); if (LOG.isTraceEnabled()) { LOG.trace("HTTP-Method {}", request.method().name()); LOG.trace("HTTP-Uri {}", request.uri()); } for (String name : request.headers().names()) { // mapping the content-type if (name.toLowerCase(Locale.US).equals("content-type")) { name = Exchange.CONTENT_TYPE; } if (name.toLowerCase(Locale.US).equals("authorization")) { String value = request.headers().get(name); // store a special header that this request was authenticated using HTTP Basic if (value != null && value.trim().startsWith("Basic")) { NettyHttpHelper.appendHeader(headers, NettyHttpConstants.HTTP_AUTHENTICATION, "Basic"); } } // add the headers one by one, and use the header filter strategy List<String> values = request.headers().getAll(name); Iterator<?> it = ObjectHelper.createIterator(values, ",", true); while (it.hasNext()) { Object extracted = it.next(); Object decoded = shouldUrlDecodeHeader(configuration, name, extracted, "UTF-8"); LOG.trace("HTTP-header: {}", extracted); if (headerFilterStrategy != null && !headerFilterStrategy.applyFilterToExternalHeaders(name, decoded, exchange)) { NettyHttpHelper.appendHeader(headers, name, decoded); } } } // add uri parameters as headers to the Camel message; // when acting as a HTTP proxy we don't want to place query // parameters in Camel message headers as the query parameters // will be passed via Exchange.HTTP_QUERY, otherwise we could have // both the Exchange.HTTP_QUERY and the values from the message // headers, so we end up with two values for the same query // parameter if (!configuration.isHttpProxy() && request.uri().contains("?")) { String query = StringHelper.after(request.uri(), "?"); Map<String, Object> uriParameters = URISupport.parseQuery(query, false, true); for (Map.Entry<String, Object> entry : uriParameters.entrySet()) { String name = entry.getKey(); Object values = entry.getValue(); Iterator<?> it = ObjectHelper.createIterator(values, ",", true); while (it.hasNext()) { Object extracted = it.next(); Object decoded = shouldUrlDecodeHeader(configuration, name, extracted, "UTF-8"); LOG.trace("URI-Parameter: {}", extracted); if (headerFilterStrategy != null && !headerFilterStrategy.applyFilterToExternalHeaders(name, decoded, exchange)) { NettyHttpHelper.appendHeader(headers, name, decoded); } } } } // if body is application/x-www-form-urlencoded then extract the body as query string and append as headers // if it is a bridgeEndpoint we need to skip this part of work // if we're proxying the body is a buffer that we do not want to consume directly if (request.method().name().equals("POST") && request.headers().get(Exchange.CONTENT_TYPE) != null && request.headers().get(Exchange.CONTENT_TYPE).startsWith(NettyHttpConstants.CONTENT_TYPE_WWW_FORM_URLENCODED) && !configuration.isBridgeEndpoint() && !configuration.isHttpProxy() && request instanceof FullHttpRequest) { String charset = "UTF-8"; // Push POST form params into the headers to retain compatibility with DefaultHttpBinding String body; ByteBuf buffer = ((FullHttpRequest)request).content(); try { body = buffer.toString(Charset.forName(charset)); } finally { buffer.release(); } if (org.apache.camel.util.ObjectHelper.isNotEmpty(body)) { for (String param : body.split("&")) { String[] pair = param.split("=", 2); if (pair.length == 2) { String name = shouldUrlDecodeHeader(configuration, "", pair[0], charset); String value = shouldUrlDecodeHeader(configuration, name, pair[1], charset); if (headerFilterStrategy != null && !headerFilterStrategy.applyFilterToExternalHeaders(name, value, exchange)) { NettyHttpHelper.appendHeader(headers, name, value); } } else { throw new IllegalArgumentException("Invalid parameter, expected to be a pair but was " + param); } } } } } /** * Decodes the header if needed to, or returns the header value as is. * * @param configuration the configuration * @param headerName the header name * @param value the current header value * @param charset the charset to use for decoding * @return the decoded value (if decoded was needed) or a <tt>toString</tt> representation of the value. * @throws UnsupportedEncodingException is thrown if error decoding. */ protected String shouldUrlDecodeHeader(NettyHttpConfiguration configuration, String headerName, Object value, String charset) throws UnsupportedEncodingException { // do not decode Content-Type if (Exchange.CONTENT_TYPE.equals(headerName)) { return value.toString(); } else if (configuration.isUrlDecodeHeaders()) { return URLDecoder.decode(value.toString(), charset); } else { return value.toString(); } } @Override public Message toCamelMessage(FullHttpResponse response, Exchange exchange, NettyHttpConfiguration configuration) throws Exception { LOG.trace("toCamelMessage: {}", response); NettyHttpMessage answer = new NettyHttpMessage(exchange.getContext(), null, response); answer.setExchange(exchange); if (configuration.isMapHeaders()) { populateCamelHeaders(response, answer.getHeaders(), exchange, configuration); } if (configuration.isDisableStreamCache() || configuration.isHttpProxy()) { // keep the body as is, and use type converters answer.setBody(response.content()); } else { // stores as byte array as the netty ByteBuf will be freed when the producer is done, and then we can no longer access the message body response.retain(); try { byte[] bytes = exchange.getContext().getTypeConverter().convertTo(byte[].class, exchange, response.content()); answer.setBody(bytes); } finally { response.release(); } } return answer; } @Override public Message toCamelMessage(InboundStreamHttpResponse response, Exchange exchange, NettyHttpConfiguration configuration) throws Exception { LOG.trace("toCamelMessage: {}", response); NettyHttpMessage answer = new NettyHttpMessage(exchange.getContext(), null, null); answer.setExchange(exchange); if (configuration.isMapHeaders()) { populateCamelHeaders(response.getHttpResponse(), answer.getHeaders(), exchange, configuration); } answer.setBody(response.getInputStream()); return answer; } @Override public void populateCamelHeaders(HttpResponse response, Map<String, Object> headers, Exchange exchange, NettyHttpConfiguration configuration) throws Exception { LOG.trace("populateCamelHeaders: {}", response); headers.put(Exchange.HTTP_RESPONSE_CODE, response.status().code()); headers.put(Exchange.HTTP_RESPONSE_TEXT, response.status().reasonPhrase()); for (String name : response.headers().names()) { // mapping the content-type if (name.toLowerCase().equals("content-type")) { name = Exchange.CONTENT_TYPE; } // add the headers one by one, and use the header filter strategy List<String> values = response.headers().getAll(name); Iterator<?> it = ObjectHelper.createIterator(values); while (it.hasNext()) { Object extracted = it.next(); LOG.trace("HTTP-header: {}", extracted); if (headerFilterStrategy != null && !headerFilterStrategy.applyFilterToExternalHeaders(name, extracted, exchange)) { NettyHttpHelper.appendHeader(headers, name, extracted); } } } } @Override public HttpResponse toNettyResponse(Message message, NettyHttpConfiguration configuration) throws Exception { LOG.trace("toNettyResponse: {}", message); if (message instanceof NettyHttpMessage) { final NettyHttpMessage nettyHttpMessage = (NettyHttpMessage) message; final FullHttpResponse response = nettyHttpMessage.getHttpResponse(); if (response != null && nettyHttpMessage.getBody() == null) { return response.retain(); } } // the message body may already be a Netty HTTP response if (message.getBody() instanceof HttpResponse) { return (HttpResponse) message.getBody(); } Object body = message.getBody(); Exception cause = message.getExchange().getException(); // support bodies as native Netty ByteBuf buffer; int code = determineResponseCode(message.getExchange(), body); LOG.trace("HTTP Status Code: {}", code); // if there was an exception then use that as body if (cause != null && !configuration.isMuteException()) { if (configuration.isTransferException()) { // we failed due an exception, and transfer it as java serialized object ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(cause); oos.flush(); IOHelper.close(oos, bos); // the body should be the serialized java object of the exception body = NettyConverter.toByteBuffer(bos.toByteArray()); // force content type to be serialized java object message.setHeader(Exchange.CONTENT_TYPE, NettyHttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT); } else { // we failed due an exception so print it as plain text StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); cause.printStackTrace(pw); // the body should then be the stacktrace body = NettyConverter.toByteBuffer(sw.toString().getBytes()); // force content type to be text/plain as that is what the stacktrace is message.setHeader(Exchange.CONTENT_TYPE, "text/plain"); } // and mark the exception as failure handled, as we handled it by returning it as the response ExchangeHelper.setFailureHandled(message.getExchange()); } else if (cause != null && configuration.isMuteException()) { // the body should hide the stacktrace (muteException enabled) body = NettyConverter.toByteBuffer("Exception".getBytes()); // force content type to be text/plain message.setHeader(Exchange.CONTENT_TYPE, "text/plain"); // and mark the exception as failure handled, as we handled it by actively muting it ExchangeHelper.setFailureHandled(message.getExchange()); } HttpResponse response = null; if (response == null && body instanceof InputStream && configuration.isDisableStreamCache()) { response = new OutboundStreamHttpResponse((InputStream)body, new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(code))); response.headers().set(TRANSFER_ENCODING, CHUNKED); } if (response == null) { if (body instanceof ByteBuf) { buffer = (ByteBuf) body; } else { // try to convert to buffer first buffer = message.getBody(ByteBuf.class); if (buffer == null) { // fallback to byte array as last resort byte[] data = message.getBody(byte[].class); if (data != null) { buffer = NettyConverter.toByteBuffer(data); } else { // and if byte array fails then try String String str; if (body != null) { str = message.getMandatoryBody(String.class); } else { str = ""; } buffer = NettyConverter.toByteBuffer(str.getBytes()); } } } if (buffer != null) { response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(code), buffer); // We just need to reset the readerIndex this time if (buffer.readerIndex() == buffer.writerIndex()) { buffer.setIndex(0, buffer.writerIndex()); } // TODO How to enable the chunk transport int len = buffer.readableBytes(); // set content-length response.headers().set(HttpHeaderNames.CONTENT_LENGTH.toString(), len); LOG.trace("Content-Length: {}", len); } else { response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(code)); } } TypeConverter tc = message.getExchange().getContext().getTypeConverter(); // append headers // must use entrySet to ensure case of keys is preserved for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); // use an iterator as there can be multiple values. (must not use a delimiter) final Iterator<?> it = ObjectHelper.createIterator(value, null, true); while (it.hasNext()) { String headerValue = tc.convertTo(String.class, it.next()); if (headerValue != null && headerFilterStrategy != null && !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, message.getExchange())) { LOG.trace("HTTP-Header: {}={}", key, headerValue); response.headers().add(key, headerValue); } } } // set the content type in the response. String contentType = MessageHelper.getContentType(message); if (contentType != null) { // set content-type response.headers().set(HttpHeaderNames.CONTENT_TYPE.toString(), contentType); LOG.trace("Content-Type: {}", contentType); } // configure connection to accordingly to keep alive configuration // favor using the header from the message String connection = message.getHeader(HttpHeaderNames.CONNECTION.toString(), String.class); // Read the connection header from the exchange property if (connection == null) { connection = message.getExchange().getProperty(HttpHeaderNames.CONNECTION.toString(), String.class); } if (connection == null) { // fallback and use the keep alive from the configuration if (configuration.isKeepAlive()) { connection = HttpHeaderValues.KEEP_ALIVE.toString(); } else { connection = HttpHeaderValues.CLOSE.toString(); } } response.headers().set(HttpHeaderNames.CONNECTION.toString(), connection); // Just make sure we close the channel when the connection value is close if (connection.equalsIgnoreCase(HttpHeaderValues.CLOSE.toString())) { message.setHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true); } LOG.trace("Connection: {}", connection); return response; } /* * set the HTTP status code */ private int determineResponseCode(Exchange camelExchange, Object body) { boolean failed = camelExchange.isFailed(); int defaultCode = failed ? 500 : 200; Message message = camelExchange.getMessage(); Integer currentCode = message.getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class); int codeToUse = currentCode == null ? defaultCode : currentCode; if (codeToUse != 500) { if ((body == null) || (body instanceof String && ((String) body).trim().isEmpty())) { // no content codeToUse = currentCode == null ? 204 : currentCode; } } return codeToUse; } @Override public HttpRequest toNettyRequest(Message message, String fullUri, NettyHttpConfiguration configuration) throws Exception { LOG.trace("toNettyRequest: {}", message); Object body = message.getBody(); // the message body may already be a Netty HTTP response if (body instanceof HttpRequest) { return (HttpRequest) message.getBody(); } String uriForRequest = fullUri; if (configuration.isUseRelativePath()) { final URI uri = new URI(uriForRequest); final String rawPath = uri.getRawPath(); if (rawPath != null) { uriForRequest = rawPath; } final String rawQuery = uri.getRawQuery(); if (rawQuery != null) { uriForRequest += "?" + rawQuery; } } final String headerProtocolVersion = message.getHeader(Exchange.HTTP_PROTOCOL_VERSION, String.class); final HttpVersion protocol; if (headerProtocolVersion == null) { protocol = HttpVersion.HTTP_1_1; } else { protocol = HttpVersion.valueOf(headerProtocolVersion); } final String headerMethod = message.getHeader(Exchange.HTTP_METHOD, String.class); final HttpMethod httpMethod; if (headerMethod == null) { httpMethod = HttpMethod.GET; } else { httpMethod = HttpMethod.valueOf(headerMethod); } HttpRequest request = null; if (message instanceof NettyHttpMessage) { // if the request is already given we should set the values // from message headers and pass on the same request final FullHttpRequest givenRequest = ((NettyHttpMessage) message).getHttpRequest(); // we need to make sure that the givenRequest is the original // request received by the proxy, only when the body wasn't // modified by a processor on route if (givenRequest != null && givenRequest.content() == body) { request = givenRequest .setProtocolVersion(protocol) .setMethod(httpMethod) .setUri(uriForRequest); } } if (request == null && body instanceof InputStream && configuration.isDisableStreamCache()) { request = new OutboundStreamHttpRequest((InputStream)body, new DefaultHttpRequest(protocol, httpMethod, uriForRequest)); request.headers().set(TRANSFER_ENCODING, CHUNKED); } if (request == null) { request = new DefaultFullHttpRequest(protocol, httpMethod, uriForRequest); if (body != null) { // support bodies as native Netty ByteBuf buffer; if (body instanceof ByteBuf) { buffer = (ByteBuf) body; } else { // try to convert to buffer first buffer = message.getBody(ByteBuf.class); if (buffer == null) { // fallback to byte array as last resort byte[] data = message.getMandatoryBody(byte[].class); if (data.length > 0) { buffer = NettyConverter.toByteBuffer(data); } } } if (buffer != null) { if (buffer.readableBytes() > 0) { request = ((DefaultFullHttpRequest)request).replace(buffer); int len = buffer.readableBytes(); // set content-length request.headers().set(HttpHeaderNames.CONTENT_LENGTH.toString(), len); LOG.trace("Content-Length: {}", len); } else { buffer.release(); } } } } // update HTTP method accordingly as we know if we have a body or not HttpMethod method = NettyHttpHelper.createMethod(message, body != null); request.setMethod(method); TypeConverter tc = message.getExchange().getContext().getTypeConverter(); // if we bridge endpoint then we need to skip matching headers with the HTTP_QUERY to avoid sending // duplicated headers to the receiver, so use this skipRequestHeaders as the list of headers to skip Map<String, Object> skipRequestHeaders = null; if (configuration.isBridgeEndpoint()) { String queryString = message.getHeader(Exchange.HTTP_QUERY, String.class); if (queryString != null) { skipRequestHeaders = URISupport.parseQuery(queryString, false, true); } // Need to remove the Host key as it should be not used message.getHeaders().remove("host"); } // append headers // must use entrySet to ensure case of keys is preserved for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); // we should not add headers for the parameters in the uri if we bridge the endpoint // as then we would duplicate headers on both the endpoint uri, and in HTTP headers as well if (skipRequestHeaders != null && skipRequestHeaders.containsKey(key)) { continue; } // use an iterator as there can be multiple values. (must not use a delimiter) final Iterator<?> it = ObjectHelper.createIterator(value, null, true); while (it.hasNext()) { String headerValue = tc.convertTo(String.class, it.next()); if (headerValue != null && headerFilterStrategy != null && !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, message.getExchange())) { LOG.trace("HTTP-Header: {}={}", key, headerValue); request.headers().add(key, headerValue); } } } // set the content type in the response. String contentType = MessageHelper.getContentType(message); if (contentType != null) { // set content-type request.headers().set(HttpHeaderNames.CONTENT_TYPE.toString(), contentType); LOG.trace("Content-Type: {}", contentType); } // must include HOST header as required by HTTP 1.1 // use URI as its faster than URL (no DNS lookup) URI u = new URI(fullUri); int port = u.getPort(); String hostHeader = u.getHost() + (port == 80 || port == -1 ? "" : ":" + u.getPort()); request.headers().set(HttpHeaderNames.HOST.toString(), hostHeader); LOG.trace("Host: {}", hostHeader); // configure connection to accordingly to keep alive configuration // favor using the header from the message String connection = message.getHeader(HttpHeaderNames.CONNECTION.toString(), String.class); if (connection == null) { // fallback and use the keep alive from the configuration if (configuration.isKeepAlive()) { connection = HttpHeaderValues.KEEP_ALIVE.toString(); } else { connection = HttpHeaderValues.CLOSE.toString(); } } request.headers().set(HttpHeaderNames.CONNECTION.toString(), connection); LOG.trace("Connection: {}", connection); return request; } @Override public HeaderFilterStrategy getHeaderFilterStrategy() { return headerFilterStrategy; } @Override public void setHeaderFilterStrategy(HeaderFilterStrategy headerFilterStrategy) { this.headerFilterStrategy = headerFilterStrategy; } }
components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/DefaultNettyHttpBinding.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.netty.http; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.ObjectOutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLDecoder; import java.nio.charset.Charset; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpHeaderValues; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import io.netty.util.ReferenceCountUtil; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.RuntimeCamelException; import org.apache.camel.TypeConverter; import org.apache.camel.component.netty.NettyConstants; import org.apache.camel.component.netty.NettyConverter; import org.apache.camel.spi.HeaderFilterStrategy; import org.apache.camel.support.ExchangeHelper; import org.apache.camel.support.MessageHelper; import org.apache.camel.support.ObjectHelper; import org.apache.camel.support.SynchronizationAdapter; import org.apache.camel.util.IOHelper; import org.apache.camel.util.StringHelper; import org.apache.camel.util.URISupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static io.netty.handler.codec.http.HttpHeaderNames.TRANSFER_ENCODING; import static io.netty.handler.codec.http.HttpHeaderValues.CHUNKED; /** * Default {@link NettyHttpBinding}. */ public class DefaultNettyHttpBinding implements NettyHttpBinding, Cloneable { private static final Logger LOG = LoggerFactory.getLogger(DefaultNettyHttpBinding.class); private HeaderFilterStrategy headerFilterStrategy = new NettyHttpHeaderFilterStrategy(); public DefaultNettyHttpBinding() { } public DefaultNettyHttpBinding(HeaderFilterStrategy headerFilterStrategy) { this.headerFilterStrategy = headerFilterStrategy; } public DefaultNettyHttpBinding copy() { try { return (DefaultNettyHttpBinding)this.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } @Override public Message toCamelMessage(FullHttpRequest request, Exchange exchange, NettyHttpConfiguration configuration) throws Exception { LOG.trace("toCamelMessage: {}", request); NettyHttpMessage answer = new NettyHttpMessage(exchange.getContext(), request, null); answer.setExchange(exchange); if (configuration.isMapHeaders()) { populateCamelHeaders(request, answer.getHeaders(), exchange, configuration); } if (configuration.isHttpProxy() || configuration.isDisableStreamCache()) { // keep the body as is, and use type converters // for proxy use case pass the request body buffer directly to the response to avoid additional processing // we need to retain it so that the request can be released and we can keep the content answer.setBody(request.content().retain()); exchange.addOnCompletion(new SynchronizationAdapter() { @Override public void onDone(Exchange exchange) { ReferenceCountUtil.release(request.content()); } }); } else { // turn the body into stream cached (on the client/consumer side we can facade the netty stream instead of converting to byte array) NettyChannelBufferStreamCache cache = new NettyChannelBufferStreamCache(request.content()); // add on completion to the cache which is needed for Camel to keep track of the lifecycle of the cache exchange.addOnCompletion(new NettyChannelBufferStreamCacheOnCompletion(cache)); answer.setBody(cache); } return answer; } @Override public Message toCamelMessage(InboundStreamHttpRequest request, Exchange exchange, NettyHttpConfiguration configuration) throws Exception { LOG.trace("toCamelMessage: {}", request); NettyHttpMessage answer = new NettyHttpMessage(exchange.getContext(), null, null); answer.setExchange(exchange); if (configuration.isMapHeaders()) { populateCamelHeaders(request.getHttpRequest(), answer.getHeaders(), exchange, configuration); } answer.setBody(request.getInputStream()); return answer; } @Override public void populateCamelHeaders(HttpRequest request, Map<String, Object> headers, Exchange exchange, NettyHttpConfiguration configuration) throws Exception { LOG.trace("populateCamelHeaders: {}", request); // NOTE: these headers is applied using the same logic as camel-http/camel-jetty to be consistent headers.put(Exchange.HTTP_METHOD, request.method().name()); // strip query parameters from the uri String s = request.uri(); if (s.contains("?")) { s = StringHelper.before(s, "?"); } // we want the full path for the url, as the client may provide the url in the HTTP headers as absolute or relative, eg // /foo // http://servername/foo String http = configuration.isSsl() ? "https://" : "http://"; if (!s.startsWith(http)) { if (configuration.getPort() != 80) { s = http + configuration.getHost() + ":" + configuration.getPort() + s; } else { s = http + configuration.getHost() + s; } } headers.put(Exchange.HTTP_URL, s); // uri is without the host and port URI uri = new URI(request.uri()); // uri is path and query parameters headers.put(Exchange.HTTP_URI, uri.getPath()); headers.put(Exchange.HTTP_QUERY, uri.getQuery()); headers.put(Exchange.HTTP_RAW_QUERY, uri.getRawQuery()); headers.put(Exchange.HTTP_SCHEME, uri.getScheme()); headers.put(Exchange.HTTP_HOST, uri.getHost()); final int port = uri.getPort(); headers.put(Exchange.HTTP_PORT, port > 0 ? port : 80); // strip the starting endpoint path so the path is relative to the endpoint uri String path = uri.getRawPath(); if (configuration.getPath() != null) { // need to match by lower case as we want to ignore case on context-path String matchPath = path.toLowerCase(Locale.US); String match = configuration.getPath() != null ? configuration.getPath().toLowerCase(Locale.US) : null; if (match != null && matchPath.startsWith(match)) { path = path.substring(configuration.getPath().length()); } } // keep the path uri using the case the request provided (do not convert to lower case) headers.put(Exchange.HTTP_PATH, path); if (LOG.isTraceEnabled()) { LOG.trace("HTTP-Method {}", request.method().name()); LOG.trace("HTTP-Uri {}", request.uri()); } for (String name : request.headers().names()) { // mapping the content-type if (name.toLowerCase(Locale.US).equals("content-type")) { name = Exchange.CONTENT_TYPE; } if (name.toLowerCase(Locale.US).equals("authorization")) { String value = request.headers().get(name); // store a special header that this request was authenticated using HTTP Basic if (value != null && value.trim().startsWith("Basic")) { NettyHttpHelper.appendHeader(headers, NettyHttpConstants.HTTP_AUTHENTICATION, "Basic"); } } // add the headers one by one, and use the header filter strategy List<String> values = request.headers().getAll(name); Iterator<?> it = ObjectHelper.createIterator(values, ",", true); while (it.hasNext()) { Object extracted = it.next(); Object decoded = shouldUrlDecodeHeader(configuration, name, extracted, "UTF-8"); LOG.trace("HTTP-header: {}", extracted); if (headerFilterStrategy != null && !headerFilterStrategy.applyFilterToExternalHeaders(name, decoded, exchange)) { NettyHttpHelper.appendHeader(headers, name, decoded); } } } // add uri parameters as headers to the Camel message; // when acting as a HTTP proxy we don't want to place query // parameters in Camel message headers as the query parameters // will be passed via Exchange.HTTP_QUERY, otherwise we could have // both the Exchange.HTTP_QUERY and the values from the message // headers, so we end up with two values for the same query // parameter if (!configuration.isHttpProxy() && request.uri().contains("?")) { String query = StringHelper.after(request.uri(), "?"); Map<String, Object> uriParameters = URISupport.parseQuery(query, false, true); for (Map.Entry<String, Object> entry : uriParameters.entrySet()) { String name = entry.getKey(); Object values = entry.getValue(); Iterator<?> it = ObjectHelper.createIterator(values, ",", true); while (it.hasNext()) { Object extracted = it.next(); Object decoded = shouldUrlDecodeHeader(configuration, name, extracted, "UTF-8"); LOG.trace("URI-Parameter: {}", extracted); if (headerFilterStrategy != null && !headerFilterStrategy.applyFilterToExternalHeaders(name, decoded, exchange)) { NettyHttpHelper.appendHeader(headers, name, decoded); } } } } // if body is application/x-www-form-urlencoded then extract the body as query string and append as headers // if it is a bridgeEndpoint we need to skip this part of work // if we're proxying the body is a buffer that we do not want to consume directly if (request.method().name().equals("POST") && request.headers().get(Exchange.CONTENT_TYPE) != null && request.headers().get(Exchange.CONTENT_TYPE).startsWith(NettyHttpConstants.CONTENT_TYPE_WWW_FORM_URLENCODED) && !configuration.isBridgeEndpoint() && !configuration.isHttpProxy() && request instanceof FullHttpRequest) { String charset = "UTF-8"; // Push POST form params into the headers to retain compatibility with DefaultHttpBinding String body; ByteBuf buffer = ((FullHttpRequest)request).content(); try { body = buffer.toString(Charset.forName(charset)); } finally { buffer.release(); } if (org.apache.camel.util.ObjectHelper.isNotEmpty(body)) { for (String param : body.split("&")) { String[] pair = param.split("=", 2); if (pair.length == 2) { String name = shouldUrlDecodeHeader(configuration, "", pair[0], charset); String value = shouldUrlDecodeHeader(configuration, name, pair[1], charset); if (headerFilterStrategy != null && !headerFilterStrategy.applyFilterToExternalHeaders(name, value, exchange)) { NettyHttpHelper.appendHeader(headers, name, value); } } else { throw new IllegalArgumentException("Invalid parameter, expected to be a pair but was " + param); } } } } } /** * Decodes the header if needed to, or returns the header value as is. * * @param configuration the configuration * @param headerName the header name * @param value the current header value * @param charset the charset to use for decoding * @return the decoded value (if decoded was needed) or a <tt>toString</tt> representation of the value. * @throws UnsupportedEncodingException is thrown if error decoding. */ protected String shouldUrlDecodeHeader(NettyHttpConfiguration configuration, String headerName, Object value, String charset) throws UnsupportedEncodingException { // do not decode Content-Type if (Exchange.CONTENT_TYPE.equals(headerName)) { return value.toString(); } else if (configuration.isUrlDecodeHeaders()) { return URLDecoder.decode(value.toString(), charset); } else { return value.toString(); } } @Override public Message toCamelMessage(FullHttpResponse response, Exchange exchange, NettyHttpConfiguration configuration) throws Exception { LOG.trace("toCamelMessage: {}", response); NettyHttpMessage answer = new NettyHttpMessage(exchange.getContext(), null, response); answer.setExchange(exchange); if (configuration.isMapHeaders()) { populateCamelHeaders(response, answer.getHeaders(), exchange, configuration); } if (configuration.isDisableStreamCache() || configuration.isHttpProxy()) { // keep the body as is, and use type converters answer.setBody(response.content()); } else { // stores as byte array as the netty ByteBuf will be freed when the producer is done, and then we can no longer access the message body response.retain(); try { byte[] bytes = exchange.getContext().getTypeConverter().convertTo(byte[].class, exchange, response.content()); answer.setBody(bytes); } finally { response.release(); } } return answer; } @Override public Message toCamelMessage(InboundStreamHttpResponse response, Exchange exchange, NettyHttpConfiguration configuration) throws Exception { LOG.trace("toCamelMessage: {}", response); NettyHttpMessage answer = new NettyHttpMessage(exchange.getContext(), null, null); answer.setExchange(exchange); if (configuration.isMapHeaders()) { populateCamelHeaders(response.getHttpResponse(), answer.getHeaders(), exchange, configuration); } answer.setBody(response.getInputStream()); return answer; } @Override public void populateCamelHeaders(HttpResponse response, Map<String, Object> headers, Exchange exchange, NettyHttpConfiguration configuration) throws Exception { LOG.trace("populateCamelHeaders: {}", response); headers.put(Exchange.HTTP_RESPONSE_CODE, response.status().code()); headers.put(Exchange.HTTP_RESPONSE_TEXT, response.status().reasonPhrase()); for (String name : response.headers().names()) { // mapping the content-type if (name.toLowerCase().equals("content-type")) { name = Exchange.CONTENT_TYPE; } // add the headers one by one, and use the header filter strategy List<String> values = response.headers().getAll(name); Iterator<?> it = ObjectHelper.createIterator(values); while (it.hasNext()) { Object extracted = it.next(); LOG.trace("HTTP-header: {}", extracted); if (headerFilterStrategy != null && !headerFilterStrategy.applyFilterToExternalHeaders(name, extracted, exchange)) { NettyHttpHelper.appendHeader(headers, name, extracted); } } } } @Override public HttpResponse toNettyResponse(Message message, NettyHttpConfiguration configuration) throws Exception { LOG.trace("toNettyResponse: {}", message); if (message instanceof NettyHttpMessage) { final NettyHttpMessage nettyHttpMessage = (NettyHttpMessage) message; final FullHttpResponse response = nettyHttpMessage.getHttpResponse(); if (response != null && nettyHttpMessage.getBody() == null) { return response.retain(); } } // the message body may already be a Netty HTTP response if (message.getBody() instanceof HttpResponse) { return (HttpResponse) message.getBody(); } Object body = message.getBody(); Exception cause = message.getExchange().getException(); // support bodies as native Netty ByteBuf buffer; int code = determineResponseCode(message.getExchange(), body); LOG.trace("HTTP Status Code: {}", code); // if there was an exception then use that as body if (cause != null && !configuration.isMuteException()) { if (configuration.isTransferException()) { // we failed due an exception, and transfer it as java serialized object ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(cause); oos.flush(); IOHelper.close(oos, bos); // the body should be the serialized java object of the exception body = NettyConverter.toByteBuffer(bos.toByteArray()); // force content type to be serialized java object message.setHeader(Exchange.CONTENT_TYPE, NettyHttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT); } else { // we failed due an exception so print it as plain text StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); cause.printStackTrace(pw); // the body should then be the stacktrace body = NettyConverter.toByteBuffer(sw.toString().getBytes()); // force content type to be text/plain as that is what the stacktrace is message.setHeader(Exchange.CONTENT_TYPE, "text/plain"); } // and mark the exception as failure handled, as we handled it by returning it as the response ExchangeHelper.setFailureHandled(message.getExchange()); } else if (cause != null && configuration.isMuteException()) { // the body should hide the stacktrace (muteException enabled) body = NettyConverter.toByteBuffer("Exception".getBytes()); // force content type to be text/plain message.setHeader(Exchange.CONTENT_TYPE, "text/plain"); // and mark the exception as failure handled, as we handled it by actively muting it ExchangeHelper.setFailureHandled(message.getExchange()); } HttpResponse response = null; if (response == null && body instanceof InputStream && configuration.isDisableStreamCache()) { response = new OutboundStreamHttpResponse((InputStream)body, new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(code))); response.headers().set(TRANSFER_ENCODING, CHUNKED); } if (response == null) { if (body instanceof ByteBuf) { buffer = (ByteBuf) body; } else { // try to convert to buffer first buffer = message.getBody(ByteBuf.class); if (buffer == null) { // fallback to byte array as last resort byte[] data = message.getBody(byte[].class); if (data != null) { buffer = NettyConverter.toByteBuffer(data); } else { // and if byte array fails then try String String str; if (body != null) { str = message.getMandatoryBody(String.class); } else { str = ""; } buffer = NettyConverter.toByteBuffer(str.getBytes()); } } } if (buffer != null) { response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(code), buffer); // We just need to reset the readerIndex this time if (buffer.readerIndex() == buffer.writerIndex()) { buffer.setIndex(0, buffer.writerIndex()); } // TODO How to enable the chunk transport int len = buffer.readableBytes(); // set content-length response.headers().set(HttpHeaderNames.CONTENT_LENGTH.toString(), len); LOG.trace("Content-Length: {}", len); } else { response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(code)); } } TypeConverter tc = message.getExchange().getContext().getTypeConverter(); // append headers // must use entrySet to ensure case of keys is preserved for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); // use an iterator as there can be multiple values. (must not use a delimiter) final Iterator<?> it = ObjectHelper.createIterator(value, null, true); while (it.hasNext()) { String headerValue = tc.convertTo(String.class, it.next()); if (headerValue != null && headerFilterStrategy != null && !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, message.getExchange())) { LOG.trace("HTTP-Header: {}={}", key, headerValue); response.headers().add(key, headerValue); } } } // set the content type in the response. String contentType = MessageHelper.getContentType(message); if (contentType != null) { // set content-type response.headers().set(HttpHeaderNames.CONTENT_TYPE.toString(), contentType); LOG.trace("Content-Type: {}", contentType); } // configure connection to accordingly to keep alive configuration // favor using the header from the message String connection = message.getHeader(HttpHeaderNames.CONNECTION.toString(), String.class); // Read the connection header from the exchange property if (connection == null) { connection = message.getExchange().getProperty(HttpHeaderNames.CONNECTION.toString(), String.class); } if (connection == null) { // fallback and use the keep alive from the configuration if (configuration.isKeepAlive()) { connection = HttpHeaderValues.KEEP_ALIVE.toString(); } else { connection = HttpHeaderValues.CLOSE.toString(); } } response.headers().set(HttpHeaderNames.CONNECTION.toString(), connection); // Just make sure we close the channel when the connection value is close if (connection.equalsIgnoreCase(HttpHeaderValues.CLOSE.toString())) { message.setHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true); } LOG.trace("Connection: {}", connection); return response; } /* * set the HTTP status code */ private int determineResponseCode(Exchange camelExchange, Object body) { boolean failed = camelExchange.isFailed(); int defaultCode = failed ? 500 : 200; Message message = camelExchange.getMessage(); Integer currentCode = message.getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class); int codeToUse = currentCode == null ? defaultCode : currentCode; if (codeToUse != 500) { if ((body == null) || (body instanceof String && ((String) body).trim().isEmpty())) { // no content codeToUse = currentCode == null ? 204 : currentCode; } } return codeToUse; } @Override public HttpRequest toNettyRequest(Message message, String fullUri, NettyHttpConfiguration configuration) throws Exception { LOG.trace("toNettyRequest: {}", message); Object body = message.getBody(); // the message body may already be a Netty HTTP response if (body instanceof HttpRequest) { return (HttpRequest) message.getBody(); } String uriForRequest = fullUri; if (configuration.isUseRelativePath()) { final URI uri = new URI(uriForRequest); final String rawPath = uri.getRawPath(); if (rawPath != null) { uriForRequest = rawPath; } final String rawQuery = uri.getRawQuery(); if (rawQuery != null) { uriForRequest += "?" + rawQuery; } } final String headerProtocolVersion = message.getHeader(Exchange.HTTP_PROTOCOL_VERSION, String.class); final HttpVersion protocol; if (headerProtocolVersion == null) { protocol = HttpVersion.HTTP_1_1; } else { protocol = HttpVersion.valueOf(headerProtocolVersion); } final String headerMethod = message.getHeader(Exchange.HTTP_METHOD, String.class); final HttpMethod httpMethod; if (headerMethod == null) { httpMethod = HttpMethod.GET; } else { httpMethod = HttpMethod.valueOf(headerMethod); } HttpRequest request = null; if (message instanceof NettyHttpMessage) { // if the request is already given we should set the values // from message headers and pass on the same request final FullHttpRequest givenRequest = ((NettyHttpMessage) message).getHttpRequest(); // we need to make sure that the givenRequest is the original // request received by the proxy, only when the body wasn't // modified by a processor on route if (givenRequest != null && givenRequest.content() == body) { request = givenRequest .setProtocolVersion(protocol) .setMethod(httpMethod) .setUri(uriForRequest); } } if (request == null && body instanceof InputStream && configuration.isDisableStreamCache()) { request = new OutboundStreamHttpRequest((InputStream)body, new DefaultHttpRequest(protocol, httpMethod, uriForRequest)); request.headers().set(TRANSFER_ENCODING, CHUNKED); } if (request == null) { request = new DefaultFullHttpRequest(protocol, httpMethod, uriForRequest); if (body != null) { // support bodies as native Netty ByteBuf buffer; if (body instanceof ByteBuf) { buffer = (ByteBuf) body; } else { // try to convert to buffer first buffer = message.getBody(ByteBuf.class); if (buffer == null) { // fallback to byte array as last resort byte[] data = message.getMandatoryBody(byte[].class); if (data.length > 0) { buffer = NettyConverter.toByteBuffer(data); } } } if (buffer != null) { if (buffer.readableBytes() > 0) { request = ((DefaultFullHttpRequest)request).replace(buffer); int len = buffer.readableBytes(); // set content-length request.headers().set(HttpHeaderNames.CONTENT_LENGTH.toString(), len); LOG.trace("Content-Length: {}", len); } else { buffer.release(); } } } } // update HTTP method accordingly as we know if we have a body or not HttpMethod method = NettyHttpHelper.createMethod(message, body != null); request.setMethod(method); TypeConverter tc = message.getExchange().getContext().getTypeConverter(); // if we bridge endpoint then we need to skip matching headers with the HTTP_QUERY to avoid sending // duplicated headers to the receiver, so use this skipRequestHeaders as the list of headers to skip Map<String, Object> skipRequestHeaders = null; if (configuration.isBridgeEndpoint()) { String queryString = message.getHeader(Exchange.HTTP_QUERY, String.class); if (queryString != null) { skipRequestHeaders = URISupport.parseQuery(queryString, false, true); } // Need to remove the Host key as it should be not used message.getHeaders().remove("host"); } // append headers // must use entrySet to ensure case of keys is preserved for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); // we should not add headers for the parameters in the uri if we bridge the endpoint // as then we would duplicate headers on both the endpoint uri, and in HTTP headers as well if (skipRequestHeaders != null && skipRequestHeaders.containsKey(key)) { continue; } // use an iterator as there can be multiple values. (must not use a delimiter) final Iterator<?> it = ObjectHelper.createIterator(value, null, true); while (it.hasNext()) { String headerValue = tc.convertTo(String.class, it.next()); if (headerValue != null && headerFilterStrategy != null && !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, message.getExchange())) { LOG.trace("HTTP-Header: {}={}", key, headerValue); request.headers().add(key, headerValue); } } } // set the content type in the response. String contentType = MessageHelper.getContentType(message); if (contentType != null) { // set content-type request.headers().set(HttpHeaderNames.CONTENT_TYPE.toString(), contentType); LOG.trace("Content-Type: {}", contentType); } // must include HOST header as required by HTTP 1.1 // use URI as its faster than URL (no DNS lookup) URI u = new URI(fullUri); int port = u.getPort(); String hostHeader = u.getHost() + (port == 80 || port == -1 ? "" : ":" + u.getPort()); request.headers().set(HttpHeaderNames.HOST.toString(), hostHeader); LOG.trace("Host: {}", hostHeader); // configure connection to accordingly to keep alive configuration // favor using the header from the message String connection = message.getHeader(HttpHeaderNames.CONNECTION.toString(), String.class); if (connection == null) { // fallback and use the keep alive from the configuration if (configuration.isKeepAlive()) { connection = HttpHeaderValues.KEEP_ALIVE.toString(); } else { connection = HttpHeaderValues.CLOSE.toString(); } } request.headers().set(HttpHeaderNames.CONNECTION.toString(), connection); LOG.trace("Connection: {}", connection); return request; } @Override public HeaderFilterStrategy getHeaderFilterStrategy() { return headerFilterStrategy; } @Override public void setHeaderFilterStrategy(HeaderFilterStrategy headerFilterStrategy) { this.headerFilterStrategy = headerFilterStrategy; } }
CAMEL-14025 - Fixed CS
components/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/DefaultNettyHttpBinding.java
CAMEL-14025 - Fixed CS
<ide><path>omponents/camel-netty-http/src/main/java/org/apache/camel/component/netty/http/DefaultNettyHttpBinding.java <ide> <ide> // and mark the exception as failure handled, as we handled it by returning it as the response <ide> ExchangeHelper.setFailureHandled(message.getExchange()); <del> } <del> else if (cause != null && configuration.isMuteException()) { <add> } else if (cause != null && configuration.isMuteException()) { <ide> <ide> // the body should hide the stacktrace (muteException enabled) <ide> body = NettyConverter.toByteBuffer("Exception".getBytes());
JavaScript
isc
a7e67c9a7c23df20c37996ed5056a3a1a2f55510
0
probot/stale,probot/stale
const createScheduler = require('probot-scheduler'); const Stale = require('./lib/stale'); module.exports = async robot => { // Visit all repositories to mark and sweep stale issues const scheduler = createScheduler(robot); // Unmark stale issues if a user comments robot.on('issue_comment', unmark); robot.on('issues', unmark); robot.on('pull_request', unmark); robot.on('pull_request_review', unmark); robot.on('pull_request_review_comment', unmark); robot.on('schedule.repository', markAndSweep); async function unmark(context) { if (!context.isBot) { const stale = await forRepository(context); let issue = context.payload.issue || context.payload.pull_request; // Some payloads don't include labels if (!issue.labels) { issue = (await context.github.issues.get(context.issue())).data; } const staleLabelAdded = context.payload.action === 'labeled' && context.payload.label.name === stale.config.staleLabel; if (stale.hasStaleLabel(issue) && issue.state !== 'closed' && !staleLabelAdded) { stale.unmark(issue); } } } async function markAndSweep(context) { const stale = await forRepository(context); if (stale.config.perform) { return stale.markAndSweep(); } } async function forRepository(context) { let config; try { config = await context.config('stale.yml'); } catch (err) { scheduler.stop(context.payload.repository); // Don't actually perform for repository without a config config = {perform: false}; } config = Object.assign(config, context.repo({logger: robot.log})); return new Stale(context.github, config); } };
index.js
const createScheduler = require('probot-scheduler'); const Stale = require('./lib/stale'); module.exports = async robot => { // Visit all repositories to mark and sweep stale issues const scheduler = createScheduler(robot); // Unmark stale issues if a user comments robot.on('issue_comment', unmark); robot.on('issues', unmark); robot.on('pull_request', unmark); robot.on('pull_request_review', unmark); robot.on('pull_request_review_comment', unmark); robot.on('schedule.repository', markAndSweep); async function unmark(event, context) { if (!context.isBot) { const stale = await forRepository(context); let issue = event.payload.issue || event.payload.pull_request; // Some payloads don't include labels if (!issue.labels) { issue = (await context.github.issues.get(context.issue())).data; } const staleLabelAdded = event.payload.action === 'labeled' && event.payload.label.name === stale.config.staleLabel; if (stale.hasStaleLabel(issue) && issue.state !== 'closed' && !staleLabelAdded) { stale.unmark(issue); } } } async function markAndSweep(context) { const stale = await forRepository(context); if (stale.config.perform) { return stale.markAndSweep(); } } async function forRepository(context) { let config; try { config = await context.config('stale.yml'); } catch (err) { scheduler.stop(context.payload.repository); // Don't actually perform for repository without a config config = {perform: false}; } config = Object.assign(config, context.repo({logger: robot.log})); return new Stale(context.github, config); } };
Combine event and context to fix deprecation
index.js
Combine event and context to fix deprecation
<ide><path>ndex.js <ide> robot.on('pull_request_review_comment', unmark); <ide> robot.on('schedule.repository', markAndSweep); <ide> <del> async function unmark(event, context) { <add> async function unmark(context) { <ide> if (!context.isBot) { <ide> const stale = await forRepository(context); <del> let issue = event.payload.issue || event.payload.pull_request; <add> let issue = context.payload.issue || context.payload.pull_request; <ide> <ide> // Some payloads don't include labels <ide> if (!issue.labels) { <ide> issue = (await context.github.issues.get(context.issue())).data; <ide> } <ide> <del> const staleLabelAdded = event.payload.action === 'labeled' && <del> event.payload.label.name === stale.config.staleLabel; <add> const staleLabelAdded = context.payload.action === 'labeled' && <add> context.payload.label.name === stale.config.staleLabel; <ide> <ide> if (stale.hasStaleLabel(issue) && issue.state !== 'closed' && !staleLabelAdded) { <ide> stale.unmark(issue);
Java
apache-2.0
c4a4f4bccfebf576fa9ac3167e53c92b7156d408
0
JetBrains/teamcity-nuget-support,JetBrains/teamcity-nuget-support,JetBrains/teamcity-nuget-support,JetBrains/teamcity-nuget-support,stormleoxia/teamcity-nuget-support,stormleoxia/teamcity-nuget-support,stormleoxia/teamcity-nuget-support
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.buildServer.nuget.tests.server; import jetbrains.buildServer.BaseTestCase; import jetbrains.buildServer.RootUrlHolder; import jetbrains.buildServer.agent.AgentRuntimeProperties; import jetbrains.buildServer.buildTriggers.BuildTriggerDescriptor; import jetbrains.buildServer.buildTriggers.BuildTriggerException; import jetbrains.buildServer.nuget.server.exec.SourcePackageInfo; import jetbrains.buildServer.nuget.server.exec.SourcePackageReference; import jetbrains.buildServer.nuget.server.toolRegistry.NuGetToolManager; import jetbrains.buildServer.nuget.server.trigger.NamedPackagesUpdateChecker; import jetbrains.buildServer.nuget.server.trigger.PackagesHashCalculator; import jetbrains.buildServer.nuget.server.trigger.TriggerConstants; import jetbrains.buildServer.nuget.server.trigger.impl.*; import jetbrains.buildServer.nuget.server.util.SystemInfo; import jetbrains.buildServer.serverSide.CustomDataStorage; import jetbrains.buildServer.util.TestFor; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jmock.Mockery; import org.jmock.api.Invocation; import org.jmock.lib.action.CustomAction; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.File; import java.util.Arrays; import java.util.Collections; import java.util.Map; import java.util.TreeMap; /** * Created by Eugene Petrenko ([email protected]) * Date: 14.07.11 18:57 */ public class NamedPackagesUpdateCheckerTest extends BaseTestCase { private Mockery m; private NamedPackagesUpdateChecker checker; private BuildTriggerDescriptor desr; private CustomDataStorage store; private NuGetToolManager manager; private PackageChangesManager chk; private Map<String, String> params; private File nugetFakePath; private RootUrlHolder myRootUrlHolder; private boolean myIsWindows; @BeforeMethod @Override protected void setUp() throws Exception { super.setUp(); myIsWindows = true; m = new Mockery(); desr = m.mock(BuildTriggerDescriptor.class); store = m.mock(CustomDataStorage.class); params = new TreeMap<String, String>(); manager = m.mock(NuGetToolManager.class); chk = m.mock(PackageChangesManager.class); myRootUrlHolder = m.mock(RootUrlHolder.class); final SystemInfo si = m.mock(SystemInfo.class); checker = new NamedPackagesUpdateChecker(chk, new TriggerRequestFactory(new CheckRequestModeFactory(si), manager, new PackageCheckRequestFactory(new PackageCheckerSettingsImpl()), myRootUrlHolder), new PackagesHashCalculator()); nugetFakePath = createTempFile(); final String path = nugetFakePath.getPath(); m.checking(new Expectations(){{ allowing(desr).getProperties(); will(returnValue(params)); allowing(manager).getNuGetPath(path); will(returnValue(path)); allowing(si).canStartNuGetProcesses(); will(new CustomAction("Return myIsWindows") { public Object invoke(Invocation invocation) throws Throwable { return myIsWindows; } }); }}); params.put(TriggerConstants.NUGET_EXE, path); params.put(TriggerConstants.PACKAGE, "NUnit"); } @Test public void test_resolves_own_feed_url() { params.put(TriggerConstants.SOURCE, "%"+ AgentRuntimeProperties.TEAMCITY_SERVER_URL+"%/a/b/c"); m.checking(new Expectations(){{ allowing(myRootUrlHolder).getRootUrl(); will(returnValue("http://some-teamcity-with-nuget.org/jonnyzzz")); oneOf(chk).checkPackage(with(req(nugetFakePath, "http://some-teamcity-with-nuget.org/jonnyzzz/a/b/c", "NUnit", null))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo("src", "pkg", "5.6.87"))))); oneOf(store).getValue("hash"); will(returnValue(null)); oneOf(store).putValue(with(equal("hash")), with(any(String.class))); oneOf(store).flush(); }}); Assert.assertNull(checker.checkChanges(desr, store)); m.assertIsSatisfied(); } @Test public void test_check_first_time_should_not_trigger() { m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo("src", "pkg", "5.6.87"))))); oneOf(store).getValue("hash"); will(returnValue(null)); oneOf(store).putValue(with(equal("hash")), with(any(String.class))); oneOf(store).flush(); }}); Assert.assertNull(checker.checkChanges(desr, store)); m.assertIsSatisfied(); } @Test public void test_check_first_time_should_not_trigger_linux() { myIsWindows = false; m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(reqTC(null, "NUnit"))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo("src", "pkg", "5.6.87"))))); oneOf(store).getValue("hash"); will(returnValue(null)); oneOf(store).putValue(with(equal("hash")), with(any(String.class))); oneOf(store).flush(); }}); Assert.assertNull(checker.checkChanges(desr, store)); m.assertIsSatisfied(); } @Test public void test_should_trigger_on_new_package() { final String source = "\\\\ServerNameRemoved\\NugetTest\\Repository"; params.put(TriggerConstants.PACKAGE, "Common"); params.put(TriggerConstants.SOURCE, source); m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(req(nugetFakePath, source, "Common", null))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo(source, "Common", "1.0.0.21"))))); oneOf(chk).checkPackage(with(req(nugetFakePath, source, "Common", null))); will(returnValue(CheckResult.fromResult(Arrays.asList( new SourcePackageInfo(source, "Common", "1.0.0.21"), new SourcePackageInfo(source, "Common", "2.0.0.22") )))); final String hash1 = "v2|s:\\\\ServerNameRemoved\\NugetTest\\Repository|p:Common|v:1.0.0.21"; final String hash2 = "v2|s:\\\\ServerNameRemoved\\NugetTest\\Repository|p:Common|v:1.0.0.21|s:\\\\ServerNameRemoved\\NugetTest\\Repository|p:Common|v:2.0.0.22"; oneOf(store).getValue("hash"); will(returnValue(null)); oneOf(store).putValue("hash", hash1); oneOf(store).flush(); oneOf(store).getValue("hash"); will(returnValue(hash1)); oneOf(store).putValue("hash", hash2); oneOf(store).flush(); }}); Assert.assertNull(checker.checkChanges(desr, store)); Assert.assertNotNull(checker.checkChanges(desr, store)); m.assertIsSatisfied(); } @Test public void test_should_trigger_on_new_package2() { final String source = "\\\\ServerNameRemoved\\NugetTest\\Repository"; params.put(TriggerConstants.PACKAGE, "Common"); params.put(TriggerConstants.SOURCE, source); m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(req(nugetFakePath, source, "Common", null))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo(source, "Common", "1.0.0.21"))))); oneOf(chk).checkPackage(with(req(nugetFakePath, source, "Common", null))); will(returnValue(CheckResult.fromResult(Arrays.asList( new SourcePackageInfo(source, "Common", "1.0.0.21"), new SourcePackageInfo(source, "Common", "2.0.0.22") )))); final String hash1 = "v2|s:\\\\ServerNameRemoved\\NugetTest\\Repository|p:Common|v:1.0.0.21"; final String hash2 = "v2|s:\\\\ServerNameRemoved\\NugetTest\\Repository|p:Common|v:1.0.0.21|s:\\\\ServerNameRemoved\\NugetTest\\Repository|p:Common|v:2.0.0.22"; oneOf(store).getValue("hash"); will(returnValue(hash1)); oneOf(store).getValue("hash"); will(returnValue(hash1)); oneOf(store).putValue("hash", hash2); oneOf(store).flush(); }}); Assert.assertNull(checker.checkChanges(desr, store)); Assert.assertNotNull(checker.checkChanges(desr, store)); m.assertIsSatisfied(); } @Test public void test_should_sort_packages() { final String source = "\\\\ServerNameRemoved\\NugetTest\\Repository"; params.put(TriggerConstants.PACKAGE, "Common"); params.put(TriggerConstants.SOURCE, source); m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(req(nugetFakePath, source, "Common", null))); will(returnValue(CheckResult.fromResult(Arrays.asList( new SourcePackageInfo(source, "Common", "1.0.0.21"), new SourcePackageInfo(null, "Common", "2.0.0.22"), new SourcePackageInfo("s2", "C3ommon", "2.0.0.22"), new SourcePackageInfo(null, "C3ommon", "2.0.0.22"), new SourcePackageInfo(null, "C3o4mmon", "2.0.0.22"), new SourcePackageInfo("s4", "C3o3mmon", "2.0.0.22"), new SourcePackageInfo(null, "C3omm5on", "2.0.0.22") )))); final String hash1 = "v2|s:\\\\ServerNameRemoved\\NugetTest\\Repository|p:Common|v:1.0.0.21|s:s2|p:C3ommon|v:2.0.0.22|s:s4|p:C3o3mmon|v:2.0.0.22|p:C3o4mmon|v:2.0.0.22|p:C3omm5on|v:2.0.0.22|p:C3ommon|v:2.0.0.22|p:Common|v:2.0.0.22"; oneOf(store).getValue("hash"); will(returnValue("v2foo")); oneOf(store).putValue("hash", hash1); oneOf(store).flush(); }}); Assert.assertNotNull(checker.checkChanges(desr, store)); m.assertIsSatisfied(); } @Test public void test_check_should_not_trigger_twice() { m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo("src", "pkg", "5.6.87"))))); oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo("src", "pkg", "5.6.87"))))); oneOf(store).getValue("hash"); will(returnValue("v2aaa")); oneOf(store).putValue("hash", "v2|s:src|p:pkg|v:5.6.87"); oneOf(store).getValue("hash"); will(returnValue("v2|s:src|p:pkg|v:5.6.87")); oneOf(store).flush(); }}); Assert.assertNotNull(checker.checkChanges(desr, store)); Assert.assertNull(checker.checkChanges(desr, store)); m.assertIsSatisfied(); } @Test @TestFor(issues = "TW-24575") public void test_should_throw_error_if_no_packages_found_but_not_update_hash() { m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); will(returnValue(CheckResult.fromResult(Collections.<SourcePackageInfo>emptyList()))); oneOf(store).getValue("hash"); will(returnValue("v2|s:src|p:pkg|v:5.6.87")); never(store).putValue("hash", "v2"); never(store).flush(); }}); try { checker.checkChanges(desr, store); Assert.fail("Exception is expected"); } catch (BuildTriggerException e) { Assert.assertTrue(e.getMessage().contains("Package NUnit was not found in the feed")); } m.assertIsSatisfied(); } @Test @TestFor(issues = "TW-27263") public void test_should_not_update_cache_if_no_packages_found_and_cache_already_valid() { m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); will(returnValue(CheckResult.fromResult(Collections.<SourcePackageInfo>emptyList()))); oneOf(store).getValue("hash"); will(returnValue("v2|s:src|p:pkg|v:5.6.87")); never(store).putValue("hash", "v2"); never(store).flush(); }}); try { checker.checkChanges(desr, store); Assert.fail("Exception is expected"); } catch (BuildTriggerException e) { Assert.assertTrue(e.getMessage().contains("Package NUnit was not found in the feed")); } m.assertIsSatisfied(); } @Test @TestFor(issues = "TW-27263") public void test_should_update_cache_if_no_packages_found_and_cache_empty() { m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); will(returnValue(CheckResult.fromResult(Collections.<SourcePackageInfo>emptyList()))); oneOf(store).getValue("hash"); will(returnValue(null)); oneOf(store).putValue("hash", "v2"); oneOf(store).flush(); }}); try { checker.checkChanges(desr, store); Assert.fail("Exception is expected"); } catch (BuildTriggerException e) { Assert.assertTrue(e.getMessage().contains("Package NUnit was not found in the feed")); } m.assertIsSatisfied(); } @Test @TestFor(issues = "TW-24575") public void test_should_trigger_zero_to_one() { m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo("src", "pkg", "5.6.87"))))); oneOf(store).getValue("hash"); will(returnValue("v2")); oneOf(store).putValue("hash", "v2|s:src|p:pkg|v:5.6.87"); oneOf(store).flush(); }}); Assert.assertNotNull(checker.checkChanges(desr, store)); m.assertIsSatisfied(); } @Test @TestFor(issues = "TW-24575") public void test_should_trigger_none_to_one() { m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); will(returnValue(CheckResult.fromResult(Collections.<SourcePackageInfo>emptyList()))); oneOf(store).getValue("hash"); will(returnValue(null)); oneOf(store).putValue("hash", "v2"); oneOf(store).flush(); }}); try { checker.checkChanges(desr, store); Assert.fail("Exception is expected"); } catch (BuildTriggerException e) { Assert.assertTrue(e.getMessage().contains("Package NUnit was not found in the feed")); } m.assertIsSatisfied(); m.checking(new Expectations() {{ oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo("src", "pkg", "5.6.87"))))); oneOf(store).getValue("hash"); will(returnValue("v2")); oneOf(store).putValue("hash", "v2|s:src|p:pkg|v:5.6.87"); oneOf(store).flush(); }}); Assert.assertNotNull(checker.checkChanges(desr, store)); m.assertIsSatisfied(); } @Test @TestFor(issues = "TW-24575") public void test_should_throw_error_if_check_result() { m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); will(returnValue(CheckResult.failed("something5555"))); }}); try { checker.checkChanges(desr, store); Assert.fail("Exception is expected"); } catch (BuildTriggerException e) { Assert.assertTrue(e.getMessage().contains("something5555")); } m.assertIsSatisfied(); } @Test public void test_check_should_not_trigger_from_older_hash() { m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo("src", "pkg", "5.6.87"))))); oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo("src", "pkg", "5.6.87"))))); oneOf(store).getValue("hash"); will(returnValue("aaa")); oneOf(store).putValue("hash", "v2|s:src|p:pkg|v:5.6.87"); oneOf(store).getValue("hash"); will(returnValue("v2|s:src|p:pkg|v:5.6.87")); oneOf(store).flush(); }}); Assert.assertNull(checker.checkChanges(desr, store)); Assert.assertNull(checker.checkChanges(desr, store)); m.assertIsSatisfied(); } @Test public void test_check_should_not_trigger_twice_linux() { myIsWindows = false; m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(reqTC(null, "NUnit"))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo("src", "pkg", "5.6.87"))))); oneOf(chk).checkPackage(with(reqTC(null, "NUnit"))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo("src", "pkg", "5.6.87"))))); oneOf(store).getValue("hash"); will(returnValue("v2aaa")); oneOf(store).putValue("hash", "v2|s:src|p:pkg|v:5.6.87"); oneOf(store).getValue("hash"); will(returnValue("v2|s:src|p:pkg|v:5.6.87")); oneOf(store).flush(); }}); Assert.assertNotNull(checker.checkChanges(desr, store)); Assert.assertNull(checker.checkChanges(desr, store)); m.assertIsSatisfied(); } @Test public void test_check_should_not_trigger_after_error() { m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo("src", "pkg", "5.6.87"))))); oneOf(chk).checkPackage(with(req(nugetFakePath))); will(throwException(new RuntimeException("Failed to execute command"))); oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo("src", "pkg", "5.6.87"))))); oneOf(store).getValue("hash"); will(returnValue("v2aaa")); oneOf(store).putValue("hash", "v2|s:src|p:pkg|v:5.6.87"); oneOf(store).getValue("hash"); will(returnValue("v2|s:src|p:pkg|v:5.6.87")); oneOf(store).flush(); }}); Assert.assertNotNull(checker.checkChanges(desr, store)); try { checker.checkChanges(desr, store); Assert.fail("should throw an exception"); } catch (BuildTriggerException e) { //NOP } Assert.assertNull(checker.checkChanges(desr, store)); m.assertIsSatisfied(); } @Test public void test_check_should_fail_on_error() { m.checking(new Expectations() {{ oneOf(chk).checkPackage(with(req(nugetFakePath))); will(throwException(new RuntimeException("Failed to execute command"))); }}); try { checker.checkChanges(desr, store); Assert.fail("should throw an exception"); } catch (BuildTriggerException e) { //NOP } m.assertIsSatisfied(); } @Test public void test_check_should_fail_on_error2() { m.checking(new Expectations() {{ oneOf(chk).checkPackage(with(req(nugetFakePath))); will(returnValue(CheckResult.failed("Failed to execute command"))); }}); try { checker.checkChanges(desr, store); Assert.fail("should throw an exception"); } catch (BuildTriggerException e) { //NOP } m.assertIsSatisfied(); } private static class Expectations extends org.jmock.Expectations { public Matcher<PackageCheckRequest> req(@NotNull final File nugetPath, @Nullable final String source, @NotNull final String id, @Nullable final String version) { return new BaseMatcher<PackageCheckRequest>() { private boolean equals(Object a, Object b) { if (a == null && b == null) return true; return a != null && a.equals(b); } public boolean matches(Object o) { if (!(o instanceof PackageCheckRequest)) return false; PackageCheckRequest r = (PackageCheckRequest) o; final SourcePackageReference pkg = r.getPackage(); if (!pkg.getPackageId().equals(id)) return false; if (!equals(pkg.getSource(), source)) return false; if (!equals(pkg.getVersionSpec(), version)) return false; final CheckRequestMode mode = r.getMode(); if (!(mode instanceof CheckRequestModeNuGet)) return false; if (!((CheckRequestModeNuGet) mode).getNuGetPath().equals(nugetPath)) return false; return true; } public void describeTo(Description description) { description.appendText("Package: ").appendValue(id).appendText("Source: ").appendValue(source); } }; } public Matcher<PackageCheckRequest> reqTC(@Nullable final String source, @NotNull final String id) { return new BaseMatcher<PackageCheckRequest>() { private boolean equals(Object a, Object b) { if (a == null && b == null) return true; return a != null && a.equals(b); } public boolean matches(Object o) { if (!(o instanceof PackageCheckRequest)) return false; PackageCheckRequest r = (PackageCheckRequest) o; final SourcePackageReference pkg = r.getPackage(); if (!pkg.getPackageId().equals(id)) return false; if (!equals(pkg.getSource(), source)) return false; final CheckRequestMode mode = r.getMode(); return mode instanceof CheckRequestModeTeamCity; } public void describeTo(Description description) { description.appendText("Package: ").appendValue(id).appendText("Source: ").appendValue(source); } }; } public Matcher<PackageCheckRequest> req(@NotNull final File nugetPath) { return new BaseMatcher<PackageCheckRequest>() { public boolean matches(Object o) { if (!(o instanceof PackageCheckRequest)) return false; PackageCheckRequest r = (PackageCheckRequest) o; final CheckRequestMode mode = r.getMode(); if (!(mode instanceof CheckRequestModeNuGet)) return false; if (!((CheckRequestModeNuGet) mode).getNuGetPath().equals(nugetPath)) return false; return true; } public void describeTo(Description description) { description.appendText("NuGet check path ").appendValue(nugetPath); } }; } } }
nuget-tests/src/jetbrains/buildServer/nuget/tests/server/NamedPackagesUpdateCheckerTest.java
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.buildServer.nuget.tests.server; import jetbrains.buildServer.BaseTestCase; import jetbrains.buildServer.RootUrlHolder; import jetbrains.buildServer.agent.AgentRuntimeProperties; import jetbrains.buildServer.buildTriggers.BuildTriggerDescriptor; import jetbrains.buildServer.buildTriggers.BuildTriggerException; import jetbrains.buildServer.nuget.server.exec.SourcePackageInfo; import jetbrains.buildServer.nuget.server.exec.SourcePackageReference; import jetbrains.buildServer.nuget.server.toolRegistry.NuGetToolManager; import jetbrains.buildServer.nuget.server.trigger.NamedPackagesUpdateChecker; import jetbrains.buildServer.nuget.server.trigger.PackagesHashCalculator; import jetbrains.buildServer.nuget.server.trigger.TriggerConstants; import jetbrains.buildServer.nuget.server.trigger.impl.*; import jetbrains.buildServer.nuget.server.util.SystemInfo; import jetbrains.buildServer.serverSide.CustomDataStorage; import jetbrains.buildServer.util.TestFor; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jmock.Mockery; import org.jmock.api.Invocation; import org.jmock.lib.action.CustomAction; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.File; import java.util.Arrays; import java.util.Collections; import java.util.Map; import java.util.TreeMap; /** * Created by Eugene Petrenko ([email protected]) * Date: 14.07.11 18:57 */ public class NamedPackagesUpdateCheckerTest extends BaseTestCase { private Mockery m; private NamedPackagesUpdateChecker checker; private BuildTriggerDescriptor desr; private CustomDataStorage store; private NuGetToolManager manager; private PackageChangesManager chk; private Map<String, String> params; private File nugetFakePath; private RootUrlHolder myRootUrlHolder; private boolean myIsWindows; @BeforeMethod @Override protected void setUp() throws Exception { super.setUp(); myIsWindows = true; m = new Mockery(); desr = m.mock(BuildTriggerDescriptor.class); store = m.mock(CustomDataStorage.class); params = new TreeMap<String, String>(); manager = m.mock(NuGetToolManager.class); chk = m.mock(PackageChangesManager.class); myRootUrlHolder = m.mock(RootUrlHolder.class); final SystemInfo si = m.mock(SystemInfo.class); checker = new NamedPackagesUpdateChecker(chk, new TriggerRequestFactory(new CheckRequestModeFactory(si), manager, new PackageCheckRequestFactory(new PackageCheckerSettingsImpl()), myRootUrlHolder), new PackagesHashCalculator()); nugetFakePath = createTempFile(); final String path = nugetFakePath.getPath(); m.checking(new Expectations(){{ allowing(desr).getProperties(); will(returnValue(params)); allowing(manager).getNuGetPath(path); will(returnValue(path)); allowing(si).canStartNuGetProcesses(); will(new CustomAction("Return myIsWindows") { public Object invoke(Invocation invocation) throws Throwable { return myIsWindows; } }); }}); params.put(TriggerConstants.NUGET_EXE, path); params.put(TriggerConstants.PACKAGE, "NUnit"); } @Test public void test_resolves_own_feed_url() { params.put(TriggerConstants.SOURCE, "%"+ AgentRuntimeProperties.TEAMCITY_SERVER_URL+"%/a/b/c"); m.checking(new Expectations(){{ allowing(myRootUrlHolder).getRootUrl(); will(returnValue("http://some-teamcity-with-nuget.org/jonnyzzz")); oneOf(chk).checkPackage(with(req(nugetFakePath, "http://some-teamcity-with-nuget.org/jonnyzzz/a/b/c", "NUnit", null))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo("src", "pkg", "5.6.87"))))); oneOf(store).getValue("hash"); will(returnValue(null)); oneOf(store).putValue(with(equal("hash")), with(any(String.class))); oneOf(store).flush(); }}); Assert.assertNull(checker.checkChanges(desr, store)); m.assertIsSatisfied(); } @Test public void test_check_first_time_should_not_trigger() { m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo("src", "pkg", "5.6.87"))))); oneOf(store).getValue("hash"); will(returnValue(null)); oneOf(store).putValue(with(equal("hash")), with(any(String.class))); oneOf(store).flush(); }}); Assert.assertNull(checker.checkChanges(desr, store)); m.assertIsSatisfied(); } @Test public void test_check_first_time_should_not_trigger_linux() { myIsWindows = false; m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(reqTC(null, "NUnit"))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo("src", "pkg", "5.6.87"))))); oneOf(store).getValue("hash"); will(returnValue(null)); oneOf(store).putValue(with(equal("hash")), with(any(String.class))); oneOf(store).flush(); }}); Assert.assertNull(checker.checkChanges(desr, store)); m.assertIsSatisfied(); } @Test public void test_should_trigger_on_new_package() { final String source = "\\\\ServerNameRemoved\\NugetTest\\Repository"; params.put(TriggerConstants.PACKAGE, "Common"); params.put(TriggerConstants.SOURCE, source); m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(req(nugetFakePath, source, "Common", null))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo(source, "Common", "1.0.0.21"))))); oneOf(chk).checkPackage(with(req(nugetFakePath, source, "Common", null))); will(returnValue(CheckResult.fromResult(Arrays.asList( new SourcePackageInfo(source, "Common", "1.0.0.21"), new SourcePackageInfo(source, "Common", "2.0.0.22") )))); final String hash1 = "v2|s:\\\\ServerNameRemoved\\NugetTest\\Repository|p:Common|v:1.0.0.21"; final String hash2 = "v2|s:\\\\ServerNameRemoved\\NugetTest\\Repository|p:Common|v:1.0.0.21|s:\\\\ServerNameRemoved\\NugetTest\\Repository|p:Common|v:2.0.0.22"; oneOf(store).getValue("hash"); will(returnValue(null)); oneOf(store).putValue("hash", hash1); oneOf(store).flush(); oneOf(store).getValue("hash"); will(returnValue(hash1)); oneOf(store).putValue("hash", hash2); oneOf(store).flush(); }}); Assert.assertNull(checker.checkChanges(desr, store)); Assert.assertNotNull(checker.checkChanges(desr, store)); m.assertIsSatisfied(); } @Test public void test_should_trigger_on_new_package2() { final String source = "\\\\ServerNameRemoved\\NugetTest\\Repository"; params.put(TriggerConstants.PACKAGE, "Common"); params.put(TriggerConstants.SOURCE, source); m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(req(nugetFakePath, source, "Common", null))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo(source, "Common", "1.0.0.21"))))); oneOf(chk).checkPackage(with(req(nugetFakePath, source, "Common", null))); will(returnValue(CheckResult.fromResult(Arrays.asList( new SourcePackageInfo(source, "Common", "1.0.0.21"), new SourcePackageInfo(source, "Common", "2.0.0.22") )))); final String hash1 = "v2|s:\\\\ServerNameRemoved\\NugetTest\\Repository|p:Common|v:1.0.0.21"; final String hash2 = "v2|s:\\\\ServerNameRemoved\\NugetTest\\Repository|p:Common|v:1.0.0.21|s:\\\\ServerNameRemoved\\NugetTest\\Repository|p:Common|v:2.0.0.22"; oneOf(store).getValue("hash"); will(returnValue(hash1)); oneOf(store).getValue("hash"); will(returnValue(hash1)); oneOf(store).putValue("hash", hash2); oneOf(store).flush(); }}); Assert.assertNull(checker.checkChanges(desr, store)); Assert.assertNotNull(checker.checkChanges(desr, store)); m.assertIsSatisfied(); } @Test public void test_should_sort_packages() { final String source = "\\\\ServerNameRemoved\\NugetTest\\Repository"; params.put(TriggerConstants.PACKAGE, "Common"); params.put(TriggerConstants.SOURCE, source); m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(req(nugetFakePath, source, "Common", null))); will(returnValue(CheckResult.fromResult(Arrays.asList( new SourcePackageInfo(source, "Common", "1.0.0.21"), new SourcePackageInfo(null, "Common", "2.0.0.22"), new SourcePackageInfo("s2", "C3ommon", "2.0.0.22"), new SourcePackageInfo(null, "C3ommon", "2.0.0.22"), new SourcePackageInfo(null, "C3o4mmon", "2.0.0.22"), new SourcePackageInfo("s4", "C3o3mmon", "2.0.0.22"), new SourcePackageInfo(null, "C3omm5on", "2.0.0.22") )))); final String hash1 = "v2|s:\\\\ServerNameRemoved\\NugetTest\\Repository|p:Common|v:1.0.0.21|s:s2|p:C3ommon|v:2.0.0.22|s:s4|p:C3o3mmon|v:2.0.0.22|p:C3o4mmon|v:2.0.0.22|p:C3omm5on|v:2.0.0.22|p:C3ommon|v:2.0.0.22|p:Common|v:2.0.0.22"; oneOf(store).getValue("hash"); will(returnValue("v2foo")); oneOf(store).putValue("hash", hash1); oneOf(store).flush(); }}); Assert.assertNotNull(checker.checkChanges(desr, store)); m.assertIsSatisfied(); } @Test public void test_check_should_not_trigger_twice() { m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo("src", "pkg", "5.6.87"))))); oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo("src", "pkg", "5.6.87"))))); oneOf(store).getValue("hash"); will(returnValue("v2aaa")); oneOf(store).putValue("hash", "v2|s:src|p:pkg|v:5.6.87"); oneOf(store).getValue("hash"); will(returnValue("v2|s:src|p:pkg|v:5.6.87")); oneOf(store).flush(); }}); Assert.assertNotNull(checker.checkChanges(desr, store)); Assert.assertNull(checker.checkChanges(desr, store)); m.assertIsSatisfied(); } @Test @TestFor(issues = "TW-24575") public void test_should_throw_error_if_no_packages_found() { m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); will(returnValue(CheckResult.fromResult(Collections.<SourcePackageInfo>emptyList()))); oneOf(store).getValue("hash"); will(returnValue("v2aaa")); oneOf(store).putValue("hash", "v2"); oneOf(store).flush(); }}); try { checker.checkChanges(desr, store); Assert.fail("Exception is expected"); } catch (BuildTriggerException e) { Assert.assertTrue(e.getMessage().contains("Package NUnit was not found in the feed")); } m.assertIsSatisfied(); } @Test @TestFor(issues = "TW-24575") public void test_should_trigger_zero_to_one() { m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo("src", "pkg", "5.6.87"))))); oneOf(store).getValue("hash"); will(returnValue("v2")); oneOf(store).putValue("hash", "v2|s:src|p:pkg|v:5.6.87"); oneOf(store).flush(); }}); Assert.assertNotNull(checker.checkChanges(desr, store)); m.assertIsSatisfied(); } @Test @TestFor(issues = "TW-24575") public void test_should_trigger_none_to_one() { m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); will(returnValue(CheckResult.fromResult(Collections.<SourcePackageInfo>emptyList()))); oneOf(store).getValue("hash"); will(returnValue(null)); oneOf(store).putValue("hash", "v2"); oneOf(store).flush(); }}); try { checker.checkChanges(desr, store); Assert.fail("Exception is expected"); } catch (BuildTriggerException e) { Assert.assertTrue(e.getMessage().contains("Package NUnit was not found in the feed")); } m.assertIsSatisfied(); m.checking(new Expectations() {{ oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo("src", "pkg", "5.6.87"))))); oneOf(store).getValue("hash"); will(returnValue("v2")); oneOf(store).putValue("hash", "v2|s:src|p:pkg|v:5.6.87"); oneOf(store).flush(); }}); Assert.assertNotNull(checker.checkChanges(desr, store)); m.assertIsSatisfied(); } @Test @TestFor(issues = "TW-24575") public void test_should_throw_error_if_check_result() { m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); will(returnValue(CheckResult.failed("something5555"))); }}); try { checker.checkChanges(desr, store); Assert.fail("Exception is expected"); } catch (BuildTriggerException e) { Assert.assertTrue(e.getMessage().contains("something5555")); } m.assertIsSatisfied(); } @Test public void test_check_should_not_trigger_from_older_hash() { m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo("src", "pkg", "5.6.87"))))); oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo("src", "pkg", "5.6.87"))))); oneOf(store).getValue("hash"); will(returnValue("aaa")); oneOf(store).putValue("hash", "v2|s:src|p:pkg|v:5.6.87"); oneOf(store).getValue("hash"); will(returnValue("v2|s:src|p:pkg|v:5.6.87")); oneOf(store).flush(); }}); Assert.assertNull(checker.checkChanges(desr, store)); Assert.assertNull(checker.checkChanges(desr, store)); m.assertIsSatisfied(); } @Test public void test_check_should_not_trigger_twice_linux() { myIsWindows = false; m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(reqTC(null, "NUnit"))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo("src", "pkg", "5.6.87"))))); oneOf(chk).checkPackage(with(reqTC(null, "NUnit"))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo("src", "pkg", "5.6.87"))))); oneOf(store).getValue("hash"); will(returnValue("v2aaa")); oneOf(store).putValue("hash", "v2|s:src|p:pkg|v:5.6.87"); oneOf(store).getValue("hash"); will(returnValue("v2|s:src|p:pkg|v:5.6.87")); oneOf(store).flush(); }}); Assert.assertNotNull(checker.checkChanges(desr, store)); Assert.assertNull(checker.checkChanges(desr, store)); m.assertIsSatisfied(); } @Test public void test_check_should_not_trigger_after_error() { m.checking(new Expectations(){{ oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo("src", "pkg", "5.6.87"))))); oneOf(chk).checkPackage(with(req(nugetFakePath))); will(throwException(new RuntimeException("Failed to execute command"))); oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); will(returnValue(CheckResult.fromResult(Arrays.asList(new SourcePackageInfo("src", "pkg", "5.6.87"))))); oneOf(store).getValue("hash"); will(returnValue("v2aaa")); oneOf(store).putValue("hash", "v2|s:src|p:pkg|v:5.6.87"); oneOf(store).getValue("hash"); will(returnValue("v2|s:src|p:pkg|v:5.6.87")); oneOf(store).flush(); }}); Assert.assertNotNull(checker.checkChanges(desr, store)); try { checker.checkChanges(desr, store); Assert.fail("should throw an exception"); } catch (BuildTriggerException e) { //NOP } Assert.assertNull(checker.checkChanges(desr, store)); m.assertIsSatisfied(); } @Test public void test_check_should_fail_on_error() { m.checking(new Expectations() {{ oneOf(chk).checkPackage(with(req(nugetFakePath))); will(throwException(new RuntimeException("Failed to execute command"))); }}); try { checker.checkChanges(desr, store); Assert.fail("should throw an exception"); } catch (BuildTriggerException e) { //NOP } m.assertIsSatisfied(); } @Test public void test_check_should_fail_on_error2() { m.checking(new Expectations() {{ oneOf(chk).checkPackage(with(req(nugetFakePath))); will(returnValue(CheckResult.failed("Failed to execute command"))); }}); try { checker.checkChanges(desr, store); Assert.fail("should throw an exception"); } catch (BuildTriggerException e) { //NOP } m.assertIsSatisfied(); } private static class Expectations extends org.jmock.Expectations { public Matcher<PackageCheckRequest> req(@NotNull final File nugetPath, @Nullable final String source, @NotNull final String id, @Nullable final String version) { return new BaseMatcher<PackageCheckRequest>() { private boolean equals(Object a, Object b) { if (a == null && b == null) return true; return a != null && a.equals(b); } public boolean matches(Object o) { if (!(o instanceof PackageCheckRequest)) return false; PackageCheckRequest r = (PackageCheckRequest) o; final SourcePackageReference pkg = r.getPackage(); if (!pkg.getPackageId().equals(id)) return false; if (!equals(pkg.getSource(), source)) return false; if (!equals(pkg.getVersionSpec(), version)) return false; final CheckRequestMode mode = r.getMode(); if (!(mode instanceof CheckRequestModeNuGet)) return false; if (!((CheckRequestModeNuGet) mode).getNuGetPath().equals(nugetPath)) return false; return true; } public void describeTo(Description description) { description.appendText("Package: ").appendValue(id).appendText("Source: ").appendValue(source); } }; } public Matcher<PackageCheckRequest> reqTC(@Nullable final String source, @NotNull final String id) { return new BaseMatcher<PackageCheckRequest>() { private boolean equals(Object a, Object b) { if (a == null && b == null) return true; return a != null && a.equals(b); } public boolean matches(Object o) { if (!(o instanceof PackageCheckRequest)) return false; PackageCheckRequest r = (PackageCheckRequest) o; final SourcePackageReference pkg = r.getPackage(); if (!pkg.getPackageId().equals(id)) return false; if (!equals(pkg.getSource(), source)) return false; final CheckRequestMode mode = r.getMode(); return mode instanceof CheckRequestModeTeamCity; } public void describeTo(Description description) { description.appendText("Package: ").appendValue(id).appendText("Source: ").appendValue(source); } }; } public Matcher<PackageCheckRequest> req(@NotNull final File nugetPath) { return new BaseMatcher<PackageCheckRequest>() { public boolean matches(Object o) { if (!(o instanceof PackageCheckRequest)) return false; PackageCheckRequest r = (PackageCheckRequest) o; final CheckRequestMode mode = r.getMode(); if (!(mode instanceof CheckRequestModeNuGet)) return false; if (!((CheckRequestModeNuGet) mode).getNuGetPath().equals(nugetPath)) return false; return true; } public void describeTo(Description description) { description.appendText("NuGet check path ").appendValue(nugetPath); } }; } } }
Add breaking tests for the cache update issue - TW-27263
nuget-tests/src/jetbrains/buildServer/nuget/tests/server/NamedPackagesUpdateCheckerTest.java
Add breaking tests for the cache update issue - TW-27263
<ide><path>uget-tests/src/jetbrains/buildServer/nuget/tests/server/NamedPackagesUpdateCheckerTest.java <ide> <ide> @Test <ide> @TestFor(issues = "TW-24575") <del> public void test_should_throw_error_if_no_packages_found() { <add> public void test_should_throw_error_if_no_packages_found_but_not_update_hash() { <ide> m.checking(new Expectations(){{ <ide> oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); <ide> will(returnValue(CheckResult.fromResult(Collections.<SourcePackageInfo>emptyList()))); <ide> <ide> <del> oneOf(store).getValue("hash"); will(returnValue("v2aaa")); <add> oneOf(store).getValue("hash"); will(returnValue("v2|s:src|p:pkg|v:5.6.87")); <add> never(store).putValue("hash", "v2"); <add> never(store).flush(); <add> }}); <add> <add> try { <add> checker.checkChanges(desr, store); <add> Assert.fail("Exception is expected"); <add> } catch (BuildTriggerException e) { <add> Assert.assertTrue(e.getMessage().contains("Package NUnit was not found in the feed")); <add> } <add> <add> m.assertIsSatisfied(); <add> } <add> <add> @Test <add> @TestFor(issues = "TW-27263") <add> public void test_should_not_update_cache_if_no_packages_found_and_cache_already_valid() { <add> m.checking(new Expectations(){{ <add> oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); <add> will(returnValue(CheckResult.fromResult(Collections.<SourcePackageInfo>emptyList()))); <add> <add> <add> oneOf(store).getValue("hash"); will(returnValue("v2|s:src|p:pkg|v:5.6.87")); <add> never(store).putValue("hash", "v2"); <add> never(store).flush(); <add> }}); <add> <add> try { <add> checker.checkChanges(desr, store); <add> Assert.fail("Exception is expected"); <add> } catch (BuildTriggerException e) { <add> Assert.assertTrue(e.getMessage().contains("Package NUnit was not found in the feed")); <add> } <add> <add> m.assertIsSatisfied(); <add> } <add> <add> @Test <add> @TestFor(issues = "TW-27263") <add> public void test_should_update_cache_if_no_packages_found_and_cache_empty() { <add> m.checking(new Expectations(){{ <add> oneOf(chk).checkPackage(with(req(nugetFakePath, null, "NUnit", null))); <add> will(returnValue(CheckResult.fromResult(Collections.<SourcePackageInfo>emptyList()))); <add> <add> <add> oneOf(store).getValue("hash"); will(returnValue(null)); <ide> oneOf(store).putValue("hash", "v2"); <ide> oneOf(store).flush(); <ide> }});
Java
mit
error: pathspec 'Java/Array/SumContinuesNumber.java' did not match any file(s) known to git
4228771ec4d59b3620ab7a30b93abec5369a064a
1
maniero/SOpt,bigown/SOpt,bigown/SOpt,maniero/SOpt,maniero/SOpt,bigown/SOpt,bigown/SOpt,bigown/SOpt,maniero/SOpt,maniero/SOpt,maniero/SOpt,bigown/SOpt,bigown/SOpt,bigown/SOpt,maniero/SOpt,maniero/SOpt,bigown/SOpt,maniero/SOpt,maniero/SOpt,maniero/SOpt,maniero/SOpt,maniero/SOpt,bigown/SOpt,maniero/SOpt,maniero/SOpt,maniero/SOpt
import java.util.*; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); ArrayList<Integer> lista = new ArrayList<>(); int soma = 0; int menor = 999; int maior = 0; System.out.println("Digite 0 para terminar"); for (;;) { System.out.println("Digite um número: "); int num = s.nextInt(); if (num == 0) break; lista.add(num); soma += num; maior = Math.max(maior, num); menor = Math.min( menor, num); } for (Integer integer : lista) System.out.println(integer); System.out.println("A média de idade é " + (soma / lista.size())); System.out.println("A maior idade é " + maior); System.out.println("A menor idade é " + menor); } } //https://pt.stackoverflow.com/q/46136/101
Java/Array/SumContinuesNumber.java
https://pt.stackoverflow.com/q/46136/101
Java/Array/SumContinuesNumber.java
https://pt.stackoverflow.com/q/46136/101
<ide><path>ava/Array/SumContinuesNumber.java <add>import java.util.*; <add> <add>public class Main { <add> public static void main(String[] args) { <add> Scanner s = new Scanner(System.in); <add> ArrayList<Integer> lista = new ArrayList<>(); <add> int soma = 0; <add> int menor = 999; <add> int maior = 0; <add> System.out.println("Digite 0 para terminar"); <add> for (;;) { <add> System.out.println("Digite um número: "); <add> int num = s.nextInt(); <add> if (num == 0) break; <add> lista.add(num); <add> soma += num; <add> maior = Math.max(maior, num); <add> menor = Math.min( menor, num); <add> } <add> for (Integer integer : lista) System.out.println(integer); <add> System.out.println("A média de idade é " + (soma / lista.size())); <add> System.out.println("A maior idade é " + maior); <add> System.out.println("A menor idade é " + menor); <add> } <add>} <add> <add>//https://pt.stackoverflow.com/q/46136/101
JavaScript
mit
9663cfde82f68039a10a758fb2755152fbc2cb23
0
abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,aaronpowell/Umbraco-CMS,abryukhov/Umbraco-CMS,WebCentrum/Umbraco-CMS,lars-erik/Umbraco-CMS,leekelleher/Umbraco-CMS,dawoe/Umbraco-CMS,aaronpowell/Umbraco-CMS,madsoulswe/Umbraco-CMS,marcemarc/Umbraco-CMS,NikRimington/Umbraco-CMS,dawoe/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,abryukhov/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,rasmuseeg/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,WebCentrum/Umbraco-CMS,lars-erik/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,leekelleher/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,leekelleher/Umbraco-CMS,arknu/Umbraco-CMS,bjarnef/Umbraco-CMS,mattbrailsford/Umbraco-CMS,rasmuseeg/Umbraco-CMS,mattbrailsford/Umbraco-CMS,leekelleher/Umbraco-CMS,tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,madsoulswe/Umbraco-CMS,tcmorris/Umbraco-CMS,umbraco/Umbraco-CMS,lars-erik/Umbraco-CMS,KevinJump/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,hfloyd/Umbraco-CMS,umbraco/Umbraco-CMS,WebCentrum/Umbraco-CMS,aaronpowell/Umbraco-CMS,abjerner/Umbraco-CMS,arknu/Umbraco-CMS,lars-erik/Umbraco-CMS,mattbrailsford/Umbraco-CMS,mattbrailsford/Umbraco-CMS,leekelleher/Umbraco-CMS,tompipe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,lars-erik/Umbraco-CMS,KevinJump/Umbraco-CMS,bjarnef/Umbraco-CMS,marcemarc/Umbraco-CMS,madsoulswe/Umbraco-CMS,tompipe/Umbraco-CMS,tcmorris/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,bjarnef/Umbraco-CMS,tompipe/Umbraco-CMS,NikRimington/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,bjarnef/Umbraco-CMS,rasmuseeg/Umbraco-CMS,hfloyd/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,umbraco/Umbraco-CMS,NikRimington/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,hfloyd/Umbraco-CMS
/** * @ngdoc service * @name umbraco.resources.entityResource * @description Loads in basic data for all entities * * ##What is an entity? * An entity is a basic **read-only** representation of an Umbraco node. It contains only the most * basic properties used to display the item in trees, lists and navigation. * * ##What is the difference between entity and content/media/etc...? * the entity only contains the basic node data, name, id and guid, whereas content * nodes fetched through the content service also contains additional all of the content property data, etc.. * This is the same principal for all entity types. Any user that is logged in to the back office will have access * to view the basic entity information for all entities since the basic entity information does not contain sensitive information. * * ##Entity object types? * You need to specify the type of object you want returned. * * The core object types are: * * - Document * - Media * - Member * - Template * - DocumentType * - MediaType * - MemberType * - Macro * - User * - Language * - Domain * - DataType **/ function entityResource($q, $http, umbRequestHelper) { //the factory object returned return { getSafeAlias: function (value, camelCase) { if (!value) { return ""; } value = value.replace("#", ""); return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "GetSafeAlias", { value: encodeURIComponent(value), camelCase: camelCase })), 'Failed to retrieve content type scaffold'); }, /** * @ngdoc method * @name umbraco.resources.entityResource#getPath * @methodOf umbraco.resources.entityResource * * @description * Returns a path, given a node ID and type * * ##usage * <pre> * entityResource.getPath(id, type) * .then(function(pathArray) { * alert('its here!'); * }); * </pre> * * @param {Int} id Id of node to return the public url to * @param {string} type Object type name * @returns {Promise} resourcePromise object containing the url. * */ getPath: function (id, type) { if (id === -1 || id === "-1") { return "-1"; } return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "GetPath", [{ id: id }, {type: type }])), 'Failed to retrieve path for id:' + id); }, /** * @ngdoc method * @name umbraco.resources.entityResource#getUrl * @methodOf umbraco.resources.entityResource * * @description * Returns a url, given a node ID and type * * ##usage * <pre> * entityResource.getUrl(id, type) * .then(function(url) { * alert('its here!'); * }); * </pre> * * @param {Int} id Id of node to return the public url to * @param {string} type Object type name * @returns {Promise} resourcePromise object containing the url. * */ getUrl: function (id, type) { if (id === -1 || id === "-1") { return ""; } return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "GetUrl", [{ id: id }, {type: type }])), 'Failed to retrieve url for id:' + id); }, /** * @ngdoc method * @name umbraco.resources.entityResource#getById * @methodOf umbraco.resources.entityResource * * @description * Gets an entity with a given id * * ##usage * <pre> * //get media by id * entityResource.getEntityById(0, "Media") * .then(function(ent) { * var myDoc = ent; * alert('its here!'); * }); * </pre> * * @param {Int} id id of entity to return * @param {string} type Object type name * @returns {Promise} resourcePromise object containing the entity. * */ getById: function (id, type) { if (id === -1 || id === "-1") { return null; } return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "GetById", [{ id: id }, { type: type }])), 'Failed to retrieve entity data for id ' + id); }, /** * @ngdoc method * @name umbraco.resources.entityResource#getByIds * @methodOf umbraco.resources.entityResource * * @description * Gets an array of entities, given a collection of ids * * ##usage * <pre> * //Get templates for ids * entityResource.getEntitiesByIds( [1234,2526,28262], "Template") * .then(function(templateArray) { * var myDoc = contentArray; * alert('they are here!'); * }); * </pre> * * @param {Array} ids ids of entities to return as an array * @param {string} type type name * @returns {Promise} resourcePromise object containing the entity array. * */ getByIds: function (ids, type) { var query = "type=" + type; return umbRequestHelper.resourcePromise( $http.post( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "GetByIds", query), { ids: ids }), 'Failed to retrieve entity data for ids ' + ids); }, /** * @ngdoc method * @name umbraco.resources.entityResource#getByQuery * @methodOf umbraco.resources.entityResource * * @description * Gets an entity from a given xpath * * ##usage * <pre> * //get content by xpath * entityResource.getByQuery("$current", -1, "Document") * .then(function(ent) { * var myDoc = ent; * alert('its here!'); * }); * </pre> * * @param {string} query xpath to use in query * @param {Int} nodeContextId id id to start from * @param {string} type Object type name * @returns {Promise} resourcePromise object containing the entity. * */ getByQuery: function (query, nodeContextId, type) { return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "GetByQuery", [{ query: query }, { nodeContextId: nodeContextId }, { type: type }])), 'Failed to retrieve entity data for query ' + query); }, /** * @ngdoc method * @name umbraco.resources.entityResource#getAll * @methodOf umbraco.resources.entityResource * * @description * Gets an entity with a given id * * ##usage * <pre> * * //Only return media * entityResource.getAll("Media") * .then(function(ent) { * var myDoc = ent; * alert('its here!'); * }); * </pre> * * @param {string} type Object type name * @param {string} postFilter optional filter expression which will execute a dynamic where clause on the server * @param {string} postFilterParams optional parameters for the postFilter expression * @returns {Promise} resourcePromise object containing the entity. * */ getAll: function (type, postFilter, postFilterParams) { //need to build the query string manually var query = "type=" + type + "&postFilter=" + (postFilter ? postFilter : ""); if (postFilter && postFilterParams) { var counter = 0; _.each(postFilterParams, function(val, key) { query += "&postFilterParams[" + counter + "].key=" + key + "&postFilterParams[" + counter + "].value=" + val; counter++; }); } return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "GetAll", query)), 'Failed to retrieve entity data for type ' + type); }, /** * @ngdoc method * @name umbraco.resources.entityResource#getAncestors * @methodOf umbraco.resources.entityResource * * @description * Gets ancestor entities for a given item * * * @param {string} type Object type name * @returns {Promise} resourcePromise object containing the entity. * */ getAncestors: function (id, type) { return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "GetAncestors", [{id: id}, {type: type}])), 'Failed to retrieve ancestor data for id ' + id); }, /** * @ngdoc method * @name umbraco.resources.entityResource#getChildren * @methodOf umbraco.resources.entityResource * * @description * Gets children entities for a given item * * @param {Int} parentid id of content item to return children of * @param {string} type Object type name * @returns {Promise} resourcePromise object containing the entity. * */ getChildren: function (id, type) { return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "GetChildren", [{ id: id }, { type: type }])), 'Failed to retrieve child data for id ' + id); }, /** * @ngdoc method * @name umbraco.resources.entityResource#getPagedChildren * @methodOf umbraco.resources.entityResource * * @description * Gets paged children of a content item with a given id * * ##usage * <pre> * entityResource.getPagedChildren(1234, "Content", {pageSize: 10, pageNumber: 2}) * .then(function(contentArray) { * var children = contentArray; * alert('they are here!'); * }); * </pre> * * @param {Int} parentid id of content item to return children of * @param {string} type Object type name * @param {Object} options optional options object * @param {Int} options.pageSize if paging data, number of nodes per page, default = 1 * @param {Int} options.pageNumber if paging data, current page index, default = 100 * @param {String} options.filter if provided, query will only return those with names matching the filter * @param {String} options.orderDirection can be `Ascending` or `Descending` - Default: `Ascending` * @param {String} options.orderBy property to order items by, default: `SortOrder` * @returns {Promise} resourcePromise object containing an array of content items. * */ getPagedChildren: function (parentId, type, options) { var defaults = { pageSize: 1, pageNumber: 100, filter: '', orderDirection: "Ascending", orderBy: "SortOrder" }; if (options === undefined) { options = {}; } //overwrite the defaults if there are any specified angular.extend(defaults, options); //now copy back to the options we will use options = defaults; //change asc/desct if (options.orderDirection === "asc") { options.orderDirection = "Ascending"; } else if (options.orderDirection === "desc") { options.orderDirection = "Descending"; } return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "GetPagedChildren", { id: parentId, type: type, pageNumber: options.pageNumber, pageSize: options.pageSize, orderBy: options.orderBy, orderDirection: options.orderDirection, filter: encodeURIComponent(options.filter) } )), 'Failed to retrieve child data for id ' + parentId); }, /** * @ngdoc method * @name umbraco.resources.entityResource#getPagedDescendants * @methodOf umbraco.resources.entityResource * * @description * Gets paged descendants of a content item with a given id * * ##usage * <pre> * entityResource.getPagedDescendants(1234, "Document", {pageSize: 10, pageNumber: 2}) * .then(function(contentArray) { * var children = contentArray; * alert('they are here!'); * }); * </pre> * * @param {Int} parentid id of content item to return descendants of * @param {string} type Object type name * @param {Object} options optional options object * @param {Int} options.pageSize if paging data, number of nodes per page, default = 100 * @param {Int} options.pageNumber if paging data, current page index, default = 1 * @param {String} options.filter if provided, query will only return those with names matching the filter * @param {String} options.orderDirection can be `Ascending` or `Descending` - Default: `Ascending` * @param {String} options.orderBy property to order items by, default: `SortOrder` * @returns {Promise} resourcePromise object containing an array of content items. * */ getPagedDescendants: function (parentId, type, options) { var defaults = { pageSize: 100, pageNumber: 1, filter: '', orderDirection: "Ascending", orderBy: "SortOrder" }; if (options === undefined) { options = {}; } //overwrite the defaults if there are any specified angular.extend(defaults, options); //now copy back to the options we will use options = defaults; //change asc/desct if (options.orderDirection === "asc") { options.orderDirection = "Ascending"; } else if (options.orderDirection === "desc") { options.orderDirection = "Descending"; } return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "GetPagedDescendants", { id: parentId, type: type, pageNumber: options.pageNumber, pageSize: options.pageSize, orderBy: options.orderBy, orderDirection: options.orderDirection, filter: encodeURIComponent(options.filter) } )), 'Failed to retrieve child data for id ' + parentId); }, /** * @ngdoc method * @name umbraco.resources.entityResource#search * @methodOf umbraco.resources.entityResource * * @description * Gets an array of entities, given a lucene query and a type * * ##usage * <pre> * entityResource.search("news", "Media") * .then(function(mediaArray) { * var myDoc = mediaArray; * alert('they are here!'); * }); * </pre> * * @param {String} Query search query * @param {String} Type type of conten to search * @returns {Promise} resourcePromise object containing the entity array. * */ search: function (query, type, searchFrom, canceler) { var args = [{ query: query }, { type: type }]; if (searchFrom) { args.push({ searchFrom: searchFrom }); } var httpConfig = {}; if (canceler) { httpConfig["timeout"] = canceler; } return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "Search", args), httpConfig), 'Failed to retrieve entity data for query ' + query); }, /** * @ngdoc method * @name umbraco.resources.entityResource#searchAll * @methodOf umbraco.resources.entityResource * * @description * Gets an array of entities from all available search indexes, given a lucene query * * ##usage * <pre> * entityResource.searchAll("bob") * .then(function(array) { * var myDoc = array; * alert('they are here!'); * }); * </pre> * * @param {String} Query search query * @returns {Promise} resourcePromise object containing the entity array. * */ searchAll: function (query, canceler) { var httpConfig = {}; if (canceler) { httpConfig["timeout"] = canceler; } return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "SearchAll", [{ query: query }]), httpConfig), 'Failed to retrieve entity data for query ' + query); } }; } angular.module('umbraco.resources').factory('entityResource', entityResource);
src/Umbraco.Web.UI.Client/src/common/resources/entity.resource.js
/** * @ngdoc service * @name umbraco.resources.entityResource * @description Loads in basic data for all entities * * ##What is an entity? * An entity is a basic **read-only** representation of an Umbraco node. It contains only the most * basic properties used to display the item in trees, lists and navigation. * * ##What is the difference between entity and content/media/etc...? * the entity only contains the basic node data, name, id and guid, whereas content * nodes fetched through the content service also contains additional all of the content property data, etc.. * This is the same principal for all entity types. Any user that is logged in to the back office will have access * to view the basic entity information for all entities since the basic entity information does not contain sensitive information. * * ##Entity object types? * You need to specify the type of object you want returned. * * The core object types are: * * - Document * - Media * - Member * - Template * - DocumentType * - MediaType * - MemberType * - Macro * - User * - Language * - Domain * - DataType **/ function entityResource($q, $http, umbRequestHelper) { //the factory object returned return { getSafeAlias: function (value, camelCase) { if (!value) { return ""; } value = value.replace("#", ""); return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "GetSafeAlias", { value: value, camelCase: camelCase })), 'Failed to retrieve content type scaffold'); }, /** * @ngdoc method * @name umbraco.resources.entityResource#getPath * @methodOf umbraco.resources.entityResource * * @description * Returns a path, given a node ID and type * * ##usage * <pre> * entityResource.getPath(id, type) * .then(function(pathArray) { * alert('its here!'); * }); * </pre> * * @param {Int} id Id of node to return the public url to * @param {string} type Object type name * @returns {Promise} resourcePromise object containing the url. * */ getPath: function (id, type) { if (id === -1 || id === "-1") { return "-1"; } return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "GetPath", [{ id: id }, {type: type }])), 'Failed to retrieve path for id:' + id); }, /** * @ngdoc method * @name umbraco.resources.entityResource#getUrl * @methodOf umbraco.resources.entityResource * * @description * Returns a url, given a node ID and type * * ##usage * <pre> * entityResource.getUrl(id, type) * .then(function(url) { * alert('its here!'); * }); * </pre> * * @param {Int} id Id of node to return the public url to * @param {string} type Object type name * @returns {Promise} resourcePromise object containing the url. * */ getUrl: function (id, type) { if (id === -1 || id === "-1") { return ""; } return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "GetUrl", [{ id: id }, {type: type }])), 'Failed to retrieve url for id:' + id); }, /** * @ngdoc method * @name umbraco.resources.entityResource#getById * @methodOf umbraco.resources.entityResource * * @description * Gets an entity with a given id * * ##usage * <pre> * //get media by id * entityResource.getEntityById(0, "Media") * .then(function(ent) { * var myDoc = ent; * alert('its here!'); * }); * </pre> * * @param {Int} id id of entity to return * @param {string} type Object type name * @returns {Promise} resourcePromise object containing the entity. * */ getById: function (id, type) { if (id === -1 || id === "-1") { return null; } return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "GetById", [{ id: id }, { type: type }])), 'Failed to retrieve entity data for id ' + id); }, /** * @ngdoc method * @name umbraco.resources.entityResource#getByIds * @methodOf umbraco.resources.entityResource * * @description * Gets an array of entities, given a collection of ids * * ##usage * <pre> * //Get templates for ids * entityResource.getEntitiesByIds( [1234,2526,28262], "Template") * .then(function(templateArray) { * var myDoc = contentArray; * alert('they are here!'); * }); * </pre> * * @param {Array} ids ids of entities to return as an array * @param {string} type type name * @returns {Promise} resourcePromise object containing the entity array. * */ getByIds: function (ids, type) { var query = "type=" + type; return umbRequestHelper.resourcePromise( $http.post( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "GetByIds", query), { ids: ids }), 'Failed to retrieve entity data for ids ' + ids); }, /** * @ngdoc method * @name umbraco.resources.entityResource#getByQuery * @methodOf umbraco.resources.entityResource * * @description * Gets an entity from a given xpath * * ##usage * <pre> * //get content by xpath * entityResource.getByQuery("$current", -1, "Document") * .then(function(ent) { * var myDoc = ent; * alert('its here!'); * }); * </pre> * * @param {string} query xpath to use in query * @param {Int} nodeContextId id id to start from * @param {string} type Object type name * @returns {Promise} resourcePromise object containing the entity. * */ getByQuery: function (query, nodeContextId, type) { return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "GetByQuery", [{ query: query }, { nodeContextId: nodeContextId }, { type: type }])), 'Failed to retrieve entity data for query ' + query); }, /** * @ngdoc method * @name umbraco.resources.entityResource#getAll * @methodOf umbraco.resources.entityResource * * @description * Gets an entity with a given id * * ##usage * <pre> * * //Only return media * entityResource.getAll("Media") * .then(function(ent) { * var myDoc = ent; * alert('its here!'); * }); * </pre> * * @param {string} type Object type name * @param {string} postFilter optional filter expression which will execute a dynamic where clause on the server * @param {string} postFilterParams optional parameters for the postFilter expression * @returns {Promise} resourcePromise object containing the entity. * */ getAll: function (type, postFilter, postFilterParams) { //need to build the query string manually var query = "type=" + type + "&postFilter=" + (postFilter ? postFilter : ""); if (postFilter && postFilterParams) { var counter = 0; _.each(postFilterParams, function(val, key) { query += "&postFilterParams[" + counter + "].key=" + key + "&postFilterParams[" + counter + "].value=" + val; counter++; }); } return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "GetAll", query)), 'Failed to retrieve entity data for type ' + type); }, /** * @ngdoc method * @name umbraco.resources.entityResource#getAncestors * @methodOf umbraco.resources.entityResource * * @description * Gets ancestor entities for a given item * * * @param {string} type Object type name * @returns {Promise} resourcePromise object containing the entity. * */ getAncestors: function (id, type) { return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "GetAncestors", [{id: id}, {type: type}])), 'Failed to retrieve ancestor data for id ' + id); }, /** * @ngdoc method * @name umbraco.resources.entityResource#getChildren * @methodOf umbraco.resources.entityResource * * @description * Gets children entities for a given item * * @param {Int} parentid id of content item to return children of * @param {string} type Object type name * @returns {Promise} resourcePromise object containing the entity. * */ getChildren: function (id, type) { return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "GetChildren", [{ id: id }, { type: type }])), 'Failed to retrieve child data for id ' + id); }, /** * @ngdoc method * @name umbraco.resources.entityResource#getPagedChildren * @methodOf umbraco.resources.entityResource * * @description * Gets paged children of a content item with a given id * * ##usage * <pre> * entityResource.getPagedChildren(1234, "Content", {pageSize: 10, pageNumber: 2}) * .then(function(contentArray) { * var children = contentArray; * alert('they are here!'); * }); * </pre> * * @param {Int} parentid id of content item to return children of * @param {string} type Object type name * @param {Object} options optional options object * @param {Int} options.pageSize if paging data, number of nodes per page, default = 1 * @param {Int} options.pageNumber if paging data, current page index, default = 100 * @param {String} options.filter if provided, query will only return those with names matching the filter * @param {String} options.orderDirection can be `Ascending` or `Descending` - Default: `Ascending` * @param {String} options.orderBy property to order items by, default: `SortOrder` * @returns {Promise} resourcePromise object containing an array of content items. * */ getPagedChildren: function (parentId, type, options) { var defaults = { pageSize: 1, pageNumber: 100, filter: '', orderDirection: "Ascending", orderBy: "SortOrder" }; if (options === undefined) { options = {}; } //overwrite the defaults if there are any specified angular.extend(defaults, options); //now copy back to the options we will use options = defaults; //change asc/desct if (options.orderDirection === "asc") { options.orderDirection = "Ascending"; } else if (options.orderDirection === "desc") { options.orderDirection = "Descending"; } return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "GetPagedChildren", { id: parentId, type: type, pageNumber: options.pageNumber, pageSize: options.pageSize, orderBy: options.orderBy, orderDirection: options.orderDirection, filter: encodeURIComponent(options.filter) } )), 'Failed to retrieve child data for id ' + parentId); }, /** * @ngdoc method * @name umbraco.resources.entityResource#getPagedDescendants * @methodOf umbraco.resources.entityResource * * @description * Gets paged descendants of a content item with a given id * * ##usage * <pre> * entityResource.getPagedDescendants(1234, "Document", {pageSize: 10, pageNumber: 2}) * .then(function(contentArray) { * var children = contentArray; * alert('they are here!'); * }); * </pre> * * @param {Int} parentid id of content item to return descendants of * @param {string} type Object type name * @param {Object} options optional options object * @param {Int} options.pageSize if paging data, number of nodes per page, default = 100 * @param {Int} options.pageNumber if paging data, current page index, default = 1 * @param {String} options.filter if provided, query will only return those with names matching the filter * @param {String} options.orderDirection can be `Ascending` or `Descending` - Default: `Ascending` * @param {String} options.orderBy property to order items by, default: `SortOrder` * @returns {Promise} resourcePromise object containing an array of content items. * */ getPagedDescendants: function (parentId, type, options) { var defaults = { pageSize: 100, pageNumber: 1, filter: '', orderDirection: "Ascending", orderBy: "SortOrder" }; if (options === undefined) { options = {}; } //overwrite the defaults if there are any specified angular.extend(defaults, options); //now copy back to the options we will use options = defaults; //change asc/desct if (options.orderDirection === "asc") { options.orderDirection = "Ascending"; } else if (options.orderDirection === "desc") { options.orderDirection = "Descending"; } return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "GetPagedDescendants", { id: parentId, type: type, pageNumber: options.pageNumber, pageSize: options.pageSize, orderBy: options.orderBy, orderDirection: options.orderDirection, filter: encodeURIComponent(options.filter) } )), 'Failed to retrieve child data for id ' + parentId); }, /** * @ngdoc method * @name umbraco.resources.entityResource#search * @methodOf umbraco.resources.entityResource * * @description * Gets an array of entities, given a lucene query and a type * * ##usage * <pre> * entityResource.search("news", "Media") * .then(function(mediaArray) { * var myDoc = mediaArray; * alert('they are here!'); * }); * </pre> * * @param {String} Query search query * @param {String} Type type of conten to search * @returns {Promise} resourcePromise object containing the entity array. * */ search: function (query, type, searchFrom, canceler) { var args = [{ query: query }, { type: type }]; if (searchFrom) { args.push({ searchFrom: searchFrom }); } var httpConfig = {}; if (canceler) { httpConfig["timeout"] = canceler; } return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "Search", args), httpConfig), 'Failed to retrieve entity data for query ' + query); }, /** * @ngdoc method * @name umbraco.resources.entityResource#searchAll * @methodOf umbraco.resources.entityResource * * @description * Gets an array of entities from all available search indexes, given a lucene query * * ##usage * <pre> * entityResource.searchAll("bob") * .then(function(array) { * var myDoc = array; * alert('they are here!'); * }); * </pre> * * @param {String} Query search query * @returns {Promise} resourcePromise object containing the entity array. * */ searchAll: function (query, canceler) { var httpConfig = {}; if (canceler) { httpConfig["timeout"] = canceler; } return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "entityApiBaseUrl", "SearchAll", [{ query: query }]), httpConfig), 'Failed to retrieve entity data for query ' + query); } }; } angular.module('umbraco.resources').factory('entityResource', entityResource);
Fixed issue with creating doctypes & templated with an Ampersand : http://issues.umbraco.org/issue/U4-11550 (#2828)
src/Umbraco.Web.UI.Client/src/common/resources/entity.resource.js
Fixed issue with creating doctypes & templated with an Ampersand : http://issues.umbraco.org/issue/U4-11550 (#2828)
<ide><path>rc/Umbraco.Web.UI.Client/src/common/resources/entity.resource.js <ide> $http.get( <ide> umbRequestHelper.getApiUrl( <ide> "entityApiBaseUrl", <del> "GetSafeAlias", { value: value, camelCase: camelCase })), <add> "GetSafeAlias", { value: encodeURIComponent(value), camelCase: camelCase })), <ide> 'Failed to retrieve content type scaffold'); <ide> }, <ide>
Java
apache-2.0
a71d689a2a7cfbf07c581a03489949068ccb178c
0
googleinterns/step126-2020,googleinterns/step126-2020,googleinterns/step126-2020,googleinterns/step126-2020,googleinterns/step126-2020
package com.google.sps.data; /* This class stores information pertaining to each precinct */ public class Precinct { /* Builder to construct each precinct object */ public static class Builder { private String name; private int population; private float averageHouseholdIncome; private float crimeRate; private float policeStationRating; public Builder(String name) { this.name = name; } /** * Sets the population of the precinct * * @param population The number of people in the precinct * @return Builder instance */ public Builder population(int population) { this.population = population; return this; } /** * Sets the household income average (USD) for the precinct * * @param averageHouseholdIncome Income in each household * @return Builder instance */ public Builder averageHouseholdIncome(float averageHouseholdIncome) { this.averageHouseholdIncome = averageHouseholdIncome; return this; } /** * Sets the crime rate for the precinct * * @param crimeRate Crime rate per 1,000 residents * @return Builder instance */ public Builder crimeRate(float crimeRate) { this.crimeRate = crimeRate; return this; } /** * Sets the rating for the police department in each precinct * * @param policeStationRating 1-5 star rating of the station * @return Builder instance */ public Builder policeStationRating(float policeStationRating) { this.policeStationRating = policeStationRating; return this; } /** * Instantiates precinct and injects builder * * @return Precinct instance */ public Precinct build() { Precinct precinct = new Precinct(this); return precinct; } } private String name; private int population; private float averageHouseholdIncome; private float crimeRate; private float policeStationRating; private Precinct(Builder builder) { this.name = builder.name; this.population = builder.population; this.averageHouseholdIncome = builder.averageHouseholdIncome; this.crimeRate = builder.crimeRate; this.policeStationRating = builder.policeStationRating; } /** * Gets the name of the precinct * * @return String The name of the precinct */ public String getName() { return name; } /** * Gets the population of the precinct * * @return int The number of people */ public int getPopulation() { return population; } /** * Gets the average household income of the precinct * * @return float The average household income */ public float getAverageHouseholdIncome() { return averageHouseholdIncome; } /** * Gets the crime rate of the precinct * * @return float The number of crimes per 1,000 residents */ public float getCrimeRate() { return crimeRate; } /** * Gets the police station rating of the precinct * * @return float The google review rating of the station */ public float getPoliceStationRating() { return policeStationRating; } }
capstone/src/main/java/com/google/sps/data/Precinct.java
package com.google.sps.data; /* This class stores information pertaining to each precinct */ public class Precinct { public static class Builder { private String name; private int population; private float averageHouseholdIncome; private float crimeRate; private float policeStationRating; public Builder(String name) { this.name = name; } /** * Sets the population of the precinct * * @param population The number of people in the precinct * @return Builder instance */ public Builder population(int population) { this.population = population; return this; } /** * Sets the household income average (USD) for the precinct * * @param averageHouseholdIncome Income in each household * @return Builder instance */ public Builder averageHouseholdIncome(float averageHouseholdIncome) { this.averageHouseholdIncome = averageHouseholdIncome; return this; } /** * Sets the crime rate for the precinct * * @param crimeRate Crime rate per 1,000 residents * @return Builder instance */ public Builder crimeRate(float crimeRate) { this.crimeRate = crimeRate; return this; } /** * Sets the rating for the police department in each precinct * * @param policeStationRating 1-5 star rating of the station * @return Builder instance */ public Builder policeStationRating(float policeStationRating) { this.policeStationRating = policeStationRating; return this; } public Precinct build() { Precinct precinct = new Precinct(); precinct.name = this.name; precinct.population = this.population; precinct.averageHouseholdIncome = this.averageHouseholdIncome; precinct.crimeRate = this.crimeRate; precinct.policeStationRating = this.policeStationRating; return precinct; } } String name; int population; float averageHouseholdIncome; float crimeRate; float policeStationRating; private Precinct() {} /** * Gets the name of the precinct * * @return String The name of the precinct */ public String getName() { return name; } /** * Gets the population of the precinct * * @return int The number of people */ public int getPopulation() { return population; } /** * Gets the average household income of the precinct * * @return float The average household income */ public float getAverageHouseholdIncome() { return averageHouseholdIncome; } /** * Gets the crime rate of the precinct * * @return float The number of crimes per 1,000 residents */ public float getCrimeRate() { return crimeRate; } /** * Gets the police station rating of the precinct * * @return float The google review rating of the station */ public float getPoliceStationRating() { return policeStationRating; } }
Fixes semantic error in builder pattern structure
capstone/src/main/java/com/google/sps/data/Precinct.java
Fixes semantic error in builder pattern structure
<ide><path>apstone/src/main/java/com/google/sps/data/Precinct.java <ide> <ide> /* This class stores information pertaining to each precinct */ <ide> public class Precinct { <del> <add> <add> /* Builder to construct each precinct object */ <ide> public static class Builder { <ide> <ide> private String name; <ide> <ide> return this; <ide> } <del> <add> <add> /** <add> * Instantiates precinct and injects builder <add> * <add> * @return Precinct instance <add> */ <ide> public Precinct build() { <del> Precinct precinct = new Precinct(); <del> precinct.name = this.name; <del> precinct.population = this.population; <del> precinct.averageHouseholdIncome = this.averageHouseholdIncome; <del> precinct.crimeRate = this.crimeRate; <del> precinct.policeStationRating = this.policeStationRating; <add> Precinct precinct = new Precinct(this); <ide> <ide> return precinct; <ide> } <ide> } <ide> <del> String name; <del> int population; <del> float averageHouseholdIncome; <del> float crimeRate; <del> float policeStationRating; <add> private String name; <add> private int population; <add> private float averageHouseholdIncome; <add> private float crimeRate; <add> private float policeStationRating; <ide> <del> private Precinct() {} <add> private Precinct(Builder builder) { <add> this.name = builder.name; <add> this.population = builder.population; <add> this.averageHouseholdIncome = builder.averageHouseholdIncome; <add> this.crimeRate = builder.crimeRate; <add> this.policeStationRating = builder.policeStationRating; <add> } <ide> <ide> /** <ide> * Gets the name of the precinct
Java
apache-2.0
24745b57eaab1156975ecced66c1b7c3b01307f7
0
rogrs/app-heroku,rogrs/app-heroku,rogrs/app-heroku
package br.com.rogrs.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import br.com.rogrs.model.Endereco; import br.com.rogrs.service.ViaCEPService; @RestController @RequestMapping("/buscar") public class CEPController { @Autowired private ViaCEPService viaCEPService; @RequestMapping("/cep") public ResponseEntity<Endereco> buscarCEP(@RequestParam(value = "cep") String cep) { Endereco endereco = viaCEPService.buscaCEP(cep); if (null == endereco || endereco.isErro()) { throw new ResourceNotFoundException("CEP não encontrado!"); } return new ResponseEntity<>(endereco, HttpStatus.OK); } @ResponseStatus(value = HttpStatus.NOT_FOUND) public class ResourceNotFoundException extends RuntimeException { private static final long serialVersionUID = -6252766749487342137L; public ResourceNotFoundException(String message) { super(message); } } }
src/main/java/br/com/rogrs/controller/CEPController.java
package br.com.rogrs.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import br.com.rogrs.model.Endereco; import br.com.rogrs.service.ViaCEPService; @RestController @RequestMapping("/buscar") public class CEPController { @Autowired private ViaCEPService viaCEPService; @RequestMapping("/cep") public ResponseEntity<Endereco> buscarCEP(@RequestParam(value="cep") String cep) { Endereco endereco = viaCEPService.buscaCEP(cep); if (null == endereco || endereco.isErro()) { throw new ResourceNotFoundException("CEP não encontrado!"); } return new ResponseEntity<>(endereco, HttpStatus.OK); } @ResponseStatus(value = HttpStatus.NOT_FOUND) public class ResourceNotFoundException extends RuntimeException { private static final long serialVersionUID = -6252766749487342137L; public ResourceNotFoundException(String message) { super(message); } } }
Ajuste na formatação
src/main/java/br/com/rogrs/controller/CEPController.java
Ajuste na formatação
<ide><path>rc/main/java/br/com/rogrs/controller/CEPController.java <ide> @RestController <ide> @RequestMapping("/buscar") <ide> public class CEPController { <del> <add> <ide> @Autowired <ide> private ViaCEPService viaCEPService; <ide> <del> @RequestMapping("/cep") <del> public ResponseEntity<Endereco> buscarCEP(@RequestParam(value="cep") String cep) { <del> <del> Endereco endereco = viaCEPService.buscaCEP(cep); <del> <del> if (null == endereco || endereco.isErro()) { <del> throw new ResourceNotFoundException("CEP não encontrado!"); <del> } <del> <del> <del> return new ResponseEntity<>(endereco, HttpStatus.OK); <del> } <del> @ResponseStatus(value = HttpStatus.NOT_FOUND) <del> public class ResourceNotFoundException extends RuntimeException <del> { <del> private static final long serialVersionUID = -6252766749487342137L; <del> public ResourceNotFoundException(String message) { <del> super(message); <del> } <del> } <add> @RequestMapping("/cep") <add> public ResponseEntity<Endereco> buscarCEP(@RequestParam(value = "cep") String cep) { <add> <add> Endereco endereco = viaCEPService.buscaCEP(cep); <add> <add> if (null == endereco || endereco.isErro()) { <add> throw new ResourceNotFoundException("CEP não encontrado!"); <add> } <add> <add> return new ResponseEntity<>(endereco, HttpStatus.OK); <add> } <add> <add> @ResponseStatus(value = HttpStatus.NOT_FOUND) <add> public class ResourceNotFoundException extends RuntimeException { <add> private static final long serialVersionUID = -6252766749487342137L; <add> <add> public ResourceNotFoundException(String message) { <add> super(message); <add> } <add> } <ide> <ide> }
JavaScript
mit
e379548d49bf7cfc50c5287c4a969fd9f1398f78
0
Aceheliflyer/Ace-Bot,Aceheliflyer/AceBot,Aceheliflyer/AceBot
const { Command } = require('discord.js-commando') const { stripIndents } = require('common-tags') const { escapeMarkdown } = require('discord.js') module.exports = class InfoCommand extends Command { constructor (client) { super(client, { name: 'info', memberName: 'info', group: 'information', description: 'Displays information about the bot.', aliases: ['about'], clientPermissions: ['EMBED_LINKS'], throttling: { usages: 2, duration: 10 }, guarded: true }) } async run (message) { /* Start Contributors */ var dev; var contrib1; var contrib2; var contrib3; var contrib4 try { dev = this.client.users.find('id', '196443959558406144').tag } catch (e) { dev = 'Aceheliflyer#0950' } try { contrib1 = this.client.users.find('id', '217797734982352896').tag } catch (e) { contrib1 = 'cat16#0725' } try { contrib2 = this.client.users.find('id', '171319044715053057').tag } catch (e) { contrib2 = 'Michael | ASIANBOI#9310' } try { contrib3 = this.client.users.find('id', '325828052422492162').tag } catch (e) { contrib3 = 'Ariathe#4163' } try { contrib4 = this.client.users.find('id', '158397118611062785').tag } catch (e) { contrib3 = 'Thatguychris#3998' } /* End Contributors */ var totalGuilds; var totalChannels; var totalUsers if (!this.client.shard) { totalGuilds = await this.client.guilds.size totalChannels = await this.client.channels.size totalUsers = await this.client.users.size } else { var totalGuildsData = await this.client.shard.fetchClientValues('guilds.size') totalGuilds = await totalGuildsData.reduce((prev, val) => prev + val, 0) var totalChannelsData = await this.client.shard.fetchClientValues('channels.size') totalChannels = await totalChannelsData.reduce((prev, val) => prev + val, 0) var totalUsersData = await this.client.shard.fetchClientValues('users.size') totalUsers = await totalUsersData.reduce((prev, val) => prev + val, 0) } message.embed({ author: { name: this.client.user.tag, icon_url: this.client.user.displayAvatarURL() }, footer: { text: message.author.tag, icon_url: message.author.displayAvatarURL() }, timestamp: new Date(), fields: [ /* eslint-disable object-property-newline */ { 'name': 'Developer', 'value': `**${escapeMarkdown(dev)}**`, 'inline': true }, { 'name': 'Version', 'value': require('../../package.json').version, 'inline': true }, { 'name': 'Library', 'value': stripIndents` **discord.js-commando** v${require('discord.js-commando/package.json').version} **discord.js** v${require('discord.js/package.json').version} `, 'inline': true }, { 'name': 'Invites', 'value': stripIndents` [Bot Invite](${await this.client.generateInvite()}) [Server Invite](${this.client.config.startConfig.invite}) `, 'inline': true }, { 'name': 'Websites', 'value': stripIndents` [Homepage](${require('../../package.json').homepage}) [Repository](${require('../../package.json').homepageGithub}) [Trello](${require('../../package.json').homepageTrello}) `, 'inline': true }, { 'name': 'Discord Stats', 'value': stripIndents` ${this.client.shard ? `**Shards:** ${this.client.shard.count}\n` : ''}**Guilds:** ${totalGuilds} **Channels:** ${totalChannels} **Users:** ${totalUsers} `, 'inline': true }, { 'name': 'Contributors', 'value': stripIndents` **${escapeMarkdown(contrib1)} -** Helped with a lot of issues I had. **${escapeMarkdown(contrib2)} -** Offered suggestions and feedback. **${escapeMarkdown(contrib3)} -** Designed the avatar for Acebot. **${escapeMarkdown(contrib4)} -** Did the web scraping for \`discordstatus\`. `, 'inline': false } /* eslint-enable object-property-newline */ ], color: 0x7289DA }) } }
commands/information/info.js
const { Command } = require('discord.js-commando') const { stripIndents } = require('common-tags') const { escapeMarkdown } = require('discord.js') module.exports = class InfoCommand extends Command { constructor (client) { super(client, { name: 'info', memberName: 'info', group: 'information', description: 'Displays information about the bot.', aliases: ['about'], clientPermissions: ['EMBED_LINKS'], throttling: { usages: 2, duration: 10 }, guarded: true }) } async run (message) { /* Start Contributors */ var dev; var contrib1; var contrib2; var contrib3; var contrib4 try { dev = this.client.users.find('id', '196443959558406144').tag } catch (e) { dev = 'Aceheliflyer#0950' } try { contrib1 = this.client.users.find('id', '217797734982352896').tag } catch (e) { contrib1 = 'cat16#0725' } try { contrib2 = this.client.users.find('id', '171319044715053057').tag } catch (e) { contrib2 = 'Michael | ASIANBOI#9310' } try { contrib3 = this.client.users.find('id', '325828052422492162').tag } catch (e) { contrib3 = 'Ariathe#4163' } try { contrib4 = this.client.users.find('id', '158397118611062785').tag } catch (e) { contrib3 = 'Thatguychris#3998' } /* End Contributors */ var totalGuilds; var totalChannels; var totalUsers if (!this.client.shard) { totalGuilds = await this.client.guilds.size totalChannels = await this.client.channels.size totalUsers = await this.client.users.size } else { var totalGuildsData = await this.client.shard.fetchClientValues('guilds.size') totalGuilds = await totalGuildsData.reduce((prev, val) => prev + val, 0) var totalChannelsData = await this.client.shard.fetchClientValues('channels.size') totalChannels = await totalChannelsData.reduce((prev, val) => prev + val, 0) var totalUsersData = await this.client.shard.fetchClientValues('users.size') totalUsers = await totalUsersData.reduce((prev, val) => prev + val, 0) } message.embed({ author: { name: this.client.user.tag, icon_url: this.client.user.displayAvatarURL() }, footer: { text: message.author.tag, icon_url: message.author.displayAvatarURL() }, timestamp: new Date(), fields: [ /* eslint-disable object-property-newline */ { 'name': 'Developer', 'value': `**${escapeMarkdown(dev)}**`, 'inline': true }, { 'name': 'Version', 'value': require('../../package.json').version, 'inline': true }, { 'name': 'Library', 'value': stripIndents` **discord.js-commando** v${require('discord.js-commando/package.json').version} **discord.js** v${require('discord.js/package.json').version} `, 'inline': true }, { 'name': 'Invites', 'value': stripIndents` [Bot Invite](${await this.client.generateInvite()}) [Server Invite](${this.client.config.startConfig.invite}) `, 'inline': true }, { 'name': 'Websites', 'value': stripIndents` [Homepage](${require('../../package.json').homepage}) [Repository](${require('../../package.json').homepageGithub}) `, 'inline': true }, { 'name': 'Discord Stats', 'value': stripIndents` ${this.client.shard ? `**Shards:** ${this.client.shard.count}\n` : ''}**Guilds:** ${totalGuilds} **Channels:** ${totalChannels} **Users:** ${totalUsers} `, 'inline': true }, { 'name': 'Contributors', 'value': stripIndents` **${escapeMarkdown(contrib1)} -** Helped with a lot of issues I had. **${escapeMarkdown(contrib2)} -** Offered suggestions and feedback. **${escapeMarkdown(contrib3)} -** Designed the avatar for Acebot. **${escapeMarkdown(contrib4)} -** Did the web scraping for \`discordstatus\`. `, 'inline': false } /* eslint-enable object-property-newline */ ], color: 0x7289DA }) } }
Commands: Added Trello to info command
commands/information/info.js
Commands: Added Trello to info command
<ide><path>ommands/information/info.js <ide> { 'name': 'Websites', 'value': stripIndents` <ide> [Homepage](${require('../../package.json').homepage}) <ide> [Repository](${require('../../package.json').homepageGithub}) <add> [Trello](${require('../../package.json').homepageTrello}) <ide> `, 'inline': true }, <ide> { 'name': 'Discord Stats', 'value': stripIndents` <ide> ${this.client.shard ? `**Shards:** ${this.client.shard.count}\n` : ''}**Guilds:** ${totalGuilds}
Java
bsd-3-clause
0cc7a3a51ce802d5a9edf4c61de9871c7b7ed10a
0
oranoceallaigh/smppapi,oranoceallaigh/smppapi,oranoceallaigh/smppapi
package ie.omk.smpp; import ie.omk.smpp.event.ConnectionObserver; import ie.omk.smpp.event.EventDispatcher; import ie.omk.smpp.event.SimpleEventDispatcher; import ie.omk.smpp.message.Bind; import ie.omk.smpp.message.BindReceiver; import ie.omk.smpp.message.BindResp; import ie.omk.smpp.message.BindTransceiver; import ie.omk.smpp.message.BindTransmitter; import ie.omk.smpp.message.SMPPPacket; import ie.omk.smpp.message.Unbind; import ie.omk.smpp.message.UnbindResp; import ie.omk.smpp.message.tlv.Tag; import ie.omk.smpp.net.SmscLink; import ie.omk.smpp.net.TcpLink; import ie.omk.smpp.util.APIConfig; import ie.omk.smpp.util.DefaultSequenceScheme; import ie.omk.smpp.util.PropertyNotFoundException; import ie.omk.smpp.util.SequenceNumberScheme; import ie.omk.smpp.version.SMPPVersion; import ie.omk.smpp.version.VersionException; import ie.omk.smpp.version.VersionFactory; import java.io.IOException; import java.net.UnknownHostException; import java.util.Collection; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; // TODO documentation! public class Connection { private static final AtomicInteger CONNECTION_ID = new AtomicInteger(1); private final Logger log; private String connectionId; private SMPPVersion version = VersionFactory.getDefaultVersion(); private ConnectionType type; private AtomicInteger state = new AtomicInteger(ConnectionState.UNBOUND.intValue()); private SmscLink smscLink; private SequenceNumberScheme numberScheme = new DefaultSequenceScheme(); private EventDispatcher eventDispatcher; private Thread receiver; private boolean useOptionalParams = version.isSupportTLV(); private boolean validating = true; public Connection(SmscLink link) { connectionId = "Connection-" + CONNECTION_ID.getAndIncrement(); log = LoggerFactory.getLogger(Connection.class + "." + connectionId); this.smscLink = link; initFromConfig(); receiver = new ReceiverThread(this); receiver.setName(connectionId + "-Receiver"); } public Connection(String host, int port) throws UnknownHostException { this(new TcpLink(host, port)); } public String getConnectionId() { return connectionId; } public void addObserver(ConnectionObserver observer) { eventDispatcher.addObserver(observer); } public void removeObserver(ConnectionObserver observer) { eventDispatcher.removeObserver(observer); } public SmscLink getSmscLink() { return smscLink; } public EventDispatcher getEventDispatcher() { return eventDispatcher; } public void setEventDispatcher(EventDispatcher eventDispatcher) { EventDispatcher oldDispatcher = this.eventDispatcher; initNewDispatcher(oldDispatcher, eventDispatcher); this.eventDispatcher = eventDispatcher; oldDispatcher.destroy(); } public SMPPVersion getVersion() { return version; } public void setVersion(SMPPVersion version) { this.version = version; this.useOptionalParams = version.isSupportTLV(); } public SequenceNumberScheme getSequenceNumberScheme() { return numberScheme; } public void setSequenceNumberScheme(SequenceNumberScheme numberScheme) { this.numberScheme = numberScheme; } public boolean isValidating() { return validating; } public void setValidating(boolean validating) { this.validating = validating; } public void bind(ConnectionType type, String systemID, String password, String systemType) throws IOException { bind(type, systemID, password, systemType, 0, 0, null); } public void bind(ConnectionType type, String systemID, String password, String systemType, int typeOfNumber, int numberPlanIndicator, String addressRange) throws IOException { Bind bindRequest; if (type == ConnectionType.TRANSMITTER) { bindRequest = new BindTransmitter(); } else if (type == ConnectionType.RECEIVER) { bindRequest = new BindReceiver(); } else { bindRequest = new BindTransceiver(); } bindRequest.setVersion(version); bindRequest.setSystemId(systemID); bindRequest.setPassword(password); bindRequest.setSystemType(systemType); bindRequest.setAddressTon(typeOfNumber); bindRequest.setAddressNpi(numberPlanIndicator); bindRequest.setAddressRange(addressRange); bind(bindRequest); } public void bind(Bind bindRequest) throws IOException { if (getState() != ConnectionState.UNBOUND) { throw new IllegalStateException("Already binding or bound."); } if (bindRequest.getCommandId() == SMPPPacket.BIND_TRANSMITTER) { type = ConnectionType.TRANSMITTER; } else if (bindRequest.getCommandId() == SMPPPacket.BIND_RECEIVER) { type = ConnectionType.RECEIVER; } else { type = ConnectionType.TRANSCEIVER; } if (!smscLink.isConnected()) { smscLink.open(); } setLinkTimeout(APIConfig.BIND_TIMEOUT); log.debug("Sending bind packet to the SMSC.."); sendPacketInternal(bindRequest); receiver.start(); } public void unbind() throws IOException { sendPacketInternal(new Unbind()); } public void sendPacket(SMPPPacket packet) throws IOException { int commandId = packet.getCommandId(); switch (commandId) { case SMPPPacket.BIND_TRANSMITTER: case SMPPPacket.BIND_TRANSCEIVER: case SMPPPacket.BIND_RECEIVER: bind((Bind) packet); return; } if (type == ConnectionType.RECEIVER) { // We allow the receiver to send any response type but a very // limited set of requests. if (packet.isRequest() && !(commandId == SMPPPacket.UNBIND || commandId == SMPPPacket.ENQUIRE_LINK)) { throw new UnsupportedOperationException( "Receiver connection cannot send command " + commandId); } } sendPacketInternal(packet); } public void closeLink() throws IOException { if (getState() == ConnectionState.UNBOUND) { smscLink.close(); } else { throw new IllegalStateException("Cannot close link while connection is bound."); } } public ConnectionState getState() { return ConnectionState.valueOf(state.get()); } void processReceivedPacket(SMPPPacket packet) { switch (packet.getCommandId()) { case SMPPPacket.BIND_TRANSMITTER_RESP: case SMPPPacket.BIND_RECEIVER_RESP: case SMPPPacket.BIND_TRANSCEIVER_RESP: processReceivedBindResponse((BindResp) packet); break; case SMPPPacket.UNBIND: processReceivedUnbind((Unbind) packet); break; case SMPPPacket.UNBIND_RESP: processReceivedUnbindResponse((UnbindResp) packet); break; default: // Do nothing. } } private void setState(ConnectionState fromState, ConnectionState toState) { if (!state.compareAndSet(fromState.intValue(), toState.intValue())) { log.error("Race condition in setting state - expected {} but is {}", fromState, getState()); } } private void initFromConfig() { APIConfig config = APIConfig.getInstance(); String s = config.getProperty(APIConfig.EVENT_DISPATCHER_CLASS, null); if (s != null) { eventDispatcher = (EventDispatcher) getClassInstance(s, EventDispatcher.class); } if (eventDispatcher == null) { eventDispatcher = new SimpleEventDispatcher(); } initNewDispatcher(null, eventDispatcher); } private void initNewDispatcher(EventDispatcher oldDispatcher, EventDispatcher newDispatcher) { newDispatcher.init(); if (oldDispatcher != null) { Collection<ConnectionObserver> observers = oldDispatcher.getObservers(); for (ConnectionObserver observer : observers) { newDispatcher.addObserver(observer); } } } // TODO: do we still want to move this to APIConfig? private Object getClassInstance(String className, Class type) { Object obj = null; try { log.debug("Attempting to instantiate a class of type {}", className); Class<?> clazz = Class.forName(className); if (!clazz.isAssignableFrom(type)) { log.error("{} is not of type {}", className, type.getClass()); } else { obj = clazz.newInstance(); } } catch (Exception x) { log.error("Could not instantiate a class of type {}: {}", className, x.getMessage()); log.debug("Stack trace", x); } return obj; } private void sendPacketInternal(SMPPPacket packet) throws IOException { if (packet.getSequenceNum() < 0L && numberScheme != null) { packet.setSequenceNum(numberScheme.nextNumber()); } if (validating) { packet.validate(version); } smscLink.write(packet, useOptionalParams); processSentPacket(packet); } private void processSentPacket(SMPPPacket packet) { switch (packet.getCommandId()) { case SMPPPacket.BIND_TRANSMITTER: case SMPPPacket.BIND_RECEIVER: case SMPPPacket.BIND_TRANSCEIVER: processSentBind((Bind) packet); break; case SMPPPacket.UNBIND: processSentUnbind((Unbind) packet); break; case SMPPPacket.UNBIND_RESP: processSentUnbindResponse((UnbindResp) packet); break; default: } } private void processSentBind(Bind bindRequest) { setState(ConnectionState.UNBOUND, ConnectionState.BINDING); } private void processSentUnbind(Unbind unbindRequest) { setState(ConnectionState.BOUND, ConnectionState.UNBINDING); } private void processSentUnbindResponse(UnbindResp unbindResponse) { int status = unbindResponse.getCommandStatus(); if (status == 0) { setState(ConnectionState.UNBINDING, ConnectionState.UNBOUND); } } private void processReceivedBindResponse(BindResp bindResponse) { int status = bindResponse.getCommandStatus(); if (status == 0) { setState(ConnectionState.BINDING, ConnectionState.BOUND); negotiateVersion(bindResponse); setLinkTimeout(APIConfig.LINK_TIMEOUT); } else { log.warn("Received a bind response with status {}", status); setState(ConnectionState.BINDING, ConnectionState.UNBOUND); } } private void negotiateVersion(BindResp bindResponse) { if (bindResponse.isSet(Tag.SC_INTERFACE_VERSION)) { log.info("SMSC did not supply SC_INTERFACE_VERSION." + " Disabling optional parameter support."); useOptionalParams = false; return; } int versionId = 0; try { versionId = bindResponse.getTLVTable().getInt(Tag.SC_INTERFACE_VERSION); SMPPVersion smscVersion = VersionFactory.getVersion(versionId); log.info("SMSC states its version as {}", smscVersion); if (smscVersion.isOlderThan(version)) { version = smscVersion; useOptionalParams = version.isSupportTLV(); } } catch (VersionException x) { log.debug("SMSC implements a version I don't know: {}", versionId); } } private void processReceivedUnbind(Unbind unbindRequest) { setState(ConnectionState.BOUND, ConnectionState.UNBINDING); } private void processReceivedUnbindResponse(UnbindResp unbindResponse) { int status = unbindResponse.getCommandStatus(); if (status == 0) { setState(ConnectionState.UNBINDING, ConnectionState.UNBOUND); } else { log.warn("Received an unbind response with status {}", status); } } private void setLinkTimeout(String propName) { try { if (smscLink.isTimeoutSupported()) { int linkTimeout = APIConfig.getInstance().getInt(propName); smscLink.setTimeout(linkTimeout); if (log.isDebugEnabled()) { log.debug("Set the link timeout to {}", linkTimeout); } } else { log.info("SMSC link implementation does not support timeouts."); } } catch (PropertyNotFoundException x) { log.debug("Not setting link timeout as it is not configured."); } } }
src/java/ie/omk/smpp/Connection.java
package ie.omk.smpp; import ie.omk.smpp.event.ConnectionObserver; import ie.omk.smpp.event.EventDispatcher; import ie.omk.smpp.event.SimpleEventDispatcher; import ie.omk.smpp.message.Bind; import ie.omk.smpp.message.BindReceiver; import ie.omk.smpp.message.BindResp; import ie.omk.smpp.message.BindTransceiver; import ie.omk.smpp.message.BindTransmitter; import ie.omk.smpp.message.SMPPPacket; import ie.omk.smpp.message.Unbind; import ie.omk.smpp.message.UnbindResp; import ie.omk.smpp.message.tlv.Tag; import ie.omk.smpp.net.SmscLink; import ie.omk.smpp.net.TcpLink; import ie.omk.smpp.util.APIConfig; import ie.omk.smpp.util.DefaultSequenceScheme; import ie.omk.smpp.util.PropertyNotFoundException; import ie.omk.smpp.util.SequenceNumberScheme; import ie.omk.smpp.version.SMPPVersion; import ie.omk.smpp.version.VersionException; import ie.omk.smpp.version.VersionFactory; import java.io.IOException; import java.net.UnknownHostException; import java.util.Collection; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; // TODO documentation! public class Connection { private static final AtomicInteger CONNECTION_ID = new AtomicInteger(1); private final Logger log; private String connectionId; private SMPPVersion version = VersionFactory.getDefaultVersion(); private ConnectionType type; private ConnectionState state = ConnectionState.UNBOUND; private SmscLink smscLink; private SequenceNumberScheme numberScheme = new DefaultSequenceScheme(); private EventDispatcher eventDispatcher; private Thread receiver; private boolean useOptionalParams = version.isSupportOptionalParams(); private boolean validating = true; public Connection(SmscLink link) { connectionId = "Connection-" + CONNECTION_ID.getAndIncrement(); log = LoggerFactory.getLogger(Connection.class + "." + connectionId); this.smscLink = link; initFromConfig(); receiver = new ReceiverThread(this); receiver.setName(connectionId + "-Receiver"); } public Connection(String host, int port) throws UnknownHostException { this(new TcpLink(host, port)); } public String getConnectionId() { return connectionId; } public void addObserver(ConnectionObserver observer) { eventDispatcher.addObserver(observer); } public void removeObserver(ConnectionObserver observer) { eventDispatcher.removeObserver(observer); } public SmscLink getSmscLink() { return smscLink; } public EventDispatcher getEventDispatcher() { return eventDispatcher; } public void setEventDispatcher(EventDispatcher eventDispatcher) { EventDispatcher oldDispatcher = this.eventDispatcher; initNewDispatcher(oldDispatcher, eventDispatcher); this.eventDispatcher = eventDispatcher; oldDispatcher.destroy(); } public SMPPVersion getVersion() { return version; } public void setVersion(SMPPVersion version) { this.version = version; this.useOptionalParams = version.isSupportOptionalParams(); } public SequenceNumberScheme getSequenceNumberScheme() { return numberScheme; } public void setSequenceNumberScheme(SequenceNumberScheme numberScheme) { this.numberScheme = numberScheme; } public boolean isValidating() { return validating; } public void setValidating(boolean validating) { this.validating = validating; } public void bind(ConnectionType type, String systemID, String password, String systemType) throws IOException { bind(type, systemID, password, systemType, 0, 0, null); } public void bind(ConnectionType type, String systemID, String password, String systemType, int typeOfNumber, int numberPlanIndicator, String addressRange) throws IOException { Bind bindRequest; if (type == ConnectionType.TRANSMITTER) { bindRequest = new BindTransmitter(); } else if (type == ConnectionType.RECEIVER) { bindRequest = new BindReceiver(); } else { bindRequest = new BindTransceiver(); } bindRequest.setVersion(version); bindRequest.setSystemId(systemID); bindRequest.setPassword(password); bindRequest.setSystemType(systemType); bindRequest.setAddressTon(typeOfNumber); bindRequest.setAddressNpi(numberPlanIndicator); bindRequest.setAddressRange(addressRange); bind(bindRequest); } public void bind(Bind bindRequest) throws IOException { if (state != ConnectionState.UNBOUND) { throw new IllegalStateException("Already binding or bound."); } if (bindRequest instanceof BindTransmitter) { type = ConnectionType.TRANSMITTER; } else if (bindRequest instanceof BindReceiver) { type = ConnectionType.RECEIVER; } else { type = ConnectionType.TRANSCEIVER; } if (!smscLink.isConnected()) { smscLink.open(); } setLinkTimeout(APIConfig.BIND_TIMEOUT); log.debug("Sending bind packet to the SMSC.."); sendPacketInternal(bindRequest); receiver.start(); } public void unbind() throws IOException { unbind(new Unbind()); } public void unbind(Unbind unbindRequest) throws IOException { if (state != ConnectionState.BOUND) { throw new IllegalStateException("Not currently bound."); } setState(ConnectionState.UNBINDING); sendPacketInternal(unbindRequest); } public void sendPacket(SMPPPacket packet) throws IOException { if (state == ConnectionState.UNBOUND) { throw new IllegalStateException("Not bound to the SMSC."); } int commandId = packet.getCommandId(); if (validating) { packet.validate(version); } // We allow the receiver to send any response type but a very // limited set of requests. if (type == ConnectionType.RECEIVER && (commandId & 0x80000000) == 0) { switch (commandId) { case SMPPPacket.BIND_RECEIVER: case SMPPPacket.UNBIND: case SMPPPacket.ENQUIRE_LINK: // Ok to go ahead and send the packet. break; default: throw new UnsupportedOperationException( "Receiver connection cannot send command " + commandId); } } sendPacketInternal(packet); } public void closeLink() throws IOException { if (state == ConnectionState.UNBOUND) { smscLink.close(); } else { throw new IllegalStateException("Cannot close link while connection is bound."); } } public ConnectionState getState() { return state; } void processReceivedPacket(SMPPPacket packet) { switch (packet.getCommandId()) { case SMPPPacket.BIND_TRANSMITTER_RESP: case SMPPPacket.BIND_RECEIVER_RESP: case SMPPPacket.BIND_TRANSCEIVER_RESP: processReceivedBindResponse((BindResp) packet); break; case SMPPPacket.UNBIND: processReceivedUnbind((Unbind) packet); break; case SMPPPacket.UNBIND_RESP: processReceivedUnbindResponse((UnbindResp) packet); break; default: // Do nothing. } } private void setState(ConnectionState state) { this.state = state; } private void initFromConfig() { APIConfig config = APIConfig.getInstance(); String s = config.getProperty(APIConfig.EVENT_DISPATCHER_CLASS, null); if (s != null) { eventDispatcher = (EventDispatcher) getClassInstance(s, EventDispatcher.class); } if (eventDispatcher == null) { eventDispatcher = new SimpleEventDispatcher(); } initNewDispatcher(null, eventDispatcher); } private void initNewDispatcher(EventDispatcher oldDispatcher, EventDispatcher newDispatcher) { newDispatcher.init(); if (oldDispatcher != null) { Collection<ConnectionObserver> observers = oldDispatcher.getObservers(); for (ConnectionObserver observer : observers) { newDispatcher.addObserver(observer); } } } // TODO: do we still want to move this to APIConfig? private Object getClassInstance(String className, Class type) { Object obj = null; try { log.debug("Attempting to instantiate a class of type {}", className); Class<?> clazz = Class.forName(className); if (!clazz.isAssignableFrom(type)) { log.error("{} is not of type {}", className, type.getClass()); } else { obj = clazz.newInstance(); } } catch (Exception x) { log.error("Could not instantiate a class of type {}: {}", className, x.getMessage()); log.debug("Stack trace", x); } return obj; } private void sendPacketInternal(SMPPPacket packet) throws IOException { if (packet.getSequenceNum() < 0L && numberScheme != null) { packet.setSequenceNum(numberScheme.nextNumber()); } smscLink.write(packet, useOptionalParams); processSentPacket(packet); } private void processSentPacket(SMPPPacket packet) { switch (packet.getCommandId()) { case SMPPPacket.BIND_TRANSMITTER: case SMPPPacket.BIND_RECEIVER: case SMPPPacket.BIND_TRANSCEIVER: processSentBind((Bind) packet); break; case SMPPPacket.UNBIND: processSentUnbind((Unbind) packet); break; case SMPPPacket.UNBIND_RESP: processSentUnbindResponse((UnbindResp) packet); break; default: } } private void processSentBind(Bind bindRequest) { setState(ConnectionState.BINDING); } private void processSentUnbind(Unbind unbindRequest) { setState(ConnectionState.UNBINDING); } private void processSentUnbindResponse(UnbindResp unbindResponse) { int status = unbindResponse.getCommandStatus(); if (status == 0) { setState(ConnectionState.UNBOUND); } } private void processReceivedBindResponse(BindResp bindResponse) { int status = bindResponse.getCommandStatus(); if (status == 0) { setState(ConnectionState.BOUND); negotiateVersion(bindResponse); setLinkTimeout(APIConfig.LINK_TIMEOUT); } else { log.warn("Received a bind response with status {}", status); setState(ConnectionState.UNBOUND); } } private void negotiateVersion(BindResp bindResponse) { Number versionId = (Number) bindResponse.getOptionalParameter( Tag.SC_INTERFACE_VERSION); if (versionId == null) { log.info("SMSC did not supply SC_INTERFACE_VERSION." + " Disabling optional parameter support."); useOptionalParams = false; return; } try { SMPPVersion smscVersion = VersionFactory.getVersion(versionId.intValue()); log.info("SMSC states its version as {}", smscVersion); if (smscVersion.isOlderThan(version)) { version = smscVersion; useOptionalParams = version.isSupportOptionalParams(); } } catch (VersionException x) { log.debug("SMSC implements a version I don't know: {}", versionId); } } private void processReceivedUnbind(Unbind unbindRequest) { setState(ConnectionState.UNBINDING); } private void processReceivedUnbindResponse(UnbindResp unbindResponse) { int status = unbindResponse.getCommandStatus(); if (status == 0) { setState(ConnectionState.UNBOUND); } else { log.warn("Received an unbind response with status {}", status); } } private void setLinkTimeout(String propName) { try { if (smscLink.isTimeoutSupported()) { int linkTimeout = APIConfig.getInstance().getInt(propName); smscLink.setTimeout(linkTimeout); if (log.isDebugEnabled()) { log.debug("Set the link timeout to {}", linkTimeout); } } else { log.info("SMSC link implementation does not support timeouts."); } } catch (PropertyNotFoundException x) { log.debug("Not setting link timeout as it is not configured."); } } }
Connection state to an AtomicInteger. Change setState method sig and operation. Updates to reflect API changes in other classes.
src/java/ie/omk/smpp/Connection.java
Connection state to an AtomicInteger. Change setState method sig and operation. Updates to reflect API changes in other classes.
<ide><path>rc/java/ie/omk/smpp/Connection.java <ide> private String connectionId; <ide> private SMPPVersion version = VersionFactory.getDefaultVersion(); <ide> private ConnectionType type; <del> private ConnectionState state = ConnectionState.UNBOUND; <add> private AtomicInteger state = new AtomicInteger(ConnectionState.UNBOUND.intValue()); <ide> private SmscLink smscLink; <ide> private SequenceNumberScheme numberScheme = new DefaultSequenceScheme(); <ide> private EventDispatcher eventDispatcher; <ide> private Thread receiver; <del> private boolean useOptionalParams = version.isSupportOptionalParams(); <add> private boolean useOptionalParams = version.isSupportTLV(); <ide> private boolean validating = true; <ide> <ide> public Connection(SmscLink link) { <ide> <ide> public void setVersion(SMPPVersion version) { <ide> this.version = version; <del> this.useOptionalParams = version.isSupportOptionalParams(); <add> this.useOptionalParams = version.isSupportTLV(); <ide> } <ide> <ide> public SequenceNumberScheme getSequenceNumberScheme() { <ide> } <ide> <ide> public void bind(Bind bindRequest) throws IOException { <del> if (state != ConnectionState.UNBOUND) { <add> if (getState() != ConnectionState.UNBOUND) { <ide> throw new IllegalStateException("Already binding or bound."); <ide> } <del> if (bindRequest instanceof BindTransmitter) { <add> if (bindRequest.getCommandId() == SMPPPacket.BIND_TRANSMITTER) { <ide> type = ConnectionType.TRANSMITTER; <del> } else if (bindRequest instanceof BindReceiver) { <add> } else if (bindRequest.getCommandId() == SMPPPacket.BIND_RECEIVER) { <ide> type = ConnectionType.RECEIVER; <ide> } else { <ide> type = ConnectionType.TRANSCEIVER; <ide> } <ide> <ide> public void unbind() throws IOException { <del> unbind(new Unbind()); <del> } <del> <del> public void unbind(Unbind unbindRequest) throws IOException { <del> if (state != ConnectionState.BOUND) { <del> throw new IllegalStateException("Not currently bound."); <del> } <del> setState(ConnectionState.UNBINDING); <del> sendPacketInternal(unbindRequest); <add> sendPacketInternal(new Unbind()); <ide> } <ide> <ide> public void sendPacket(SMPPPacket packet) throws IOException { <del> if (state == ConnectionState.UNBOUND) { <del> throw new IllegalStateException("Not bound to the SMSC."); <del> } <ide> int commandId = packet.getCommandId(); <del> if (validating) { <del> packet.validate(version); <del> } <del> // We allow the receiver to send any response type but a very <del> // limited set of requests. <del> if (type == ConnectionType.RECEIVER && (commandId & 0x80000000) == 0) { <del> switch (commandId) { <del> case SMPPPacket.BIND_RECEIVER: <del> case SMPPPacket.UNBIND: <del> case SMPPPacket.ENQUIRE_LINK: <del> // Ok to go ahead and send the packet. <del> break; <del> default: <add> switch (commandId) { <add> case SMPPPacket.BIND_TRANSMITTER: <add> case SMPPPacket.BIND_TRANSCEIVER: <add> case SMPPPacket.BIND_RECEIVER: <add> bind((Bind) packet); <add> return; <add> } <add> if (type == ConnectionType.RECEIVER) { <add> // We allow the receiver to send any response type but a very <add> // limited set of requests. <add> if (packet.isRequest() <add> && !(commandId == SMPPPacket.UNBIND <add> || commandId == SMPPPacket.ENQUIRE_LINK)) { <ide> throw new UnsupportedOperationException( <ide> "Receiver connection cannot send command " + commandId); <ide> } <ide> } <ide> <ide> public void closeLink() throws IOException { <del> if (state == ConnectionState.UNBOUND) { <add> if (getState() == ConnectionState.UNBOUND) { <ide> smscLink.close(); <ide> } else { <ide> throw new IllegalStateException("Cannot close link while connection is bound."); <ide> } <ide> <ide> public ConnectionState getState() { <del> return state; <add> return ConnectionState.valueOf(state.get()); <ide> } <ide> <ide> void processReceivedPacket(SMPPPacket packet) { <ide> } <ide> } <ide> <del> private void setState(ConnectionState state) { <del> this.state = state; <add> private void setState(ConnectionState fromState, ConnectionState toState) { <add> if (!state.compareAndSet(fromState.intValue(), toState.intValue())) { <add> log.error("Race condition in setting state - expected {} but is {}", <add> fromState, getState()); <add> } <ide> } <ide> <ide> private void initFromConfig() { <ide> if (packet.getSequenceNum() < 0L && numberScheme != null) { <ide> packet.setSequenceNum(numberScheme.nextNumber()); <ide> } <add> if (validating) { <add> packet.validate(version); <add> } <ide> smscLink.write(packet, useOptionalParams); <ide> processSentPacket(packet); <ide> } <ide> } <ide> <ide> private void processSentBind(Bind bindRequest) { <del> setState(ConnectionState.BINDING); <add> setState(ConnectionState.UNBOUND, ConnectionState.BINDING); <ide> } <ide> <ide> private void processSentUnbind(Unbind unbindRequest) { <del> setState(ConnectionState.UNBINDING); <add> setState(ConnectionState.BOUND, ConnectionState.UNBINDING); <ide> } <ide> <ide> private void processSentUnbindResponse(UnbindResp unbindResponse) { <ide> int status = unbindResponse.getCommandStatus(); <ide> if (status == 0) { <del> setState(ConnectionState.UNBOUND); <add> setState(ConnectionState.UNBINDING, ConnectionState.UNBOUND); <ide> } <ide> } <ide> <ide> private void processReceivedBindResponse(BindResp bindResponse) { <ide> int status = bindResponse.getCommandStatus(); <ide> if (status == 0) { <del> setState(ConnectionState.BOUND); <add> setState(ConnectionState.BINDING, ConnectionState.BOUND); <ide> negotiateVersion(bindResponse); <ide> setLinkTimeout(APIConfig.LINK_TIMEOUT); <ide> } else { <ide> log.warn("Received a bind response with status {}", status); <del> setState(ConnectionState.UNBOUND); <add> setState(ConnectionState.BINDING, ConnectionState.UNBOUND); <ide> } <ide> } <ide> <ide> private void negotiateVersion(BindResp bindResponse) { <del> Number versionId = (Number) bindResponse.getOptionalParameter( <del> Tag.SC_INTERFACE_VERSION); <del> if (versionId == null) { <add> if (bindResponse.isSet(Tag.SC_INTERFACE_VERSION)) { <ide> log.info("SMSC did not supply SC_INTERFACE_VERSION." <ide> + " Disabling optional parameter support."); <ide> useOptionalParams = false; <ide> return; <ide> } <add> int versionId = 0; <ide> try { <add> versionId = <add> bindResponse.getTLVTable().getInt(Tag.SC_INTERFACE_VERSION); <ide> SMPPVersion smscVersion = <del> VersionFactory.getVersion(versionId.intValue()); <add> VersionFactory.getVersion(versionId); <ide> log.info("SMSC states its version as {}", smscVersion); <ide> if (smscVersion.isOlderThan(version)) { <ide> version = smscVersion; <del> useOptionalParams = version.isSupportOptionalParams(); <add> useOptionalParams = version.isSupportTLV(); <ide> } <ide> } catch (VersionException x) { <ide> log.debug("SMSC implements a version I don't know: {}", versionId); <ide> } <ide> <ide> private void processReceivedUnbind(Unbind unbindRequest) { <del> setState(ConnectionState.UNBINDING); <add> setState(ConnectionState.BOUND, ConnectionState.UNBINDING); <ide> } <ide> <ide> private void processReceivedUnbindResponse(UnbindResp unbindResponse) { <ide> int status = unbindResponse.getCommandStatus(); <ide> if (status == 0) { <del> setState(ConnectionState.UNBOUND); <add> setState(ConnectionState.UNBINDING, ConnectionState.UNBOUND); <ide> } else { <ide> log.warn("Received an unbind response with status {}", status); <ide> }
Java
apache-2.0
2340805cac728bef286f1954cce0d160fb1c77df
0
vector-im/riot-automated-tests,vector-im/riot-automated-tests
package mobilestests_android; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Method; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import com.esotericsoftware.yamlbeans.YamlException; import pom_android.main_tabs.RiotFavouritesTabPageObjects; import pom_android.main_tabs.RiotHomePageTabObjects; import pom_android.main_tabs.RiotPeopleTabPageObjects; import pom_android.main_tabs.RiotRoomsTabPageObjects; import utility.Constant; import utility.HttpsRequestsToMatrix; import utility.MatrixUtilities; import utility.RiotParentTest; import utility.ScreenshotUtility; /** * Tests on Ux Rework. * @author jeangb */ @Listeners({ ScreenshotUtility.class }) public class RiotUxReworkTests extends RiotParentTest{ private String riotUserADisplayName="riotuser1"; private String riotUserBDisplayName="riotuser2"; private String riotUserAAccessToken; private String testRoomId; /** * 1. Create room A from home page. </br> * 2. Make it favourite. </br> * Check that the room is in the FAVOURITES section on the home page. </br> * 3. Hit FAVOURITES tab, and check that room A is present. </br> * 4. Hit PEOPLE tab, and check that room A is not present. </br> * 5. Hit ROOMS tab and check that room A is present. * @throws IOException, InterruptedException */ @Test(groups={"1driver_android","1checkuser"}, priority=0) public void duplicatedFavouritedRoomAccrossTabsTest() throws IOException, InterruptedException{ String roomName="favouriteRoomAutoTest"; //1. Create room A from home page. createRoomWithByRequestsToMatrix(roomName); //2. Make it favourite. RiotHomePageTabObjects homePage = new RiotHomePageTabObjects(appiumFactory.getAndroidDriver1()); homePage.clickOnContextMenuOnRoom(roomName, "Favourite"); //Check that the room is in the FAVOURITES section on the home page. homePage.checkRoomInCategory(roomName, homePage.favouritesSectionLayout,0); //3. Hit FAVOURITES tab, and check that room A is present. RiotFavouritesTabPageObjects favouritesPage=homePage.openFavouriteTab(); Assert.assertNotNull(favouritesPage.getRoomByName(roomName), "Room "+roomName+" not found in Favourites tab."); //4. Hit PEOPLE tab, and check that room A is not present. RiotPeopleTabPageObjects peopleTab=favouritesPage.openPeopleTab(); Assert.assertNull(peopleTab.getRoomByName(roomName), "Room "+roomName+" found in People tab and it shouldn't be."); //5. Hit ROOMS tab and check that room A is present. RiotRoomsTabPageObjects roomsTab = peopleTab.openRoomsTab(); Assert.assertNotNull(roomsTab.getRoomByName(roomName), "Room "+roomName+" not found in Rooms tab."); } /** * 1. Create direct chat with user B. </br> * 2. Make it favourite. </br> * Check that the room is in the FAVOURITES section on the home page. </br> * 3. Hit FAVOURITES tab, and check that direct chat with user B is present. </br> * 4. Hit PEOPLE tab and check that direct chat with user B is present. * 5. Hit ROOMS tab and check that room A is not present. * @throws IOException, InterruptedException */ @Test(groups={"1driver_android","1checkuser"}, priority=1) public void duplicatedDirectChatAccrossTabsTest() throws IOException, InterruptedException{ //1. Create direct chat with user B. createDirectChatWithByRequestsToMatrix(MatrixUtilities.getMatrixIdFromDisplayName(riotUserBDisplayName)); //2. Make it favourite. RiotHomePageTabObjects homePage = new RiotHomePageTabObjects(appiumFactory.getAndroidDriver1()); homePage.clickOnContextMenuOnRoom(riotUserBDisplayName, "Direct Chat"); homePage.clickOnContextMenuOnRoom(riotUserBDisplayName, "Favourite"); //Check that the room is in the FAVOURITES section on the home page. homePage.checkRoomInCategory(riotUserBDisplayName, homePage.favouritesSectionLayout,0); //3. Hit FAVOURITES tab, and check that direct chat with user B is present. RiotFavouritesTabPageObjects favouritesPage=homePage.openFavouriteTab(); Assert.assertNotNull(favouritesPage.getRoomByName(riotUserBDisplayName), "Direct chat "+riotUserBDisplayName+" not found in Favourites tab."); //4. Hit PEOPLE tab and check that direct chat with user B is present. RiotPeopleTabPageObjects peopleTab = favouritesPage.openPeopleTab(); Assert.assertNotNull(peopleTab.getRoomByName(riotUserBDisplayName), "Direct chat "+riotUserBDisplayName+" not found in People tab."); //5. Hit ROOMS tab and check that direct chat with user B is not present. RiotRoomsTabPageObjects roomsTab = peopleTab.openRoomsTab(); Assert.assertNull(roomsTab.getRoomByName(riotUserBDisplayName), "Direct chat "+riotUserBDisplayName+" found in Rooms tab and it shouldn't be."); } /** * 1. Create room A from home page. </br> * 2. Make it low priority. </br> * Check that the room is in the LOW PRIORITY section on the home page. </br> * 3. Hit ROOMS tab and check that room A is not present. * @throws IOException, InterruptedException */ @Test(groups={"1driver_android","1checkuser"}, priority=2) public void notDuplicatedLowPriorityRoomAccrossTabsTest() throws IOException, InterruptedException{ String roomName = "lowPriorityRoomTest"; //1. Create room A from home page. createRoomWithByRequestsToMatrix(roomName); //2. Make it low priority. RiotHomePageTabObjects homePage = new RiotHomePageTabObjects(appiumFactory.getAndroidDriver1()); homePage.clickOnContextMenuOnRoom(roomName, "De-prioritize"); //Check that the room is in the LOW PRIORITY section on the home page. homePage.checkRoomInCategory(roomName, homePage.lowPrioritySectionLayout,0); //3. Hit ROOMS tab and check that room A is not present RiotRoomsTabPageObjects roomsTab=homePage.openRoomsTab(); Assert.assertNull(roomsTab.getRoomByName(roomName), "Room "+roomName+" found in Rooms tab and it shouldn't be."); } /** * 1. Create direct chat with user B. </br> * 2. Make it low priority. </br> * Check that the room is in the LOW PRIORITY section on the home page. </br> * 3. Hit PEOPLE tab and check that direct chat with user B is not present. * @throws IOException, InterruptedException */ @Test(groups={"1driver_android","1checkuser"}, priority=3) public void notDuplicatedDirectChatAccrossTabsTest() throws IOException, InterruptedException{ //1. Create direct chat with user B. createDirectChatWithByRequestsToMatrix(MatrixUtilities.getMatrixIdFromDisplayName(riotUserBDisplayName)); //2. Make it low priority. RiotHomePageTabObjects homePage = new RiotHomePageTabObjects(appiumFactory.getAndroidDriver1()); homePage.clickOnContextMenuOnRoom(riotUserBDisplayName, "Direct Chat"); homePage.clickOnContextMenuOnRoom(riotUserBDisplayName, "De-prioritize"); //Check that the room is in the LOW PRIORITY section on the home page. homePage.checkRoomInCategory(riotUserBDisplayName, homePage.lowPrioritySectionLayout,0); //3. Hit PEOPLE tab and check that direct chat with user B is not present. RiotPeopleTabPageObjects peopleTab = homePage.openPeopleTab(); Assert.assertNull(peopleTab.getRoomByName(riotUserBDisplayName), "Direct chat "+riotUserBDisplayName+" found in People tab and it shouldn't be."); } /** * Brows tabs and check the filter search field text. * 1. Open home page tab, check that filter field text is 'Search for rooms' * 2. Open favourites tab, check that filter field text is 'Search for favourites' * 3. Open people tab, check that filter field text is 'Search for people' * 4. Open rooms tab, check that filter field text is 'Search for rooms' */ @Test(groups={"1driver_android","1checkuser"}, priority=4) public void filterOptionSearchTest() throws InterruptedException{ //1. Open home page tab, check that filter field text is 'Search for rooms' RiotHomePageTabObjects homePageTab = new RiotHomePageTabObjects(appiumFactory.getAndroidDriver1()); Assert.assertEquals(homePageTab.filterBarEditText.getText(), "Search for rooms"); //2. Open favourites tab, check that filter field text is 'Search for favourites' RiotFavouritesTabPageObjects favouritesTab= homePageTab.openFavouriteTab(); Assert.assertEquals(favouritesTab.filterBarEditText.getText(), "Search for favourites"); //3. Open people tab, check that filter field text is 'Search for people' RiotPeopleTabPageObjects peopleTab = favouritesTab.openPeopleTab(); Assert.assertEquals(peopleTab.filterBarEditText.getText(), "Search for people"); //4. Open rooms tab, check that filter field text is 'Search for rooms' RiotRoomsTabPageObjects roomsTab=peopleTab.openRoomsTab(); Assert.assertEquals(roomsTab.filterBarEditText.getText(), "Search for rooms"); } /** * 1. Open people tab </br> * 2. Hit LOCAL ADDRESS BOOK sticky header </br> * Local contact list is displayed </br> * 3. Hit CONVERSATIONS sticky header </br> * Conversations list is displayed </br> * 4. Open rooms tab </br> * 5. Hit ROOM DIRECTORY stikcy header </br> * Check that room directory section is displayed </br> * 6. Hit ROOMS stikcy header </br> * Check that rooms displayed * @throws InterruptedException */ @Test(groups={"1driver_android","1checkuser_default_hs"}, priority=5) public void stickyHeaderTest() throws InterruptedException{ //1. Open people tab RiotHomePageTabObjects homePageTab = new RiotHomePageTabObjects(appiumFactory.getAndroidDriver1()); RiotPeopleTabPageObjects peopleTab = homePageTab.openPeopleTab(); //2. Hit LOCAL ADDRESS BOOK sticky heade peopleTab.hitSectionHeader("LOCAL ADDRESS BOOK"); //Local contact list is displayed Assert.assertTrue(peopleTab.peopleList.size()>1, "Contacts list is empty"); //3. Hit CONVERSATIONS sticky header peopleTab.hitSectionHeader("CONVERSATIONS"); //Conversations list is displayed Assert.assertTrue(peopleTab.roomsList.size()>1,"Conversations list is empty"); //4. Open rooms tab RiotRoomsTabPageObjects roomsTab = peopleTab.openRoomsTab(); //5. Hit ROOM DIRECTORY stikcy header waitUntilDisplayed(appiumFactory.getAndroidDriver1(), "im.vector.alpha:id/section_loading", false, 10); roomsTab.hitSectionHeader("ROOM DIRECTORY"); //Check that room directory section is displayed Assert.assertTrue(roomsTab.publicRoomsList.size()>1, "Rooms directory list is empty"); // 6. Hit ROOMS stikcy header roomsTab.hitSectionHeader("ROOMS"); //Check that room section is displayed Assert.assertTrue(roomsTab.roomsList.size()>1, "Rooms list is empty"); } /** * Create a room by using https requests to home server. * @param roomName */ private void createRoomWithByRequestsToMatrix(String roomName) throws IOException{ //1. Create room R with user A. riotUserAAccessToken=HttpsRequestsToMatrix.login(riotUserADisplayName, Constant.DEFAULT_USERPWD); testRoomId=HttpsRequestsToMatrix.createRoom(riotUserAAccessToken, roomName); //2. Invite user B. HttpsRequestsToMatrix.sendInvitationToUser(riotUserAAccessToken, testRoomId, MatrixUtilities.getMatrixIdFromDisplayName(riotUserBDisplayName)); } /** * Create a direct chatwith user B by using https requests to home server. * @param roomName * @throws IOException */ private void createDirectChatWithByRequestsToMatrix(String invitedMatrixId) throws IOException{ //1. Create room R with user A. riotUserAAccessToken=HttpsRequestsToMatrix.login(riotUserADisplayName, Constant.DEFAULT_USERPWD); testRoomId=HttpsRequestsToMatrix.createDirectChatRoom(riotUserAAccessToken, invitedMatrixId); //2. Invite user B. HttpsRequestsToMatrix.sendInvitationToUser(riotUserAAccessToken, testRoomId, MatrixUtilities.getMatrixIdFromDisplayName(riotUserBDisplayName)); } @AfterMethod(alwaysRun=true) private void leaveRoomAfterTest(Method m) throws InterruptedException, IOException{ switch (m.getName()) { case "duplicatedFavouritedRoomAccrossTabsTest": leaveAndForgetRoomUsers(); break; case "duplicatedDirectChatAccrossTabsTest": leaveAndForgetRoomUsers(); break; case "notDuplicatedLowPriorityRoomAccrossTabsTest": leaveAndForgetRoomUsers(); break; case "notDuplicatedDirectChatAccrossTabsTest": leaveAndForgetRoomUsers(); break; default: break; } } @AfterMethod(alwaysRun=true,groups={"1driver_android"}) private void restart1ApplicationAfterTest(Method m) throws InterruptedException{ restartApplication(appiumFactory.getAndroidDriver1()); } private void leaveAndForgetRoomUsers() throws IOException{ //leave room user A HttpsRequestsToMatrix.leaveRoom(riotUserAAccessToken, testRoomId); //forget room user A HttpsRequestsToMatrix.forgetRoom(riotUserAAccessToken, testRoomId); } /** * Log the good user if not.</br> Secure the test. */ @BeforeGroups("1checkuser") private void checkIfUserLogged() throws InterruptedException, FileNotFoundException, YamlException{ super.checkIfUserLoggedAndHomeServerSetUpAndroid(appiumFactory.getAndroidDriver1(), riotUserADisplayName, Constant.DEFAULT_USERPWD); } /** * Log the good user if not.</br> Secure the test. */ @BeforeGroups("1checkuser_default_hs") private void checkIfUserLoggedWithDefaultHs() throws InterruptedException, FileNotFoundException, YamlException{ super.checkIfUserLoggedAndHomeServerSetUpAndroid(appiumFactory.getAndroidDriver1(), riotUserADisplayName, Constant.DEFAULT_USERPWD,true); } }
VectorMobileTests/src/test/java/mobilestests_android/RiotUxReworkTests.java
package mobilestests_android; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Method; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import com.esotericsoftware.yamlbeans.YamlException; import pom_android.main_tabs.RiotFavouritesTabPageObjects; import pom_android.main_tabs.RiotHomePageTabObjects; import pom_android.main_tabs.RiotPeopleTabPageObjects; import pom_android.main_tabs.RiotRoomsTabPageObjects; import utility.Constant; import utility.HttpsRequestsToMatrix; import utility.MatrixUtilities; import utility.RiotParentTest; import utility.ScreenshotUtility; /** * Tests on Ux Rework. * @author jeangb */ @Listeners({ ScreenshotUtility.class }) public class RiotUxReworkTests extends RiotParentTest{ private String riotUserADisplayName="riotuser1"; private String riotUserBDisplayName="riotuser2"; private String riotUserAAccessToken; private String testRoomId; /** * 1. Create room A from home page. </br> * 2. Make it favourite. </br> * Check that the room is in the FAVOURITES section on the home page. </br> * 3. Hit FAVOURITES tab, and check that room A is present. </br> * 4. Hit PEOPLE tab, and check that room A is not present. </br> * 5. Hit ROOMS tab and check that room A is present. * @throws IOException, InterruptedException */ @Test(groups={"1driver_android","1checkuser"}, priority=0) public void duplicatedFavouritedRoomAccrossTabsTest() throws IOException, InterruptedException{ String roomName="favouriteRoomAutoTest"; //1. Create room A from home page. createRoomWithByRequestsToMatrix(roomName); //2. Make it favourite. RiotHomePageTabObjects homePage = new RiotHomePageTabObjects(appiumFactory.getAndroidDriver1()); homePage.clickOnContextMenuOnRoom(roomName, "Favourite"); //Check that the room is in the FAVOURITES section on the home page. homePage.checkRoomInCategory(roomName, homePage.favouritesSectionLayout,0); //3. Hit FAVOURITES tab, and check that room A is present. RiotFavouritesTabPageObjects favouritesPage=homePage.openFavouriteTab(); Assert.assertNotNull(favouritesPage.getRoomByName(roomName), "Room "+roomName+" not found in Favourites tab."); //4. Hit PEOPLE tab, and check that room A is not present. RiotPeopleTabPageObjects peopleTab=favouritesPage.openPeopleTab(); Assert.assertNull(peopleTab.getRoomByName(roomName), "Room "+roomName+" found in People tab and it shouldn't be."); //5. Hit ROOMS tab and check that room A is present. RiotRoomsTabPageObjects roomsTab = peopleTab.openRoomsTab(); Assert.assertNotNull(roomsTab.getRoomByName(roomName), "Room "+roomName+" not found in Rooms tab."); } /** * 1. Create direct chat with user B. </br> * 2. Make it favourite. </br> * Check that the room is in the FAVOURITES section on the home page. </br> * 3. Hit FAVOURITES tab, and check that direct chat with user B is present. </br> * 4. Hit PEOPLE tab and check that direct chat with user B is present. * 5. Hit ROOMS tab and check that room A is not present. * @throws IOException, InterruptedException */ @Test(groups={"1driver_android","1checkuser"}, priority=1) public void duplicatedDirectChatAccrossTabsTest() throws IOException, InterruptedException{ //1. Create direct chat with user B. createDirectChatWithByRequestsToMatrix(MatrixUtilities.getMatrixIdFromDisplayName(riotUserBDisplayName)); //2. Make it favourite. RiotHomePageTabObjects homePage = new RiotHomePageTabObjects(appiumFactory.getAndroidDriver1()); homePage.clickOnContextMenuOnRoom(riotUserBDisplayName, "Direct Chat"); homePage.clickOnContextMenuOnRoom(riotUserBDisplayName, "Favourite"); //Check that the room is in the FAVOURITES section on the home page. homePage.checkRoomInCategory(riotUserBDisplayName, homePage.favouritesSectionLayout,0); //3. Hit FAVOURITES tab, and check that direct chat with user B is present. RiotFavouritesTabPageObjects favouritesPage=homePage.openFavouriteTab(); Assert.assertNotNull(favouritesPage.getRoomByName(riotUserBDisplayName), "Direct chat "+riotUserBDisplayName+" not found in Favourites tab."); //4. Hit PEOPLE tab and check that direct chat with user B is present. RiotPeopleTabPageObjects peopleTab = favouritesPage.openPeopleTab(); Assert.assertNotNull(peopleTab.getRoomByName(riotUserBDisplayName), "Direct chat "+riotUserBDisplayName+" not found in People tab."); //5. Hit ROOMS tab and check that direct chat with user B is not present. RiotRoomsTabPageObjects roomsTab = peopleTab.openRoomsTab(); Assert.assertNull(roomsTab.getRoomByName(riotUserBDisplayName), "Direct chat "+riotUserBDisplayName+" found in Rooms tab and it shouldn't be."); } /** * 1. Create room A from home page. </br> * 2. Make it low priority. </br> * Check that the room is in the LOW PRIORITY section on the home page. </br> * 3. Hit ROOMS tab and check that room A is not present. * @throws IOException, InterruptedException */ @Test(groups={"1driver_android","1checkuser"}, priority=2) public void notDuplicatedLowPriorityRoomAccrossTabsTest() throws IOException, InterruptedException{ String roomName = "lowPriorityRoomTest"; //1. Create room A from home page. createRoomWithByRequestsToMatrix(roomName); //2. Make it low priority. RiotHomePageTabObjects homePage = new RiotHomePageTabObjects(appiumFactory.getAndroidDriver1()); homePage.clickOnContextMenuOnRoom(roomName, "De-prioritize"); //Check that the room is in the LOW PRIORITY section on the home page. homePage.checkRoomInCategory(roomName, homePage.lowPrioritySectionLayout,0); //3. Hit ROOMS tab and check that room A is not present RiotRoomsTabPageObjects roomsTab=homePage.openRoomsTab(); Assert.assertNull(roomsTab.getRoomByName(roomName), "Room "+roomName+" found in Rooms tab and it shouldn't be."); } /** * 1. Create direct chat with user B. </br> * 2. Make it low priority. </br> * Check that the room is in the LOW PRIORITY section on the home page. </br> * 3. Hit PEOPLE tab and check that direct chat with user B is not present. * @throws IOException, InterruptedException */ @Test(groups={"1driver_android","1checkuser"}, priority=3) public void notDuplicatedDirectChatAccrossTabsTest() throws IOException, InterruptedException{ //1. Create direct chat with user B. createDirectChatWithByRequestsToMatrix(MatrixUtilities.getMatrixIdFromDisplayName(riotUserBDisplayName)); //2. Make it low priority. RiotHomePageTabObjects homePage = new RiotHomePageTabObjects(appiumFactory.getAndroidDriver1()); homePage.clickOnContextMenuOnRoom(riotUserBDisplayName, "Direct Chat"); homePage.clickOnContextMenuOnRoom(riotUserBDisplayName, "De-prioritize"); //Check that the room is in the LOW PRIORITY section on the home page. homePage.checkRoomInCategory(riotUserBDisplayName, homePage.lowPrioritySectionLayout,0); //3. Hit PEOPLE tab and check that direct chat with user B is not present. RiotPeopleTabPageObjects peopleTab = homePage.openPeopleTab(); Assert.assertNull(peopleTab.getRoomByName(riotUserBDisplayName), "Direct chat "+riotUserBDisplayName+" found in People tab and it shouldn't be."); } /** * 1. Open people tab </br> * 2. Hit LOCAL ADDRESS BOOK sticky header </br> * Local contact list is displayed </br> * 3. Hit CONVERSATIONS sticky header </br> * Conversations list is displayed </br> * 4. Open rooms tab </br> * 5. Hit ROOM DIRECTORY stikcy header </br> * Check that room directory section is displayed </br> * 6. Hit ROOMS stikcy header </br> * Check that rooms displayed * @throws InterruptedException */ @Test(groups={"1driver_android","1checkuser"}, priority=4) public void stickyHeaderTest() throws InterruptedException{ //1. Open people tab RiotHomePageTabObjects homePageTab = new RiotHomePageTabObjects(appiumFactory.getAndroidDriver1()); RiotPeopleTabPageObjects peopleTab = homePageTab.openPeopleTab(); //2. Hit LOCAL ADDRESS BOOK sticky heade peopleTab.hitSectionHeader("LOCAL ADDRESS BOOK"); //Local contact list is displayed Assert.assertTrue(peopleTab.peopleList.size()>1, "Contacts list is empty"); //3. Hit CONVERSATIONS sticky header peopleTab.hitSectionHeader("CONVERSATIONS"); //Conversations list is displayed Assert.assertTrue(peopleTab.roomsList.size()>1,"Conversations list is empty"); //4. Open rooms tab RiotRoomsTabPageObjects roomsTab = peopleTab.openRoomsTab(); //5. Hit ROOM DIRECTORY stikcy header roomsTab.hitSectionHeader("ROOM DIRECTORY"); //Check that room directory section is displayed Assert.assertTrue(roomsTab.publicRoomsList.size()>1, "Rooms directory list is empty"); // 6. Hit ROOMS stikcy header roomsTab.hitSectionHeader("ROOMS"); //Check that room section is displayed Assert.assertTrue(roomsTab.roomsList.size()>1, "Rooms list is empty"); } /** * Brows tabs and check the filter search field text. * 1. Open home page tab, check that filter field text is 'Search for rooms' * 2. Open favourites tab, check that filter field text is 'Search for favourites' * 3. Open people tab, check that filter field text is 'Search for people' * 4. Open rooms tab, check that filter field text is 'Search for rooms' */ @Test(groups={"1driver_android","1checkuser"}, priority=5) public void filterOptionSearchTest() throws InterruptedException{ //1. Open home page tab, check that filter field text is 'Search for rooms' RiotHomePageTabObjects homePageTab = new RiotHomePageTabObjects(appiumFactory.getAndroidDriver1()); Assert.assertEquals(homePageTab.filterBarEditText.getText(), "Search for rooms"); //2. Open favourites tab, check that filter field text is 'Search for favourites' RiotFavouritesTabPageObjects favouritesTab= homePageTab.openFavouriteTab(); Assert.assertEquals(favouritesTab.filterBarEditText.getText(), "Search for favourites"); //3. Open people tab, check that filter field text is 'Search for people' RiotPeopleTabPageObjects peopleTab = favouritesTab.openPeopleTab(); Assert.assertEquals(peopleTab.filterBarEditText.getText(), "Search for people"); //4. Open rooms tab, check that filter field text is 'Search for rooms' RiotRoomsTabPageObjects roomsTab=peopleTab.openRoomsTab(); Assert.assertEquals(roomsTab.filterBarEditText.getText(), "Search for rooms"); } /** * Create a room by using https requests to home server. * @param roomName */ private void createRoomWithByRequestsToMatrix(String roomName) throws IOException{ //1. Create room R with user A. riotUserAAccessToken=HttpsRequestsToMatrix.login(riotUserADisplayName, Constant.DEFAULT_USERPWD); testRoomId=HttpsRequestsToMatrix.createRoom(riotUserAAccessToken, roomName); //2. Invite user B. HttpsRequestsToMatrix.sendInvitationToUser(riotUserAAccessToken, testRoomId, MatrixUtilities.getMatrixIdFromDisplayName(riotUserBDisplayName)); } /** * Create a direct chatwith user B by using https requests to home server. * @param roomName * @throws IOException */ private void createDirectChatWithByRequestsToMatrix(String invitedMatrixId) throws IOException{ //1. Create room R with user A. riotUserAAccessToken=HttpsRequestsToMatrix.login(riotUserADisplayName, Constant.DEFAULT_USERPWD); testRoomId=HttpsRequestsToMatrix.createDirectChatRoom(riotUserAAccessToken, invitedMatrixId); //2. Invite user B. HttpsRequestsToMatrix.sendInvitationToUser(riotUserAAccessToken, testRoomId, MatrixUtilities.getMatrixIdFromDisplayName(riotUserBDisplayName)); } @AfterMethod(alwaysRun=true) private void leaveRoomAfterTest(Method m) throws InterruptedException, IOException{ switch (m.getName()) { case "duplicatedFavouritedRoomAccrossTabsTest": leaveAndForgetRoomUsers(); break; case "duplicatedDirectChatAccrossTabsTest": leaveAndForgetRoomUsers(); break; case "notDuplicatedLowPriorityRoomAccrossTabsTest": leaveAndForgetRoomUsers(); break; case "notDuplicatedDirectChatAccrossTabsTest": leaveAndForgetRoomUsers(); break; default: break; } } private void leaveAndForgetRoomUsers() throws IOException{ //leave room user A HttpsRequestsToMatrix.leaveRoom(riotUserAAccessToken, testRoomId); //forget room user A HttpsRequestsToMatrix.forgetRoom(riotUserAAccessToken, testRoomId); } /** * Log the good user if not.</br> Secure the test. * @param myDriver * @param username * @param pwd */ @BeforeGroups("1checkuser") private void checkIfUserLogged() throws InterruptedException, FileNotFoundException, YamlException{ super.checkIfUserLoggedAndHomeServerSetUpAndroid(appiumFactory.getAndroidDriver1(), riotUserADisplayName, Constant.DEFAULT_USERPWD); } }
Improvements in RiotUxReworkTests for riot-android - Forces stickyHeaderTest to user default matrix.org homeserver - Added a restart riot function between each test
VectorMobileTests/src/test/java/mobilestests_android/RiotUxReworkTests.java
Improvements in RiotUxReworkTests for riot-android
<ide><path>ectorMobileTests/src/test/java/mobilestests_android/RiotUxReworkTests.java <ide> } <ide> <ide> /** <del> * 1. Open people tab </br> <del> * 2. Hit LOCAL ADDRESS BOOK sticky header </br> <del> * Local contact list is displayed </br> <del> * 3. Hit CONVERSATIONS sticky header </br> <del> * Conversations list is displayed </br> <del> * 4. Open rooms tab </br> <del> * 5. Hit ROOM DIRECTORY stikcy header </br> <del> * Check that room directory section is displayed </br> <del> * 6. Hit ROOMS stikcy header </br> <del> * Check that rooms displayed <del> * @throws InterruptedException <del> */ <del> @Test(groups={"1driver_android","1checkuser"}, priority=4) <del> public void stickyHeaderTest() throws InterruptedException{ <del> //1. Open people tab <del> RiotHomePageTabObjects homePageTab = new RiotHomePageTabObjects(appiumFactory.getAndroidDriver1()); <del> RiotPeopleTabPageObjects peopleTab = homePageTab.openPeopleTab(); <del> <del> //2. Hit LOCAL ADDRESS BOOK sticky heade <del> peopleTab.hitSectionHeader("LOCAL ADDRESS BOOK"); <del> //Local contact list is displayed <del> Assert.assertTrue(peopleTab.peopleList.size()>1, "Contacts list is empty"); <del> <del> //3. Hit CONVERSATIONS sticky header <del> peopleTab.hitSectionHeader("CONVERSATIONS"); <del> //Conversations list is displayed <del> Assert.assertTrue(peopleTab.roomsList.size()>1,"Conversations list is empty"); <del> <del> //4. Open rooms tab <del> RiotRoomsTabPageObjects roomsTab = peopleTab.openRoomsTab(); <del> //5. Hit ROOM DIRECTORY stikcy header <del> roomsTab.hitSectionHeader("ROOM DIRECTORY"); <del> //Check that room directory section is displayed <del> Assert.assertTrue(roomsTab.publicRoomsList.size()>1, "Rooms directory list is empty"); <del> <del> // 6. Hit ROOMS stikcy header <del> roomsTab.hitSectionHeader("ROOMS"); <del> //Check that room section is displayed <del> Assert.assertTrue(roomsTab.roomsList.size()>1, "Rooms list is empty"); <del> } <del> <del> /** <ide> * Brows tabs and check the filter search field text. <ide> * 1. Open home page tab, check that filter field text is 'Search for rooms' <ide> * 2. Open favourites tab, check that filter field text is 'Search for favourites' <ide> * 3. Open people tab, check that filter field text is 'Search for people' <ide> * 4. Open rooms tab, check that filter field text is 'Search for rooms' <ide> */ <del> @Test(groups={"1driver_android","1checkuser"}, priority=5) <add> @Test(groups={"1driver_android","1checkuser"}, priority=4) <ide> public void filterOptionSearchTest() throws InterruptedException{ <ide> //1. Open home page tab, check that filter field text is 'Search for rooms' <ide> RiotHomePageTabObjects homePageTab = new RiotHomePageTabObjects(appiumFactory.getAndroidDriver1()); <ide> } <ide> <ide> /** <add> * 1. Open people tab </br> <add> * 2. Hit LOCAL ADDRESS BOOK sticky header </br> <add> * Local contact list is displayed </br> <add> * 3. Hit CONVERSATIONS sticky header </br> <add> * Conversations list is displayed </br> <add> * 4. Open rooms tab </br> <add> * 5. Hit ROOM DIRECTORY stikcy header </br> <add> * Check that room directory section is displayed </br> <add> * 6. Hit ROOMS stikcy header </br> <add> * Check that rooms displayed <add> * @throws InterruptedException <add> */ <add> @Test(groups={"1driver_android","1checkuser_default_hs"}, priority=5) <add> public void stickyHeaderTest() throws InterruptedException{ <add> //1. Open people tab <add> RiotHomePageTabObjects homePageTab = new RiotHomePageTabObjects(appiumFactory.getAndroidDriver1()); <add> RiotPeopleTabPageObjects peopleTab = homePageTab.openPeopleTab(); <add> <add> //2. Hit LOCAL ADDRESS BOOK sticky heade <add> peopleTab.hitSectionHeader("LOCAL ADDRESS BOOK"); <add> //Local contact list is displayed <add> Assert.assertTrue(peopleTab.peopleList.size()>1, "Contacts list is empty"); <add> <add> //3. Hit CONVERSATIONS sticky header <add> peopleTab.hitSectionHeader("CONVERSATIONS"); <add> //Conversations list is displayed <add> Assert.assertTrue(peopleTab.roomsList.size()>1,"Conversations list is empty"); <add> <add> //4. Open rooms tab <add> RiotRoomsTabPageObjects roomsTab = peopleTab.openRoomsTab(); <add> //5. Hit ROOM DIRECTORY stikcy header <add> waitUntilDisplayed(appiumFactory.getAndroidDriver1(), "im.vector.alpha:id/section_loading", false, 10); <add> roomsTab.hitSectionHeader("ROOM DIRECTORY"); <add> //Check that room directory section is displayed <add> Assert.assertTrue(roomsTab.publicRoomsList.size()>1, "Rooms directory list is empty"); <add> <add> // 6. Hit ROOMS stikcy header <add> roomsTab.hitSectionHeader("ROOMS"); <add> //Check that room section is displayed <add> Assert.assertTrue(roomsTab.roomsList.size()>1, "Rooms list is empty"); <add> } <add> <add> /** <ide> * Create a room by using https requests to home server. <ide> * @param roomName <ide> */ <ide> break; <ide> } <ide> } <add> <add> @AfterMethod(alwaysRun=true,groups={"1driver_android"}) <add> private void restart1ApplicationAfterTest(Method m) throws InterruptedException{ <add> restartApplication(appiumFactory.getAndroidDriver1()); <add> } <add> <ide> private void leaveAndForgetRoomUsers() throws IOException{ <ide> //leave room user A <ide> HttpsRequestsToMatrix.leaveRoom(riotUserAAccessToken, testRoomId); <ide> <ide> /** <ide> * Log the good user if not.</br> Secure the test. <del> * @param myDriver <del> * @param username <del> * @param pwd <ide> */ <ide> @BeforeGroups("1checkuser") <ide> private void checkIfUserLogged() throws InterruptedException, FileNotFoundException, YamlException{ <ide> super.checkIfUserLoggedAndHomeServerSetUpAndroid(appiumFactory.getAndroidDriver1(), riotUserADisplayName, Constant.DEFAULT_USERPWD); <ide> } <add> <add> /** <add> * Log the good user if not.</br> Secure the test. <add> */ <add> @BeforeGroups("1checkuser_default_hs") <add> private void checkIfUserLoggedWithDefaultHs() throws InterruptedException, FileNotFoundException, YamlException{ <add> super.checkIfUserLoggedAndHomeServerSetUpAndroid(appiumFactory.getAndroidDriver1(), riotUserADisplayName, Constant.DEFAULT_USERPWD,true); <add> } <ide> }
Java
bsd-3-clause
a8445105fad1ff352bfa1d13f078b26968423c0b
0
NCIP/c3pr,NCIP/c3pr,NCIP/c3pr
package edu.duke.cabig.c3pr.domain; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.OrderBy; import javax.persistence.Table; import javax.persistence.Transient; import javax.persistence.UniqueConstraint; import org.apache.commons.collections15.functors.InstantiateFactory; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; import org.hibernate.annotations.Where; import org.springframework.context.MessageSource; import org.springframework.context.support.ResourceBundleMessageSource; import edu.duke.cabig.c3pr.constants.RandomizationType; import edu.duke.cabig.c3pr.domain.factory.ParameterizedInstantiateFactory; import edu.duke.cabig.c3pr.exception.C3PRCodedRuntimeException; import edu.duke.cabig.c3pr.exception.C3PRExceptionHelper; import edu.duke.cabig.c3pr.utils.ProjectedList; import edu.duke.cabig.c3pr.utils.StringUtils; import gov.nih.nci.cabig.ctms.collections.LazyListHelper; /** * The Class Epoch. * * @author Ram Chilukuri, Priyatam */ @Entity @Table(name = "epochs", uniqueConstraints = { @UniqueConstraint(columnNames = { "stu_id", "name" }) }) @GenericGenerator(name = "id-generator", strategy = "native", parameters = { @Parameter(name = "sequence", value = "EPOCHS_ID_SEQ") }) public class Epoch extends AbstractMutableDeletableDomainObject implements Comparable<Epoch> { /** The name. */ private String name; /** The description text. */ private String descriptionText; /** The study. */ private Study study; /** The epoch order. */ private Integer epochOrder; /** The lazy list helper. */ private LazyListHelper lazyListHelper; /** The randomization. */ private Randomization randomization; /** The randomized indicator. */ private Boolean randomizedIndicator = false; /** The eligibility criteria. */ private List<EligibilityCriteria> eligibilityCriteria; /** The c3 pr exception helper. */ private C3PRExceptionHelper c3PRExceptionHelper; /** The c3pr error messages. */ private MessageSource c3prErrorMessages; /** The accrual ceiling. */ private Integer accrualCeiling; /** The current book randomization entry position. */ private Integer currentBookRandomizationEntryPosition; /** The accrual indicator. */ private Boolean accrualIndicator = false; /** The reservation indicator. */ private Boolean reservationIndicator = false; /** The enrollment indicator. */ private Boolean enrollmentIndicator = false; /** The stratification indicator. */ private Boolean stratificationIndicator = false; /** The treatment indicator. */ private Boolean treatmentIndicator = false; /** * Factory method. * * @param epochName the epoch name * @param armNames the arm names * * @return the epoch */ public static Epoch createEpochWithArms(String epochName, String... armNames) { Epoch epoch = new Epoch(); epoch.setName(epochName); if (armNames.length == 0) { epoch.addNewArm(epochName); } else { for (String armName : armNames) { epoch.addNewArm(armName); } } return epoch; } /** * Creates the epoch. * * @param epochName the epoch name * * @return the epoch */ public static Epoch createEpoch(String epochName) { Epoch epoch = new Epoch(); epoch.setName(epochName); return epoch; } /** * Gets the requires arm. * * @return the requires arm */ @Transient public Boolean getRequiresArm() { return (this.getRandomizedIndicator() || this.getArms().size() > 0); } /** * Checks if is reserving. * * @return true, if is reserving */ @Transient public boolean isReserving() { return this.reservationIndicator; } /** * Gets the name. * * @return the name */ public String getName() { return name; } /** * Sets the name. * * @param name the new name */ public void setName(String name) { this.name = name; } /** * Gets the current book randomization entry position. * * @return the current book randomization entry position */ @Column(name = "current_bk_rand_entry") public Integer getCurrentBookRandomizationEntryPosition() { return currentBookRandomizationEntryPosition; } /** * Sets the current book randomization entry position. * * @param currentBookRandomizationEntryPosition the new current book randomization entry position */ public void setCurrentBookRandomizationEntryPosition( Integer currentBookRandomizationEntryPosition) { this.currentBookRandomizationEntryPosition = currentBookRandomizationEntryPosition; } /** * Gets the study. * * @return the study */ @ManyToOne @JoinColumn(name = "stu_id", nullable = false) public Study getStudy() { return study; } /** * Sets the study. * * @param study the new study */ public void setStudy(Study study) { this.study = study; } /** * Sets the description text. * * @param descriptionText the new description text */ public void setDescriptionText(String descriptionText) { this.descriptionText = descriptionText; } /** * Gets the description text. * * @return the description text */ public String getDescriptionText() { return descriptionText; } /* (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo(Epoch o) { if (this.equals(o)) return 0; else return 1; } /* (non-Javadoc) * @see edu.duke.cabig.c3pr.domain.AbstractMutableDeletableDomainObject#hashCode() */ @Override public int hashCode() { final int PRIME = 31; int result = super.hashCode(); result = PRIME * result; result = PRIME * result + ((name == null) ? 0 : name.hashCode()); return result; } /* (non-Javadoc) * @see edu.duke.cabig.c3pr.domain.AbstractMutableDeletableDomainObject#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; final Epoch other = (Epoch) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equalsIgnoreCase(other.name)) return false; return true; } /** * Gets the epoch order. * * @return the epoch order */ public Integer getEpochOrder() { return epochOrder; } /** * Sets the epoch order. * * @param epochOrder the new epoch order */ public void setEpochOrder(Integer epochOrder) { this.epochOrder = epochOrder; } // Code from Non-Treatment Epoch /** * Gets the accrual ceiling. * * @return the accrual ceiling */ public Integer getAccrualCeiling() { return accrualCeiling; } /** * Sets the accrual ceiling. * * @param accrualCeiling the new accrual ceiling */ public void setAccrualCeiling(Integer accrualCeiling) { this.accrualCeiling = accrualCeiling; } /** * Gets the accrual indicator. * * @return the accrual indicator */ public Boolean getAccrualIndicator() { return accrualIndicator; } /** * Sets the accrual indicator. * * @param accrualIndicator the new accrual indicator */ public void setAccrualIndicator(Boolean accrualIndicator) { this.accrualIndicator = accrualIndicator; } /** * Gets the enrollment indicator. * * @return the enrollment indicator */ public Boolean getEnrollmentIndicator() { return enrollmentIndicator; } /** * Sets the enrollment indicator. * * @param enrollmentIndicator the new enrollment indicator */ public void setEnrollmentIndicator(Boolean enrollmentIndicator) { this.enrollmentIndicator = enrollmentIndicator; } /** * Gets the reservation indicator. * * @return the reservation indicator */ public Boolean getReservationIndicator() { return reservationIndicator; } /** * Sets the reservation indicator. * * @param reservationIndicator the new reservation indicator */ public void setReservationIndicator(Boolean reservationIndicator) { this.reservationIndicator = reservationIndicator; } // No-Arg Constructor for Hibernate /** * Instantiates a new epoch. */ public Epoch() { currentBookRandomizationEntryPosition = new Integer(0); ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource(); resourceBundleMessageSource.setBasename("error_messages_multisite"); ResourceBundleMessageSource resourceBundleMessageSource1 = new ResourceBundleMessageSource(); resourceBundleMessageSource1.setBasename("error_messages_c3pr"); resourceBundleMessageSource1 .setParentMessageSource(resourceBundleMessageSource); this.c3prErrorMessages = resourceBundleMessageSource1; this.c3PRExceptionHelper = new C3PRExceptionHelper(c3prErrorMessages); lazyListHelper = new LazyListHelper(); lazyListHelper.add(StratificationCriterion.class, new InstantiateFactory<StratificationCriterion>( StratificationCriterion.class)); lazyListHelper.add(InclusionEligibilityCriteria.class, new ParameterizedInstantiateFactory<InclusionEligibilityCriteria>( InclusionEligibilityCriteria.class)); lazyListHelper .add( ExclusionEligibilityCriteria.class, new ParameterizedInstantiateFactory<ExclusionEligibilityCriteria>( ExclusionEligibilityCriteria.class)); lazyListHelper.add(Arm.class, new BiDirectionalInstantiateFactory<Arm>( Arm.class, this)); lazyListHelper.add(InclusionEligibilityCriteria.class, new InstantiateFactory<InclusionEligibilityCriteria>( InclusionEligibilityCriteria.class)); lazyListHelper.add(ExclusionEligibilityCriteria.class, new InstantiateFactory<ExclusionEligibilityCriteria>( ExclusionEligibilityCriteria.class)); lazyListHelper.add(StratumGroup.class, new InstantiateFactory<StratumGroup>(StratumGroup.class)); setEligibilityCriteria(new ArrayList<EligibilityCriteria>()); } // / LOGIC /** * Adds the new arm. * * @param armName the arm name */ public void addNewArm(String armName) { Arm arm = new Arm(); arm.setName(armName); addArm(arm); } /** * Adds the arm. * * @param arm the arm */ public void addArm(Arm arm) { for (Arm armPresent : getArms()) { if (armPresent.equals(arm)) { throw new RuntimeException( "arm with same name already exists in epoch"); } } getArms().add(arm); arm.setEpoch(this); } /* (non-Javadoc) * @see edu.duke.cabig.c3pr.domain.AbstractMutableDeletableDomainObject#setRetiredIndicatorAsTrue() */ @Override @Transient /* * settting the retired_indicator for every child object to true */ public void setRetiredIndicatorAsTrue() { // setting the indicator for epoch super.setRetiredIndicatorAsTrue(); // setting the indicator for its arms List<Arm> armList = this.getArms(); Arm arm; Iterator armIter = armList.iterator(); while (armIter.hasNext()) { arm = (Arm) armIter.next(); arm.setRetiredIndicatorAsTrue(); } // setting the indicator for its eligibilityCriteria List<EligibilityCriteria> ecList = this.getEligibilityCriteria(); EligibilityCriteria ec; Iterator ecIter = ecList.iterator(); while (ecIter.hasNext()) { ec = (EligibilityCriteria) ecIter.next(); ec.setRetiredIndicatorAsTrue(); } List<InclusionEligibilityCriteria> iecList = this .getInclusionEligibilityCriteria(); InclusionEligibilityCriteria iec; Iterator iecIter = iecList.iterator(); while (iecIter.hasNext()) { iec = (InclusionEligibilityCriteria) iecIter.next(); iec.setRetiredIndicatorAsTrue(); } List<ExclusionEligibilityCriteria> eecList = this .getExclusionEligibilityCriteria(); ExclusionEligibilityCriteria eec; Iterator eecIter = eecList.iterator(); while (eecIter.hasNext()) { eec = (ExclusionEligibilityCriteria) eecIter.next(); eec.setRetiredIndicatorAsTrue(); } // set strGrps and Randomizations if (this.getRandomization() != null) { this.getRandomization().setRetiredIndicatorAsTrue(); } // set strCri List<StratificationCriterion> scList = this.getStratificationCriteria(); StratificationCriterion sc; Iterator scIter = scList.iterator(); while (scIter.hasNext()) { sc = (StratificationCriterion) scIter.next(); sc.setRetiredIndicatorAsTrue(); } List<StratumGroup> sgList = this.getStratumGroups(); StratumGroup sg; Iterator sgIter = sgList.iterator(); while (sgIter.hasNext()) { sg = (StratumGroup) sgIter.next(); sg.setRetiredIndicatorAsTrue(); } } /** * Checks if is multiple arms. * * @return true, if is multiple arms */ @Transient public boolean isMultipleArms() { return getArms().size() > 1; } /** * Gets the arms internal. * * @return the arms internal */ @OneToMany(fetch = FetchType.LAZY) @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) @JoinColumn(name = "eph_id") @Where(clause = "retired_indicator = 'false'") public List<Arm> getArmsInternal() { return lazyListHelper.getInternalList(Arm.class); } /** * Gets the arms. * * @return the arms */ @Transient public List<Arm> getArms() { return lazyListHelper.getLazyList(Arm.class); } /** * Sets the arms internal. * * @param arms the new arms internal */ public void setArmsInternal(List<Arm> arms) { lazyListHelper.setInternalList(Arm.class, arms); } /** * Sets the arms. * * @param arms the new arms */ public void setArms(List<Arm> arms) { lazyListHelper.setInternalList(Arm.class, arms); } /** * Adds the eligibility criterion. * * @param eligibilityCriterion the eligibility criterion */ public void addEligibilityCriterion(EligibilityCriteria eligibilityCriterion) { this.getEligibilityCriteria().add(eligibilityCriterion); } /** * Gets the stratification criteria internal. * * @return the stratification criteria internal */ @OneToMany(fetch = FetchType.LAZY) @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) @JoinColumn(name = "EPH_ID") @Where(clause = "retired_indicator = 'false'") public List<StratificationCriterion> getStratificationCriteriaInternal() { return lazyListHelper.getInternalList(StratificationCriterion.class); } /** * Gets the stratification criteria. * * @return the stratification criteria */ @Transient public List<StratificationCriterion> getStratificationCriteria() { return lazyListHelper.getLazyList(StratificationCriterion.class); } /** * Sets the stratification criteria. * * @param stratificationCriteria the new stratification criteria */ public void setStratificationCriteria( List<StratificationCriterion> stratificationCriteria) { lazyListHelper.setInternalList(StratificationCriterion.class, stratificationCriteria); } /** * Sets the stratification criteria internal. * * @param stratificationCriteria the new stratification criteria internal */ public void setStratificationCriteriaInternal( List<StratificationCriterion> stratificationCriteria) { lazyListHelper.setInternalList(StratificationCriterion.class, stratificationCriteria); } /** * Adds the stratification criterion. * * @param stratificationCriterion the stratification criterion */ public void addStratificationCriterion( StratificationCriterion stratificationCriterion) { this.getStratificationCriteria().add(stratificationCriterion); } /** * Gets the eligibility criteria. * * @return the eligibility criteria */ @OneToMany @Cascade( { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) @JoinColumn(name = "EPH_ID") @Where(clause = "retired_indicator = 'false'") public List<EligibilityCriteria> getEligibilityCriteria() { return eligibilityCriteria; } /** * Sets the eligibility criteria. * * @param eligibilityCriteria the new eligibility criteria */ public void setEligibilityCriteria(List<EligibilityCriteria> eligibilityCriteria) { this.eligibilityCriteria = eligibilityCriteria; lazyListHelper.setInternalList(InclusionEligibilityCriteria.class, new ProjectedList<InclusionEligibilityCriteria>(this.eligibilityCriteria, InclusionEligibilityCriteria.class)); lazyListHelper .setInternalList(ExclusionEligibilityCriteria.class, new ProjectedList<ExclusionEligibilityCriteria>( this.eligibilityCriteria, ExclusionEligibilityCriteria.class)); } /** * Gets the inclusion eligibility criteria. * * @return the inclusion eligibility criteria */ @Transient public List<InclusionEligibilityCriteria> getInclusionEligibilityCriteria() { return lazyListHelper.getLazyList(InclusionEligibilityCriteria.class); } /** * Sets the inclusion eligibility criteria. * * @param inclusionEligibilityCriteria the new inclusion eligibility criteria */ public void setInclusionEligibilityCriteria( List<InclusionEligibilityCriteria> inclusionEligibilityCriteria) { // do nothing } /** * Gets the exclusion eligibility criteria. * * @return the exclusion eligibility criteria */ @Transient public List<ExclusionEligibilityCriteria> getExclusionEligibilityCriteria() { return lazyListHelper.getLazyList(ExclusionEligibilityCriteria.class); } /** * Sets the exclusion eligibility criteria. * * @param exclusionEligibilityCriteria the new exclusion eligibility criteria */ public void setExclusionEligibilityCriteria( List<ExclusionEligibilityCriteria> exclusionEligibilityCriteria) { // do nothing } /** * Gets the stratum groups internal. * * @return the stratum groups internal */ @OneToMany(fetch = FetchType.LAZY) @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) @JoinColumn(name = "epochs_id") @Where(clause = "retired_indicator = 'false'") @OrderBy("stratumGroupNumber") public List<StratumGroup> getStratumGroupsInternal() { return lazyListHelper.getInternalList(StratumGroup.class); } /** * Sets the stratum groups internal. * * @param stratumGroup the new stratum groups internal */ public void setStratumGroupsInternal(List<StratumGroup> stratumGroup) { lazyListHelper.setInternalList(StratumGroup.class, stratumGroup); } /** * Gets the stratum groups. * * @return the stratum groups */ @Transient public List<StratumGroup> getStratumGroups() { return lazyListHelper.getLazyList(StratumGroup.class); } /** * Sets the stratum groups. * * @param stratumGroup the new stratum groups */ public void setStratumGroups(List<StratumGroup> stratumGroup) { } /** * Gets the randomization. * * @return the randomization */ @OneToOne @JoinColumn(name = "rndm_id") @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) public Randomization getRandomization() { return randomization; } /** * Sets the randomization. * * @param randomization the new randomization */ public void setRandomization(Randomization randomization) { this.randomization = randomization; } /** * Checks for book randomization entry. * * @return true, if successful */ @Transient public boolean hasBookRandomizationEntry() { if (this.getRandomization() instanceof BookRandomization) { if (((((BookRandomization) this.getRandomization()) .getBookRandomizationEntry()) != null) && ((BookRandomization) this.getRandomization()) .getBookRandomizationEntry().size() > 0) { return true; } } return false; } /** * Gets the stratum group for ans combination. * * @param scacList the scac list * * @return the stratum group for ans combination */ @Transient /* * This method iterates thru the stratum groups for the treatmentEpoch and * finds the one that has the same stratificationCriAnsCombination as the * one passed in and returns it. returns null if no matching stratum group * is found */ public StratumGroup getStratumGroupForAnsCombination( List<StratificationCriterionAnswerCombination> scacList) { StratumGroup sg = new StratumGroup(); sg.getStratificationCriterionAnswerCombination().addAll(scacList); List<StratumGroup> sgList; sgList = this.getStratumGroups(); Iterator iter = sgList.iterator(); StratumGroup sgCurr; while (iter.hasNext()) { sgCurr = (StratumGroup) iter.next(); if (sgCurr.equals(sg)) { return sgCurr; } } return null; } /** * Gets the stratum group by number. * * @param number the number * * @return the stratum group by number */ @Transient /* * This method iterates thru the stratum groups for the Epoch and * finds the one that has the same stratum group number as the one passed in * and returns it. returns null if no matching stratum group is found */ public StratumGroup getStratumGroupByNumber(Integer number) { for (StratumGroup sgCurr : this.getStratumGroups()) { if (sgCurr.getStratumGroupNumber().equals(number)) { return sgCurr; } } return null; } /** * Checks for stratification. * * @return true, if successful */ @Transient public boolean hasStratification() { return (getStratificationCriteria().size() > 0); } /** * Checks for stratum groups. * * @return true, if successful */ @Transient public boolean hasStratumGroups() { return (getStratumGroups().size() > 0); } /** * Checks for eligibility. * * @return true, if successful */ @Transient public boolean hasEligibility() { return (getEligibilityCriteria().size() > 0); } /** * Gets the randomized indicator. * * @return the randomized indicator */ public Boolean getRandomizedIndicator() { return randomizedIndicator; } /** * Sets the randomized indicator. * * @param randomizedIndicator the new randomized indicator */ public void setRandomizedIndicator(Boolean randomizedIndicator) { this.randomizedIndicator = randomizedIndicator; } /** * Evaluate status. * * @param errors the errors * * @return true, if successful * * @throws C3PRCodedRuntimeException the c3 pr coded runtime exception */ public void evaluateStatus(List<Error> errors) throws C3PRCodedRuntimeException { evaluateStratificationDataEntryStatus(errors); evaluateRandomizationDataEntryStatus(errors); evaluateEligibilityDataEntryStatus(errors); } /** * Evaluate stratification data entry status. * * @param errors the errors * * @return true, if successful * * @throws C3PRCodedRuntimeException the c3 pr coded runtime exception */ public boolean evaluateStratificationDataEntryStatus(List<Error> errors) throws C3PRCodedRuntimeException { if (this.getStratificationIndicator()) { if (!this.hasStratification() || !this.hasStratumGroups()) { errors.add(new Error(getC3PRExceptionHelper().getRuntimeException( getCode("C3PR.EXCEPTION.STUDY.DATAENTRY.MISSING.STRATIFICATION_CRITERIA_OR_STRATUM_GROUPS_FOR_RANDOMIZED_EPOCH.CODE"), new String[] { this.getName() }).getMessage())); } } return true; } /** * Evaluate randomization data entry status. * * @param errors the errors * * @return true, if successful * * @throws C3PRCodedRuntimeException the c3 pr coded runtime exception */ public boolean evaluateRandomizationDataEntryStatus(List<Error> errors) throws C3PRCodedRuntimeException { if (this.getRandomizedIndicator()) { if ((this.getArms().size() < 2)||(this.getRandomization() == null)) { if (this.getArms().size() < 2) { errors.add(new Error(getC3PRExceptionHelper().getRuntimeException( getCode("C3PR.EXCEPTION.STUDY.DATAENTRY.MISSING.ATLEAST_2_ARMS_FOR_RANDOMIZED_EPOCH.CODE"), new String[] { this.getName() }).getMessage())); } } } if (this.study.getRandomizationType() == (RandomizationType.BOOK)) { if (this.getRandomizedIndicator()) { if (!this.hasBookRandomizationEntry()) { errors.add(new Error(getC3PRExceptionHelper().getRuntimeException( getCode("C3PR.EXCEPTION.STUDY.DATAENTRY.MISSING.BOOK_ENTRIES_FOR_BOOK_RANDOMIZED_EPOCH.CODE"), new String[] { this.getName() }).getMessage())); } } } if (this.study.getRandomizationType() == (RandomizationType.PHONE_CALL)) { if (this.getRandomizedIndicator()) { Randomization randomization = this.getRandomization(); if (randomization instanceof PhoneCallRandomization) { if (StringUtils .isBlank(((PhoneCallRandomization) randomization) .getPhoneNumber())) { errors.add(new Error(getC3PRExceptionHelper().getRuntimeException( getCode("C3PR.EXCEPTION.STUDY.DATAENTRY.MISSING.PHONE_NUMBER_FOR_PHONE_CALL_RANDOMIZED_EPOCH.CODE"), new String[] { this.getName() }).getMessage())); } } } } return true; } /** * Evaluate eligibility data entry status. * * @param errors the errors * * @return true, if successful * * @throws C3PRCodedRuntimeException the c3 pr coded runtime exception */ public boolean evaluateEligibilityDataEntryStatus(List<Error> errors) throws C3PRCodedRuntimeException { // Default returns true unless more information is obtained return true; } /** * Gets the code. * * @param errortypeString the errortype string * * @return the code */ @Transient public int getCode(String errortypeString) { return Integer.parseInt(this.c3prErrorMessages.getMessage( errortypeString, null, null)); } /** * Gets the c3 pr exception helper. * * @return the c3 pr exception helper */ @Transient public C3PRExceptionHelper getC3PRExceptionHelper() { return c3PRExceptionHelper; } /** * Sets the exception helper. * * @param c3PRExceptionHelper the new exception helper */ public void setExceptionHelper(C3PRExceptionHelper c3PRExceptionHelper) { this.c3PRExceptionHelper = c3PRExceptionHelper; } /** * Gets the c3pr error messages. * * @return the c3pr error messages */ @Transient public MessageSource getC3prErrorMessages() { return c3prErrorMessages; } /** * Sets the c3pr error messages. * * @param errorMessages the new c3pr error messages */ public void setC3prErrorMessages(MessageSource errorMessages) { c3prErrorMessages = errorMessages; } /** * Checks if is enrolling. * * @return true, if is enrolling */ @Transient public boolean isEnrolling() { return enrollmentIndicator; } /** * Gets the stratification indicator. * * @return the stratification indicator */ public Boolean getStratificationIndicator() { return stratificationIndicator; } /** * Sets the stratification indicator. * * @param stratificationIndicator the new stratification indicator */ public void setStratificationIndicator(Boolean stratificationIndicator) { this.stratificationIndicator = stratificationIndicator; } /** * Gets the treatment indicator. * * @return the treatment indicator */ public Boolean getTreatmentIndicator() { return treatmentIndicator; } /** * Sets the treatment indicator. * * @param treatmentIndicator the new treatment indicator */ public void setTreatmentIndicator(Boolean treatmentIndicator) { this.treatmentIndicator = treatmentIndicator; } /** * Gets the arm by name. * * @param armName the arm name * * @return the arm by name */ @Transient public Arm getArmByName(String armName){ for(Arm localArm:this.getArms()){ if(armName.equals(localArm.getName())){ return localArm; } } return null; } /** * Generate stratum groups. * * @param request the request * @param commandObj the command obj * @param error the error * @param epochCountIndex the epoch count index */ public void generateStratumGroups() { ArrayList<StratumGroup> stratumGroupList; this.getStratumGroups().clear(); int stratificationCriterionSize = this.getStratificationCriteria().size(); if (stratificationCriterionSize > 0) { StratificationCriterionPermissibleAnswer permissibleAnswersArray[][] = new StratificationCriterionPermissibleAnswer[stratificationCriterionSize][]; List<StratificationCriterionPermissibleAnswer> tempAnswersList; // creating a 2d array of answers for every treatment epoch for (int i = 0; i < stratificationCriterionSize; i++) { tempAnswersList = this.getStratificationCriteria().get(i) .getPermissibleAnswers(); permissibleAnswersArray[i] = new StratificationCriterionPermissibleAnswer[tempAnswersList .size()]; for (int j = 0; j < tempAnswersList.size(); j++) { permissibleAnswersArray[i][j] = tempAnswersList.get(j); } } stratumGroupList = stratumGroupCombinationGenerator(permissibleAnswersArray, 0, new ArrayList<StratumGroup>(), new ArrayList<StratificationCriterionAnswerCombination>()); this.getStratumGroups().addAll(stratumGroupList); } } /** * Stratum group combination generator. * recursive method which computes all possible combinations * of sc and scpa and creates a list of stratum Groups for the same. * * @param epoch the epoch * @param permissibleAnswersArray the permissible answers array * @param intRecurseLevel the int recurse level * @param stratumGroupList the stratum group list * @param generatedAnswerCombinationList the generated answer combination list * * @return the array list< stratum group> */ private ArrayList<StratumGroup> stratumGroupCombinationGenerator(StratificationCriterionPermissibleAnswer[][] permissibleAnswersArray, int intRecurseLevel, ArrayList<StratumGroup> stratumGroupList, ArrayList<StratificationCriterionAnswerCombination> generatedAnswerCombinationList) { StratificationCriterionAnswerCombination stratificationCriterionAnswerCombination ; ArrayList<StratificationCriterionAnswerCombination> stratificationCriterionAnswerCombinationList; int numberOfStratumGroups = 0; for (int i = 0; i < permissibleAnswersArray[intRecurseLevel].length; i++) { stratificationCriterionAnswerCombination = new StratificationCriterionAnswerCombination(); stratificationCriterionAnswerCombinationList = new ArrayList<StratificationCriterionAnswerCombination>(); stratificationCriterionAnswerCombination .setStratificationCriterionPermissibleAnswer(permissibleAnswersArray[intRecurseLevel][i]); stratificationCriterionAnswerCombination.setStratificationCriterion(this .getStratificationCriteria().get(intRecurseLevel)); if (!generatedAnswerCombinationList.isEmpty()) { stratificationCriterionAnswerCombinationList.addAll(generatedAnswerCombinationList); } stratificationCriterionAnswerCombinationList.add(stratificationCriterionAnswerCombination); if (intRecurseLevel < permissibleAnswersArray.length - 1) { // stepping into the next question stratumGroupList = stratumGroupCombinationGenerator(permissibleAnswersArray, intRecurseLevel + 1, stratumGroupList, stratificationCriterionAnswerCombinationList); } else { // ran out of questions and hence now i have a combination of answers to save. numberOfStratumGroups = stratumGroupList.size(); stratumGroupList.add(numberOfStratumGroups, new StratumGroup()); stratumGroupList.get(numberOfStratumGroups) .getStratificationCriterionAnswerCombination().addAll( cloneStratificationCriterionAnswerCombination(stratificationCriterionAnswerCombinationList)); stratumGroupList.get(numberOfStratumGroups).setStratumGroupNumber(numberOfStratumGroups); } } return stratumGroupList; } /** * Clones the StratificationCriterionAnswerCombination for the comboGenerator. * * @param stratificationCriterionAnswerCombinationList the stratification criterion answer combination list * * @return the list< stratification criterion answer combination> */ private List<StratificationCriterionAnswerCombination> cloneStratificationCriterionAnswerCombination( List<StratificationCriterionAnswerCombination> stratificationCriterionAnswerCombinationList) { List<StratificationCriterionAnswerCombination> clonedList = new ArrayList<StratificationCriterionAnswerCombination>(); Iterator<StratificationCriterionAnswerCombination> iter = stratificationCriterionAnswerCombinationList .iterator(); while (iter.hasNext()) { clonedList.add(new StratificationCriterionAnswerCombination(iter .next())); } return clonedList; } }
codebase/projects/core/src/java/edu/duke/cabig/c3pr/domain/Epoch.java
package edu.duke.cabig.c3pr.domain; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.OrderBy; import javax.persistence.Table; import javax.persistence.Transient; import javax.persistence.UniqueConstraint; import org.apache.commons.collections15.functors.InstantiateFactory; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; import org.hibernate.annotations.Where; import org.springframework.context.MessageSource; import org.springframework.context.support.ResourceBundleMessageSource; import edu.duke.cabig.c3pr.constants.RandomizationType; import edu.duke.cabig.c3pr.domain.factory.ParameterizedInstantiateFactory; import edu.duke.cabig.c3pr.exception.C3PRCodedRuntimeException; import edu.duke.cabig.c3pr.exception.C3PRExceptionHelper; import edu.duke.cabig.c3pr.utils.ProjectedList; import edu.duke.cabig.c3pr.utils.StringUtils; import gov.nih.nci.cabig.ctms.collections.LazyListHelper; // TODO: Auto-generated Javadoc /** * The Class Epoch. * * @author Ram Chilukuri, Priyatam */ @Entity @Table(name = "epochs", uniqueConstraints = { @UniqueConstraint(columnNames = { "stu_id", "name" }) }) @GenericGenerator(name = "id-generator", strategy = "native", parameters = { @Parameter(name = "sequence", value = "EPOCHS_ID_SEQ") }) public class Epoch extends AbstractMutableDeletableDomainObject implements Comparable<Epoch> { /** The name. */ private String name; /** The description text. */ private String descriptionText; /** The study. */ private Study study; /** The epoch order. */ private Integer epochOrder; /** The lazy list helper. */ private LazyListHelper lazyListHelper; /** The randomization. */ private Randomization randomization; /** The randomized indicator. */ private Boolean randomizedIndicator = false; /** The eligibility criteria. */ private List<EligibilityCriteria> eligibilityCriteria; /** The c3 pr exception helper. */ private C3PRExceptionHelper c3PRExceptionHelper; /** The c3pr error messages. */ private MessageSource c3prErrorMessages; /** The accrual ceiling. */ private Integer accrualCeiling; /** The current book randomization entry position. */ private Integer currentBookRandomizationEntryPosition; /** The accrual indicator. */ private Boolean accrualIndicator = false; /** The reservation indicator. */ private Boolean reservationIndicator = false; /** The enrollment indicator. */ private Boolean enrollmentIndicator = false; /** The stratification indicator. */ private Boolean stratificationIndicator = false; /** The treatment indicator. */ private Boolean treatmentIndicator = false; /** * Factory method. * * @param epochName the epoch name * @param armNames the arm names * * @return the epoch */ public static Epoch createEpochWithArms(String epochName, String... armNames) { Epoch epoch = new Epoch(); epoch.setName(epochName); if (armNames.length == 0) { epoch.addNewArm(epochName); } else { for (String armName : armNames) { epoch.addNewArm(armName); } } return epoch; } /** * Creates the epoch. * * @param epochName the epoch name * * @return the epoch */ public static Epoch createEpoch(String epochName) { Epoch epoch = new Epoch(); epoch.setName(epochName); return epoch; } /** * Gets the requires arm. * * @return the requires arm */ @Transient public Boolean getRequiresArm() { return (this.getRandomizedIndicator() || this.getArms().size() > 0); } /** * Checks if is reserving. * * @return true, if is reserving */ @Transient public boolean isReserving() { return this.reservationIndicator; } /** * Gets the name. * * @return the name */ public String getName() { return name; } /** * Sets the name. * * @param name the new name */ public void setName(String name) { this.name = name; } /** * Gets the current book randomization entry position. * * @return the current book randomization entry position */ @Column(name = "current_bk_rand_entry") public Integer getCurrentBookRandomizationEntryPosition() { return currentBookRandomizationEntryPosition; } /** * Sets the current book randomization entry position. * * @param currentBookRandomizationEntryPosition the new current book randomization entry position */ public void setCurrentBookRandomizationEntryPosition( Integer currentBookRandomizationEntryPosition) { this.currentBookRandomizationEntryPosition = currentBookRandomizationEntryPosition; } /** * Gets the study. * * @return the study */ @ManyToOne @JoinColumn(name = "stu_id", nullable = false) public Study getStudy() { return study; } /** * Sets the study. * * @param study the new study */ public void setStudy(Study study) { this.study = study; } /** * Sets the description text. * * @param descriptionText the new description text */ public void setDescriptionText(String descriptionText) { this.descriptionText = descriptionText; } /** * Gets the description text. * * @return the description text */ public String getDescriptionText() { return descriptionText; } /* (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo(Epoch o) { if (this.equals(o)) return 0; else return 1; } /* (non-Javadoc) * @see edu.duke.cabig.c3pr.domain.AbstractMutableDeletableDomainObject#hashCode() */ @Override public int hashCode() { final int PRIME = 31; int result = super.hashCode(); result = PRIME * result; result = PRIME * result + ((name == null) ? 0 : name.hashCode()); return result; } /* (non-Javadoc) * @see edu.duke.cabig.c3pr.domain.AbstractMutableDeletableDomainObject#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; final Epoch other = (Epoch) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equalsIgnoreCase(other.name)) return false; return true; } /** * Gets the epoch order. * * @return the epoch order */ public Integer getEpochOrder() { return epochOrder; } /** * Sets the epoch order. * * @param epochOrder the new epoch order */ public void setEpochOrder(Integer epochOrder) { this.epochOrder = epochOrder; } // Code from Non-Treatment Epoch /** * Gets the accrual ceiling. * * @return the accrual ceiling */ public Integer getAccrualCeiling() { return accrualCeiling; } /** * Sets the accrual ceiling. * * @param accrualCeiling the new accrual ceiling */ public void setAccrualCeiling(Integer accrualCeiling) { this.accrualCeiling = accrualCeiling; } /** * Gets the accrual indicator. * * @return the accrual indicator */ public Boolean getAccrualIndicator() { return accrualIndicator; } /** * Sets the accrual indicator. * * @param accrualIndicator the new accrual indicator */ public void setAccrualIndicator(Boolean accrualIndicator) { this.accrualIndicator = accrualIndicator; } /** * Gets the enrollment indicator. * * @return the enrollment indicator */ public Boolean getEnrollmentIndicator() { return enrollmentIndicator; } /** * Sets the enrollment indicator. * * @param enrollmentIndicator the new enrollment indicator */ public void setEnrollmentIndicator(Boolean enrollmentIndicator) { this.enrollmentIndicator = enrollmentIndicator; } /** * Gets the reservation indicator. * * @return the reservation indicator */ public Boolean getReservationIndicator() { return reservationIndicator; } /** * Sets the reservation indicator. * * @param reservationIndicator the new reservation indicator */ public void setReservationIndicator(Boolean reservationIndicator) { this.reservationIndicator = reservationIndicator; } // No-Arg Constructor for Hibernate /** * Instantiates a new epoch. */ public Epoch() { currentBookRandomizationEntryPosition = new Integer(0); ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource(); resourceBundleMessageSource.setBasename("error_messages_multisite"); ResourceBundleMessageSource resourceBundleMessageSource1 = new ResourceBundleMessageSource(); resourceBundleMessageSource1.setBasename("error_messages_c3pr"); resourceBundleMessageSource1 .setParentMessageSource(resourceBundleMessageSource); this.c3prErrorMessages = resourceBundleMessageSource1; this.c3PRExceptionHelper = new C3PRExceptionHelper(c3prErrorMessages); lazyListHelper = new LazyListHelper(); lazyListHelper.add(StratificationCriterion.class, new InstantiateFactory<StratificationCriterion>( StratificationCriterion.class)); lazyListHelper.add(InclusionEligibilityCriteria.class, new ParameterizedInstantiateFactory<InclusionEligibilityCriteria>( InclusionEligibilityCriteria.class)); lazyListHelper .add( ExclusionEligibilityCriteria.class, new ParameterizedInstantiateFactory<ExclusionEligibilityCriteria>( ExclusionEligibilityCriteria.class)); lazyListHelper.add(Arm.class, new BiDirectionalInstantiateFactory<Arm>( Arm.class, this)); lazyListHelper.add(InclusionEligibilityCriteria.class, new InstantiateFactory<InclusionEligibilityCriteria>( InclusionEligibilityCriteria.class)); lazyListHelper.add(ExclusionEligibilityCriteria.class, new InstantiateFactory<ExclusionEligibilityCriteria>( ExclusionEligibilityCriteria.class)); lazyListHelper.add(StratumGroup.class, new InstantiateFactory<StratumGroup>(StratumGroup.class)); setEligibilityCriteria(new ArrayList<EligibilityCriteria>()); } // / LOGIC /** * Adds the new arm. * * @param armName the arm name */ public void addNewArm(String armName) { Arm arm = new Arm(); arm.setName(armName); addArm(arm); } /** * Adds the arm. * * @param arm the arm */ public void addArm(Arm arm) { for (Arm armPresent : getArms()) { if (armPresent.equals(arm)) { throw new RuntimeException( "arm with same name already exists in epoch"); } } getArms().add(arm); arm.setEpoch(this); } /* (non-Javadoc) * @see edu.duke.cabig.c3pr.domain.AbstractMutableDeletableDomainObject#setRetiredIndicatorAsTrue() */ @Override @Transient /* * settting the retired_indicator for every child object to true */ public void setRetiredIndicatorAsTrue() { // setting the indicator for epoch super.setRetiredIndicatorAsTrue(); // setting the indicator for its arms List<Arm> armList = this.getArms(); Arm arm; Iterator armIter = armList.iterator(); while (armIter.hasNext()) { arm = (Arm) armIter.next(); arm.setRetiredIndicatorAsTrue(); } // setting the indicator for its eligibilityCriteria List<EligibilityCriteria> ecList = this.getEligibilityCriteria(); EligibilityCriteria ec; Iterator ecIter = ecList.iterator(); while (ecIter.hasNext()) { ec = (EligibilityCriteria) ecIter.next(); ec.setRetiredIndicatorAsTrue(); } List<InclusionEligibilityCriteria> iecList = this .getInclusionEligibilityCriteria(); InclusionEligibilityCriteria iec; Iterator iecIter = iecList.iterator(); while (iecIter.hasNext()) { iec = (InclusionEligibilityCriteria) iecIter.next(); iec.setRetiredIndicatorAsTrue(); } List<ExclusionEligibilityCriteria> eecList = this .getExclusionEligibilityCriteria(); ExclusionEligibilityCriteria eec; Iterator eecIter = eecList.iterator(); while (eecIter.hasNext()) { eec = (ExclusionEligibilityCriteria) eecIter.next(); eec.setRetiredIndicatorAsTrue(); } // set strGrps and Randomizations if (this.getRandomization() != null) { this.getRandomization().setRetiredIndicatorAsTrue(); } // set strCri List<StratificationCriterion> scList = this.getStratificationCriteria(); StratificationCriterion sc; Iterator scIter = scList.iterator(); while (scIter.hasNext()) { sc = (StratificationCriterion) scIter.next(); sc.setRetiredIndicatorAsTrue(); } List<StratumGroup> sgList = this.getStratumGroups(); StratumGroup sg; Iterator sgIter = sgList.iterator(); while (sgIter.hasNext()) { sg = (StratumGroup) sgIter.next(); sg.setRetiredIndicatorAsTrue(); } } /** * Checks if is multiple arms. * * @return true, if is multiple arms */ @Transient public boolean isMultipleArms() { return getArms().size() > 1; } /** * Gets the arms internal. * * @return the arms internal */ @OneToMany(fetch = FetchType.LAZY) @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) @JoinColumn(name = "eph_id") @Where(clause = "retired_indicator = 'false'") public List<Arm> getArmsInternal() { return lazyListHelper.getInternalList(Arm.class); } /** * Gets the arms. * * @return the arms */ @Transient public List<Arm> getArms() { return lazyListHelper.getLazyList(Arm.class); } /** * Sets the arms internal. * * @param arms the new arms internal */ public void setArmsInternal(List<Arm> arms) { lazyListHelper.setInternalList(Arm.class, arms); } /** * Sets the arms. * * @param arms the new arms */ public void setArms(List<Arm> arms) { lazyListHelper.setInternalList(Arm.class, arms); } /** * Adds the eligibility criterion. * * @param eligibilityCriterion the eligibility criterion */ public void addEligibilityCriterion(EligibilityCriteria eligibilityCriterion) { this.getEligibilityCriteria().add(eligibilityCriterion); } /** * Gets the stratification criteria internal. * * @return the stratification criteria internal */ @OneToMany(fetch = FetchType.LAZY) @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) @JoinColumn(name = "EPH_ID") @Where(clause = "retired_indicator = 'false'") public List<StratificationCriterion> getStratificationCriteriaInternal() { return lazyListHelper.getInternalList(StratificationCriterion.class); } /** * Gets the stratification criteria. * * @return the stratification criteria */ @Transient public List<StratificationCriterion> getStratificationCriteria() { return lazyListHelper.getLazyList(StratificationCriterion.class); } /** * Sets the stratification criteria. * * @param stratificationCriteria the new stratification criteria */ public void setStratificationCriteria( List<StratificationCriterion> stratificationCriteria) { lazyListHelper.setInternalList(StratificationCriterion.class, stratificationCriteria); } /** * Sets the stratification criteria internal. * * @param stratificationCriteria the new stratification criteria internal */ public void setStratificationCriteriaInternal( List<StratificationCriterion> stratificationCriteria) { lazyListHelper.setInternalList(StratificationCriterion.class, stratificationCriteria); } /** * Adds the stratification criterion. * * @param stratificationCriterion the stratification criterion */ public void addStratificationCriterion( StratificationCriterion stratificationCriterion) { this.getStratificationCriteria().add(stratificationCriterion); } /** * Gets the eligibility criteria. * * @return the eligibility criteria */ @OneToMany @Cascade( { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) @JoinColumn(name = "EPH_ID") @Where(clause = "retired_indicator = 'false'") public List<EligibilityCriteria> getEligibilityCriteria() { return eligibilityCriteria; } /** * Sets the eligibility criteria. * * @param eligibilityCriteria the new eligibility criteria */ public void setEligibilityCriteria(List<EligibilityCriteria> eligibilityCriteria) { this.eligibilityCriteria = eligibilityCriteria; lazyListHelper.setInternalList(InclusionEligibilityCriteria.class, new ProjectedList<InclusionEligibilityCriteria>(this.eligibilityCriteria, InclusionEligibilityCriteria.class)); lazyListHelper .setInternalList(ExclusionEligibilityCriteria.class, new ProjectedList<ExclusionEligibilityCriteria>( this.eligibilityCriteria, ExclusionEligibilityCriteria.class)); } /** * Gets the inclusion eligibility criteria. * * @return the inclusion eligibility criteria */ @Transient public List<InclusionEligibilityCriteria> getInclusionEligibilityCriteria() { return lazyListHelper.getLazyList(InclusionEligibilityCriteria.class); } /** * Sets the inclusion eligibility criteria. * * @param inclusionEligibilityCriteria the new inclusion eligibility criteria */ public void setInclusionEligibilityCriteria( List<InclusionEligibilityCriteria> inclusionEligibilityCriteria) { // do nothing } /** * Gets the exclusion eligibility criteria. * * @return the exclusion eligibility criteria */ @Transient public List<ExclusionEligibilityCriteria> getExclusionEligibilityCriteria() { return lazyListHelper.getLazyList(ExclusionEligibilityCriteria.class); } /** * Sets the exclusion eligibility criteria. * * @param exclusionEligibilityCriteria the new exclusion eligibility criteria */ public void setExclusionEligibilityCriteria( List<ExclusionEligibilityCriteria> exclusionEligibilityCriteria) { // do nothing } /** * Gets the stratum groups internal. * * @return the stratum groups internal */ @OneToMany(fetch = FetchType.LAZY) @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) @JoinColumn(name = "epochs_id") @Where(clause = "retired_indicator = 'false'") @OrderBy("stratumGroupNumber") public List<StratumGroup> getStratumGroupsInternal() { return lazyListHelper.getInternalList(StratumGroup.class); } /** * Sets the stratum groups internal. * * @param stratumGroup the new stratum groups internal */ public void setStratumGroupsInternal(List<StratumGroup> stratumGroup) { lazyListHelper.setInternalList(StratumGroup.class, stratumGroup); } /** * Gets the stratum groups. * * @return the stratum groups */ @Transient public List<StratumGroup> getStratumGroups() { return lazyListHelper.getLazyList(StratumGroup.class); } /** * Sets the stratum groups. * * @param stratumGroup the new stratum groups */ public void setStratumGroups(List<StratumGroup> stratumGroup) { } /** * Gets the randomization. * * @return the randomization */ @OneToOne @JoinColumn(name = "rndm_id") @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN }) public Randomization getRandomization() { return randomization; } /** * Sets the randomization. * * @param randomization the new randomization */ public void setRandomization(Randomization randomization) { this.randomization = randomization; } /** * Checks for book randomization entry. * * @return true, if successful */ @Transient public boolean hasBookRandomizationEntry() { if (this.getRandomization() instanceof BookRandomization) { if (((((BookRandomization) this.getRandomization()) .getBookRandomizationEntry()) != null) && ((BookRandomization) this.getRandomization()) .getBookRandomizationEntry().size() > 0) { return true; } } return false; } /** * Gets the stratum group for ans combination. * * @param scacList the scac list * * @return the stratum group for ans combination */ @Transient /* * This method iterates thru the stratum groups for the treatmentEpoch and * finds the one that has the same stratificationCriAnsCombination as the * one passed in and returns it. returns null if no matching stratum group * is found */ public StratumGroup getStratumGroupForAnsCombination( List<StratificationCriterionAnswerCombination> scacList) { StratumGroup sg = new StratumGroup(); sg.getStratificationCriterionAnswerCombination().addAll(scacList); List<StratumGroup> sgList; sgList = this.getStratumGroups(); Iterator iter = sgList.iterator(); StratumGroup sgCurr; while (iter.hasNext()) { sgCurr = (StratumGroup) iter.next(); if (sgCurr.equals(sg)) { return sgCurr; } } return null; } /** * Gets the stratum group by number. * * @param number the number * * @return the stratum group by number */ @Transient /* * This method iterates thru the stratum groups for the Epoch and * finds the one that has the same stratum group number as the one passed in * and returns it. returns null if no matching stratum group is found */ public StratumGroup getStratumGroupByNumber(Integer number) { for (StratumGroup sgCurr : this.getStratumGroups()) { if (sgCurr.getStratumGroupNumber().equals(number)) { return sgCurr; } } return null; } /** * Checks for stratification. * * @return true, if successful */ @Transient public boolean hasStratification() { return (getStratificationCriteria().size() > 0); } /** * Checks for stratum groups. * * @return true, if successful */ @Transient public boolean hasStratumGroups() { return (getStratumGroups().size() > 0); } /** * Checks for eligibility. * * @return true, if successful */ @Transient public boolean hasEligibility() { return (getEligibilityCriteria().size() > 0); } /** * Gets the randomized indicator. * * @return the randomized indicator */ public Boolean getRandomizedIndicator() { return randomizedIndicator; } /** * Sets the randomized indicator. * * @param randomizedIndicator the new randomized indicator */ public void setRandomizedIndicator(Boolean randomizedIndicator) { this.randomizedIndicator = randomizedIndicator; } /** * Evaluate status. * * @param errors the errors * * @return true, if successful * * @throws C3PRCodedRuntimeException the c3 pr coded runtime exception */ public void evaluateStatus(List<Error> errors) throws C3PRCodedRuntimeException { evaluateStratificationDataEntryStatus(errors); evaluateRandomizationDataEntryStatus(errors); evaluateEligibilityDataEntryStatus(errors); } /** * Evaluate stratification data entry status. * * @param errors the errors * * @return true, if successful * * @throws C3PRCodedRuntimeException the c3 pr coded runtime exception */ public boolean evaluateStratificationDataEntryStatus(List<Error> errors) throws C3PRCodedRuntimeException { if (this.getStratificationIndicator()) { if (!this.hasStratification() || !this.hasStratumGroups()) { errors.add(new Error(getC3PRExceptionHelper().getRuntimeException( getCode("C3PR.EXCEPTION.STUDY.DATAENTRY.MISSING.STRATIFICATION_CRITERIA_OR_STRATUM_GROUPS_FOR_RANDOMIZED_EPOCH.CODE"), new String[] { this.getName() }).getMessage())); } } return true; } /** * Evaluate randomization data entry status. * * @param errors the errors * * @return true, if successful * * @throws C3PRCodedRuntimeException the c3 pr coded runtime exception */ public boolean evaluateRandomizationDataEntryStatus(List<Error> errors) throws C3PRCodedRuntimeException { if (this.getRandomizedIndicator()) { if ((this.getArms().size() < 2)||(this.getRandomization() == null)) { if (this.getArms().size() < 2) { errors.add(new Error(getC3PRExceptionHelper().getRuntimeException( getCode("C3PR.EXCEPTION.STUDY.DATAENTRY.MISSING.ATLEAST_2_ARMS_FOR_RANDOMIZED_EPOCH.CODE"), new String[] { this.getName() }).getMessage())); } } } if (this.study.getRandomizationType() == (RandomizationType.BOOK)) { if (this.getRandomizedIndicator()) { if (!this.hasBookRandomizationEntry()) { errors.add(new Error(getC3PRExceptionHelper().getRuntimeException( getCode("C3PR.EXCEPTION.STUDY.DATAENTRY.MISSING.BOOK_ENTRIES_FOR_BOOK_RANDOMIZED_EPOCH.CODE"), new String[] { this.getName() }).getMessage())); } } } if (this.study.getRandomizationType() == (RandomizationType.PHONE_CALL)) { if (this.getRandomizedIndicator()) { Randomization randomization = this.getRandomization(); if (randomization instanceof PhoneCallRandomization) { if (StringUtils .isBlank(((PhoneCallRandomization) randomization) .getPhoneNumber())) { errors.add(new Error(getC3PRExceptionHelper().getRuntimeException( getCode("C3PR.EXCEPTION.STUDY.DATAENTRY.MISSING.PHONE_NUMBER_FOR_PHONE_CALL_RANDOMIZED_EPOCH.CODE"), new String[] { this.getName() }).getMessage())); } } } } return true; } /** * Evaluate eligibility data entry status. * * @param errors the errors * * @return true, if successful * * @throws C3PRCodedRuntimeException the c3 pr coded runtime exception */ public boolean evaluateEligibilityDataEntryStatus(List<Error> errors) throws C3PRCodedRuntimeException { // Default returns true unless more information is obtained return true; } /** * Gets the code. * * @param errortypeString the errortype string * * @return the code */ @Transient public int getCode(String errortypeString) { return Integer.parseInt(this.c3prErrorMessages.getMessage( errortypeString, null, null)); } /** * Gets the c3 pr exception helper. * * @return the c3 pr exception helper */ @Transient public C3PRExceptionHelper getC3PRExceptionHelper() { return c3PRExceptionHelper; } /** * Sets the exception helper. * * @param c3PRExceptionHelper the new exception helper */ public void setExceptionHelper(C3PRExceptionHelper c3PRExceptionHelper) { this.c3PRExceptionHelper = c3PRExceptionHelper; } /** * Gets the c3pr error messages. * * @return the c3pr error messages */ @Transient public MessageSource getC3prErrorMessages() { return c3prErrorMessages; } /** * Sets the c3pr error messages. * * @param errorMessages the new c3pr error messages */ public void setC3prErrorMessages(MessageSource errorMessages) { c3prErrorMessages = errorMessages; } /** * Checks if is enrolling. * * @return true, if is enrolling */ @Transient public boolean isEnrolling() { return enrollmentIndicator; } /** * Gets the stratification indicator. * * @return the stratification indicator */ public Boolean getStratificationIndicator() { return stratificationIndicator; } /** * Sets the stratification indicator. * * @param stratificationIndicator the new stratification indicator */ public void setStratificationIndicator(Boolean stratificationIndicator) { this.stratificationIndicator = stratificationIndicator; } /** * Gets the treatment indicator. * * @return the treatment indicator */ public Boolean getTreatmentIndicator() { return treatmentIndicator; } /** * Sets the treatment indicator. * * @param treatmentIndicator the new treatment indicator */ public void setTreatmentIndicator(Boolean treatmentIndicator) { this.treatmentIndicator = treatmentIndicator; } /** * Gets the arm by name. * * @param armName the arm name * * @return the arm by name */ @Transient public Arm getArmByName(String armName){ for(Arm localArm:this.getArms()){ if(armName.equals(localArm.getName())){ return localArm; } } return null; } /** * Generate stratum groups. * * @param request the request * @param commandObj the command obj * @param error the error * @param epochCountIndex the epoch count index */ public void generateStratumGroups() { ArrayList<StratumGroup> stratumGroupList; this.getStratumGroups().clear(); int stratificationCriterionSize = this.getStratificationCriteria().size(); if (stratificationCriterionSize > 0) { StratificationCriterionPermissibleAnswer permissibleAnswersArray[][] = new StratificationCriterionPermissibleAnswer[stratificationCriterionSize][]; List<StratificationCriterionPermissibleAnswer> tempAnswersList; // creating a 2d array of answers for every treatment epoch for (int i = 0; i < stratificationCriterionSize; i++) { tempAnswersList = this.getStratificationCriteria().get(i) .getPermissibleAnswers(); permissibleAnswersArray[i] = new StratificationCriterionPermissibleAnswer[tempAnswersList .size()]; for (int j = 0; j < tempAnswersList.size(); j++) { permissibleAnswersArray[i][j] = tempAnswersList.get(j); } } stratumGroupList = stratumGroupCombinationGenerator(permissibleAnswersArray, 0, new ArrayList<StratumGroup>(), new ArrayList<StratificationCriterionAnswerCombination>()); this.getStratumGroups().addAll(stratumGroupList); } } /** * Stratum group combination generator. * recursive method which computes all possible combinations * of sc and scpa and creates a list of stratum Groups for the same. * * @param epoch the epoch * @param permissibleAnswersArray the permissible answers array * @param intRecurseLevel the int recurse level * @param stratumGroupList the stratum group list * @param generatedAnswerCombinationList the generated answer combination list * * @return the array list< stratum group> */ private ArrayList<StratumGroup> stratumGroupCombinationGenerator(StratificationCriterionPermissibleAnswer[][] permissibleAnswersArray, int intRecurseLevel, ArrayList<StratumGroup> stratumGroupList, ArrayList<StratificationCriterionAnswerCombination> generatedAnswerCombinationList) { StratificationCriterionAnswerCombination stratificationCriterionAnswerCombination ; ArrayList<StratificationCriterionAnswerCombination> stratificationCriterionAnswerCombinationList; int numberOfStratumGroups = 0; for (int i = 0; i < permissibleAnswersArray[intRecurseLevel].length; i++) { stratificationCriterionAnswerCombination = new StratificationCriterionAnswerCombination(); stratificationCriterionAnswerCombinationList = new ArrayList<StratificationCriterionAnswerCombination>(); stratificationCriterionAnswerCombination .setStratificationCriterionPermissibleAnswer(permissibleAnswersArray[intRecurseLevel][i]); stratificationCriterionAnswerCombination.setStratificationCriterion(this .getStratificationCriteria().get(intRecurseLevel)); if (!generatedAnswerCombinationList.isEmpty()) { stratificationCriterionAnswerCombinationList.addAll(generatedAnswerCombinationList); } stratificationCriterionAnswerCombinationList.add(stratificationCriterionAnswerCombination); if (intRecurseLevel < permissibleAnswersArray.length - 1) { // stepping into the next question stratumGroupList = stratumGroupCombinationGenerator(permissibleAnswersArray, intRecurseLevel + 1, stratumGroupList, stratificationCriterionAnswerCombinationList); } else { // ran out of questions and hence now i have a combination of answers to save. numberOfStratumGroups = stratumGroupList.size(); stratumGroupList.add(numberOfStratumGroups, new StratumGroup()); stratumGroupList.get(numberOfStratumGroups) .getStratificationCriterionAnswerCombination().addAll( cloneStratificationCriterionAnswerCombination(stratificationCriterionAnswerCombinationList)); stratumGroupList.get(numberOfStratumGroups).setStratumGroupNumber(numberOfStratumGroups); } } return stratumGroupList; } /** * Clones the StratificationCriterionAnswerCombination for the comboGenerator. * * @param stratificationCriterionAnswerCombinationList the stratification criterion answer combination list * * @return the list< stratification criterion answer combination> */ private List<StratificationCriterionAnswerCombination> cloneStratificationCriterionAnswerCombination( List<StratificationCriterionAnswerCombination> stratificationCriterionAnswerCombinationList) { List<StratificationCriterionAnswerCombination> clonedList = new ArrayList<StratificationCriterionAnswerCombination>(); Iterator<StratificationCriterionAnswerCombination> iter = stratificationCriterionAnswerCombinationList .iterator(); while (iter.hasNext()) { clonedList.add(new StratificationCriterionAnswerCombination(iter .next())); } return clonedList; } }
Domain layer test coverage work.
codebase/projects/core/src/java/edu/duke/cabig/c3pr/domain/Epoch.java
Domain layer test coverage work.
<ide><path>odebase/projects/core/src/java/edu/duke/cabig/c3pr/domain/Epoch.java <ide> import edu.duke.cabig.c3pr.utils.StringUtils; <ide> import gov.nih.nci.cabig.ctms.collections.LazyListHelper; <ide> <del>// TODO: Auto-generated Javadoc <ide> /** <ide> * The Class Epoch. <ide> *
JavaScript
mit
eedfe5a0bc0ee00420639e5e3d789eb36dbbf6de
0
sunag/sea3d,sunag/sea3d,sunag/sea3d,sunag/sea3d,sunag/sea3d,sunag/sea3d
/** _ _ _ _____ __ _______ ______ * | |___| |_| |__ /__ | | | | _ | * * * | / _ \ _| | __\ | | \ | _ | U _ * |_\___/\__|_||_| _ |____/____ |__ \_|_ |_|_____| * * @author LoTh / http://3dflashlo.wordpress.com/ * @author SUNAG / http://www.sunag.com.br/ * @author Ammo.lab / https://github.com/lo-th/Ammo.lab/ */ 'use strict'; SEA3D.AMMO = { world: null, rigidBodies: [], rigidBodiesTarget: [], rigidBodiesEnabled: [], constraints: [], vehicles: [], vehiclesWheels: [], ACTIVE: 1, ISLAND_SLEEPING: 2, WANTS_DEACTIVATION: 3, DISABLE_DEACTIVATION: 4, DISABLE_SIMULATION: 5, VERSION: 0.8, init: function ( gravity, worldScale, broadphase ) { gravity = gravity !== undefined ? gravity : - 90.8; this.worldScale = worldScale == undefined ? 1 : worldScale; this.broadphase = broadphase == undefined ? 'bvt' : broadphase; this.solver = new Ammo.btSequentialImpulseConstraintSolver(); this.collisionConfig = new Ammo.btDefaultCollisionConfiguration(); this.dispatcher = new Ammo.btCollisionDispatcher( this.collisionConfig ); switch ( this.broadphase ) { case 'bvt': this.broadphase = new Ammo.btDbvtBroadphase(); break; case 'sap': this.broadphase = new Ammo.btAxisSweep3( new Ammo.btVector3( - this.worldScale, - this.worldScale, - this.worldScale ), new Ammo.btVector3( this.worldScale, this.worldScale, this.worldScale ), 4096 ); break; case 'simple': this.broadphase = new Ammo.btSimpleBroadphase(); break; } this.world = new Ammo.btDiscreteDynamicsWorld( this.dispatcher, this.broadphase, this.solver, this.collisionConfig ); this.setGravity( gravity ); console.log( "THREE.AMMO " + this.VERSION ); }, setGravity: function ( gravity ) { this.gravity = gravity; this.world.setGravity( new Ammo.btVector3( 0, gravity, 0 ) ); return this; }, getGravity: function () { return this.gravity; }, setEnabledRigidBody: function ( rb, enabled ) { if ( this.getEnabledRigidBody( rb ) == enabled ) return; if ( enabled ) this.world.addRigidBody( rb ); else this.world.removeRigidBody( rb ); return this; }, getEnabledRigidBody: function ( rb ) { return this.rigidBodiesEnabled[ this.rigidBodies.indexOf( rb ) ] === true; }, addRigidBody: function ( rb, target, enabled ) { enabled = enabled !== undefined ? enabled : true; this.rigidBodies.push( rb ); this.rigidBodiesTarget.push( target ); this.rigidBodiesEnabled.push( false ); this.setEnabledRigidBody( rb, enabled ); return this; }, removeRigidBody: function ( rb, destroy ) { var index = this.rigidBodies.indexOf( rb ); this.setEnabledRigidBody( rb, false ); this.rigidBodies.splice( index, 1 ); this.rigidBodiesTarget.splice( index, 1 ); this.rigidBodiesEnabled.splice( index, 1 ); if ( destroy ) Ammo.destroy( rb ); return this; }, containsRigidBody: function ( rb ) { return this.rigidBodies.indexOf( rb ) > - 1; }, addConstraint: function ( ctrt, disableCollisionsBetweenBodies ) { disableCollisionsBetweenBodies = disableCollisionsBetweenBodies == undefined ? true : disableCollisionsBetweenBodies; this.constraints.push( ctrt ); this.world.addConstraint( ctrt, disableCollisionsBetweenBodies ); return this; }, removeConstraint: function ( ctrt, destroy ) { this.constraints.splice( this.constraints.indexOf( ctrt ), 1 ); this.world.removeConstraint( ctrt ); if ( destroy ) Ammo.destroy( ctrt ); return this; }, containsConstraint: function ( ctrt ) { return this.constraints.indexOf( rb ) > - 1; }, addVehicle: function ( vehicle, wheels ) { this.vehicles.push( vehicle ); this.vehiclesWheels.push( wheels != undefined ? wheels : [] ); this.world.addAction( vehicle ); return this; }, removeVehicle: function ( vehicle, destroy ) { var index = this.vehicles.indexOf( vehicle ); this.vehicles.splice( index, 1 ); this.vehiclesWheels.splice( index, 1 ); this.world.removeAction( vehicle ); if ( destroy ) Ammo.destroy( vehicle ); return this; }, containsVehicle: function ( vehicle ) { return this.vehicles.indexOf( vehicle ) > - 1; }, createTriangleMesh: function ( geometry, index, removeDuplicateVertices ) { index = index == undefined ? - 1 : index; removeDuplicateVertices = removeDuplicateVertices == undefined ? false : removeDuplicateVertices; var mTriMesh = new Ammo.btTriangleMesh(); var v0 = new Ammo.btVector3( 0, 0, 0 ); var v1 = new Ammo.btVector3( 0, 0, 0 ); var v2 = new Ammo.btVector3( 0, 0, 0 ); var vertex = geometry.getAttribute( 'position' ).array; var indexes = geometry.getIndex().array; var group = index >= 0 ? geometry.groups[ index ] : undefined, start = group ? group.start : 0, count = group ? group.count : indexes.length; var scale = 1 / this.worldScale; for ( var idx = start; idx < count; idx += 3 ) { var vx1 = indexes[ idx ] * 3, vx2 = indexes[ idx + 1 ] * 3, vx3 = indexes[ idx + 2 ] * 3; v0.setValue( vertex[ vx1 ] * scale, vertex[ vx1 + 1 ] * scale, vertex[ vx1 + 2 ] * scale ); v1.setValue( vertex[ vx2 ] * scale, vertex[ vx2 + 1 ] * scale, vertex[ vx2 + 2 ] * scale ); v2.setValue( vertex[ vx3 ] * scale, vertex[ vx3 + 1 ] * scale, vertex[ vx3 + 2 ] * scale ); mTriMesh.addTriangle( v0, v1, v2, removeDuplicateVertices ); } return mTriMesh; }, createConvexHull: function ( geometry, index ) { index = index == undefined ? - 1 : index; var mConvexHull = new Ammo.btConvexHullShape(); var v0 = new Ammo.btVector3( 0, 0, 0 ); var vertex = geometry.getAttribute( 'position' ).array; var indexes = geometry.getIndex().array; var group = index >= 0 ? geometry.groups[ index ] : undefined, start = group ? group.start : 0, count = group ? group.count : indexes.length; var scale = 1 / this.worldScale; for ( var idx = start; idx < count; idx += 3 ) { var vx1 = indexes[ idx ] * 3; var point = new Ammo.btVector3( vertex[ vx1 ] * scale, vertex[ vx1 + 1 ] * scale, vertex[ vx1 + 2 ] * scale ); mConvexHull.addPoint( point ); } return mConvexHull; }, getTargetByRigidBody: function ( rb ) { return this.rigidBodiesTarget[ this.rigidBodies.indexOf( rb ) ]; }, getRigidBodyByTarget: function ( target ) { return this.rigidBodies[ this.rigidBodiesTarget.indexOf( target ) ]; }, getTransformFromMatrix: function ( mtx ) { var transform = new Ammo.btTransform(); var pos = THREE.SEA3D.VECBUF.setFromMatrixPosition( mtx ); transform.setOrigin( new Ammo.btVector3( pos.x, pos.y, pos.z ) ); var scl = THREE.SEA3D.VECBUF.setFromMatrixScale( mtx ); mtx.scale( scl.set( 1 / scl.x, 1 / scl.y, 1 / scl.z ) ); var quat = new THREE.Quaternion().setFromRotationMatrix( mtx ); var q = new Ammo.btQuaternion(); q.setValue( quat.x, quat.y, quat.z, quat.w ); transform.setRotation( q ); Ammo.destroy( q ); return transform; }, getMatrixFromTransform: function ( transform ) { var position = new THREE.Vector3(); var quaternion = new THREE.Quaternion(); var scale = new THREE.Vector3( 1, 1, 1 ); return function ( transform, matrix ) { matrix = matrix || new THREE.Matrix4(); var pos = transform.getOrigin(), quat = transform.getRotation(); position.set( pos.x(), pos.y(), pos.z() ); quaternion.set( quat.x(), quat.y(), quat.z(), quat.w() ); matrix.compose( position, quaternion, scale ); return matrix; }; }(), updateTargetTransform: function () { var matrix = new THREE.Matrix4(); var position = new THREE.Vector3(); var quaternion = new THREE.Quaternion(); var scale = new THREE.Vector3( 1, 1, 1 ); return function ( obj3d, transform, offset ) { var pos = transform.getOrigin(), quat = transform.getRotation(); if ( offset ) { position.set( pos.x(), pos.y(), pos.z() ); quaternion.set( quat.x(), quat.y(), quat.z(), quat.w() ); matrix.compose( position, quaternion, scale ); matrix.multiplyMatrices( matrix, offset ); obj3d.position.setFromMatrixPosition( matrix ); obj3d.quaternion.setFromRotationMatrix( matrix ); } else { obj3d.position.set( pos.x(), pos.y(), pos.z() ); obj3d.quaternion.set( quat.x(), quat.y(), quat.z(), quat.w() ); } return this; }; }(), update: function ( delta, iteration, fixedDelta ) { this.world.stepSimulation( delta, iteration || 0, fixedDelta || ( 60 / 1000 ) ); var i, j; for ( i = 0; i < this.vehicles.length; i ++ ) { var vehicle = this.vehicles[ i ], numWheels = vehicle.getNumWheels(), wheels = this.vehiclesWheels[ i ]; for ( j = 0; j < numWheels; j ++ ) { vehicle.updateWheelTransform( j, true ); var wheelsTransform = vehicle.getWheelTransformWS( j ), wheelTarget = wheels[ j ]; if ( wheelTarget ) { this.updateTargetTransform( wheelTarget, wheelsTransform, wheelTarget.physics ? wheelTarget.physics.offset : null ); } } } for ( i = 0; i < this.rigidBodies.length; i ++ ) { var rb = this.rigidBodies[ i ], target = this.rigidBodiesTarget[ i ]; if ( target && rb.isActive() ) { this.updateTargetTransform( target, rb.getWorldTransform(), target.physics ? target.physics.offset : null ); } } return this; } };
Source/Three.JS/physics/SEA3DAmmo.js
/** _ _ _ _____ __ _______ ______ * | |___| |_| |__ /__ | | | | _ | * * * | / _ \ _| | __\ | | \ | _ | U _ * |_\___/\__|_||_| _ |____/____ |__ \_|_ |_|_____| * * @author LoTh / http://3dflashlo.wordpress.com/ * @author SUNAG / http://www.sunag.com.br/ * @author Ammo.lab / https://github.com/lo-th/Ammo.lab/ */ 'use strict'; SEA3D.AMMO = { world: null, rigidBodies: [], rigidBodiesTarget: [], rigidBodiesEnabled: [], constraints: [], vehicles: [], vehiclesWheels: [], ACTIVE: 1, ISLAND_SLEEPING: 2, WANTS_DEACTIVATION: 3, DISABLE_DEACTIVATION: 4, DISABLE_SIMULATION: 5, VERSION: 0.8, init: function ( gravity, worldScale, broadphase ) { gravity = gravity !== undefined ? gravity : - 90.8; this.worldScale = worldScale == undefined ? 1 : worldScale; this.broadphase = broadphase == undefined ? 'bvt' : broadphase; this.solver = new Ammo.btSequentialImpulseConstraintSolver(); this.collisionConfig = new Ammo.btDefaultCollisionConfiguration(); this.dispatcher = new Ammo.btCollisionDispatcher( this.collisionConfig ); switch ( this.broadphase ) { case 'bvt': this.broadphase = new Ammo.btDbvtBroadphase(); break; case 'sap': this.broadphase = new Ammo.btAxisSweep3( new Ammo.btVector3( - this.worldScale, - this.worldScale, - this.worldScale ), new Ammo.btVector3( this.worldScale, this.worldScale, this.worldScale ), 4096 ); break; case 'simple': this.broadphase = new Ammo.btSimpleBroadphase(); break; } this.world = new Ammo.btDiscreteDynamicsWorld( this.dispatcher, this.broadphase, this.solver, this.collisionConfig ); this.setGravity( gravity ); console.log( "THREE.AMMO " + this.VERSION ); }, setGravity: function ( gravity ) { this.gravity = gravity; this.world.setGravity( new Ammo.btVector3( 0, gravity, 0 ) ); return this; }, getGravity: function () { return this.gravity; }, setEnabledRigidBody: function ( rb, enabled ) { if ( this.getEnabledRigidBody( rb ) == enabled ) return; if ( enabled ) this.world.addRigidBody( rb ); else this.world.removeRigidBody( rb ); return this; }, getEnabledRigidBody: function ( rb ) { return this.rigidBodiesEnabled[ this.rigidBodies.indexOf( rb ) ] === true; }, addRigidBody: function ( rb, target, enabled ) { enabled = enabled !== undefined ? enabled : true; this.rigidBodies.push( rb ); this.rigidBodiesTarget.push( target ); this.rigidBodiesEnabled.push( false ); this.setEnabledRigidBody( rb, enabled ); return this; }, removeRigidBody: function ( rb, destroy ) { var index = this.rigidBodies.indexOf( rb ); this.setEnabledRigidBody( rb, false ); this.rigidBodies.splice( index, 1 ); this.rigidBodiesTarget.splice( index, 1 ); this.rigidBodiesEnabled.splice( index, 1 ); if ( destroy ) Ammo.destroy( rb ); return this; }, containsRigidBody: function ( rb ) { return this.rigidBodies.indexOf( rb ) > - 1; }, addConstraint: function ( ctrt, disableCollisionsBetweenBodies ) { disableCollisionsBetweenBodies = disableCollisionsBetweenBodies == undefined ? true : disableCollisionsBetweenBodies; this.constraints.push( ctrt ); this.world.addConstraint( ctrt, disableCollisionsBetweenBodies ); return this; }, removeConstraint: function ( ctrt, destroy ) { this.constraints.splice( this.constraints.indexOf( ctrt ), 1 ); this.world.removeConstraint( ctrt ); if ( destroy ) Ammo.destroy( ctrt ); return this; }, containsConstraint: function ( ctrt ) { return this.constraints.indexOf( rb ) > - 1; }, addVehicle: function ( vehicle, wheels ) { this.vehicles.push( vehicle ); this.vehiclesWheels.push( wheels != undefined ? wheels : [] ); this.world.addAction( vehicle ); return this; }, removeVehicle: function ( vehicle, destroy ) { var index = this.vehicles.indexOf( vehicle ); this.vehicles.splice( index, 1 ); this.vehiclesWheels.splice( index, 1 ); this.world.removeAction( vehicle ); if ( destroy ) Ammo.destroy( vehicle ); return this; }, containsVehicle: function ( vehicle ) { return this.vehicles.indexOf( vehicle ) > - 1; }, createTriangleMesh: function ( geometry, index, removeDuplicateVertices ) { index = index == undefined ? - 1 : index; removeDuplicateVertices = removeDuplicateVertices == undefined ? false : removeDuplicateVertices; var mTriMesh = new Ammo.btTriangleMesh(); var v0 = new Ammo.btVector3( 0, 0, 0 ); var v1 = new Ammo.btVector3( 0, 0, 0 ); var v2 = new Ammo.btVector3( 0, 0, 0 ); var vertex = geometry.getAttribute( 'position' ).array; var indexes = geometry.getIndex().array; var group = index >= 0 ? geometry.groups[ index ] : undefined, start = group ? group.start : 0, count = group ? group.count : indexes.length; var scale = 1 / this.worldScale; for ( var idx = start; idx < count; idx += 3 ) { var vx1 = indexes[ idx ] * 3, vx2 = indexes[ idx + 1 ] * 3, vx3 = indexes[ idx + 2 ] * 3; v0.setValue( vertex[ vx1 ] * scale, vertex[ vx1 + 1 ] * scale, vertex[ vx1 + 2 ] * scale ); v1.setValue( vertex[ vx2 ] * scale, vertex[ vx2 + 1 ] * scale, vertex[ vx2 + 2 ] * scale ); v2.setValue( vertex[ vx3 ] * scale, vertex[ vx3 + 1 ] * scale, vertex[ vx3 + 2 ] * scale ); mTriMesh.addTriangle( v0, v1, v2, removeDuplicateVertices ); } return mTriMesh; }, createConvexHull: function ( geometry, index ) { index = index == undefined ? - 1 : index; var mConvexHull = new Ammo.btConvexHullShape(); var v0 = new Ammo.btVector3( 0, 0, 0 ); var vertex = geometry.getAttribute( 'position' ).array; var indexes = geometry.getIndex().array; var group = index >= 0 ? geometry.groups[ index ] : undefined, start = group ? group.start : 0, count = group ? group.count : indexes.length; var scale = 1 / this.worldScale; for ( var idx = start; idx < count; idx += 3 ) { var vx1 = indexes[ idx ] * 3; var point = new Ammo.btVector3( vertex[ vx1 ] * scale, vertex[ vx1 + 1 ] * scale, vertex[ vx1 + 2 ] * scale ); mConvexHull.addPoint( point ); } return mConvexHull; }, getTargetByRigidBody: function ( rb ) { return this.rigidBodiesTarget[ this.rigidBodies.indexOf( rb ) ]; }, getRigidBodyByTarget: function ( target ) { return this.rigidBodies[ this.rigidBodiesTarget.indexOf( target ) ]; }, getTransformFromMatrix: function ( mtx ) { var transform = new Ammo.btTransform(); var pos = THREE.SEA3D.VECBUF.setFromMatrixPosition( mtx ); transform.setOrigin( new Ammo.btVector3( pos.x, pos.y, pos.z ) ); var scl = THREE.SEA3D.VECBUF.setFromMatrixScale( mtx ); mtx.scale( scl.set( 1 / scl.x, 1 / scl.y, 1 / scl.z ) ); var quat = new THREE.Quaternion().setFromRotationMatrix( mtx ); var q = new Ammo.btQuaternion(); q.setValue( quat.x, quat.y, quat.z, quat.w ); transform.setRotation( q ); Ammo.destroy( q ); return transform; }, getMatrixFromTransform: function ( transform ) { var position = new THREE.Vector3(); var quaternion = new THREE.Quaternion(); var scale = new THREE.Vector3( 1, 1, 1 ); return function ( transform, matrix ) { matrix = matrix || new THREE.Matrix4(); var pos = transform.getOrigin(), quat = transform.getRotation(); position.set( pos.x(), pos.y(), pos.z() ); quaternion.set( quat.x(), quat.y(), quat.z(), quat.w() ); matrix.compose( position, quaternion, scale ); return matrix; }; }(), updateTargetTransform: function () { var matrix = new THREE.Matrix4(); var position = new THREE.Vector3(); var quaternion = new THREE.Quaternion(); var scale = new THREE.Vector3( 1, 1, 1 ); return function ( obj3d, transform, offset ) { var pos = transform.getOrigin(), quat = transform.getRotation(); if ( offset ) { position.set( pos.x(), pos.y(), pos.z() ); quaternion.set( quat.x(), quat.y(), quat.z(), quat.w() ); matrix.compose( position, quaternion, scale ); matrix.multiplyMatrices( matrix, offset ); obj3d.position.setFromMatrixPosition( matrix ); obj3d.quaternion.setFromRotationMatrix( matrix ); } else { obj3d.position.set( pos.x(), pos.y(), pos.z() ); obj3d.quaternion.set( quat.x(), quat.y(), quat.z(), quat.w() ); } return this; }; }(), update: function ( delta, iteration, fixedDelta ) { this.world.stepSimulation( delta, iteration || 0, fixedDelta || ( 60 / 1000 ) ); var i, j; for ( i = 0; i < this.vehicles.length; i ++ ) { var vehicle = this.vehicles[ i ], numWheels = vehicle.getNumWheels(), wheels = this.vehiclesWheels[ i ]; for ( j = 0; j < numWheels; j ++ ) { vehicle.updateWheelTransform( j, true ); var wheelsTransform = vehicle.getWheelTransformWS( j ), wheelTarget = wheels[ j ]; if ( wheelTarget ) { this.updateTargetTransform( wheelTarget, wheelsTransform, target.physics ? wheelTarget.physics.offset : null ); } } } for ( i = 0; i < this.rigidBodies.length; i ++ ) { var rb = this.rigidBodies[ i ], target = this.rigidBodiesTarget[ i ]; if ( target && rb.isActive() ) { this.updateTargetTransform( target, rb.getWorldTransform(), target.physics ? target.physics.offset : null ); } } return this; } };
fix wheel offset
Source/Three.JS/physics/SEA3DAmmo.js
fix wheel offset
<ide><path>ource/Three.JS/physics/SEA3DAmmo.js <ide> <ide> if ( wheelTarget ) { <ide> <del> this.updateTargetTransform( wheelTarget, wheelsTransform, target.physics ? wheelTarget.physics.offset : null ); <add> this.updateTargetTransform( wheelTarget, wheelsTransform, wheelTarget.physics ? wheelTarget.physics.offset : null ); <ide> <ide> } <ide>
Java
agpl-3.0
f02940eb215ef10b90193aa00b32d193cc323a34
0
Kunagi/kunagi,JavierPeris/kunagi,Kunagi/kunagi,JavierPeris/kunagi,Kunagi/kunagi,JavierPeris/kunagi,Kunagi/kunagi,JavierPeris/kunagi,JavierPeris/kunagi,Kunagi/kunagi
package scrum.client.project; import ilarkesto.gwt.client.AFieldValueWidget; import ilarkesto.gwt.client.AMultiSelectionViewEditWidget; import ilarkesto.gwt.client.ButtonWidget; import ilarkesto.gwt.client.TableBuilder; import ilarkesto.gwt.client.ToolbarWidget; import ilarkesto.gwt.client.editor.IntegerEditorWidget; import java.util.ArrayList; import java.util.Collections; import java.util.List; import scrum.client.ListPredicate; import scrum.client.common.AScrumWidget; import scrum.client.common.BlockListWidget; import scrum.client.workspace.PagePanel; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.Widget; public class ProductBacklogWidget extends AScrumWidget { private BlockListWidget<Requirement> list; private ToolbarWidget toolbar; private AMultiSelectionViewEditWidget<ListPredicate<Requirement>> predicateSelect; private List<ListPredicate<Requirement>> predicates; @Override protected Widget onInitialization() { predicates = new ArrayList<ListPredicate<Requirement>>(); predicates.add(new ListPredicate<Requirement>("closed", true) { @Override protected boolean test(Requirement element) { return element.isClosed(); } }); list = new BlockListWidget<Requirement>(RequirementBlock.FACTORY); list.setAutoSorter(getCurrentProject().getRequirementsOrderComparator()); if (getCurrentProject().isProductOwner(getCurrentUser())) { list.setDndSorting(true); list.setMoveObserver(new MoveObserver()); } // Filters Panel filterPanel = new FlowPanel(); filterPanel.add(new Label("Filter: ")); predicateSelect = new AMultiSelectionViewEditWidget<ListPredicate<Requirement>>() { @Override protected void onViewerUpdate() { setViewerItems(filter(predicates)); } @Override protected void onEditorUpdate() { setEditorItems(predicates); setEditorSelectedItems(filter(predicates)); } private List<ListPredicate<Requirement>> filter(List<ListPredicate<Requirement>> predicates) { List<ListPredicate<Requirement>> filteredList = new ArrayList<ListPredicate<Requirement>>(predicates .size()); for (ListPredicate<Requirement> p : predicates) { if (p.isEnabled()) filteredList.add(p); } return filteredList; } @Override protected void onEditorSubmit() { List<ListPredicate<Requirement>> selected = getEditorSelectedItems(); for (ListPredicate<Requirement> p : predicates) { p.setEnabled(selected.contains(p)); } ProductBacklogWidget.this.update(); } @Override public boolean isEditable() { return true; } }; filterPanel.add(predicateSelect); TableBuilder tb = new TableBuilder(); tb.setCellPadding(2); tb.addField("Assumed Velocity", new IntegerEditorWidget(getCurrentProject().getVelocityModel())); tb.addField("Velocity in last Sprint", new AFieldValueWidget() { @Override protected void onUpdate() { setText(getCurrentProject().getVelocityFromLastSprint()); super.onUpdate(); } }); PagePanel page = new PagePanel(); page.addHeader("Product Backlog", new ButtonWidget(new CreateRequirementAction())); page.addSection(tb.createTable()); page.addSection(filterPanel); page.addSection(list); return page; } @Override protected void onUpdate() { super.onUpdate(); List<Requirement> requirements = filter(getCurrentProject().getRequirements()); Collections.sort(requirements, getCurrentProject().getRequirementsOrderComparator()); EstimationBarFactory.createEstimationBars(requirements, getCurrentProject().getVelocity()); list.setObjects(requirements); } private List<Requirement> filter(List<Requirement> requirements) { ArrayList<Requirement> result = new ArrayList<Requirement>(requirements.size()); for (Requirement r : requirements) { if (noPredicateContains(r)) result.add(r); } return result; } private boolean noPredicateContains(Requirement r) { for (ListPredicate<Requirement> p : predicates) { if (p.contains(r)) return false; } return true; } public void selectRequirement(Requirement requirement) { list.extendObject(requirement); } class MoveObserver implements Runnable { public void run() { List<Requirement> requirements = list.getObjects(); getCurrentProject().updateRequirementsOrder(requirements); update(); } } }
src/main/java/scrum/client/project/ProductBacklogWidget.java
package scrum.client.project; import ilarkesto.gwt.client.AFieldValueWidget; import ilarkesto.gwt.client.AMultiSelectionViewEditWidget; import ilarkesto.gwt.client.ButtonWidget; import ilarkesto.gwt.client.TableBuilder; import ilarkesto.gwt.client.ToolbarWidget; import ilarkesto.gwt.client.editor.IntegerEditorWidget; import java.util.ArrayList; import java.util.Collections; import java.util.List; import scrum.client.ListPredicate; import scrum.client.common.AScrumWidget; import scrum.client.common.BlockListWidget; import scrum.client.workspace.PagePanel; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.Widget; public class ProductBacklogWidget extends AScrumWidget { private BlockListWidget<Requirement> list; private ToolbarWidget toolbar; private AMultiSelectionViewEditWidget<ListPredicate<Requirement>> predicateSelect; private List<ListPredicate<Requirement>> predicates; @Override protected Widget onInitialization() { predicates = new ArrayList<ListPredicate<Requirement>>(); predicates.add(new ListPredicate<Requirement>("closed", true) { @Override protected boolean test(Requirement element) { return element.isClosed(); } }); list = new BlockListWidget<Requirement>(RequirementBlock.FACTORY); list.setAutoSorter(getCurrentProject().getRequirementsOrderComparator()); if (getCurrentProject().isProductOwner(getCurrentUser())) { list.setDndSorting(true); list.setMoveObserver(new MoveObserver()); } // Filters Panel filterPanel = new FlowPanel(); filterPanel.add(new Label("Filter: ")); predicateSelect = new AMultiSelectionViewEditWidget<ListPredicate<Requirement>>() { @Override protected void onViewerUpdate() { setViewerItems(filter(predicates)); } @Override protected void onEditorUpdate() { setEditorItems(predicates); setEditorSelectedItems(filter(predicates)); } private List<ListPredicate<Requirement>> filter(List<ListPredicate<Requirement>> predicates) { List<ListPredicate<Requirement>> filteredList = new ArrayList<ListPredicate<Requirement>>(predicates .size()); for (ListPredicate<Requirement> p : predicates) { if (p.isEnabled()) filteredList.add(p); } return filteredList; } @Override protected void onEditorSubmit() { List<ListPredicate<Requirement>> selected = getEditorSelectedItems(); for (ListPredicate<Requirement> p : predicates) { p.setEnabled(selected.contains(p)); } ProductBacklogWidget.this.update(); } @Override public boolean isEditable() { return true; } }; filterPanel.add(predicateSelect); TableBuilder tb = new TableBuilder(); tb.setCellPadding(2); tb.addField("Velocity", new IntegerEditorWidget(getCurrentProject().getVelocityModel())); tb.addField("Velocity in last Sprint", new AFieldValueWidget() { @Override protected void onUpdate() { setText(getCurrentProject().getVelocityFromLastSprint()); super.onUpdate(); } }); PagePanel page = new PagePanel(); page.addHeader("Product Backlog", new ButtonWidget(new CreateRequirementAction())); page.addSection(tb.createTable()); page.addSection(filterPanel); page.addSection(list); return page; } @Override protected void onUpdate() { super.onUpdate(); List<Requirement> requirements = filter(getCurrentProject().getRequirements()); Collections.sort(requirements, getCurrentProject().getRequirementsOrderComparator()); EstimationBarFactory.createEstimationBars(requirements, getCurrentProject().getVelocity()); list.setObjects(requirements); } private List<Requirement> filter(List<Requirement> requirements) { ArrayList<Requirement> result = new ArrayList<Requirement>(requirements.size()); for (Requirement r : requirements) { if (noPredicateContains(r)) result.add(r); } return result; } private boolean noPredicateContains(Requirement r) { for (ListPredicate<Requirement> p : predicates) { if (p.contains(r)) return false; } return true; } public void selectRequirement(Requirement requirement) { list.extendObject(requirement); } class MoveObserver implements Runnable { public void run() { List<Requirement> requirements = list.getObjects(); getCurrentProject().updateRequirementsOrder(requirements); update(); } } }
velocity in product backlog git-svn-id: 5d16f60e415856c0d9146e9340794746a8f5c347@2972 15bc23fa-3125-0410-a1f3-bdc40dbf1900
src/main/java/scrum/client/project/ProductBacklogWidget.java
velocity in product backlog
<ide><path>rc/main/java/scrum/client/project/ProductBacklogWidget.java <ide> <ide> TableBuilder tb = new TableBuilder(); <ide> tb.setCellPadding(2); <del> tb.addField("Velocity", new IntegerEditorWidget(getCurrentProject().getVelocityModel())); <add> tb.addField("Assumed Velocity", new IntegerEditorWidget(getCurrentProject().getVelocityModel())); <ide> tb.addField("Velocity in last Sprint", new AFieldValueWidget() { <ide> <ide> @Override
Java
apache-2.0
997835fefede67fcd09efa2c1b32c126e06aaf87
0
ceylon/ceylon-common,ceylon/ceylon-common,jvasileff/ceylon-common,jvasileff/ceylon-common,ceylon/ceylon-common,jvasileff/ceylon-common
package com.redhat.ceylon.common.config; import java.io.File; import java.util.Arrays; import java.util.Collections; import java.util.List; import com.redhat.ceylon.common.Constants; import com.redhat.ceylon.common.FileUtil; public class DefaultToolOptions { public final static String DEFAULTS_ENCODING = "defaults.encoding"; public final static String DEFAULTS_OFFLINE = "defaults.offline"; public final static String COMPILER_SOURCE = "compiler.source"; public final static String COMPILER_RESOURCE = "compiler.resource"; public final static String COMPILER_DOC = "compiler.doc"; public final static String COMPILER_NOOSGI = "compiler.noosgi"; public final static String COMPILER_PACK200 = "compiler.pack200"; public final static String RUNTOOL_COMPILE = "runtool.compile"; public final static String TESTTOOL_COMPILE = "testtool.compile"; private DefaultToolOptions() { } public static String getDefaultEncoding() { return getDefaultEncoding(CeylonConfig.get()); } public static String getDefaultEncoding(CeylonConfig config) { return config.getOption(DEFAULTS_ENCODING); } public static boolean getDefaultOffline() { return getDefaultOffline(CeylonConfig.get()); } public static boolean getDefaultOffline(CeylonConfig config) { return config.getBoolOption(DEFAULTS_OFFLINE, false); } public static List<File> getCompilerSourceDirs() { return getCompilerSourceDirs(CeylonConfig.get()); } public static List<File> getCompilerSourceDirs(CeylonConfig config) { String[] dirs = config.getOptionValues(COMPILER_SOURCE); if (dirs != null) { return Arrays.asList(FileUtil.pathsToFileArray(dirs)); } else { return Collections.singletonList(new File(Constants.DEFAULT_SOURCE_DIR)); } } public static List<File> getCompilerResourceDirs() { return getCompilerResourceDirs(CeylonConfig.get()); } public static List<File> getCompilerResourceDirs(CeylonConfig config) { String[] dirs = config.getOptionValues(COMPILER_RESOURCE); if (dirs != null) { return Arrays.asList(FileUtil.pathsToFileArray(dirs)); } else { return Collections.singletonList(new File(Constants.DEFAULT_RESOURCE_DIR)); } } public static List<File> getCompilerDocDirs() { return getCompilerDocDirs(CeylonConfig.get()); } public static List<File> getCompilerDocDirs(CeylonConfig config) { String[] dirs = config.getOptionValues(COMPILER_DOC); if (dirs != null) { return Arrays.asList(FileUtil.pathsToFileArray(dirs)); } else { return Collections.singletonList(new File(Constants.DEFAULT_DOC_DIR)); } } public static File getCompilerOutDir() { return getCompilerOutDir(CeylonConfig.get()); } public static File getCompilerOutDir(CeylonConfig config) { return new File(Repositories.withConfig(config).getOutputRepository().getUrl()); } public static boolean getCompilerNoOsgi() { return getCompilerNoOsgi(CeylonConfig.get()); } public static boolean getCompilerNoOsgi(CeylonConfig config) { return config.getBoolOption(COMPILER_NOOSGI, false); } public static boolean getCompilerPack200() { return getCompilerPack200(CeylonConfig.get()); } public static boolean getCompilerPack200(CeylonConfig config) { return config.getBoolOption(COMPILER_PACK200, false); } public static String getRunToolCompileFlags() { return getRunToolCompileFlags(CeylonConfig.get()); } public static String getRunToolCompileFlags(CeylonConfig config) { return config.getOption(RUNTOOL_COMPILE, Constants.DEFAULT_RUNTOOL_COMPILATION_FLAGS); } public static String getTestToolCompileFlags() { return getTestToolCompileFlags(CeylonConfig.get()); } public static String getTestToolCompileFlags(CeylonConfig config) { return config.getOption(TESTTOOL_COMPILE, Constants.DEFAULT_TESTTOOL_COMPILATION_FLAGS); } }
src/com/redhat/ceylon/common/config/DefaultToolOptions.java
package com.redhat.ceylon.common.config; import java.io.File; import java.util.Arrays; import java.util.Collections; import java.util.List; import com.redhat.ceylon.common.Constants; import com.redhat.ceylon.common.FileUtil; public class DefaultToolOptions { public final static String DEFAULTS_ENCODING = "defaults.encoding"; public final static String DEFAULTS_OFFLINE = "defaults.offline"; public final static String COMPILER_SOURCE = "compiler.source"; public final static String COMPILER_RESOURCE = "compiler.resource"; public final static String COMPILER_DOC = "compiler.doc"; public final static String RUNTOOL_COMPILE = "runtool.compile"; public final static String TESTTOOL_COMPILE = "testtool.compile"; private DefaultToolOptions() { } public static String getDefaultEncoding() { return getDefaultEncoding(CeylonConfig.get()); } public static String getDefaultEncoding(CeylonConfig config) { return config.getOption(DEFAULTS_ENCODING); } public static boolean getDefaultOffline() { return getDefaultOffline(CeylonConfig.get()); } public static boolean getDefaultOffline(CeylonConfig config) { return config.getBoolOption(DEFAULTS_OFFLINE, false); } public static List<File> getCompilerSourceDirs() { return getCompilerSourceDirs(CeylonConfig.get()); } public static List<File> getCompilerSourceDirs(CeylonConfig config) { String[] dirs = config.getOptionValues(COMPILER_SOURCE); if (dirs != null) { return Arrays.asList(FileUtil.pathsToFileArray(dirs)); } else { return Collections.singletonList(new File(Constants.DEFAULT_SOURCE_DIR)); } } public static List<File> getCompilerResourceDirs() { return getCompilerResourceDirs(CeylonConfig.get()); } public static List<File> getCompilerResourceDirs(CeylonConfig config) { String[] dirs = config.getOptionValues(COMPILER_RESOURCE); if (dirs != null) { return Arrays.asList(FileUtil.pathsToFileArray(dirs)); } else { return Collections.singletonList(new File(Constants.DEFAULT_RESOURCE_DIR)); } } public static List<File> getCompilerDocDirs() { return getCompilerDocDirs(CeylonConfig.get()); } public static List<File> getCompilerDocDirs(CeylonConfig config) { String[] dirs = config.getOptionValues(COMPILER_DOC); if (dirs != null) { return Arrays.asList(FileUtil.pathsToFileArray(dirs)); } else { return Collections.singletonList(new File(Constants.DEFAULT_DOC_DIR)); } } public static File getCompilerOutDir() { return getCompilerOutDir(CeylonConfig.get()); } public static File getCompilerOutDir(CeylonConfig config) { return new File(Repositories.withConfig(config).getOutputRepository().getUrl()); } public static String getRunToolCompileFlags() { return getRunToolCompileFlags(CeylonConfig.get()); } public static String getRunToolCompileFlags(CeylonConfig config) { return config.getOption(RUNTOOL_COMPILE, Constants.DEFAULT_RUNTOOL_COMPILATION_FLAGS); } public static String getTestToolCompileFlags() { return getTestToolCompileFlags(CeylonConfig.get()); } public static String getTestToolCompileFlags(CeylonConfig config) { return config.getOption(TESTTOOL_COMPILE, Constants.DEFAULT_TESTTOOL_COMPILATION_FLAGS); } }
Added constants and helper methods for the compiler configuration options `NoOsgi` and `Pack200` (see ceylon/ceylon-compiler#275)
src/com/redhat/ceylon/common/config/DefaultToolOptions.java
Added constants and helper methods for the compiler configuration options `NoOsgi` and `Pack200` (see ceylon/ceylon-compiler#275)
<ide><path>rc/com/redhat/ceylon/common/config/DefaultToolOptions.java <ide> public final static String COMPILER_SOURCE = "compiler.source"; <ide> public final static String COMPILER_RESOURCE = "compiler.resource"; <ide> public final static String COMPILER_DOC = "compiler.doc"; <add> public final static String COMPILER_NOOSGI = "compiler.noosgi"; <add> public final static String COMPILER_PACK200 = "compiler.pack200"; <ide> <ide> public final static String RUNTOOL_COMPILE = "runtool.compile"; <ide> public final static String TESTTOOL_COMPILE = "testtool.compile"; <ide> return new File(Repositories.withConfig(config).getOutputRepository().getUrl()); <ide> } <ide> <add> public static boolean getCompilerNoOsgi() { <add> return getCompilerNoOsgi(CeylonConfig.get()); <add> } <add> <add> public static boolean getCompilerNoOsgi(CeylonConfig config) { <add> return config.getBoolOption(COMPILER_NOOSGI, false); <add> } <add> <add> public static boolean getCompilerPack200() { <add> return getCompilerPack200(CeylonConfig.get()); <add> } <add> <add> public static boolean getCompilerPack200(CeylonConfig config) { <add> return config.getBoolOption(COMPILER_PACK200, false); <add> } <add> <ide> public static String getRunToolCompileFlags() { <ide> return getRunToolCompileFlags(CeylonConfig.get()); <ide> }
Java
apache-2.0
cbd44ef18988178718287628b0cf881a79ceda9d
0
warmsheep/VirtualEncoder
package org.warmsheep.encoder.actor.processor; import java.io.Serializable; import org.apache.commons.lang.StringUtils; import org.jpos.iso.ISOMsg; import org.jpos.iso.ISOUtil; import org.jpos.transaction.Context; import org.warmsheep.encoder.actor.AbsActor; import org.warmsheep.encoder.bean.A0CommandBean; import org.warmsheep.encoder.constants.KeyConstants; import org.warmsheep.encoder.constants.RespCmdType; import org.warmsheep.encoder.ic.RespCodeIC; import org.warmsheep.encoder.ic.TxnIC; import org.warmsheep.encoder.security.util.OddEventCheckUtil; import org.warmsheep.util.UUIDUitl; import org.warmsheep.util.security.utils.EncryptUtil; /** * A0指令处理器 * */ public class A0Processor extends AbsActor { @Override public int prepare(long id, Serializable serializable) { Context context = (Context) serializable; try { ISOMsg reqMsg = (ISOMsg) context.get(TxnIC.MSG_HSM); String header = reqMsg.getString(0); String commandType = reqMsg.getString(1); String requestData = reqMsg.getString(2); A0CommandBean a0CommandBean = A0CommandBean.build(header, commandType, requestData); byte[] randomKeyBytes = null; if(a0CommandBean.getLmkKeyFlag().equals("X")){ randomKeyBytes = UUIDUitl.generateString(16).getBytes(); } else if(a0CommandBean.getLmkKeyFlag().equals("Z")){ randomKeyBytes = UUIDUitl.generateString(8).getBytes(); } if(!a0CommandBean.getLmkKeyFlag().equals(a0CommandBean.getZmkKeyFlag())){ throw new Exception("LMK/ZMK KEY FLAG NOT EQUALS!"); } //进行奇偶校验 randomKeyBytes = OddEventCheckUtil.parityOfOdd(randomKeyBytes, 0); //产生校验值 String checkValue = EncryptUtil.desEncryptHexString("0000000000000000", ISOUtil.hexString(randomKeyBytes)); String encryptKey = null; switch (a0CommandBean.getKeyType()) { case "000": //ZMK/KEK encryptKey = KeyConstants.ZMK_000; break; case "001": //ZPK encryptKey = KeyConstants.ZPK_001; break; case "002": //PVK/TPK/TMK encryptKey = KeyConstants.TPK_TMK_PVK_002; break; case "003": //TAK encryptKey = KeyConstants.TAK_003; break; case "007": //edk encryptKey = KeyConstants.EDK_007; break; case "008"://ZAK encryptKey = KeyConstants.ZAK_008; break; case "00A": //ZEK/DEK break; case "00C": break; case "100": break; case "109": break; case "209": break; case "309": break; case "402": break; case "509": break; default: break; } String randomKeyOnLmk = EncryptUtil.desEncryptHexString(ISOUtil.hexString(randomKeyBytes), encryptKey); if(a0CommandBean.getLmkKeyFlag().equalsIgnoreCase("X")){ randomKeyOnLmk = "X" + randomKeyOnLmk; } String randomKeyOnZmk = ""; if(a0CommandBean.getGenerateMode().equals("1")){ String zmkCipher = a0CommandBean.getZmkCipher(); if(zmkCipher.substring(0,1).equalsIgnoreCase("X")){ zmkCipher = zmkCipher.substring(1); } String zmkClearText = EncryptUtil.desDecryptToHex(zmkCipher, KeyConstants.ZMK_000); randomKeyOnZmk = EncryptUtil.desEncryptHexString(ISOUtil.hexString(randomKeyBytes), zmkClearText); if(a0CommandBean.getZmkKeyFlag().equalsIgnoreCase("X")){ randomKeyOnZmk = "X" + randomKeyOnZmk; } } if(StringUtils.isNotBlank(randomKeyOnLmk)){ context.put(TxnIC.RESULT_TYPE, RespCmdType.A1); context.put(TxnIC.RESULT_CODE, RespCodeIC.SUCCESS); context.put(TxnIC.RESULT_DATA, randomKeyOnLmk.toUpperCase() + randomKeyOnZmk.toUpperCase() + checkValue.toUpperCase()); } else { context.put(TxnIC.RESULT_TYPE, RespCmdType.A1); //TODO待实现 context.put(TxnIC.RESULT_CODE, RespCodeIC.FORMAT_ERROR); } return PREPARED | NO_JOIN; } catch (Exception e) { logger.error("MS指令处理出现异常", e); context.put(TxnIC.RESULT_CODE, RespCodeIC.OTHER_ERROR); return ABORTED | NO_JOIN; } } }
code/wp-virtual-encoder/src/main/java/org/warmsheep/encoder/actor/processor/A0Processor.java
package org.warmsheep.encoder.actor.processor; import java.io.Serializable; import org.apache.commons.lang.StringUtils; import org.jpos.iso.ISOMsg; import org.jpos.iso.ISOUtil; import org.jpos.transaction.Context; import org.warmsheep.encoder.actor.AbsActor; import org.warmsheep.encoder.bean.A0CommandBean; import org.warmsheep.encoder.constants.KeyConstants; import org.warmsheep.encoder.constants.RespCmdType; import org.warmsheep.encoder.ic.RespCodeIC; import org.warmsheep.encoder.ic.TxnIC; import org.warmsheep.encoder.security.util.OddEventCheckUtil; import org.warmsheep.util.UUIDUitl; import org.warmsheep.util.security.utils.EncryptUtil; /** * A0指令处理器 * */ public class A0Processor extends AbsActor { @Override public int prepare(long id, Serializable serializable) { Context context = (Context) serializable; try { ISOMsg reqMsg = (ISOMsg) context.get(TxnIC.MSG_HSM); String header = reqMsg.getString(0); String commandType = reqMsg.getString(1); String requestData = reqMsg.getString(2); A0CommandBean a0CommandBean = A0CommandBean.build(header, commandType, requestData); byte[] randomKeyBytes = null; if(a0CommandBean.getLmkKeyFlag().equals("X")){ randomKeyBytes = UUIDUitl.generateString(16).getBytes(); } else if(a0CommandBean.getLmkKeyFlag().equals("Z")){ randomKeyBytes = UUIDUitl.generateString(8).getBytes(); } if(!a0CommandBean.getLmkKeyFlag().equals(a0CommandBean.getZmkKeyFlag())){ throw new Exception("LMK/ZMK KEY FLAG NOT EQUALS!"); } //进行奇偶校验 randomKeyBytes = OddEventCheckUtil.parityOfOdd(randomKeyBytes, 0); //产生校验值 String checkValue = EncryptUtil.desEncryptHexString("0000000000000000", ISOUtil.hexString(randomKeyBytes)); String encryptKey = null; switch (a0CommandBean.getKeyType()) { case "000": //ZMK/KEK encryptKey = KeyConstants.ZMK_000; break; case "001": //ZPK encryptKey = KeyConstants.ZPK_001; break; case "002": //PVK/TPK/TMK encryptKey = KeyConstants.TPK_TMK_PVK_002; break; case "003": //TAK encryptKey = KeyConstants.TAK_003; break; case "007": //edk encryptKey = KeyConstants.EDK_007; break; case "008"://ZAK encryptKey = KeyConstants.ZAK_008; break; case "00A": //ZEK/DEK break; case "00C": break; case "100": break; case "109": break; case "209": break; case "309": break; case "402": break; case "509": break; default: break; } String randomKeyOnLmk = EncryptUtil.desEncryptHexString(ISOUtil.hexString(randomKeyBytes), encryptKey); if(a0CommandBean.getLmkKeyFlag().equalsIgnoreCase("X")){ randomKeyOnLmk = "X" + randomKeyOnLmk; } String randomKeyOnZmk = ""; if(a0CommandBean.getGenerateMode().equals("1")){ String zmkCipher = a0CommandBean.getZmkCipher(); if(zmkCipher.substring(0,1).equalsIgnoreCase("X")){ zmkCipher = zmkCipher.substring(1); } String zmkClearText = EncryptUtil.desDecryptToHex(zmkCipher, KeyConstants.ZMK_000); randomKeyOnZmk = EncryptUtil.desEncryptHexString(ISOUtil.hexString(randomKeyBytes), zmkClearText); if(a0CommandBean.getZmkKeyFlag().equalsIgnoreCase("X")){ randomKeyOnZmk = "X" + randomKeyOnZmk; } } if(StringUtils.isNotBlank(randomKeyOnLmk)){ context.put(TxnIC.RESULT_TYPE, RespCmdType.MT); context.put(TxnIC.RESULT_CODE, RespCodeIC.SUCCESS); context.put(TxnIC.RESULT_DATA, randomKeyOnLmk.toUpperCase() + randomKeyOnZmk.toUpperCase() + checkValue.toUpperCase()); } else { context.put(TxnIC.RESULT_TYPE, RespCmdType.MT); //TODO待实现 context.put(TxnIC.RESULT_CODE, RespCodeIC.FORMAT_ERROR); } return PREPARED | NO_JOIN; } catch (Exception e) { logger.error("MS指令处理出现异常", e); context.put(TxnIC.RESULT_CODE, RespCodeIC.OTHER_ERROR); return ABORTED | NO_JOIN; } } }
修正A0返回类型错误
code/wp-virtual-encoder/src/main/java/org/warmsheep/encoder/actor/processor/A0Processor.java
修正A0返回类型错误
<ide><path>ode/wp-virtual-encoder/src/main/java/org/warmsheep/encoder/actor/processor/A0Processor.java <ide> } <ide> <ide> if(StringUtils.isNotBlank(randomKeyOnLmk)){ <del> context.put(TxnIC.RESULT_TYPE, RespCmdType.MT); <add> context.put(TxnIC.RESULT_TYPE, RespCmdType.A1); <ide> context.put(TxnIC.RESULT_CODE, RespCodeIC.SUCCESS); <ide> context.put(TxnIC.RESULT_DATA, randomKeyOnLmk.toUpperCase() + randomKeyOnZmk.toUpperCase() + checkValue.toUpperCase()); <ide> } else { <del> context.put(TxnIC.RESULT_TYPE, RespCmdType.MT); <add> context.put(TxnIC.RESULT_TYPE, RespCmdType.A1); <ide> //TODO待实现 <ide> context.put(TxnIC.RESULT_CODE, RespCodeIC.FORMAT_ERROR); <ide> }
Java
apache-2.0
a3bdd7fee9e6614ebdc1b1f4f87039c8561c00c0
0
dslomov/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,ibinti/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,clumsy/intellij-community,semonte/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,supersven/intellij-community,ryano144/intellij-community,caot/intellij-community,ibinti/intellij-community,amith01994/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,robovm/robovm-studio,apixandru/intellij-community,holmes/intellij-community,fnouama/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,suncycheng/intellij-community,consulo/consulo,vvv1559/intellij-community,kool79/intellij-community,samthor/intellij-community,adedayo/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,da1z/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,consulo/consulo,blademainer/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,izonder/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,signed/intellij-community,signed/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,signed/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,adedayo/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,supersven/intellij-community,caot/intellij-community,supersven/intellij-community,supersven/intellij-community,semonte/intellij-community,allotria/intellij-community,signed/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,ernestp/consulo,suncycheng/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,kdwink/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,joewalnes/idea-community,jagguli/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,consulo/consulo,signed/intellij-community,fnouama/intellij-community,vladmm/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,hurricup/intellij-community,slisson/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,fitermay/intellij-community,allotria/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,tmpgit/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,petteyg/intellij-community,signed/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,consulo/consulo,ivan-fedorov/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,holmes/intellij-community,FHannes/intellij-community,xfournet/intellij-community,signed/intellij-community,da1z/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,joewalnes/idea-community,salguarnieri/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,joewalnes/idea-community,FHannes/intellij-community,xfournet/intellij-community,da1z/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,fnouama/intellij-community,amith01994/intellij-community,xfournet/intellij-community,fitermay/intellij-community,kdwink/intellij-community,semonte/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,petteyg/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,jagguli/intellij-community,allotria/intellij-community,amith01994/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,asedunov/intellij-community,asedunov/intellij-community,adedayo/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,signed/intellij-community,fitermay/intellij-community,petteyg/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,da1z/intellij-community,semonte/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,kool79/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,clumsy/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,ryano144/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,ernestp/consulo,adedayo/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,signed/intellij-community,izonder/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,signed/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,blademainer/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,retomerz/intellij-community,vladmm/intellij-community,kool79/intellij-community,samthor/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,consulo/consulo,suncycheng/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,pwoodworth/intellij-community,signed/intellij-community,caot/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,jagguli/intellij-community,caot/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,ernestp/consulo,diorcety/intellij-community,ivan-fedorov/intellij-community,consulo/consulo,ol-loginov/intellij-community,izonder/intellij-community,izonder/intellij-community,allotria/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,vladmm/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,FHannes/intellij-community,kool79/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,joewalnes/idea-community,michaelgallacher/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,fitermay/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,ernestp/consulo,izonder/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,samthor/intellij-community,holmes/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,holmes/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,samthor/intellij-community,joewalnes/idea-community,fnouama/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,ftomassetti/intellij-community,joewalnes/idea-community,ibinti/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,apixandru/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,slisson/intellij-community,adedayo/intellij-community,blademainer/intellij-community,hurricup/intellij-community,clumsy/intellij-community,joewalnes/idea-community,allotria/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,retomerz/intellij-community,asedunov/intellij-community,xfournet/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,semonte/intellij-community,Lekanich/intellij-community,ernestp/consulo,TangHao1987/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,slisson/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,Lekanich/intellij-community,samthor/intellij-community,signed/intellij-community,youdonghai/intellij-community,samthor/intellij-community,supersven/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,caot/intellij-community,supersven/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,samthor/intellij-community,kool79/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,fitermay/intellij-community,samthor/intellij-community,diorcety/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,caot/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,kool79/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,holmes/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,izonder/intellij-community,semonte/intellij-community,ibinti/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,ryano144/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,diorcety/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,SerCeMan/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,vladmm/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,xfournet/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,jagguli/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,holmes/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,semonte/intellij-community,kool79/intellij-community,holmes/intellij-community,kdwink/intellij-community,allotria/intellij-community,apixandru/intellij-community,joewalnes/idea-community,diorcety/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,FHannes/intellij-community,allotria/intellij-community,youdonghai/intellij-community,caot/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,slisson/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,joewalnes/idea-community,allotria/intellij-community,dslomov/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,hurricup/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,akosyakov/intellij-community,izonder/intellij-community,adedayo/intellij-community,kool79/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,ryano144/intellij-community,ernestp/consulo,supersven/intellij-community,vladmm/intellij-community,petteyg/intellij-community,holmes/intellij-community,asedunov/intellij-community,FHannes/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,da1z/intellij-community,hurricup/intellij-community,semonte/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,clumsy/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,fnouama/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,semonte/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,petteyg/intellij-community,clumsy/intellij-community,petteyg/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,allotria/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,slisson/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,da1z/intellij-community,FHannes/intellij-community
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.execution.ui; import com.intellij.execution.ExecutionBundle; import com.intellij.ide.util.BrowseFilesListener; import com.intellij.openapi.projectRoots.ProjectJdkTable; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.ui.ComponentWithBrowseButton; import com.intellij.openapi.ui.TextComponentAccessor; import com.intellij.openapi.util.io.FileUtil; import com.intellij.ui.GuiUtils; import com.intellij.ui.InsertPathAction; import com.intellij.ui.TextFieldWithHistory; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; /** * User: anna * Date: Jun 21, 2005 */ public class AlternativeJREPanel extends JPanel { private final ComponentWithBrowseButton<TextFieldWithHistory> myPathField; private final JCheckBox myCbEnabled; final TextFieldWithHistory myFieldWithHistory; public AlternativeJREPanel() { super(new GridBagLayout()); myCbEnabled = new JCheckBox(ExecutionBundle.message("run.configuration.use.alternate.jre.checkbox")); final GridBagConstraints gc = new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(2, -2, 2, 2), 0, 0); add(myCbEnabled, gc); myFieldWithHistory = new TextFieldWithHistory(); final ArrayList<String> foundJDKs = new ArrayList<String>(); final Sdk[] allJDKs = ProjectJdkTable.getInstance().getAllJdks(); for (Sdk jdk : allJDKs) { foundJDKs.add(jdk.getHomePath()); } myFieldWithHistory.setHistory(foundJDKs); myPathField = new ComponentWithBrowseButton<TextFieldWithHistory>(myFieldWithHistory, null); myPathField.addBrowseFolderListener(ExecutionBundle.message("run.configuration.select.alternate.jre.label"), ExecutionBundle.message("run.configuration.select.jre.dir.label"), null, BrowseFilesListener.SINGLE_DIRECTORY_DESCRIPTOR, TextComponentAccessor.TEXT_FIELD_WITH_HISTORY_WHOLE_TEXT); gc.insets.left = 20; add(myPathField, gc); InsertPathAction.addTo(myFieldWithHistory.getTextEditor()); gc.weighty = 1; add(Box.createVerticalBox(), gc); myCbEnabled.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { enabledChanged(); } }); enabledChanged(); } private void enabledChanged() { final boolean pathEnabled = isPathEnabled(); GuiUtils.enableChildren(myPathField, pathEnabled); myFieldWithHistory.invalidate(); //need to revalidate inner component } public String getPath() { return FileUtil.toSystemIndependentName(myPathField.getChildComponent().getText().trim()); } private void setPath(final String path) { myPathField.getChildComponent().setText(FileUtil.toSystemDependentName(path == null ? "" : path)); } public boolean isPathEnabled() { return myCbEnabled.isSelected(); } private void setPathEnabled(boolean b) { myCbEnabled.setSelected(b); enabledChanged(); } public void init(String path, boolean isEnabled){ setPathEnabled(isEnabled); setPath(path); } }
java/execution/impl/src/com/intellij/execution/ui/AlternativeJREPanel.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.execution.ui; import com.intellij.execution.ExecutionBundle; import com.intellij.ide.util.BrowseFilesListener; import com.intellij.openapi.projectRoots.ProjectJdkTable; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.ui.ComponentWithBrowseButton; import com.intellij.openapi.ui.TextComponentAccessor; import com.intellij.openapi.util.io.FileUtil; import com.intellij.ui.GuiUtils; import com.intellij.ui.InsertPathAction; import com.intellij.ui.TextFieldWithHistory; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; /** * User: anna * Date: Jun 21, 2005 */ public class AlternativeJREPanel extends JPanel{ private final ComponentWithBrowseButton<TextFieldWithHistory> myPathField; private final JCheckBox myCbEnabled; final TextFieldWithHistory myFieldWithHistory; public AlternativeJREPanel() { super(new GridBagLayout()); myCbEnabled = new JCheckBox(ExecutionBundle.message("run.configuration.use.alternate.jre.checkbox")); final GridBagConstraints gc = new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(2, -2, 2, 2), 0, 0); add(myCbEnabled, gc); myFieldWithHistory = new TextFieldWithHistory(); myFieldWithHistory.setBorder(BorderFactory.createEtchedBorder()); final ArrayList<String> foundJdks = new ArrayList<String>(); final Sdk[] allJdks = ProjectJdkTable.getInstance().getAllJdks(); for (Sdk jdk : allJdks) { foundJdks.add(jdk.getHomePath()); } myFieldWithHistory.setHistory(foundJdks); myPathField = new ComponentWithBrowseButton<TextFieldWithHistory>(myFieldWithHistory, null); myPathField.addBrowseFolderListener(ExecutionBundle.message("run.configuration.select.alternate.jre.label"), ExecutionBundle.message("run.configuration.select.jre.dir.label"), null, BrowseFilesListener.SINGLE_DIRECTORY_DESCRIPTOR, TextComponentAccessor.TEXT_FIELD_WITH_HISTORY_WHOLE_TEXT); gc.insets.left = 20; add(myPathField, gc); InsertPathAction.addTo(myFieldWithHistory.getTextEditor()); gc.weighty = 1; add(Box.createVerticalBox(), gc); myCbEnabled.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { enabledChanged(); } }); enabledChanged(); } private void enabledChanged() { final boolean pathEnabled = isPathEnabled(); GuiUtils.enableChildren(myPathField, pathEnabled); myFieldWithHistory.invalidate(); //need to revalidate inner component } public String getPath() { return FileUtil.toSystemIndependentName(myPathField.getChildComponent().getText().trim()); } private void setPath(final String path) { myPathField.getChildComponent().setText(FileUtil.toSystemDependentName(path == null ? "" : path)); } public boolean isPathEnabled() { return myCbEnabled.isSelected(); } private void setPathEnabled(boolean b) { myCbEnabled.setSelected(b); enabledChanged(); } public void init(String path, boolean isEnabled){ setPathEnabled(isEnabled); setPath(path); } }
Fix alternative JRE panel UI
java/execution/impl/src/com/intellij/execution/ui/AlternativeJREPanel.java
Fix alternative JRE panel UI
<ide><path>ava/execution/impl/src/com/intellij/execution/ui/AlternativeJREPanel.java <ide> * User: anna <ide> * Date: Jun 21, 2005 <ide> */ <del>public class AlternativeJREPanel extends JPanel{ <add>public class AlternativeJREPanel extends JPanel { <ide> private final ComponentWithBrowseButton<TextFieldWithHistory> myPathField; <ide> private final JCheckBox myCbEnabled; <ide> final TextFieldWithHistory myFieldWithHistory; <ide> <ide> public AlternativeJREPanel() { <ide> super(new GridBagLayout()); <add> <ide> myCbEnabled = new JCheckBox(ExecutionBundle.message("run.configuration.use.alternate.jre.checkbox")); <ide> final GridBagConstraints gc = new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 0, GridBagConstraints.NORTHWEST, <ide> GridBagConstraints.HORIZONTAL, new Insets(2, -2, 2, 2), 0, 0); <ide> add(myCbEnabled, gc); <ide> <ide> myFieldWithHistory = new TextFieldWithHistory(); <del> myFieldWithHistory.setBorder(BorderFactory.createEtchedBorder()); <del> final ArrayList<String> foundJdks = new ArrayList<String>(); <del> final Sdk[] allJdks = ProjectJdkTable.getInstance().getAllJdks(); <del> for (Sdk jdk : allJdks) { <del> foundJdks.add(jdk.getHomePath()); <add> final ArrayList<String> foundJDKs = new ArrayList<String>(); <add> final Sdk[] allJDKs = ProjectJdkTable.getInstance().getAllJdks(); <add> for (Sdk jdk : allJDKs) { <add> foundJDKs.add(jdk.getHomePath()); <ide> } <del> myFieldWithHistory.setHistory(foundJdks); <add> myFieldWithHistory.setHistory(foundJDKs); <ide> myPathField = new ComponentWithBrowseButton<TextFieldWithHistory>(myFieldWithHistory, null); <ide> myPathField.addBrowseFolderListener(ExecutionBundle.message("run.configuration.select.alternate.jre.label"), <ide> ExecutionBundle.message("run.configuration.select.jre.dir.label"), <del> null, BrowseFilesListener.SINGLE_DIRECTORY_DESCRIPTOR, TextComponentAccessor.TEXT_FIELD_WITH_HISTORY_WHOLE_TEXT); <add> null, BrowseFilesListener.SINGLE_DIRECTORY_DESCRIPTOR, <add> TextComponentAccessor.TEXT_FIELD_WITH_HISTORY_WHOLE_TEXT); <ide> gc.insets.left = 20; <ide> add(myPathField, gc); <ide> InsertPathAction.addTo(myFieldWithHistory.getTextEditor()); <ide> setPath(path); <ide> } <ide> } <del>
Java
apache-2.0
26314643a3c2db4c6be50ac664e2fd0eb657b83b
0
igorakkerman/jlib
/* * jlib - Open Source Java Library * * www.jlib.org * * * Copyright 2005-2015 Igor Akkerman * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jlib.core.language; import java.util.Optional; import java.util.function.Predicate; import java.util.function.Supplier; public final class OptionalUtility { public static <Value> Optional<Value> optionalOf(final Value value, final Predicate<? super Value> predicate) { return optionalOf(value, predicate.test(value)); } public static <Value> Optional<Value> optionalOf(final Supplier<Value> value, final Predicate<? super Value> predicate) { return optionalOf(value.get(), predicate); } public static <Value> Optional<Value> optionalOf(final Value value, final boolean condition) { return condition ? Optional.of(value) : Optional.<Value>empty(); } public static <Value> Optional<Value> optionalOf(final Supplier<Value> value, final boolean condition) { return optionalOf(value.get(), condition); } private OptionalUtility() {} }
jlib-core/src/main/java/org/jlib/core/language/OptionalUtility.java
/* * jlib - Open Source Java Library * * www.jlib.org * * * Copyright 2005-2015 Igor Akkerman * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jlib.core.language; import java.util.Optional; import java.util.function.Predicate; public final class OptionalUtility { public static <Value> Optional<Value> optionalOf(final Value value, final Predicate<? super Value> predicate) { return optionalOf(value, predicate.test(value)); } public static <Value> Optional<Value> optionalOf(final Value value, final boolean condition) { return condition ? Optional.of(value) : Optional.<Value>empty(); } private OptionalUtility() {} }
OptionalUtility created
jlib-core/src/main/java/org/jlib/core/language/OptionalUtility.java
OptionalUtility created
<ide><path>lib-core/src/main/java/org/jlib/core/language/OptionalUtility.java <ide> <ide> import java.util.Optional; <ide> import java.util.function.Predicate; <add>import java.util.function.Supplier; <ide> <ide> public final class OptionalUtility { <ide> <ide> public static <Value> Optional<Value> optionalOf(final Value value, final Predicate<? super Value> predicate) { <ide> return optionalOf(value, predicate.test(value)); <add> } <add> <add> public static <Value> Optional<Value> optionalOf(final Supplier<Value> value, <add> final Predicate<? super Value> predicate) { <add> return optionalOf(value.get(), predicate); <ide> } <ide> <ide> public static <Value> Optional<Value> optionalOf(final Value value, final boolean condition) { <ide> Optional.<Value>empty(); <ide> } <ide> <add> public static <Value> Optional<Value> optionalOf(final Supplier<Value> value, final boolean condition) { <add> return optionalOf(value.get(), condition); <add> } <add> <ide> private OptionalUtility() {} <ide> }
Java
apache-2.0
7f6464fcad9821259a40bb24f97f5e9dd9ceaa66
0
jimma/xerces,ronsigal/xerces,ronsigal/xerces,RackerWilliams/xercesj,RackerWilliams/xercesj,jimma/xerces,ronsigal/xerces,jimma/xerces,RackerWilliams/xercesj
/* * Copyright 1999-2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xerces.dom; import org.w3c.dom.CharacterData; import org.w3c.dom.DOMException; import org.w3c.dom.Node; import org.w3c.dom.Text; /** * Text nodes hold the non-markup, non-Entity content of * an Element or Attribute. * <P> * When a document is first made available to the DOM, there is only * one Text object for each block of adjacent plain-text. Users (ie, * applications) may create multiple adjacent Texts during editing -- * see {@link org.w3c.dom.Element#normalize} for discussion. * <P> * Note that CDATASection is a subclass of Text. This is conceptually * valid, since they're really just two different ways of quoting * characters when they're written out as part of an XML stream. * * @version $Id$ * @since PR-DOM-Level-1-19980818. */ public class TextImpl extends CharacterDataImpl implements CharacterData, Text { // // Private Data members // //Used by replaceWholeText private boolean fTextOnlyChildren = false; // // Constants // /** Serialization version. */ static final long serialVersionUID = -5294980852957403469L; // // Constructors // /** Default constructor */ public TextImpl(){} /** Factory constructor. */ public TextImpl(CoreDocumentImpl ownerDoc, String data) { super(ownerDoc, data); } /** * NON-DOM: resets node and sets specified values for the current node * * @param ownerDoc * @param data */ public void setValues(CoreDocumentImpl ownerDoc, String data){ flags=0; nextSibling = null; previousSibling=null; setOwnerDocument(ownerDoc); super.data = data; } // // Node methods // /** * A short integer indicating what type of node this is. The named * constants for this value are defined in the org.w3c.dom.Node interface. */ public short getNodeType() { return Node.TEXT_NODE; } /** Returns the node name. */ public String getNodeName() { return "#text"; } /** * NON-DOM: Set whether this Text is ignorable whitespace. */ public void setIgnorableWhitespace(boolean ignore) { if (needsSyncData()) { synchronizeData(); } isIgnorableWhitespace(ignore); } // setIgnorableWhitespace(boolean) /** * DOM L3 Core CR - Experimental * * Returns whether this text node contains * element content whitespace</a>, often abusively called "ignorable whitespace". * The text node is determined to contain whitespace in element content * during the load of the document or if validation occurs while using * <code>Document.normalizeDocument()</code>. * @since DOM Level 3 */ public boolean isElementContentWhitespace() { // REVISIT: is this implemenation correct? if (needsSyncData()) { synchronizeData(); } return internalIsIgnorableWhitespace(); } /** * DOM Level 3 WD - Experimental. * Returns all text of <code>Text</code> nodes logically-adjacent text * nodes to this node, concatenated in document order. * @since DOM Level 3 */ public String getWholeText(){ if (needsSyncData()) { synchronizeData(); } if (nextSibling == null) { return data; } if (fBufferStr == null){ fBufferStr = new StringBuffer(); } else { fBufferStr.setLength(0); } if (data != null && data.length() != 0) { fBufferStr.append(data); } getWholeText(nextSibling, fBufferStr); return fBufferStr.toString(); } /** * Concatenates the text of all logically-adjacent text nodes * * @param node * @param buffer * @return true - if execution was stopped because the type of node * other than EntityRef, Text, CDATA is encountered, otherwise * return false */ private boolean getWholeText(Node node, StringBuffer buffer){ String text; while (node != null) { short type = node.getNodeType(); if (type == Node.ENTITY_REFERENCE_NODE) { if (getWholeText(node.getFirstChild(), buffer)){ return true; } } else if (type == Node.TEXT_NODE || type == Node.CDATA_SECTION_NODE) { ((NodeImpl)node).getTextContent(buffer); } else { return true; } node = node.getNextSibling(); } return false; } /** * Replaces the text of the current node and all logically-adjacent text * nodes with the specified text. All logically-adjacent text nodes are * removed including the current node unless it was the recipient of the * replacement text. * * @param content * The content of the replacing Text node. * @return text - The Text node created with the specified content. * @since DOM Level 3 */ public Text replaceWholeText(String content) throws DOMException { if (needsSyncData()) { synchronizeData(); } //if the content is null Node parent = this.getParentNode(); if (content == null || content.length() == 0) { // remove current node if (parent != null) { // check if node in the tree parent.removeChild(this); } return null; } //replace the text node Text currentNode = null; if (isReadOnly()) { Text newNode = this.ownerDocument().createTextNode(content); if (parent != null) { // check if node in the tree parent.insertBefore(newNode, this); parent.removeChild(this); currentNode = newNode; } else { return newNode; } } else { this.setData(content); currentNode = this; } //check logically-adjacent text nodes Node prev = this.getPreviousSibling(); while (prev != null) { fTextOnlyChildren = false; // make sure we can make the replacement if (!canModifyPrev(prev)) { throw new DOMException( DOMException.NO_MODIFICATION_ALLOWED_ERR, DOMMessageFormatter.formatMessage( DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null)); } else { //If the logically-adjacent previous node can be replaced //remove it. A logically adjacent node can be replaced if //it is a Text or CDATASection node or an EntityReference with //Text and CDATA only children if ((prev.getNodeType() == Node.TEXT_NODE) || (prev .getNodeType() == Node.CDATA_SECTION_NODE)|| (prev.getNodeType() == Node.ENTITY_REFERENCE_NODE && fTextOnlyChildren)) { parent.removeChild(prev); prev = this; } } prev = prev.getPreviousSibling(); } //check logically-adjacent text nodes Node next = this.getNextSibling(); while (next != null) { fTextOnlyChildren = false; // make sure we can make the replacement if (!canModifyNext(next)) { throw new DOMException( DOMException.NO_MODIFICATION_ALLOWED_ERR, DOMMessageFormatter.formatMessage( DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null)); } else { //If the logically-adjacent next node can be replaced //remove it. A logically adjacent node can be replaced if //it is a Text or CDATASection node or an EntityReference with //Text and CDATA only children if ((next.getNodeType() == Node.TEXT_NODE) || (next .getNodeType() == Node.CDATA_SECTION_NODE) || (next.getNodeType() == Node.ENTITY_REFERENCE_NODE && fTextOnlyChildren)) { parent.removeChild(next); next = this; } } next = next.getNextSibling(); } return currentNode; } /** * If any EntityReference to be removed has descendants that are not * EntityReference, Text, or CDATASection nodes, the replaceWholeText method * must fail before performing any modification of the document, raising a * DOMException with the code NO_MODIFICATION_ALLOWED_ERR. Traverse previous * siblings of the node to be replaced. If a previous sibling is an * EntityReference node, get it's last child. If the last child was a Text * or CDATASection node and its previous siblings are neither a replaceable * EntityReference or Text or CDATASection nodes, return false. IF the last * child was neither Text nor CDATASection nor a replaceable EntityReference * Node, then return true. If the last child was a Text or CDATASection node * any its previous sibling was not or was an EntityReference that did not * contain only Text or CDATASection nodes, return false. Check this recursively * for EntityReference nodes. * * @param node * @return true - can replace text false - can't replace exception must be * raised */ private boolean canModifyPrev(Node node) { boolean textLastChild = false; short type = node.getNodeType(); if (type == Node.ENTITY_REFERENCE_NODE) { //If the previous sibling was entityreference //check if its content is replaceable Node lastChild = node.getLastChild(); //if the entity reference has no children //return false if (lastChild == null) { fTextOnlyChildren = false; return false; } //The replacement text of the entity reference should //be either only text,cadatsections or replaceable entity //reference nodes or the last child should be neither of these while (lastChild != null) { short lType = lastChild.getNodeType(); if (lType == Node.TEXT_NODE || lType == Node.CDATA_SECTION_NODE) { textLastChild = true; fTextOnlyChildren = true; } else if (lType == Node.ENTITY_REFERENCE_NODE) { if (!canModifyPrev(lastChild)) { fTextOnlyChildren = false; return false; } else { //If the EntityReference child contains //only text, or non-text or ends with a //non-text node. textLastChild = true; } } else { if (textLastChild) { fTextOnlyChildren = false; return false; } else { return true; } } lastChild = lastChild.getPreviousSibling(); } } else if (type == Node.TEXT_NODE || type == Node.CDATA_SECTION_NODE) { //If the previous sibling was text or cdatasection move to next fTextOnlyChildren = true; } else { //If the previous sibling was anything but text or //cdatasection or an entity reference, stop search and //return true return true; } return true; } /** * If any EntityReference to be removed has descendants that are not * EntityReference, Text, or CDATASection nodes, the replaceWholeText method * must fail before performing any modification of the document, raising a * DOMException with the code NO_MODIFICATION_ALLOWED_ERR. Traverse previous * siblings of the node to be replaced. If a previous sibling is an * EntityReference node, get it's last child. If the first child was a Text * or CDATASection node and its next siblings are neither a replaceable * EntityReference or Text or CDATASection nodes, return false. IF the first * child was neither Text nor CDATASection nor a replaceable EntityReference * Node, then return true. If the first child was a Text or CDATASection node * any its next sibling was not or was an EntityReference that did not * contain only Text or CDATASection nodes, return false. Check this recursively * for EntityReference nodes. * * @param node * @return true - can replace text false - can't replace exception must be * raised */ private boolean canModifyNext(Node node) { boolean textFirstChild = false; short type = node.getNodeType(); if (type == Node.ENTITY_REFERENCE_NODE) { //If the previous sibling was entityreference //check if its content is replaceable Node firstChild = node.getFirstChild(); //if the entity reference has no children //return false if (firstChild == null) { fTextOnlyChildren = false; return false; } //The replacement text of the entity reference should //be either only text,cadatsections or replaceable entity //reference nodes or the last child should be neither of these while (firstChild != null) { short lType = firstChild.getNodeType(); if (lType == Node.TEXT_NODE || lType == Node.CDATA_SECTION_NODE) { fTextOnlyChildren = true; textFirstChild = true; } else if (lType == Node.ENTITY_REFERENCE_NODE) { if (!canModifyNext(firstChild)) { fTextOnlyChildren = false; return false; } else { //If the EntityReference child contains //only text, or non-text or ends with a //non-text node. textFirstChild = true; } } else { //If the first child was replaceable text and next //children are not, then return false if (textFirstChild) { fTextOnlyChildren = false; return false; } else { return true; } } firstChild = firstChild.getNextSibling(); } } else if (type == Node.TEXT_NODE || type == Node.CDATA_SECTION_NODE) { //If the previous sibling was text or cdatasection move to next fTextOnlyChildren = true; } else { //If the next sibling was anything but text or //cdatasection or an entity reference, stop search and //return true return true; } return true; } /** * NON-DOM: Returns whether this Text is ignorable whitespace. */ public boolean isIgnorableWhitespace() { if (needsSyncData()) { synchronizeData(); } return internalIsIgnorableWhitespace(); } // isIgnorableWhitespace():boolean // // Text methods // /** * Break a text node into two sibling nodes. (Note that if the current node * has no parent, they won't wind up as "siblings" -- they'll both be * orphans.) * * @param offset * The offset at which to split. If offset is at the end of the * available data, the second node will be empty. * * @return A reference to the new node (containing data after the offset * point). The original node will contain data up to that point. * * @throws DOMException(INDEX_SIZE_ERR) * if offset is <0 or >length. * * @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) * if node is read-only. */ public Text splitText(int offset) throws DOMException { if (isReadOnly()) { throw new DOMException( DOMException.NO_MODIFICATION_ALLOWED_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null)); } if (needsSyncData()) { synchronizeData(); } if (offset < 0 || offset > data.length() ) { throw new DOMException(DOMException.INDEX_SIZE_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INDEX_SIZE_ERR", null)); } // split text into two separate nodes Text newText = getOwnerDocument().createTextNode(data.substring(offset)); setNodeValue(data.substring(0, offset)); // insert new text node Node parentNode = getParentNode(); if (parentNode != null) { parentNode.insertBefore(newText, nextSibling); } return newText; } // splitText(int):Text /** * NON-DOM (used by DOMParser): Reset data for the node. */ public void replaceData (String value){ data = value; } /** * NON-DOM (used by DOMParser: Sets data to empty string. * Returns the value the data was set to. */ public String removeData (){ String olddata=data; data = ""; return olddata; } } // class TextImpl
src/org/apache/xerces/dom/TextImpl.java
/* * Copyright 1999-2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xerces.dom; import org.w3c.dom.CharacterData; import org.w3c.dom.DOMException; import org.w3c.dom.Node; import org.w3c.dom.Text; /** * Text nodes hold the non-markup, non-Entity content of * an Element or Attribute. * <P> * When a document is first made available to the DOM, there is only * one Text object for each block of adjacent plain-text. Users (ie, * applications) may create multiple adjacent Texts during editing -- * see {@link org.w3c.dom.Element#normalize} for discussion. * <P> * Note that CDATASection is a subclass of Text. This is conceptually * valid, since they're really just two different ways of quoting * characters when they're written out as part of an XML stream. * * @version $Id$ * @since PR-DOM-Level-1-19980818. */ public class TextImpl extends CharacterDataImpl implements CharacterData, Text { // // Constants // /** Serialization version. */ static final long serialVersionUID = -5294980852957403469L; // // Constructors // /** Default constructor */ public TextImpl(){} /** Factory constructor. */ public TextImpl(CoreDocumentImpl ownerDoc, String data) { super(ownerDoc, data); } /** * NON-DOM: resets node and sets specified values for the current node * * @param ownerDoc * @param data */ public void setValues(CoreDocumentImpl ownerDoc, String data){ flags=0; nextSibling = null; previousSibling=null; setOwnerDocument(ownerDoc); super.data = data; } // // Node methods // /** * A short integer indicating what type of node this is. The named * constants for this value are defined in the org.w3c.dom.Node interface. */ public short getNodeType() { return Node.TEXT_NODE; } /** Returns the node name. */ public String getNodeName() { return "#text"; } /** * NON-DOM: Set whether this Text is ignorable whitespace. */ public void setIgnorableWhitespace(boolean ignore) { if (needsSyncData()) { synchronizeData(); } isIgnorableWhitespace(ignore); } // setIgnorableWhitespace(boolean) /** * DOM L3 Core CR - Experimental * * Returns whether this text node contains * element content whitespace</a>, often abusively called "ignorable whitespace". * The text node is determined to contain whitespace in element content * during the load of the document or if validation occurs while using * <code>Document.normalizeDocument()</code>. * @since DOM Level 3 */ public boolean isElementContentWhitespace() { // REVISIT: is this implemenation correct? if (needsSyncData()) { synchronizeData(); } return internalIsIgnorableWhitespace(); } /** * DOM Level 3 WD - Experimental. * Returns all text of <code>Text</code> nodes logically-adjacent text * nodes to this node, concatenated in document order. * @since DOM Level 3 */ public String getWholeText(){ if (needsSyncData()) { synchronizeData(); } if (nextSibling == null) { return data; } if (fBufferStr == null){ fBufferStr = new StringBuffer(); } else { fBufferStr.setLength(0); } if (data != null && data.length() != 0) { fBufferStr.append(data); } getWholeText(nextSibling, fBufferStr); return fBufferStr.toString(); } /** * Concatenates the text of all logically-adjacent text nodes * * @param node * @param buffer * @return true - if execution was stopped because the type of node * other than EntityRef, Text, CDATA is encountered, otherwise * return false */ private boolean getWholeText(Node node, StringBuffer buffer){ String text; while (node != null) { short type = node.getNodeType(); if (type == Node.ENTITY_REFERENCE_NODE) { if (getWholeText(node.getFirstChild(), buffer)){ return true; } } else if (type == Node.TEXT_NODE || type == Node.CDATA_SECTION_NODE) { ((NodeImpl)node).getTextContent(buffer); } else { return true; } node = node.getNextSibling(); } return false; } /** * DOM Level 3 WD - Experimental. */ public Text replaceWholeText(String content) throws DOMException{ if (needsSyncData()) { synchronizeData(); } // make sure we can make the replacement if (!canModify(nextSibling)) { throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null)); } Node parent = this.getParentNode(); if (content == null || content.length() == 0) { // remove current node if (parent !=null) { // check if node in the tree parent.removeChild(this); return null; } } Text currentNode = null; if (isReadOnly()){ Text newNode = this.ownerDocument().createTextNode(content); if (parent !=null) { // check if node in the tree parent.insertBefore(newNode, this); parent.removeChild(this); currentNode = newNode; } else { return newNode; } } else { this.setData(content); currentNode = this; } Node sibling = currentNode.getNextSibling(); while ( sibling !=null) { parent.removeChild(sibling); sibling = currentNode.getNextSibling(); } return currentNode; } /** * If any EntityReference to be removed has descendants * that are not EntityReference, Text, or CDATASection * nodes, the replaceWholeText method must fail before * performing any modification of the document, raising a * DOMException with the code NO_MODIFICATION_ALLOWED_ERR. * * @param node * @return true - can replace text * false - can't replace exception must be raised */ private boolean canModify(Node node){ while (node != null) { short type = node.getNodeType(); if (type == Node.ENTITY_REFERENCE_NODE) { if (!canModify(node.getFirstChild())){ return false; } } else if (type != Node.TEXT_NODE && type != Node.CDATA_SECTION_NODE) { return false; } node = node.getNextSibling(); } return true; } /** * NON-DOM: Returns whether this Text is ignorable whitespace. */ public boolean isIgnorableWhitespace() { if (needsSyncData()) { synchronizeData(); } return internalIsIgnorableWhitespace(); } // isIgnorableWhitespace():boolean // // Text methods // /** * Break a text node into two sibling nodes. (Note that if the * current node has no parent, they won't wind up as "siblings" -- * they'll both be orphans.) * * @param offset The offset at which to split. If offset is at the * end of the available data, the second node will be empty. * * @return A reference to the new node (containing data after the * offset point). The original node will contain data up to that * point. * * @throws DOMException(INDEX_SIZE_ERR) if offset is <0 or >length. * * @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if node is read-only. */ public Text splitText(int offset) throws DOMException { if (isReadOnly()) { throw new DOMException( DOMException.NO_MODIFICATION_ALLOWED_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null)); } if (needsSyncData()) { synchronizeData(); } if (offset < 0 || offset > data.length() ) { throw new DOMException(DOMException.INDEX_SIZE_ERR, DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INDEX_SIZE_ERR", null)); } // split text into two separate nodes Text newText = getOwnerDocument().createTextNode(data.substring(offset)); setNodeValue(data.substring(0, offset)); // insert new text node Node parentNode = getParentNode(); if (parentNode != null) { parentNode.insertBefore(newText, nextSibling); } return newText; } // splitText(int):Text /** * NON-DOM (used by DOMParser): Reset data for the node. */ public void replaceData (String value){ data = value; } /** * NON-DOM (used by DOMParser: Sets data to empty string. * Returns the value the data was set to. */ public String removeData (){ String olddata=data; data = ""; return olddata; } } // class TextImpl
Patch to fix problems with replaceWholeText. git-svn-id: 21df804813e9d3638e43477f308dd0be51e5f30f@319958 13f79535-47bb-0310-9956-ffa450edef68
src/org/apache/xerces/dom/TextImpl.java
Patch to fix problems with replaceWholeText.
<ide><path>rc/org/apache/xerces/dom/TextImpl.java <ide> extends CharacterDataImpl <ide> implements CharacterData, Text { <ide> <add> // <add> // Private Data members <add> // <add> //Used by replaceWholeText <add> private boolean fTextOnlyChildren = false; <add> <ide> // <ide> // Constants <ide> // <ide> } <ide> <ide> /** <del> * DOM Level 3 WD - Experimental. <del> */ <del> public Text replaceWholeText(String content) <del> throws DOMException{ <add> * Replaces the text of the current node and all logically-adjacent text <add> * nodes with the specified text. All logically-adjacent text nodes are <add> * removed including the current node unless it was the recipient of the <add> * replacement text. <add> * <add> * @param content <add> * The content of the replacing Text node. <add> * @return text - The Text node created with the specified content. <add> * @since DOM Level 3 <add> */ <add> public Text replaceWholeText(String content) throws DOMException { <ide> <ide> if (needsSyncData()) { <ide> synchronizeData(); <ide> } <del> <del> // make sure we can make the replacement <del> if (!canModify(nextSibling)) { <del> throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, <del> DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null)); <del> } <del> <add> //if the content is null <ide> Node parent = this.getParentNode(); <ide> if (content == null || content.length() == 0) { <ide> // remove current node <del> if (parent !=null) { // check if node in the tree <add> if (parent != null) { // check if node in the tree <ide> parent.removeChild(this); <del> return null; <del> } <del> } <add> } <add> return null; <add> } <add> <add> //replace the text node <ide> Text currentNode = null; <del> if (isReadOnly()){ <add> if (isReadOnly()) { <ide> Text newNode = this.ownerDocument().createTextNode(content); <del> if (parent !=null) { // check if node in the tree <add> if (parent != null) { // check if node in the tree <ide> parent.insertBefore(newNode, this); <ide> parent.removeChild(this); <ide> currentNode = newNode; <ide> } else { <ide> return newNode; <ide> } <del> } else { <add> } else { <ide> this.setData(content); <ide> currentNode = this; <ide> } <del> Node sibling = currentNode.getNextSibling(); <del> while ( sibling !=null) { <del> parent.removeChild(sibling); <del> sibling = currentNode.getNextSibling(); <del> } <del> <add> <add> //check logically-adjacent text nodes <add> Node prev = this.getPreviousSibling(); <add> while (prev != null) { <add> fTextOnlyChildren = false; <add> <add> // make sure we can make the replacement <add> if (!canModifyPrev(prev)) { <add> throw new DOMException( <add> DOMException.NO_MODIFICATION_ALLOWED_ERR, <add> DOMMessageFormatter.formatMessage( <add> DOMMessageFormatter.DOM_DOMAIN, <add> "NO_MODIFICATION_ALLOWED_ERR", null)); <add> } else { <add> //If the logically-adjacent previous node can be replaced <add> //remove it. A logically adjacent node can be replaced if <add> //it is a Text or CDATASection node or an EntityReference with <add> //Text and CDATA only children <add> if ((prev.getNodeType() == Node.TEXT_NODE) || (prev <add> .getNodeType() == Node.CDATA_SECTION_NODE)|| <add> (prev.getNodeType() == Node.ENTITY_REFERENCE_NODE && fTextOnlyChildren)) { <add> parent.removeChild(prev); <add> prev = this; <add> } <add> } <add> prev = prev.getPreviousSibling(); <add> } <add> <add> //check logically-adjacent text nodes <add> Node next = this.getNextSibling(); <add> while (next != null) { <add> fTextOnlyChildren = false; <add> <add> // make sure we can make the replacement <add> if (!canModifyNext(next)) { <add> throw new DOMException( <add> DOMException.NO_MODIFICATION_ALLOWED_ERR, <add> DOMMessageFormatter.formatMessage( <add> DOMMessageFormatter.DOM_DOMAIN, <add> "NO_MODIFICATION_ALLOWED_ERR", null)); <add> } else { <add> //If the logically-adjacent next node can be replaced <add> //remove it. A logically adjacent node can be replaced if <add> //it is a Text or CDATASection node or an EntityReference with <add> //Text and CDATA only children <add> if ((next.getNodeType() == Node.TEXT_NODE) || (next <add> .getNodeType() == Node.CDATA_SECTION_NODE) || <add> (next.getNodeType() == Node.ENTITY_REFERENCE_NODE && fTextOnlyChildren)) { <add> parent.removeChild(next); <add> next = this; <add> } <add> } <add> next = next.getNextSibling(); <add> } <add> <ide> return currentNode; <ide> } <ide> <ide> /** <del> * If any EntityReference to be removed has descendants <del> * that are not EntityReference, Text, or CDATASection <del> * nodes, the replaceWholeText method must fail before <del> * performing any modification of the document, raising a <del> * DOMException with the code NO_MODIFICATION_ALLOWED_ERR. <add> * If any EntityReference to be removed has descendants that are not <add> * EntityReference, Text, or CDATASection nodes, the replaceWholeText method <add> * must fail before performing any modification of the document, raising a <add> * DOMException with the code NO_MODIFICATION_ALLOWED_ERR. Traverse previous <add> * siblings of the node to be replaced. If a previous sibling is an <add> * EntityReference node, get it's last child. If the last child was a Text <add> * or CDATASection node and its previous siblings are neither a replaceable <add> * EntityReference or Text or CDATASection nodes, return false. IF the last <add> * child was neither Text nor CDATASection nor a replaceable EntityReference <add> * Node, then return true. If the last child was a Text or CDATASection node <add> * any its previous sibling was not or was an EntityReference that did not <add> * contain only Text or CDATASection nodes, return false. Check this recursively <add> * for EntityReference nodes. <ide> * <ide> * @param node <del> * @return true - can replace text <del> * false - can't replace exception must be raised <del> */ <del> private boolean canModify(Node node){ <del> while (node != null) { <del> short type = node.getNodeType(); <del> if (type == Node.ENTITY_REFERENCE_NODE) { <del> if (!canModify(node.getFirstChild())){ <del> return false; <add> * @return true - can replace text false - can't replace exception must be <add> * raised <add> */ <add> private boolean canModifyPrev(Node node) { <add> boolean textLastChild = false; <add> <add> short type = node.getNodeType(); <add> <add> if (type == Node.ENTITY_REFERENCE_NODE) { <add> //If the previous sibling was entityreference <add> //check if its content is replaceable <add> Node lastChild = node.getLastChild(); <add> <add> //if the entity reference has no children <add> //return false <add> if (lastChild == null) { <add> fTextOnlyChildren = false; <add> return false; <add> } <add> <add> //The replacement text of the entity reference should <add> //be either only text,cadatsections or replaceable entity <add> //reference nodes or the last child should be neither of these <add> while (lastChild != null) { <add> short lType = lastChild.getNodeType(); <add> <add> if (lType == Node.TEXT_NODE || lType == Node.CDATA_SECTION_NODE) { <add> textLastChild = true; <add> fTextOnlyChildren = true; <add> } else if (lType == Node.ENTITY_REFERENCE_NODE) { <add> if (!canModifyPrev(lastChild)) { <add> fTextOnlyChildren = false; <add> return false; <add> } else { <add> //If the EntityReference child contains <add> //only text, or non-text or ends with a <add> //non-text node. <add> textLastChild = true; <add> } <add> <add> } else { <add> if (textLastChild) { <add> fTextOnlyChildren = false; <add> return false; <add> } else { <add> return true; <add> } <ide> } <del> } <del> else if (type != Node.TEXT_NODE && <del> type != Node.CDATA_SECTION_NODE) { <add> lastChild = lastChild.getPreviousSibling(); <add> } <add> } else if (type == Node.TEXT_NODE || type == Node.CDATA_SECTION_NODE) { <add> //If the previous sibling was text or cdatasection move to next <add> fTextOnlyChildren = true; <add> } else { <add> //If the previous sibling was anything but text or <add> //cdatasection or an entity reference, stop search and <add> //return true <add> return true; <add> } <add> return true; <add> } <add> <add> /** <add> * If any EntityReference to be removed has descendants that are not <add> * EntityReference, Text, or CDATASection nodes, the replaceWholeText method <add> * must fail before performing any modification of the document, raising a <add> * DOMException with the code NO_MODIFICATION_ALLOWED_ERR. Traverse previous <add> * siblings of the node to be replaced. If a previous sibling is an <add> * EntityReference node, get it's last child. If the first child was a Text <add> * or CDATASection node and its next siblings are neither a replaceable <add> * EntityReference or Text or CDATASection nodes, return false. IF the first <add> * child was neither Text nor CDATASection nor a replaceable EntityReference <add> * Node, then return true. If the first child was a Text or CDATASection node <add> * any its next sibling was not or was an EntityReference that did not <add> * contain only Text or CDATASection nodes, return false. Check this recursively <add> * for EntityReference nodes. <add> * <add> * @param node <add> * @return true - can replace text false - can't replace exception must be <add> * raised <add> */ <add> <add> private boolean canModifyNext(Node node) { <add> boolean textFirstChild = false; <add> <add> short type = node.getNodeType(); <add> <add> if (type == Node.ENTITY_REFERENCE_NODE) { <add> //If the previous sibling was entityreference <add> //check if its content is replaceable <add> Node firstChild = node.getFirstChild(); <add> <add> //if the entity reference has no children <add> //return false <add> if (firstChild == null) { <add> fTextOnlyChildren = false; <ide> return false; <ide> } <del> <del> node = node.getNextSibling(); <add> <add> //The replacement text of the entity reference should <add> //be either only text,cadatsections or replaceable entity <add> //reference nodes or the last child should be neither of these <add> while (firstChild != null) { <add> short lType = firstChild.getNodeType(); <add> <add> if (lType == Node.TEXT_NODE || lType == Node.CDATA_SECTION_NODE) { <add> fTextOnlyChildren = true; <add> textFirstChild = true; <add> } else if (lType == Node.ENTITY_REFERENCE_NODE) { <add> if (!canModifyNext(firstChild)) { <add> fTextOnlyChildren = false; <add> return false; <add> } else { <add> //If the EntityReference child contains <add> //only text, or non-text or ends with a <add> //non-text node. <add> textFirstChild = true; <add> } <add> } else { <add> //If the first child was replaceable text and next <add> //children are not, then return false <add> if (textFirstChild) { <add> fTextOnlyChildren = false; <add> return false; <add> } else { <add> return true; <add> } <add> } <add> firstChild = firstChild.getNextSibling(); <add> } <add> } else if (type == Node.TEXT_NODE || type == Node.CDATA_SECTION_NODE) { <add> //If the previous sibling was text or cdatasection move to next <add> fTextOnlyChildren = true; <add> } else { <add> //If the next sibling was anything but text or <add> //cdatasection or an entity reference, stop search and <add> //return true <add> return true; <ide> } <ide> return true; <ide> } <ide> // Text methods <ide> // <ide> <del> /** <del> * Break a text node into two sibling nodes. (Note that if the <del> * current node has no parent, they won't wind up as "siblings" -- <del> * they'll both be orphans.) <del> * <del> * @param offset The offset at which to split. If offset is at the <del> * end of the available data, the second node will be empty. <del> * <del> * @return A reference to the new node (containing data after the <del> * offset point). The original node will contain data up to that <del> * point. <del> * <del> * @throws DOMException(INDEX_SIZE_ERR) if offset is <0 or >length. <del> * <del> * @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) if node is read-only. <add> /** <add> * Break a text node into two sibling nodes. (Note that if the current node <add> * has no parent, they won't wind up as "siblings" -- they'll both be <add> * orphans.) <add> * <add> * @param offset <add> * The offset at which to split. If offset is at the end of the <add> * available data, the second node will be empty. <add> * <add> * @return A reference to the new node (containing data after the offset <add> * point). The original node will contain data up to that point. <add> * <add> * @throws DOMException(INDEX_SIZE_ERR) <add> * if offset is <0 or >length. <add> * <add> * @throws DOMException(NO_MODIFICATION_ALLOWED_ERR) <add> * if node is read-only. <ide> */ <ide> public Text splitText(int offset) <ide> throws DOMException { <ide> <del> if (isReadOnly()) { <add> if (isReadOnly()) { <ide> throw new DOMException( <del> DOMException.NO_MODIFICATION_ALLOWED_ERR, <add> DOMException.NO_MODIFICATION_ALLOWED_ERR, <ide> DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "NO_MODIFICATION_ALLOWED_ERR", null)); <ide> } <ide> <ide> if (needsSyncData()) { <ide> synchronizeData(); <ide> } <del> if (offset < 0 || offset > data.length() ) { <add> if (offset < 0 || offset > data.length() ) { <ide> throw new DOMException(DOMException.INDEX_SIZE_ERR, <ide> DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN, "INDEX_SIZE_ERR", null)); <ide> } <del> <add> <ide> // split text into two separate nodes <del> Text newText = <add> Text newText = <ide> getOwnerDocument().createTextNode(data.substring(offset)); <del> setNodeValue(data.substring(0, offset)); <add> setNodeValue(data.substring(0, offset)); <ide> <ide> // insert new text node <ide> Node parentNode = getParentNode(); <del> if (parentNode != null) { <del> parentNode.insertBefore(newText, nextSibling); <del> } <del> <del> return newText; <add> if (parentNode != null) { <add> parentNode.insertBefore(newText, nextSibling); <add> } <add> <add> return newText; <ide> <ide> } // splitText(int):Text <ide> <ide> return olddata; <ide> } <ide> <del> <ide> } // class TextImpl
Java
mit
9413a2f132410196de6b1e4b9ca14be89ba27b16
0
elBukkit/MagicPlugin,elBukkit/MagicPlugin,elBukkit/MagicPlugin
package com.elmakers.mine.bukkit.magic.command; import com.elmakers.mine.bukkit.api.batch.Batch; import com.elmakers.mine.bukkit.api.block.BlockData; import com.elmakers.mine.bukkit.api.magic.Automaton; import com.elmakers.mine.bukkit.api.magic.Mage; import com.elmakers.mine.bukkit.api.magic.MageController; import com.elmakers.mine.bukkit.api.magic.MagicAPI; import com.elmakers.mine.bukkit.api.spell.SpellTemplate; import com.elmakers.mine.bukkit.api.wand.LostWand; import com.elmakers.mine.bukkit.api.wand.Wand; import com.elmakers.mine.bukkit.block.UndoList; import com.elmakers.mine.bukkit.magic.MagicController; import com.elmakers.mine.bukkit.utility.BoundingBox; import com.elmakers.mine.bukkit.utility.CompatibilityUtils; import com.elmakers.mine.bukkit.utility.DeprecatedUtils; import com.elmakers.mine.bukkit.utility.NMSUtils; import com.elmakers.mine.bukkit.utility.RunnableJob; import com.elmakers.mine.bukkit.wand.WandCleanupRunnable; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Ageable; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Skeleton; import org.bukkit.entity.Slime; import org.bukkit.entity.Villager; import org.bukkit.entity.Zombie; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; import org.bukkit.scheduler.BukkitTask; import org.bukkit.util.BlockVector; import org.bukkit.util.Vector; import java.io.File; import java.io.InputStream; import java.lang.reflect.Constructor; import java.net.URL; import java.security.CodeSource; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class MagicCommandExecutor extends MagicMapExecutor { private RunnableJob runningTask = null; public MagicCommandExecutor(MagicAPI api) { super(api); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (args.length == 0) { if (!api.hasPermission(sender, "Magic.commands.magic")) { sendNoPermission(sender); return true; } sender.sendMessage("Magic " + getMagicVersion()); return true; } String subCommand = args[0]; if (sender instanceof Player) { if (!api.hasPermission(sender, "Magic.commands.magic." + subCommand)) { sendNoPermission(sender); return true; } } if (subCommand.equalsIgnoreCase("rpcheck")) { api.getController().checkResourcePack(sender); return true; } if (subCommand.equalsIgnoreCase("save")) { api.save(); sender.sendMessage("Data saved."); return true; } if (subCommand.equalsIgnoreCase("load")) { api.reload(sender); return true; } if (subCommand.equalsIgnoreCase("clearcache")) { api.clearCache(); sender.sendMessage("Image map cache cleared."); return true; } if (subCommand.equalsIgnoreCase("commit")) { if (api.commit()) { sender.sendMessage("All changes committed"); } else { sender.sendMessage("Nothing to commit"); } return true; } if (subCommand.equalsIgnoreCase("give") || subCommand.equalsIgnoreCase("sell")) { Player player = null; int argStart = 1; if (sender instanceof Player) { if (args.length > 1) { player = DeprecatedUtils.getPlayer(args[1]); } if (player == null) { player = (Player)sender; } else { argStart = 2; } } else { if (args.length <= 1) { sender.sendMessage("Must specify a player name"); return true; } argStart = 2; player = DeprecatedUtils.getPlayer(args[1]); if (player == null) { sender.sendMessage("Can't find player " + args[1]); return true; } if (!player.isOnline()) { sender.sendMessage("Player " + args[1] + " is not online"); return true; } } String[] args2 = Arrays.copyOfRange(args, argStart, args.length); if (subCommand.equalsIgnoreCase("give") || subCommand.equalsIgnoreCase("sell")) { return onMagicGive(sender, player, subCommand, args2); } } if (subCommand.equalsIgnoreCase("worth")) { if (!(sender instanceof Player)) { sender.sendMessage("This command may only be used in-game"); return true; } Player player = (Player)sender; ItemStack item = player.getInventory().getItemInMainHand(); if (item == null || item.getType() == Material.AIR) { player.sendMessage("You must be holding an item"); return true; } showWorth(player, item); return true; } if (subCommand.equalsIgnoreCase("list")) { return onMagicList(sender, subCommand, args); } if (subCommand.equalsIgnoreCase("cancel")) { checkRunningTask(); if (runningTask != null) { runningTask.cancel(); runningTask = null; sender.sendMessage("Job cancelled"); } int stoppedPending = 0; for (Mage mage : api.getMages()) { while (mage.cancelPending() != null) stoppedPending++; } sender.sendMessage("Stopped " + stoppedPending + " pending spell casts"); return true; } if (subCommand.equalsIgnoreCase("clean")) { checkRunningTask(); if (runningTask != null) { sender.sendMessage("Cancel current job first"); return true; } World world = null; String owner = null; if (args.length > 1) { owner = args[1]; } if (sender instanceof Player) { world = ((Player)sender).getWorld(); } else { if (args.length > 2) { String worldName = args[2]; world = Bukkit.getWorld(worldName); } } boolean check = false; if (owner != null && owner.equals("check")){ check = true; owner = "ALL"; } String description = check ? "Checking for" : "Cleaning up"; String ownerName = owner == null ? "(Unowned)" : owner; if (world == null) { sender.sendMessage(description + " lost wands in all worlds for owner: " + ownerName); } else if (ownerName.equals("ALL")) { sender.sendMessage(description + " lost wands in world '" + world.getName() + "' for ALL owners"); } else { sender.sendMessage(description + " lost wands in world '" + world.getName() + "' for owner " + ownerName); } runningTask = new WandCleanupRunnable(api, world, owner, check); runningTask.runTaskTimer(api.getPlugin(), 5, 5); return true; } sender.sendMessage("Unknown magic command: " + subCommand); return true; } protected boolean onMagicList(CommandSender sender, String subCommand, String[] args) { String usage = "Usage: magic list <wands|map|automata|tasks|schematics|entities|blocks>"; String listCommand = ""; if (args.length > 1) { listCommand = args[1]; if (!api.hasPermission(sender, "Magic.commands.magic." + subCommand + "." + listCommand)) { sendNoPermission(sender); return false; } } else { sender.sendMessage(ChatColor.GRAY + "For more specific information, add 'tasks', 'wands', 'maps', 'schematics', 'entities', 'blocks' or 'automata' parameter."); MageController apiController = api.getController(); if (apiController != null && apiController instanceof MagicController) { MagicController controller = (MagicController)apiController; long timeout = controller.getPhysicsTimeout(); if (timeout > 0) { long seconds = (timeout - System.currentTimeMillis()) / 1000; sender.sendMessage(ChatColor.GREEN + "Physics handler active for another " + ChatColor.DARK_GREEN + seconds + ChatColor.GREEN + " seconds"); } else { sender.sendMessage(ChatColor.GRAY + "Physics handler inactive"); } } Collection<Mage> mages = api.getMages(); sender.sendMessage(ChatColor.AQUA + "Modified blocks (" + ChatColor.LIGHT_PURPLE + UndoList.getModified().size() + ChatColor.AQUA + ")"); sender.sendMessage(ChatColor.AQUA + "Watching blocks (" + ChatColor.LIGHT_PURPLE + UndoList.getWatching().size() + ChatColor.AQUA + ")"); sender.sendMessage(ChatColor.AQUA + "Registered breakable (" + ChatColor.LIGHT_PURPLE + UndoList.getBreakable().size() + ChatColor.AQUA + ")"); sender.sendMessage(ChatColor.AQUA + "Registered reflective (" + ChatColor.LIGHT_PURPLE + UndoList.getReflective().size() + ChatColor.AQUA + ")"); sender.sendMessage(ChatColor.LIGHT_PURPLE + "Active mages: " + ChatColor.LIGHT_PURPLE + mages.size()); Collection<com.elmakers.mine.bukkit.api.block.UndoList> pendingUndo = api.getPendingUndo(); sender.sendMessage(ChatColor.AQUA + "Pending undo (" + ChatColor.LIGHT_PURPLE + pendingUndo.size() + ChatColor.AQUA + "): "); long now = System.currentTimeMillis(); for (com.elmakers.mine.bukkit.api.block.UndoList undo : pendingUndo) { long remainingTime = (undo.getScheduledTime() - now) / 1000; sender.sendMessage(ChatColor.AQUA + undo.getName() + ChatColor.GRAY + " will undo in " + ChatColor.WHITE + "" + remainingTime + "" + ChatColor.GRAY + " seconds"); } Collection<Mage> pending = api.getMagesWithPendingBatches(); sender.sendMessage(ChatColor.AQUA + "Pending casts (" + ChatColor.LIGHT_PURPLE + pending.size() + ChatColor.AQUA + "): "); for (Mage mage : pending) { int totalSize = 0; int totalRemaining = 0; Collection<Batch> pendingBatches = mage.getPendingBatches(); String names = ""; if (pendingBatches.size() > 0) { for (Batch batch : pendingBatches) { names = names + batch.getName() + " "; totalSize += batch.size(); totalRemaining = batch.remaining(); } } sender.sendMessage(ChatColor.AQUA + mage.getName() + ChatColor.GRAY + " has " + ChatColor.WHITE + "" + pendingBatches.size() + "" + ChatColor.GRAY + " pending (" + ChatColor.WHITE + "" + totalRemaining + "/" + totalSize + "" + ChatColor.GRAY + ") (" + names + ")"); } return true; } if (listCommand.equalsIgnoreCase("schematics")) { List<String> schematics = new ArrayList<String>(); try { Plugin plugin = (Plugin)api; MagicController controller = (MagicController)api.getController(); // Find built-in schematics CodeSource src = MagicAPI.class.getProtectionDomain().getCodeSource(); if (src != null) { URL jar = src.getLocation(); try(InputStream is = jar.openStream(); ZipInputStream zip = new ZipInputStream(is)) { while(true) { ZipEntry e = zip.getNextEntry(); if (e == null) break; String name = e.getName(); if (name.startsWith("schematics/")) { schematics.add(name.replace("schematics/", "")); } } } } // Check extra path first File configFolder = plugin.getDataFolder(); File magicSchematicFolder = new File(configFolder, "schematics"); if (magicSchematicFolder.exists()) { for (File nextFile : magicSchematicFolder.listFiles()) { schematics.add(nextFile.getName()); } } String extraSchematicFilePath = controller.getExtraSchematicFilePath(); if (extraSchematicFilePath != null && extraSchematicFilePath.length() > 0) { File schematicFolder = new File(configFolder, "../" + extraSchematicFilePath); if (schematicFolder.exists() && !schematicFolder.equals(magicSchematicFolder)) { for (File nextFile : schematicFolder.listFiles()) { schematics.add(nextFile.getName()); } } } } catch (Exception ex) { sender.sendMessage("Error loading schematics: " + ex.getMessage()); ex.printStackTrace();; } sender.sendMessage(ChatColor.DARK_AQUA + "Found " + ChatColor.LIGHT_PURPLE + schematics.size() + ChatColor.DARK_AQUA + " schematics"); Collections.sort(schematics); for (String schematic : schematics) { if (schematic.indexOf(".schematic") > 0) { sender.sendMessage(ChatColor.AQUA + schematic.replace(".schematic", "")); } } return true; } if (listCommand.equalsIgnoreCase("tasks")) { List<BukkitTask> tasks = Bukkit.getScheduler().getPendingTasks(); HashMap<String, Integer> pluginCounts = new HashMap<String, Integer>(); HashMap<String, HashMap<String, Integer>> taskCounts = new HashMap<String, HashMap<String, Integer>>(); for (BukkitTask task : tasks) { String pluginName = task.getOwner().getName(); HashMap<String, Integer> pluginTaskCounts = taskCounts.get(pluginName); if (pluginTaskCounts == null) { pluginTaskCounts = new HashMap<String, Integer>(); taskCounts.put(pluginName, pluginTaskCounts); } String className = "(Unknown)"; Runnable taskRunnable = CompatibilityUtils.getTaskRunnable(task); if (taskRunnable != null) { Class<? extends Runnable> taskClass = taskRunnable.getClass(); className = taskClass.getName(); } Integer count = pluginTaskCounts.get(className); if (count == null) count = 0; count++; pluginTaskCounts.put(className, count); Integer totalCount = pluginCounts.get(pluginName); if (totalCount == null) totalCount = 0; totalCount++; pluginCounts.put(pluginName, totalCount); } sender.sendMessage(ChatColor.LIGHT_PURPLE + "Active tasks: " + tasks.size()); for (Entry<String, HashMap<String, Integer>> pluginEntry : taskCounts.entrySet()) { String pluginName = pluginEntry.getKey(); sender.sendMessage(" " + ChatColor.DARK_PURPLE + pluginName + ": " + ChatColor.LIGHT_PURPLE + pluginCounts.get(pluginName)); for (Entry<String, Integer> taskEntry : pluginEntry.getValue().entrySet()) { sender.sendMessage(" " + ChatColor.DARK_PURPLE + taskEntry.getKey() + ": " + ChatColor.LIGHT_PURPLE + taskEntry.getValue()); } } return true; } if (listCommand.equalsIgnoreCase("wands")) { String owner = ""; if (args.length > 2) { owner = args[2]; } Collection<LostWand> lostWands = api.getLostWands(); int shown = 0; for (LostWand lostWand : lostWands) { Location location = lostWand.getLocation(); if (location == null) continue; if (owner.length() > 0 && !owner.equalsIgnoreCase (lostWand.getOwner())) { continue; } shown++; sender.sendMessage(ChatColor.AQUA + lostWand.getName() + ChatColor.WHITE + " (" + lostWand.getOwner() + ") @ " + ChatColor.BLUE + location.getWorld().getName() + " " + location.getBlockX() + " " + location.getBlockY() + " " + location.getBlockZ()); } sender.sendMessage(shown + " lost wands found" + (owner.length() > 0 ? " for " + owner : "")); return true; } if (listCommand.equalsIgnoreCase("automata")) { Collection<Automaton> automata = api.getAutomata(); for (Automaton automaton : automata) { BlockVector location = automaton.getPosition(); String worldName = automaton.getWorldName(); boolean isOnline = false; World world = Bukkit.getWorld(worldName); if (worldName != null) { isOnline = world.isChunkLoaded(location.getBlockX() >> 4, location.getBlockZ() >> 4); } ChatColor nameColor = isOnline ? ChatColor.AQUA : ChatColor.GRAY; sender.sendMessage(nameColor + automaton.getName() + ChatColor.WHITE + " @ " + ChatColor.BLUE + worldName + " " + location.getBlockX() + " " + location.getBlockY() + " " + location.getBlockZ()); } sender.sendMessage(automata.size() + " automata active"); return true; } if (listCommand.equalsIgnoreCase("maps")) { String keyword = ""; for (int i = 2; i < args.length; i++) { if (i != 2) keyword = keyword + " "; keyword = keyword + args[i]; } onMapList(sender, keyword); return true; } if (listCommand.equalsIgnoreCase("blocks")) { for (BlockData blockData : UndoList.getModified().values()) { BlockVector blockLocation = blockData.getLocation(); Block block = blockData.getBlock(); sender.sendMessage(ChatColor.BLUE + "Block at " + ChatColor.GRAY + blockLocation.getBlockX() + ChatColor.DARK_GRAY + "," + ChatColor.GRAY + blockLocation.getBlockY() + ChatColor.DARK_GRAY + "," + ChatColor.GRAY + blockLocation.getBlockZ() + ChatColor.BLUE + " stored as " + ChatColor.AQUA + blockData.getMaterial() + ChatColor.BLUE + " is currently " + ChatColor.AQUA + block.getType() + ChatColor.BLUE + " from " + ChatColor.GOLD + blockData.getUndoList().getName()); } return true; } if (listCommand.equalsIgnoreCase("mages")) { for (Mage mage : api.getController().getMages()) { Entity mageEntity = mage.getEntity(); String mageType = mageEntity == null ? "Non-Entity" : mageEntity.getType().name(); sender.sendMessage(ChatColor.AQUA + "Mage id " + ChatColor.YELLOW + mage.getId() + ChatColor.GRAY + " (" + mage.getName() + ") " + ChatColor.AQUA + " of type " + ChatColor.DARK_AQUA + mageType + ChatColor.AQUA); } return true; } if (listCommand.equalsIgnoreCase("entities")) { World world = Bukkit.getWorlds().get(0); NumberFormat formatter = new DecimalFormat("#0.0"); List<EntityType> types = Arrays.asList(EntityType.values()); Collections.sort(types, new Comparator<EntityType>() { @Override public int compare(EntityType o1, EntityType o2) { return o1.name().compareTo(o2.name()); } }); Collection<? extends Player> players = Bukkit.getServer().getOnlinePlayers(); for (Player player : players) { showEntityInfo(sender, player, EntityType.PLAYER.name() + ChatColor.GRAY + " (" + player.getName() + " [" + (player.isSneaking() ? "sneaking" : "standing") + "])", formatter); break; } final Class<?> worldClass = NMSUtils.getBukkitClass("net.minecraft.server.World"); for (EntityType entityType : types) { if (entityType.isSpawnable()) { Entity testEntity = null; String errorMessage = null; String entityName = "Entity" + entityType.getEntityClass().getSimpleName(); // A few hacky special cases :( // Still better than actually adding all of these entities to the world! if (entityName.equals("EntityGiant")) { entityName = "EntityGiantZombie"; } else if (entityName.equals("EntityLeashHitch")) { entityName = "EntityLeash"; } else if (entityName.equals("EntityStorageMinecart")) { entityName = "EntityMinecartChest"; } else if (entityName.equals("EntitySpawnerMinecart")) { entityName = "EntityMinecartMobSpawner"; } else if (entityName.equals("EntityCommandMinecart")) { entityName = "EntityMinecartCommandBlock"; } else if (entityName.equals("EntityPoweredMinecart")) { entityName = "EntityMinecartFurnace"; } else if (entityName.equals("EntityExplosiveMinecart")) { entityName = "EntityMinecartTNT"; } else if (entityName.contains("Minecart")) { entityName = entityType.getEntityClass().getSimpleName(); entityName = entityName.replace("Minecart", ""); entityName = "EntityMinecart" + entityName; } try { Class<?> entityClass = NMSUtils.getBukkitClass("net.minecraft.server." + entityName); if (entityClass != null) { Constructor<? extends Object> constructor = entityClass.getConstructor(worldClass); Object nmsWorld = NMSUtils.getHandle(world); Object nmsEntity = constructor.newInstance(nmsWorld); testEntity = NMSUtils.getBukkitEntity(nmsEntity); if (testEntity == null) { errorMessage = "Failed to get Bukkit entity for class " + entityName; } } else { errorMessage = "Could not load class " + entityName; } } catch (Exception ex) { testEntity = null; errorMessage = ex.getClass().getSimpleName() + " [" + entityName + "]"; String message = ex.getMessage(); if (message != null && !message.isEmpty()) { errorMessage += ": " + message; } } if (testEntity == null) { sender.sendMessage(ChatColor.BLACK + entityType.name() + ": " + ChatColor.RED + "Spawning error " + ChatColor.DARK_RED + "(" + errorMessage + ")"); continue; } String label = entityType.name(); Ageable ageable = (testEntity instanceof Ageable) ? (Ageable)testEntity : null; Zombie zombie = (testEntity instanceof Zombie) ? (Zombie)testEntity : null; Skeleton skeleton = (testEntity instanceof Skeleton) ? (Skeleton)testEntity : null; Slime slime = (testEntity instanceof Slime) ? (Slime)testEntity : null; if (ageable != null) { label = label + ChatColor.GRAY + " (Adult)"; ageable.setAdult(); } else if (zombie != null) { label = label + ChatColor.GRAY + " (Adult)"; zombie.setBaby(false); zombie.setVillagerProfession(null); } else if (skeleton != null) { label = label + ChatColor.GRAY + " (NORMAL)"; skeleton.setSkeletonType(Skeleton.SkeletonType.NORMAL); } else if (slime != null) { label = label + ChatColor.GRAY + " (Size 1)"; slime.setSize(1); } showEntityInfo(sender, testEntity, label, formatter); if (ageable != null) { label = entityType.name() + ChatColor.GRAY + " (Baby)"; ageable.setBaby(); showEntityInfo(sender, testEntity, label, formatter); } else if (zombie != null) { label = entityType.name() + ChatColor.GRAY + " (Baby)"; zombie.setBaby(true); showEntityInfo(sender, testEntity, label, formatter); label = entityType.name() + ChatColor.GRAY + " (Villager)"; zombie.setBaby(false); zombie.setVillagerProfession(Villager.Profession.FARMER); showEntityInfo(sender, testEntity, label, formatter); label = entityType.name() + ChatColor.GRAY + " (Baby Villager)"; zombie.setBaby(true); showEntityInfo(sender, testEntity, label, formatter); } else if (skeleton != null) { label = entityType.name() + ChatColor.GRAY + " (WITHER)"; skeleton.setSkeletonType(Skeleton.SkeletonType.WITHER); showEntityInfo(sender, testEntity, label, formatter); } else if (slime != null) { label = entityType.name() + ChatColor.GRAY + " (Size 2)"; slime.setSize(2); showEntityInfo(sender, testEntity, label, formatter); label = entityType.name() + ChatColor.GRAY + " (Size 4)"; slime.setSize(4); showEntityInfo(sender, testEntity, label, formatter); label = entityType.name() + ChatColor.GRAY + " (Size 8)"; slime.setSize(8); showEntityInfo(sender, testEntity, label, formatter); label = entityType.name() + ChatColor.GRAY + " (Size 16)"; slime.setSize(16); showEntityInfo(sender, testEntity, label, formatter); } } } return true; } sender.sendMessage(usage); return true; } private void showEntityInfo(CommandSender sender, Entity entity, String label, NumberFormat formatter) { BoundingBox hitbox = CompatibilityUtils.getHitbox(entity); Vector size = hitbox.size(); String message = ChatColor.BLACK + label + ": " + ChatColor.AQUA + formatter.format(size.getX()) + ChatColor.DARK_GRAY + "x" + ChatColor.AQUA + formatter.format(size.getY()) + ChatColor.DARK_GRAY + "x" + ChatColor.AQUA + formatter.format(size.getZ()); if (entity instanceof LivingEntity) { LivingEntity li = (LivingEntity)entity; message += ChatColor.DARK_GRAY + ", " + ChatColor.GREEN + ((int)li.getMaxHealth()) + "hp"; } sender.sendMessage(message); } protected boolean onMagicGive(CommandSender sender, Player player, String command, String[] args) { String playerCommand = (sender instanceof Player) ? "" : "<player> "; String usageString = "Usage: /magic give " + playerCommand + "<spellname|'material'|'upgrade'|'wand'> [materialname|wandname]"; if (args.length == 0) { sender.sendMessage(usageString); return true; } String key = ""; boolean isMaterial = false; boolean isWand = false; boolean isUpgrade = false; if (args.length > 1 && !args[0].equals("material") && !args[0].equals("wand") && !args[0].equals("upgrade")) { sender.sendMessage(usageString); return true; } if (args[0].equals("wand")) { isWand = true; key = args.length > 1 ? args[1] : ""; } else if (args[0].equals("upgrade")) { isUpgrade = true; key = args.length > 1 ? args[1] : ""; } else if (args[0].equals("material")) { if (args.length < 2) { sender.sendMessage(usageString); return true; } isMaterial = true; key = args[1]; } else { key = args[0]; } boolean giveItem = command.equals("give") || command.equals("sell"); boolean showWorth = command.equals("worth") || command.equals("sell"); boolean giveValue = command.equals("sell"); if (isWand) { giveWand(sender, player, key, false, giveItem, giveValue, showWorth); } else if (isMaterial) { onGiveBrush(sender, player, key, false, giveItem, giveValue, showWorth); } else if (isUpgrade) { onGiveUpgrade(sender, player, key, false, giveItem, giveValue, showWorth); } else { onGive(sender, player, key, giveItem, giveValue, showWorth); } return true; } protected void onGive(CommandSender sender, Player player, String key, boolean giveItem, boolean giveValue, boolean showWorth) { if (!onGiveSpell(sender, player, key, true, giveItem, giveValue, showWorth)) { if (!onGiveBrush(sender, player, key, true, giveItem, giveValue, showWorth)) { if (!giveWand(sender, player, key, true, giveItem, giveValue, showWorth)) { sender.sendMessage("Failed to create a spell, brush or wand item for " + key); } } } } protected boolean onGiveSpell(CommandSender sender, Player player, String spellKey, boolean quiet, boolean giveItem, boolean giveValue, boolean showWorth) { ItemStack itemStack = api.createSpellItem(spellKey); if (itemStack == null) { if (!quiet) sender.sendMessage("Failed to create spell item for " + spellKey); return false; } if (giveItem) { api.giveItemToPlayer(player, itemStack); if (sender != player && !quiet) { sender.sendMessage("Gave spell " + spellKey + " to " + player.getName()); } } if (showWorth) { showWorth(sender, itemStack); } return true; } protected boolean onGiveBrush(CommandSender sender, Player player, String materialKey, boolean quiet, boolean giveItem, boolean giveValue, boolean showWorth) { ItemStack itemStack = api.createBrushItem(materialKey); if (itemStack == null) { if (!quiet) sender.sendMessage("Failed to create material item for " + materialKey); return false; } if (giveItem) { api.giveItemToPlayer(player, itemStack); if (sender != player && !quiet) { sender.sendMessage("Gave brush " + materialKey + " to " + player.getName()); } } if (showWorth) { showWorth(sender, itemStack); } return true; } protected boolean onGiveUpgrade(CommandSender sender, Player player, String wandKey, boolean quiet, boolean giveItem, boolean giveValue, boolean showWorth) { Mage mage = api.getMage(player); Wand currentWand = mage.getActiveWand(); if (currentWand != null) { currentWand.closeInventory(); } Wand wand = api.createWand(wandKey); if (wand != null) { wand.makeUpgrade(); if (giveItem) { api.giveItemToPlayer(player, wand.getItem()); if (sender != player && !quiet) { sender.sendMessage("Gave upgrade " + wand.getName() + " to " + player.getName()); } } if (showWorth) { showWorth(sender, wand.getItem()); } } else { if (!quiet) sender.sendMessage(api.getMessages().getParameterized("wand.unknown_template", "$name", wandKey)); return false; } return true; } protected void checkRunningTask() { if (runningTask != null && runningTask.isFinished()) { runningTask = null; } } @Override public Collection<String> onTabComplete(CommandSender sender, String commandName, String[] args) { List<String> options = new ArrayList<String>(); if (args.length == 1) { addIfPermissible(sender, options, "Magic.commands.magic.", "clean"); addIfPermissible(sender, options, "Magic.commands.magic.", "clearcache"); addIfPermissible(sender, options, "Magic.commands.magic.", "cancel"); addIfPermissible(sender, options, "Magic.commands.magic.", "load"); addIfPermissible(sender, options, "Magic.commands.magic.", "save"); addIfPermissible(sender, options, "Magic.commands.magic.", "commit"); addIfPermissible(sender, options, "Magic.commands.magic.", "give"); addIfPermissible(sender, options, "Magic.commands.magic.", "worth"); addIfPermissible(sender, options, "Magic.commands.magic.", "sell"); addIfPermissible(sender, options, "Magic.commands.magic.", "list"); } else if (args.length == 2) { if (args[0].equalsIgnoreCase("list")) { addIfPermissible(sender, options, "Magic.commands.magic.list", "maps"); addIfPermissible(sender, options, "Magic.commands.magic.list", "wands"); addIfPermissible(sender, options, "Magic.commands.magic.list", "automata"); addIfPermissible(sender, options, "Magic.commands.magic.list", "schematics"); addIfPermissible(sender, options, "Magic.commands.magic.list", "entities"); addIfPermissible(sender, options, "Magic.commands.magic.list", "tasks"); addIfPermissible(sender, options, "Magic.commands.magic.list", "blocks"); addIfPermissible(sender, options, "Magic.commands.magic.list", "mages"); } else if (args[0].equalsIgnoreCase("give") || args[0].equalsIgnoreCase("worth") || args[0].equalsIgnoreCase("sell")) { options.add("wand"); options.add("material"); options.add("upgrade"); Collection<SpellTemplate> spellList = api.getSpellTemplates(sender.hasPermission("Magic.bypass_hidden")); for (SpellTemplate spell : spellList) { options.add(spell.getKey()); } Collection<String> allWands = api.getWandKeys(); for (String wandKey : allWands) { options.add(wandKey); } options.addAll(api.getBrushes()); } } else if (args.length == 3) { if (args[0].equalsIgnoreCase("give") || args[0].equalsIgnoreCase("sell")) { if (args[1].equalsIgnoreCase("upgrade") || args[1].equalsIgnoreCase("wand")) { Collection<String> allWands = api.getWandKeys(); for (String wandKey : allWands) { options.add(wandKey); } } else if (args[1].equalsIgnoreCase("material")) { options.addAll(api.getBrushes()); } } else if (args[0].equalsIgnoreCase("configure") || args[0].equalsIgnoreCase("describe")) { Player player = DeprecatedUtils.getPlayer(args[1]); if (player != null) { Mage mage = api.getMage(player); ConfigurationSection data = mage.getData(); options.addAll(data.getKeys(false)); } } } return options; } }
Magic/src/main/java/com/elmakers/mine/bukkit/magic/command/MagicCommandExecutor.java
package com.elmakers.mine.bukkit.magic.command; import com.elmakers.mine.bukkit.api.batch.Batch; import com.elmakers.mine.bukkit.api.block.BlockData; import com.elmakers.mine.bukkit.api.magic.Automaton; import com.elmakers.mine.bukkit.api.magic.Mage; import com.elmakers.mine.bukkit.api.magic.MageController; import com.elmakers.mine.bukkit.api.magic.MagicAPI; import com.elmakers.mine.bukkit.api.spell.SpellTemplate; import com.elmakers.mine.bukkit.api.wand.LostWand; import com.elmakers.mine.bukkit.api.wand.Wand; import com.elmakers.mine.bukkit.block.UndoList; import com.elmakers.mine.bukkit.magic.MagicController; import com.elmakers.mine.bukkit.utility.BoundingBox; import com.elmakers.mine.bukkit.utility.CompatibilityUtils; import com.elmakers.mine.bukkit.utility.DeprecatedUtils; import com.elmakers.mine.bukkit.utility.NMSUtils; import com.elmakers.mine.bukkit.utility.RunnableJob; import com.elmakers.mine.bukkit.wand.WandCleanupRunnable; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Ageable; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Skeleton; import org.bukkit.entity.Slime; import org.bukkit.entity.Villager; import org.bukkit.entity.Zombie; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; import org.bukkit.scheduler.BukkitTask; import org.bukkit.util.BlockVector; import org.bukkit.util.Vector; import java.io.File; import java.lang.reflect.Constructor; import java.net.URL; import java.security.CodeSource; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class MagicCommandExecutor extends MagicMapExecutor { private RunnableJob runningTask = null; public MagicCommandExecutor(MagicAPI api) { super(api); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (args.length == 0) { if (!api.hasPermission(sender, "Magic.commands.magic")) { sendNoPermission(sender); return true; } sender.sendMessage("Magic " + getMagicVersion()); return true; } String subCommand = args[0]; if (sender instanceof Player) { if (!api.hasPermission(sender, "Magic.commands.magic." + subCommand)) { sendNoPermission(sender); return true; } } if (subCommand.equalsIgnoreCase("rpcheck")) { api.getController().checkResourcePack(sender); return true; } if (subCommand.equalsIgnoreCase("save")) { api.save(); sender.sendMessage("Data saved."); return true; } if (subCommand.equalsIgnoreCase("load")) { api.reload(sender); return true; } if (subCommand.equalsIgnoreCase("clearcache")) { api.clearCache(); sender.sendMessage("Image map cache cleared."); return true; } if (subCommand.equalsIgnoreCase("commit")) { if (api.commit()) { sender.sendMessage("All changes committed"); } else { sender.sendMessage("Nothing to commit"); } return true; } if (subCommand.equalsIgnoreCase("give") || subCommand.equalsIgnoreCase("sell")) { Player player = null; int argStart = 1; if (sender instanceof Player) { if (args.length > 1) { player = DeprecatedUtils.getPlayer(args[1]); } if (player == null) { player = (Player)sender; } else { argStart = 2; } } else { if (args.length <= 1) { sender.sendMessage("Must specify a player name"); return true; } argStart = 2; player = DeprecatedUtils.getPlayer(args[1]); if (player == null) { sender.sendMessage("Can't find player " + args[1]); return true; } if (!player.isOnline()) { sender.sendMessage("Player " + args[1] + " is not online"); return true; } } String[] args2 = Arrays.copyOfRange(args, argStart, args.length); if (subCommand.equalsIgnoreCase("give") || subCommand.equalsIgnoreCase("sell")) { return onMagicGive(sender, player, subCommand, args2); } } if (subCommand.equalsIgnoreCase("worth")) { if (!(sender instanceof Player)) { sender.sendMessage("This command may only be used in-game"); return true; } Player player = (Player)sender; ItemStack item = player.getInventory().getItemInMainHand(); if (item == null || item.getType() == Material.AIR) { player.sendMessage("You must be holding an item"); return true; } showWorth(player, item); return true; } if (subCommand.equalsIgnoreCase("list")) { return onMagicList(sender, subCommand, args); } if (subCommand.equalsIgnoreCase("cancel")) { checkRunningTask(); if (runningTask != null) { runningTask.cancel(); runningTask = null; sender.sendMessage("Job cancelled"); } int stoppedPending = 0; for (Mage mage : api.getMages()) { while (mage.cancelPending() != null) stoppedPending++; } sender.sendMessage("Stopped " + stoppedPending + " pending spell casts"); return true; } if (subCommand.equalsIgnoreCase("clean")) { checkRunningTask(); if (runningTask != null) { sender.sendMessage("Cancel current job first"); return true; } World world = null; String owner = null; if (args.length > 1) { owner = args[1]; } if (sender instanceof Player) { world = ((Player)sender).getWorld(); } else { if (args.length > 2) { String worldName = args[2]; world = Bukkit.getWorld(worldName); } } boolean check = false; if (owner != null && owner.equals("check")){ check = true; owner = "ALL"; } String description = check ? "Checking for" : "Cleaning up"; String ownerName = owner == null ? "(Unowned)" : owner; if (world == null) { sender.sendMessage(description + " lost wands in all worlds for owner: " + ownerName); } else if (ownerName.equals("ALL")) { sender.sendMessage(description + " lost wands in world '" + world.getName() + "' for ALL owners"); } else { sender.sendMessage(description + " lost wands in world '" + world.getName() + "' for owner " + ownerName); } runningTask = new WandCleanupRunnable(api, world, owner, check); runningTask.runTaskTimer(api.getPlugin(), 5, 5); return true; } sender.sendMessage("Unknown magic command: " + subCommand); return true; } protected boolean onMagicList(CommandSender sender, String subCommand, String[] args) { String usage = "Usage: magic list <wands|map|automata|tasks|schematics|entities|blocks>"; String listCommand = ""; if (args.length > 1) { listCommand = args[1]; if (!api.hasPermission(sender, "Magic.commands.magic." + subCommand + "." + listCommand)) { sendNoPermission(sender); return false; } } else { sender.sendMessage(ChatColor.GRAY + "For more specific information, add 'tasks', 'wands', 'maps', 'schematics', 'entities', 'blocks' or 'automata' parameter."); MageController apiController = api.getController(); if (apiController != null && apiController instanceof MagicController) { MagicController controller = (MagicController)apiController; long timeout = controller.getPhysicsTimeout(); if (timeout > 0) { long seconds = (timeout - System.currentTimeMillis()) / 1000; sender.sendMessage(ChatColor.GREEN + "Physics handler active for another " + ChatColor.DARK_GREEN + seconds + ChatColor.GREEN + " seconds"); } else { sender.sendMessage(ChatColor.GRAY + "Physics handler inactive"); } } Collection<Mage> mages = api.getMages(); sender.sendMessage(ChatColor.AQUA + "Modified blocks (" + ChatColor.LIGHT_PURPLE + UndoList.getModified().size() + ChatColor.AQUA + ")"); sender.sendMessage(ChatColor.AQUA + "Watching blocks (" + ChatColor.LIGHT_PURPLE + UndoList.getWatching().size() + ChatColor.AQUA + ")"); sender.sendMessage(ChatColor.AQUA + "Registered breakable (" + ChatColor.LIGHT_PURPLE + UndoList.getBreakable().size() + ChatColor.AQUA + ")"); sender.sendMessage(ChatColor.AQUA + "Registered reflective (" + ChatColor.LIGHT_PURPLE + UndoList.getReflective().size() + ChatColor.AQUA + ")"); sender.sendMessage(ChatColor.LIGHT_PURPLE + "Active mages: " + ChatColor.LIGHT_PURPLE + mages.size()); Collection<com.elmakers.mine.bukkit.api.block.UndoList> pendingUndo = api.getPendingUndo(); sender.sendMessage(ChatColor.AQUA + "Pending undo (" + ChatColor.LIGHT_PURPLE + pendingUndo.size() + ChatColor.AQUA + "): "); long now = System.currentTimeMillis(); for (com.elmakers.mine.bukkit.api.block.UndoList undo : pendingUndo) { long remainingTime = (undo.getScheduledTime() - now) / 1000; sender.sendMessage(ChatColor.AQUA + undo.getName() + ChatColor.GRAY + " will undo in " + ChatColor.WHITE + "" + remainingTime + "" + ChatColor.GRAY + " seconds"); } Collection<Mage> pending = api.getMagesWithPendingBatches(); sender.sendMessage(ChatColor.AQUA + "Pending casts (" + ChatColor.LIGHT_PURPLE + pending.size() + ChatColor.AQUA + "): "); for (Mage mage : pending) { int totalSize = 0; int totalRemaining = 0; Collection<Batch> pendingBatches = mage.getPendingBatches(); String names = ""; if (pendingBatches.size() > 0) { for (Batch batch : pendingBatches) { names = names + batch.getName() + " "; totalSize += batch.size(); totalRemaining = batch.remaining(); } } sender.sendMessage(ChatColor.AQUA + mage.getName() + ChatColor.GRAY + " has " + ChatColor.WHITE + "" + pendingBatches.size() + "" + ChatColor.GRAY + " pending (" + ChatColor.WHITE + "" + totalRemaining + "/" + totalSize + "" + ChatColor.GRAY + ") (" + names + ")"); } return true; } if (listCommand.equalsIgnoreCase("schematics")) { List<String> schematics = new ArrayList<String>(); try { Plugin plugin = (Plugin)api; MagicController controller = (MagicController)api.getController(); // Find built-in schematics CodeSource src = MagicAPI.class.getProtectionDomain().getCodeSource(); if (src != null) { URL jar = src.getLocation(); ZipInputStream zip = new ZipInputStream(jar.openStream()); while(true) { ZipEntry e = zip.getNextEntry(); if (e == null) break; String name = e.getName(); if (name.startsWith("schematics/")) { schematics.add(name.replace("schematics/", "")); } } } // Check extra path first File configFolder = plugin.getDataFolder(); File magicSchematicFolder = new File(configFolder, "schematics"); if (magicSchematicFolder.exists()) { for (File nextFile : magicSchematicFolder.listFiles()) { schematics.add(nextFile.getName()); } } String extraSchematicFilePath = controller.getExtraSchematicFilePath(); if (extraSchematicFilePath != null && extraSchematicFilePath.length() > 0) { File schematicFolder = new File(configFolder, "../" + extraSchematicFilePath); if (schematicFolder.exists() && !schematicFolder.equals(magicSchematicFolder)) { for (File nextFile : schematicFolder.listFiles()) { schematics.add(nextFile.getName()); } } } } catch (Exception ex) { sender.sendMessage("Error loading schematics: " + ex.getMessage()); ex.printStackTrace();; } sender.sendMessage(ChatColor.DARK_AQUA + "Found " + ChatColor.LIGHT_PURPLE + schematics.size() + ChatColor.DARK_AQUA + " schematics"); Collections.sort(schematics); for (String schematic : schematics) { if (schematic.indexOf(".schematic") > 0) { sender.sendMessage(ChatColor.AQUA + schematic.replace(".schematic", "")); } } return true; } if (listCommand.equalsIgnoreCase("tasks")) { List<BukkitTask> tasks = Bukkit.getScheduler().getPendingTasks(); HashMap<String, Integer> pluginCounts = new HashMap<String, Integer>(); HashMap<String, HashMap<String, Integer>> taskCounts = new HashMap<String, HashMap<String, Integer>>(); for (BukkitTask task : tasks) { String pluginName = task.getOwner().getName(); HashMap<String, Integer> pluginTaskCounts = taskCounts.get(pluginName); if (pluginTaskCounts == null) { pluginTaskCounts = new HashMap<String, Integer>(); taskCounts.put(pluginName, pluginTaskCounts); } String className = "(Unknown)"; Runnable taskRunnable = CompatibilityUtils.getTaskRunnable(task); if (taskRunnable != null) { Class<? extends Runnable> taskClass = taskRunnable.getClass(); className = taskClass.getName(); } Integer count = pluginTaskCounts.get(className); if (count == null) count = 0; count++; pluginTaskCounts.put(className, count); Integer totalCount = pluginCounts.get(pluginName); if (totalCount == null) totalCount = 0; totalCount++; pluginCounts.put(pluginName, totalCount); } sender.sendMessage(ChatColor.LIGHT_PURPLE + "Active tasks: " + tasks.size()); for (Entry<String, HashMap<String, Integer>> pluginEntry : taskCounts.entrySet()) { String pluginName = pluginEntry.getKey(); sender.sendMessage(" " + ChatColor.DARK_PURPLE + pluginName + ": " + ChatColor.LIGHT_PURPLE + pluginCounts.get(pluginName)); for (Entry<String, Integer> taskEntry : pluginEntry.getValue().entrySet()) { sender.sendMessage(" " + ChatColor.DARK_PURPLE + taskEntry.getKey() + ": " + ChatColor.LIGHT_PURPLE + taskEntry.getValue()); } } return true; } if (listCommand.equalsIgnoreCase("wands")) { String owner = ""; if (args.length > 2) { owner = args[2]; } Collection<LostWand> lostWands = api.getLostWands(); int shown = 0; for (LostWand lostWand : lostWands) { Location location = lostWand.getLocation(); if (location == null) continue; if (owner.length() > 0 && !owner.equalsIgnoreCase (lostWand.getOwner())) { continue; } shown++; sender.sendMessage(ChatColor.AQUA + lostWand.getName() + ChatColor.WHITE + " (" + lostWand.getOwner() + ") @ " + ChatColor.BLUE + location.getWorld().getName() + " " + location.getBlockX() + " " + location.getBlockY() + " " + location.getBlockZ()); } sender.sendMessage(shown + " lost wands found" + (owner.length() > 0 ? " for " + owner : "")); return true; } if (listCommand.equalsIgnoreCase("automata")) { Collection<Automaton> automata = api.getAutomata(); for (Automaton automaton : automata) { BlockVector location = automaton.getPosition(); String worldName = automaton.getWorldName(); boolean isOnline = false; World world = Bukkit.getWorld(worldName); if (worldName != null) { isOnline = world.isChunkLoaded(location.getBlockX() >> 4, location.getBlockZ() >> 4); } ChatColor nameColor = isOnline ? ChatColor.AQUA : ChatColor.GRAY; sender.sendMessage(nameColor + automaton.getName() + ChatColor.WHITE + " @ " + ChatColor.BLUE + worldName + " " + location.getBlockX() + " " + location.getBlockY() + " " + location.getBlockZ()); } sender.sendMessage(automata.size() + " automata active"); return true; } if (listCommand.equalsIgnoreCase("maps")) { String keyword = ""; for (int i = 2; i < args.length; i++) { if (i != 2) keyword = keyword + " "; keyword = keyword + args[i]; } onMapList(sender, keyword); return true; } if (listCommand.equalsIgnoreCase("blocks")) { for (BlockData blockData : UndoList.getModified().values()) { BlockVector blockLocation = blockData.getLocation(); Block block = blockData.getBlock(); sender.sendMessage(ChatColor.BLUE + "Block at " + ChatColor.GRAY + blockLocation.getBlockX() + ChatColor.DARK_GRAY + "," + ChatColor.GRAY + blockLocation.getBlockY() + ChatColor.DARK_GRAY + "," + ChatColor.GRAY + blockLocation.getBlockZ() + ChatColor.BLUE + " stored as " + ChatColor.AQUA + blockData.getMaterial() + ChatColor.BLUE + " is currently " + ChatColor.AQUA + block.getType() + ChatColor.BLUE + " from " + ChatColor.GOLD + blockData.getUndoList().getName()); } return true; } if (listCommand.equalsIgnoreCase("mages")) { for (Mage mage : api.getController().getMages()) { Entity mageEntity = mage.getEntity(); String mageType = mageEntity == null ? "Non-Entity" : mageEntity.getType().name(); sender.sendMessage(ChatColor.AQUA + "Mage id " + ChatColor.YELLOW + mage.getId() + ChatColor.GRAY + " (" + mage.getName() + ") " + ChatColor.AQUA + " of type " + ChatColor.DARK_AQUA + mageType + ChatColor.AQUA); } return true; } if (listCommand.equalsIgnoreCase("entities")) { World world = Bukkit.getWorlds().get(0); NumberFormat formatter = new DecimalFormat("#0.0"); List<EntityType> types = Arrays.asList(EntityType.values()); Collections.sort(types, new Comparator<EntityType>() { @Override public int compare(EntityType o1, EntityType o2) { return o1.name().compareTo(o2.name()); } }); Collection<? extends Player> players = Bukkit.getServer().getOnlinePlayers(); for (Player player : players) { showEntityInfo(sender, player, EntityType.PLAYER.name() + ChatColor.GRAY + " (" + player.getName() + " [" + (player.isSneaking() ? "sneaking" : "standing") + "])", formatter); break; } final Class<?> worldClass = NMSUtils.getBukkitClass("net.minecraft.server.World"); for (EntityType entityType : types) { if (entityType.isSpawnable()) { Entity testEntity = null; String errorMessage = null; String entityName = "Entity" + entityType.getEntityClass().getSimpleName(); // A few hacky special cases :( // Still better than actually adding all of these entities to the world! if (entityName.equals("EntityGiant")) { entityName = "EntityGiantZombie"; } else if (entityName.equals("EntityLeashHitch")) { entityName = "EntityLeash"; } else if (entityName.equals("EntityStorageMinecart")) { entityName = "EntityMinecartChest"; } else if (entityName.equals("EntitySpawnerMinecart")) { entityName = "EntityMinecartMobSpawner"; } else if (entityName.equals("EntityCommandMinecart")) { entityName = "EntityMinecartCommandBlock"; } else if (entityName.equals("EntityPoweredMinecart")) { entityName = "EntityMinecartFurnace"; } else if (entityName.equals("EntityExplosiveMinecart")) { entityName = "EntityMinecartTNT"; } else if (entityName.contains("Minecart")) { entityName = entityType.getEntityClass().getSimpleName(); entityName = entityName.replace("Minecart", ""); entityName = "EntityMinecart" + entityName; } try { Class<?> entityClass = NMSUtils.getBukkitClass("net.minecraft.server." + entityName); if (entityClass != null) { Constructor<? extends Object> constructor = entityClass.getConstructor(worldClass); Object nmsWorld = NMSUtils.getHandle(world); Object nmsEntity = constructor.newInstance(nmsWorld); testEntity = NMSUtils.getBukkitEntity(nmsEntity); if (testEntity == null) { errorMessage = "Failed to get Bukkit entity for class " + entityName; } } else { errorMessage = "Could not load class " + entityName; } } catch (Exception ex) { testEntity = null; errorMessage = ex.getClass().getSimpleName() + " [" + entityName + "]"; String message = ex.getMessage(); if (message != null && !message.isEmpty()) { errorMessage += ": " + message; } } if (testEntity == null) { sender.sendMessage(ChatColor.BLACK + entityType.name() + ": " + ChatColor.RED + "Spawning error " + ChatColor.DARK_RED + "(" + errorMessage + ")"); continue; } String label = entityType.name(); Ageable ageable = (testEntity instanceof Ageable) ? (Ageable)testEntity : null; Zombie zombie = (testEntity instanceof Zombie) ? (Zombie)testEntity : null; Skeleton skeleton = (testEntity instanceof Skeleton) ? (Skeleton)testEntity : null; Slime slime = (testEntity instanceof Slime) ? (Slime)testEntity : null; if (ageable != null) { label = label + ChatColor.GRAY + " (Adult)"; ageable.setAdult(); } else if (zombie != null) { label = label + ChatColor.GRAY + " (Adult)"; zombie.setBaby(false); zombie.setVillagerProfession(null); } else if (skeleton != null) { label = label + ChatColor.GRAY + " (NORMAL)"; skeleton.setSkeletonType(Skeleton.SkeletonType.NORMAL); } else if (slime != null) { label = label + ChatColor.GRAY + " (Size 1)"; slime.setSize(1); } showEntityInfo(sender, testEntity, label, formatter); if (ageable != null) { label = entityType.name() + ChatColor.GRAY + " (Baby)"; ageable.setBaby(); showEntityInfo(sender, testEntity, label, formatter); } else if (zombie != null) { label = entityType.name() + ChatColor.GRAY + " (Baby)"; zombie.setBaby(true); showEntityInfo(sender, testEntity, label, formatter); label = entityType.name() + ChatColor.GRAY + " (Villager)"; zombie.setBaby(false); zombie.setVillagerProfession(Villager.Profession.FARMER); showEntityInfo(sender, testEntity, label, formatter); label = entityType.name() + ChatColor.GRAY + " (Baby Villager)"; zombie.setBaby(true); showEntityInfo(sender, testEntity, label, formatter); } else if (skeleton != null) { label = entityType.name() + ChatColor.GRAY + " (WITHER)"; skeleton.setSkeletonType(Skeleton.SkeletonType.WITHER); showEntityInfo(sender, testEntity, label, formatter); } else if (slime != null) { label = entityType.name() + ChatColor.GRAY + " (Size 2)"; slime.setSize(2); showEntityInfo(sender, testEntity, label, formatter); label = entityType.name() + ChatColor.GRAY + " (Size 4)"; slime.setSize(4); showEntityInfo(sender, testEntity, label, formatter); label = entityType.name() + ChatColor.GRAY + " (Size 8)"; slime.setSize(8); showEntityInfo(sender, testEntity, label, formatter); label = entityType.name() + ChatColor.GRAY + " (Size 16)"; slime.setSize(16); showEntityInfo(sender, testEntity, label, formatter); } } } return true; } sender.sendMessage(usage); return true; } private void showEntityInfo(CommandSender sender, Entity entity, String label, NumberFormat formatter) { BoundingBox hitbox = CompatibilityUtils.getHitbox(entity); Vector size = hitbox.size(); String message = ChatColor.BLACK + label + ": " + ChatColor.AQUA + formatter.format(size.getX()) + ChatColor.DARK_GRAY + "x" + ChatColor.AQUA + formatter.format(size.getY()) + ChatColor.DARK_GRAY + "x" + ChatColor.AQUA + formatter.format(size.getZ()); if (entity instanceof LivingEntity) { LivingEntity li = (LivingEntity)entity; message += ChatColor.DARK_GRAY + ", " + ChatColor.GREEN + ((int)li.getMaxHealth()) + "hp"; } sender.sendMessage(message); } protected boolean onMagicGive(CommandSender sender, Player player, String command, String[] args) { String playerCommand = (sender instanceof Player) ? "" : "<player> "; String usageString = "Usage: /magic give " + playerCommand + "<spellname|'material'|'upgrade'|'wand'> [materialname|wandname]"; if (args.length == 0) { sender.sendMessage(usageString); return true; } String key = ""; boolean isMaterial = false; boolean isWand = false; boolean isUpgrade = false; if (args.length > 1 && !args[0].equals("material") && !args[0].equals("wand") && !args[0].equals("upgrade")) { sender.sendMessage(usageString); return true; } if (args[0].equals("wand")) { isWand = true; key = args.length > 1 ? args[1] : ""; } else if (args[0].equals("upgrade")) { isUpgrade = true; key = args.length > 1 ? args[1] : ""; } else if (args[0].equals("material")) { if (args.length < 2) { sender.sendMessage(usageString); return true; } isMaterial = true; key = args[1]; } else { key = args[0]; } boolean giveItem = command.equals("give") || command.equals("sell"); boolean showWorth = command.equals("worth") || command.equals("sell"); boolean giveValue = command.equals("sell"); if (isWand) { giveWand(sender, player, key, false, giveItem, giveValue, showWorth); } else if (isMaterial) { onGiveBrush(sender, player, key, false, giveItem, giveValue, showWorth); } else if (isUpgrade) { onGiveUpgrade(sender, player, key, false, giveItem, giveValue, showWorth); } else { onGive(sender, player, key, giveItem, giveValue, showWorth); } return true; } protected void onGive(CommandSender sender, Player player, String key, boolean giveItem, boolean giveValue, boolean showWorth) { if (!onGiveSpell(sender, player, key, true, giveItem, giveValue, showWorth)) { if (!onGiveBrush(sender, player, key, true, giveItem, giveValue, showWorth)) { if (!giveWand(sender, player, key, true, giveItem, giveValue, showWorth)) { sender.sendMessage("Failed to create a spell, brush or wand item for " + key); } } } } protected boolean onGiveSpell(CommandSender sender, Player player, String spellKey, boolean quiet, boolean giveItem, boolean giveValue, boolean showWorth) { ItemStack itemStack = api.createSpellItem(spellKey); if (itemStack == null) { if (!quiet) sender.sendMessage("Failed to create spell item for " + spellKey); return false; } if (giveItem) { api.giveItemToPlayer(player, itemStack); if (sender != player && !quiet) { sender.sendMessage("Gave spell " + spellKey + " to " + player.getName()); } } if (showWorth) { showWorth(sender, itemStack); } return true; } protected boolean onGiveBrush(CommandSender sender, Player player, String materialKey, boolean quiet, boolean giveItem, boolean giveValue, boolean showWorth) { ItemStack itemStack = api.createBrushItem(materialKey); if (itemStack == null) { if (!quiet) sender.sendMessage("Failed to create material item for " + materialKey); return false; } if (giveItem) { api.giveItemToPlayer(player, itemStack); if (sender != player && !quiet) { sender.sendMessage("Gave brush " + materialKey + " to " + player.getName()); } } if (showWorth) { showWorth(sender, itemStack); } return true; } protected boolean onGiveUpgrade(CommandSender sender, Player player, String wandKey, boolean quiet, boolean giveItem, boolean giveValue, boolean showWorth) { Mage mage = api.getMage(player); Wand currentWand = mage.getActiveWand(); if (currentWand != null) { currentWand.closeInventory(); } Wand wand = api.createWand(wandKey); if (wand != null) { wand.makeUpgrade(); if (giveItem) { api.giveItemToPlayer(player, wand.getItem()); if (sender != player && !quiet) { sender.sendMessage("Gave upgrade " + wand.getName() + " to " + player.getName()); } } if (showWorth) { showWorth(sender, wand.getItem()); } } else { if (!quiet) sender.sendMessage(api.getMessages().getParameterized("wand.unknown_template", "$name", wandKey)); return false; } return true; } protected void checkRunningTask() { if (runningTask != null && runningTask.isFinished()) { runningTask = null; } } @Override public Collection<String> onTabComplete(CommandSender sender, String commandName, String[] args) { List<String> options = new ArrayList<String>(); if (args.length == 1) { addIfPermissible(sender, options, "Magic.commands.magic.", "clean"); addIfPermissible(sender, options, "Magic.commands.magic.", "clearcache"); addIfPermissible(sender, options, "Magic.commands.magic.", "cancel"); addIfPermissible(sender, options, "Magic.commands.magic.", "load"); addIfPermissible(sender, options, "Magic.commands.magic.", "save"); addIfPermissible(sender, options, "Magic.commands.magic.", "commit"); addIfPermissible(sender, options, "Magic.commands.magic.", "give"); addIfPermissible(sender, options, "Magic.commands.magic.", "worth"); addIfPermissible(sender, options, "Magic.commands.magic.", "sell"); addIfPermissible(sender, options, "Magic.commands.magic.", "list"); } else if (args.length == 2) { if (args[0].equalsIgnoreCase("list")) { addIfPermissible(sender, options, "Magic.commands.magic.list", "maps"); addIfPermissible(sender, options, "Magic.commands.magic.list", "wands"); addIfPermissible(sender, options, "Magic.commands.magic.list", "automata"); addIfPermissible(sender, options, "Magic.commands.magic.list", "schematics"); addIfPermissible(sender, options, "Magic.commands.magic.list", "entities"); addIfPermissible(sender, options, "Magic.commands.magic.list", "tasks"); addIfPermissible(sender, options, "Magic.commands.magic.list", "blocks"); addIfPermissible(sender, options, "Magic.commands.magic.list", "mages"); } else if (args[0].equalsIgnoreCase("give") || args[0].equalsIgnoreCase("worth") || args[0].equalsIgnoreCase("sell")) { options.add("wand"); options.add("material"); options.add("upgrade"); Collection<SpellTemplate> spellList = api.getSpellTemplates(sender.hasPermission("Magic.bypass_hidden")); for (SpellTemplate spell : spellList) { options.add(spell.getKey()); } Collection<String> allWands = api.getWandKeys(); for (String wandKey : allWands) { options.add(wandKey); } options.addAll(api.getBrushes()); } } else if (args.length == 3) { if (args[0].equalsIgnoreCase("give") || args[0].equalsIgnoreCase("sell")) { if (args[1].equalsIgnoreCase("upgrade") || args[1].equalsIgnoreCase("wand")) { Collection<String> allWands = api.getWandKeys(); for (String wandKey : allWands) { options.add(wandKey); } } else if (args[1].equalsIgnoreCase("material")) { options.addAll(api.getBrushes()); } } else if (args[0].equalsIgnoreCase("configure") || args[0].equalsIgnoreCase("describe")) { Player player = DeprecatedUtils.getPlayer(args[1]); if (player != null) { Mage mage = api.getMage(player); ConfigurationSection data = mage.getData(); options.addAll(data.getKeys(false)); } } } return options; } }
Read schematics using try-with-resources for automatic closure
Magic/src/main/java/com/elmakers/mine/bukkit/magic/command/MagicCommandExecutor.java
Read schematics using try-with-resources for automatic closure
<ide><path>agic/src/main/java/com/elmakers/mine/bukkit/magic/command/MagicCommandExecutor.java <ide> import org.bukkit.util.Vector; <ide> <ide> import java.io.File; <add>import java.io.InputStream; <ide> import java.lang.reflect.Constructor; <ide> import java.net.URL; <ide> import java.security.CodeSource; <ide> CodeSource src = MagicAPI.class.getProtectionDomain().getCodeSource(); <ide> if (src != null) { <ide> URL jar = src.getLocation(); <del> ZipInputStream zip = new ZipInputStream(jar.openStream()); <del> while(true) { <del> ZipEntry e = zip.getNextEntry(); <del> if (e == null) <del> break; <del> String name = e.getName(); <del> if (name.startsWith("schematics/")) { <del> schematics.add(name.replace("schematics/", "")); <del> } <del> } <del> } <add> try(InputStream is = jar.openStream(); <add> ZipInputStream zip = new ZipInputStream(is)) { <add> while(true) { <add> ZipEntry e = zip.getNextEntry(); <add> if (e == null) <add> break; <add> String name = e.getName(); <add> if (name.startsWith("schematics/")) { <add> schematics.add(name.replace("schematics/", "")); <add> } <add> } <add> } <add> } <ide> <ide> // Check extra path first <ide> File configFolder = plugin.getDataFolder();
Java
apache-2.0
1448c7dc0d95b8359f43ad54ee85f15bf6c91de5
0
ahb0327/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,ryano144/intellij-community,da1z/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,signed/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,izonder/intellij-community,caot/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,caot/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,MichaelNedzelsky/intellij-community,supersven/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,da1z/intellij-community,FHannes/intellij-community,hurricup/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,kool79/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,adedayo/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,allotria/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,signed/intellij-community,amith01994/intellij-community,da1z/intellij-community,fitermay/intellij-community,da1z/intellij-community,jagguli/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,slisson/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,samthor/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,da1z/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,caot/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,amith01994/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,signed/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,hurricup/intellij-community,semonte/intellij-community,caot/intellij-community,caot/intellij-community,izonder/intellij-community,FHannes/intellij-community,semonte/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,signed/intellij-community,vvv1559/intellij-community,allotria/intellij-community,fitermay/intellij-community,jagguli/intellij-community,apixandru/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,caot/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,signed/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,blademainer/intellij-community,robovm/robovm-studio,robovm/robovm-studio,xfournet/intellij-community,apixandru/intellij-community,samthor/intellij-community,fnouama/intellij-community,dslomov/intellij-community,caot/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,apixandru/intellij-community,ryano144/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,xfournet/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,kool79/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,holmes/intellij-community,ryano144/intellij-community,suncycheng/intellij-community,slisson/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,samthor/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,caot/intellij-community,supersven/intellij-community,izonder/intellij-community,diorcety/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,ryano144/intellij-community,jagguli/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,kool79/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,supersven/intellij-community,amith01994/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,signed/intellij-community,ibinti/intellij-community,supersven/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,holmes/intellij-community,samthor/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,diorcety/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,signed/intellij-community,adedayo/intellij-community,fnouama/intellij-community,samthor/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,slisson/intellij-community,clumsy/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,tmpgit/intellij-community,izonder/intellij-community,asedunov/intellij-community,holmes/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,kool79/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,retomerz/intellij-community,vladmm/intellij-community,da1z/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,samthor/intellij-community,akosyakov/intellij-community,caot/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,semonte/intellij-community,signed/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,holmes/intellij-community,vladmm/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,ryano144/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,supersven/intellij-community,adedayo/intellij-community,vladmm/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,semonte/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,xfournet/intellij-community,amith01994/intellij-community,diorcety/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,robovm/robovm-studio,allotria/intellij-community,holmes/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,retomerz/intellij-community,fitermay/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,petteyg/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,retomerz/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,dslomov/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,diorcety/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,supersven/intellij-community,kdwink/intellij-community,fnouama/intellij-community,caot/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,xfournet/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,apixandru/intellij-community,dslomov/intellij-community,slisson/intellij-community,ibinti/intellij-community,kdwink/intellij-community,dslomov/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,slisson/intellij-community,samthor/intellij-community,vladmm/intellij-community,fnouama/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,izonder/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,clumsy/intellij-community,clumsy/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,hurricup/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,ibinti/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,robovm/robovm-studio,jagguli/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,jagguli/intellij-community,holmes/intellij-community,orekyuu/intellij-community,izonder/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,holmes/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,izonder/intellij-community,wreckJ/intellij-community,da1z/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,semonte/intellij-community,semonte/intellij-community,kool79/intellij-community,gnuhub/intellij-community,da1z/intellij-community,asedunov/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,caot/intellij-community,adedayo/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,diorcety/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,vladmm/intellij-community,da1z/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,slisson/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,asedunov/intellij-community,robovm/robovm-studio,izonder/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,xfournet/intellij-community,FHannes/intellij-community,ryano144/intellij-community,apixandru/intellij-community,asedunov/intellij-community,robovm/robovm-studio,kdwink/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,diorcety/intellij-community,kool79/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,vladmm/intellij-community,samthor/intellij-community,ryano144/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community
/* * Copyright 2000-2011 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.xdebugger; import com.intellij.execution.impl.ConsoleViewImpl; import com.intellij.icons.AllIcons; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.Result; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.testFramework.UsefulTestCase; import com.intellij.util.ui.UIUtil; import com.intellij.xdebugger.breakpoints.*; import com.intellij.xdebugger.evaluation.XDebuggerEvaluator; import com.intellij.xdebugger.frame.*; import com.intellij.xdebugger.frame.XNamedValue; import com.intellij.xdebugger.impl.XDebugSessionImpl; import com.intellij.xdebugger.impl.breakpoints.XBreakpointUtil; import com.intellij.xdebugger.impl.breakpoints.XLineBreakpointImpl; import junit.framework.Assert; import org.intellij.lang.annotations.Language; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.List; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; public class XDebuggerTestUtil { private static final int TIMEOUT = 25000; private XDebuggerTestUtil() { } public static <B extends XBreakpoint<?>> void assertBreakpointValidity(Project project, VirtualFile file, int line, boolean validity, String errorMessage, Class<? extends XBreakpointType<B, ?>> breakpointType) { XLineBreakpointType type = (XLineBreakpointType)XDebuggerUtil.getInstance().findBreakpointType(breakpointType); XBreakpointManager manager = XDebuggerManager.getInstance(project).getBreakpointManager(); XLineBreakpointImpl breakpoint = (XLineBreakpointImpl)manager.findBreakpointAtLine(type, file, line); Assert.assertNotNull(breakpoint); Assert.assertEquals(validity ? AllIcons.Debugger.Db_verified_breakpoint : AllIcons.Debugger.Db_invalid_breakpoint, breakpoint.getIcon()); Assert.assertEquals(errorMessage, breakpoint.getErrorMessage()); } public static void toggleBreakpoint(Project project, VirtualFile file, int line) { XDebuggerUtil.getInstance().toggleLineBreakpoint(project, file, line); } public static <P extends XBreakpointProperties> XBreakpoint<P> insertBreakpoint(final Project project, final P properties, final Class<? extends XBreakpointType<XBreakpoint<P>, P>> typeClass) { return new WriteAction<XBreakpoint<P>>() { protected void run(final Result<XBreakpoint<P>> result) { result.setResult(XDebuggerManager.getInstance(project).getBreakpointManager() .addBreakpoint((XBreakpointType<XBreakpoint<P>, P>)XDebuggerUtil.getInstance().findBreakpointType(typeClass), properties)); } }.execute().getResultObject(); } public static void removeBreakpoint(final Project project, final XBreakpoint<?> breakpoint) { new WriteAction() { protected void run(final Result result) { XDebuggerManager.getInstance(project).getBreakpointManager().removeBreakpoint(breakpoint); } }.execute(); } public static void assertPosition(XSourcePosition pos, VirtualFile file, int line) throws IOException { Assert.assertNotNull(pos); Assert.assertEquals(new File(file.getPath()).getCanonicalPath(), new File(pos.getFile().getPath()).getCanonicalPath()); if (line != -1) Assert.assertEquals(line, pos.getLine()); } public static void assertCurrentPosition(XDebugSession session, VirtualFile file, int line) throws IOException { assertPosition(session.getCurrentPosition(), file, line); } public static XExecutionStack getActiveThread(@NotNull XDebugSession session) { return session.getSuspendContext().getActiveExecutionStack(); } public static List<XStackFrame> collectFrames(@NotNull XDebugSession session) throws InterruptedException { return collectFrames(null, session); } public static List<XStackFrame> collectFrames(@Nullable XExecutionStack thread, @NotNull XDebugSession session) throws InterruptedException { return collectStacks(thread == null ? getActiveThread(session) : thread); } public static List<XStackFrame> collectStacks(@NotNull XExecutionStack thread) throws InterruptedException { return collectStacks(thread, TIMEOUT * 2); } public static List<XStackFrame> collectStacks(XExecutionStack thread, long timeout) throws InterruptedException { XTestStackFrameContainer container = new XTestStackFrameContainer(); thread.computeStackFrames(0, container); return container.waitFor(timeout).first; } public static Pair<XValue, String> evaluate(XDebugSession session, String expression) throws InterruptedException { return evaluate(session, expression, TIMEOUT); } public static Pair<XValue, String> evaluate(XDebugSession session, String expression, long timeout) throws InterruptedException { XDebuggerEvaluator evaluator = session.getCurrentStackFrame().getEvaluator(); XTestEvaluationCallback callback = new XTestEvaluationCallback(); evaluator.evaluate(expression, callback, session.getCurrentPosition()); return callback.waitFor(timeout); } public static void waitForSwing() throws InterruptedException, InvocationTargetException { final com.intellij.util.concurrency.Semaphore s = new com.intellij.util.concurrency.Semaphore(); s.down(); ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { s.up(); } }); s.waitForUnsafe(); UIUtil.invokeAndWaitIfNeeded(new Runnable() { public void run() { } }); } @NotNull public static XValue findVar(Collection<XValue> vars, String name) { StringBuilder names = new StringBuilder(); for (XValue each : vars) { if (each instanceof XNamedValue) { String eachName = ((XNamedValue)each).getName(); if (eachName.equals(name)) return each; if (names.length() > 0) names.append(", "); names.append(eachName); } } throw new AssertionError("var '" + name + "' not found among " + names); } public static XTestValueNode computePresentation(@NotNull XValue value) throws InterruptedException { return computePresentation(value, TIMEOUT); } public static XTestValueNode computePresentation(XValue value, long timeout) throws InterruptedException { XTestValueNode node = new XTestValueNode(); if (value instanceof com.intellij.xdebugger.frame.XNamedValue) { node.myName = ((XNamedValue)value).getName(); } value.computePresentation(node, XValuePlace.TREE); node.waitFor(timeout); return node; } public static void assertVariable(XValue var, @Nullable String name, @Nullable String type, @Nullable String value, @Nullable Boolean hasChildren) throws InterruptedException { XTestValueNode node = computePresentation(var); if (name != null) Assert.assertEquals(name, node.myName); if (type != null) Assert.assertEquals(type, node.myType); if (value != null) Assert.assertEquals(value, node.myValue); if (hasChildren != null) Assert.assertEquals((boolean)hasChildren, node.myHasChildren); } public static void assertVariableValue(XValue var, @Nullable String name, @Nullable String value) throws InterruptedException { assertVariable(var, name, null, value, null); } public static void assertVariableValue(Collection<XValue> vars, @Nullable String name, @Nullable String value) throws InterruptedException { assertVariableValue(findVar(vars, name), name, value); } public static void assertVariableValueMatches(@NotNull Collection<XValue> vars, @Nullable String name, @Nullable @Language("RegExp") String valuePattern) throws InterruptedException { assertVariableValueMatches(findVar(vars, name), name, valuePattern); } public static void assertVariableValueMatches(@NotNull XValue var, @Nullable String name, @Nullable @Language("RegExp") String valuePattern) throws InterruptedException { assertVariableValueMatches(var, name, null, valuePattern); } public static void assertVariableValueMatches(@NotNull XValue var, @Nullable String name, @Nullable String type, @Nullable @Language("RegExp") String valuePattern) throws InterruptedException { XTestValueNode node = computePresentation(var); if (name != null) Assert.assertEquals(name, node.myName); if (type != null) Assert.assertEquals(type, node.myType); if (valuePattern != null) { Assert.assertTrue("Expected value" + valuePattern + " Actual value: " + node.myValue, node.myValue.matches(valuePattern)); } } public static void assertVariableTypeMatches(@NotNull Collection<XValue> vars, @Nullable String name, @Nullable @Language("RegExp") String typePattern) throws InterruptedException { assertVariableTypeMatches(findVar(vars, name), name, typePattern); } public static void assertVariableTypeMatches(@NotNull XValue var, @Nullable String name, @Nullable @Language("RegExp") String typePattern) throws InterruptedException { XTestValueNode node = computePresentation(var); if (name != null) { Assert.assertEquals(name, node.myName); } if (typePattern != null) { Assert.assertTrue("Expected type: " + typePattern + " Actual type: " + node.myType, node.myType.matches(typePattern)); } } public static void assertVariableFullValue(@NotNull XValue var, @Nullable String value) throws InterruptedException { XTestValueNode node = computePresentation(var); final String[] result = new String[1]; node.myFullValueEvaluator.startEvaluation(new XFullValueEvaluator.XFullValueEvaluationCallback() { @Override public void evaluated(@NotNull String fullValue) { result[0] = fullValue; } @Override public void evaluated(@NotNull String fullValue, @Nullable Font font) { result[0] = fullValue; } @Override public void errorOccurred(@NotNull String errorMessage) { result[0] = errorMessage; } @Override public boolean isObsolete() { return false; } }); Assert.assertEquals(value, result[0]); } public static void assertVariableFullValue(Collection<XValue> vars, @Nullable String name, @Nullable String value) throws InterruptedException { assertVariableFullValue(findVar(vars, name), value); } public static void assertVariables(List<XValue> vars, String... names) throws InterruptedException { List<String> expectedNames = new ArrayList<String>(Arrays.asList(names)); List<String> actualNames = new ArrayList<String>(); for (XValue each : vars) { actualNames.add(computePresentation(each).myName); } Collections.sort(actualNames); Collections.sort(expectedNames); UsefulTestCase.assertOrderedEquals(actualNames, expectedNames); } public static void assertVariablesContain(List<XValue> vars, String... names) throws InterruptedException { List<String> expectedNames = new ArrayList<String>(Arrays.asList(names)); List<String> actualNames = new ArrayList<String>(); for (XValue each : vars) { actualNames.add(computePresentation(each).myName); } expectedNames.removeAll(actualNames); UsefulTestCase.assertTrue("Missing variables:" + StringUtil.join(expectedNames, ", ") + "\nAll Variables: " + StringUtil.join(actualNames, ", "), expectedNames.isEmpty()); } public static void assertSourcePosition(final XValue value, VirtualFile file, int offset) { final XTestNavigatable n = new XTestNavigatable(); ApplicationManager.getApplication().runReadAction(new Runnable() { @Override public void run() { value.computeSourcePosition(n); } }); Assert.assertNotNull(n.myPosition); Assert.assertEquals(file, n.myPosition.getFile()); Assert.assertEquals(offset, n.myPosition.getOffset()); } public static boolean waitFor(Semaphore semaphore, long timeoutInMillis) throws InterruptedException { return semaphore.tryAcquire(timeoutInMillis, TimeUnit.MILLISECONDS); } public static void assertVariable(Collection<XValue> vars, @Nullable String name, @Nullable String type, @Nullable String value, @Nullable Boolean hasChildren) throws InterruptedException { assertVariable(findVar(vars, name), name, type, value, hasChildren); } @NotNull public static String getConsoleText(final @NotNull ConsoleViewImpl consoleView) { new WriteAction() { protected void run(Result result) throws Throwable { consoleView.flushDeferredText(); } }.execute(); return consoleView.getEditor().getDocument().getText(); } public static <T extends XBreakpointType> XBreakpoint addBreakpoint(@NotNull final Project project, @NotNull final Class<T> exceptionType, @NotNull final XBreakpointProperties properties) { final XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager(); XBreakpointType[] types = XBreakpointUtil.getBreakpointTypes(); final Ref<XBreakpoint> breakpoint = Ref.create(null); for (XBreakpointType type : types) { if (exceptionType.isInstance(type)) { final T breakpointType = exceptionType.cast(type); new WriteAction() { @Override protected void run(Result result) throws Throwable { breakpoint.set(breakpointManager.addBreakpoint(breakpointType, properties)); } }.execute(); break; } } return breakpoint.get(); } public static void removeAllBreakpoints(@NotNull final Project project) { final XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager(); XBreakpoint<?>[] breakpoints = breakpointManager.getAllBreakpoints(); for (XBreakpoint b : breakpoints) { breakpointManager.removeBreakpoint(b); } } public static void setBreakpointCondition(Project project, int line, final String condition) { XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager(); for (XBreakpoint breakpoint : breakpointManager.getAllBreakpoints()) { if (breakpoint instanceof XLineBreakpoint) { final XLineBreakpoint lineBreakpoint = (XLineBreakpoint)breakpoint; if (lineBreakpoint.getLine() == line) { new WriteAction() { @Override protected void run(Result result) throws Throwable { lineBreakpoint.setCondition(condition); } }.execute(); } } } } public static void setBreakpointLogExpression(Project project, int line, final String logExpression) { XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager(); for (XBreakpoint breakpoint : breakpointManager.getAllBreakpoints()) { if (breakpoint instanceof XLineBreakpoint) { final XLineBreakpoint lineBreakpoint = (XLineBreakpoint)breakpoint; if (lineBreakpoint.getLine() == line) { new WriteAction() { @Override protected void run(Result result) throws Throwable { lineBreakpoint.setLogExpression(logExpression); lineBreakpoint.setLogMessage(true); } }.execute(); } } } } public static void disposeDebugSession(final XDebugSession debugSession) { new WriteAction() { protected void run(Result result) throws Throwable { XDebugSessionImpl session = (XDebugSessionImpl)debugSession; Disposer.dispose(session.getSessionTab()); Disposer.dispose(session.getConsoleView()); } }.execute(); } public static void assertVariable(Pair<XValue, String> varAndErrorMessage, @Nullable String name, @Nullable String type, @Nullable String value, @Nullable Boolean hasChildren) throws InterruptedException { Assert.assertNull(varAndErrorMessage.second); assertVariable(varAndErrorMessage.first, name, type, value, hasChildren); } public static String assertVariableExpression(XValue desc, String expectedExpression) { String expression = desc.getEvaluationExpression(); Assert.assertEquals(expectedExpression, expression); return expression; } public static class XTestStackFrameContainer extends XTestContainer<XStackFrame> implements XExecutionStack.XStackFrameContainer { public void addStackFrames(@NotNull List<? extends XStackFrame> stackFrames, boolean last) { addChildren(stackFrames, last); } @Override public void errorOccurred(@NotNull String errorMessage) { setErrorMessage(errorMessage); } } public static class XTestNavigatable implements XNavigatable { private XSourcePosition myPosition; @Override public void setSourcePosition(@Nullable XSourcePosition sourcePosition) { myPosition = sourcePosition; } public XSourcePosition getPosition() { return myPosition; } } }
platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XDebuggerTestUtil.java
/* * Copyright 2000-2011 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.xdebugger; import com.intellij.execution.impl.ConsoleViewImpl; import com.intellij.icons.AllIcons; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.Result; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.testFramework.UsefulTestCase; import com.intellij.util.ui.UIUtil; import com.intellij.xdebugger.breakpoints.*; import com.intellij.xdebugger.evaluation.XDebuggerEvaluator; import com.intellij.xdebugger.frame.*; import com.intellij.xdebugger.frame.XNamedValue; import com.intellij.xdebugger.impl.XDebugSessionImpl; import com.intellij.xdebugger.impl.breakpoints.XBreakpointUtil; import com.intellij.xdebugger.impl.breakpoints.XLineBreakpointImpl; import junit.framework.Assert; import org.intellij.lang.annotations.Language; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.*; import java.util.List; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; public class XDebuggerTestUtil { private static final int TIMEOUT = 25000; private XDebuggerTestUtil() { } public static <B extends XBreakpoint<?>> void assertBreakpointValidity(Project project, VirtualFile file, int line, boolean validity, String errorMessage, Class<? extends XBreakpointType<B, ?>> breakpointType) { XLineBreakpointType type = (XLineBreakpointType)XDebuggerUtil.getInstance().findBreakpointType(breakpointType); XBreakpointManager manager = XDebuggerManager.getInstance(project).getBreakpointManager(); XLineBreakpointImpl breakpoint = (XLineBreakpointImpl)manager.findBreakpointAtLine(type, file, line); Assert.assertNotNull(breakpoint); Assert.assertEquals(validity ? AllIcons.Debugger.Db_verified_breakpoint : AllIcons.Debugger.Db_invalid_breakpoint, breakpoint.getIcon()); Assert.assertEquals(errorMessage, breakpoint.getErrorMessage()); } public static void toggleBreakpoint(Project project, VirtualFile file, int line) { XDebuggerUtil.getInstance().toggleLineBreakpoint(project, file, line); } public static <P extends XBreakpointProperties> XBreakpoint<P> insertBreakpoint(final Project project, final P properties, final Class<? extends XBreakpointType<XBreakpoint<P>, P>> typeClass) { return new WriteAction<XBreakpoint<P>>() { protected void run(final Result<XBreakpoint<P>> result) { result.setResult(XDebuggerManager.getInstance(project).getBreakpointManager() .addBreakpoint((XBreakpointType<XBreakpoint<P>, P>)XDebuggerUtil.getInstance().findBreakpointType(typeClass), properties)); } }.execute().getResultObject(); } public static void removeBreakpoint(final Project project, final XBreakpoint<?> breakpoint) { new WriteAction() { protected void run(final Result result) { XDebuggerManager.getInstance(project).getBreakpointManager().removeBreakpoint(breakpoint); } }.execute(); } public static void assertPosition(XSourcePosition pos, VirtualFile file, int line) throws IOException { Assert.assertNotNull(pos); Assert.assertEquals(new File(file.getPath()).getCanonicalPath(), new File(pos.getFile().getPath()).getCanonicalPath()); if (line != -1) Assert.assertEquals(line, pos.getLine()); } public static void assertCurrentPosition(XDebugSession session, VirtualFile file, int line) throws IOException { assertPosition(session.getCurrentPosition(), file, line); } public static XExecutionStack getActiveThread(@NotNull XDebugSession session) { return session.getSuspendContext().getActiveExecutionStack(); } public static List<XStackFrame> collectFrames(@NotNull XDebugSession session) throws InterruptedException { return collectFrames(null, session); } public static List<XStackFrame> collectFrames(@Nullable XExecutionStack thread, @NotNull XDebugSession session) throws InterruptedException { return collectStacks(thread == null ? getActiveThread(session) : thread); } public static List<XStackFrame> collectStacks(@NotNull XExecutionStack thread) throws InterruptedException { return collectStacks(thread, TIMEOUT * 2); } public static List<XStackFrame> collectStacks(XExecutionStack thread, long timeout) throws InterruptedException { XTestStackFrameContainer container = new XTestStackFrameContainer(); thread.computeStackFrames(0, container); return container.waitFor(timeout).first; } public static Pair<XValue, String> evaluate(XDebugSession session, String expression) throws InterruptedException { return evaluate(session, expression, TIMEOUT); } public static Pair<XValue, String> evaluate(XDebugSession session, String expression, long timeout) throws InterruptedException { XDebuggerEvaluator evaluator = session.getCurrentStackFrame().getEvaluator(); XTestEvaluationCallback callback = new XTestEvaluationCallback(); evaluator.evaluate(expression, callback, session.getCurrentPosition()); return callback.waitFor(timeout); } public static void waitForSwing() throws InterruptedException, InvocationTargetException { final com.intellij.util.concurrency.Semaphore s = new com.intellij.util.concurrency.Semaphore(); s.down(); ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { s.up(); } }); s.waitForUnsafe(); UIUtil.invokeAndWaitIfNeeded(new Runnable() { public void run() { } }); } @NotNull public static XValue findVar(Collection<XValue> vars, String name) { StringBuilder names = new StringBuilder(); for (XValue each : vars) { if (each instanceof XNamedValue) { String eachName = ((XNamedValue)each).getName(); if (eachName.equals(name)) return each; if (names.length() > 0) names.append(", "); names.append(eachName); } } throw new AssertionError("var '" + name + "' not found among " + names); } public static XTestValueNode computePresentation(@NotNull XValue value) throws InterruptedException { return computePresentation(value, TIMEOUT); } public static XTestValueNode computePresentation(XValue value, long timeout) throws InterruptedException { XTestValueNode node = new XTestValueNode(); if (value instanceof com.intellij.xdebugger.frame.XNamedValue) { node.myName = ((XNamedValue)value).getName(); } value.computePresentation(node, XValuePlace.TREE); node.waitFor(timeout); return node; } public static void assertVariable(XValue var, @Nullable String name, @Nullable String type, @Nullable String value, @Nullable Boolean hasChildren) throws InterruptedException { XTestValueNode node = computePresentation(var); if (name != null) Assert.assertEquals(name, node.myName); if (type != null) Assert.assertEquals(type, node.myType); if (value != null) Assert.assertEquals(value, node.myValue); if (hasChildren != null) Assert.assertEquals((boolean)hasChildren, node.myHasChildren); } public static void assertVariableValue(XValue var, @Nullable String name, @Nullable String value) throws InterruptedException { assertVariable(var, name, null, value, null); } public static void assertVariableValue(Collection<XValue> vars, @Nullable String name, @Nullable String value) throws InterruptedException { assertVariableValue(findVar(vars, name), name, value); } public static void assertVariableValueMatches(@NotNull Collection<XValue> vars, @Nullable String name, @Nullable @Language("RegExp") String valuePattern) throws InterruptedException { assertVariableValueMatches(findVar(vars, name), name, valuePattern); } public static void assertVariableValueMatches(@NotNull XValue var, @Nullable String name, @Nullable @Language("RegExp") String valuePattern) throws InterruptedException { assertVariableValueMatches(var, name, null, valuePattern); } public static void assertVariableValueMatches(@NotNull XValue var, @Nullable String name, @Nullable String type, @Nullable @Language("RegExp") String valuePattern) throws InterruptedException { XTestValueNode node = computePresentation(var); if (name != null) Assert.assertEquals(name, node.myName); if (type != null) Assert.assertEquals(type, node.myType); if (valuePattern != null) { Assert.assertTrue("Expected value" + valuePattern + " Actual value: " + node.myValue, node.myValue.matches(valuePattern)); } } public static void assertVariableTypeMatches(@NotNull Collection<XValue> vars, @Nullable String name, @Nullable @Language("RegExp") String typePattern) throws InterruptedException { assertVariableTypeMatches(findVar(vars, name), name, typePattern); } public static void assertVariableTypeMatches(@NotNull XValue var, @Nullable String name, @Nullable @Language("RegExp") String typePattern) throws InterruptedException { XTestValueNode node = computePresentation(var); if (name != null) { Assert.assertEquals(name, node.myName); } if (typePattern != null) { Assert.assertTrue("Expected type: " + typePattern + " Actual type: " + node.myType, node.myType.matches(typePattern)); } } public static void assertVariableFullValue(@NotNull XValue var, @Nullable String value) throws InterruptedException { XTestValueNode node = computePresentation(var); final String[] result = new String[1]; node.myFullValueEvaluator.startEvaluation(new XFullValueEvaluator.XFullValueEvaluationCallback() { @Override public void evaluated(@NotNull String fullValue) { result[0] = fullValue; } @Override public void evaluated(@NotNull String fullValue, @Nullable Font font) { result[0] = fullValue; } @Override public void errorOccurred(@NotNull String errorMessage) { result[0] = errorMessage; } @Override public boolean isObsolete() { return false; } }); Assert.assertEquals(value, result[0]); } public static void assertVariableFullValue(Collection<XValue> vars, @Nullable String name, @Nullable String value) throws InterruptedException { assertVariableFullValue(findVar(vars, name), value); } public static void assertVariables(List<XValue> vars, String... names) throws InterruptedException { List<String> expectedNames = new ArrayList<String>(Arrays.asList(names)); List<String> actualNames = new ArrayList<String>(); for (XValue each : vars) { actualNames.add(computePresentation(each).myName); } Collections.sort(actualNames); Collections.sort(expectedNames); UsefulTestCase.assertOrderedEquals(actualNames, expectedNames); } public static void assertVariablesContain(List<XValue> vars, String... names) throws InterruptedException { List<String> expectedNames = new ArrayList<String>(Arrays.asList(names)); List<String> actualNames = new ArrayList<String>(); for (XValue each : vars) { actualNames.add(computePresentation(each).myName); } expectedNames.removeAll(actualNames); UsefulTestCase.assertTrue("Missing variables:" + StringUtil.join(expectedNames, ", ") + "\nAll Variables: " + StringUtil.join(actualNames, ", "), expectedNames.isEmpty()); } public static void assertSourcePosition(final XValue value, VirtualFile file, int offset) { final XTestNavigatable n = new XTestNavigatable(); ApplicationManager.getApplication().runReadAction(new Runnable() { @Override public void run() { value.computeSourcePosition(n); } }); Assert.assertNotNull(n.myPosition); Assert.assertEquals(file, n.myPosition.getFile()); Assert.assertEquals(offset, n.myPosition.getOffset()); } public static boolean waitFor(Semaphore semaphore, long timeoutInMillis) throws InterruptedException { return semaphore.tryAcquire(timeoutInMillis, TimeUnit.MILLISECONDS); } public static void assertVariable(Collection<XValue> vars, @Nullable String name, @Nullable String type, @Nullable String value, @Nullable Boolean hasChildren) throws InterruptedException { assertVariable(findVar(vars, name), name, type, value, hasChildren); } @NotNull public static String getConsoleText(final @NotNull ConsoleViewImpl consoleView) { new WriteAction() { protected void run(Result result) throws Throwable { consoleView.flushDeferredText(); } }.execute(); return consoleView.getEditor().getDocument().getText(); } public static <T extends XBreakpointType> XBreakpoint addBreakpoint(@NotNull final Project project, @NotNull final Class<T> exceptionType, @NotNull final XBreakpointProperties properties) { final XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager(); XBreakpointType[] types = XBreakpointUtil.getBreakpointTypes(); final Ref<XBreakpoint> breakpoint = Ref.create(null); for (XBreakpointType type : types) { if (exceptionType.isInstance(type)) { final T breakpointType = exceptionType.cast(type); new WriteAction() { @Override protected void run(Result result) throws Throwable { breakpoint.set(breakpointManager.addBreakpoint(breakpointType, properties)); } }.execute(); break; } } return breakpoint.get(); } public static void removeAllBreakpoints(@NotNull final Project project) { final XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager(); XBreakpoint<?>[] breakpoints = breakpointManager.getAllBreakpoints(); for (XBreakpoint b : breakpoints) { breakpointManager.removeBreakpoint(b); } } public static void setBreakpointCondition(Project project, int line, final String condition) { XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager(); for (XBreakpoint breakpoint : breakpointManager.getAllBreakpoints()) { if (breakpoint instanceof XLineBreakpoint) { final XLineBreakpoint lineBreakpoint = (XLineBreakpoint)breakpoint; if (lineBreakpoint.getLine() == line) { new WriteAction() { @Override protected void run(Result result) throws Throwable { lineBreakpoint.setCondition(condition); } }.execute(); } } } } public static void setBreakpointLogExpression(Project project, int line, final String logExpression) { XBreakpointManager breakpointManager = XDebuggerManager.getInstance(project).getBreakpointManager(); for (XBreakpoint breakpoint : breakpointManager.getAllBreakpoints()) { if (breakpoint instanceof XLineBreakpoint) { final XLineBreakpoint lineBreakpoint = (XLineBreakpoint)breakpoint; if (lineBreakpoint.getLine() == line) { new WriteAction() { @Override protected void run(Result result) throws Throwable { lineBreakpoint.setLogExpression(logExpression); lineBreakpoint.setLogMessage(true); } }.execute(); } } } } public static void disposeDebugSession(final XDebugSession debugSession) { new WriteAction() { protected void run(Result result) throws Throwable { XDebugSessionImpl session = (XDebugSessionImpl)debugSession; Disposer.dispose(session.getSessionTab()); Disposer.dispose(session.getConsoleView()); } }.execute(); } public static void assertVariable(Pair<XValue, String> varAndErrorMessage, @Nullable String name, @Nullable String type, @Nullable String value, @Nullable Boolean hasChildren) throws InterruptedException { Assert.assertNull(varAndErrorMessage.second); assertVariable(varAndErrorMessage.first, name, type, value, hasChildren); } public static String assertVariableExpression(XValue desc, String expectedExpression) { String expression = desc.getEvaluationExpression(); Assert.assertEquals(expectedExpression, expression); return expression; } public static class XTestStackFrameContainer extends XTestContainer<XStackFrame> implements XExecutionStack.XStackFrameContainer { public void addStackFrames(@NotNull List<? extends XStackFrame> stackFrames, boolean last) { addChildren(stackFrames, last); } @Override public void errorOccurred(String errorMessage) { setErrorMessage(errorMessage); } public void errorOccured(String errorMessage) { errorOccurred(errorMessage); } } public static class XTestNavigatable implements XNavigatable { private XSourcePosition myPosition; @Override public void setSourcePosition(@Nullable XSourcePosition sourcePosition) { myPosition = sourcePosition; } public XSourcePosition getPosition() { return myPosition; } } }
cleanup
platform/xdebugger-impl/testSrc/com/intellij/xdebugger/XDebuggerTestUtil.java
cleanup
<ide><path>latform/xdebugger-impl/testSrc/com/intellij/xdebugger/XDebuggerTestUtil.java <ide> } <ide> <ide> @Override <del> public void errorOccurred(String errorMessage) { <add> public void errorOccurred(@NotNull String errorMessage) { <ide> setErrorMessage(errorMessage); <del> } <del> <del> public void errorOccured(String errorMessage) { <del> errorOccurred(errorMessage); <ide> } <ide> } <ide>
Java
apache-2.0
ce605efbbf90471d7af47d727a6735cc238b4992
0
aspectran/aspectran,aspectran/aspectran
/* * Copyright (c) 2008-2018 The Aspectran Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aspectran.demo.speak; import com.aspectran.core.component.bean.ablility.DisposableBean; import com.aspectran.core.component.bean.ablility.InitializableBean; import com.aspectran.core.util.ToStringBuilder; import com.aspectran.core.util.logging.Log; import com.aspectran.core.util.logging.LogFactory; import com.sun.speech.freetts.Voice; import com.sun.speech.freetts.VoiceManager; import java.util.Properties; import java.util.Set; /** * <p>Created: 2018. 8. 29.</p> */ public class TextToSpeechBean implements InitializableBean, DisposableBean { private static final Log log = LogFactory.getLog(TextToSpeechBean.class); private String voicePackage; private String voiceName; private Voice voice; public void setProperties(Properties properties) { Set<String> keys = properties.stringPropertyNames(); for (String key : keys) { System.setProperty(key, properties.getProperty(key)); } } public void setVoicePackage(String voicePackage) { this.voicePackage = voicePackage; System.setProperty("freetts.voices", voicePackage); } public void setVoiceName(String voiceName) { this.voiceName = voiceName; } @Override public void initialize() { if (voicePackage == null) { setVoicePackage("com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory"); } if (log.isDebugEnabled()) { VoiceManager voiceManager = VoiceManager.getInstance(); Voice[] voices = voiceManager.getVoices(); String[] arr = new String[voices.length]; for (int i = 0; i < arr.length; i++) { arr[i] = voices[i].getName() + "(" + voices[i].getDomain() + " domain)"; } ToStringBuilder tsb = new ToStringBuilder("All voices available"); tsb.append("voices", arr); log.debug(tsb.toString()); } VoiceManager voiceManager = VoiceManager.getInstance(); if (voiceName != null) { voice = voiceManager.getVoice(voiceName); } else { Voice[] voices = voiceManager.getVoices(); if (voices != null && voices.length > 0) { voice = voices[0]; } } voice = voiceManager.getVoice(voiceName); if (voice != null) { voice.allocate(); } } @Override public void destroy() { if (voice != null) { voice.deallocate(); } } public void speak(String text) { if (voice == null) { throw new IllegalStateException("Cannot find a voice named " + voiceName); } voice.speak(text); } public static void main(String[] args) { TextToSpeechBean textToSpeechBean = new TextToSpeechBean(); textToSpeechBean.setVoiceName("kevin16"); textToSpeechBean.initialize(); textToSpeechBean.speak("test"); textToSpeechBean.destroy(); } }
demo/src/main/java/com/aspectran/demo/speak/TextToSpeechBean.java
/* * Copyright (c) 2008-2018 The Aspectran Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aspectran.demo.speak; import com.aspectran.core.component.bean.ablility.DisposableBean; import com.aspectran.core.component.bean.ablility.InitializableBean; import com.aspectran.core.util.ToStringBuilder; import com.aspectran.core.util.logging.Log; import com.aspectran.core.util.logging.LogFactory; import com.sun.speech.freetts.Voice; import com.sun.speech.freetts.VoiceManager; import java.util.Properties; import java.util.Set; /** * <p>Created: 2018. 8. 29.</p> */ public class TextToSpeechBean implements InitializableBean, DisposableBean { private static final Log log = LogFactory.getLog(TextToSpeechBean.class); private String voiceName; private Voice voice; public void setProperties(Properties properties) { Set<String> keys = properties.stringPropertyNames(); for (String key : keys) { System.setProperty(key, properties.getProperty(key)); } } public void setVoiceName(String voiceName) { this.voiceName = voiceName; } @Override public void initialize() { if (log.isDebugEnabled()) { VoiceManager voiceManager = VoiceManager.getInstance(); Voice[] voices = voiceManager.getVoices(); String[] arr = new String[voices.length]; for (int i = 0; i < arr.length; i++) { arr[i] = voices[i].getName() + "(" + voices[i].getDomain() + " domain)"; } ToStringBuilder tsb = new ToStringBuilder("All voices available"); tsb.append("voices", arr); log.debug(tsb.toString()); } VoiceManager voiceManager = VoiceManager.getInstance(); if (voiceName != null) { voice = voiceManager.getVoice(voiceName); } else { Voice[] voices = voiceManager.getVoices(); if (voices != null && voices.length > 0) { voice = voices[0]; } } voice = voiceManager.getVoice(voiceName); if (voice != null) { voice.allocate(); } } @Override public void destroy() { if (voice != null) { voice.deallocate(); } } public void speak(String text) { if (voice == null) { throw new IllegalStateException("Cannot find a voice named " + voiceName); } voice.speak(text); } public static void listAllVoices() { System.setProperty("freetts.voices", "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory"); System.out.println(); System.out.println("All voices available:"); VoiceManager voiceManager = VoiceManager.getInstance(); Voice[] voices = voiceManager.getVoices(); for (Voice voice1 : voices) { System.out.println(" " + voice1.getName() + " (" + voice1.getDomain() + " domain)"); } } public static void main(String[] args) { Properties props = new Properties(); props.setProperty("freetts.voices", "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory"); TextToSpeechBean textToSpeechBean = new TextToSpeechBean(); textToSpeechBean.setProperties(props); textToSpeechBean.setVoiceName("kevin16"); textToSpeechBean.initialize(); textToSpeechBean.speak("test"); textToSpeechBean.destroy(); } }
Update demo
demo/src/main/java/com/aspectran/demo/speak/TextToSpeechBean.java
Update demo
<ide><path>emo/src/main/java/com/aspectran/demo/speak/TextToSpeechBean.java <ide> <ide> private static final Log log = LogFactory.getLog(TextToSpeechBean.class); <ide> <add> private String voicePackage; <add> <ide> private String voiceName; <ide> <ide> private Voice voice; <ide> } <ide> } <ide> <add> public void setVoicePackage(String voicePackage) { <add> this.voicePackage = voicePackage; <add> System.setProperty("freetts.voices", voicePackage); <add> } <add> <ide> public void setVoiceName(String voiceName) { <ide> this.voiceName = voiceName; <ide> } <ide> <ide> @Override <ide> public void initialize() { <add> if (voicePackage == null) { <add> setVoicePackage("com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory"); <add> } <add> <ide> if (log.isDebugEnabled()) { <ide> VoiceManager voiceManager = VoiceManager.getInstance(); <ide> Voice[] voices = voiceManager.getVoices(); <ide> voice.speak(text); <ide> } <ide> <del> public static void listAllVoices() { <del> System.setProperty("freetts.voices", "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory"); <del> System.out.println(); <del> System.out.println("All voices available:"); <del> VoiceManager voiceManager = VoiceManager.getInstance(); <del> Voice[] voices = voiceManager.getVoices(); <del> for (Voice voice1 : voices) { <del> System.out.println(" " + voice1.getName() + " (" + voice1.getDomain() + " domain)"); <del> } <del> } <del> <ide> public static void main(String[] args) { <del> Properties props = new Properties(); <del> props.setProperty("freetts.voices", "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory"); <del> <ide> TextToSpeechBean textToSpeechBean = new TextToSpeechBean(); <del> textToSpeechBean.setProperties(props); <ide> textToSpeechBean.setVoiceName("kevin16"); <ide> textToSpeechBean.initialize(); <ide> textToSpeechBean.speak("test");
Java
lgpl-2.1
cf7afaf45abb16c85e9ca9a4deec9f5c405866be
0
lcahlander/exist,wolfgangmm/exist,wolfgangmm/exist,hungerburg/exist,dizzzz/exist,ambs/exist,dizzzz/exist,wshager/exist,eXist-db/exist,eXist-db/exist,jensopetersen/exist,opax/exist,adamretter/exist,joewiz/exist,hungerburg/exist,wshager/exist,windauer/exist,ambs/exist,windauer/exist,hungerburg/exist,wshager/exist,lcahlander/exist,olvidalo/exist,jensopetersen/exist,adamretter/exist,RemiKoutcherawy/exist,dizzzz/exist,eXist-db/exist,ambs/exist,ambs/exist,adamretter/exist,RemiKoutcherawy/exist,jensopetersen/exist,opax/exist,opax/exist,jensopetersen/exist,wshager/exist,lcahlander/exist,windauer/exist,lcahlander/exist,RemiKoutcherawy/exist,olvidalo/exist,adamretter/exist,ljo/exist,jensopetersen/exist,eXist-db/exist,olvidalo/exist,ljo/exist,joewiz/exist,olvidalo/exist,wolfgangmm/exist,ambs/exist,ljo/exist,eXist-db/exist,opax/exist,adamretter/exist,windauer/exist,wolfgangmm/exist,ljo/exist,windauer/exist,RemiKoutcherawy/exist,eXist-db/exist,lcahlander/exist,joewiz/exist,ljo/exist,windauer/exist,opax/exist,olvidalo/exist,RemiKoutcherawy/exist,joewiz/exist,hungerburg/exist,ljo/exist,wshager/exist,lcahlander/exist,joewiz/exist,wshager/exist,adamretter/exist,dizzzz/exist,jensopetersen/exist,hungerburg/exist,wolfgangmm/exist,RemiKoutcherawy/exist,dizzzz/exist,ambs/exist,dizzzz/exist,wolfgangmm/exist,joewiz/exist
/* * eXist Open Source Native XML Database * Copyright (C) 2001-06 The eXist Project * http://exist-db.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * $Id$ */ package org.exist.xquery; import java.util.Stack; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.exist.Database; import org.exist.storage.DBBroker; import org.exist.xquery.value.Sequence; /** * XQuery profiling output. Profiling information is written to a * logger. The profiler can be enabled/disabled and configured * via an XQuery pragma or "declare option" expression. Example: * * <pre>declare option exist:profiling "enabled=yes verbosity=10 logger=profiler";</pre> * * @author wolf * */ public class Profiler { /** value for Verbosity property: basic profiling : just elapsed time */ public static final int TIME = 1; /** value for Verbosity property: For optimizations */ public static final int OPTIMIZATIONS = 2; /** For computations that will trigger further optimizations */ public static final int OPTIMIZATION_FLAGS = 3; /** Indicates the dependencies of the expression */ public static final int DEPENDENCIES = 4; /** An abstract level for viewing the expression's context sequence/item */ public static final int START_SEQUENCES = 4; /** Just returns the number of items in the sequence */ public static final int ITEM_COUNT = 5; /** For a truncated string representation of the context sequence (TODO) */ public static final int SEQUENCE_PREVIEW = 6; /** For a full representation of the context sequence (TODO) */ public static final int SEQUENCE_DUMP = 8; public static final String CONFIG_PROPERTY_TRACELOG = "xquery.profiling.tracelog"; /** * The logger where all output goes. */ private Logger log = LogManager.getLogger("xquery.profiling"); private Stack<ProfiledExpr> stack = new Stack<ProfiledExpr>(); private final StringBuilder buf = new StringBuilder(64); private boolean enabled = false; private boolean logEnabled = false; private int verbosity = 0; private PerformanceStats stats; private long queryStart = 0; private Database db; public Profiler(Database db) { this.db = db; this.stats = new PerformanceStats(db); } /** * Configure the profiler from an XQuery pragma. * Parameters are: * * <ul> * <li><strong>enabled</strong>: yes|no.</li> * <li><strong>logger</strong>: name of the logger to use.</li> * <li><strong>verbosity</strong>: integer value &gt; 0. 1 does only output function calls.</li> * </ul> * @param pragma */ public final void configure(Option pragma) { final String options[] = pragma.tokenizeContents(); String params[]; for (int i = 0; i < options.length; i++) { params = Option.parseKeyValuePair(options[i]); if (params != null) { if ("trace".equals(params[0])) { stats.setEnabled(true); } else if ("tracelog".equals(params[0])) { logEnabled = "yes".equals(params[1]); } else if ("logger".equals(params[0])) { log = LogManager.getLogger(params[1]); } else if ("enabled".equals(params[0])) { enabled = "yes".equals(params[1]); } else if ("verbosity".equals(params[0])) { try { verbosity = Integer.parseInt(params[1]); } catch (final NumberFormatException e) { log.warn( "invalid value for verbosity: " + "should be an integer between 0 and " + SEQUENCE_DUMP ); } } } } if (verbosity == 0) {enabled=false;} } /** * Is profiling enabled? * * @return True if profiling is enabled */ public final boolean isEnabled() { return enabled; } public final boolean isLogEnabled() { try { final DBBroker broker = db.getActiveBroker(); final Boolean globalProp = (Boolean) broker.getConfiguration().getProperty(CONFIG_PROPERTY_TRACELOG); return logEnabled || (globalProp != null && globalProp.booleanValue()); } catch (Throwable t) { log.debug("Ignored exception: " + t.getMessage()); return logEnabled; } } public final void setLogEnabled(boolean enabled) { logEnabled = enabled; } public final boolean traceFunctions() { return stats.isEnabled() || isLogEnabled(); } /** * @return the verbosity of the profiler. */ public final int verbosity() { return verbosity; } public final void traceQueryStart() { queryStart = System.currentTimeMillis(); } public final void traceQueryEnd(XQueryContext context) { stats.recordQuery(context.getSource().path(), (System.currentTimeMillis() - queryStart)); } public final void traceFunctionStart(Function function) { if (isLogEnabled()) { log.trace(String.format("ENTER %-25s", function.getSignature().getName())); } } public final void traceFunctionEnd(Function function, long elapsed) { if (stats.isEnabled()) { final String source = String.format("%s [%d:%d]", function.getContext().getSource().getKey(), function .getLine(), function.getColumn()); stats.recordFunctionCall(function.getSignature().getName(), source, elapsed); } if (isLogEnabled()) { log.trace(String.format("EXIT %-25s %10d ms", function.getSignature().getName(), elapsed)); } } public final void traceIndexUsage(XQueryContext context, String indexType, Expression expression, int mode, long elapsed) { stats.recordIndexUse(expression, indexType, context.getSource().path(), mode, elapsed); } private void save() { if (db != null) { db.getPerformanceStats().merge(stats); } } /** * Called by an expression to indicate the start of an operation. * The profiler registers the start time. * * @param expr the expression. */ public final void start(Expression expr) { start(expr, null); } /** * Called by an expression to indicate the start of an operation. * The profiler registers the start time. * * @param expr the expression. * @param message if not null, contains an optional message to print in the log. */ public final void start(Expression expr, String message) { if (!enabled) {return;} if (stack.size() == 0) { log.debug("QUERY START"); } buf.setLength(0); for (int i = 0; i < stack.size(); i++) buf.append('\t'); final ProfiledExpr e = new ProfiledExpr(expr); stack.push(e); buf.append("START\t"); printPosition(e.expr); buf.append(expr.toString()); log.debug(buf.toString()); if (message != null && !"".equals(message)) { buf.setLength(0); for (int i = 0; i < stack.size(); i++) buf.append('\t'); buf.append("MSG\t"); buf.append(message); buf.append("\t"); printPosition(e.expr); buf.append(expr.toString()); log.debug(buf.toString()); } } /** * Called by an expression to indicate the end of an operation. * The profiler computes the elapsed time. * * @param expr the expression. * @param message required: a message to be printed to the log. */ public final void end(Expression expr, String message, Sequence result) { if (!enabled) {return;} try { final ProfiledExpr e = stack.pop(); if (e.expr != expr) { log.warn("Error: the object passed to end() does not correspond to the expression on top of the stack."); stack.clear(); return; } final long elapsed = System.currentTimeMillis() - e.start; if (message != null && !"".equals(message)) { buf.setLength(0); for (int i = 0; i < stack.size(); i++) buf.append('\t'); buf.append("MSG\t"); buf.append(message); buf.append("\t"); printPosition(e.expr); buf.append(expr.toString()); log.debug(buf.toString()); } if (verbosity > START_SEQUENCES) { buf.setLength(0); for (int i = 0; i < stack.size(); i++) buf.append('\t'); buf.append("RESULT\t"); /* if (verbosity >= SEQUENCE_DUMP) buf.append(result.toString()); else if (verbosity >= SEQUENCE_PREVIEW) buf.append(sequencePreview(result)); else*/ if (verbosity >= ITEM_COUNT) { buf.append(result.getItemCount()).append(" item(s)");} buf.append("\t"); printPosition(e.expr); buf.append(expr.toString()); log.debug(buf.toString()); } if (verbosity >= TIME) { buf.setLength(0); for (int i = 0; i < stack.size(); i++) buf.append('\t'); buf.append("TIME\t"); buf.append(elapsed).append(" ms"); buf.append("\t"); printPosition(e.expr); buf.append(expr.toString()); log.debug(buf.toString()); } buf.setLength(0); for (int i = 0; i < stack.size(); i++) buf.append('\t'); buf.append("END\t"); printPosition(e.expr); buf.append(expr.toString()); log.debug(buf.toString()); if (stack.size() == 0) { log.debug("QUERY END"); } } catch (final RuntimeException e) { log.debug("Profiler: could not pop from expression stack - " + expr + " - "+ message + ". Error : "+ e.getMessage()); } } /** * Print out a single profiling message for the given * expression object. * * * @param level * @param title * @param sequence * @param expr */ public final void message(Expression expr, int level, String title, Sequence sequence) { if (!enabled) {return;} if (level > verbosity) {return;} buf.setLength(0); for (int i = 0; i < stack.size() - 1; i++) buf.append('\t'); if (title != null && !"".equals(title)) {buf.append(title);} else {buf.append("MSG");} buf.append("\t"); /* if (verbosity >= SEQUENCE_DUMP) buf.append(sequence.toString()); else if (verbosity >= SEQUENCE_PREVIEW) buf.append(sequencePreview(sequence)); else */ if (verbosity >= ITEM_COUNT) { buf.append(sequence.getItemCount()).append(" item(s)");} buf.append("\t"); buf.append(expr.toString()); log.debug(buf.toString()); } public final void message(Expression expr, int level, String title, String message) { if (!enabled) {return;} if (level > verbosity) {return;} buf.setLength(0); for (int i = 0; i < stack.size() - 1; i++) buf.append('\t'); if (title != null && !"".equals(title)) {buf.append(title);} else {buf.append("MSG");} if (message != null && !"".equals(message)) { buf.append("\t"); buf.append(message); } buf.append("\t"); printPosition(expr); buf.append(expr.toString()); log.debug(buf.toString()); } public void reset() { if (stack.size() > 0) {log.debug("QUERY RESET");} stack.clear(); if (stats.isEnabled() && stats.hasData()) { save(); stats.reset(); } } private void printPosition(Expression expr) { if (expr.getLine() > -1) { buf.append('['); buf.append(expr.getLine()); buf.append(','); buf.append(expr.getColumn()); buf.append("]\t"); } else {buf.append("\t");} } //TODO : find a way to preview "abstract" sequences // never used locally @SuppressWarnings("unused") private String sequencePreview(Sequence sequence) { final StringBuilder truncation = new StringBuilder(); if (sequence.isEmpty()) {truncation.append(sequence.toString());} else if (sequence.hasOne()) { truncation.append("("); if (sequence.itemAt(0).toString().length() > 20) {truncation.append(sequence.itemAt(0).toString().substring(0, 20)).append("... ");} else {truncation.append(sequence.itemAt(0).toString());} truncation.append(")"); } else { truncation.append("("); if (sequence.itemAt(0).toString().length() > 20) {truncation.append(sequence.itemAt(0).toString().substring(0, 20)).append("... ");} else {truncation.append(sequence.itemAt(0).toString());} truncation.append(", ... )"); } return truncation.toString(); } private final static class ProfiledExpr { long start; Expression expr; private ProfiledExpr(Expression expression) { this.expr = expression; this.start = System.currentTimeMillis(); } } public void setEnabled(boolean enabled) { this.enabled = enabled; } public void setVerbosity(int verbosity) { this.verbosity = verbosity; } }
src/org/exist/xquery/Profiler.java
/* * eXist Open Source Native XML Database * Copyright (C) 2001-06 The eXist Project * http://exist-db.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * $Id$ */ package org.exist.xquery; import java.util.Stack; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.exist.Database; import org.exist.storage.DBBroker; import org.exist.xquery.value.Sequence; /** * XQuery profiling output. Profiling information is written to a * logger. The profiler can be enabled/disabled and configured * via an XQuery pragma or "declare option" expression. Example: * * <pre>declare option exist:profiling "enabled=yes verbosity=10 logger=profiler";</pre> * * @author wolf * */ public class Profiler { /** value for Verbosity property: basic profiling : just elapsed time */ public static final int TIME = 1; /** value for Verbosity property: For optimizations */ public static final int OPTIMIZATIONS = 2; /** For computations that will trigger further optimizations */ public static final int OPTIMIZATION_FLAGS = 3; /** Indicates the dependencies of the expression */ public static final int DEPENDENCIES = 4; /** An abstract level for viewing the expression's context sequence/item */ public static final int START_SEQUENCES = 4; /** Just returns the number of items in the sequence */ public static final int ITEM_COUNT = 5; /** For a truncated string representation of the context sequence (TODO) */ public static final int SEQUENCE_PREVIEW = 6; /** For a full representation of the context sequence (TODO) */ public static final int SEQUENCE_DUMP = 8; public static final String CONFIG_PROPERTY_TRACELOG = "xquery.profiling.tracelog"; /** * The logger where all output goes. */ private Logger log = LogManager.getLogger("xquery.profiling"); private Stack<ProfiledExpr> stack = new Stack<ProfiledExpr>(); private final StringBuilder buf = new StringBuilder(64); private boolean enabled = false; private boolean logEnabled = false; private int verbosity = 0; private PerformanceStats stats; private long queryStart = 0; private Database db; public Profiler(Database db) { this.db = db; this.stats = new PerformanceStats(db); } /** * Configure the profiler from an XQuery pragma. * Parameters are: * * <ul> * <li><strong>enabled</strong>: yes|no.</li> * <li><strong>logger</strong>: name of the logger to use.</li> * <li><strong>verbosity</strong>: integer value &gt; 0. 1 does only output function calls.</li> * </ul> * @param pragma */ public final void configure(Option pragma) { final String options[] = pragma.tokenizeContents(); String params[]; for (int i = 0; i < options.length; i++) { params = Option.parseKeyValuePair(options[i]); if (params != null) { if ("trace".equals(params[0])) { stats.setEnabled(true); } else if ("tracelog".equals(params[0])) { logEnabled = "yes".equals(params[1]); } else if ("logger".equals(params[0])) { log = LogManager.getLogger(params[1]); } else if ("enabled".equals(params[0])) { enabled = "yes".equals(params[1]); } else if ("verbosity".equals(params[0])) { try { verbosity = Integer.parseInt(params[1]); } catch (final NumberFormatException e) { log.warn( "invalid value for verbosity: " + "should be an integer between 0 and " + SEQUENCE_DUMP ); } } } } if (verbosity == 0) {enabled=false;} } /** * Is profiling enabled? * * @return True if profiling is enabled */ public final boolean isEnabled() { return enabled; } public final boolean isLogEnabled() { try { final DBBroker broker = db.getActiveBroker(); final Boolean globalProp = (Boolean) broker.getConfiguration().getProperty(CONFIG_PROPERTY_TRACELOG); return logEnabled || (globalProp != null && globalProp.booleanValue()); } catch (Throwable t) { log.debug("Ignored exception: " + t.getMessage()); return logEnabled; } } public final void setLogEnabled(boolean enabled) { logEnabled = enabled; } public final boolean traceFunctions() { return stats.isEnabled() || isLogEnabled(); } /** * @return the verbosity of the profiler. */ public final int verbosity() { return verbosity; } public final void traceQueryStart() { queryStart = System.currentTimeMillis(); } public final void traceQueryEnd(XQueryContext context) { stats.recordQuery(context.getSource().path(), (System.currentTimeMillis() - queryStart)); } public final void traceFunctionStart(Function function) { if (isLogEnabled()) { log.trace(String.format("ENTER %-25s", function.getSignature().getName())); } } public final void traceFunctionEnd(Function function, long elapsed) { if (stats.isEnabled()) { final String source = String.format("%s [%d:%d]", function.getContext().getXacmlSource().getKey(), function .getLine(), function.getColumn()); stats.recordFunctionCall(function.getSignature().getName(), source, elapsed); } if (isLogEnabled()) { log.trace(String.format("EXIT %-25s %10d ms", function.getSignature().getName(), elapsed)); } } public final void traceIndexUsage(XQueryContext context, String indexType, Expression expression, int mode, long elapsed) { stats.recordIndexUse(expression, indexType, context.getSource().path(), mode, elapsed); } private void save() { if (db != null) { db.getPerformanceStats().merge(stats); } } /** * Called by an expression to indicate the start of an operation. * The profiler registers the start time. * * @param expr the expression. */ public final void start(Expression expr) { start(expr, null); } /** * Called by an expression to indicate the start of an operation. * The profiler registers the start time. * * @param expr the expression. * @param message if not null, contains an optional message to print in the log. */ public final void start(Expression expr, String message) { if (!enabled) {return;} if (stack.size() == 0) { log.debug("QUERY START"); } buf.setLength(0); for (int i = 0; i < stack.size(); i++) buf.append('\t'); final ProfiledExpr e = new ProfiledExpr(expr); stack.push(e); buf.append("START\t"); printPosition(e.expr); buf.append(expr.toString()); log.debug(buf.toString()); if (message != null && !"".equals(message)) { buf.setLength(0); for (int i = 0; i < stack.size(); i++) buf.append('\t'); buf.append("MSG\t"); buf.append(message); buf.append("\t"); printPosition(e.expr); buf.append(expr.toString()); log.debug(buf.toString()); } } /** * Called by an expression to indicate the end of an operation. * The profiler computes the elapsed time. * * @param expr the expression. * @param message required: a message to be printed to the log. */ public final void end(Expression expr, String message, Sequence result) { if (!enabled) {return;} try { final ProfiledExpr e = stack.pop(); if (e.expr != expr) { log.warn("Error: the object passed to end() does not correspond to the expression on top of the stack."); stack.clear(); return; } final long elapsed = System.currentTimeMillis() - e.start; if (message != null && !"".equals(message)) { buf.setLength(0); for (int i = 0; i < stack.size(); i++) buf.append('\t'); buf.append("MSG\t"); buf.append(message); buf.append("\t"); printPosition(e.expr); buf.append(expr.toString()); log.debug(buf.toString()); } if (verbosity > START_SEQUENCES) { buf.setLength(0); for (int i = 0; i < stack.size(); i++) buf.append('\t'); buf.append("RESULT\t"); /* if (verbosity >= SEQUENCE_DUMP) buf.append(result.toString()); else if (verbosity >= SEQUENCE_PREVIEW) buf.append(sequencePreview(result)); else*/ if (verbosity >= ITEM_COUNT) { buf.append(result.getItemCount()).append(" item(s)");} buf.append("\t"); printPosition(e.expr); buf.append(expr.toString()); log.debug(buf.toString()); } if (verbosity >= TIME) { buf.setLength(0); for (int i = 0; i < stack.size(); i++) buf.append('\t'); buf.append("TIME\t"); buf.append(elapsed).append(" ms"); buf.append("\t"); printPosition(e.expr); buf.append(expr.toString()); log.debug(buf.toString()); } buf.setLength(0); for (int i = 0; i < stack.size(); i++) buf.append('\t'); buf.append("END\t"); printPosition(e.expr); buf.append(expr.toString()); log.debug(buf.toString()); if (stack.size() == 0) { log.debug("QUERY END"); } } catch (final RuntimeException e) { log.debug("Profiler: could not pop from expression stack - " + expr + " - "+ message + ". Error : "+ e.getMessage()); } } /** * Print out a single profiling message for the given * expression object. * * * @param level * @param title * @param sequence * @param expr */ public final void message(Expression expr, int level, String title, Sequence sequence) { if (!enabled) {return;} if (level > verbosity) {return;} buf.setLength(0); for (int i = 0; i < stack.size() - 1; i++) buf.append('\t'); if (title != null && !"".equals(title)) {buf.append(title);} else {buf.append("MSG");} buf.append("\t"); /* if (verbosity >= SEQUENCE_DUMP) buf.append(sequence.toString()); else if (verbosity >= SEQUENCE_PREVIEW) buf.append(sequencePreview(sequence)); else */ if (verbosity >= ITEM_COUNT) { buf.append(sequence.getItemCount()).append(" item(s)");} buf.append("\t"); buf.append(expr.toString()); log.debug(buf.toString()); } public final void message(Expression expr, int level, String title, String message) { if (!enabled) {return;} if (level > verbosity) {return;} buf.setLength(0); for (int i = 0; i < stack.size() - 1; i++) buf.append('\t'); if (title != null && !"".equals(title)) {buf.append(title);} else {buf.append("MSG");} if (message != null && !"".equals(message)) { buf.append("\t"); buf.append(message); } buf.append("\t"); printPosition(expr); buf.append(expr.toString()); log.debug(buf.toString()); } public void reset() { if (stack.size() > 0) {log.debug("QUERY RESET");} stack.clear(); if (stats.isEnabled() && stats.hasData()) { save(); stats.reset(); } } private void printPosition(Expression expr) { if (expr.getLine() > -1) { buf.append('['); buf.append(expr.getLine()); buf.append(','); buf.append(expr.getColumn()); buf.append("]\t"); } else {buf.append("\t");} } //TODO : find a way to preview "abstract" sequences // never used locally @SuppressWarnings("unused") private String sequencePreview(Sequence sequence) { final StringBuilder truncation = new StringBuilder(); if (sequence.isEmpty()) {truncation.append(sequence.toString());} else if (sequence.hasOne()) { truncation.append("("); if (sequence.itemAt(0).toString().length() > 20) {truncation.append(sequence.itemAt(0).toString().substring(0, 20)).append("... ");} else {truncation.append(sequence.itemAt(0).toString());} truncation.append(")"); } else { truncation.append("("); if (sequence.itemAt(0).toString().length() > 20) {truncation.append(sequence.itemAt(0).toString().substring(0, 20)).append("... ");} else {truncation.append(sequence.itemAt(0).toString());} truncation.append(", ... )"); } return truncation.toString(); } private final static class ProfiledExpr { long start; Expression expr; private ProfiledExpr(Expression expression) { this.expr = expression; this.start = System.currentTimeMillis(); } } public void setEnabled(boolean enabled) { this.enabled = enabled; } public void setVerbosity(int verbosity) { this.verbosity = verbosity; } }
[ignore] Adopt to internal API change (fixes a0a8f130dae16b49ed75be4caaa193c52d113742).
src/org/exist/xquery/Profiler.java
[ignore] Adopt to internal API change (fixes a0a8f130dae16b49ed75be4caaa193c52d113742).
<ide><path>rc/org/exist/xquery/Profiler.java <ide> <ide> public final void traceFunctionEnd(Function function, long elapsed) { <ide> if (stats.isEnabled()) { <del> final String source = String.format("%s [%d:%d]", function.getContext().getXacmlSource().getKey(), function <add> final String source = String.format("%s [%d:%d]", function.getContext().getSource().getKey(), <add> function <ide> .getLine(), function.getColumn()); <ide> stats.recordFunctionCall(function.getSignature().getName(), source, elapsed); <ide> }
Java
apache-2.0
5f64b920e60788903b78f8a74584e3fec7cc12a7
0
CarGuo/GSYVideoPlayer,CarGuo/GSYVideoPlayer
package com.example.gsyvideoplayer.video; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.example.gsyvideoplayer.R; import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer; import com.shuyu.gsyvideoplayer.video.base.GSYBaseVideoPlayer; import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer; /** * Created by shuyu on 2016/12/23. * CustomGSYVideoPlayer是试验中,建议使用的时候使用StandardGSYVideoPlayer */ public class LandLayoutVideo extends StandardGSYVideoPlayer { /** * 1.5.0开始加入,如果需要不同布局区分功能,需要重载 */ public LandLayoutVideo(Context context, Boolean fullFlag) { super(context, fullFlag); } public LandLayoutVideo(Context context) { super(context); } public LandLayoutVideo(Context context, AttributeSet attrs) { super(context, attrs); } //这个必须配置最上面的构造才能生效 @Override public int getLayoutId() { if (mIfCurrentIsFullscreen) { return R.layout.sample_video_land; } return R.layout.sample_video_normal; } @Override protected void updateStartImage() { if (mIfCurrentIsFullscreen) { if(mStartButton instanceof ImageView) { ImageView imageView = (ImageView) mStartButton; if (mCurrentState == CURRENT_STATE_PLAYING) { imageView.setImageResource(R.drawable.video_click_pause_selector); } else if (mCurrentState == CURRENT_STATE_ERROR) { imageView.setImageResource(R.drawable.video_click_play_selector); } else { imageView.setImageResource(R.drawable.video_click_play_selector); } } } else { super.updateStartImage(); } } @Override public int getEnlargeImageRes() { return R.drawable.custom_enlarge; } @Override public int getShrinkImageRes() { return R.drawable.custom_shrink; } }
app/src/main/java/com/example/gsyvideoplayer/video/LandLayoutVideo.java
package com.example.gsyvideoplayer.video; import android.content.Context; import android.util.AttributeSet; import android.widget.ImageView; import com.example.gsyvideoplayer.R; import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer; /** * Created by shuyu on 2016/12/23. * CustomGSYVideoPlayer是试验中,建议使用的时候使用StandardGSYVideoPlayer */ public class LandLayoutVideo extends StandardGSYVideoPlayer { /** * 1.5.0开始加入,如果需要不同布局区分功能,需要重载 */ public LandLayoutVideo(Context context, Boolean fullFlag) { super(context, fullFlag); } public LandLayoutVideo(Context context) { super(context); } public LandLayoutVideo(Context context, AttributeSet attrs) { super(context, attrs); } //这个必须配置最上面的构造才能生效 @Override public int getLayoutId() { if (mIfCurrentIsFullscreen) { return R.layout.sample_video_land; } return R.layout.sample_video_normal; } @Override protected void updateStartImage() { if (mIfCurrentIsFullscreen) { if(mStartButton instanceof ImageView) { ImageView imageView = (ImageView) mStartButton; if (mCurrentState == CURRENT_STATE_PLAYING) { imageView.setImageResource(R.drawable.video_click_pause_selector); } else if (mCurrentState == CURRENT_STATE_ERROR) { imageView.setImageResource(R.drawable.video_click_play_selector); } else { imageView.setImageResource(R.drawable.video_click_play_selector); } } } else { super.updateStartImage(); } } }
fix demo
app/src/main/java/com/example/gsyvideoplayer/video/LandLayoutVideo.java
fix demo
<ide><path>pp/src/main/java/com/example/gsyvideoplayer/video/LandLayoutVideo.java <ide> <ide> import android.content.Context; <ide> import android.util.AttributeSet; <add>import android.view.View; <add>import android.view.ViewGroup; <ide> import android.widget.ImageView; <ide> <ide> import com.example.gsyvideoplayer.R; <ide> import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer; <add>import com.shuyu.gsyvideoplayer.video.base.GSYBaseVideoPlayer; <add>import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer; <ide> <ide> /** <ide> * Created by shuyu on 2016/12/23. <ide> } <ide> } <ide> <add> @Override <add> public int getEnlargeImageRes() { <add> return R.drawable.custom_enlarge; <add> } <add> <add> @Override <add> public int getShrinkImageRes() { <add> return R.drawable.custom_shrink; <add> } <add> <ide> <ide> }
JavaScript
isc
90358b958b6389cbb3439f37bcea4bf018bd2a1c
0
nexdrew/newww,rutaihwa/newww,kemitchell/newww,kemitchell/newww,aredridel/newww,rutaihwa/newww,watilde/newww,aredridel/newww,watilde/newww,watilde/newww,nexdrew/newww,kemitchell/newww,nexdrew/newww,aredridel/newww,rutaihwa/newww
/* Caching is tricky, and so deserves explanation. * * This is currently specific to the CMS, though most of the specifics are * factored separately. * * The general principles are thus: if we have it in cache, serve it up, even * if it's stale. If there's stale data in the cache, update it for future * requests. Don't hammer the backend if it's stale. We only have to fetch it * once. */ var P = require('bluebird'); var url = require('url'); var fetch = require('node-fetch'); fetch.Promise = P; var redis = require('redis'); P.promisifyAll(redis.RedisClient.prototype); var bole = require('bole'); var logger = bole("CMS"); var debug = require('debuglog')('newww:cms'); var pool = P.promisifyAll(require('generic-pool').Pool({ name: 'redis', max: 10, min: 1, idleTimeoutMillis: 30000, create: function(cb) { var client = redis.createClient(process.env.REDIS_URL); client.on('connect', function() { client.removeListener('error', cb); cb(null, client); }); client.on('error', cb); }, destroy: function(client) { client.end(); } })); function Cache(name, fn, ttl) { this.pending = {}; this.fn = fn; this.name = name; this.ttl = ttl; } Cache.prototype.get = function(key) { var cache = this; var cacheKey = cache.name + ":" + key; return withRedis(function(redis) { debug("checking for %j in cache", key); return redis.getAsync(cacheKey).then(JSON.parse) }).then(function(cached) { if (!cached) { debug("%j is not in cache, fetching", key); return cache.fetch(key); } else { debug("%j is in cache.", key); cached.fetchedFromCacheAt = Date.now(); var freshAfter = Date.now() - cache.ttl; if (cached.fetchedAt < freshAfter) { debug("Freshening %j because content fetched at %j is older than %j", key, cached.fetchedAt, freshAfter); cache.fetch(key); } return cached; } }); }; Cache.prototype.fetch = function(key) { var cache = this; var cacheKey = cache.name + ":" + key; if (!cache.pending[key]) { debug("no request for %j is pending, starting one", key); cache.pending[key] = P.resolve(cache.fn(key)).finally(function() { debug("Removing pending request for %j", key); delete cache.pending[key] }).tap(function(value) { return withRedis(function(redis) { debug("Got fresh content for %j, storing to cache", key); return redis.setAsync(cacheKey, JSON.stringify(value)); }).then(function() { debug("Content for %j is now in cache", key); }).catch(function(err) { debug("Error %j", err.message); logger.error(err); return value; }); }); } else { debug("Request for %j is already pending", key); } return cache.pending[key]; }; function withRedis(liftedFn) { var redisP = pool.acquireAsync(); return redisP.then(function(conn) { return redisP.then(liftedFn).finally(function() { pool.release(conn); }); }); } var cache = new Cache('content', fetchPage, 30 * 60 * 1000); function fetchPage(slug) { var pageRoot = url.resolve(process.env.CMS_API, 'pages/'); var pageUrl = url.resolve(pageRoot, slug); debug("Fetching %j for %j", pageUrl, slug); return fetch(pageUrl).then(function(res) { return res.json() }).then(function(page) { debug("Got content for %j: %j", slug, page); if (typeof page != 'object' || !page.id || !page.html || !page.title) { throw new Error("Invalid page returned"); } return page; }).then(function addMarker(json) { json.fetchedAt = Date.now(); return json; }); } module.exports = function getPage(slug) { return cache.get(slug); };
lib/cms.js
/* Caching is tricky, and so deserves explanation. * * This is currently specific to the CMS, though most of the specifics are * factored separately. * * The general principles are thus: if we have it in cache, serve it up, even * if it's stale. If there's stale data in the cache, update it for future * requests. Don't hammer the backend if it's stale. We only have to fetch it * once. */ var P = require('bluebird'); var url = require('url'); var fetch = require('node-fetch'); fetch.Promise = P; var redis = require('redis'); P.promisifyAll(redis.RedisClient.prototype); var bole = require('bole'); var logger = bole("CMS"); var debug = require('debuglog')('newww:cms'); var pool = P.promisifyAll(require('generic-pool').Pool({ name: 'redis', max: 10, min: 1, idleTimeoutMillis: 30000, create: function(cb) { var client = redis.createClient(process.env.REDIS_URL); client.on('connect', function() { client.removeListener('error', cb); cb(null, client); }); client.on('error', cb); }, destroy: function(client) { client.end(); } })); function Cache(name, fn, ttl) { this.pending = {}; this.fn = fn; this.name = name; this.ttl = ttl; } Cache.prototype.get = function(key) { var cache = this; var cacheKey = cache.name + ":" + key; return withRedis(function(redis) { debug("checking for %j in cache", key); return redis.getAsync(cacheKey).then(JSON.parse) }).then(function(cached) { if (!cached) { debug("%j is not in cache, fetching", key); return cache.fetch(key); } else { debug("%j is in cache.", key); cached.fetchedFromCacheAt = Date.now(); var freshAfter = Date.now() - cache.ttl; if (cached.fetchedAt < freshAfter) { debug("Freshening %j because content fetched at %j is older than %j", key, cached.fetchedAt, freshAfter); cache.fetch(key); } return cached; } }); }; Cache.prototype.fetch = function(key) { var cache = this; var cacheKey = cache.name + ":" + key; if (!cache.pending[key]) { debug("no request for %j is pending, starting one", key); cache.pending[key] = P.resolve(cache.fn(key)).finally(function() { debug("Removing pending request for %j", key); delete cache.pending[key] }).tap(function(value) { return withRedis(function(redis) { debug("Got fresh content for %j, storing to cache", key); return redis.setAsync(cacheKey, JSON.stringify(value)); }).then(function() { debug("Content for %j is now in cache", key); }).catch(function(err) { debug("Error %j", err.message); logger.error(err); return value; }); }); } else { debug("Request for %j is already pending", key); } return cache.pending[key]; }; function withRedis(liftedFn) { var redisP = pool.acquireAsync(); return redisP.then(function(conn) { return redisP.then(liftedFn).finally(function() { pool.release(conn); }); }); } var cache = new Cache('content', fetchPage, 30 * 60 * 1000); function fetchPage(slug) { var pageRoot = url.resolve(process.env.CMS_API, 'pages/'); return fetch(url.resolve(pageRoot, slug)).then(function(res) { return res.json() }).then(function addMarker(json) { json.fetchedAt = Date.now(); return json; }); } module.exports = function getPage(slug) { return cache.get(slug); };
Validate pages returned from API
lib/cms.js
Validate pages returned from API
<ide><path>ib/cms.js <ide> <ide> function fetchPage(slug) { <ide> var pageRoot = url.resolve(process.env.CMS_API, 'pages/'); <del> return fetch(url.resolve(pageRoot, slug)).then(function(res) { <add> var pageUrl = url.resolve(pageRoot, slug); <add> debug("Fetching %j for %j", pageUrl, slug); <add> return fetch(pageUrl).then(function(res) { <ide> return res.json() <add> }).then(function(page) { <add> debug("Got content for %j: %j", slug, page); <add> if (typeof page != 'object' || !page.id || !page.html || !page.title) { <add> throw new Error("Invalid page returned"); <add> } <add> return page; <ide> }).then(function addMarker(json) { <ide> json.fetchedAt = Date.now(); <ide> return json;
Java
apache-2.0
3a5b4a0b264395cdd30406244496810b058baa0c
0
irccloud/android,irccloud/android,irccloud/android,irccloud/android,irccloud/android
package com.irccloud.android; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.HashSet; import java.util.Iterator; import java.util.TreeMap; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Debug; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import com.actionbarsherlock.app.SherlockListFragment; import com.google.gson.JsonArray; import com.google.gson.JsonObject; public class MessageViewFragment extends SherlockListFragment { private NetworkConnection conn; private TextView statusView; private View headerViewContainer; private View headerView; private TextView unreadView; private TextView unreadTopLabel; private View unreadTopView; private int cid; private int bid; private long last_seen_eid; private long min_eid; private long earliest_eid; private long backlog_eid = 0; private String name; private String type; private boolean firstScroll = true; private boolean requestingBacklog = false; private boolean shouldShowUnread = false; private float avgInsertTime = 0; private int newMsgs = 0; private long newMsgTime = 0; private MessageViewListener mListener; public static final int ROW_MESSAGE = 0; public static final int ROW_TIMESTAMP = 1; public static final int ROW_BACKLOGMARKER = 2; public static final int ROW_SOCKETCLOSED = 3; public static final int ROW_LASTSEENEID = 4; private static final String TYPE_TIMESTAMP = "__timestamp__"; private static final String TYPE_BACKLOGMARKER = "__backlog__"; private static final String TYPE_LASTSEENEID = "__lastseeneid__"; private MessageAdapter adapter; private long currentCollapsedEid = -1; private CollapsedEventsList collapsedEvents = new CollapsedEventsList(); private int lastCollapsedDay = -1; private HashSet<Long> expandedSectionEids = new HashSet<Long>(); private RefreshTask refreshTask = null; private HeartbeatTask heartbeatTask = null; private Ignore ignore = new Ignore(); private class MessageAdapter extends BaseAdapter { ArrayList<EventsDataSource.Event> data; private SherlockListFragment ctx; private long max_eid = 0; private long min_eid = 0; private int lastDay = -1; private int lastSeenEidMarkerPosition = -1; private int currentGroupPosition = -1; private class ViewHolder { int type; TextView timestamp; TextView message; } public MessageAdapter(SherlockListFragment context) { ctx = context; data = new ArrayList<EventsDataSource.Event>(); } public void clear() { max_eid = 0; min_eid = 0; lastDay = -1; lastSeenEidMarkerPosition = -1; currentGroupPosition = -1; data.clear(); } public void removeItem(long eid) { for(int i = 0; i < data.size(); i++) { if(data.get(i).eid == eid) { data.remove(i); i--; } } } public int getBacklogMarkerPosition() { for(int i = 0; i < data.size(); i++) { if(data.get(i).row_type == ROW_BACKLOGMARKER) { return i; } } return -1; } public int insertLastSeenEIDMarker() { EventsDataSource.Event e = EventsDataSource.getInstance().new Event(); e.type = TYPE_LASTSEENEID; e.row_type = ROW_LASTSEENEID; e.bg_color = R.drawable.socketclosed_bg; for(int i = 0; i < data.size(); i++) { if(data.get(i).row_type == ROW_LASTSEENEID) { data.remove(i); } } for(int i = data.size() - 1; i >= 0; i--) { if(data.get(i).eid <= last_seen_eid) { lastSeenEidMarkerPosition = i; break; } } if(lastSeenEidMarkerPosition != data.size() - 1) { if(lastSeenEidMarkerPosition > 0 && data.get(lastSeenEidMarkerPosition - 1).row_type == ROW_TIMESTAMP) lastSeenEidMarkerPosition--; if(lastSeenEidMarkerPosition > 0) data.add(lastSeenEidMarkerPosition + 1, e); } else { lastSeenEidMarkerPosition = -1; } return lastSeenEidMarkerPosition; } public int getLastSeenEIDPosition() { return lastSeenEidMarkerPosition; } public synchronized void addItem(long eid, EventsDataSource.Event e) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(eid / 1000); int insert_pos = -1; SimpleDateFormat formatter; formatter = new SimpleDateFormat("h:mm a"); if(conn.getUserInfo() != null && conn.getUserInfo().prefs != null) { try { JSONObject prefs = conn.getUserInfo().prefs; if(prefs.has("time-24hr") && prefs.getBoolean("time-24hr")) { if(prefs.has("time-seconds") && prefs.getBoolean("time-seconds")) formatter = new SimpleDateFormat("H:mm:ss"); else formatter = new SimpleDateFormat("H:mm"); } else if(prefs.has("time-seconds") && prefs.getBoolean("time-seconds")) { formatter = new SimpleDateFormat("h:mm:ss a"); } } catch (JSONException e1) { e1.printStackTrace(); } } e.timestamp = formatter.format(calendar.getTime()); e.group_eid = currentCollapsedEid; if(currentGroupPosition > 0 && eid == currentCollapsedEid && e.eid != eid) { //Shortcut for replacing the current group calendar.setTimeInMillis(e.eid / 1000); lastDay = calendar.get(Calendar.DAY_OF_YEAR); data.remove(currentGroupPosition); data.add(currentGroupPosition, e); insert_pos = currentGroupPosition; } else if(eid > max_eid || data.size() == 0) { //Message at the bottom if(data.size() > 0) { calendar.setTimeInMillis(data.get(data.size()-1).eid / 1000); lastDay = calendar.get(Calendar.DAY_OF_YEAR); calendar.setTimeInMillis(eid/1000); } else { lastDay = 0; } max_eid = eid; data.add(e); insert_pos = data.size() - 1; } else if(min_eid > eid) { //Message goes on top calendar.setTimeInMillis(data.get(1).eid / 1000); lastDay = calendar.get(Calendar.DAY_OF_YEAR); calendar.setTimeInMillis(eid/1000); if(calendar.get(Calendar.DAY_OF_YEAR) != lastDay) { //Insert above the dateline data.add(0, e); insert_pos = 0; } else { //Insert below the dateline data.add(1, e); insert_pos = 1; } } else { int i = 0; for(EventsDataSource.Event e1 : data) { if(e1.row_type != ROW_TIMESTAMP && e1.eid > eid && e.eid == eid) { //Insert the message if(i > 0 && data.get(i-1).row_type != ROW_TIMESTAMP) { calendar.setTimeInMillis(data.get(i-1).eid / 1000); lastDay = calendar.get(Calendar.DAY_OF_YEAR); data.add(i, e); insert_pos = i; break; } else { //There was a date line above our insertion point calendar.setTimeInMillis(e1.eid / 1000); lastDay = calendar.get(Calendar.DAY_OF_YEAR); calendar.setTimeInMillis(eid/1000); if(calendar.get(Calendar.DAY_OF_YEAR) != lastDay) { //Insert above the dateline if(i > 1) { calendar.setTimeInMillis(data.get(i-2).eid / 1000); lastDay = calendar.get(Calendar.DAY_OF_YEAR); } else { //We're above the first dateline, so we'll need to put a new one on top! lastDay = 0; } calendar.setTimeInMillis(eid/1000); data.add(i-1, e); insert_pos = i-1; } else { //Insert below the dateline data.add(i, e); insert_pos = i; } break; } } else if(e1.row_type != ROW_TIMESTAMP && (e1.eid == eid || e1.group_eid == eid)) { //Replace the message lastDay = calendar.get(Calendar.DAY_OF_YEAR); data.remove(i); data.add(i, e); insert_pos = i; break; } i++; } } if(insert_pos == -1) { Log.e("IRCCloud", "Couldn't insert EID: " + eid + " MSG: " + e.html); return; } if(eid == currentCollapsedEid && e.eid == eid) { currentGroupPosition = insert_pos; } else if(currentCollapsedEid == -1) { currentGroupPosition = -1; } if(calendar.get(Calendar.DAY_OF_YEAR) != lastDay) { formatter.applyPattern("EEEE, MMMM dd, yyyy"); EventsDataSource.Event d = EventsDataSource.getInstance().new Event(); d.type = TYPE_TIMESTAMP; d.row_type = ROW_TIMESTAMP; d.eid = eid; d.timestamp = formatter.format(calendar.getTime()); d.bg_color = R.color.dateline_bg; data.add(insert_pos, d); lastDay = calendar.get(Calendar.DAY_OF_YEAR); if(currentGroupPosition > -1) currentGroupPosition++; } } @Override public int getCount() { return data.size(); } @Override public Object getItem(int position) { return data.get(position); } @Override public long getItemId(int position) { return data.get(position).eid; } public long getGroupForPosition(int position) { return data.get(position).group_eid; } @Override public View getView(int position, View convertView, ViewGroup parent) { EventsDataSource.Event e = data.get(position); View row = convertView; ViewHolder holder; if(row != null && ((ViewHolder)row.getTag()).type != e.row_type) row = null; if (row == null) { LayoutInflater inflater = ctx.getLayoutInflater(null); if(e.row_type == ROW_BACKLOGMARKER) row = inflater.inflate(R.layout.row_backlogmarker, null); else if(e.row_type == ROW_TIMESTAMP) row = inflater.inflate(R.layout.row_timestamp, null); else if(e.row_type == ROW_SOCKETCLOSED) row = inflater.inflate(R.layout.row_socketclosed, null); else if(e.row_type == ROW_LASTSEENEID) row = inflater.inflate(R.layout.row_lastseeneid, null); else row = inflater.inflate(R.layout.row_message, null); holder = new ViewHolder(); holder.timestamp = (TextView) row.findViewById(R.id.timestamp); holder.message = (TextView) row.findViewById(R.id.message); holder.type = e.row_type; row.setTag(holder); } else { holder = (ViewHolder) row.getTag(); } row.setBackgroundResource(e.bg_color); if(holder.timestamp != null) holder.timestamp.setText(e.timestamp); if(e.group_msg != null && e.html == null) e.html = ColorFormatter.irc_to_html(e.group_msg); if(holder.message != null && e.html != null) { holder.message.setTextColor(getResources().getColorStateList(e.color)); holder.message.setText(ColorFormatter.html_to_spanned(e.html)); } return row; } } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View v = inflater.inflate(R.layout.messageview, container, false); statusView = (TextView)v.findViewById(R.id.statusView); unreadView = (TextView)v.findViewById(R.id.unread); unreadView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { getListView().setSelection(adapter.getCount() - 1); } }); unreadTopView = v.findViewById(R.id.unreadTop); unreadTopView.setVisibility(View.INVISIBLE); unreadTopView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { unreadTopView.setVisibility(View.GONE); getListView().setSelection(adapter.getLastSeenEIDPosition()); Long e = adapter.data.get(adapter.data.size() - 1).eid; new HeartbeatTask().execute(e); } }); unreadTopLabel = (TextView)v.findViewById(R.id.unreadTopText); Button b = (Button)v.findViewById(R.id.markAsRead); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { unreadTopView.setVisibility(View.GONE); Long e = adapter.data.get(adapter.data.size() - 1).eid; new HeartbeatTask().execute(e); } }); ((ListView)v.findViewById(android.R.id.list)).setOnScrollListener(new OnScrollListener() { @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if(headerView != null) { if(firstVisibleItem == 0 && !requestingBacklog && headerView.getVisibility() == View.VISIBLE && bid != -1) { requestingBacklog = true; conn.request_backlog(cid, bid, earliest_eid); } } int markerPos = -1; if(adapter != null) markerPos = adapter.getLastSeenEIDPosition(); if(unreadView != null && adapter != null) { if(firstVisibleItem + visibleItemCount == totalItemCount) { unreadView.setVisibility(View.GONE); if(newMsgs > 0 || unreadTopView.getVisibility() == View.GONE) { Long e = adapter.data.get(adapter.data.size() - 1).eid; if(heartbeatTask != null) heartbeatTask.cancel(true); heartbeatTask = new HeartbeatTask(); heartbeatTask.execute(e); } newMsgs = 0; newMsgTime = 0; } } if(firstVisibleItem + visibleItemCount < totalItemCount) shouldShowUnread = true; if(adapter != null && unreadTopView != null && unreadTopView.getVisibility() == View.VISIBLE) { if(markerPos > 0 && getListView().getFirstVisiblePosition() <= markerPos) { unreadTopView.setVisibility(View.GONE); Long e = adapter.data.get(adapter.data.size() - 1).eid; if(heartbeatTask != null) heartbeatTask.cancel(true); heartbeatTask = new HeartbeatTask(); heartbeatTask.execute(e); } } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } }); return v; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(savedInstanceState != null && savedInstanceState.containsKey("cid")) { cid = savedInstanceState.getInt("cid"); bid = savedInstanceState.getInt("bid"); name = savedInstanceState.getString("name"); last_seen_eid = savedInstanceState.getLong("last_seen_eid"); min_eid = savedInstanceState.getLong("min_eid"); type = savedInstanceState.getString("type"); firstScroll = savedInstanceState.getBoolean("firstScroll"); backlog_eid = savedInstanceState.getLong("backlog_eid"); //TODO: serialize the adapter data } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (MessageViewListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement MessageViewListener"); } } @Override public void onSaveInstanceState(Bundle state) { super.onSaveInstanceState(state); state.putInt("cid", cid); state.putInt("bid", bid); state.putLong("last_seen_eid", last_seen_eid); state.putLong("min_eid", min_eid); state.putString("name", name); state.putString("type", type); state.putBoolean("firstScroll", firstScroll); state.putLong("backlog_eid", backlog_eid); //TODO: serialize the adapter data } @Override public void setArguments(Bundle args) { cid = args.getInt("cid", 0); bid = args.getInt("bid", 0); last_seen_eid = args.getLong("last_seen_eid", 0); min_eid = args.getLong("min_eid", 0); name = args.getString("name"); type = args.getString("type"); firstScroll = true; requestingBacklog = false; shouldShowUnread = false; avgInsertTime = 0; newMsgs = 0; newMsgTime = 0; earliest_eid = 0; backlog_eid = 0; collapsedEvents.setChannel(cid, name); if(unreadTopView != null) unreadTopView.setVisibility(View.INVISIBLE); if(headerView != null) { mHandler.postDelayed(new Runnable() { @Override public void run() { if(EventsDataSource.getInstance().getEventsForBuffer(bid) != null) { requestingBacklog = true; if(refreshTask != null) refreshTask.cancel(true); refreshTask = new RefreshTask(); refreshTask.execute((Void)null); } else { if(bid == -1) { headerView.setVisibility(View.GONE); } else { headerView.setVisibility(View.VISIBLE); ignore.setIgnores(ServersDataSource.getInstance().getServer(cid).ignores); } adapter.clear(); adapter.notifyDataSetInvalidated(); mListener.onMessageViewReady(); } } }, 100); } } private synchronized void insertEvent(EventsDataSource.Event event, boolean backlog, boolean nextIsGrouped) { try { long start = System.currentTimeMillis(); if(min_eid == 0) min_eid = event.eid; if(event.eid == min_eid) { headerView.setVisibility(View.GONE); } if(event.eid < earliest_eid) earliest_eid = event.eid; String type = event.type; long eid = event.eid; if(type.startsWith("you_")) type = type.substring(4); if(type.equalsIgnoreCase("joined_channel") || type.equalsIgnoreCase("parted_channel") || type.equalsIgnoreCase("nickchange") || type.equalsIgnoreCase("quit") || type.equalsIgnoreCase("user_channel_mode")) { if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) { JSONObject hiddenMap = conn.getUserInfo().prefs.getJSONObject("channel-hideJoinPart"); if(hiddenMap.has(String.valueOf(bid)) && hiddenMap.getBoolean(String.valueOf(bid))) { adapter.removeItem(event.eid); if(!backlog) adapter.notifyDataSetChanged(); return; } } Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(eid / 1000); if(currentCollapsedEid == -1 || calendar.get(Calendar.DAY_OF_YEAR) != lastCollapsedDay) { collapsedEvents.clear(); currentCollapsedEid = eid; lastCollapsedDay = calendar.get(Calendar.DAY_OF_YEAR); } if(expandedSectionEids.contains(currentCollapsedEid)) collapsedEvents.clear(); if(type.equalsIgnoreCase("joined_channel")) { collapsedEvents.addEvent(CollapsedEventsList.TYPE_JOIN, event.nick, null, event.hostmask, null); } else if(type.equalsIgnoreCase("parted_channel")) { collapsedEvents.addEvent(CollapsedEventsList.TYPE_PART, event.nick, null, event.hostmask, null); } else if(type.equalsIgnoreCase("quit")) { collapsedEvents.addEvent(CollapsedEventsList.TYPE_QUIT, event.nick, null, event.hostmask, event.msg); } else if(type.equalsIgnoreCase("nickchange")) { collapsedEvents.addEvent(CollapsedEventsList.TYPE_NICKCHANGE, event.nick, event.old_nick, null, null); } else if(type.equalsIgnoreCase("user_channel_mode")) { boolean unknown = false; JsonObject ops = event.ops; if(ops != null) { JsonArray add = ops.getAsJsonArray("add"); for(int i = 0; i < add.size(); i++) { JsonObject op = add.get(i).getAsJsonObject(); if(op.get("mode").getAsString().equalsIgnoreCase("q")) collapsedEvents.addEvent(CollapsedEventsList.TYPE_MODE, op.get("param").getAsString(), event.from, event.hostmask, null, CollapsedEventsList.MODE_OWNER); else if(op.get("mode").getAsString().equalsIgnoreCase("a")) collapsedEvents.addEvent(CollapsedEventsList.TYPE_MODE, op.get("param").getAsString(), event.from, event.hostmask, null, CollapsedEventsList.MODE_ADMIN); else if(op.get("mode").getAsString().equalsIgnoreCase("o")) collapsedEvents.addEvent(CollapsedEventsList.TYPE_MODE, op.get("param").getAsString(), event.from, event.hostmask, null, CollapsedEventsList.MODE_OP); else if(op.get("mode").getAsString().equalsIgnoreCase("h")) collapsedEvents.addEvent(CollapsedEventsList.TYPE_MODE, op.get("param").getAsString(), event.from, event.hostmask, null, CollapsedEventsList.MODE_HALFOP); else if(op.get("mode").getAsString().equalsIgnoreCase("v")) collapsedEvents.addEvent(CollapsedEventsList.TYPE_MODE, op.get("param").getAsString(), event.from, event.hostmask, null, CollapsedEventsList.MODE_VOICE); else unknown = true; } JsonArray remove = ops.getAsJsonArray("remove"); for(int i = 0; i < remove.size(); i++) { JsonObject op = remove.get(i).getAsJsonObject(); if(op.get("mode").getAsString().equalsIgnoreCase("q")) collapsedEvents.addEvent(CollapsedEventsList.TYPE_MODE, op.get("param").getAsString(), event.from, event.hostmask, null, CollapsedEventsList.MODE_DEOWNER); else if(op.get("mode").getAsString().equalsIgnoreCase("a")) collapsedEvents.addEvent(CollapsedEventsList.TYPE_MODE, op.get("param").getAsString(), event.from, event.hostmask, null, CollapsedEventsList.MODE_DEADMIN); else if(op.get("mode").getAsString().equalsIgnoreCase("o")) collapsedEvents.addEvent(CollapsedEventsList.TYPE_MODE, op.get("param").getAsString(), event.from, event.hostmask, null, CollapsedEventsList.MODE_DEOP); else if(op.get("mode").getAsString().equalsIgnoreCase("h")) collapsedEvents.addEvent(CollapsedEventsList.TYPE_MODE, op.get("param").getAsString(), event.from, event.hostmask, null, CollapsedEventsList.MODE_DEHALFOP); else if(op.get("mode").getAsString().equalsIgnoreCase("v")) collapsedEvents.addEvent(CollapsedEventsList.TYPE_MODE, op.get("param").getAsString(), event.from, event.hostmask, null, CollapsedEventsList.MODE_DEVOICE); else unknown = true; } } if(unknown) { collapsedEvents.clear(); } } String msg = (nextIsGrouped && currentCollapsedEid != event.eid)?"":collapsedEvents.getCollapsedMessage(); if(msg == null && type.equalsIgnoreCase("nickchange")) { msg = event.old_nick + " → <b>" + event.nick + "</b>"; } if(msg == null && type.equalsIgnoreCase("user_channel_mode")) { msg = "<b>" + collapsedEvents.formatNick(event.from) + "</b> set mode: <b>" + event.diff + " " + event.nick + "</b>"; currentCollapsedEid = eid; } if(!expandedSectionEids.contains(currentCollapsedEid)) { if(eid != currentCollapsedEid) msg = "[+] " + msg; eid = currentCollapsedEid; } event.color = R.color.timestamp; event.group_msg = msg; event.html = null; } else { currentCollapsedEid = -1; collapsedEvents.clear(); if(event.from != null) event.html = "<b>" + collapsedEvents.formatNick(event.from) + "</b> " + event.msg; else event.html = event.msg; } if(!type.equalsIgnoreCase("user_channel_mode") && event.from != null && event.hostmask != null) { String usermask = event.from + "!" + event.hostmask; if(ignore.match(usermask)) return; } adapter.addItem(eid, event); if(!backlog) adapter.notifyDataSetChanged(); long time = (System.currentTimeMillis() - start); if(avgInsertTime == 0) avgInsertTime = time; avgInsertTime += time; avgInsertTime /= 2.0; //Log.i("IRCCloud", "Average insert time: " + avgInsertTime); if(getListView().getLastVisiblePosition() >= (adapter.getCount() - 1)) { shouldShowUnread = false; } if(!backlog && shouldShowUnread) { if(newMsgTime == 0) newMsgTime = System.currentTimeMillis(); newMsgs++; update_unread(); } if(!backlog && !shouldShowUnread) getListView().setSelection(adapter.getCount() - 1); if(!backlog) { int markerPos = adapter.getLastSeenEIDPosition(); if(markerPos > 0 && getListView().getFirstVisiblePosition() > markerPos) { unreadTopLabel.setText((getListView().getFirstVisiblePosition() - markerPos) + " unread messages"); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void onListItemClick(ListView l, View v, int position, long id) { long group = adapter.getGroupForPosition(position-1); if(expandedSectionEids.contains(group)) expandedSectionEids.remove(group); else expandedSectionEids.add(group); if(refreshTask != null) refreshTask.cancel(true); refreshTask = new RefreshTask(); refreshTask.execute((Void)null); } @SuppressWarnings("unchecked") public void onResume() { super.onResume(); getListView().setStackFromBottom(true); getListView().requestFocus(); if(bid == -1) { BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(cid, name); if(b != null) { bid = b.bid; } } if(getListView().getHeaderViewsCount() == 0) { headerViewContainer = getLayoutInflater(null).inflate(R.layout.messageview_header, null); headerView = headerViewContainer.findViewById(R.id.progress); getListView().addHeaderView(headerViewContainer); } adapter = new MessageAdapter(this); setListAdapter(adapter); conn = NetworkConnection.getInstance(); conn.addHandler(mHandler); if(ServersDataSource.getInstance().getServer(cid) != null) ignore.setIgnores(ServersDataSource.getInstance().getServer(cid).ignores); if(bid != -1) { collapsedEvents.setChannel(cid, name); TreeMap<Long,EventsDataSource.Event> events = EventsDataSource.getInstance().getEventsForBuffer((int)bid); if(events != null) { events = (TreeMap<Long, EventsDataSource.Event>)events.clone(); ServersDataSource.Server server = ServersDataSource.getInstance().getServer(cid); BuffersDataSource.Buffer buffer = BuffersDataSource.getInstance().getBuffer((int)bid); if(backlog_eid > 0) { EventsDataSource.Event backlogMarker = EventsDataSource.getInstance().new Event(); backlogMarker.eid = backlog_eid; backlogMarker.type = TYPE_BACKLOGMARKER; backlogMarker.row_type = ROW_BACKLOGMARKER; backlogMarker.bg_color = R.color.message_bg; events.put(backlog_eid, backlogMarker); } refresh(events, server, buffer); adapter.notifyDataSetChanged(); getListView().setSelection(adapter.getCount() - 1); } } } private class HeartbeatTask extends AsyncTaskEx<Long, Void, Void> { @Override protected Void doInBackground(Long... params) { Long eid = params[0]; try { Thread.sleep(1000); } catch (InterruptedException e) { } if(isCancelled()) return null; if(eid > last_seen_eid && conn.getState() == NetworkConnection.STATE_CONNECTED) { if(getActivity() != null && getActivity().getIntent() != null) getActivity().getIntent().putExtra("last_seen_eid", eid); NetworkConnection.getInstance().heartbeat(bid, cid, bid, eid); last_seen_eid = eid; BuffersDataSource.getInstance().updateLastSeenEid(bid, eid); } return null; } @Override protected void onPostExecute(Void result) { if(!isCancelled()) heartbeatTask = null; } } private class RefreshTask extends AsyncTaskEx<Void, Void, Void> { TreeMap<Long,EventsDataSource.Event> events; ServersDataSource.Server server; BuffersDataSource.Buffer buffer; @SuppressWarnings("unchecked") @Override protected Void doInBackground(Void... params) { buffer = BuffersDataSource.getInstance().getBuffer((int)bid); server = ServersDataSource.getInstance().getServer(cid); long time = System.currentTimeMillis(); events = EventsDataSource.getInstance().getEventsForBuffer((int)bid); Log.i("IRCCloud", "Loaded data in " + (System.currentTimeMillis() - time) + "ms"); if(!isCancelled() && events != null && events.size() > 0) { events = (TreeMap<Long, EventsDataSource.Event>)events.clone(); } return null; } @Override protected void onPostExecute(Void result) { if(isCancelled()) return; if(events != null && events.size() > 0) { int oldPosition = getListView().getFirstVisiblePosition(); if(earliest_eid > events.firstKey()) { backlog_eid = adapter.getGroupForPosition(oldPosition) - 1; if(backlog_eid < 0) { backlog_eid = adapter.getItemId(oldPosition) - 1; } EventsDataSource.Event backlogMarker = EventsDataSource.getInstance().new Event(); backlogMarker.eid = backlog_eid; backlogMarker.type = TYPE_BACKLOGMARKER; backlogMarker.row_type = ROW_BACKLOGMARKER; backlogMarker.html = "__backlog__"; backlogMarker.bg_color = R.color.message_bg; events.put(backlog_eid, backlogMarker); } adapter.clear(); refresh(events, server, buffer); try { int markerPos = adapter.getBacklogMarkerPosition(); if(markerPos != -1 && requestingBacklog) { getListView().setSelectionFromTop(oldPosition + markerPos + 1, headerViewContainer.getHeight()); } } catch (IllegalStateException e) { //The list view doesn't exist yet Log.e("IRCCloud", "Tried to refresh the message list, but it didn't exist."); } } requestingBacklog = false; refreshTask = null; } } private void refresh(TreeMap<Long,EventsDataSource.Event> events, ServersDataSource.Server server, BuffersDataSource.Buffer buffer) { collapsedEvents.clear(); currentCollapsedEid = -1; if(events == null || (events.size() == 0 && min_eid > 0)) { if(bid != -1) { requestingBacklog = true; conn.request_backlog(cid, bid, 0); } else { headerView.setVisibility(View.GONE); } } else if(events.size() > 0) { if(ServersDataSource.getInstance().getServer(cid) != null) ignore.setIgnores(ServersDataSource.getInstance().getServer(cid).ignores); else ignore.setIgnores(null); earliest_eid = events.firstKey(); if(events.firstKey() > min_eid && min_eid > 0) { headerView.setVisibility(View.VISIBLE); } else { headerView.setVisibility(View.GONE); } if(events.size() > 0) { avgInsertTime = 0; //Debug.startMethodTracing("refresh"); long start = System.currentTimeMillis(); Iterator<EventsDataSource.Event> i = events.values().iterator(); EventsDataSource.Event next = i.next(); Calendar calendar = Calendar.getInstance(); while(next != null) { EventsDataSource.Event e = next; next = i.hasNext()?i.next():null; String type = (next == null)?"":next.type; if(next != null && currentCollapsedEid != -1 && !expandedSectionEids.contains(currentCollapsedEid) && (type.equalsIgnoreCase("joined_channel") || type.equalsIgnoreCase("parted_channel") || type.equalsIgnoreCase("nickchange") || type.equalsIgnoreCase("quit") || type.equalsIgnoreCase("user_channel_mode"))) { calendar.setTimeInMillis(next.eid / 1000); insertEvent(e, true, calendar.get(Calendar.DAY_OF_YEAR) == lastCollapsedDay); } else { insertEvent(e, true, false); } } if(adapter.getLastSeenEIDPosition() == -1) adapter.insertLastSeenEIDMarker(); Log.i("IRCCloud", "Backlog rendering took: " + (System.currentTimeMillis() - start) + "ms"); //Debug.stopMethodTracing(); avgInsertTime = 0; adapter.notifyDataSetChanged(); } } mHandler.removeCallbacks(mFirstScrollRunnable); mHandler.removeCallbacks(mUpdateTopUnreadRunnable); mHandler.post(mFirstScrollRunnable); mHandler.postDelayed(mUpdateTopUnreadRunnable, 100); } private Runnable mFirstScrollRunnable = new Runnable() { @Override public void run() { if(adapter != null) { if(firstScroll) { getListView().setSelection(adapter.data.size() - 1); firstScroll = false; } } } }; private Runnable mUpdateTopUnreadRunnable = new Runnable() { @Override public void run() { if(adapter != null) { int markerPos = adapter.getLastSeenEIDPosition(); if(markerPos > 0 && getListView().getFirstVisiblePosition() > markerPos) { if(shouldTrackUnread()) { unreadTopLabel.setText((getListView().getFirstVisiblePosition() - markerPos - 1) + " unread messages"); unreadTopView.setVisibility(View.VISIBLE); } else { unreadTopView.setVisibility(View.GONE); } } else { unreadTopView.setVisibility(View.GONE); if(adapter.data.size() > 0) { Long e = adapter.data.get(adapter.data.size() - 1).eid; if(heartbeatTask != null) heartbeatTask.cancel(true); heartbeatTask = new HeartbeatTask(); heartbeatTask.execute(e); } } ServersDataSource.Server s = ServersDataSource.getInstance().getServer(cid); if(s != null) update_status(s.status, s.fail_info); if(mListener != null) mListener.onMessageViewReady(); } else { Log.e("IRCCloud", "Adapter was null!"); } } }; private boolean shouldTrackUnread() { if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null && conn.getUserInfo().prefs.has("channel-disableTrackUnread")) { try { JSONObject disabledMap = conn.getUserInfo().prefs.getJSONObject("channel-disableTrackUnread"); if(disabledMap.has(String.valueOf(bid)) && disabledMap.getBoolean(String.valueOf(bid))) { return false; } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return true; } private class UnreadRefreshRunnable implements Runnable { @Override public void run() { update_unread(); } } UnreadRefreshRunnable unreadRefreshRunnable = null; private void update_unread() { if(unreadRefreshRunnable != null) { mHandler.removeCallbacks(unreadRefreshRunnable); unreadRefreshRunnable = null; } if(newMsgs > 0) { int minutes = (int)((System.currentTimeMillis() - newMsgTime)/60000); if(minutes < 1) unreadView.setText("Less than a minute of chatter ("); else if(minutes == 1) unreadView.setText("1 minute of chatter ("); else unreadView.setText(minutes + " minutes of chatter ("); if(newMsgs == 1) unreadView.setText(unreadView.getText() + "1 message)"); else unreadView.setText(unreadView.getText() + (newMsgs + " messages)")); unreadView.setVisibility(View.VISIBLE); unreadRefreshRunnable = new UnreadRefreshRunnable(); mHandler.postDelayed(unreadRefreshRunnable, 10000); } } private class StatusRefreshRunnable implements Runnable { String status; JsonObject fail_info; public StatusRefreshRunnable(String status, JsonObject fail_info) { this.status = status; this.fail_info = fail_info; } @Override public void run() { update_status(status, fail_info); } } StatusRefreshRunnable statusRefreshRunnable = null; private void update_status(String status, JsonObject fail_info) { if(statusRefreshRunnable != null) { mHandler.removeCallbacks(statusRefreshRunnable); statusRefreshRunnable = null; } if(status.equals("connected_ready")) { statusView.setVisibility(View.GONE); statusView.setText(""); } else if(status.equals("quitting")) { statusView.setVisibility(View.VISIBLE); statusView.setText("Disconnecting"); statusView.setTextColor(getResources().getColor(R.color.dark_blue)); statusView.setBackgroundResource(R.drawable.background_blue); } else if(status.equals("disconnected")) { statusView.setVisibility(View.VISIBLE); statusView.setText("Disconnected"); statusView.setTextColor(getResources().getColor(R.color.dark_blue)); statusView.setBackgroundResource(R.drawable.background_blue); } else if(status.equals("queued")) { statusView.setVisibility(View.VISIBLE); statusView.setText("Connection queued"); statusView.setTextColor(getResources().getColor(R.color.dark_blue)); statusView.setBackgroundResource(R.drawable.background_blue); } else if(status.equals("connecting")) { statusView.setVisibility(View.VISIBLE); statusView.setText("Connecting"); statusView.setTextColor(getResources().getColor(R.color.dark_blue)); statusView.setBackgroundResource(R.drawable.background_blue); } else if(status.equals("connected")) { statusView.setVisibility(View.VISIBLE); statusView.setText("Connected"); statusView.setTextColor(getResources().getColor(R.color.dark_blue)); statusView.setBackgroundResource(R.drawable.background_blue); } else if(status.equals("connected_joining")) { statusView.setVisibility(View.VISIBLE); statusView.setText("Connected: Joining Channels"); statusView.setTextColor(getResources().getColor(R.color.dark_blue)); statusView.setBackgroundResource(R.drawable.background_blue); } else if(status.equals("pool_unavailable")) { statusView.setVisibility(View.VISIBLE); statusView.setText("Disconnected: Connection temporarily unavailable"); statusView.setTextColor(getResources().getColor(R.color.status_fail_text)); statusView.setBackgroundResource(R.drawable.status_fail_bg); } else if(status.equals("waiting_to_retry")) { try { statusView.setVisibility(View.VISIBLE); long seconds = (fail_info.get("timestamp").getAsLong() + fail_info.get("retry_timeout").getAsInt()) - System.currentTimeMillis()/1000; statusView.setText("Disconnected: " + fail_info.get("reason").getAsString() + ". Reconnecting in " + seconds + " seconds."); statusView.setTextColor(getResources().getColor(R.color.status_fail_text)); statusView.setBackgroundResource(R.drawable.status_fail_bg); statusRefreshRunnable = new StatusRefreshRunnable(status, fail_info); mHandler.postDelayed(statusRefreshRunnable, 500); } catch (Exception e) { e.printStackTrace(); } } else if(status.equals("ip_retry")) { statusView.setVisibility(View.VISIBLE); statusView.setText("Trying another IP address"); statusView.setTextColor(getResources().getColor(R.color.dark_blue)); statusView.setBackgroundResource(R.drawable.background_blue); } } public void onPause() { super.onPause(); if(statusRefreshRunnable != null) { mHandler.removeCallbacks(statusRefreshRunnable); statusRefreshRunnable = null; } if(conn != null) conn.removeHandler(mHandler); } private final Handler mHandler = new Handler() { IRCCloudJSONObject e; public void handleMessage(Message msg) { switch (msg.what) { case NetworkConnection.EVENT_BACKLOG_END: case NetworkConnection.EVENT_USERINFO: if(refreshTask != null) refreshTask.cancel(true); refreshTask = new RefreshTask(); refreshTask.execute((Void)null); break; case NetworkConnection.EVENT_STATUSCHANGED: try { IRCCloudJSONObject object = (IRCCloudJSONObject)msg.obj; if(object.getInt("cid") == cid) { update_status(object.getString("new_status"), object.getJsonObject("fail_info")); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } break; case NetworkConnection.EVENT_MAKEBUFFER: BuffersDataSource.Buffer buffer = (BuffersDataSource.Buffer)msg.obj; if(bid == -1 && buffer.cid == cid && buffer.name.equalsIgnoreCase(name)) { bid = buffer.bid; if(refreshTask != null) refreshTask.cancel(true); refreshTask = new RefreshTask(); refreshTask.execute((Void)null); } break; case NetworkConnection.EVENT_DELETEBUFFER: if((Integer)msg.obj == bid) { Intent parentActivityIntent = new Intent(getActivity(), MainActivity.class); parentActivityIntent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); getActivity().startActivity(parentActivityIntent); getActivity().finish(); } break; case NetworkConnection.EVENT_USERCHANNELMODE: case NetworkConnection.EVENT_SETIGNORES: e = (IRCCloudJSONObject)msg.obj; if(e.cid() == cid) { if(refreshTask != null) refreshTask.cancel(true); refreshTask = new RefreshTask(); refreshTask.execute((Void)null); } break; case NetworkConnection.EVENT_HEARTBEATECHO: if(adapter != null) { BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBuffer(bid); if(b != null && last_seen_eid != b.last_seen_eid) { last_seen_eid = b.last_seen_eid; if(last_seen_eid == adapter.data.get(adapter.data.size() - 1).eid || !shouldTrackUnread()) { unreadTopView.setVisibility(View.GONE); } } } break; case NetworkConnection.EVENT_CHANNELTOPIC: case NetworkConnection.EVENT_JOIN: case NetworkConnection.EVENT_PART: case NetworkConnection.EVENT_NICKCHANGE: case NetworkConnection.EVENT_QUIT: case NetworkConnection.EVENT_KICK: case NetworkConnection.EVENT_CHANNELMODE: case NetworkConnection.EVENT_SELFDETAILS: case NetworkConnection.EVENT_USERMODE: e = (IRCCloudJSONObject)msg.obj; if(e.bid() == bid) { EventsDataSource.Event event = EventsDataSource.getInstance().getEvent(e.eid(), e.bid()); insertEvent(event, false, false); } break; case NetworkConnection.EVENT_BUFFERMSG: EventsDataSource.Event event = (EventsDataSource.Event)msg.obj; if(event.bid == bid) { insertEvent(event, false, false); } break; default: break; } } }; public interface MessageViewListener { public void onMessageViewReady(); } }
src/com/irccloud/android/MessageViewFragment.java
package com.irccloud.android; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.HashSet; import java.util.Iterator; import java.util.TreeMap; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Debug; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import com.actionbarsherlock.app.SherlockListFragment; import com.google.gson.JsonArray; import com.google.gson.JsonObject; public class MessageViewFragment extends SherlockListFragment { private NetworkConnection conn; private TextView statusView; private View headerViewContainer; private View headerView; private TextView unreadView; private TextView unreadTopLabel; private View unreadTopView; private int cid; private int bid; private long last_seen_eid; private long min_eid; private long earliest_eid; private long backlog_eid = 0; private String name; private String type; private boolean firstScroll = true; private boolean requestingBacklog = false; private boolean shouldShowUnread = false; private float avgInsertTime = 0; private int newMsgs = 0; private long newMsgTime = 0; private MessageViewListener mListener; public static final int ROW_MESSAGE = 0; public static final int ROW_TIMESTAMP = 1; public static final int ROW_BACKLOGMARKER = 2; public static final int ROW_SOCKETCLOSED = 3; public static final int ROW_LASTSEENEID = 4; private static final String TYPE_TIMESTAMP = "__timestamp__"; private static final String TYPE_BACKLOGMARKER = "__backlog__"; private static final String TYPE_LASTSEENEID = "__lastseeneid__"; private MessageAdapter adapter; private long currentCollapsedEid = -1; private CollapsedEventsList collapsedEvents = new CollapsedEventsList(); private int lastCollapsedDay = -1; private HashSet<Long> expandedSectionEids = new HashSet<Long>(); private RefreshTask refreshTask = null; private HeartbeatTask heartbeatTask = null; private Ignore ignore = new Ignore(); private class MessageAdapter extends BaseAdapter { ArrayList<EventsDataSource.Event> data; private SherlockListFragment ctx; private long max_eid = 0; private long min_eid = 0; private int lastDay = -1; private int lastSeenEidMarkerPosition = -1; private int currentGroupPosition = -1; private class ViewHolder { int type; TextView timestamp; TextView message; } public MessageAdapter(SherlockListFragment context) { ctx = context; data = new ArrayList<EventsDataSource.Event>(); } public void clear() { max_eid = 0; min_eid = 0; lastDay = -1; lastSeenEidMarkerPosition = -1; currentGroupPosition = -1; data.clear(); } public void removeItem(long eid) { for(int i = 0; i < data.size(); i++) { if(data.get(i).eid == eid) { data.remove(i); i--; } } } public int getBacklogMarkerPosition() { for(int i = 0; i < data.size(); i++) { if(data.get(i).row_type == ROW_BACKLOGMARKER) { return i; } } return -1; } public int insertLastSeenEIDMarker() { EventsDataSource.Event e = EventsDataSource.getInstance().new Event(); e.type = TYPE_LASTSEENEID; e.row_type = ROW_LASTSEENEID; e.bg_color = R.drawable.socketclosed_bg; for(int i = 0; i < data.size(); i++) { if(data.get(i).row_type == ROW_LASTSEENEID) { data.remove(i); } } for(int i = data.size() - 1; i >= 0; i--) { if(data.get(i).eid <= last_seen_eid) { lastSeenEidMarkerPosition = i; break; } } if(lastSeenEidMarkerPosition != data.size() - 1) { if(lastSeenEidMarkerPosition > 0 && data.get(lastSeenEidMarkerPosition - 1).row_type == ROW_TIMESTAMP) lastSeenEidMarkerPosition--; if(lastSeenEidMarkerPosition > 0) data.add(lastSeenEidMarkerPosition + 1, e); } else { lastSeenEidMarkerPosition = -1; } return lastSeenEidMarkerPosition; } public int getLastSeenEIDPosition() { return lastSeenEidMarkerPosition; } public synchronized void addItem(long eid, EventsDataSource.Event e) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(eid / 1000); int insert_pos = -1; SimpleDateFormat formatter; formatter = new SimpleDateFormat("h:mm a"); if(conn.getUserInfo() != null && conn.getUserInfo().prefs != null) { try { JSONObject prefs = conn.getUserInfo().prefs; if(prefs.has("time-24hr") && prefs.getBoolean("time-24hr")) { if(prefs.has("time-seconds") && prefs.getBoolean("time-seconds")) formatter = new SimpleDateFormat("H:mm:ss"); else formatter = new SimpleDateFormat("H:mm"); } else if(prefs.has("time-seconds") && prefs.getBoolean("time-seconds")) { formatter = new SimpleDateFormat("h:mm:ss a"); } } catch (JSONException e1) { e1.printStackTrace(); } } e.timestamp = formatter.format(calendar.getTime()); e.group_eid = currentCollapsedEid; if(currentGroupPosition > 0 && eid == currentCollapsedEid && e.eid != eid) { //Shortcut for replacing the current group calendar.setTimeInMillis(e.eid / 1000); lastDay = calendar.get(Calendar.DAY_OF_YEAR); data.remove(currentGroupPosition); data.add(currentGroupPosition, e); insert_pos = currentGroupPosition; } else if(eid > max_eid || data.size() == 0) { //Message at the bottom if(data.size() > 0) { calendar.setTimeInMillis(data.get(data.size()-1).eid / 1000); lastDay = calendar.get(Calendar.DAY_OF_YEAR); calendar.setTimeInMillis(eid/1000); } else { lastDay = 0; } max_eid = eid; data.add(e); insert_pos = data.size() - 1; } else if(min_eid > eid) { //Message goes on top calendar.setTimeInMillis(data.get(1).eid / 1000); lastDay = calendar.get(Calendar.DAY_OF_YEAR); calendar.setTimeInMillis(eid/1000); if(calendar.get(Calendar.DAY_OF_YEAR) != lastDay) { //Insert above the dateline data.add(0, e); insert_pos = 0; } else { //Insert below the dateline data.add(1, e); insert_pos = 1; } } else { int i = 0; for(EventsDataSource.Event e1 : data) { if(e1.row_type != ROW_TIMESTAMP && e1.eid > eid && e.eid == eid) { //Insert the message if(i > 0 && data.get(i-1).row_type != ROW_TIMESTAMP) { calendar.setTimeInMillis(data.get(i-1).eid / 1000); lastDay = calendar.get(Calendar.DAY_OF_YEAR); data.add(i, e); insert_pos = i; break; } else { //There was a date line above our insertion point calendar.setTimeInMillis(e1.eid / 1000); lastDay = calendar.get(Calendar.DAY_OF_YEAR); calendar.setTimeInMillis(eid/1000); if(calendar.get(Calendar.DAY_OF_YEAR) != lastDay) { //Insert above the dateline if(i > 1) { calendar.setTimeInMillis(data.get(i-2).eid / 1000); lastDay = calendar.get(Calendar.DAY_OF_YEAR); } else { //We're above the first dateline, so we'll need to put a new one on top! lastDay = 0; } calendar.setTimeInMillis(eid/1000); data.add(i-1, e); insert_pos = i-1; } else { //Insert below the dateline data.add(i, e); insert_pos = i; } break; } } else if(e1.row_type != ROW_TIMESTAMP && (e1.eid == eid || e1.group_eid == eid)) { //Replace the message lastDay = calendar.get(Calendar.DAY_OF_YEAR); data.remove(i); data.add(i, e); insert_pos = i; break; } i++; } } if(insert_pos == -1) { Log.e("IRCCloud", "Couldn't insert EID: " + eid + " MSG: " + e.html); return; } if(eid == currentCollapsedEid && e.eid == eid) { currentGroupPosition = insert_pos; } else if(currentCollapsedEid == -1) { currentGroupPosition = -1; } if(calendar.get(Calendar.DAY_OF_YEAR) != lastDay) { formatter.applyPattern("EEEE, MMMM dd, yyyy"); EventsDataSource.Event d = EventsDataSource.getInstance().new Event(); d.type = TYPE_TIMESTAMP; d.row_type = ROW_TIMESTAMP; d.eid = eid; d.timestamp = formatter.format(calendar.getTime()); d.bg_color = R.color.dateline_bg; data.add(insert_pos, d); lastDay = calendar.get(Calendar.DAY_OF_YEAR); if(currentGroupPosition > -1) currentGroupPosition++; } } @Override public int getCount() { return data.size(); } @Override public Object getItem(int position) { return data.get(position); } @Override public long getItemId(int position) { return data.get(position).eid; } public long getGroupForPosition(int position) { return data.get(position).group_eid; } @Override public View getView(int position, View convertView, ViewGroup parent) { EventsDataSource.Event e = data.get(position); View row = convertView; ViewHolder holder; if(row != null && ((ViewHolder)row.getTag()).type != e.row_type) row = null; if (row == null) { LayoutInflater inflater = ctx.getLayoutInflater(null); if(e.row_type == ROW_BACKLOGMARKER) row = inflater.inflate(R.layout.row_backlogmarker, null); else if(e.row_type == ROW_TIMESTAMP) row = inflater.inflate(R.layout.row_timestamp, null); else if(e.row_type == ROW_SOCKETCLOSED) row = inflater.inflate(R.layout.row_socketclosed, null); else if(e.row_type == ROW_LASTSEENEID) row = inflater.inflate(R.layout.row_lastseeneid, null); else row = inflater.inflate(R.layout.row_message, null); holder = new ViewHolder(); holder.timestamp = (TextView) row.findViewById(R.id.timestamp); holder.message = (TextView) row.findViewById(R.id.message); holder.type = e.row_type; row.setTag(holder); } else { holder = (ViewHolder) row.getTag(); } row.setBackgroundResource(e.bg_color); if(holder.timestamp != null) holder.timestamp.setText(e.timestamp); if(e.group_msg != null && e.html == null) e.html = ColorFormatter.irc_to_html(e.group_msg); if(holder.message != null && e.html != null) { holder.message.setTextColor(getResources().getColorStateList(e.color)); holder.message.setText(ColorFormatter.html_to_spanned(e.html)); } return row; } } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View v = inflater.inflate(R.layout.messageview, container, false); statusView = (TextView)v.findViewById(R.id.statusView); unreadView = (TextView)v.findViewById(R.id.unread); unreadView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { getListView().setSelection(adapter.getCount() - 1); } }); unreadTopView = v.findViewById(R.id.unreadTop); unreadTopView.setVisibility(View.INVISIBLE); unreadTopView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { unreadTopView.setVisibility(View.GONE); getListView().setSelection(adapter.getLastSeenEIDPosition()); Long e = adapter.data.get(adapter.data.size() - 1).eid; new HeartbeatTask().execute(e); } }); unreadTopLabel = (TextView)v.findViewById(R.id.unreadTopText); Button b = (Button)v.findViewById(R.id.markAsRead); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { unreadTopView.setVisibility(View.GONE); Long e = adapter.data.get(adapter.data.size() - 1).eid; new HeartbeatTask().execute(e); } }); ((ListView)v.findViewById(android.R.id.list)).setOnScrollListener(new OnScrollListener() { @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if(headerView != null) { if(firstVisibleItem == 0 && !requestingBacklog && headerView.getVisibility() == View.VISIBLE && bid != -1) { requestingBacklog = true; conn.request_backlog(cid, bid, earliest_eid); } } int markerPos = -1; if(adapter != null) markerPos = adapter.getLastSeenEIDPosition(); if(unreadView != null && adapter != null) { if(firstVisibleItem + visibleItemCount == totalItemCount) { unreadView.setVisibility(View.GONE); if(newMsgs > 0 || unreadTopView.getVisibility() == View.GONE) { Long e = adapter.data.get(adapter.data.size() - 1).eid; if(heartbeatTask != null) heartbeatTask.cancel(true); heartbeatTask = new HeartbeatTask(); heartbeatTask.execute(e); } newMsgs = 0; newMsgTime = 0; } } if(firstVisibleItem + visibleItemCount < totalItemCount) shouldShowUnread = true; if(adapter != null && unreadTopView != null && unreadTopView.getVisibility() == View.VISIBLE) { if(markerPos > 0 && getListView().getFirstVisiblePosition() <= markerPos) { unreadTopView.setVisibility(View.GONE); Long e = adapter.data.get(adapter.data.size() - 1).eid; if(heartbeatTask != null) heartbeatTask.cancel(true); heartbeatTask = new HeartbeatTask(); heartbeatTask.execute(e); } } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } }); return v; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(savedInstanceState != null && savedInstanceState.containsKey("cid")) { cid = savedInstanceState.getInt("cid"); bid = savedInstanceState.getInt("bid"); name = savedInstanceState.getString("name"); last_seen_eid = savedInstanceState.getLong("last_seen_eid"); min_eid = savedInstanceState.getLong("min_eid"); type = savedInstanceState.getString("type"); firstScroll = savedInstanceState.getBoolean("firstScroll"); backlog_eid = savedInstanceState.getLong("backlog_eid"); //TODO: serialize the adapter data } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (MessageViewListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement MessageViewListener"); } } @Override public void onSaveInstanceState(Bundle state) { super.onSaveInstanceState(state); state.putInt("cid", cid); state.putInt("bid", bid); state.putLong("last_seen_eid", last_seen_eid); state.putLong("min_eid", min_eid); state.putString("name", name); state.putString("type", type); state.putBoolean("firstScroll", firstScroll); state.putLong("backlog_eid", backlog_eid); //TODO: serialize the adapter data } @Override public void setArguments(Bundle args) { cid = args.getInt("cid", 0); bid = args.getInt("bid", 0); last_seen_eid = args.getLong("last_seen_eid", 0); min_eid = args.getLong("min_eid", 0); name = args.getString("name"); type = args.getString("type"); firstScroll = true; requestingBacklog = false; shouldShowUnread = false; avgInsertTime = 0; newMsgs = 0; newMsgTime = 0; earliest_eid = 0; backlog_eid = 0; collapsedEvents.setChannel(cid, name); if(unreadTopView != null) unreadTopView.setVisibility(View.INVISIBLE); if(headerView != null) { mHandler.postDelayed(new Runnable() { @Override public void run() { if(EventsDataSource.getInstance().getEventsForBuffer(bid) != null) { requestingBacklog = true; if(refreshTask != null) refreshTask.cancel(true); refreshTask = new RefreshTask(); refreshTask.execute((Void)null); } else { if(bid == -1) { headerView.setVisibility(View.GONE); } else { headerView.setVisibility(View.VISIBLE); ignore.setIgnores(ServersDataSource.getInstance().getServer(cid).ignores); } adapter.clear(); adapter.notifyDataSetInvalidated(); mListener.onMessageViewReady(); } } }, 100); } } private synchronized void insertEvent(EventsDataSource.Event event, boolean backlog, boolean nextIsGrouped) { try { long start = System.currentTimeMillis(); if(min_eid == 0) min_eid = event.eid; if(event.eid == min_eid) { headerView.setVisibility(View.GONE); } if(event.eid < earliest_eid) earliest_eid = event.eid; String type = event.type; long eid = event.eid; if(type.startsWith("you_")) type = type.substring(4); if(type.equalsIgnoreCase("joined_channel") || type.equalsIgnoreCase("parted_channel") || type.equalsIgnoreCase("nickchange") || type.equalsIgnoreCase("quit") || type.equalsIgnoreCase("user_channel_mode")) { if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null) { JSONObject hiddenMap = conn.getUserInfo().prefs.getJSONObject("channel-hideJoinPart"); if(hiddenMap.has(String.valueOf(bid)) && hiddenMap.getBoolean(String.valueOf(bid))) { adapter.removeItem(event.eid); if(!backlog) adapter.notifyDataSetChanged(); return; } } Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(eid / 1000); if(currentCollapsedEid == -1 || calendar.get(Calendar.DAY_OF_YEAR) != lastCollapsedDay) { collapsedEvents.clear(); currentCollapsedEid = eid; lastCollapsedDay = calendar.get(Calendar.DAY_OF_YEAR); } if(expandedSectionEids.contains(currentCollapsedEid)) collapsedEvents.clear(); if(type.equalsIgnoreCase("joined_channel")) { collapsedEvents.addEvent(CollapsedEventsList.TYPE_JOIN, event.nick, null, event.hostmask, null); } else if(type.equalsIgnoreCase("parted_channel")) { collapsedEvents.addEvent(CollapsedEventsList.TYPE_PART, event.nick, null, event.hostmask, null); } else if(type.equalsIgnoreCase("quit")) { collapsedEvents.addEvent(CollapsedEventsList.TYPE_QUIT, event.nick, null, event.hostmask, event.msg); } else if(type.equalsIgnoreCase("nickchange")) { collapsedEvents.addEvent(CollapsedEventsList.TYPE_NICKCHANGE, event.nick, event.old_nick, null, null); } else if(type.equalsIgnoreCase("user_channel_mode")) { boolean unknown = false; JsonObject ops = event.ops; if(ops != null) { JsonArray add = ops.getAsJsonArray("add"); for(int i = 0; i < add.size(); i++) { JsonObject op = add.get(i).getAsJsonObject(); if(op.get("mode").getAsString().equalsIgnoreCase("q")) collapsedEvents.addEvent(CollapsedEventsList.TYPE_MODE, op.get("param").getAsString(), event.from, event.hostmask, null, CollapsedEventsList.MODE_OWNER); else if(op.get("mode").getAsString().equalsIgnoreCase("a")) collapsedEvents.addEvent(CollapsedEventsList.TYPE_MODE, op.get("param").getAsString(), event.from, event.hostmask, null, CollapsedEventsList.MODE_ADMIN); else if(op.get("mode").getAsString().equalsIgnoreCase("o")) collapsedEvents.addEvent(CollapsedEventsList.TYPE_MODE, op.get("param").getAsString(), event.from, event.hostmask, null, CollapsedEventsList.MODE_OP); else if(op.get("mode").getAsString().equalsIgnoreCase("h")) collapsedEvents.addEvent(CollapsedEventsList.TYPE_MODE, op.get("param").getAsString(), event.from, event.hostmask, null, CollapsedEventsList.MODE_HALFOP); else if(op.get("mode").getAsString().equalsIgnoreCase("v")) collapsedEvents.addEvent(CollapsedEventsList.TYPE_MODE, op.get("param").getAsString(), event.from, event.hostmask, null, CollapsedEventsList.MODE_VOICE); else unknown = true; } JsonArray remove = ops.getAsJsonArray("remove"); for(int i = 0; i < remove.size(); i++) { JsonObject op = remove.get(i).getAsJsonObject(); if(op.get("mode").getAsString().equalsIgnoreCase("q")) collapsedEvents.addEvent(CollapsedEventsList.TYPE_MODE, op.get("param").getAsString(), event.from, event.hostmask, null, CollapsedEventsList.MODE_DEOWNER); else if(op.get("mode").getAsString().equalsIgnoreCase("a")) collapsedEvents.addEvent(CollapsedEventsList.TYPE_MODE, op.get("param").getAsString(), event.from, event.hostmask, null, CollapsedEventsList.MODE_DEADMIN); else if(op.get("mode").getAsString().equalsIgnoreCase("o")) collapsedEvents.addEvent(CollapsedEventsList.TYPE_MODE, op.get("param").getAsString(), event.from, event.hostmask, null, CollapsedEventsList.MODE_DEOP); else if(op.get("mode").getAsString().equalsIgnoreCase("h")) collapsedEvents.addEvent(CollapsedEventsList.TYPE_MODE, op.get("param").getAsString(), event.from, event.hostmask, null, CollapsedEventsList.MODE_DEHALFOP); else if(op.get("mode").getAsString().equalsIgnoreCase("v")) collapsedEvents.addEvent(CollapsedEventsList.TYPE_MODE, op.get("param").getAsString(), event.from, event.hostmask, null, CollapsedEventsList.MODE_DEVOICE); else unknown = true; } } if(unknown) { collapsedEvents.clear(); } } String msg = (nextIsGrouped && currentCollapsedEid != event.eid)?"":collapsedEvents.getCollapsedMessage(); if(msg == null && type.equalsIgnoreCase("nickchange")) { msg = event.old_nick + " → <b>" + event.nick + "</b>"; } if(msg == null && type.equalsIgnoreCase("user_channel_mode")) { msg = "<b>" + collapsedEvents.formatNick(event.from) + "</b> set mode: <b>" + event.diff + " " + event.nick + "</b>"; currentCollapsedEid = eid; } if(!expandedSectionEids.contains(currentCollapsedEid)) { if(eid != currentCollapsedEid) msg = "[+] " + msg; eid = currentCollapsedEid; } event.color = R.color.timestamp; event.group_msg = msg; event.html = null; } else { currentCollapsedEid = -1; collapsedEvents.clear(); if(event.from != null) event.html = "<b>" + collapsedEvents.formatNick(event.from) + "</b> " + event.msg; else event.html = event.msg; } if(!type.equalsIgnoreCase("user_channel_mode") && event.from != null && event.hostmask != null) { String usermask = event.from + "!" + event.hostmask; if(ignore.match(usermask)) return; } adapter.addItem(eid, event); if(!backlog) adapter.notifyDataSetChanged(); long time = (System.currentTimeMillis() - start); if(avgInsertTime == 0) avgInsertTime = time; avgInsertTime += time; avgInsertTime /= 2.0; //Log.i("IRCCloud", "Average insert time: " + avgInsertTime); if(getListView().getLastVisiblePosition() >= (adapter.getCount() - 1)) { shouldShowUnread = false; } if(!backlog && shouldShowUnread) { if(newMsgTime == 0) newMsgTime = System.currentTimeMillis(); newMsgs++; update_unread(); } if(!backlog && !shouldShowUnread) getListView().setSelection(adapter.getCount() - 1); if(!backlog) { int markerPos = adapter.getLastSeenEIDPosition(); if(markerPos > 0 && getListView().getFirstVisiblePosition() > markerPos) { unreadTopLabel.setText((getListView().getFirstVisiblePosition() - markerPos) + " unread messages"); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void onListItemClick(ListView l, View v, int position, long id) { long group = adapter.getGroupForPosition(position-1); if(expandedSectionEids.contains(group)) expandedSectionEids.remove(group); else expandedSectionEids.add(group); if(refreshTask != null) refreshTask.cancel(true); refreshTask = new RefreshTask(); refreshTask.execute((Void)null); } @SuppressWarnings("unchecked") public void onResume() { super.onResume(); getListView().setStackFromBottom(true); getListView().requestFocus(); if(bid == -1) { BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBufferByName(cid, name); if(b != null) { bid = b.bid; } } if(getListView().getHeaderViewsCount() == 0) { headerViewContainer = getLayoutInflater(null).inflate(R.layout.messageview_header, null); headerView = headerViewContainer.findViewById(R.id.progress); getListView().addHeaderView(headerViewContainer); } adapter = new MessageAdapter(this); setListAdapter(adapter); conn = NetworkConnection.getInstance(); conn.addHandler(mHandler); if(ServersDataSource.getInstance().getServer(cid) != null) ignore.setIgnores(ServersDataSource.getInstance().getServer(cid).ignores); if(bid != -1) { collapsedEvents.setChannel(cid, name); TreeMap<Long,EventsDataSource.Event> events = EventsDataSource.getInstance().getEventsForBuffer((int)bid); if(events != null) { events = (TreeMap<Long, EventsDataSource.Event>)events.clone(); ServersDataSource.Server server = ServersDataSource.getInstance().getServer(cid); BuffersDataSource.Buffer buffer = BuffersDataSource.getInstance().getBuffer((int)bid); if(backlog_eid > 0) { EventsDataSource.Event backlogMarker = EventsDataSource.getInstance().new Event(); backlogMarker.eid = backlog_eid; backlogMarker.type = TYPE_BACKLOGMARKER; backlogMarker.row_type = ROW_BACKLOGMARKER; backlogMarker.bg_color = R.color.message_bg; events.put(backlog_eid, backlogMarker); } refresh(events, server, buffer); adapter.notifyDataSetChanged(); getListView().setSelection(adapter.getCount() - 1); } } } private class HeartbeatTask extends AsyncTaskEx<Long, Void, Void> { @Override protected Void doInBackground(Long... params) { Long eid = params[0]; try { Thread.sleep(1000); } catch (InterruptedException e) { } if(isCancelled()) return null; if(eid > last_seen_eid && conn.getState() == NetworkConnection.STATE_CONNECTED) { if(getActivity() != null && getActivity().getIntent() != null) getActivity().getIntent().putExtra("last_seen_eid", eid); NetworkConnection.getInstance().heartbeat(bid, cid, bid, eid); last_seen_eid = eid; BuffersDataSource.getInstance().updateLastSeenEid(bid, eid); } return null; } @Override protected void onPostExecute(Void result) { if(!isCancelled()) heartbeatTask = null; } } private class RefreshTask extends AsyncTaskEx<Void, Void, Void> { TreeMap<Long,EventsDataSource.Event> events; ServersDataSource.Server server; BuffersDataSource.Buffer buffer; @SuppressWarnings("unchecked") @Override protected Void doInBackground(Void... params) { buffer = BuffersDataSource.getInstance().getBuffer((int)bid); server = ServersDataSource.getInstance().getServer(cid); long time = System.currentTimeMillis(); events = EventsDataSource.getInstance().getEventsForBuffer((int)bid); Log.i("IRCCloud", "Loaded data in " + (System.currentTimeMillis() - time) + "ms"); if(!isCancelled() && events != null && events.size() > 0) { events = (TreeMap<Long, EventsDataSource.Event>)events.clone(); } return null; } @Override protected void onPostExecute(Void result) { if(isCancelled()) return; if(events != null && events.size() > 0) { int oldPosition = getListView().getFirstVisiblePosition(); if(earliest_eid > events.firstKey()) { backlog_eid = adapter.getGroupForPosition(oldPosition) - 1; if(backlog_eid < 0) { backlog_eid = adapter.getItemId(oldPosition) - 1; } EventsDataSource.Event backlogMarker = EventsDataSource.getInstance().new Event(); backlogMarker.eid = backlog_eid; backlogMarker.type = TYPE_BACKLOGMARKER; backlogMarker.row_type = ROW_BACKLOGMARKER; backlogMarker.html = "__backlog__"; backlogMarker.bg_color = R.color.message_bg; events.put(backlog_eid, backlogMarker); } adapter.clear(); refresh(events, server, buffer); try { int markerPos = adapter.getBacklogMarkerPosition(); if(markerPos != -1 && requestingBacklog) { getListView().setSelectionFromTop(oldPosition + markerPos + 1, headerViewContainer.getHeight()); } } catch (IllegalStateException e) { //The list view doesn't exist yet Log.e("IRCCloud", "Tried to refresh the message list, but it didn't exist."); } } requestingBacklog = false; refreshTask = null; } } private void refresh(TreeMap<Long,EventsDataSource.Event> events, ServersDataSource.Server server, BuffersDataSource.Buffer buffer) { collapsedEvents.clear(); currentCollapsedEid = -1; if(events == null || (events.size() == 0 && min_eid > 0)) { if(bid != -1) { requestingBacklog = true; conn.request_backlog(cid, bid, 0); } else { headerView.setVisibility(View.GONE); } } else if(events.size() > 0) { if(ServersDataSource.getInstance().getServer(cid) != null) ignore.setIgnores(ServersDataSource.getInstance().getServer(cid).ignores); else ignore.setIgnores(null); earliest_eid = events.firstKey(); if(events.firstKey() > min_eid && min_eid > 0) { headerView.setVisibility(View.VISIBLE); } else { headerView.setVisibility(View.GONE); } if(events.size() > 0) { avgInsertTime = 0; //Debug.startMethodTracing("refresh"); long start = System.currentTimeMillis(); Iterator<EventsDataSource.Event> i = events.values().iterator(); EventsDataSource.Event next = i.next(); while(next != null) { EventsDataSource.Event e = next; next = i.hasNext()?i.next():null; String type = (next == null)?"":next.type; if(next != null && currentCollapsedEid != -1 && !expandedSectionEids.contains(currentCollapsedEid) && (type.equalsIgnoreCase("joined_channel") || type.equalsIgnoreCase("parted_channel") || type.equalsIgnoreCase("nickchange") || type.equalsIgnoreCase("quit") || type.equalsIgnoreCase("user_channel_mode"))) insertEvent(e, true, true); else insertEvent(e, true, false); } if(adapter.getLastSeenEIDPosition() == -1) adapter.insertLastSeenEIDMarker(); Log.i("IRCCloud", "Backlog rendering took: " + (System.currentTimeMillis() - start) + "ms"); //Debug.stopMethodTracing(); avgInsertTime = 0; adapter.notifyDataSetChanged(); } } mHandler.removeCallbacks(mFirstScrollRunnable); mHandler.removeCallbacks(mUpdateTopUnreadRunnable); mHandler.post(mFirstScrollRunnable); mHandler.postDelayed(mUpdateTopUnreadRunnable, 100); } private Runnable mFirstScrollRunnable = new Runnable() { @Override public void run() { if(adapter != null) { if(firstScroll) { getListView().setSelection(adapter.data.size() - 1); firstScroll = false; } } } }; private Runnable mUpdateTopUnreadRunnable = new Runnable() { @Override public void run() { if(adapter != null) { int markerPos = adapter.getLastSeenEIDPosition(); if(markerPos > 0 && getListView().getFirstVisiblePosition() > markerPos) { if(shouldTrackUnread()) { unreadTopLabel.setText((getListView().getFirstVisiblePosition() - markerPos - 1) + " unread messages"); unreadTopView.setVisibility(View.VISIBLE); } else { unreadTopView.setVisibility(View.GONE); } } else { unreadTopView.setVisibility(View.GONE); if(adapter.data.size() > 0) { Long e = adapter.data.get(adapter.data.size() - 1).eid; if(heartbeatTask != null) heartbeatTask.cancel(true); heartbeatTask = new HeartbeatTask(); heartbeatTask.execute(e); } } ServersDataSource.Server s = ServersDataSource.getInstance().getServer(cid); if(s != null) update_status(s.status, s.fail_info); if(mListener != null) mListener.onMessageViewReady(); } else { Log.e("IRCCloud", "Adapter was null!"); } } }; private boolean shouldTrackUnread() { if(conn != null && conn.getUserInfo() != null && conn.getUserInfo().prefs != null && conn.getUserInfo().prefs.has("channel-disableTrackUnread")) { try { JSONObject disabledMap = conn.getUserInfo().prefs.getJSONObject("channel-disableTrackUnread"); if(disabledMap.has(String.valueOf(bid)) && disabledMap.getBoolean(String.valueOf(bid))) { return false; } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return true; } private class UnreadRefreshRunnable implements Runnable { @Override public void run() { update_unread(); } } UnreadRefreshRunnable unreadRefreshRunnable = null; private void update_unread() { if(unreadRefreshRunnable != null) { mHandler.removeCallbacks(unreadRefreshRunnable); unreadRefreshRunnable = null; } if(newMsgs > 0) { int minutes = (int)((System.currentTimeMillis() - newMsgTime)/60000); if(minutes < 1) unreadView.setText("Less than a minute of chatter ("); else if(minutes == 1) unreadView.setText("1 minute of chatter ("); else unreadView.setText(minutes + " minutes of chatter ("); if(newMsgs == 1) unreadView.setText(unreadView.getText() + "1 message)"); else unreadView.setText(unreadView.getText() + (newMsgs + " messages)")); unreadView.setVisibility(View.VISIBLE); unreadRefreshRunnable = new UnreadRefreshRunnable(); mHandler.postDelayed(unreadRefreshRunnable, 10000); } } private class StatusRefreshRunnable implements Runnable { String status; JsonObject fail_info; public StatusRefreshRunnable(String status, JsonObject fail_info) { this.status = status; this.fail_info = fail_info; } @Override public void run() { update_status(status, fail_info); } } StatusRefreshRunnable statusRefreshRunnable = null; private void update_status(String status, JsonObject fail_info) { if(statusRefreshRunnable != null) { mHandler.removeCallbacks(statusRefreshRunnable); statusRefreshRunnable = null; } if(status.equals("connected_ready")) { statusView.setVisibility(View.GONE); statusView.setText(""); } else if(status.equals("quitting")) { statusView.setVisibility(View.VISIBLE); statusView.setText("Disconnecting"); statusView.setTextColor(getResources().getColor(R.color.dark_blue)); statusView.setBackgroundResource(R.drawable.background_blue); } else if(status.equals("disconnected")) { statusView.setVisibility(View.VISIBLE); statusView.setText("Disconnected"); statusView.setTextColor(getResources().getColor(R.color.dark_blue)); statusView.setBackgroundResource(R.drawable.background_blue); } else if(status.equals("queued")) { statusView.setVisibility(View.VISIBLE); statusView.setText("Connection queued"); statusView.setTextColor(getResources().getColor(R.color.dark_blue)); statusView.setBackgroundResource(R.drawable.background_blue); } else if(status.equals("connecting")) { statusView.setVisibility(View.VISIBLE); statusView.setText("Connecting"); statusView.setTextColor(getResources().getColor(R.color.dark_blue)); statusView.setBackgroundResource(R.drawable.background_blue); } else if(status.equals("connected")) { statusView.setVisibility(View.VISIBLE); statusView.setText("Connected"); statusView.setTextColor(getResources().getColor(R.color.dark_blue)); statusView.setBackgroundResource(R.drawable.background_blue); } else if(status.equals("connected_joining")) { statusView.setVisibility(View.VISIBLE); statusView.setText("Connected: Joining Channels"); statusView.setTextColor(getResources().getColor(R.color.dark_blue)); statusView.setBackgroundResource(R.drawable.background_blue); } else if(status.equals("pool_unavailable")) { statusView.setVisibility(View.VISIBLE); statusView.setText("Disconnected: Connection temporarily unavailable"); statusView.setTextColor(getResources().getColor(R.color.status_fail_text)); statusView.setBackgroundResource(R.drawable.status_fail_bg); } else if(status.equals("waiting_to_retry")) { try { statusView.setVisibility(View.VISIBLE); long seconds = (fail_info.get("timestamp").getAsLong() + fail_info.get("retry_timeout").getAsInt()) - System.currentTimeMillis()/1000; statusView.setText("Disconnected: " + fail_info.get("reason").getAsString() + ". Reconnecting in " + seconds + " seconds."); statusView.setTextColor(getResources().getColor(R.color.status_fail_text)); statusView.setBackgroundResource(R.drawable.status_fail_bg); statusRefreshRunnable = new StatusRefreshRunnable(status, fail_info); mHandler.postDelayed(statusRefreshRunnable, 500); } catch (Exception e) { e.printStackTrace(); } } else if(status.equals("ip_retry")) { statusView.setVisibility(View.VISIBLE); statusView.setText("Trying another IP address"); statusView.setTextColor(getResources().getColor(R.color.dark_blue)); statusView.setBackgroundResource(R.drawable.background_blue); } } public void onPause() { super.onPause(); if(statusRefreshRunnable != null) { mHandler.removeCallbacks(statusRefreshRunnable); statusRefreshRunnable = null; } if(conn != null) conn.removeHandler(mHandler); } private final Handler mHandler = new Handler() { IRCCloudJSONObject e; public void handleMessage(Message msg) { switch (msg.what) { case NetworkConnection.EVENT_BACKLOG_END: case NetworkConnection.EVENT_USERINFO: if(refreshTask != null) refreshTask.cancel(true); refreshTask = new RefreshTask(); refreshTask.execute((Void)null); break; case NetworkConnection.EVENT_STATUSCHANGED: try { IRCCloudJSONObject object = (IRCCloudJSONObject)msg.obj; if(object.getInt("cid") == cid) { update_status(object.getString("new_status"), object.getJsonObject("fail_info")); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } break; case NetworkConnection.EVENT_MAKEBUFFER: BuffersDataSource.Buffer buffer = (BuffersDataSource.Buffer)msg.obj; if(bid == -1 && buffer.cid == cid && buffer.name.equalsIgnoreCase(name)) { bid = buffer.bid; if(refreshTask != null) refreshTask.cancel(true); refreshTask = new RefreshTask(); refreshTask.execute((Void)null); } break; case NetworkConnection.EVENT_DELETEBUFFER: if((Integer)msg.obj == bid) { Intent parentActivityIntent = new Intent(getActivity(), MainActivity.class); parentActivityIntent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); getActivity().startActivity(parentActivityIntent); getActivity().finish(); } break; case NetworkConnection.EVENT_USERCHANNELMODE: case NetworkConnection.EVENT_SETIGNORES: e = (IRCCloudJSONObject)msg.obj; if(e.cid() == cid) { if(refreshTask != null) refreshTask.cancel(true); refreshTask = new RefreshTask(); refreshTask.execute((Void)null); } break; case NetworkConnection.EVENT_HEARTBEATECHO: if(adapter != null) { BuffersDataSource.Buffer b = BuffersDataSource.getInstance().getBuffer(bid); if(b != null && last_seen_eid != b.last_seen_eid) { last_seen_eid = b.last_seen_eid; if(last_seen_eid == adapter.data.get(adapter.data.size() - 1).eid || !shouldTrackUnread()) { unreadTopView.setVisibility(View.GONE); } } } break; case NetworkConnection.EVENT_CHANNELTOPIC: case NetworkConnection.EVENT_JOIN: case NetworkConnection.EVENT_PART: case NetworkConnection.EVENT_NICKCHANGE: case NetworkConnection.EVENT_QUIT: case NetworkConnection.EVENT_KICK: case NetworkConnection.EVENT_CHANNELMODE: case NetworkConnection.EVENT_SELFDETAILS: case NetworkConnection.EVENT_USERMODE: e = (IRCCloudJSONObject)msg.obj; if(e.bid() == bid) { EventsDataSource.Event event = EventsDataSource.getInstance().getEvent(e.eid(), e.bid()); insertEvent(event, false, false); } break; case NetworkConnection.EVENT_BUFFERMSG: EventsDataSource.Event event = (EventsDataSource.Event)msg.obj; if(event.bid == bid) { insertEvent(event, false, false); } break; default: break; } } }; public interface MessageViewListener { public void onMessageViewReady(); } }
Fix a bug where the date line could cause a blank collapsed row
src/com/irccloud/android/MessageViewFragment.java
Fix a bug where the date line could cause a blank collapsed row
<ide><path>rc/com/irccloud/android/MessageViewFragment.java <ide> long start = System.currentTimeMillis(); <ide> Iterator<EventsDataSource.Event> i = events.values().iterator(); <ide> EventsDataSource.Event next = i.next(); <add> Calendar calendar = Calendar.getInstance(); <ide> while(next != null) { <ide> EventsDataSource.Event e = next; <ide> next = i.hasNext()?i.next():null; <ide> String type = (next == null)?"":next.type; <del> if(next != null && currentCollapsedEid != -1 && !expandedSectionEids.contains(currentCollapsedEid) && (type.equalsIgnoreCase("joined_channel") || type.equalsIgnoreCase("parted_channel") || type.equalsIgnoreCase("nickchange") || type.equalsIgnoreCase("quit") || type.equalsIgnoreCase("user_channel_mode"))) <del> insertEvent(e, true, true); <del> else <add> <add> if(next != null && currentCollapsedEid != -1 && !expandedSectionEids.contains(currentCollapsedEid) && (type.equalsIgnoreCase("joined_channel") || type.equalsIgnoreCase("parted_channel") || type.equalsIgnoreCase("nickchange") || type.equalsIgnoreCase("quit") || type.equalsIgnoreCase("user_channel_mode"))) { <add> calendar.setTimeInMillis(next.eid / 1000); <add> insertEvent(e, true, calendar.get(Calendar.DAY_OF_YEAR) == lastCollapsedDay); <add> } else { <ide> insertEvent(e, true, false); <add> } <ide> } <ide> if(adapter.getLastSeenEIDPosition() == -1) <ide> adapter.insertLastSeenEIDMarker();
JavaScript
mit
3e6c8f47343ccd9325d92922af8426d79e4882c5
0
williammalone/BlocksJS,williammalone/BlocksJS,sojs/BlocksJS,sojs/BlocksJS
/* Copyright (c) 2013 William Malone (www.williammalone.com) 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. */ /*global window, document, navigator */ var BLOCKS; if (BLOCKS === undefined) { BLOCKS = {}; } BLOCKS.audio = {}; BLOCKS.audio.soundInstance = function (player) { "use strict"; var inst = {}; inst.stop = player.stopSoundInstance(inst); inst.play = player.playSoundInstance(inst); inst.getSoundGain = player.getSoundInstanceGain(); return inst; }; BLOCKS.audio.audioElementPlayer = function (spec) { "use strict"; var speaker = BLOCKS.eventDispatcher(), spriteSrc, curSoundInst, initialized = false, loadStarted = false, loadComplete = false, ready = false, loadPercentage = 0, prevLoadPercentage, audioElement, loadInterval, soundCompleteTimer, sounds = {}, muted = false, maybeReady = false, resetGainValue, pausedFirstTime, testSoundComplete = function () { if (!ready) { ready = true; if (speaker.debug) { BLOCKS.debug("audio ready"); } speaker.dispatchEvent("ready"); } }, setReady = function () { if (!maybeReady) { maybeReady = true; speaker.createSound({ name: "BlocksTestSound", start: 0, end: 0.5 }); playSound("BlocksTestSound", testSoundComplete); window.setTimeout(function () { if (!ready) { playSound("BlocksTestSound", testSoundComplete); window.setTimeout(function () { if (!ready) { testSoundComplete(); } }, 10000); } }, 10000); } }, onCanPlayThrough = function () { setReady(); }, load = function () { if (!audioElement) { return; } if (speaker.debug) { BLOCKS.debug("load audio sprite: " + spriteSrc); } if (loadInterval) { window.clearInterval(loadInterval); } loadInterval = window.setInterval(function () { var loadTime, loadPercentage; //if (speaker.debug) { // BLOCKS.debug("audioElement.buffered.length: " + audioElement.buffered.length); //} if (!audioElement.buffered.length) { return; } loadTime = audioElement.buffered.end(audioElement.buffered.length - 1); loadPercentage = loadTime / audioElement.duration * 100; if (!isNaN(loadPercentage) && prevLoadPercentage !== loadPercentage) { prevLoadPercentage = loadPercentage; speaker.dispatchEvent("loadUpdate"); if (speaker.debug) { BLOCKS.debug("loadUpdate: " + Math.round(loadPercentage) + "%"); } if (!pausedFirstTime) { pausedFirstTime = true; audioElement.pause(); } } if (window.Math.abs(loadTime - audioElement.duration) < 0.1) { window.clearInterval(loadInterval); setReady(); speaker.dispatchEvent("loadComplete"); if (speaker.debug) { BLOCKS.debug("loadComplete"); } } }, 100); audioElement.play(); }, endSound = function () { // Clear the sound complete timer window.clearInterval(soundCompleteTimer); soundCompleteTimer = null; //if (audioElement) { audioElement.pause(); //} }, stop = function () { endSound(); curSoundInst = null; }, soundCompleteChecker = function () { var inst; // If a sound is playing if (curSoundInst) { // If the scrubber is past the sound end time then the sound is complete if (audioElement.currentTime >= curSoundInst.end) { // If the sound is set to loop then move the scrubber to the beginning of the sound if (curSoundInst.loop === true) { audioElement.currentTime = curSoundInst.start; } else { endSound(); speaker.dispatchEvent("played"); inst = curSoundInst; curSoundInst = null; if (inst.callback) { inst.callback(inst.name); } } } } else { window.clearInterval(soundCompleteTimer); } }, playSound = function (name, callback) { if (speaker.debug) { BLOCKS.debug("Play sound: " + name + " (" + sounds[name].start + " - " + sounds[name].end + ")"); } if (sounds[name].start >= 0 && sounds[name].end > 0) { // If the previous sound had a different volume set temporarily if (resetGainValue >= 0) { audioElement.volume = resetGainValue; resetGainValue = null; } // Save the sound about to play curSoundInst = { name: sounds[name].name, start: sounds[name].start, end: sounds[name].end, loop: sounds[name].loop, sound: sounds[name].sound, callback: callback }; // Move the scrubber to the start of the sound audioElement.currentTime = sounds[name].start; // Play the sound audioElement.play(); // Start a listener to check if the sound is complete if (soundCompleteTimer) { window.clearInterval(soundCompleteTimer); } soundCompleteTimer = window.setInterval(soundCompleteChecker, 100); return true; } else { BLOCKS.warn("Sound parameters not specified."); return false; } }, // Pause the audio element pause = function () { audioElement.pause(); }, // Play the audio element if a sound is currently playing unpause = function () { if (curSoundInst) { audioElement.play(); } }, // Mute all sound mute = function () { audioElement.volume = 0; }, // Unmute all sound unmute = function () { audioElement.volume = 1; }; speaker.setSoundGain = function (name, gain) { if (curSoundInst && curSoundInst.name === name) { // Save the current volume to be reset for next sound resetGainValue = audioElement.volume; audioElement.volume = gain; } }; speaker.play = function (name, callback) { if (sounds[name]) { return playSound(name, callback); } else { BLOCKS.warn("Cannot play sound '" + name + "' because it was not defined"); } }; // Pause the audio element speaker.pause = function () { pause(); }; // Unpause the audio element speaker.unpause = function () { unpause(); }; // Pause the audio element and clear the current sound speaker.stop = function () { stop(); }; // Mute all sound speaker.mute = function () { if (!muted) { mute(); } muted = true; }; // Unmute all sound speaker.unmute = function () { if (muted) { unmute(); } muted = false; }; speaker.isMuted = function () { return muted; }; // Return if audio is ready to be played speaker.isReady = function () { return true; }; speaker.load = function () { if (!loadStarted) { loadStarted = true; load(); } }; speaker.createSound = function (spec) { sounds[spec.name] = { name: spec.name, start: spec.start, end: spec.end, loop: spec.loop }; }; speaker.getActiveSounds = function () { return [curSoundInst]; }; speaker.getNumFiles = function () { return 1; }; speaker.getNumFilesLoaded = function () { return ready ? 1 : 0; }; // Create audio element (function () { if (spec && spec.src) { // Add audio path if (spec.path) { spriteSrc = spec.path; } else { spriteSrc = ""; } // Add the sprite filename without extension spriteSrc += spec.src; audioElement = document.createElement("audio"); audioElement.addEventListener("canplaythrough", onCanPlayThrough); // Add the extension if (audioElement.canPlayType("audio/mpeg")) { spriteSrc += ".mp3"; } else if (audioElement.canPlayType("audio/ogg")) { spriteSrc += ".ogg"; } audioElement.src = spriteSrc; } else { BLOCKS.error("sprite filename not specified"); } }()); return speaker; }; BLOCKS.audio.webAudioPlayer = function (spec) { "use strict"; var speaker = BLOCKS.eventDispatcher(), initialized = false, loadStarted = false, loadComplete = false, ready = false, muted = false, extension, path = (spec && spec.path) || "", masterGain, ctx, sounds = {}, files = {}, instances = [], tracks = {}, loadTimeoutId, maxLoadTime = spec.maxLoadTime || 60000, // The maximum amount of time for all sounds to load loadTries = 0, maxLoadTries = 5, createTrack = function (name) { if (!tracks[name]) { tracks[name] = { name: name, gain: (ctx.createGain) ? ctx.createGain() : ctx.createGainNode() }; // Connect the track's gain node to the master node tracks[name].gain.connect(masterGain); } return tracks[name]; }, onFileLoaded = function (file) { var key, numFilesLoaded, totalNumFiles; numFilesLoaded = speaker.getNumFilesLoaded(); totalNumFiles = speaker.getNumFiles(); if (speaker.debug) { BLOCKS.debug("load: " + numFilesLoaded + " of " + totalNumFiles); } //BLOCKS.debug("load: " + numFilesLoaded + " of " + totalNumFiles + " (" + file.src + ")"); speaker.dispatchEvent("update", numFilesLoaded, totalNumFiles); if (numFilesLoaded === totalNumFiles) { if (!ready) { ready = true; // Clear the load timeout window.clearTimeout(loadTimeoutId); if (speaker.debug) { BLOCKS.debug("audio ready"); } //BLOCKS.debug("speaker is ready"); speaker.dispatchEvent("ready"); } } }, loadFile = function (file) { file.request = new window.XMLHttpRequest(); // For Internet Explorer if (!("withCredentials" in file.request)) { file.request = new window.XDomainRequest(); } file.request.open("get", path + file.src + extension, true); file.request.responseType = "arraybuffer"; file.request.onload = function() { //BLOCKS.debug("Sound Loaded: " + (path + file.src + extension) + " -> " + file.request); ctx.decodeAudioData(file.request.response, function(buffer) { //BLOCKS.debug("Sound Decoded: " + (path + file.src + extension) + " -> " + file.request); file.buffer = buffer; file.loaded = true; // TODO: Dispatch an notification that the file has been loaded for the first time, in case we want to play it after its loaded // TODO: Update the progress if we are waiting for pre-load onFileLoaded(file); file.request = null; }, function (error) { if (BLOCKS.debug) { BLOCKS.debug("Error decoding buffer: " + path + file.src + extension); } file.request = null; }); }; file.request.send(); }, load = function () { var source; loadStarted = true; source = ctx.createOscillator(); if (source.start) { source.start(0, 0, 1); } else if (source.noteGrainOn) { source.noteGrainOn(0, 0, 1); } }, destroyInstance = function (inst) { var i, index; for (i = 0; i < instances.length; i += 1) { if (instances[i] === inst) { instances[i] = null; index = i; break; } } instances.splice(index, 1); }, soundCompleteChecker = function (inst) { var callback, soundName; if (speaker.debug) { BLOCKS.debug("Sound '" + inst.sound.name + "' Complete"); } if (inst.callback) { callback = inst.callback; soundName = inst.name; } // Destroy the instance before calling a possible callback destroyInstance(inst); if (callback) { callback(soundName); } }, stopSound = function (inst) { window.clearTimeout(inst.timeout); if (inst.source.stop) { inst.source.stop(0); } else if (inst.source.noteGrainOff) { inst.source.noteGrainOff(0); } else { inst.source.noteOff(0); } destroyInstance(inst); }, getSoundGain = function (inst) { return inst.gain.gain.value; }, setSoundGain = function (inst, gainValue, delay) { // If the sound doesn't have its own gain then create its own gain we can change if (inst.gain === inst.track.gain) { // Disconnect the source from its track gain node inst.source.disconnect(0); // Create a new gain inst.gain = (ctx.createGain) ? ctx.createGain() : ctx.createGainNode(); inst.gain.connect(masterGain); // Connect the source to the new gain inst.source.connect(inst.gain); } if (speaker.debug) { BLOCKS.debug("speaker.setSoundGain of sound '" + inst.name + "' to '" + gainValue + "'"); } // If the gain should be faded out if (delay) { inst.gain.gain.linearRampToValueAtTime(inst.gain.gain.value, ctx.currentTime); inst.gain.gain.linearRampToValueAtTime(gainValue, ctx.currentTime + delay); } else { inst.gain.gain.value = gainValue; } }, pauseSound = function (inst) { window.clearTimeout(inst.timeout); inst.currentTime = ((+ new Date()) - inst.startTime) / 1000 % inst.source.buffer.duration; if (inst.source.stop) { inst.source.stop(0); } else if (inst.source.noteGrainOff) { inst.source.noteGrainOff(0); } else { inst.source.noteOff(0); } //if (speaker.debug) { // BLOCKS.debug("Pause sound: '" + inst.name + "' at scrubber position of " + inst.currentTime.toFixed(2)); //} }, unpauseSound = function (inst) { var newInst; //if (speaker.debug) { // BLOCKS.debug("Unpause sound: '" + inst.name + "'"); //} // Play a new instance of the sound newInst = playSound(inst.name, inst.callback, inst.track.name, inst.currentTime); if (inst.gain.gain.value !== 1) { setSoundGain(newInst, inst.gain.gain.value); } // Delete the old instance destroyInstance(inst); }, playSound = function (name, callback, trackName, currentTime, delay) { var inst = {}; if (sounds[name].file.loaded) { instances.push(inst); inst.sound = sounds[name]; inst.name = name; // If an offset is set (set when unpausing a sound) if (currentTime) { inst.currentTime = currentTime; } else { // Start from the beginning of the sound inst.currentTime = 0; } // Save when the sound starts, or would have started if started from the beginning inst.startTime = (+ new Date()) - inst.currentTime * 1000; if (delay) { // Play the sound after a delay inst.delay = ctx.currentTime + delay; } else { // Play the sound immediately delay = 0; inst.delay = 0; } if (trackName) { if (!tracks[trackName]) { createTrack(trackName); } inst.track = tracks[trackName]; } else { inst.track = tracks["default"]; } // Create a new source for this sound instance inst.source = ctx.createBufferSource(); inst.source.buffer = sounds[name].file.buffer; inst.source.loop = sounds[name].loop; inst.gain = inst.track.gain; // Connect the source to the gains inst.source.connect(inst.gain); if (!sounds[name].loop) { // Timeout at the end of the sound inst.timeout = window.setTimeout(soundCompleteChecker, (delay + inst.source.buffer.duration - inst.currentTime) * 1000, inst); // Assign a callback to be called once the sound is complete inst.callback = callback; } if (speaker.debug) { if (inst.currentTime) { BLOCKS.debug("Play sound: " + name + " (" + inst.currentTime + " - " + sounds[name].end + "), src: " + sounds[name].file.src + extension); } else { BLOCKS.debug("Play sound: " + name + " (" + sounds[name].start + " - " + sounds[name].end + "), src: " + sounds[name].file.src + extension); } } // Play the sound if (inst.source.start) { // If an offset is specified then add the start time and duration parameters if (inst.currentTime) { inst.source.start(inst.delay, inst.currentTime, inst.source.buffer.duration - inst.currentTime); } else { inst.source.start(inst.delay); } } else if (inst.source.noteGrainOn) { inst.source.noteGrainOn(inst.delay, inst.currentTime, inst.source.buffer.duration - inst.currentTime); } return inst; } else { // TODO: Play the unloaded sound once its loaded //if (speaker.debug) { BLOCKS.warn("Tried to play sound: " + name + ", but it is not loaded yet"); //} } }, createLoadTimer = function () { loadTimeoutId = window.setTimeout(function () { var key; for (key in files) { if (files.hasOwnProperty(key)) { if (!files[key].loaded) { // Cancel the request if (files[key].request) { BLOCKS.warn("Sound file load has timed out. Aborting request and trying again: " + files[key].src); files[key].request.abort(); } else { BLOCKS.warn("Sound file load has timed out. Sending additional request: " + files[key].src); } loadFile(files[key]); } } } loadTries += 1; if (loadTries < maxLoadTries) { createLoadTimer(); } }, maxLoadTime); }; speaker.play = function (name, callback, trackName, startTime, delay) { if (sounds[name]) { return playSound(name, callback, trackName, startTime, delay); } else { BLOCKS.warn("Cannot play sound '" + name + "' because it was not defined"); } }; speaker.getSoundDuration = function (name) { return sounds[name].file.buffer.duration; }; speaker.getSoundInstanceGain = function (inst) { return getSoundGain(inst); }; speaker.getSoundGain = function (name) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { return getSoundGain(instanceArr[i]); } } }; speaker.setSoundInstanceGain = function (inst, gainValue, delay) { setSoundGain(inst, gainValue, delay); }; speaker.setSoundGain = function (name, gainValue, delay) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { setSoundGain(instanceArr[i], gainValue, delay); } } }; speaker.stopSound = function (name) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { stopSound(instanceArr[i]); } } }; speaker.pauseSound = function (name) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { pauseSound(instanceArr[i]); } } }; speaker.unpauseSound = function (name) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { unpauseSound(instanceArr[i]); } } }; speaker.stopTrack = function (trackName) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].track.name === trackName) { stopSound(instanceArr[i]); } } }; speaker.pauseTrack = function (trackName) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].track.name === trackName) { pauseSound(instanceArr[i]); } } }; speaker.unpauseTrack = function (trackName) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].track.name === trackName) { unpauseSound(instanceArr[i]); } } }; // Stop all sounds speaker.stop = function () { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { stopSound(instanceArr[i]); } }; // Pause all sounds speaker.pause = function () { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { pauseSound(instanceArr[i]); } }; // Unpause any paused sounds speaker.unpause = function () { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { unpauseSound(instanceArr[i]); } }; // Mute all sound speaker.mute = function () { if (!muted) { muted = true; masterGain.gain.value = 0; } }; // Unmute all sound speaker.unmute = function () { if (muted) { muted = false; masterGain.gain.value = 1; } }; speaker.isMuted = function () { return muted; }; // Load the audio element speaker.load = function () { if (!loadStarted) { loadStarted = true; createLoadTimer(); load(); } }; // Return if audio is ready to be played speaker.isReady = function () { return ready; }; speaker.createSound = function (spec) { sounds[spec.name] = { name: spec.name, start: spec.start, end: spec.end, loop: spec.loop }; //BLOCKS.debug("Create Sound: " + spec.name); if (!files[spec.src]) { files[spec.src] = { src: spec.src }; loadFile(files[spec.src]); //BLOCKS.debug("Load Sound: " + spec.src); } sounds[spec.name].file = files[spec.src]; }; speaker.getActiveSoundInstances = function () { return instances; }; speaker.getNumFiles = function () { var key, totalNumFiles; totalNumFiles = 0; // Determine load progress for (key in files) { if (files.hasOwnProperty(key)) { totalNumFiles += 1; } } return totalNumFiles; }; speaker.getNumFilesLoaded = function () { var key, numFilesLoaded; numFilesLoaded = 0; // Determine load progress for (key in files) { if (files.hasOwnProperty(key)) { if (files[key].loaded) { numFilesLoaded += 1; } } } return numFilesLoaded; }; speaker.getCurrentTime = function () { return ctx.currentTime; }; speaker.multipleTracksSupported = true; (function () { var tmpAudioElement = document.createElement("audio"), fireFoxDetected; // Use ogg for Firefox due to a bud decoding buffer data fireFoxDetected = (navigator.userAgent.toLowerCase().indexOf('firefox') > -1); if (tmpAudioElement.canPlayType("audio/mpeg;").replace(/no/, "") && !!(tmpAudioElement.canPlayType) && !fireFoxDetected) { extension = ".mp3"; } else { extension = ".ogg"; } if (typeof AudioContext !== "undefined") { ctx = new window.AudioContext(); } else if (typeof webkitAudioContext !== "undefined") { ctx = new window.webkitAudioContext(); } if (ctx) { // Create the master gain node masterGain = (ctx.createGain) ? ctx.createGain() : ctx.createGainNode(); // Connext the master gain node to the context's output masterGain.connect(ctx.destination); } else { BLOCKS.error("Cannot create audio context."); } createTrack("default"); }()); return speaker; }; BLOCKS.audio.multiAudioElementPlayer = function (spec) { "use strict"; var speaker = BLOCKS.eventDispatcher(), initialized = false, loadStarted = false, loadComplete = false, ready = false, muted = false, extension, path = (spec && spec.path) || "", masterGain, ctx, sounds = {}, files = {}, instances = [], tracks = {}, loadTimeoutId, maxLoadTime = spec.maxLoadTime || 60000, // The maximum amount of time for all sounds to load loadTries = 0, maxLoadTries = 5, createTrack = function (name) { if (!tracks[name]) { tracks[name] = { name: name, gain: (ctx.createGain) ? ctx.createGain() : ctx.createGainNode() }; // Connect the track's gain node to the master node tracks[name].gain.connect(masterGain); } return tracks[name]; }, onFileLoaded = function (file) { var key, numFilesLoaded, totalNumFiles; numFilesLoaded = speaker.getNumFilesLoaded(); totalNumFiles = speaker.getNumFiles(); if (speaker.debug) { BLOCKS.debug("load: " + numFilesLoaded + " of " + totalNumFiles); } speaker.dispatchEvent("update", numFilesLoaded, totalNumFiles); if (numFilesLoaded === totalNumFiles) { if (!ready) { ready = true; // Clear the load timeout window.clearTimeout(loadTimeoutId); if (speaker.debug) { BLOCKS.debug("audio ready"); } speaker.dispatchEvent("ready"); } } }, loadFile = function (file) { file.audioElement = document.createElement("audio"); file.audioElement.preload = true; file.audioElement.src = (path + file.src + extension); file.audioElement.load(); file.audioElement.addEventListener("canplaythrough", function () { BLOCKS.debug("Audio element loaded: " + (path + file.src + extension)); file.loaded = true; onFileLoaded(file); }); //document.body.appendChild(file.audioElement); }, load = function () { /* var source; loadStarted = true; source = ctx.createOscillator(); if (source.start) { source.start(0, 0, 1); } else if (source.noteGrainOn) { source.noteGrainOn(0, 0, 1); } */ }, destroyInstance = function (inst) { var i, index; for (i = 0; i < instances.length; i += 1) { if (instances[i] === inst) { instances[i] = null; index = i; break; } } instances.splice(index, 1); }, soundCompleteChecker = function (inst) { var callback, soundName; if (speaker.debug) { BLOCKS.debug("Sound '" + inst.sound.name + "' Complete"); } if (inst.callback) { callback = inst.callback; soundName = inst.name; } // Destroy the instance before calling a possible callback destroyInstance(inst); if (callback) { callback(soundName); } }, stopSound = function (inst) { if (inst.timeout) { window.clearTimeout(inst.timeout); } if (inst.fadeTimeout) { window.clearTimeout(inst.fadeTimeout); } /* if (inst.source.stop) { inst.source.stop(0); } else if (inst.source.noteGrainOff) { inst.source.noteGrainOff(0); } else { inst.source.noteOff(0); } */ inst.sound.file.audioElement.pause(); destroyInstance(inst); }, getSoundGain = function (inst) { return inst.gain.gain.value; }, setSoundGain = function (inst, gainValue, delay) { var fadeInterval = 10; // Clear previous fade if it's still going if (inst.fadeTimeout) { inst.sound.file.audioElement.volume = inst.fadeTarget; window.clearInterval(inst.fadeTimeout); inst.fadeTarget = 0; inst.fadeAmount = 0; } if (delay) { // Create timer to fade the gain over time inst.fadeTarget = gainValue; inst.fadeAmount = (gainValue - inst.sound.file.audioElement.volume) / ((delay * 1000) / fadeInterval); inst.fadeTimeout = window.setInterval(function () { if (inst.sound.file.audioElement.volume === inst.fadeTarget) { window.clearInterval(inst.fadeTimeout); } inst.sound.file.audioElement.volume += inst.fadeAmount; }, fadeInterval); } else { inst.sound.file.audioElement.volume = gainValue; } }, pauseSound = function (inst) { window.clearTimeout(inst.timeout); inst.currentTime = ((+ new Date()) - inst.startTime) / 1000 % inst.sound.file.audioElement.duration; inst.sound.file.audioElement.pause(); }, unpauseSound = function (inst) { var newInst; //if (speaker.debug) { // BLOCKS.debug("Unpause sound: '" + inst.name + "'"); //} newInst = playSound(inst.name, inst.callback, null, inst.currentTime); // Delete the old instance destroyInstance(inst); }, playSound = function (name, callback, trackName, currentTime, delay) { var inst = {}; if (sounds[name].file.loaded) { instances.push(inst); inst.sound = sounds[name]; inst.name = name; // If an offset is set (set when unpausing a sound) if (currentTime) { inst.currentTime = currentTime; } else { // Start from the beginning of the sound inst.currentTime = 0; } // Save when the sound starts, or would have started if started from the beginning inst.startTime = (+ new Date()) - inst.currentTime * 1000; if (delay) { // Play the sound after a delay inst.delay = ctx.currentTime + delay; } else { // Play the sound immediately delay = 0; inst.delay = 0; } if (trackName) { if (!tracks[trackName]) { createTrack(trackName); } inst.track = tracks[trackName]; } else { inst.track = tracks["default"]; } // Create a new source for this sound instance //inst.source = ctx.createBufferSource(); //inst.source.buffer = sounds[name].file.buffer; //inst.source.loop = sounds[name].loop; //inst.gain = inst.track.gain; // Connect the source to the gains //inst.source.connect(inst.gain); if (!sounds[name].loop) { // Timeout at the end of the sound //inst.timeout = window.setTimeout(soundCompleteChecker, (delay + inst.source.buffer.duration - inst.currentTime) * 1000, inst); // Assign a callback to be called once the sound is complete inst.callback = callback; } else { inst.sound.file.audioElement.loop = true; } if (speaker.debug) { if (inst.currentTime) { BLOCKS.debug("Play sound: " + name + " (" + inst.currentTime + " - " + sounds[name].end + "), src: " + sounds[name].file.src + extension); } else { BLOCKS.debug("Play sound: " + name + " (" + sounds[name].start + " - " + sounds[name].end + "), src: " + sounds[name].file.src + extension); } } inst.sound.file.audioElement.currentTime = inst.currentTime; inst.sound.file.audioElement.play(); /* // Play the sound if (inst.source.start) { // If an offset is specified then add the start time and duration parameters if (inst.currentTime) { inst.source.start(inst.delay, inst.currentTime, inst.source.buffer.duration - inst.currentTime); } else { inst.source.start(inst.delay); } } else if (inst.source.noteGrainOn) { inst.source.noteGrainOn(inst.delay, inst.currentTime, inst.source.buffer.duration - inst.currentTime); } */ return inst; } else { // TODO: Play the unloaded sound once its loaded //if (speaker.debug) { BLOCKS.warn("Tried to play sound: " + name + ", but it is not loaded yet"); //} } }, createLoadTimer = function () { loadTimeoutId = window.setTimeout(function () { var key; for (key in files) { if (files.hasOwnProperty(key)) { if (!files[key].loaded) { // Cancel the request if (files[key].request) { BLOCKS.warn("Sound file load has timed out. Aborting request and trying again: " + files[key].src); files[key].request.abort(); } else { BLOCKS.warn("Sound file load has timed out. Sending additional request: " + files[key].src); } loadFile(files[key]); } } } loadTries += 1; if (loadTries < maxLoadTries) { createLoadTimer(); } }, maxLoadTime); }; speaker.play = function (name, callback, trackName, startTime, delay) { if (sounds[name]) { return playSound(name, callback, trackName, startTime, delay); } else { BLOCKS.warn("Cannot play sound '" + name + "' because it was not defined"); } }; speaker.getSoundDuration = function (name) { return sounds[name].file.buffer.duration; }; speaker.getSoundInstanceGain = function (inst) { return getSoundGain(inst); }; speaker.getSoundGain = function (name) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { return getSoundGain(instanceArr[i]); } } }; speaker.setSoundInstanceGain = function (inst, gainValue, delay) { setSoundGain(inst, gainValue, delay); }; speaker.setSoundGain = function (name, gainValue, delay) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { setSoundGain(instanceArr[i], gainValue, delay); } } }; speaker.stopSound = function (name) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { stopSound(instanceArr[i]); } } }; speaker.pauseSound = function (name) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { pauseSound(instanceArr[i]); } } }; speaker.unpauseSound = function (name) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { unpauseSound(instanceArr[i]); } } }; speaker.stopTrack = function (trackName) { //var i, instanceArr = instances.slice(0); // //for (i = 0; i < instanceArr.length; i += 1) { // if (instanceArr[i].track.name === trackName) { // stopSound(instanceArr[i]); // } //} }; speaker.pauseTrack = function (trackName) { //var i, instanceArr = instances.slice(0); // //for (i = 0; i < instanceArr.length; i += 1) { // if (instanceArr[i].track.name === trackName) { // pauseSound(instanceArr[i]); // } //} }; speaker.unpauseTrack = function (trackName) { //var i, instanceArr = instances.slice(0); // //for (i = 0; i < instanceArr.length; i += 1) { // if (instanceArr[i].track.name === trackName) { // unpauseSound(instanceArr[i]); // } //} }; // Stop all sounds speaker.stop = function () { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { stopSound(instanceArr[i]); } }; // Pause all sounds speaker.pause = function () { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { pauseSound(instanceArr[i]); } }; // Unpause any paused sounds speaker.unpause = function () { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { unpauseSound(instanceArr[i]); } }; // Mute all sound speaker.mute = function () { if (!muted) { muted = true; // TODO: mute all sounds } }; // Unmute all sound speaker.unmute = function () { if (muted) { muted = false; // TODO: unmute all sounds } }; speaker.isMuted = function () { return muted; }; // Load the audio element speaker.load = function () { if (!loadStarted) { loadStarted = true; createLoadTimer(); load(); } }; // Return if audio is ready to be played speaker.isReady = function () { return ready; }; speaker.createSound = function (spec) { sounds[spec.name] = { name: spec.name, start: spec.start, end: spec.end, loop: spec.loop }; //BLOCKS.debug("Create Sound: " + spec.name); if (!files[spec.src]) { files[spec.src] = { src: spec.src }; loadFile(files[spec.src]); //BLOCKS.debug("Load Sound: " + spec.src); } sounds[spec.name].file = files[spec.src]; }; speaker.getActiveSoundInstances = function () { return instances; }; speaker.getNumFiles = function () { var key, totalNumFiles; totalNumFiles = 0; // Determine load progress for (key in files) { if (files.hasOwnProperty(key)) { totalNumFiles += 1; } } return totalNumFiles; }; speaker.getNumFilesLoaded = function () { var key, numFilesLoaded; numFilesLoaded = 0; // Determine load progress for (key in files) { if (files.hasOwnProperty(key)) { if (files[key].loaded) { numFilesLoaded += 1; } } } return numFilesLoaded; }; speaker.getCurrentTime = function () { // Since multiple sounds could be playing this returns nothing return null; }; speaker.multipleTracksSupported = true; (function () { extension = ".mp3"; }()); return speaker; }; BLOCKS.speaker = function (spec) { "use strict"; var speaker; // Create audio element (function () { if (!spec) { spec = {}; } if (spec.audioPlayerType === "multiAudioElementPlayer") { speaker = BLOCKS.audio.multiAudioElementPlayer(spec); } else if ((typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') && spec.webAudioEnabled !== false) { speaker = BLOCKS.audio.webAudioPlayer(spec); } else { speaker = BLOCKS.audio.audioElementPlayer(spec); } }()); speaker.debug = false; return speaker; };
src/js/speaker.js
/* Copyright (c) 2013 William Malone (www.williammalone.com) 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. */ /*global window, document, navigator */ var BLOCKS; if (BLOCKS === undefined) { BLOCKS = {}; } BLOCKS.audio = {}; BLOCKS.audio.soundInstance = function (player) { "use strict"; var inst = {}; inst.stop = player.stopSoundInstance(inst); inst.play = player.playSoundInstance(inst); inst.getSoundGain = player.getSoundInstanceGain(); return inst; }; BLOCKS.audio.audioElementPlayer = function (spec) { "use strict"; var speaker = BLOCKS.eventDispatcher(), spriteSrc, curSoundInst, initialized = false, loadStarted = false, loadComplete = false, ready = false, loadPercentage = 0, prevLoadPercentage, audioElement, loadInterval, soundCompleteTimer, sounds = {}, muted = false, maybeReady = false, resetGainValue, pausedFirstTime, testSoundComplete = function () { if (!ready) { ready = true; if (speaker.debug) { BLOCKS.debug("audio ready"); } speaker.dispatchEvent("ready"); } }, setReady = function () { if (!maybeReady) { maybeReady = true; speaker.createSound({ name: "BlocksTestSound", start: 0, end: 0.5 }); playSound("BlocksTestSound", testSoundComplete); window.setTimeout(function () { if (!ready) { playSound("BlocksTestSound", testSoundComplete); window.setTimeout(function () { if (!ready) { testSoundComplete(); } }, 10000); } }, 10000); } }, onCanPlayThrough = function () { setReady(); }, load = function () { if (!audioElement) { return; } if (speaker.debug) { BLOCKS.debug("load audio sprite: " + spriteSrc); } if (loadInterval) { window.clearInterval(loadInterval); } loadInterval = window.setInterval(function () { var loadTime, loadPercentage; //if (speaker.debug) { // BLOCKS.debug("audioElement.buffered.length: " + audioElement.buffered.length); //} if (!audioElement.buffered.length) { return; } loadTime = audioElement.buffered.end(audioElement.buffered.length - 1); loadPercentage = loadTime / audioElement.duration * 100; if (!isNaN(loadPercentage) && prevLoadPercentage !== loadPercentage) { prevLoadPercentage = loadPercentage; speaker.dispatchEvent("loadUpdate"); if (speaker.debug) { BLOCKS.debug("loadUpdate: " + Math.round(loadPercentage) + "%"); } if (!pausedFirstTime) { pausedFirstTime = true; audioElement.pause(); } } if (window.Math.abs(loadTime - audioElement.duration) < 0.1) { window.clearInterval(loadInterval); setReady(); speaker.dispatchEvent("loadComplete"); if (speaker.debug) { BLOCKS.debug("loadComplete"); } } }, 100); audioElement.play(); }, endSound = function () { // Clear the sound complete timer window.clearInterval(soundCompleteTimer); soundCompleteTimer = null; //if (audioElement) { audioElement.pause(); //} }, stop = function () { endSound(); curSoundInst = null; }, soundCompleteChecker = function () { var inst; // If a sound is playing if (curSoundInst) { // If the scrubber is past the sound end time then the sound is complete if (audioElement.currentTime >= curSoundInst.end) { // If the sound is set to loop then move the scrubber to the beginning of the sound if (curSoundInst.loop === true) { audioElement.currentTime = curSoundInst.start; } else { endSound(); speaker.dispatchEvent("played"); inst = curSoundInst; curSoundInst = null; if (inst.callback) { inst.callback(inst.name); } } } } else { window.clearInterval(soundCompleteTimer); } }, playSound = function (name, callback) { if (speaker.debug) { BLOCKS.debug("Play sound: " + name + " (" + sounds[name].start + " - " + sounds[name].end + ")"); } if (sounds[name].start >= 0 && sounds[name].end > 0) { // If the previous sound had a different volume set temporarily if (resetGainValue >= 0) { audioElement.volume = resetGainValue; resetGainValue = null; } // Save the sound about to play curSoundInst = { name: sounds[name].name, start: sounds[name].start, end: sounds[name].end, loop: sounds[name].loop, sound: sounds[name].sound, callback: callback }; // Move the scrubber to the start of the sound audioElement.currentTime = sounds[name].start; // Play the sound audioElement.play(); // Start a listener to check if the sound is complete if (soundCompleteTimer) { window.clearInterval(soundCompleteTimer); } soundCompleteTimer = window.setInterval(soundCompleteChecker, 100); return true; } else { BLOCKS.warn("Sound parameters not specified."); return false; } }, // Pause the audio element pause = function () { audioElement.pause(); }, // Play the audio element if a sound is currently playing unpause = function () { if (curSoundInst) { audioElement.play(); } }, // Mute all sound mute = function () { audioElement.volume = 0; }, // Unmute all sound unmute = function () { audioElement.volume = 1; }; speaker.setSoundGain = function (name, gain) { if (curSoundInst && curSoundInst.name === name) { // Save the current volume to be reset for next sound resetGainValue = audioElement.volume; audioElement.volume = gain; } }; speaker.play = function (name, callback) { if (sounds[name]) { return playSound(name, callback); } else { BLOCKS.warn("Cannot play sound '" + name + "' because it was not defined"); } }; // Pause the audio element speaker.pause = function () { pause(); }; // Unpause the audio element speaker.unpause = function () { unpause(); }; // Pause the audio element and clear the current sound speaker.stop = function () { stop(); }; // Mute all sound speaker.mute = function () { if (!muted) { mute(); } muted = true; }; // Unmute all sound speaker.unmute = function () { if (muted) { unmute(); } muted = false; }; speaker.isMuted = function () { return muted; }; // Return if audio is ready to be played speaker.isReady = function () { return true; }; speaker.load = function () { if (!loadStarted) { loadStarted = true; load(); } }; speaker.createSound = function (spec) { sounds[spec.name] = { name: spec.name, start: spec.start, end: spec.end, loop: spec.loop }; }; speaker.getActiveSounds = function () { return [curSoundInst]; }; speaker.getNumFiles = function () { return 1; }; speaker.getNumFilesLoaded = function () { return ready ? 1 : 0; }; // Create audio element (function () { if (spec && spec.src) { // Add audio path if (spec.path) { spriteSrc = spec.path; } else { spriteSrc = ""; } // Add the sprite filename without extension spriteSrc += spec.src; audioElement = document.createElement("audio"); audioElement.addEventListener("canplaythrough", onCanPlayThrough); // Add the extension if (audioElement.canPlayType("audio/mpeg")) { spriteSrc += ".mp3"; } else if (audioElement.canPlayType("audio/ogg")) { spriteSrc += ".ogg"; } audioElement.src = spriteSrc; } else { BLOCKS.error("sprite filename not specified"); } }()); return speaker; }; BLOCKS.audio.webAudioPlayer = function (spec) { "use strict"; var speaker = BLOCKS.eventDispatcher(), initialized = false, loadStarted = false, loadComplete = false, ready = false, muted = false, extension, path = (spec && spec.path) || "", masterGain, ctx, sounds = {}, files = {}, instances = [], tracks = {}, loadTimeoutId, maxLoadTime = spec.maxLoadTime || 60000, // The maximum amount of time for all sounds to load loadTries = 0, maxLoadTries = 5, createTrack = function (name) { if (!tracks[name]) { tracks[name] = { name: name, gain: (ctx.createGain) ? ctx.createGain() : ctx.createGainNode() }; // Connect the track's gain node to the master node tracks[name].gain.connect(masterGain); } return tracks[name]; }, onFileLoaded = function (file) { var key, numFilesLoaded, totalNumFiles; numFilesLoaded = speaker.getNumFilesLoaded(); totalNumFiles = speaker.getNumFiles(); if (speaker.debug) { BLOCKS.debug("load: " + numFilesLoaded + " of " + totalNumFiles); } //BLOCKS.debug("load: " + numFilesLoaded + " of " + totalNumFiles + " (" + file.src + ")"); speaker.dispatchEvent("update", numFilesLoaded, totalNumFiles); if (numFilesLoaded === totalNumFiles) { if (!ready) { ready = true; // Clear the load timeout window.clearTimeout(loadTimeoutId); if (speaker.debug) { BLOCKS.debug("audio ready"); } //BLOCKS.debug("speaker is ready"); speaker.dispatchEvent("ready"); } } }, loadFile = function (file) { file.request = new window.XMLHttpRequest(); // For Internet Explorer if (!("withCredentials" in file.request)) { file.request = new window.XDomainRequest(); } file.request.open("get", path + file.src + extension, true); file.request.responseType = "arraybuffer"; file.request.onload = function() { //BLOCKS.debug("Sound Loaded: " + (path + file.src + extension) + " -> " + file.request); ctx.decodeAudioData(file.request.response, function(buffer) { //BLOCKS.debug("Sound Decoded: " + (path + file.src + extension) + " -> " + file.request); file.buffer = buffer; file.loaded = true; // TODO: Dispatch an notification that the file has been loaded for the first time, in case we want to play it after its loaded // TODO: Update the progress if we are waiting for pre-load onFileLoaded(file); file.request = null; }, function (error) { if (BLOCKS.debug) { BLOCKS.debug("Error decoding buffer: " + path + file.src + extension); } file.request = null; }); }; file.request.send(); }, load = function () { var source; loadStarted = true; source = ctx.createOscillator(); if (source.start) { source.start(0, 0, 1); } else if (source.noteGrainOn) { source.noteGrainOn(0, 0, 1); } }, destroyInstance = function (inst) { var i, index; for (i = 0; i < instances.length; i += 1) { if (instances[i] === inst) { instances[i] = null; index = i; break; } } instances.splice(index, 1); }, soundCompleteChecker = function (inst) { var callback, soundName; if (speaker.debug) { BLOCKS.debug("Sound '" + inst.sound.name + "' Complete"); } if (inst.callback) { callback = inst.callback; soundName = inst.name; } // Destroy the instance before calling a possible callback destroyInstance(inst); if (callback) { callback(soundName); } }, stopSound = function (inst) { window.clearTimeout(inst.timeout); if (inst.source.stop) { inst.source.stop(0); } else if (inst.source.noteGrainOff) { inst.source.noteGrainOff(0); } else { inst.source.noteOff(0); } destroyInstance(inst); }, getSoundGain = function (inst) { return inst.gain.gain.value; }, setSoundGain = function (inst, gainValue, delay) { // If the sound doesn't have its own gain then create its own gain we can change if (inst.gain === inst.track.gain) { // Disconnect the source from its track gain node inst.source.disconnect(0); // Create a new gain inst.gain = (ctx.createGain) ? ctx.createGain() : ctx.createGainNode(); inst.gain.connect(masterGain); // Connect the source to the new gain inst.source.connect(inst.gain); } if (speaker.debug) { BLOCKS.debug("speaker.setSoundGain of sound '" + inst.name + "' to '" + gainValue + "'"); } // If the gain should be faded out if (delay) { inst.gain.gain.linearRampToValueAtTime(inst.gain.gain.value, ctx.currentTime); inst.gain.gain.linearRampToValueAtTime(gainValue, ctx.currentTime + delay); } else { inst.gain.gain.value = gainValue; } }, pauseSound = function (inst) { window.clearTimeout(inst.timeout); inst.currentTime = ((+ new Date()) - inst.startTime) / 1000 % inst.source.buffer.duration; if (inst.source.stop) { inst.source.stop(0); } else if (inst.source.noteGrainOff) { inst.source.noteGrainOff(0); } else { inst.source.noteOff(0); } //if (speaker.debug) { // BLOCKS.debug("Pause sound: '" + inst.name + "' at scrubber position of " + inst.currentTime.toFixed(2)); //} }, unpauseSound = function (inst) { var newInst; //if (speaker.debug) { // BLOCKS.debug("Unpause sound: '" + inst.name + "'"); //} // Play a new instance of the sound newInst = playSound(inst.name, inst.callback, inst.track.name, inst.currentTime); if (inst.gain.gain.value !== 1) { setSoundGain(newInst, inst.gain.gain.value); } // Delete the old instance destroyInstance(inst); }, playSound = function (name, callback, trackName, currentTime, delay) { var inst = {}; if (sounds[name].file.loaded) { instances.push(inst); inst.sound = sounds[name]; inst.name = name; // If an offset is set (set when unpausing a sound) if (currentTime) { inst.currentTime = currentTime; } else { // Start from the beginning of the sound inst.currentTime = 0; } // Save when the sound starts, or would have started if started from the beginning inst.startTime = (+ new Date()) - inst.currentTime * 1000; if (delay) { // Play the sound after a delay inst.delay = ctx.currentTime + delay; } else { // Play the sound immediately delay = 0; inst.delay = 0; } if (trackName) { if (!tracks[trackName]) { createTrack(trackName); } inst.track = tracks[trackName]; } else { inst.track = tracks["default"]; } // Create a new source for this sound instance inst.source = ctx.createBufferSource(); inst.source.buffer = sounds[name].file.buffer; inst.source.loop = sounds[name].loop; inst.gain = inst.track.gain; // Connect the source to the gains inst.source.connect(inst.gain); if (!sounds[name].loop) { // Timeout at the end of the sound inst.timeout = window.setTimeout(soundCompleteChecker, (delay + inst.source.buffer.duration - inst.currentTime) * 1000, inst); // Assign a callback to be called once the sound is complete inst.callback = callback; } if (speaker.debug) { if (inst.currentTime) { BLOCKS.debug("Play sound: " + name + " (" + inst.currentTime + " - " + sounds[name].end + "), src: " + sounds[name].file.src + extension); } else { BLOCKS.debug("Play sound: " + name + " (" + sounds[name].start + " - " + sounds[name].end + "), src: " + sounds[name].file.src + extension); } } // Play the sound if (inst.source.start) { // If an offset is specified then add the start time and duration parameters if (inst.currentTime) { inst.source.start(inst.delay, inst.currentTime, inst.source.buffer.duration - inst.currentTime); } else { inst.source.start(inst.delay); } } else if (inst.source.noteGrainOn) { inst.source.noteGrainOn(inst.delay, inst.currentTime, inst.source.buffer.duration - inst.currentTime); } return inst; } else { // TODO: Play the unloaded sound once its loaded //if (speaker.debug) { BLOCKS.warn("Tried to play sound: " + name + ", but it is not loaded yet"); //} } }, createLoadTimer = function () { loadTimeoutId = window.setTimeout(function () { var key; for (key in files) { if (files.hasOwnProperty(key)) { if (!files[key].loaded) { // Cancel the request if (files[key].request) { BLOCKS.warn("Sound file load has timed out. Aborting request and trying again: " + files[key].src); files[key].request.abort(); } else { BLOCKS.warn("Sound file load has timed out. Sending additional request: " + files[key].src); } loadFile(files[key]); } } } loadTries += 1; if (loadTries < maxLoadTries) { createLoadTimer(); } }, maxLoadTime); }; speaker.play = function (name, callback, trackName, startTime, delay) { if (sounds[name]) { return playSound(name, callback, trackName, startTime, delay); } else { BLOCKS.warn("Cannot play sound '" + name + "' because it was not defined"); } }; speaker.getSoundDuration = function (name) { return sounds[name].file.buffer.duration; }; speaker.getSoundInstanceGain = function (inst) { return getSoundGain(inst); }; speaker.getSoundGain = function (name) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { return getSoundGain(instanceArr[i]); } } }; speaker.setSoundInstanceGain = function (inst, gainValue, delay) { setSoundGain(inst, gainValue, delay); }; speaker.setSoundGain = function (name, gainValue, delay) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { setSoundGain(instanceArr[i], gainValue, delay); } } }; speaker.stopSound = function (name) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { stopSound(instanceArr[i]); } } }; speaker.pauseSound = function (name) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { pauseSound(instanceArr[i]); } } }; speaker.unpauseSound = function (name) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { unpauseSound(instanceArr[i]); } } }; speaker.stopTrack = function (trackName) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].track.name === trackName) { stopSound(instanceArr[i]); } } }; speaker.pauseTrack = function (trackName) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].track.name === trackName) { pauseSound(instanceArr[i]); } } }; speaker.unpauseTrack = function (trackName) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].track.name === trackName) { unpauseSound(instanceArr[i]); } } }; // Stop all sounds speaker.stop = function () { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { stopSound(instanceArr[i]); } }; // Pause all sounds speaker.pause = function () { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { pauseSound(instanceArr[i]); } }; // Unpause any paused sounds speaker.unpause = function () { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { unpauseSound(instanceArr[i]); } }; // Mute all sound speaker.mute = function () { if (!muted) { muted = true; masterGain.gain.value = 0; } }; // Unmute all sound speaker.unmute = function () { if (muted) { muted = false; masterGain.gain.value = 1; } }; speaker.isMuted = function () { return muted; }; // Load the audio element speaker.load = function () { if (!loadStarted) { loadStarted = true; createLoadTimer(); load(); } }; // Return if audio is ready to be played speaker.isReady = function () { return ready; }; speaker.createSound = function (spec) { sounds[spec.name] = { name: spec.name, start: spec.start, end: spec.end, loop: spec.loop }; //BLOCKS.debug("Create Sound: " + spec.name); if (!files[spec.src]) { files[spec.src] = { src: spec.src }; loadFile(files[spec.src]); //BLOCKS.debug("Load Sound: " + spec.src); } sounds[spec.name].file = files[spec.src]; }; speaker.getActiveSoundInstances = function () { return instances; }; speaker.getNumFiles = function () { var key, totalNumFiles; totalNumFiles = 0; // Determine load progress for (key in files) { if (files.hasOwnProperty(key)) { totalNumFiles += 1; } } return totalNumFiles; }; speaker.getNumFilesLoaded = function () { var key, numFilesLoaded; numFilesLoaded = 0; // Determine load progress for (key in files) { if (files.hasOwnProperty(key)) { if (files[key].loaded) { numFilesLoaded += 1; } } } return numFilesLoaded; }; speaker.getCurrentTime = function () { return ctx.currentTime; }; speaker.multipleTracksSupported = true; (function () { var tmpAudioElement = document.createElement("audio"), fireFoxDetected; // Use ogg for Firefox due to a bud decoding buffer data fireFoxDetected = (navigator.userAgent.toLowerCase().indexOf('firefox') > -1); if (tmpAudioElement.canPlayType("audio/mpeg;").replace(/no/, "") && !!(tmpAudioElement.canPlayType) && !fireFoxDetected) { extension = ".mp3"; } else { extension = ".ogg"; } if (typeof AudioContext !== "undefined") { ctx = new window.AudioContext(); } else if (typeof webkitAudioContext !== "undefined") { ctx = new window.webkitAudioContext(); } if (ctx) { // Create the master gain node masterGain = (ctx.createGain) ? ctx.createGain() : ctx.createGainNode(); // Connext the master gain node to the context's output masterGain.connect(ctx.destination); } else { BLOCKS.error("Cannot create audio context."); } createTrack("default"); }()); return speaker; }; BLOCKS.audio.multiAudioElementPlayer = function (spec) { "use strict"; var speaker = BLOCKS.eventDispatcher(), initialized = false, loadStarted = false, loadComplete = false, ready = false, muted = false, extension, path = (spec && spec.path) || "", masterGain, ctx, sounds = {}, files = {}, instances = [], tracks = {}, loadTimeoutId, maxLoadTime = spec.maxLoadTime || 60000, // The maximum amount of time for all sounds to load loadTries = 0, maxLoadTries = 5, createTrack = function (name) { if (!tracks[name]) { tracks[name] = { name: name, gain: (ctx.createGain) ? ctx.createGain() : ctx.createGainNode() }; // Connect the track's gain node to the master node tracks[name].gain.connect(masterGain); } return tracks[name]; }, onFileLoaded = function (file) { var key, numFilesLoaded, totalNumFiles; numFilesLoaded = speaker.getNumFilesLoaded(); totalNumFiles = speaker.getNumFiles(); if (speaker.debug) { BLOCKS.debug("load: " + numFilesLoaded + " of " + totalNumFiles); } speaker.dispatchEvent("update", numFilesLoaded, totalNumFiles); if (numFilesLoaded === totalNumFiles) { if (!ready) { ready = true; // Clear the load timeout window.clearTimeout(loadTimeoutId); if (speaker.debug) { BLOCKS.debug("audio ready"); } speaker.dispatchEvent("ready"); } } }, loadFile = function (file) { file.audioElement = document.createElement("audio"); file.audioElement.preload = true; file.audioElement.src = (path + file.src + extension); file.audioElement.load(); file.audioElement.addEventListener("canplaythrough", function () { BLOCKS.debug("Audio element loaded: " + (path + file.src + extension)); file.loaded = true; onFileLoaded(file); }); //document.body.appendChild(file.audioElement); }, load = function () { /* var source; loadStarted = true; source = ctx.createOscillator(); if (source.start) { source.start(0, 0, 1); } else if (source.noteGrainOn) { source.noteGrainOn(0, 0, 1); } */ }, destroyInstance = function (inst) { var i, index; for (i = 0; i < instances.length; i += 1) { if (instances[i] === inst) { instances[i] = null; index = i; break; } } instances.splice(index, 1); }, soundCompleteChecker = function (inst) { var callback, soundName; if (speaker.debug) { BLOCKS.debug("Sound '" + inst.sound.name + "' Complete"); } if (inst.callback) { callback = inst.callback; soundName = inst.name; } // Destroy the instance before calling a possible callback destroyInstance(inst); if (callback) { callback(soundName); } }, stopSound = function (inst) { window.clearTimeout(inst.timeout); /* if (inst.source.stop) { inst.source.stop(0); } else if (inst.source.noteGrainOff) { inst.source.noteGrainOff(0); } else { inst.source.noteOff(0); } */ inst.sound.file.audioElement.pause(); destroyInstance(inst); }, getSoundGain = function (inst) { return inst.gain.gain.value; }, setSoundGain = function (inst, gainValue, delay) { // TODO: support a fade in and out with the delay property inst.sound.file.audioElement.volume = gainValue; /* // If the sound doesn't have its own gain then create its own gain we can change if (inst.gain === inst.track.gain) { // Disconnect the source from its track gain node inst.source.disconnect(0); // Create a new gain inst.gain = (ctx.createGain) ? ctx.createGain() : ctx.createGainNode(); inst.gain.connect(masterGain); // Connect the source to the new gain inst.source.connect(inst.gain); } if (speaker.debug) { BLOCKS.debug("speaker.setSoundGain of sound '" + inst.name + "' to '" + gainValue + "'"); } // If the gain should be faded out if (delay) { inst.gain.gain.linearRampToValueAtTime(inst.gain.gain.value, ctx.currentTime); inst.gain.gain.linearRampToValueAtTime(gainValue, ctx.currentTime + delay); } else { inst.gain.gain.value = gainValue; } */ }, pauseSound = function (inst) { window.clearTimeout(inst.timeout); inst.currentTime = ((+ new Date()) - inst.startTime) / 1000 % inst.sound.file.audioElement.duration; inst.sound.file.audioElement.pause(); //if (inst.source.stop) { // inst.source.stop(0); //} else if (inst.source.noteGrainOff) { // inst.source.noteGrainOff(0); //} else { // inst.source.noteOff(0); //} //if (speaker.debug) { // BLOCKS.debug("Pause sound: '" + inst.name + "' at scrubber position of " + inst.currentTime.toFixed(2)); //} }, unpauseSound = function (inst) { var newInst; //if (speaker.debug) { // BLOCKS.debug("Unpause sound: '" + inst.name + "'"); //} // Play a new instance of the sound //newInst = playSound(inst.name, inst.callback, inst.track.name, inst.currentTime); newInst = playSound(inst.name, inst.callback, null, inst.currentTime); //if (inst.gain.gain.value !== 1) { // setSoundGain(newInst, inst.gain.gain.value); //} // Delete the old instance destroyInstance(inst); }, playSound = function (name, callback, trackName, currentTime, delay) { var inst = {}; if (sounds[name].file.loaded) { instances.push(inst); inst.sound = sounds[name]; inst.name = name; // If an offset is set (set when unpausing a sound) if (currentTime) { inst.currentTime = currentTime; } else { // Start from the beginning of the sound inst.currentTime = 0; } // Save when the sound starts, or would have started if started from the beginning inst.startTime = (+ new Date()) - inst.currentTime * 1000; if (delay) { // Play the sound after a delay inst.delay = ctx.currentTime + delay; } else { // Play the sound immediately delay = 0; inst.delay = 0; } if (trackName) { if (!tracks[trackName]) { createTrack(trackName); } inst.track = tracks[trackName]; } else { inst.track = tracks["default"]; } // Create a new source for this sound instance //inst.source = ctx.createBufferSource(); //inst.source.buffer = sounds[name].file.buffer; //inst.source.loop = sounds[name].loop; //inst.gain = inst.track.gain; // Connect the source to the gains //inst.source.connect(inst.gain); if (!sounds[name].loop) { // Timeout at the end of the sound //inst.timeout = window.setTimeout(soundCompleteChecker, (delay + inst.source.buffer.duration - inst.currentTime) * 1000, inst); // Assign a callback to be called once the sound is complete inst.callback = callback; } else { inst.sound.file.audioElement.loop = true; } if (speaker.debug) { if (inst.currentTime) { BLOCKS.debug("Play sound: " + name + " (" + inst.currentTime + " - " + sounds[name].end + "), src: " + sounds[name].file.src + extension); } else { BLOCKS.debug("Play sound: " + name + " (" + sounds[name].start + " - " + sounds[name].end + "), src: " + sounds[name].file.src + extension); } } inst.sound.file.audioElement.currentTime = inst.currentTime; inst.sound.file.audioElement.play(); /* // Play the sound if (inst.source.start) { // If an offset is specified then add the start time and duration parameters if (inst.currentTime) { inst.source.start(inst.delay, inst.currentTime, inst.source.buffer.duration - inst.currentTime); } else { inst.source.start(inst.delay); } } else if (inst.source.noteGrainOn) { inst.source.noteGrainOn(inst.delay, inst.currentTime, inst.source.buffer.duration - inst.currentTime); } */ return inst; } else { // TODO: Play the unloaded sound once its loaded //if (speaker.debug) { BLOCKS.warn("Tried to play sound: " + name + ", but it is not loaded yet"); //} } }, createLoadTimer = function () { loadTimeoutId = window.setTimeout(function () { var key; for (key in files) { if (files.hasOwnProperty(key)) { if (!files[key].loaded) { // Cancel the request if (files[key].request) { BLOCKS.warn("Sound file load has timed out. Aborting request and trying again: " + files[key].src); files[key].request.abort(); } else { BLOCKS.warn("Sound file load has timed out. Sending additional request: " + files[key].src); } loadFile(files[key]); } } } loadTries += 1; if (loadTries < maxLoadTries) { createLoadTimer(); } }, maxLoadTime); }; speaker.play = function (name, callback, trackName, startTime, delay) { if (sounds[name]) { return playSound(name, callback, trackName, startTime, delay); } else { BLOCKS.warn("Cannot play sound '" + name + "' because it was not defined"); } }; speaker.getSoundDuration = function (name) { return sounds[name].file.buffer.duration; }; speaker.getSoundInstanceGain = function (inst) { return getSoundGain(inst); }; speaker.getSoundGain = function (name) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { return getSoundGain(instanceArr[i]); } } }; speaker.setSoundInstanceGain = function (inst, gainValue, delay) { setSoundGain(inst, gainValue, delay); }; speaker.setSoundGain = function (name, gainValue, delay) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { setSoundGain(instanceArr[i], gainValue, delay); } } }; speaker.stopSound = function (name) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { stopSound(instanceArr[i]); } } }; speaker.pauseSound = function (name) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { pauseSound(instanceArr[i]); } } }; speaker.unpauseSound = function (name) { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { if (instanceArr[i].name === name) { unpauseSound(instanceArr[i]); } } }; speaker.stopTrack = function (trackName) { //var i, instanceArr = instances.slice(0); // //for (i = 0; i < instanceArr.length; i += 1) { // if (instanceArr[i].track.name === trackName) { // stopSound(instanceArr[i]); // } //} }; speaker.pauseTrack = function (trackName) { //var i, instanceArr = instances.slice(0); // //for (i = 0; i < instanceArr.length; i += 1) { // if (instanceArr[i].track.name === trackName) { // pauseSound(instanceArr[i]); // } //} }; speaker.unpauseTrack = function (trackName) { //var i, instanceArr = instances.slice(0); // //for (i = 0; i < instanceArr.length; i += 1) { // if (instanceArr[i].track.name === trackName) { // unpauseSound(instanceArr[i]); // } //} }; // Stop all sounds speaker.stop = function () { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { stopSound(instanceArr[i]); } }; // Pause all sounds speaker.pause = function () { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { pauseSound(instanceArr[i]); } }; // Unpause any paused sounds speaker.unpause = function () { var i, instanceArr = instances.slice(0); for (i = 0; i < instanceArr.length; i += 1) { unpauseSound(instanceArr[i]); } }; // Mute all sound speaker.mute = function () { if (!muted) { muted = true; // TODO: mute all sounds } }; // Unmute all sound speaker.unmute = function () { if (muted) { muted = false; // TODO: unmute all sounds } }; speaker.isMuted = function () { return muted; }; // Load the audio element speaker.load = function () { if (!loadStarted) { loadStarted = true; createLoadTimer(); load(); } }; // Return if audio is ready to be played speaker.isReady = function () { return ready; }; speaker.createSound = function (spec) { sounds[spec.name] = { name: spec.name, start: spec.start, end: spec.end, loop: spec.loop }; //BLOCKS.debug("Create Sound: " + spec.name); if (!files[spec.src]) { files[spec.src] = { src: spec.src }; loadFile(files[spec.src]); //BLOCKS.debug("Load Sound: " + spec.src); } sounds[spec.name].file = files[spec.src]; }; speaker.getActiveSoundInstances = function () { return instances; }; speaker.getNumFiles = function () { var key, totalNumFiles; totalNumFiles = 0; // Determine load progress for (key in files) { if (files.hasOwnProperty(key)) { totalNumFiles += 1; } } return totalNumFiles; }; speaker.getNumFilesLoaded = function () { var key, numFilesLoaded; numFilesLoaded = 0; // Determine load progress for (key in files) { if (files.hasOwnProperty(key)) { if (files[key].loaded) { numFilesLoaded += 1; } } } return numFilesLoaded; }; speaker.getCurrentTime = function () { // Since multiple sounds could be playing this returns nothing return null; }; speaker.multipleTracksSupported = true; (function () { extension = ".mp3"; }()); return speaker; }; BLOCKS.speaker = function (spec) { "use strict"; var speaker; // Create audio element (function () { if (!spec) { spec = {}; } if (spec.audioPlayerType === "multiAudioElementPlayer") { speaker = BLOCKS.audio.multiAudioElementPlayer(spec); } else if ((typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') && spec.webAudioEnabled !== false) { speaker = BLOCKS.audio.webAudioPlayer(spec); } else { speaker = BLOCKS.audio.audioElementPlayer(spec); } }()); speaker.debug = false; return speaker; };
Added multiAudioElementPlayer fade support
src/js/speaker.js
Added multiAudioElementPlayer fade support
<ide><path>rc/js/speaker.js <ide> <ide> stopSound = function (inst) { <ide> <del> window.clearTimeout(inst.timeout); <del> <add> if (inst.timeout) { <add> window.clearTimeout(inst.timeout); <add> } <add> if (inst.fadeTimeout) { <add> window.clearTimeout(inst.fadeTimeout); <add> } <ide> /* <ide> if (inst.source.stop) { <ide> inst.source.stop(0); <ide> }, <ide> <ide> setSoundGain = function (inst, gainValue, delay) { <del> <del>// TODO: support a fade in and out with the delay property <del> inst.sound.file.audioElement.volume = gainValue; <del> <del> /* <del> // If the sound doesn't have its own gain then create its own gain we can change <del> if (inst.gain === inst.track.gain) { <del> <del> // Disconnect the source from its track gain node <del> inst.source.disconnect(0); <del> <del> // Create a new gain <del> inst.gain = (ctx.createGain) ? ctx.createGain() : ctx.createGainNode(); <del> inst.gain.connect(masterGain); <del> <del> // Connect the source to the new gain <del> inst.source.connect(inst.gain); <del> } <del> if (speaker.debug) { <del> BLOCKS.debug("speaker.setSoundGain of sound '" + inst.name + "' to '" + gainValue + "'"); <del> } <del> // If the gain should be faded out <add> <add> var fadeInterval = 10; <add> <add> // Clear previous fade if it's still going <add> if (inst.fadeTimeout) { <add> inst.sound.file.audioElement.volume = inst.fadeTarget; <add> window.clearInterval(inst.fadeTimeout); <add> inst.fadeTarget = 0; <add> inst.fadeAmount = 0; <add> } <add> <ide> if (delay) { <del> inst.gain.gain.linearRampToValueAtTime(inst.gain.gain.value, ctx.currentTime); <del> inst.gain.gain.linearRampToValueAtTime(gainValue, ctx.currentTime + delay); <add> <add> // Create timer to fade the gain over time <add> inst.fadeTarget = gainValue; <add> inst.fadeAmount = (gainValue - inst.sound.file.audioElement.volume) / ((delay * 1000) / fadeInterval); <add> inst.fadeTimeout = window.setInterval(function () { <add> if (inst.sound.file.audioElement.volume === inst.fadeTarget) { <add> window.clearInterval(inst.fadeTimeout); <add> } <add> inst.sound.file.audioElement.volume += inst.fadeAmount; <add> }, fadeInterval); <ide> } else { <del> inst.gain.gain.value = gainValue; <del> } <del> */ <add> inst.sound.file.audioElement.volume = gainValue; <add> } <ide> }, <ide> <ide> pauseSound = function (inst) { <ide> inst.currentTime = ((+ new Date()) - inst.startTime) / 1000 % inst.sound.file.audioElement.duration; <ide> <ide> inst.sound.file.audioElement.pause(); <del> <del> //if (inst.source.stop) { <del> // inst.source.stop(0); <del> //} else if (inst.source.noteGrainOff) { <del> // inst.source.noteGrainOff(0); <del> //} else { <del> // inst.source.noteOff(0); <del> //} <del> <del> //if (speaker.debug) { <del> // BLOCKS.debug("Pause sound: '" + inst.name + "' at scrubber position of " + inst.currentTime.toFixed(2)); <del> //} <ide> }, <ide> <ide> unpauseSound = function (inst) { <ide> //if (speaker.debug) { <ide> // BLOCKS.debug("Unpause sound: '" + inst.name + "'"); <ide> //} <del> <del> // Play a new instance of the sound <del> //newInst = playSound(inst.name, inst.callback, inst.track.name, inst.currentTime); <add> <ide> newInst = playSound(inst.name, inst.callback, null, inst.currentTime); <ide> <del> //if (inst.gain.gain.value !== 1) { <del> // setSoundGain(newInst, inst.gain.gain.value); <del> //} <del> <ide> // Delete the old instance <ide> destroyInstance(inst); <ide> },
Java
bsd-3-clause
89157596f9be310520a772227861d0ce08ffb6ea
0
forcedotcom/phoenix,forcedotcom/phoenix
/******************************************************************************* * Copyright (c) 2013, Salesforce.com, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Salesforce.com nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ package com.salesforce.phoenix.end2end; import static com.salesforce.phoenix.util.TestUtil.*; import static org.junit.Assert.*; import java.sql.*; import java.util.Properties; import org.junit.Test; import com.salesforce.phoenix.util.PhoenixRuntime; /** * Tests for table with transparent salting. */ public class SaltedTableTest extends BaseClientMangedTimeTest { private static void initTableValues(byte[][] splits, long ts) throws Exception { String url = PHOENIX_JDBC_URL + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + ts; Properties props = new Properties(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(url, props); // Rows we inserted: // 1ab123abc111 // 1abc456abc111 // 1de123abc111 // 2abc123def222 // 3abc123ghi333 // 4abc123jkl444 try { // Upsert with no column specifies. ensureTableCreated(getUrl(), TABLE_WITH_SALTING, splits, ts-2); String query = "UPSERT INTO " + TABLE_WITH_SALTING + " VALUES(?,?,?,?,?)"; PreparedStatement stmt = conn.prepareStatement(query); stmt.setInt(1, 1); stmt.setString(2, "ab"); stmt.setString(3, "123"); stmt.setString(4, "abc"); stmt.setInt(5, 111); stmt.execute(); conn.commit(); stmt.setInt(1, 1); stmt.setString(2, "abc"); stmt.setString(3, "456"); stmt.setString(4, "abc"); stmt.setInt(5, 111); stmt.execute(); conn.commit(); // Test upsert when statement explicitly specifies the columns to upsert into. query = "UPSERT INTO " + TABLE_WITH_SALTING + " (a_integer, a_string, a_id, b_string, b_integer) " + " VALUES(?,?,?,?,?)"; stmt = conn.prepareStatement(query); stmt.setInt(1, 1); stmt.setString(2, "de"); stmt.setString(3, "123"); stmt.setString(4, "abc"); stmt.setInt(5, 111); stmt.execute(); conn.commit(); stmt.setInt(1, 2); stmt.setString(2, "abc"); stmt.setString(3, "123"); stmt.setString(4, "def"); stmt.setInt(5, 222); stmt.execute(); conn.commit(); // Test upsert when order of column is shuffled. query = "UPSERT INTO " + TABLE_WITH_SALTING + " (a_string, a_integer, a_id, b_string, b_integer) " + " VALUES(?,?,?,?,?)"; stmt = conn.prepareStatement(query); stmt.setString(1, "abc"); stmt.setInt(2, 3); stmt.setString(3, "123"); stmt.setString(4, "ghi"); stmt.setInt(5, 333); stmt.execute(); conn.commit(); stmt.setString(1, "abc"); stmt.setInt(2, 4); stmt.setString(3, "123"); stmt.setString(4, "jkl"); stmt.setInt(5, 444); stmt.execute(); conn.commit(); } finally { conn.close(); } } @Test public void testTableWithInvalidBucketNumber() throws Exception { long ts = nextTimestamp(); String url = PHOENIX_JDBC_URL + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 5); Properties props = new Properties(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(url, props); try { String query = "create table salted_table (a_integer integer not null CONSTRAINT pk PRIMARY KEY (a_integer)) SALT_BUCKETS = 257"; PreparedStatement stmt = conn.prepareStatement(query); stmt.execute(); fail("Should have caught exception"); } catch (SQLException e) { assertTrue(e.getMessage(), e.getMessage().contains("ERROR 1021 (42Y80): Salt bucket numbers should be with 1 and 256.")); } finally { conn.close(); } } @Test public void testSelectValueNoWhereClause() throws Exception { long ts = nextTimestamp(); String url = PHOENIX_JDBC_URL + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 5); Properties props = new Properties(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(url, props); try { initTableValues(null, ts); String query = "SELECT * FROM " + TABLE_WITH_SALTING; PreparedStatement statement = conn.prepareStatement(query); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); assertEquals(3, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("ghi", rs.getString(4)); assertEquals(333, rs.getInt(5)); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals("ab", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("abc", rs.getString(4)); assertEquals(111, rs.getInt(5)); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals("de", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("abc", rs.getString(4)); assertEquals(111, rs.getInt(5)); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("def", rs.getString(4)); assertEquals(222, rs.getInt(5)); assertTrue(rs.next()); assertEquals(4, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("jkl", rs.getString(4)); assertEquals(444, rs.getInt(5)); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("456", rs.getString(3)); assertEquals("abc", rs.getString(4)); assertEquals(111, rs.getInt(5)); assertFalse(rs.next()); } finally { conn.close(); } } @Test public void testSelectValueWithFullyQualifiedWhereClause() throws Exception { long ts = nextTimestamp(); String url = PHOENIX_JDBC_URL + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 5); Properties props = new Properties(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(url, props); try { initTableValues(null, ts); String query; PreparedStatement stmt; ResultSet rs; // Variable length slot with bounded ranges. query = "SELECT * FROM " + TABLE_WITH_SALTING + " WHERE a_integer = 1 AND a_string >= 'ab' AND a_string < 'de' AND a_id = '123'"; stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals("ab", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("abc", rs.getString(4)); assertEquals(111, rs.getInt(5)); assertFalse(rs.next()); // all single slots with one value. query = "SELECT * FROM " + TABLE_WITH_SALTING + " WHERE a_integer = 1 AND a_string = 'ab' AND a_id = '123'"; stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals("ab", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("abc", rs.getString(4)); assertEquals(111, rs.getInt(5)); assertFalse(rs.next()); // all single slots with multiple values. query = "SELECT * FROM " + TABLE_WITH_SALTING + " WHERE a_integer in (2, 4) AND a_string = 'abc' AND a_id = '123'"; stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("def", rs.getString(4)); assertEquals(222, rs.getInt(5)); assertTrue(rs.next()); assertEquals(4, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("jkl", rs.getString(4)); assertEquals(444, rs.getInt(5)); assertFalse(rs.next()); query = "SELECT * FROM " + TABLE_WITH_SALTING + " WHERE a_integer in (1,2,3,4) AND a_string in ('a', 'abc', 'de') AND a_id = '123'"; stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); assertTrue(rs.next()); assertEquals(3, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("ghi", rs.getString(4)); assertEquals(333, rs.getInt(5)); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals("de", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("abc", rs.getString(4)); assertEquals(111, rs.getInt(5)); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("def", rs.getString(4)); assertEquals(222, rs.getInt(5)); assertTrue(rs.next()); assertEquals(4, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("jkl", rs.getString(4)); assertEquals(444, rs.getInt(5)); assertFalse(rs.next()); // fixed length slot with bounded ranges. query = "SELECT * FROM " + TABLE_WITH_SALTING + " WHERE a_integer > 1 AND a_integer < 4 AND a_string = 'abc' AND a_id = '123'"; stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); assertTrue(rs.next()); assertEquals(3, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("ghi", rs.getString(4)); assertEquals(333, rs.getInt(5)); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("def", rs.getString(4)); assertEquals(222, rs.getInt(5)); assertFalse(rs.next()); // fixed length slot with unbound ranges. query = "SELECT * FROM " + TABLE_WITH_SALTING + " WHERE a_integer > 1 AND a_string = 'abc' AND a_id = '123'"; stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); assertTrue(rs.next()); assertEquals(3, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("ghi", rs.getString(4)); assertEquals(333, rs.getInt(5)); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("def", rs.getString(4)); assertEquals(222, rs.getInt(5)); assertTrue(rs.next()); assertEquals(4, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("jkl", rs.getString(4)); assertEquals(444, rs.getInt(5)); assertFalse(rs.next()); // Variable length slot with unbounded ranges. query = "SELECT * FROM " + TABLE_WITH_SALTING + " WHERE a_integer = 1 AND a_string > 'ab' AND a_id = '123'"; stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals("de", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("abc", rs.getString(4)); assertEquals(111, rs.getInt(5)); assertFalse(rs.next()); } finally { conn.close(); } } @Test public void testSelectValueWithNotFullyQualifiedWhereClause() throws Exception { long ts = nextTimestamp(); String url = PHOENIX_JDBC_URL + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 5); Properties props = new Properties(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(url, props); try { initTableValues(null, ts); // Where without fully qualified key, point query. String query = "SELECT * FROM " + TABLE_WITH_SALTING + " WHERE a_integer = ? AND a_string = ?"; PreparedStatement stmt = conn.prepareStatement(query); stmt.setInt(1, 1); stmt.setString(2, "abc"); ResultSet rs = stmt.executeQuery(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("456", rs.getString(3)); assertEquals("abc", rs.getString(4)); assertEquals(111, rs.getInt(5)); assertFalse(rs.next()); // Where without fully qualified key, range query. query = "SELECT * FROM " + TABLE_WITH_SALTING + " WHERE a_integer >= 2"; stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); assertTrue(rs.next()); assertEquals(3, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("ghi", rs.getString(4)); assertEquals(333, rs.getInt(5)); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("def", rs.getString(4)); assertEquals(222, rs.getInt(5)); assertTrue(rs.next()); assertEquals(4, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("jkl", rs.getString(4)); assertEquals(444, rs.getInt(5)); assertFalse(rs.next()); // With point query. query = "SELECT a_string FROM " + TABLE_WITH_SALTING + " WHERE a_string = ?"; stmt = conn.prepareStatement(query); stmt.setString(1, "de"); rs = stmt.executeQuery(); assertTrue(rs.next()); assertEquals("de", rs.getString(1)); assertFalse(rs.next()); query = "SELECT a_id FROM " + TABLE_WITH_SALTING + " WHERE a_id = ?"; stmt = conn.prepareStatement(query); stmt.setString(1, "456"); rs = stmt.executeQuery(); assertTrue(rs.next()); assertEquals("456", rs.getString(1)); assertFalse(rs.next()); } finally { conn.close(); } } @Test public void testSelectWithGroupBy() throws Exception { long ts = nextTimestamp(); String url = PHOENIX_JDBC_URL + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 5); Properties props = new Properties(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(url, props); try { // Force all entries to fall in one region. initTableValues(new byte[][] {{(byte) 5}}, ts); String query = "SELECT a_integer FROM " + TABLE_WITH_SALTING + " GROUP BY a_integer"; PreparedStatement stmt = conn.prepareStatement(query); ResultSet rs = stmt.executeQuery(); int count = 0; while (rs.next()) { count++; } assertEquals("Group by does not return the right count.", count, 4); } finally { conn.close(); } } }
src/test/java/com/salesforce/phoenix/end2end/SaltedTableTest.java
/******************************************************************************* * Copyright (c) 2013, Salesforce.com, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of Salesforce.com nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ package com.salesforce.phoenix.end2end; import static com.salesforce.phoenix.util.TestUtil.*; import static org.junit.Assert.*; import java.sql.*; import java.util.Properties; import org.junit.Test; import com.salesforce.phoenix.util.PhoenixRuntime; /** * Tests for table with transparent salting. */ public class SaltedTableTest extends BaseClientMangedTimeTest { private static byte[][] splits = null; private static void initTableValues(byte[][] splits, long ts) throws Exception { String url = PHOENIX_JDBC_URL + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + ts; Properties props = new Properties(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(url, props); // Rows we inserted: // 1ab123abc111 // 1abc456abc111 // 1de123abc111 // 2abc123def222 // 3abc123ghi333 // 4abc123jkl444 try { // Upsert with no column specifies. ensureTableCreated(getUrl(), TABLE_WITH_SALTING, splits, ts-2); String query = "UPSERT INTO " + TABLE_WITH_SALTING + " VALUES(?,?,?,?,?)"; PreparedStatement stmt = conn.prepareStatement(query); stmt.setInt(1, 1); stmt.setString(2, "ab"); stmt.setString(3, "123"); stmt.setString(4, "abc"); stmt.setInt(5, 111); stmt.execute(); conn.commit(); stmt.setInt(1, 1); stmt.setString(2, "abc"); stmt.setString(3, "456"); stmt.setString(4, "abc"); stmt.setInt(5, 111); stmt.execute(); conn.commit(); // Test upsert when statement explicitly specifies the columns to upsert into. query = "UPSERT INTO " + TABLE_WITH_SALTING + " (a_integer, a_string, a_id, b_string, b_integer) " + " VALUES(?,?,?,?,?)"; stmt = conn.prepareStatement(query); stmt.setInt(1, 1); stmt.setString(2, "de"); stmt.setString(3, "123"); stmt.setString(4, "abc"); stmt.setInt(5, 111); stmt.execute(); conn.commit(); stmt.setInt(1, 2); stmt.setString(2, "abc"); stmt.setString(3, "123"); stmt.setString(4, "def"); stmt.setInt(5, 222); stmt.execute(); conn.commit(); // Test upsert when order of column is shuffled. query = "UPSERT INTO " + TABLE_WITH_SALTING + " (a_string, a_integer, a_id, b_string, b_integer) " + " VALUES(?,?,?,?,?)"; stmt = conn.prepareStatement(query); stmt.setString(1, "abc"); stmt.setInt(2, 3); stmt.setString(3, "123"); stmt.setString(4, "ghi"); stmt.setInt(5, 333); stmt.execute(); conn.commit(); stmt.setString(1, "abc"); stmt.setInt(2, 4); stmt.setString(3, "123"); stmt.setString(4, "jkl"); stmt.setInt(5, 444); stmt.execute(); conn.commit(); } finally { conn.close(); } } @Test public void testTableWithInvalidBucketNumber() throws Exception { long ts = nextTimestamp(); String url = PHOENIX_JDBC_URL + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 5); Properties props = new Properties(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(url, props); try { String query = "create table salted_table (a_integer integer not null CONSTRAINT pk PRIMARY KEY (a_integer)) SALT_BUCKETS = 257"; PreparedStatement stmt = conn.prepareStatement(query); stmt.execute(); fail("Should have caught exception"); } catch (SQLException e) { assertTrue(e.getMessage(), e.getMessage().contains("ERROR 1021 (42Y80): Salt bucket numbers should be with 1 and 256.")); } finally { conn.close(); } } @Test public void testSelectValueNoWhereClause() throws Exception { long ts = nextTimestamp(); String url = PHOENIX_JDBC_URL + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 5); Properties props = new Properties(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(url, props); try { initTableValues(splits, ts); String query = "SELECT * FROM " + TABLE_WITH_SALTING; PreparedStatement statement = conn.prepareStatement(query); ResultSet rs = statement.executeQuery(); assertTrue(rs.next()); assertEquals(3, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("ghi", rs.getString(4)); assertEquals(333, rs.getInt(5)); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals("ab", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("abc", rs.getString(4)); assertEquals(111, rs.getInt(5)); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals("de", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("abc", rs.getString(4)); assertEquals(111, rs.getInt(5)); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("def", rs.getString(4)); assertEquals(222, rs.getInt(5)); assertTrue(rs.next()); assertEquals(4, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("jkl", rs.getString(4)); assertEquals(444, rs.getInt(5)); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("456", rs.getString(3)); assertEquals("abc", rs.getString(4)); assertEquals(111, rs.getInt(5)); assertFalse(rs.next()); } finally { conn.close(); } } @Test public void testSelectValueWithFullyQualifiedWhereClause() throws Exception { long ts = nextTimestamp(); String url = PHOENIX_JDBC_URL + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 5); Properties props = new Properties(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(url, props); try { initTableValues(splits, ts); String query; PreparedStatement stmt; ResultSet rs; // Variable length slot with bounded ranges. query = "SELECT * FROM " + TABLE_WITH_SALTING + " WHERE a_integer = 1 AND a_string >= 'ab' AND a_string < 'de' AND a_id = '123'"; stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals("ab", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("abc", rs.getString(4)); assertEquals(111, rs.getInt(5)); assertFalse(rs.next()); // all single slots with one value. query = "SELECT * FROM " + TABLE_WITH_SALTING + " WHERE a_integer = 1 AND a_string = 'ab' AND a_id = '123'"; stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals("ab", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("abc", rs.getString(4)); assertEquals(111, rs.getInt(5)); assertFalse(rs.next()); // all single slots with multiple values. query = "SELECT * FROM " + TABLE_WITH_SALTING + " WHERE a_integer in (2, 4) AND a_string = 'abc' AND a_id = '123'"; stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("def", rs.getString(4)); assertEquals(222, rs.getInt(5)); assertTrue(rs.next()); assertEquals(4, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("jkl", rs.getString(4)); assertEquals(444, rs.getInt(5)); assertFalse(rs.next()); query = "SELECT * FROM " + TABLE_WITH_SALTING + " WHERE a_integer in (1,2,3,4) AND a_string in ('a', 'abc', 'de') AND a_id = '123'"; stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); assertTrue(rs.next()); assertEquals(3, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("ghi", rs.getString(4)); assertEquals(333, rs.getInt(5)); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals("de", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("abc", rs.getString(4)); assertEquals(111, rs.getInt(5)); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("def", rs.getString(4)); assertEquals(222, rs.getInt(5)); assertTrue(rs.next()); assertEquals(4, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("jkl", rs.getString(4)); assertEquals(444, rs.getInt(5)); assertFalse(rs.next()); // fixed length slot with bounded ranges. query = "SELECT * FROM " + TABLE_WITH_SALTING + " WHERE a_integer > 1 AND a_integer < 4 AND a_string = 'abc' AND a_id = '123'"; stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); assertTrue(rs.next()); assertEquals(3, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("ghi", rs.getString(4)); assertEquals(333, rs.getInt(5)); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("def", rs.getString(4)); assertEquals(222, rs.getInt(5)); assertFalse(rs.next()); // fixed length slot with unbound ranges. query = "SELECT * FROM " + TABLE_WITH_SALTING + " WHERE a_integer > 1 AND a_string = 'abc' AND a_id = '123'"; stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); assertTrue(rs.next()); assertEquals(3, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("ghi", rs.getString(4)); assertEquals(333, rs.getInt(5)); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("def", rs.getString(4)); assertEquals(222, rs.getInt(5)); assertTrue(rs.next()); assertEquals(4, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("jkl", rs.getString(4)); assertEquals(444, rs.getInt(5)); assertFalse(rs.next()); // Variable length slot with unbounded ranges. query = "SELECT * FROM " + TABLE_WITH_SALTING + " WHERE a_integer = 1 AND a_string > 'ab' AND a_id = '123'"; stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals("de", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("abc", rs.getString(4)); assertEquals(111, rs.getInt(5)); assertFalse(rs.next()); } finally { conn.close(); } } @Test public void testSelectValueWithNotFullyQualifiedWhereClause() throws Exception { long ts = nextTimestamp(); String url = PHOENIX_JDBC_URL + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 5); Properties props = new Properties(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(url, props); try { initTableValues(splits, ts); // Where without fully qualified key, point query. String query = "SELECT * FROM " + TABLE_WITH_SALTING + " WHERE a_integer = ? AND a_string = ?"; PreparedStatement stmt = conn.prepareStatement(query); stmt.setInt(1, 1); stmt.setString(2, "abc"); ResultSet rs = stmt.executeQuery(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("456", rs.getString(3)); assertEquals("abc", rs.getString(4)); assertEquals(111, rs.getInt(5)); assertFalse(rs.next()); // Where without fully qualified key, range query. query = "SELECT * FROM " + TABLE_WITH_SALTING + " WHERE a_integer >= 2"; stmt = conn.prepareStatement(query); rs = stmt.executeQuery(); assertTrue(rs.next()); assertEquals(3, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("ghi", rs.getString(4)); assertEquals(333, rs.getInt(5)); assertTrue(rs.next()); assertEquals(2, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("def", rs.getString(4)); assertEquals(222, rs.getInt(5)); assertTrue(rs.next()); assertEquals(4, rs.getInt(1)); assertEquals("abc", rs.getString(2)); assertEquals("123", rs.getString(3)); assertEquals("jkl", rs.getString(4)); assertEquals(444, rs.getInt(5)); assertFalse(rs.next()); // With point query. query = "SELECT a_string FROM " + TABLE_WITH_SALTING + " WHERE a_string = ?"; stmt = conn.prepareStatement(query); stmt.setString(1, "de"); rs = stmt.executeQuery(); assertTrue(rs.next()); assertEquals("de", rs.getString(1)); assertFalse(rs.next()); query = "SELECT a_id FROM " + TABLE_WITH_SALTING + " WHERE a_id = ?"; stmt = conn.prepareStatement(query); stmt.setString(1, "456"); rs = stmt.executeQuery(); assertTrue(rs.next()); assertEquals("456", rs.getString(1)); assertFalse(rs.next()); } finally { conn.close(); } } }
Test for select pk column with group by on a salted table.
src/test/java/com/salesforce/phoenix/end2end/SaltedTableTest.java
Test for select pk column with group by on a salted table.
<ide><path>rc/test/java/com/salesforce/phoenix/end2end/SaltedTableTest.java <ide> */ <ide> public class SaltedTableTest extends BaseClientMangedTimeTest { <ide> <del> private static byte[][] splits = null; <del> <ide> private static void initTableValues(byte[][] splits, long ts) throws Exception { <ide> String url = PHOENIX_JDBC_URL + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + ts; <ide> Properties props = new Properties(TEST_PROPERTIES); <ide> Properties props = new Properties(TEST_PROPERTIES); <ide> Connection conn = DriverManager.getConnection(url, props); <ide> try { <del> initTableValues(splits, ts); <add> initTableValues(null, ts); <ide> <ide> String query = "SELECT * FROM " + TABLE_WITH_SALTING; <ide> PreparedStatement statement = conn.prepareStatement(query); <ide> Properties props = new Properties(TEST_PROPERTIES); <ide> Connection conn = DriverManager.getConnection(url, props); <ide> try { <del> initTableValues(splits, ts); <add> initTableValues(null, ts); <ide> String query; <ide> PreparedStatement stmt; <ide> ResultSet rs; <ide> Properties props = new Properties(TEST_PROPERTIES); <ide> Connection conn = DriverManager.getConnection(url, props); <ide> try { <del> initTableValues(splits, ts); <add> initTableValues(null, ts); <ide> <ide> // Where without fully qualified key, point query. <ide> String query = "SELECT * FROM " + TABLE_WITH_SALTING + " WHERE a_integer = ? AND a_string = ?"; <ide> conn.close(); <ide> } <ide> } <add> <add> @Test <add> public void testSelectWithGroupBy() throws Exception { <add> long ts = nextTimestamp(); <add> String url = PHOENIX_JDBC_URL + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 5); <add> Properties props = new Properties(TEST_PROPERTIES); <add> Connection conn = DriverManager.getConnection(url, props); <add> try { <add> // Force all entries to fall in one region. <add> initTableValues(new byte[][] {{(byte) 5}}, ts); <add> <add> String query = "SELECT a_integer FROM " + TABLE_WITH_SALTING + " GROUP BY a_integer"; <add> PreparedStatement stmt = conn.prepareStatement(query); <add> ResultSet rs = stmt.executeQuery(); <add> int count = 0; <add> while (rs.next()) { <add> count++; <add> } <add> assertEquals("Group by does not return the right count.", count, 4); <add> } finally { <add> conn.close(); <add> } <add> } <ide> }
Java
mpl-2.0
533ad7ccaf182a1254dc6e51c49599fd2c2eb45b
0
Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV,Helioviewer-Project/JHelioviewer-SWHV
package org.helioviewer.plugins.eveplugin.radio.data; import java.awt.Rectangle; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.helioviewer.base.logging.Log; import org.helioviewer.base.math.Interval; import org.helioviewer.base.math.Vector2dDouble; import org.helioviewer.base.math.Vector2dInt; import org.helioviewer.plugins.eveplugin.EVEState; import org.helioviewer.plugins.eveplugin.radio.model.ResolutionSetting; import org.helioviewer.plugins.eveplugin.radio.model.YValueModel; import org.helioviewer.plugins.eveplugin.radio.model.YValueModelManager; import org.helioviewer.plugins.eveplugin.radio.model.ZoomManager; import org.helioviewer.plugins.eveplugin.settings.EVESettings; import org.helioviewer.plugins.eveplugin.view.linedataselector.LineDataSelectorModel; import org.helioviewer.viewmodel.changeevent.ChangeEvent; import org.helioviewer.viewmodel.metadata.HelioviewerMetaData; import org.helioviewer.viewmodel.region.RegionAdapter; import org.helioviewer.viewmodel.region.StaticRegion; import org.helioviewer.viewmodel.view.View; import org.helioviewer.viewmodel.view.jp2view.JHVJP2View; import org.helioviewer.viewmodel.view.jp2view.JHVJP2View.ReaderMode; import org.helioviewer.viewmodel.view.jp2view.JP2Image; import org.helioviewer.viewmodel.view.jp2view.image.ResolutionSet; import org.helioviewer.viewmodel.viewport.StaticViewport; import org.helioviewer.viewmodel.viewport.ViewportAdapter; /** * The radio data manager manages all the downloaded data for radio * spectrograms. * * It receives all of its input from the radio downloader as listener of the * radio downloader. * * @author [email protected] * */ public class RadioDataManager implements RadioDownloaderListener { /** The singleton instance of the class. */ private static RadioDataManager instance; /** A list collecting all the radio data manager listeners. */ private List<RadioDataManagerListener> listeners; /** A map keeping the download request data. */ private Map<Long, DownloadRequestData> downloadRequestData; /** Instance of the radio downloader */ private RadioDownloader downloader; /** A buffer holding all the requests for data. */ private RequestForDataBuffer requestBuffer; /** The instance of the line data selector model */ private LineDataSelectorModel lineDataSelectorModel; /** Instance of the radio image cache */ private RadioImageCache cache; /** Instance of the zoom manager */ private ZoomManager zoomManager; /** Id for identifying the requests for data. */ private long id = 0; /** Instance of eve state */ private EVEState eveState; /** INstance of the y-value model manager */ private YValueModelManager yValueModelManager; /** * private constructor used when the instance is requested for the first * time. * */ private RadioDataManager() { listeners = new ArrayList<RadioDataManagerListener>(); downloadRequestData = new HashMap<Long, DownloadRequestData>(); downloader = RadioDownloader.getSingletonInstance(); downloader.addRadioDownloaderListener(this); lineDataSelectorModel = LineDataSelectorModel.getSingletonInstance(); cache = RadioImageCache.getInstance(); requestBuffer = new RequestForDataBuffer(); zoomManager = ZoomManager.getSingletonInstance(); eveState = EVEState.getSingletonInstance(); yValueModelManager = YValueModelManager.getInstance(); } /** * Access to the singleton instance of the radio data manager * * @return The instance of the radio data manager */ public static RadioDataManager getSingletonInstance() { if (instance == null) { instance = new RadioDataManager(); } return instance; } /** * Adds a radio data manager listener. * * @param l * The listener to add */ public void addRadioManagerListener(RadioDataManagerListener l) { listeners.add(l); } /** * Removes a radio data manager listener. * * @param l * The listener to remove */ public void removeRadioManagerListener(RadioDataManagerListener l) { listeners.remove(l); } /** * Inform the RadioDataManager about the new data that was received. The * RadioDataManagerListeners will be informed about the new received data. * * * @param data * The data received * @param imageID * The ID of the image for which data was received * @param downloadID * The ID of the download batch the image is part of * @param dataSize * The height and width of the data */ public synchronized void dataForIDReceived(byte[] data, Long imageID, Long downloadID, Rectangle dataSize) { fireDataforIDReceived(data, imageID, downloadID, dataSize); } /** * Removes the given download request data. The data is removed from the * line selector model. The images are removed from the cache. * * The listeners are informed about the removal of the download request * data. * * @param drd * The download request data that should be removed */ public void removeDownloadRequestData(DownloadRequestData drd) { this.downloadRequestData.remove(drd.getDownloadID()); lineDataSelectorModel.removeLineData(drd); for (Long imageID : drd.getRadioImages().keySet()) { cache.remove(imageID, drd.getPlotIdentifier()); } fireDownloadRequestDataRemoved(drd); } /** * Changed the visibility of the download request data. All radio data * manager listeners are informed. * * * @param drd * The download request data for which the visiblility is changed */ public void downloadRequestDataVisibilityChanged(DownloadRequestData drd) { fireDownloadRequestDataVisibilityChanged(drd); } /** * Request the radio data manager for new data. * * As long as the mouse is dragged no new data is requested. This to improve * the responsiveness of the program. * * This function can be called asynchronously. A request buffer is used to * store the all the calls. As long as there are requests in the buffer * function continues. * * @param xStart * The start time for which new data is requested * @param xEnd * The end time for which new data is requested * @param yStart * The start frequency for which new data is requested * @param yEnd * The end frequency for which new data is requested * @param xRatio * The x-ratio (time per pixel) * @param yRatio * The y-ratio (frequency per pixel) * @param iDs * The download ID-s for which new data is requested * @param plotIdentifier * The identifier of the plot for which new data is requested */ public void requestForData(Date xStart, Date xEnd, double yStart, double yEnd, double xRatio, double yRatio, List<Long> iDs, String plotIdentifier) { Long start = System.currentTimeMillis(); Log.trace("Request for data : " + id + " time " + start); if (!eveState.isMouseTimeIntervalDragging() && !eveState.isMouseValueIntervalDragging()) { Log.trace("mouse is not dragged"); if (!requestBuffer.hasData()) { requestBuffer.addRequestConfig(new RequestConfig(xStart, xEnd, yStart, yEnd, xRatio, yRatio, iDs)); while (requestBuffer.hasData()) { RequestConfig requestConfig = requestBuffer.getData(); synchronized (downloadRequestData) { handleRequestConfig(requestConfig, xStart, xEnd, yStart, yEnd, plotIdentifier); } } } else { Log.trace("Add request to buffer"); requestBuffer.addRequestConfig(new RequestConfig(xStart, xEnd, yStart, yEnd, xRatio, yRatio, iDs)); } } else { Log.trace("Mouse is dragged"); } long end = System.currentTimeMillis(); Log.trace("Finished request for data id: " + id + " time : " + end + " in " + (end - start) + " milliseconds"); id++; } /** * Informs the radio data manager about an image, identified by imageID from * download identified by downloadID, finished its downloading? * * * @param imageID * The image id of the image that finished downloading * @param downloadID * The download id of the batch of which the image was part */ public void finishedDownloadingID(Long imageID, Long downloadID) { synchronized (downloadRequestData) { DownloadRequestData drd = this.downloadRequestData.get(downloadID); if (drd != null) { RadioImage image = drd.getRadioImages().get(imageID); if (image != null) { image.setDownloading(false); } boolean isDownloading = false; for (RadioImage im : drd.getRadioImages().values()) { if (im.isDownloading()) { isDownloading = true; break; } } if (!isDownloading) { drd.setDownloading(false); lineDataSelectorModel.downloadFinished(drd); } } } } /* * RadioDownloadListener */ @Override public void intervalTooBig(Date requestedStartTime, Date requestedEndTime, long ID, String identifier) { DownloadRequestData drd = new DownloadRequestData(ID, identifier); downloadRequestData.put(ID, drd); lineDataSelectorModel.addLineData(drd); fireIntervalTooBig(ID, identifier); fireNewDataAvailable(drd, ID); fireDownloadRequestAnswered(new Interval<Date>(requestedStartTime, requestedEndTime), ID, identifier); } @Override public void newJPXFilesDownloaded(List<DownloadedJPXData> jpxFiles, Date requestedStartTime, Date requestedEndTime, Long downloadID, String plotIdentifier) { Log.trace("Init the download request data in radio data manager"); synchronized (downloadRequestData) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); DownloadRequestData drd = new DownloadRequestData(downloadID, plotIdentifier); drd.setDownloading(true); lineDataSelectorModel.addLineData(drd); if (!jpxFiles.isEmpty()) { for (DownloadedJPXData djd : jpxFiles) { handleDownloadedJPXData(djd, sdf, drd, downloadID, plotIdentifier); } } this.downloadRequestData.put(downloadID, drd); defineMaxBounds(downloadID, plotIdentifier); fireNewDataAvailable(drd, downloadID); fireDownloadRequestAnswered(new Interval<Date>(requestedStartTime, requestedEndTime), downloadID, plotIdentifier); } } @Override public void newAdditionalDataDownloaded(List<DownloadedJPXData> jpxFiles, Long downloadID, String plotIdentifier, double ratioX, double ratioY) { synchronized (downloadRequestData) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); DownloadRequestData drd = downloadRequestData.get(downloadID); drd.setDownloading(true); lineDataSelectorModel.downloadStarted(drd); for (DownloadedJPXData djd : jpxFiles) { handleAdditionalJPXData(djd, ratioX, ratioY, downloadID, drd, sdf, plotIdentifier); } this.downloadRequestData.put(downloadID, drd); defineMaxBounds(downloadID, plotIdentifier); fireNewDataAvailable(drd, downloadID); } } @Override public void newNoData(List<Interval<Date>> noDataList, String identifier, long downloadID) { if (!eveState.isMouseTimeIntervalDragging() && !eveState.isMouseValueIntervalDragging()) { fireNoDataIntervalsReceived(noDataList, downloadID, identifier); } } /** * Define the maximum bound of the frequency interval. The y-value model is * updated. * * @param downloadID * The download ID for which the bounds are defined * @param plotIdentifier * The plot identifier for which the bound are defined */ private void defineMaxBounds(Long downloadID, String plotIdentifier) { synchronized (downloadRequestData) { FrequencyInterval maxFrequencyInterval = new FrequencyInterval(); DownloadRequestData drd = this.downloadRequestData.get(downloadID); if (drd != null) { Map<Long, RadioImage> radioImages = drd.getRadioImages(); if (!radioImages.isEmpty()) { int localMinFrequency = -1; int localMaxFrequency = -1; boolean first = true; for (RadioImage image : radioImages.values()) { if (first) { localMinFrequency = image.getFreqInterval().getStart(); localMaxFrequency = image.getFreqInterval().getEnd(); first = false; } else { if (image.getFreqInterval().getStart() < localMinFrequency) { localMinFrequency = image.getFreqInterval().getStart(); } if (image.getFreqInterval().getEnd() > localMaxFrequency) { localMaxFrequency = image.getFreqInterval().getEnd(); } } } maxFrequencyInterval = new FrequencyInterval(localMinFrequency, localMaxFrequency); } else { maxFrequencyInterval = new FrequencyInterval(0, 0); } } YValueModel yValueModel = yValueModelManager.getYValueModel(plotIdentifier); yValueModel.setAvailableYMin(maxFrequencyInterval.getStart()); yValueModel.setAvailableYMax(maxFrequencyInterval.getEnd()); } } /** * Informs all RadioDataManagerListener of new received data. * * @param data * The data received * @param imageID * The ID of the image for which data was received * @param downloadID * The ID of the download batch the image is part of * @param dataSize * The height and width of the data */ private void fireDataforIDReceived(byte[] data, Long imageID, Long downloadID, Rectangle dataSize) { synchronized (downloadRequestData) { DownloadRequestData drd = downloadRequestData.get(downloadID); if (drd != null) { RadioImage image = drd.getRadioImages().get(imageID); if (image != null) { synchronized (image) { image.setLastDataSize(dataSize); if (image.getVisibleImageFreqInterval() != null && image.getVisibleImageTimeInterval() != null) { for (RadioDataManagerListener l : listeners) { l.newDataForIDReceived(data, image.getVisibleImageTimeInterval(), image.getVisibleImageFreqInterval(), dataSize, downloadID, drd.getPlotIdentifier(), imageID); } } } } else { // Log.debug("The image was null"); } } else { // Log.debug("Download request data was null"); } } } /** * Informs the radio data manager listeners about new available data. * * @param drd * The available data * @param iD * The download id */ private void fireNewDataAvailable(DownloadRequestData drd, long iD) { for (RadioDataManagerListener l : listeners) { l.newDataAvailable(drd, iD); } } /** * Informs the radio data managers listeners about data that was removed. * * @param drd * The data that was removed */ private void fireDownloadRequestDataRemoved(DownloadRequestData drd) { for (RadioDataManagerListener l : listeners) { l.downloadRequestDataRemoved(drd, drd.getDownloadID()); } } /** * Informs the radio data manager listeners about the data visibility that * was changed. * * @param drd * The download request data for which the data visibility was * changed. */ private void fireDownloadRequestDataVisibilityChanged(DownloadRequestData drd) { for (RadioDataManagerListener l : listeners) { l.downloadRequestDataVisibilityChanged(drd, drd.getDownloadID()); } lineDataSelectorModel.lineDataElementUpdated(drd); } /** * Informs the radio data manager listeners about the download request that * was answered. * * @param timeInterval * The time interval over which the request was answered * @param downloadID * The download id for which the request was answered * @param plotIdentifier * The identifier of the plot for which the request as answered */ private void fireDownloadRequestAnswered(Interval<Date> timeInterval, long downloadID, String plotIdentifier) { for (RadioDataManagerListener l : listeners) { l.downloadRequestAnswered(timeInterval, downloadID, plotIdentifier); } } /** * Function handles a request configuration. * * @param requestConfig * The request configuration to be handled * @param xStart * The start date of the currently visible time interval * @param xEnd * The end date of the currently visible time interval * @param yStart * The start value of the currently visible frequency interval * @param yEnd * The end value of the currently visible frequency interval * @param plotIdentifier * The identifier of the plot */ private void handleRequestConfig(RequestConfig requestConfig, Date xStart, Date xEnd, double yStart, double yEnd, String plotIdentifier) { Log.trace("Request for data in interval " + requestConfig.getxStart() + " - " + requestConfig.getxEnd()); Log.trace("Request for data in frequency interval " + requestConfig.getyStart() + " - " + requestConfig.getyEnd()); if (requestConfig.getxEnd().getTime() - requestConfig.getxStart().getTime() > EVESettings.MAXIMUM_INTERVAL_RANGE_MILLI_SEC_REQ) { Log.trace("Interval too big"); for (Long id : requestConfig.getIDs()) { fireIntervalTooBig(id, plotIdentifier); } } else { RadioImageCacheResult result = cache.getRadioImageCacheResultForInterval(requestConfig.getxStart(), requestConfig.getxEnd(), 24L * 60 * 60 * 1000, plotIdentifier); for (Long id : requestConfig.getIDs()) { DownloadRequestData drd = downloadRequestData.get(id); if (drd != null) { downloader.requestAndOpenIntervals(result.getMissingInterval(), id, drd.getPlotIdentifier(), requestConfig.getxRatio(), requestConfig.getyRatio()); } else { Log.trace("drd is null"); } } for (Long id : requestConfig.getIDs()) { DownloadRequestData drd = downloadRequestData.get(id); if (drd != null) { fireClearSavedImages(id, result.getToRemove(), drd.getPlotIdentifier()); Log.trace("Size of available images : " + result.getAvailableData().size()); for (DownloadedJPXData jpxData : result.getAvailableData()) { handleAvailableData(jpxData, xStart, xEnd, yStart, yEnd, plotIdentifier, drd); } } } } } /** * Handles new available data send by the radio downloader * * @param xStart * The start time of the currently visible time interval * @param xEnd * The end time of the currently visible time interval * @param yStart * The start frequency of the currently visible frequency * interval * @param yEnd * The end frequency of the currently visible frequency interval * @param jpxData * The downloaded jpx data that should be handled * @param plotIdentifier * The identifier of the plot * @param drd * The download request data * */ private void handleAvailableData(DownloadedJPXData jpxData, Date xStart, Date xEnd, double yStart, double yEnd, String plotIdentifier, DownloadRequestData drd) { RadioImage ri = drd.getRadioImages().get(jpxData.getImageID()); if (ri != null) { synchronized (ri) { ri.setVisibleIntervals(xStart, xEnd, (int) Math.round(yStart), (int) Math.round(yEnd)); if (ri.getVisibleImageFreqInterval() != null && ri.getVisibleImageTimeInterval() != null) { Interval<Date> visibleDateInterval = ri.getVisibleImageTimeInterval(); FrequencyInterval visibleFrequencyInterval = ri.getVisibleImageFreqInterval(); if (!visibleDateInterval.getStart().equals(visibleDateInterval.getEnd())) { Log.trace("Visible start time : " + visibleDateInterval.getStart().getTime() + " Date : " + visibleDateInterval.getStart()); Log.trace("Visible end time : " + visibleDateInterval.getEnd().getTime() + " Date : " + visibleDateInterval.getEnd()); Rectangle viewport = zoomManager.getAvailableSpaceForInterval(visibleDateInterval.getStart(), visibleDateInterval.getEnd(), visibleFrequencyInterval.getStart(), visibleFrequencyInterval.getEnd(), id, plotIdentifier); View v = jpxData.getView(); JHVJP2View jp2View = v.getAdapter(JHVJP2View.class); if (jp2View != null) { jp2View.setViewport(new ViewportAdapter(new StaticViewport(new Vector2dInt(viewport.width, viewport.height))), new ChangeEvent()); Rectangle roi = ri.getROI(); Log.trace("*********************************************"); Log.trace("requested interval : " + xStart + " - " + xEnd + " , " + yStart + " - " + yEnd); Log.trace("image id : " + ri.getRadioImageID()); Log.trace("image interval : " + ri.getTimeInterval().getStart() + " - " + ri.getTimeInterval().getEnd() + " , " + ri.getFreqInterval().getStart() + " - " + ri.getFreqInterval().getEnd()); Log.trace("visible interval : " + ri.getVisibleImageTimeInterval().getStart() + " - " + ri.getVisibleImageTimeInterval().getEnd() + " , " + ri.getVisibleImageFreqInterval().getStart() + " - " + ri.getVisibleImageFreqInterval().getEnd()); Log.trace("viewport[width-height] : " + viewport.width + " - " + viewport.height); Log.trace("ROI [x0,y0,width,height] : " + roi.x + "," + roi.y + "," + roi.width + "," + roi.height); Log.trace("*********************************************"); HelioviewerMetaData md = (HelioviewerMetaData) jp2View.getMetadata(); Double mpp = md.getUnitsPerPixel(); if (jp2View.setRegion(new RegionAdapter(new StaticRegion(roi.getX() * mpp, roi.getY() * mpp, new Vector2dDouble(roi.getWidth() * mpp, roi.getHeight() * mpp))), new ChangeEvent())) { Log.trace("The region is changed"); } else { Log.trace("The region has not changed send a data not changed for image id : " + ri.getRadioImageID()); if (ri.getLastDataSize() != null) { fireDataNotChanged(ri.getVisibleImageTimeInterval(), ri.getVisibleImageFreqInterval(), ri.getLastDataSize(), drd.getDownloadID(), drd.getPlotIdentifier(), ri.getRadioImageID()); } else { Log.trace("Last data size was null for radio image id : " + ri.getRadioImageID()); } } } } else { Log.trace("Start and end date of the visible interval were the same. No data requested"); } } } } } /** * Instructs the radio data manager listeners to clear the saved images in * the list. * * @param downloadID * The download identifier for which the images should be removed * @param toRemove * The list of image identifiers that should be removed * @param plotIdentifier * The plot identifier for which the image should be removed */ private void fireClearSavedImages(Long downloadID, List<Long> toRemove, String plotIdentifier) { Log.trace("Clear images for downloadID " + downloadID + " and plotIdentifier " + plotIdentifier + " nr of elements to remove: " + toRemove.size()); for (Long imageID : toRemove) { for (RadioDataManagerListener l : listeners) { l.clearAllSavedImagesForID(downloadID, imageID, plotIdentifier); } } } /** * Instructs the radio data managers about data that was not changed. * * @param timeInterval * The visible interval over which the data did not change * @param freqInterval * The visible frequency interval over which the data did not * change * @param rectangle * The area available for the image * @param downloadID * The download identifier for which the data did not change * @param plotIdentifier * The plot identifier for which the data did not change * @param imageID * The image identifier for which the data did not change */ private void fireDataNotChanged(Interval<Date> timeInterval, FrequencyInterval freqInterval, Rectangle rectangle, Long downloadID, String plotIdentifier, long imageID) { List<Long> tempList = new ArrayList<Long>(); tempList.add(downloadID); for (RadioDataManagerListener l : listeners) { l.dataNotChanged(timeInterval, freqInterval, rectangle, tempList, plotIdentifier, imageID); } } /** * Informs the radio data manager listeners about a request for a too big * interval * * @param downloadID * The download identifier for which the requested interval was * too big * @param plotIdentifier * The plot identifier for which the request was too big */ private void fireIntervalTooBig(long downloadID, String plotIdentifier) { for (RadioDataManagerListener l : listeners) { l.intervalTooBig(downloadID, plotIdentifier); } } /** * Handles newly downloaded jpx-data. * * @param djd * The jpx-data to be handled * @param drd * The corresponding download request data * @param sdf * The used simple data format * @param downloadID * The download identifier for which the data was downloaded * @param plotIdentifier * The plot identifier for which the data was downloaded */ private void handleDownloadedJPXData(DownloadedJPXData djd, SimpleDateFormat sdf, DownloadRequestData drd, Long downloadID, String plotIdentifier) { JHVJP2View jpxView = djd.getView().getAdapter(JHVJP2View.class); if (jpxView != null) { jpxView.setReaderMode(ReaderMode.ONLYFIREONCOMPLETE); JP2Image image = jpxView.getJP2Image(); ResolutionSet rs = image.getResolutionSet(); Interval<Integer> interval = image.getCompositionLayerRange(); LineDataSelectorModel.getSingletonInstance().downloadStarted(drd); for (int i = interval.getStart(); i <= interval.getEnd(); i++) { try { FrequencyInterval fi = new FrequencyInterval(Integer.parseInt(image.get("STARTFRQ", i)), Integer.parseInt(image.get("END-FREQ", i))); Date start = null; Date end = null; try { start = sdf.parse(image.get("DATE-OBS", i)); end = sdf.parse(image.get("DATE-END", i)); } catch (ParseException e) { e.printStackTrace(); Log.error("Could not parse " + image.get("DATE-OBS", i) + " or " + image.get("DATE-END", i)); } List<ResolutionSetting> resolutionSettings = new ArrayList<ResolutionSetting>(); if (start != null && end != null) { Double freqStart = Double.parseDouble(image.get("STARTFRQ", i)); Double freqEnd = Double.parseDouble(image.get("END-FREQ", i)); Interval<Date> dateInterval = new Interval<Date>(start, end); for (int j = 0; j <= rs.getMaxResolutionLevels(); j++) { ResolutionSetting tempResSet = new ResolutionSetting((1.0 * (end.getTime() - start.getTime()) / rs.getResolutionLevel(j).getResolutionBounds().width), ((freqEnd - freqStart) / rs.getResolutionLevel(j).getResolutionBounds().height), j, rs.getResolutionLevel(j).getResolutionBounds().width, rs.getResolutionLevel(j).getResolutionBounds().height, rs.getResolutionLevel(j).getZoomLevel()); resolutionSettings.add(tempResSet); } int highestLevel = -1; ResolutionSetting lastUsedResolutionSetting = null; for (ResolutionSetting rst : resolutionSettings) { if (rst.getResolutionLevel() > highestLevel) { highestLevel = rst.getResolutionLevel(); lastUsedResolutionSetting = rst; } } jpxView.setViewport(new ViewportAdapter(new StaticViewport(lastUsedResolutionSetting.getVec2dIntRepresentation())), new ChangeEvent()); RadioImage tempRs = new RadioImage(djd, downloadID, djd.getImageID(), dateInterval, fi, i, rs, resolutionSettings, plotIdentifier, true); tempRs.setLastUsedResolutionSetting(lastUsedResolutionSetting); drd.addRadioImage(tempRs); } else { Log.error("Start and/or stop is null"); } } catch (IOException e) { Log.error("Some of the metadata could not be read aborting..."); return; } } } } /** * Handles the download of additional jpx-data. * * @param ratioY * The x-ratio of time per pixel * @param ratioX * The y-ratio of frequency per pixel * @param djd * The additional downloaded jpx-data * @param drd * The corresponding download request data * @param downloadID * The download identifier for which additional data was * downloaded * @param sdf * The used simple data format * @param plotIdentifier * The plot identifier for which new additional data was * downloaded * */ private void handleAdditionalJPXData(DownloadedJPXData djd, double ratioX, double ratioY, Long downloadID, DownloadRequestData drd, SimpleDateFormat sdf, String plotIdentifier) { JHVJP2View jpxView = djd.getView().getAdapter(JHVJP2View.class); if (jpxView != null) { jpxView.setReaderMode(ReaderMode.ONLYFIREONCOMPLETE); JP2Image image = jpxView.getJP2Image(); ResolutionSet rs = image.getResolutionSet(); Interval<Integer> interval = image.getCompositionLayerRange(); LineDataSelectorModel.getSingletonInstance().downloadStarted(drd); for (int i = interval.getStart(); i <= interval.getEnd(); i++) { try { FrequencyInterval fi = new FrequencyInterval(Integer.parseInt(image.get("STARTFRQ", i)), Integer.parseInt(image.get("END-FREQ", i))); Date start = null; Date end = null; try { start = sdf.parse(image.get("DATE-OBS", i)); end = sdf.parse(image.get("DATE-END", i)); } catch (ParseException e) { e.printStackTrace(); Log.error("Could not parse " + image.get("DATE-OBS", i) + " or " + image.get("DATE-END", i)); } List<ResolutionSetting> resolutionSettings = new ArrayList<ResolutionSetting>(); if (start != null && end != null) { Double freqStart = Double.parseDouble(image.get("STARTFRQ", i)); Double freqEnd = Double.parseDouble(image.get("END-FREQ", i)); Interval<Date> dateInterval = new Interval<Date>(start, end); for (int j = 0; j <= rs.getMaxResolutionLevels(); j++) { ResolutionSetting tempResSet = new ResolutionSetting((1.0 * (end.getTime() - start.getTime()) / rs.getResolutionLevel(j).getResolutionBounds().width), ((freqEnd - freqStart) / rs.getResolutionLevel(j).getResolutionBounds().height), j, rs.getResolutionLevel(j).getResolutionBounds().width, rs.getResolutionLevel(j).getResolutionBounds().height, rs.getResolutionLevel(j).getZoomLevel()); resolutionSettings.add(tempResSet); } RadioImage tempRs = new RadioImage(djd, downloadID, djd.getImageID(), dateInterval, fi, i, rs, resolutionSettings, plotIdentifier, true); ResolutionSetting lastUsedResolutionSetting = tempRs.defineBestResolutionSetting(ratioX, ratioY); jpxView.setViewport(new ViewportAdapter(new StaticViewport(lastUsedResolutionSetting.getVec2dIntRepresentation())), new ChangeEvent()); tempRs.setLastUsedResolutionSetting(lastUsedResolutionSetting); drd.addRadioImage(tempRs); } else { Log.error("Start and/or stop is null"); } } catch (IOException e) { return; } } } } /** * Informs radio data manager listeners about interval with no data that * where reseive. * * @param noDataList * A list with interval for which no data was received * @param downloadID * The download identifier for which intervals with no data was * received * @param plotIdentifier * The plot identifier for which intervals with no data were * received */ private void fireNoDataIntervalsReceived(List<Interval<Date>> noDataList, Long downloadID, String plotIdentifier) { for (RadioDataManagerListener l : listeners) { l.noDataInterval(noDataList, downloadID, plotIdentifier); } } }
plugins/jhv-eveplugin/src/org/helioviewer/plugins/eveplugin/radio/data/RadioDataManager.java
package org.helioviewer.plugins.eveplugin.radio.data; import java.awt.Rectangle; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.helioviewer.base.logging.Log; import org.helioviewer.base.math.Interval; import org.helioviewer.base.math.Vector2dDouble; import org.helioviewer.base.math.Vector2dInt; import org.helioviewer.plugins.eveplugin.EVEState; import org.helioviewer.plugins.eveplugin.radio.model.ResolutionSetting; import org.helioviewer.plugins.eveplugin.radio.model.YValueModel; import org.helioviewer.plugins.eveplugin.radio.model.YValueModelManager; import org.helioviewer.plugins.eveplugin.radio.model.ZoomManager; import org.helioviewer.plugins.eveplugin.settings.EVESettings; import org.helioviewer.plugins.eveplugin.view.linedataselector.LineDataSelectorModel; import org.helioviewer.viewmodel.changeevent.ChangeEvent; import org.helioviewer.viewmodel.metadata.HelioviewerMetaData; import org.helioviewer.viewmodel.region.RegionAdapter; import org.helioviewer.viewmodel.region.StaticRegion; import org.helioviewer.viewmodel.view.View; import org.helioviewer.viewmodel.view.jp2view.JHVJP2View; import org.helioviewer.viewmodel.view.jp2view.JHVJP2View.ReaderMode; import org.helioviewer.viewmodel.view.jp2view.JP2Image; import org.helioviewer.viewmodel.view.jp2view.image.ResolutionSet; import org.helioviewer.viewmodel.viewport.StaticViewport; import org.helioviewer.viewmodel.viewport.ViewportAdapter; /** * The radio data manager manages all the downloaded data for radio * spectrograms. * * It receives all of its input from the radio downloader as listener of the * radio downloader. * * @author [email protected] * */ public class RadioDataManager implements RadioDownloaderListener { /** The singleton instance of the class. */ private static RadioDataManager instance; /** A list collecting all the radio data manager listeners. */ private List<RadioDataManagerListener> listeners; /** A map keeping the download request data. */ private Map<Long, DownloadRequestData> downloadRequestData; /** Instance of the radio downloader */ private RadioDownloader downloader; /** A buffer holding all the requests for data. */ private RequestForDataBuffer requestBuffer; /** The instance of the line data selector model */ private LineDataSelectorModel lineDataSelectorModel; /** Instance of the radio image cache */ private RadioImageCache cache; /** Instance of the zoom manager */ private ZoomManager zoomManager; /** Id for identifying the requests for data. */ private long id = 0; /** Instance of eve state */ private EVEState eveState; /** INstance of the y-value model manager */ private YValueModelManager yValueModelManager; /** * private constructor used when the instance is requested for the first * time. * */ private RadioDataManager() { listeners = new ArrayList<RadioDataManagerListener>(); downloadRequestData = new HashMap<Long, DownloadRequestData>(); downloader = RadioDownloader.getSingletonInstance(); downloader.addRadioDownloaderListener(this); lineDataSelectorModel = LineDataSelectorModel.getSingletonInstance(); cache = RadioImageCache.getInstance(); requestBuffer = new RequestForDataBuffer(); zoomManager = ZoomManager.getSingletonInstance(); eveState = EVEState.getSingletonInstance(); yValueModelManager = YValueModelManager.getInstance(); } /** * Access to the singleton instance of the radio data manager * * @return The instance of the radio data manager */ public static RadioDataManager getSingletonInstance() { if (instance == null) { instance = new RadioDataManager(); } return instance; } /** * Adds a radio data manager listener. * * @param l * The listener to add */ public void addRadioManagerListener(RadioDataManagerListener l) { listeners.add(l); } /** * Removes a radio data manager listener. * * @param l * The listener to remove */ public void removeRadioManagerListener(RadioDataManagerListener l) { listeners.remove(l); } /** * Inform the RadioDataManager about the new data that was received. The * RadioDataManagerListeners will be informed about the new received data. * * * @param data * The data received * @param imageID * The ID of the image for which data was received * @param downloadID * The ID of the download batch the image is part of * @param dataSize * The height and width of the data */ public synchronized void dataForIDReceived(byte[] data, Long imageID, Long downloadID, Rectangle dataSize) { fireDataforIDReceived(data, imageID, downloadID, dataSize); } /** * Removes the given download request data. The data is removed from the * line selector model. The images are removed from the cache. * * The listeners are informed about the removal of the download request * data. * * @param drd * The download request data that should be removed */ public void removeDownloadRequestData(DownloadRequestData drd) { this.downloadRequestData.remove(drd.getDownloadID()); lineDataSelectorModel.removeLineData(drd); for (Long imageID : drd.getRadioImages().keySet()) { cache.remove(imageID, drd.getPlotIdentifier()); } fireDownloadRequestDataRemoved(drd); } /** * Changed the visibility of the download request data. All radio data * manager listeners are informed. * * * @param drd * The download request data for which the visiblility is changed */ public void downloadRequestDataVisibilityChanged(DownloadRequestData drd) { fireDownloadRequestDataVisibilityChanged(drd); } /** * Request the radio data manager for new data. * * As long as the mouse is dragged no new data is requested. This to improve * the responsiveness of the program. * * This function can be called asynchronously. A request buffer is used to * store the all the calls. As long as there are requests in the buffer * function continues. * * @param xStart * The start time for which new data is requested * @param xEnd * The end time for which new data is requested * @param yStart * The start frequency for which new data is requested * @param yEnd * The end frequency for which new data is requested * @param xRatio * The x-ratio (time per pixel) * @param yRatio * The y-ratio (frequency per pixel) * @param iDs * The download ID-s for which new data is requested * @param plotIdentifier * The identifier of the plot for which new data is requested */ public void requestForData(Date xStart, Date xEnd, double yStart, double yEnd, double xRatio, double yRatio, List<Long> iDs, String plotIdentifier) { Long start = System.currentTimeMillis(); Log.trace("Request for data : " + id + " time " + start); if (!eveState.isMouseTimeIntervalDragging() && !eveState.isMouseValueIntervalDragging()) { Log.trace("mouse is not dragged"); if (!requestBuffer.hasData()) { requestBuffer.addRequestConfig(new RequestConfig(xStart, xEnd, yStart, yEnd, xRatio, yRatio, iDs)); while (requestBuffer.hasData()) { RequestConfig requestConfig = requestBuffer.getData(); synchronized (downloadRequestData) { handleRequestConfig(requestConfig, xStart, xEnd, yStart, yEnd, plotIdentifier); } } } else { Log.trace("Add request to buffer"); requestBuffer.addRequestConfig(new RequestConfig(xStart, xEnd, yStart, yEnd, xRatio, yRatio, iDs)); } } else { Log.trace("Mouse is dragged"); } long end = System.currentTimeMillis(); Log.trace("Finished request for data id: " + id + " time : " + end + " in " + (end - start) + " milliseconds"); id++; } /** * Informs the radio data manager about an image, identified by imageID from * download identified by downloadID, finished its downloading? * * * @param imageID * The image id of the image that finished downloading * @param downloadID * The download id of the batch of which the image was part */ public void finishedDownloadingID(Long imageID, Long downloadID) { synchronized (downloadRequestData) { DownloadRequestData drd = this.downloadRequestData.get(downloadID); if (drd != null) { RadioImage image = drd.getRadioImages().get(imageID); if (image != null) { image.setDownloading(false); } boolean isDownloading = false; for (RadioImage im : drd.getRadioImages().values()) { if (im.isDownloading()) { isDownloading = true; break; } } if (!isDownloading) { drd.setDownloading(false); lineDataSelectorModel.downloadFinished(drd); } } } } /* * RadioDownloadListener */ @Override public void intervalTooBig(Date requestedStartTime, Date requestedEndTime, long ID, String identifier) { DownloadRequestData drd = new DownloadRequestData(ID, identifier); downloadRequestData.put(ID, drd); lineDataSelectorModel.addLineData(drd); fireIntervalTooBig(ID, identifier); fireNewDataAvailable(drd, ID); fireDownloadRequestAnswered(new Interval<Date>(requestedStartTime, requestedEndTime), ID, identifier); } @Override public void newJPXFilesDownloaded(List<DownloadedJPXData> jpxFiles, Date requestedStartTime, Date requestedEndTime, Long downloadID, String plotIdentifier) { Log.trace("Init the download request data in radio data manager"); synchronized (downloadRequestData) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); DownloadRequestData drd = new DownloadRequestData(downloadID, plotIdentifier); drd.setDownloading(true); lineDataSelectorModel.addLineData(drd); if (!jpxFiles.isEmpty()) { for (DownloadedJPXData djd : jpxFiles) { handleDownloadedJPXData(djd, sdf, drd, downloadID, plotIdentifier); } } this.downloadRequestData.put(downloadID, drd); defineMaxBounds(downloadID, plotIdentifier); fireNewDataAvailable(drd, downloadID); fireDownloadRequestAnswered(new Interval<Date>(requestedStartTime, requestedEndTime), downloadID, plotIdentifier); } } @Override public void newAdditionalDataDownloaded(List<DownloadedJPXData> jpxFiles, Long downloadID, String plotIdentifier, double ratioX, double ratioY) { synchronized (downloadRequestData) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); DownloadRequestData drd = downloadRequestData.get(downloadID); drd.setDownloading(true); lineDataSelectorModel.downloadStarted(drd); for (DownloadedJPXData djd : jpxFiles) { handleAdditionalJPXData(djd, ratioX, ratioY, downloadID, drd, sdf, plotIdentifier); } this.downloadRequestData.put(downloadID, drd); defineMaxBounds(downloadID, plotIdentifier); fireNewDataAvailable(drd, downloadID); } } @Override public void newNoData(List<Interval<Date>> noDataList, String identifier, long downloadID) { if (!eveState.isMouseTimeIntervalDragging() && !eveState.isMouseValueIntervalDragging()) { fireNoDataIntervalsReceived(noDataList, downloadID, identifier); } } /** * Define the maximum bound of the frequency interval. The y-value model is * updated. * * @param downloadID * The download ID for which the bounds are defined * @param plotIdentifier * The plot identifier for which the bound are defined */ private void defineMaxBounds(Long downloadID, String plotIdentifier) { synchronized (downloadRequestData) { FrequencyInterval maxFrequencyInterval = new FrequencyInterval(); DownloadRequestData drd = this.downloadRequestData.get(downloadID); if (drd != null) { Map<Long, RadioImage> radioImages = drd.getRadioImages(); if (!radioImages.isEmpty()) { int localMinFrequency = -1; int localMaxFrequency = -1; boolean first = true; for (RadioImage image : radioImages.values()) { if (first) { localMinFrequency = image.getFreqInterval().getStart(); localMaxFrequency = image.getFreqInterval().getEnd(); first = false; } else { if (image.getFreqInterval().getStart() < localMinFrequency) { localMinFrequency = image.getFreqInterval().getStart(); } if (image.getFreqInterval().getEnd() > localMaxFrequency) { localMaxFrequency = image.getFreqInterval().getEnd(); } } } maxFrequencyInterval = new FrequencyInterval(localMinFrequency, localMaxFrequency); } else { maxFrequencyInterval = new FrequencyInterval(0, 0); } } YValueModel yValueModel = yValueModelManager.getYValueModel(plotIdentifier); yValueModel.setAvailableYMin(maxFrequencyInterval.getStart()); yValueModel.setAvailableYMax(maxFrequencyInterval.getEnd()); } } /** * Informs all RadioDataManagerListener of new received data. * * @param data * The data received * @param imageID * The ID of the image for which data was received * @param downloadID * The ID of the download batch the image is part of * @param dataSize * The height and width of the data */ private void fireDataforIDReceived(byte[] data, Long imageID, Long downloadID, Rectangle dataSize) { synchronized (downloadRequestData) { DownloadRequestData drd = downloadRequestData.get(downloadID); if (drd != null) { RadioImage image = drd.getRadioImages().get(imageID); if (image != null) { synchronized (image) { image.setLastDataSize(dataSize); if (image.getVisibleImageFreqInterval() != null && image.getVisibleImageTimeInterval() != null) { for (RadioDataManagerListener l : listeners) { l.newDataForIDReceived(data, image.getVisibleImageTimeInterval(), image.getVisibleImageFreqInterval(), dataSize, downloadID, drd.getPlotIdentifier(), imageID); } } } } else { // Log.debug("The image was null"); } } else { // Log.debug("Download request data was null"); } } } /** * Informs the radio data manager listeners about new available data. * * @param drd * The available data * @param iD * The download id */ private void fireNewDataAvailable(DownloadRequestData drd, long iD) { for (RadioDataManagerListener l : listeners) { l.newDataAvailable(drd, iD); } } /** * Informs the radio data managers listeners about data that was removed. * * @param drd * The data that was removed */ private void fireDownloadRequestDataRemoved(DownloadRequestData drd) { for (RadioDataManagerListener l : listeners) { l.downloadRequestDataRemoved(drd, drd.getDownloadID()); } } /** * Informs the radio data manager listeners about the data visibility that * was changed. * * @param drd * The download request data for which the data visibility was * changed. */ private void fireDownloadRequestDataVisibilityChanged(DownloadRequestData drd) { for (RadioDataManagerListener l : listeners) { l.downloadRequestDataVisibilityChanged(drd, drd.getDownloadID()); } lineDataSelectorModel.lineDataElementUpdated(drd); } /** * Informs the radio data manager listeners about the download request that * was answered. * * @param timeInterval * The time interval over which the request was answered * @param downloadID * The download id for which the request was answered * @param plotIdentifier * The identifier of the plot for which the request as answered */ private void fireDownloadRequestAnswered(Interval<Date> timeInterval, long downloadID, String plotIdentifier) { for (RadioDataManagerListener l : listeners) { l.downloadRequestAnswered(timeInterval, downloadID, plotIdentifier); } } /** * Function handles a request configuration. * * @param requestConfig * The request configuration to be handled * @param xStart * The start date of the currently visible time interval * @param xEnd * The end date of the currently visible time interval * @param yStart * The start value of the currently visible frequency interval * @param yEnd * The end value of the currently visible frequency interval * @param plotIdentifier * The identifier of the plot */ private void handleRequestConfig(RequestConfig requestConfig, Date xStart, Date xEnd, double yStart, double yEnd, String plotIdentifier) { Log.trace("Request for data in interval " + requestConfig.getxStart() + " - " + requestConfig.getxEnd()); Log.trace("Request for data in frequency interval " + requestConfig.getyStart() + " - " + requestConfig.getyEnd()); if (requestConfig.getxEnd().getTime() - requestConfig.getxStart().getTime() > EVESettings.MAXIMUM_INTERVAL_RANGE_MILLI_SEC_REQ) { Log.trace("Interval too big"); for (Long id : requestConfig.getIDs()) { fireIntervalTooBig(id, plotIdentifier); } } else { RadioImageCacheResult result = cache.getRadioImageCacheResultForInterval(requestConfig.getxStart(), requestConfig.getxEnd(), 24L * 60 * 60 * 1000, plotIdentifier); for (Long id : requestConfig.getIDs()) { DownloadRequestData drd = downloadRequestData.get(id); if (drd != null) { downloader.requestAndOpenIntervals(result.getMissingInterval(), id, drd.getPlotIdentifier(), requestConfig.getxRatio(), requestConfig.getyRatio()); } else { Log.trace("drd is null"); } } for (Long id : requestConfig.getIDs()) { DownloadRequestData drd = downloadRequestData.get(id); if (drd != null) { fireClearSavedImages(id, result.getToRemove(), drd.getPlotIdentifier()); Log.trace("Size of available images : " + result.getAvailableData().size()); for (DownloadedJPXData jpxData : result.getAvailableData()) { handleAvailableData(jpxData, xStart, xEnd, yStart, yEnd, plotIdentifier, drd); } } } } } /** * Handles new available data send by the radio downloader * * @param xStart * The start time of the currently visible time interval * @param xEnd * The end time of the currently visible time interval * @param yStart * The start frequency of the currently visible frequency * interval * @param yEnd * The end frequency of the currently visible frequency interval * @param jpxData * The downloaded jpx data that should be handled * @param plotIdentifier * The identifier of the plot * @param drd * The download request data * */ private void handleAvailableData(DownloadedJPXData jpxData, Date xStart, Date xEnd, double yStart, double yEnd, String plotIdentifier, DownloadRequestData drd) { RadioImage ri = drd.getRadioImages().get(jpxData.getImageID()); if (ri != null) { synchronized (ri) { ri.setVisibleIntervals(xStart, xEnd, (int) Math.round(yStart), (int) Math.round(yEnd)); if (ri.getVisibleImageFreqInterval() != null && ri.getVisibleImageTimeInterval() != null) { Interval<Date> visibleDateInterval = ri.getVisibleImageTimeInterval(); FrequencyInterval visibleFrequencyInterval = ri.getVisibleImageFreqInterval(); if (!visibleDateInterval.getStart().equals(visibleDateInterval.getEnd())) { Log.trace("Visible start time : " + visibleDateInterval.getStart().getTime() + " Date : " + visibleDateInterval.getStart()); Log.trace("Visible end time : " + visibleDateInterval.getEnd().getTime() + " Date : " + visibleDateInterval.getEnd()); Rectangle viewport = zoomManager.getAvailableSpaceForInterval(visibleDateInterval.getStart(), visibleDateInterval.getEnd(), visibleFrequencyInterval.getStart(), visibleFrequencyInterval.getEnd(), id, plotIdentifier); View v = jpxData.getView(); JHVJP2View jp2View = v.getAdapter(JHVJP2View.class); if (jp2View != null) { jp2View.setViewport(new ViewportAdapter(new StaticViewport(new Vector2dInt(viewport.width, viewport.height))), new ChangeEvent()); Rectangle roi = ri.getROI(); Log.trace("*********************************************"); Log.trace("requested interval : " + xStart + " - " + xEnd + " , " + yStart + " - " + yEnd); Log.trace("image id : " + ri.getRadioImageID()); Log.trace("image interval : " + ri.getTimeInterval().getStart() + " - " + ri.getTimeInterval().getEnd() + " , " + ri.getFreqInterval().getStart() + " - " + ri.getFreqInterval().getEnd()); Log.trace("visible interval : " + ri.getVisibleImageTimeInterval().getStart() + " - " + ri.getVisibleImageTimeInterval().getEnd() + " , " + ri.getVisibleImageFreqInterval().getStart() + " - " + ri.getVisibleImageFreqInterval().getEnd()); Log.trace("viewport[width-height] : " + viewport.width + " - " + viewport.height); Log.trace("ROI [x0,y0,width,height] : " + roi.x + "," + roi.y + "," + roi.width + "," + roi.height); Log.trace("*********************************************"); HelioviewerMetaData md = (HelioviewerMetaData) jp2View.getMetadata(); Double mpp = md.getUnitsPerPixel(); if (jp2View.setRegion(new RegionAdapter(new StaticRegion(roi.getX() * mpp, roi.getY() * mpp, new Vector2dDouble(roi.getWidth() * mpp, roi.getHeight() * mpp))), new ChangeEvent())) { Log.trace("The region is changed"); } else { Log.trace("The region has not changed send a data not changed for image id : " + ri.getRadioImageID()); if (ri.getLastDataSize() != null) { fireDataNotChanged(ri.getVisibleImageTimeInterval(), ri.getVisibleImageFreqInterval(), ri.getLastDataSize(), id, drd.getPlotIdentifier(), ri.getRadioImageID()); } else { Log.trace("Last data size was null for radio image id : " + ri.getRadioImageID()); } } } } else { Log.trace("Start and end date of the visible interval were the same. No data requested"); } } } } } /** * Instructs the radio data manager listeners to clear the saved images in * the list. * * @param downloadID * The download identifier for which the images should be removed * @param toRemove * The list of image identifiers that should be removed * @param plotIdentifier * The plot identifier for which the image should be removed */ private void fireClearSavedImages(Long downloadID, List<Long> toRemove, String plotIdentifier) { Log.trace("Clear images for downloadID " + downloadID + " and plotIdentifier " + plotIdentifier + " nr of elements to remove: " + toRemove.size()); for (Long imageID : toRemove) { for (RadioDataManagerListener l : listeners) { l.clearAllSavedImagesForID(downloadID, imageID, plotIdentifier); } } } /** * Instructs the radio data managers about data that was not changed. * * @param timeInterval * The visible interval over which the data did not change * @param freqInterval * The visible frequency interval over which the data did not * change * @param rectangle * The area available for the image * @param downloadID * The download identifier for which the data did not change * @param plotIdentifier * The plot identifier for which the data did not change * @param imageID * The image identifier for which the data did not change */ private void fireDataNotChanged(Interval<Date> timeInterval, FrequencyInterval freqInterval, Rectangle rectangle, Long downloadID, String plotIdentifier, long imageID) { List<Long> tempList = new ArrayList<Long>(); tempList.add(downloadID); for (RadioDataManagerListener l : listeners) { l.dataNotChanged(timeInterval, freqInterval, rectangle, tempList, plotIdentifier, imageID); } } /** * Informs the radio data manager listeners about a request for a too big * interval * * @param downloadID * The download identifier for which the requested interval was * too big * @param plotIdentifier * The plot identifier for which the request was too big */ private void fireIntervalTooBig(long downloadID, String plotIdentifier) { for (RadioDataManagerListener l : listeners) { l.intervalTooBig(downloadID, plotIdentifier); } } /** * Handles newly downloaded jpx-data. * * @param djd * The jpx-data to be handled * @param drd * The corresponding download request data * @param sdf * The used simple data format * @param downloadID * The download identifier for which the data was downloaded * @param plotIdentifier * The plot identifier for which the data was downloaded */ private void handleDownloadedJPXData(DownloadedJPXData djd, SimpleDateFormat sdf, DownloadRequestData drd, Long downloadID, String plotIdentifier) { JHVJP2View jpxView = djd.getView().getAdapter(JHVJP2View.class); if (jpxView != null) { jpxView.setReaderMode(ReaderMode.ONLYFIREONCOMPLETE); JP2Image image = jpxView.getJP2Image(); ResolutionSet rs = image.getResolutionSet(); Interval<Integer> interval = image.getCompositionLayerRange(); LineDataSelectorModel.getSingletonInstance().downloadStarted(drd); for (int i = interval.getStart(); i <= interval.getEnd(); i++) { try { FrequencyInterval fi = new FrequencyInterval(Integer.parseInt(image.get("STARTFRQ", i)), Integer.parseInt(image.get("END-FREQ", i))); Date start = null; Date end = null; try { start = sdf.parse(image.get("DATE-OBS", i)); end = sdf.parse(image.get("DATE-END", i)); } catch (ParseException e) { e.printStackTrace(); Log.error("Could not parse " + image.get("DATE-OBS", i) + " or " + image.get("DATE-END", i)); } List<ResolutionSetting> resolutionSettings = new ArrayList<ResolutionSetting>(); if (start != null && end != null) { Double freqStart = Double.parseDouble(image.get("STARTFRQ", i)); Double freqEnd = Double.parseDouble(image.get("END-FREQ", i)); Interval<Date> dateInterval = new Interval<Date>(start, end); for (int j = 0; j <= rs.getMaxResolutionLevels(); j++) { ResolutionSetting tempResSet = new ResolutionSetting((1.0 * (end.getTime() - start.getTime()) / rs.getResolutionLevel(j).getResolutionBounds().width), ((freqEnd - freqStart) / rs.getResolutionLevel(j).getResolutionBounds().height), j, rs.getResolutionLevel(j).getResolutionBounds().width, rs.getResolutionLevel(j).getResolutionBounds().height, rs.getResolutionLevel(j).getZoomLevel()); resolutionSettings.add(tempResSet); } int highestLevel = -1; ResolutionSetting lastUsedResolutionSetting = null; for (ResolutionSetting rst : resolutionSettings) { if (rst.getResolutionLevel() > highestLevel) { highestLevel = rst.getResolutionLevel(); lastUsedResolutionSetting = rst; } } jpxView.setViewport(new ViewportAdapter(new StaticViewport(lastUsedResolutionSetting.getVec2dIntRepresentation())), new ChangeEvent()); RadioImage tempRs = new RadioImage(djd, downloadID, djd.getImageID(), dateInterval, fi, i, rs, resolutionSettings, plotIdentifier, true); tempRs.setLastUsedResolutionSetting(lastUsedResolutionSetting); drd.addRadioImage(tempRs); } else { Log.error("Start and/or stop is null"); } } catch (IOException e) { Log.error("Some of the metadata could not be read aborting..."); return; } } } } /** * Handles the download of additional jpx-data. * * @param ratioY * The x-ratio of time per pixel * @param ratioX * The y-ratio of frequency per pixel * @param djd * The additional downloaded jpx-data * @param drd * The corresponding download request data * @param downloadID * The download identifier for which additional data was * downloaded * @param sdf * The used simple data format * @param plotIdentifier * The plot identifier for which new additional data was * downloaded * */ private void handleAdditionalJPXData(DownloadedJPXData djd, double ratioX, double ratioY, Long downloadID, DownloadRequestData drd, SimpleDateFormat sdf, String plotIdentifier) { JHVJP2View jpxView = djd.getView().getAdapter(JHVJP2View.class); if (jpxView != null) { jpxView.setReaderMode(ReaderMode.ONLYFIREONCOMPLETE); JP2Image image = jpxView.getJP2Image(); ResolutionSet rs = image.getResolutionSet(); Interval<Integer> interval = image.getCompositionLayerRange(); LineDataSelectorModel.getSingletonInstance().downloadStarted(drd); for (int i = interval.getStart(); i <= interval.getEnd(); i++) { try { FrequencyInterval fi = new FrequencyInterval(Integer.parseInt(image.get("STARTFRQ", i)), Integer.parseInt(image.get("END-FREQ", i))); Date start = null; Date end = null; try { start = sdf.parse(image.get("DATE-OBS", i)); end = sdf.parse(image.get("DATE-END", i)); } catch (ParseException e) { e.printStackTrace(); Log.error("Could not parse " + image.get("DATE-OBS", i) + " or " + image.get("DATE-END", i)); } List<ResolutionSetting> resolutionSettings = new ArrayList<ResolutionSetting>(); if (start != null && end != null) { Double freqStart = Double.parseDouble(image.get("STARTFRQ", i)); Double freqEnd = Double.parseDouble(image.get("END-FREQ", i)); Interval<Date> dateInterval = new Interval<Date>(start, end); for (int j = 0; j <= rs.getMaxResolutionLevels(); j++) { ResolutionSetting tempResSet = new ResolutionSetting((1.0 * (end.getTime() - start.getTime()) / rs.getResolutionLevel(j).getResolutionBounds().width), ((freqEnd - freqStart) / rs.getResolutionLevel(j).getResolutionBounds().height), j, rs.getResolutionLevel(j).getResolutionBounds().width, rs.getResolutionLevel(j).getResolutionBounds().height, rs.getResolutionLevel(j).getZoomLevel()); resolutionSettings.add(tempResSet); } RadioImage tempRs = new RadioImage(djd, downloadID, djd.getImageID(), dateInterval, fi, i, rs, resolutionSettings, plotIdentifier, true); ResolutionSetting lastUsedResolutionSetting = tempRs.defineBestResolutionSetting(ratioX, ratioY); jpxView.setViewport(new ViewportAdapter(new StaticViewport(lastUsedResolutionSetting.getVec2dIntRepresentation())), new ChangeEvent()); tempRs.setLastUsedResolutionSetting(lastUsedResolutionSetting); drd.addRadioImage(tempRs); } else { Log.error("Start and/or stop is null"); } } catch (IOException e) { return; } } } } /** * Informs radio data manager listeners about interval with no data that * where reseive. * * @param noDataList * A list with interval for which no data was received * @param downloadID * The download identifier for which intervals with no data was * received * @param plotIdentifier * The plot identifier for which intervals with no data were * received */ private void fireNoDataIntervalsReceived(List<Interval<Date>> noDataList, Long downloadID, String plotIdentifier) { for (RadioDataManagerListener l : listeners) { l.noDataInterval(noDataList, downloadID, plotIdentifier); } } }
Fixed null pointer git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@1364 b4e469a2-07ce-4b26-9273-4d7d95a670c7
plugins/jhv-eveplugin/src/org/helioviewer/plugins/eveplugin/radio/data/RadioDataManager.java
Fixed null pointer
<ide><path>lugins/jhv-eveplugin/src/org/helioviewer/plugins/eveplugin/radio/data/RadioDataManager.java <ide> } else { <ide> Log.trace("The region has not changed send a data not changed for image id : " + ri.getRadioImageID()); <ide> if (ri.getLastDataSize() != null) { <del> fireDataNotChanged(ri.getVisibleImageTimeInterval(), ri.getVisibleImageFreqInterval(), ri.getLastDataSize(), id, drd.getPlotIdentifier(), ri.getRadioImageID()); <add> fireDataNotChanged(ri.getVisibleImageTimeInterval(), ri.getVisibleImageFreqInterval(), ri.getLastDataSize(), drd.getDownloadID(), drd.getPlotIdentifier(), ri.getRadioImageID()); <ide> } else { <ide> Log.trace("Last data size was null for radio image id : " + ri.getRadioImageID()); <ide> }
Java
mit
43aecf3c0b5376f6d5abaacdf273648c2fcc517b
0
reasm/reasm-m68k
package org.reasm.m68k.source; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.List; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.reasm.SubstringBounds; import org.reasm.m68k.parseerrors.LabelExpectedParseError; import org.reasm.m68k.testhelpers.EquivalentParseError; import org.reasm.source.ParseError; import org.reasm.source.parseerrors.MismatchedParenthesisParseError; import org.reasm.source.parseerrors.UnterminatedStringParseError; import ca.fragag.text.CharSequenceReader; import ca.fragag.text.GenericCharSequenceReader; /** * Test class for {@link LogicalLineParser}. * * @author Francis Gagné */ @RunWith(Parameterized.class) @SuppressWarnings("javadoc") public class LogicalLineParserTest { private static final ArrayList<Object[]> TEST_DATA = new ArrayList<>(); private static final SubstringBounds[] NO_LABELS = new SubstringBounds[0]; private static final SubstringBounds[] NO_OPERANDS = NO_LABELS; private static final int[] NO_CONTINUATION_CHARACTERS = new int[0]; static { addDataItem("", 0, null, NO_LABELS, null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem(" ", 1, null, NO_LABELS, null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("\t", 1, null, NO_LABELS, null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("a", 1, null, array(bounds(0, 1)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("a ", 2, null, array(bounds(0, 1)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("a:", 2, null, array(bounds(0, 1)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("a: ", 3, null, array(bounds(0, 1)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("a :", 3, null, array(bounds(0, 1)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("abc", 3, null, array(bounds(0, 3)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("abc ", 4, null, array(bounds(0, 3)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem(" a:", 3, null, array(bounds(1, 2)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem(" a: ", 4, null, array(bounds(1, 2)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("abc def:", 8, null, array(bounds(0, 3), bounds(4, 7)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("abc def: ", 9, null, array(bounds(0, 3), bounds(4, 7)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("abc def :", 9, null, array(bounds(0, 3), bounds(4, 7)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("abc: def:", 9, null, array(bounds(0, 3), bounds(5, 8)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem(":", 1, new LabelExpectedParseError(0), array(bounds(0, 0)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("abc::", 5, new LabelExpectedParseError(4), array(bounds(0, 3), bounds(4, 4)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("abc:::", 6, new LabelExpectedParseError(4), array(bounds(0, 3), bounds(4, 4), bounds(5, 5)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem(" a", 2, null, NO_LABELS, bounds(1, 2), NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem(" a ", 3, null, NO_LABELS, bounds(1, 2), NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc", 4, null, NO_LABELS, bounds(1, 4), NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc ", 5, null, NO_LABELS, bounds(1, 4), NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("abc def", 7, null, array(bounds(0, 3)), bounds(4, 7), NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc d", 6, null, NO_LABELS, bounds(1, 4), array(bounds(5, 6)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc d ", 7, null, NO_LABELS, bounds(1, 4), array(bounds(5, 6)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc d ", 8, null, NO_LABELS, bounds(1, 4), array(bounds(5, 6)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc ,", 6, null, NO_LABELS, bounds(1, 4), array(bounds(5, 5), bounds(6, 6)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc def,ghi", 12, null, NO_LABELS, bounds(1, 4), array(bounds(5, 8), bounds(9, 12)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc def, ghi", 13, null, NO_LABELS, bounds(1, 4), array(bounds(5, 8), bounds(10, 13)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc def,ghi,jkl", 16, null, NO_LABELS, bounds(1, 4), array(bounds(5, 8), bounds(9, 12), bounds(13, 16)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc (", 6, new MismatchedParenthesisParseError(5), NO_LABELS, bounds(1, 4), array(bounds(5, 6)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc )", 6, new MismatchedParenthesisParseError(5), NO_LABELS, bounds(1, 4), array(bounds(5, 6)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc )(", 7, new MismatchedParenthesisParseError(5), NO_LABELS, bounds(1, 4), array(bounds(5, 7)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc ()", 7, null, NO_LABELS, bounds(1, 4), array(bounds(5, 7)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc (d)", 8, null, NO_LABELS, bounds(1, 4), array(bounds(5, 8)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc (,)", 8, null, NO_LABELS, bounds(1, 4), array(bounds(5, 8)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc (()", 8, new MismatchedParenthesisParseError(6), NO_LABELS, bounds(1, 4), array(bounds(5, 8)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc ())", 8, new MismatchedParenthesisParseError(7), NO_LABELS, bounds(1, 4), array(bounds(5, 8)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc ())d", 9, new MismatchedParenthesisParseError(7), NO_LABELS, bounds(1, 4), array(bounds(5, 9)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc ()))", 9, new MismatchedParenthesisParseError(7), NO_LABELS, bounds(1, 4), array(bounds(5, 9)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc (())", 9, null, NO_LABELS, bounds(1, 4), array(bounds(5, 9)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc ((d))", 10, null, NO_LABELS, bounds(1, 4), array(bounds(5, 10)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc (d,e)", 10, null, NO_LABELS, bounds(1, 4), array(bounds(5, 10)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc \"", 6, new UnterminatedStringParseError(5), NO_LABELS, bounds(1, 4), array(bounds(5, 6)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc \"d", 7, new UnterminatedStringParseError(5), NO_LABELS, bounds(1, 4), array(bounds(5, 7)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc \"\"", 7, null, NO_LABELS, bounds(1, 4), array(bounds(5, 7)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc \"d\"", 8, null, NO_LABELS, bounds(1, 4), array(bounds(5, 8)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc \",\"", 8, null, NO_LABELS, bounds(1, 4), array(bounds(5, 8)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc \"\\\"", 8, new UnterminatedStringParseError(5), NO_LABELS, bounds(1, 4), array(bounds(5, 8)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc )\"", 7, new MismatchedParenthesisParseError(5), NO_LABELS, bounds(1, 4), array(bounds(5, 7)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc '", 6, new UnterminatedStringParseError(5), NO_LABELS, bounds(1, 4), array(bounds(5, 6)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc 'd", 7, new UnterminatedStringParseError(5), NO_LABELS, bounds(1, 4), array(bounds(5, 7)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc ''", 7, null, NO_LABELS, bounds(1, 4), array(bounds(5, 7)), null, NO_CONTINUATION_CHARACTERS); addDataItem("*", 1, null, NO_LABELS, null, NO_OPERANDS, bounds(0, 1), NO_CONTINUATION_CHARACTERS); addDataItem("*xyz", 4, null, NO_LABELS, null, NO_OPERANDS, bounds(0, 4), NO_CONTINUATION_CHARACTERS); addDataItem(";", 1, null, NO_LABELS, null, NO_OPERANDS, bounds(0, 1), NO_CONTINUATION_CHARACTERS); addDataItem(";xyz", 4, null, NO_LABELS, null, NO_OPERANDS, bounds(0, 4), NO_CONTINUATION_CHARACTERS); addDataItem(" *xyz", 5, null, NO_LABELS, bounds(1, 5), NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem(" ;xyz", 5, null, NO_LABELS, null, NO_OPERANDS, bounds(1, 5), NO_CONTINUATION_CHARACTERS); addDataItem("a;xyz", 5, null, array(bounds(0, 1)), null, NO_OPERANDS, bounds(1, 5), NO_CONTINUATION_CHARACTERS); addDataItem("a:;xyz", 6, null, array(bounds(0, 1)), null, NO_OPERANDS, bounds(2, 6), NO_CONTINUATION_CHARACTERS); addDataItem("a: ;xyz", 7, null, array(bounds(0, 1)), null, NO_OPERANDS, bounds(3, 7), NO_CONTINUATION_CHARACTERS); addDataItem("a :;xyz", 7, null, array(bounds(0, 1)), null, NO_OPERANDS, bounds(3, 7), NO_CONTINUATION_CHARACTERS); addDataItem(" a;xyz", 6, null, NO_LABELS, bounds(1, 2), NO_OPERANDS, bounds(2, 6), NO_CONTINUATION_CHARACTERS); addDataItem(" a ;xyz", 7, null, NO_LABELS, bounds(1, 2), NO_OPERANDS, bounds(3, 7), NO_CONTINUATION_CHARACTERS); addDataItem(" a b;xyz", 8, null, NO_LABELS, bounds(1, 2), array(bounds(3, 4)), bounds(4, 8), NO_CONTINUATION_CHARACTERS); addDataItem(" a b ;xyz", 9, null, NO_LABELS, bounds(1, 2), array(bounds(3, 4)), bounds(5, 9), NO_CONTINUATION_CHARACTERS); addDataItem(" a b,;xyz", 9, null, NO_LABELS, bounds(1, 2), array(bounds(3, 4), bounds(5, 5)), bounds(5, 9), NO_CONTINUATION_CHARACTERS); addDataItem(" a (;xyz", 8, new MismatchedParenthesisParseError(3), NO_LABELS, bounds(1, 2), array(bounds(3, 4)), bounds(4, 8), NO_CONTINUATION_CHARACTERS); addDataItem(" a \";xyz", 8, new UnterminatedStringParseError(3), NO_LABELS, bounds(1, 2), array(bounds(3, 8)), null, NO_CONTINUATION_CHARACTERS); addDataItem("\n", 1, null, NO_LABELS, null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("\n ", 1, null, NO_LABELS, null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("\r", 1, null, NO_LABELS, null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("\r ", 1, null, NO_LABELS, null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("\r\n", 2, null, NO_LABELS, null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("\r\n ", 2, null, NO_LABELS, null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("a\n", 2, null, array(bounds(0, 1)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("a&", 2, null, array(bounds(0, 2)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("a&\n", 3, null, array(bounds(0, 3)), null, NO_OPERANDS, null, new int[] { 1 }); addDataItem("a&\n\n", 4, null, array(bounds(0, 3)), null, NO_OPERANDS, null, new int[] { 1 }); addDataItem("a&\nb", 4, null, array(bounds(0, 4)), null, NO_OPERANDS, null, new int[] { 1 }); addDataItem("a&\rb", 4, null, array(bounds(0, 4)), null, NO_OPERANDS, null, new int[] { 1 }); addDataItem("a&\r\nb", 5, null, array(bounds(0, 5)), null, NO_OPERANDS, null, new int[] { 1 }); addDataItem("a&\n ", 4, null, array(bounds(0, 4)), null, NO_OPERANDS, null, new int[] { 1 }); addDataItem("a&\n \n", 5, null, array(bounds(0, 4)), null, NO_OPERANDS, null, new int[] { 1 }); addDataItem("a&\n b", 5, null, array(bounds(0, 5)), null, NO_OPERANDS, null, new int[] { 1 }); addDataItem("a&\n b", 6, null, array(bounds(0, 6)), null, NO_OPERANDS, null, new int[] { 1 }); addDataItem(" a&", 3, null, NO_LABELS, bounds(1, 3), NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem(" a&\n", 4, null, NO_LABELS, bounds(1, 4), NO_OPERANDS, null, new int[] { 2 }); addDataItem(" a&\nb", 5, null, NO_LABELS, bounds(1, 5), NO_OPERANDS, null, new int[] { 2 }); addDataItem(" a b&", 5, null, NO_LABELS, bounds(1, 2), array(bounds(3, 5)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" a b&\n", 6, null, NO_LABELS, bounds(1, 2), array(bounds(3, 6)), null, new int[] { 4 }); addDataItem(" a b&\nc", 7, null, NO_LABELS, bounds(1, 2), array(bounds(3, 7)), null, new int[] { 4 }); addDataItem(" a b,&\nc", 8, null, NO_LABELS, bounds(1, 2), array(bounds(3, 4), bounds(7, 8)), null, new int[] { 5 }); } /** * Gets the test data for this parameterized test. * * @return the test data */ @Nonnull @Parameters public static List<Object[]> data() { return TEST_DATA; } private static void addDataItem(@Nonnull String text, int length, @CheckForNull ParseError parseError, @Nonnull SubstringBounds[] labels, @CheckForNull SubstringBounds mnemonic, @Nonnull SubstringBounds[] operands, @CheckForNull SubstringBounds comment, @Nonnull int[] continuationCharacters) { TEST_DATA.add(new Object[] { text, 0, length, parseError, labels, mnemonic, operands, comment, continuationCharacters }); TEST_DATA.add(new Object[] { "\n" + text, 1, length, parseError, labels, mnemonic, operands, comment, continuationCharacters }); } @Nonnull @SafeVarargs private static <T> T[] array(@Nonnull T... bounds) { return bounds; } @Nonnull private static SubstringBounds bounds(int start, int end) { return new SubstringBounds(start, end); } @Nonnull private final String text; private final int start; private final int length; @CheckForNull private final ParseError parseError; @Nonnull private final SubstringBounds[] labels; @CheckForNull private final SubstringBounds mnemonic; @Nonnull private final SubstringBounds[] operands; @CheckForNull private final SubstringBounds comment; @Nonnull private final int[] continuationCharacters; public LogicalLineParserTest(@Nonnull String text, int start, int length, @CheckForNull ParseError parseError, @Nonnull SubstringBounds[] labels, @CheckForNull SubstringBounds mnemonic, @Nonnull SubstringBounds[] operands, @CheckForNull SubstringBounds comment, @Nonnull int[] continuationCharacters) { this.text = text; this.start = start; this.length = length; this.parseError = parseError; this.labels = labels; this.mnemonic = mnemonic; this.operands = operands; this.comment = comment; this.continuationCharacters = continuationCharacters; } /** * Asserts that {@link LogicalLineParser#parse(CharSequenceReader)} parses a {@link LogicalLine} with the correct attributes. */ @Test public void parse() { final LogicalLine logicalLine = LogicalLineParser.parse(new GenericCharSequenceReader(this.text, this.start)); // Check SourceNode properties assertThat(logicalLine.getLength(), is(this.length)); if (this.parseError == null) { assertThat(logicalLine.getParseError(), is(nullValue())); } else { assertThat(logicalLine.getParseError(), is(new EquivalentParseError(this.parseError))); } // Check labels assertThat(logicalLine.getNumberOfLabels(), is(this.labels.length)); for (int i = 0; i < this.labels.length; i++) { assertThat(logicalLine.getLabelBounds(i), is(this.labels[i])); } // Check mnemonic assertThat(logicalLine.getMnemonicBounds(), is(this.mnemonic)); // Check operands assertThat(logicalLine.getNumberOfOperands(), is(this.operands.length)); for (int i = 0; i < this.operands.length; i++) { assertThat(logicalLine.getOperandBounds(i), is(this.operands[i])); } // Check comment assertThat(logicalLine.getCommentBounds(), is(this.comment)); // Check continuation characters assertThat(logicalLine.getNumberOfContinuationCharacters(), is(this.continuationCharacters.length)); for (int i = 0; i < this.continuationCharacters.length; i++) { assertThat(logicalLine.getContinuationCharacter(i), is(this.continuationCharacters[i])); } } }
src/test/java/org/reasm/m68k/source/LogicalLineParserTest.java
package org.reasm.m68k.source; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.List; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.reasm.SubstringBounds; import org.reasm.m68k.parseerrors.LabelExpectedParseError; import org.reasm.m68k.testhelpers.EquivalentParseError; import org.reasm.source.ParseError; import org.reasm.source.parseerrors.MismatchedParenthesisParseError; import org.reasm.source.parseerrors.UnterminatedStringParseError; import ca.fragag.text.CharSequenceReader; import ca.fragag.text.GenericCharSequenceReader; /** * Test class for {@link LogicalLineParser}. * * @author Francis Gagné */ @RunWith(Parameterized.class) @SuppressWarnings("javadoc") public class LogicalLineParserTest { private static final ArrayList<Object[]> TEST_DATA = new ArrayList<>(); private static final SubstringBounds[] NO_LABELS = new SubstringBounds[0]; private static final SubstringBounds[] NO_OPERANDS = NO_LABELS; private static final int[] NO_CONTINUATION_CHARACTERS = new int[0]; static { addDataItem("", 0, null, NO_LABELS, null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem(" ", 1, null, NO_LABELS, null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("\t", 1, null, NO_LABELS, null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("a", 1, null, array(bounds(0, 1)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("a ", 2, null, array(bounds(0, 1)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("a:", 2, null, array(bounds(0, 1)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("a: ", 3, null, array(bounds(0, 1)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("a :", 3, null, array(bounds(0, 1)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("abc", 3, null, array(bounds(0, 3)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("abc ", 4, null, array(bounds(0, 3)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem(" a:", 3, null, array(bounds(1, 2)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem(" a: ", 4, null, array(bounds(1, 2)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("abc def:", 8, null, array(bounds(0, 3), bounds(4, 7)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("abc def: ", 9, null, array(bounds(0, 3), bounds(4, 7)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("abc def :", 9, null, array(bounds(0, 3), bounds(4, 7)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("abc: def:", 9, null, array(bounds(0, 3), bounds(5, 8)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem(":", 1, new LabelExpectedParseError(0), array(bounds(0, 0)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("abc::", 5, new LabelExpectedParseError(4), array(bounds(0, 3), bounds(4, 4)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("abc:::", 6, new LabelExpectedParseError(4), array(bounds(0, 3), bounds(4, 4), bounds(5, 5)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem(" a", 2, null, NO_LABELS, bounds(1, 2), NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem(" a ", 3, null, NO_LABELS, bounds(1, 2), NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc", 4, null, NO_LABELS, bounds(1, 4), NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc ", 5, null, NO_LABELS, bounds(1, 4), NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("abc def", 7, null, array(bounds(0, 3)), bounds(4, 7), NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc d", 6, null, NO_LABELS, bounds(1, 4), array(bounds(5, 6)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc d ", 7, null, NO_LABELS, bounds(1, 4), array(bounds(5, 6)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc d ", 8, null, NO_LABELS, bounds(1, 4), array(bounds(5, 6)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc ,", 6, null, NO_LABELS, bounds(1, 4), array(bounds(5, 5), bounds(6, 6)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc def,ghi", 12, null, NO_LABELS, bounds(1, 4), array(bounds(5, 8), bounds(9, 12)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc def, ghi", 13, null, NO_LABELS, bounds(1, 4), array(bounds(5, 8), bounds(10, 13)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc def,ghi,jkl", 16, null, NO_LABELS, bounds(1, 4), array(bounds(5, 8), bounds(9, 12), bounds(13, 16)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc (", 6, new MismatchedParenthesisParseError(5), NO_LABELS, bounds(1, 4), array(bounds(5, 6)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc )", 6, new MismatchedParenthesisParseError(5), NO_LABELS, bounds(1, 4), array(bounds(5, 6)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc )(", 7, new MismatchedParenthesisParseError(5), NO_LABELS, bounds(1, 4), array(bounds(5, 7)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc ()", 7, null, NO_LABELS, bounds(1, 4), array(bounds(5, 7)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc (d)", 8, null, NO_LABELS, bounds(1, 4), array(bounds(5, 8)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc (,)", 8, null, NO_LABELS, bounds(1, 4), array(bounds(5, 8)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc (()", 8, new MismatchedParenthesisParseError(6), NO_LABELS, bounds(1, 4), array(bounds(5, 8)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc ())", 8, new MismatchedParenthesisParseError(7), NO_LABELS, bounds(1, 4), array(bounds(5, 8)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc ())d", 9, new MismatchedParenthesisParseError(7), NO_LABELS, bounds(1, 4), array(bounds(5, 9)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc ()))", 9, new MismatchedParenthesisParseError(7), NO_LABELS, bounds(1, 4), array(bounds(5, 9)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc (())", 9, null, NO_LABELS, bounds(1, 4), array(bounds(5, 9)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc ((d))", 10, null, NO_LABELS, bounds(1, 4), array(bounds(5, 10)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc (d,e)", 10, null, NO_LABELS, bounds(1, 4), array(bounds(5, 10)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc \"", 6, new UnterminatedStringParseError(5), NO_LABELS, bounds(1, 4), array(bounds(5, 6)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc \"d", 7, new UnterminatedStringParseError(5), NO_LABELS, bounds(1, 4), array(bounds(5, 7)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc \"\"", 7, null, NO_LABELS, bounds(1, 4), array(bounds(5, 7)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc \"d\"", 8, null, NO_LABELS, bounds(1, 4), array(bounds(5, 8)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc \",\"", 8, null, NO_LABELS, bounds(1, 4), array(bounds(5, 8)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc \"\\\"", 8, new UnterminatedStringParseError(5), NO_LABELS, bounds(1, 4), array(bounds(5, 8)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc )\"", 7, new MismatchedParenthesisParseError(5), NO_LABELS, bounds(1, 4), array(bounds(5, 7)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc '", 6, new UnterminatedStringParseError(5), NO_LABELS, bounds(1, 4), array(bounds(5, 6)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc 'd", 7, new UnterminatedStringParseError(5), NO_LABELS, bounds(1, 4), array(bounds(5, 7)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" abc ''", 7, null, NO_LABELS, bounds(1, 4), array(bounds(5, 7)), null, NO_CONTINUATION_CHARACTERS); addDataItem("*", 1, null, NO_LABELS, null, NO_OPERANDS, bounds(0, 1), NO_CONTINUATION_CHARACTERS); addDataItem("*xyz", 4, null, NO_LABELS, null, NO_OPERANDS, bounds(0, 4), NO_CONTINUATION_CHARACTERS); addDataItem(";", 1, null, NO_LABELS, null, NO_OPERANDS, bounds(0, 1), NO_CONTINUATION_CHARACTERS); addDataItem(";xyz", 4, null, NO_LABELS, null, NO_OPERANDS, bounds(0, 4), NO_CONTINUATION_CHARACTERS); addDataItem(" *xyz", 5, null, NO_LABELS, bounds(1, 5), NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem(" ;xyz", 5, null, NO_LABELS, null, NO_OPERANDS, bounds(1, 5), NO_CONTINUATION_CHARACTERS); addDataItem("a;xyz", 5, null, array(bounds(0, 1)), null, NO_OPERANDS, bounds(1, 5), NO_CONTINUATION_CHARACTERS); addDataItem("a:;xyz", 6, null, array(bounds(0, 1)), null, NO_OPERANDS, bounds(2, 6), NO_CONTINUATION_CHARACTERS); addDataItem("a: ;xyz", 7, null, array(bounds(0, 1)), null, NO_OPERANDS, bounds(3, 7), NO_CONTINUATION_CHARACTERS); addDataItem("a :;xyz", 7, null, array(bounds(0, 1)), null, NO_OPERANDS, bounds(3, 7), NO_CONTINUATION_CHARACTERS); addDataItem(" a;xyz", 6, null, NO_LABELS, bounds(1, 2), NO_OPERANDS, bounds(2, 6), NO_CONTINUATION_CHARACTERS); addDataItem(" a ;xyz", 7, null, NO_LABELS, bounds(1, 2), NO_OPERANDS, bounds(3, 7), NO_CONTINUATION_CHARACTERS); addDataItem(" a b;xyz", 8, null, NO_LABELS, bounds(1, 2), array(bounds(3, 4)), bounds(4, 8), NO_CONTINUATION_CHARACTERS); addDataItem(" a b ;xyz", 9, null, NO_LABELS, bounds(1, 2), array(bounds(3, 4)), bounds(5, 9), NO_CONTINUATION_CHARACTERS); addDataItem(" a b,;xyz", 9, null, NO_LABELS, bounds(1, 2), array(bounds(3, 4), bounds(5, 5)), bounds(5, 9), NO_CONTINUATION_CHARACTERS); addDataItem(" a (;xyz", 8, new MismatchedParenthesisParseError(3), NO_LABELS, bounds(1, 2), array(bounds(3, 4)), bounds(4, 8), NO_CONTINUATION_CHARACTERS); addDataItem(" a \";xyz", 8, new UnterminatedStringParseError(3), NO_LABELS, bounds(1, 2), array(bounds(3, 8)), null, NO_CONTINUATION_CHARACTERS); addDataItem("\n", 1, null, NO_LABELS, null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("\n ", 1, null, NO_LABELS, null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("\r", 1, null, NO_LABELS, null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("\r ", 1, null, NO_LABELS, null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("\r\n", 2, null, NO_LABELS, null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("\r\n ", 2, null, NO_LABELS, null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("a\n", 2, null, array(bounds(0, 1)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("a&", 2, null, array(bounds(0, 2)), null, NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem("a&\n", 3, null, array(bounds(0, 3)), null, NO_OPERANDS, null, new int[] { 1 }); addDataItem("a&\n\n", 4, null, array(bounds(0, 3)), null, NO_OPERANDS, null, new int[] { 1 }); addDataItem("a&\nb", 4, null, array(bounds(0, 4)), null, NO_OPERANDS, null, new int[] { 1 }); addDataItem("a&\rb", 4, null, array(bounds(0, 4)), null, NO_OPERANDS, null, new int[] { 1 }); addDataItem("a&\r\nb", 5, null, array(bounds(0, 5)), null, NO_OPERANDS, null, new int[] { 1 }); addDataItem("a&\n ", 4, null, array(bounds(0, 4)), null, NO_OPERANDS, null, new int[] { 1 }); addDataItem("a&\n \n", 5, null, array(bounds(0, 4)), null, NO_OPERANDS, null, new int[] { 1 }); addDataItem("a&\n b", 5, null, array(bounds(0, 5)), null, NO_OPERANDS, null, new int[] { 1 }); addDataItem("a&\n b", 6, null, array(bounds(0, 6)), null, NO_OPERANDS, null, new int[] { 1 }); addDataItem(" a&", 3, null, NO_LABELS, bounds(1, 3), NO_OPERANDS, null, NO_CONTINUATION_CHARACTERS); addDataItem(" a&\n", 4, null, NO_LABELS, bounds(1, 4), NO_OPERANDS, null, new int[] { 2 }); addDataItem(" a&\nb", 5, null, NO_LABELS, bounds(1, 5), NO_OPERANDS, null, new int[] { 2 }); addDataItem(" a b&", 5, null, NO_LABELS, bounds(1, 2), array(bounds(3, 5)), null, NO_CONTINUATION_CHARACTERS); addDataItem(" a b&\n", 6, null, NO_LABELS, bounds(1, 2), array(bounds(3, 6)), null, new int[] { 4 }); addDataItem(" a b&\nc", 7, null, NO_LABELS, bounds(1, 2), array(bounds(3, 7)), null, new int[] { 4 }); addDataItem(" a b,&\nc", 8, null, NO_LABELS, bounds(1, 2), array(bounds(3, 4), bounds(7, 8)), null, new int[] { 5 }); } /** * Gets the test data for this parameterized test. * * @return the test data */ @Nonnull @Parameters public static List<Object[]> data() { return TEST_DATA; } private static void addDataItem(@Nonnull String text, int length, @CheckForNull ParseError parseError, @Nonnull SubstringBounds[] labels, @CheckForNull SubstringBounds mnemonic, @Nonnull SubstringBounds[] operands, @CheckForNull SubstringBounds comment, @Nonnull int[] continuationCharacters) { TEST_DATA.add(new Object[] { text, 0, length, parseError, labels, mnemonic, operands, comment, continuationCharacters }); TEST_DATA.add(new Object[] { "\n" + text, 1, length, parseError, labels, mnemonic, operands, comment, continuationCharacters }); } @Nonnull @SafeVarargs private static <T> T[] array(@Nonnull T... bounds) { return bounds; } @Nonnull private static SubstringBounds bounds(int start, int end) { return new SubstringBounds(start, end); } @Nonnull private final String text; private final int start; private final int length; @CheckForNull private final ParseError parseError; @Nonnull private final SubstringBounds[] labels; @CheckForNull private final SubstringBounds mnemonic; @Nonnull private final SubstringBounds[] operands; @CheckForNull private final SubstringBounds comment; @Nonnull private final int[] continuationCharacters; public LogicalLineParserTest(@Nonnull String text, int start, int length, @CheckForNull ParseError parseError, @Nonnull SubstringBounds[] labels, @CheckForNull SubstringBounds mnemonic, @Nonnull SubstringBounds[] operands, @CheckForNull SubstringBounds comment, @Nonnull int[] continuationCharacters) { this.text = text; this.start = start; this.length = length; this.parseError = parseError; this.labels = labels; this.mnemonic = mnemonic; this.operands = operands; this.comment = comment; this.continuationCharacters = continuationCharacters; } /** * Asserts that {@link LogicalLineParser#parse(LogicalLineParserResult, CharSequenceReader)} parses a {@link LogicalLine} with * the correct attributes. */ @Test public void parse() { final LogicalLine logicalLine = LogicalLineParser.parse(new GenericCharSequenceReader(this.text, this.start)); // Check SourceNode properties assertThat(logicalLine.getLength(), is(this.length)); if (this.parseError == null) { assertThat(logicalLine.getParseError(), is(nullValue())); } else { assertThat(logicalLine.getParseError(), is(new EquivalentParseError(this.parseError))); } // Check labels assertThat(logicalLine.getNumberOfLabels(), is(this.labels.length)); for (int i = 0; i < this.labels.length; i++) { assertThat(logicalLine.getLabelBounds(i), is(this.labels[i])); } // Check mnemonic assertThat(logicalLine.getMnemonicBounds(), is(this.mnemonic)); // Check operands assertThat(logicalLine.getNumberOfOperands(), is(this.operands.length)); for (int i = 0; i < this.operands.length; i++) { assertThat(logicalLine.getOperandBounds(i), is(this.operands[i])); } // Check comment assertThat(logicalLine.getCommentBounds(), is(this.comment)); // Check continuation characters assertThat(logicalLine.getNumberOfContinuationCharacters(), is(this.continuationCharacters.length)); for (int i = 0; i < this.continuationCharacters.length; i++) { assertThat(logicalLine.getContinuationCharacter(i), is(this.continuationCharacters[i])); } } }
Fix Javadoc on LogicalLineParserTest.parse()
src/test/java/org/reasm/m68k/source/LogicalLineParserTest.java
Fix Javadoc on LogicalLineParserTest.parse()
<ide><path>rc/test/java/org/reasm/m68k/source/LogicalLineParserTest.java <ide> } <ide> <ide> /** <del> * Asserts that {@link LogicalLineParser#parse(LogicalLineParserResult, CharSequenceReader)} parses a {@link LogicalLine} with <del> * the correct attributes. <add> * Asserts that {@link LogicalLineParser#parse(CharSequenceReader)} parses a {@link LogicalLine} with the correct attributes. <ide> */ <ide> @Test <ide> public void parse() {
Java
mit
4345b330aa17e6a2b09f075c2b24fb6f14b706d8
0
kohsuke/hudson,sathiya-mit/jenkins,NehemiahMi/jenkins,v1v/jenkins,MichaelPranovich/jenkins_sc,ChrisA89/jenkins,gitaccountforprashant/gittest,morficus/jenkins,oleg-nenashev/jenkins,tangkun75/jenkins,varmenise/jenkins,pantheon-systems/jenkins,arunsingh/jenkins,guoxu0514/jenkins,ydubreuil/jenkins,Wilfred/jenkins,amruthsoft9/Jenkis,stephenc/jenkins,FTG-003/jenkins,christ66/jenkins,noikiy/jenkins,vlajos/jenkins,mrooney/jenkins,mrooney/jenkins,github-api-test-org/jenkins,NehemiahMi/jenkins,MarkEWaite/jenkins,hashar/jenkins,SenolOzer/jenkins,noikiy/jenkins,thomassuckow/jenkins,jtnord/jenkins,albers/jenkins,mpeltonen/jenkins,batmat/jenkins,ydubreuil/jenkins,pantheon-systems/jenkins,amruthsoft9/Jenkis,v1v/jenkins,pselle/jenkins,protazy/jenkins,andresrc/jenkins,mattclark/jenkins,amruthsoft9/Jenkis,hplatou/jenkins,albers/jenkins,khmarbaise/jenkins,sathiya-mit/jenkins,lvotypko/jenkins2,lvotypko/jenkins,nandan4/Jenkins,jglick/jenkins,paulmillar/jenkins,escoem/jenkins,dbroady1/jenkins,MarkEWaite/jenkins,albers/jenkins,jcsirot/jenkins,petermarcoen/jenkins,damianszczepanik/jenkins,daspilker/jenkins,escoem/jenkins,evernat/jenkins,github-api-test-org/jenkins,jk47/jenkins,SebastienGllmt/jenkins,lilyJi/jenkins,Jimilian/jenkins,jpbriend/jenkins,keyurpatankar/hudson,paulwellnerbou/jenkins,KostyaSha/jenkins,tangkun75/jenkins,aduprat/jenkins,6WIND/jenkins,Ykus/jenkins,daniel-beck/jenkins,dennisjlee/jenkins,pselle/jenkins,amruthsoft9/Jenkis,escoem/jenkins,sathiya-mit/jenkins,huybrechts/hudson,ikedam/jenkins,everyonce/jenkins,luoqii/jenkins,mrobinet/jenkins,daniel-beck/jenkins,seanlin816/jenkins,Jochen-A-Fuerbacher/jenkins,my7seven/jenkins,akshayabd/jenkins,jtnord/jenkins,Vlatombe/jenkins,lvotypko/jenkins3,vijayto/jenkins,292388900/jenkins,sathiya-mit/jenkins,jtnord/jenkins,jcarrothers-sap/jenkins,vjuranek/jenkins,6WIND/jenkins,godfath3r/jenkins,liorhson/jenkins,stefanbrausch/hudson-main,morficus/jenkins,Wilfred/jenkins,alvarolobato/jenkins,oleg-nenashev/jenkins,CodeShane/jenkins,liorhson/jenkins,lvotypko/jenkins2,godfath3r/jenkins,jenkinsci/jenkins,maikeffi/hudson,KostyaSha/jenkins,FarmGeek4Life/jenkins,hplatou/jenkins,khmarbaise/jenkins,andresrc/jenkins,daniel-beck/jenkins,mdonohue/jenkins,mattclark/jenkins,liorhson/jenkins,liupugong/jenkins,jcarrothers-sap/jenkins,wuwen5/jenkins,thomassuckow/jenkins,aldaris/jenkins,abayer/jenkins,deadmoose/jenkins,aduprat/jenkins,nandan4/Jenkins,iterate/coding-dojo,hashar/jenkins,vijayto/jenkins,FTG-003/jenkins,rsandell/jenkins,DanielWeber/jenkins,daspilker/jenkins,escoem/jenkins,azweb76/jenkins,mcanthony/jenkins,csimons/jenkins,iqstack/jenkins,stefanbrausch/hudson-main,mrobinet/jenkins,batmat/jenkins,dariver/jenkins,varmenise/jenkins,vjuranek/jenkins,verbitan/jenkins,alvarolobato/jenkins,pantheon-systems/jenkins,everyonce/jenkins,guoxu0514/jenkins,292388900/jenkins,lindzh/jenkins,protazy/jenkins,scoheb/jenkins,CodeShane/jenkins,escoem/jenkins,DanielWeber/jenkins,ChrisA89/jenkins,dariver/jenkins,jglick/jenkins,bkmeneguello/jenkins,goldchang/jenkins,lvotypko/jenkins,keyurpatankar/hudson,verbitan/jenkins,vvv444/jenkins,duzifang/my-jenkins,ikedam/jenkins,ikedam/jenkins,jhoblitt/jenkins,jhoblitt/jenkins,svanoort/jenkins,ikedam/jenkins,6WIND/jenkins,KostyaSha/jenkins,aheritier/jenkins,scoheb/jenkins,Wilfred/jenkins,huybrechts/hudson,FarmGeek4Life/jenkins,oleg-nenashev/jenkins,mrobinet/jenkins,soenter/jenkins,aquarellian/jenkins,chbiel/jenkins,gorcz/jenkins,1and1/jenkins,github-api-test-org/jenkins,evernat/jenkins,hudson/hudson-2.x,amuniz/jenkins,Krasnyanskiy/jenkins,seanlin816/jenkins,Jimilian/jenkins,nandan4/Jenkins,Jimilian/jenkins,tfennelly/jenkins,Wilfred/jenkins,christ66/jenkins,rlugojr/jenkins,6WIND/jenkins,csimons/jenkins,jpbriend/jenkins,albers/jenkins,MarkEWaite/jenkins,khmarbaise/jenkins,guoxu0514/jenkins,vvv444/jenkins,liupugong/jenkins,mdonohue/jenkins,lordofthejars/jenkins,bkmeneguello/jenkins,rsandell/jenkins,luoqii/jenkins,ns163/jenkins,mcanthony/jenkins,godfath3r/jenkins,jpederzolli/jenkins-1,vivek/hudson,rashmikanta-1984/jenkins,lvotypko/jenkins3,vjuranek/jenkins,hemantojhaa/jenkins,arunsingh/jenkins,mpeltonen/jenkins,v1v/jenkins,gusreiber/jenkins,evernat/jenkins,intelchen/jenkins,ydubreuil/jenkins,Vlatombe/jenkins,protazy/jenkins,ajshastri/jenkins,yonglehou/jenkins,jk47/jenkins,stefanbrausch/hudson-main,vivek/hudson,gitaccountforprashant/gittest,jcarrothers-sap/jenkins,elkingtonmcb/jenkins,recena/jenkins,singh88/jenkins,duzifang/my-jenkins,kzantow/jenkins,recena/jenkins,wangyikai/jenkins,guoxu0514/jenkins,gusreiber/jenkins,hashar/jenkins,godfath3r/jenkins,dennisjlee/jenkins,aldaris/jenkins,my7seven/jenkins,ns163/jenkins,svanoort/jenkins,DoctorQ/jenkins,AustinKwang/jenkins,tfennelly/jenkins,alvarolobato/jenkins,viqueen/jenkins,brunocvcunha/jenkins,scoheb/jenkins,tastatur/jenkins,vivek/hudson,samatdav/jenkins,paulmillar/jenkins,aquarellian/jenkins,jzjzjzj/jenkins,wangyikai/jenkins,ns163/jenkins,scoheb/jenkins,1and1/jenkins,protazy/jenkins,tastatur/jenkins,lvotypko/jenkins2,kzantow/jenkins,vijayto/jenkins,hplatou/jenkins,liupugong/jenkins,mrobinet/jenkins,6WIND/jenkins,morficus/jenkins,arunsingh/jenkins,iterate/coding-dojo,sathiya-mit/jenkins,recena/jenkins,msrb/jenkins,christ66/jenkins,jcarrothers-sap/jenkins,soenter/jenkins,varmenise/jenkins,DoctorQ/jenkins,tastatur/jenkins,my7seven/jenkins,jcsirot/jenkins,DanielWeber/jenkins,vlajos/jenkins,goldchang/jenkins,liupugong/jenkins,amruthsoft9/Jenkis,aquarellian/jenkins,sathiya-mit/jenkins,SebastienGllmt/jenkins,h4ck3rm1k3/jenkins,bkmeneguello/jenkins,oleg-nenashev/jenkins,singh88/jenkins,maikeffi/hudson,Jimilian/jenkins,ndeloof/jenkins,akshayabd/jenkins,daniel-beck/jenkins,mrooney/jenkins,varmenise/jenkins,AustinKwang/jenkins,daniel-beck/jenkins,KostyaSha/jenkins,msrb/jenkins,vijayto/jenkins,mpeltonen/jenkins,kzantow/jenkins,jk47/jenkins,rsandell/jenkins,mdonohue/jenkins,github-api-test-org/jenkins,aldaris/jenkins,evernat/jenkins,lvotypko/jenkins2,ErikVerheul/jenkins,everyonce/jenkins,wangyikai/jenkins,yonglehou/jenkins,ndeloof/jenkins,my7seven/jenkins,singh88/jenkins,daniel-beck/jenkins,lilyJi/jenkins,liupugong/jenkins,gitaccountforprashant/gittest,christ66/jenkins,bpzhang/jenkins,yonglehou/jenkins,patbos/jenkins,hplatou/jenkins,FarmGeek4Life/jenkins,samatdav/jenkins,varmenise/jenkins,jtnord/jenkins,tangkun75/jenkins,wuwen5/jenkins,KostyaSha/jenkins,MadsNielsen/jtemp,Jochen-A-Fuerbacher/jenkins,github-api-test-org/jenkins,lordofthejars/jenkins,MadsNielsen/jtemp,alvarolobato/jenkins,iqstack/jenkins,292388900/jenkins,ikedam/jenkins,DanielWeber/jenkins,kohsuke/hudson,rsandell/jenkins,stephenc/jenkins,synopsys-arc-oss/jenkins,patbos/jenkins,morficus/jenkins,jglick/jenkins,tfennelly/jenkins,shahharsh/jenkins,tangkun75/jenkins,lvotypko/jenkins3,msrb/jenkins,deadmoose/jenkins,vivek/hudson,lilyJi/jenkins,ikedam/jenkins,SebastienGllmt/jenkins,liupugong/jenkins,khmarbaise/jenkins,brunocvcunha/jenkins,dennisjlee/jenkins,ndeloof/jenkins,github-api-test-org/jenkins,khmarbaise/jenkins,FTG-003/jenkins,ErikVerheul/jenkins,csimons/jenkins,lvotypko/jenkins,1and1/jenkins,Wilfred/jenkins,aheritier/jenkins,stefanbrausch/hudson-main,viqueen/jenkins,ndeloof/jenkins,lilyJi/jenkins,my7seven/jenkins,jzjzjzj/jenkins,samatdav/jenkins,ns163/jenkins,wuwen5/jenkins,MarkEWaite/jenkins,viqueen/jenkins,christ66/jenkins,lordofthejars/jenkins,keyurpatankar/hudson,olivergondza/jenkins,goldchang/jenkins,kohsuke/hudson,albers/jenkins,shahharsh/jenkins,svanoort/jenkins,pjanouse/jenkins,FTG-003/jenkins,jenkinsci/jenkins,h4ck3rm1k3/jenkins,synopsys-arc-oss/jenkins,rlugojr/jenkins,mpeltonen/jenkins,iqstack/jenkins,arunsingh/jenkins,chbiel/jenkins,v1v/jenkins,bpzhang/jenkins,chbiel/jenkins,stephenc/jenkins,jpederzolli/jenkins-1,intelchen/jenkins,rashmikanta-1984/jenkins,jpederzolli/jenkins-1,lindzh/jenkins,dbroady1/jenkins,jcsirot/jenkins,stephenc/jenkins,hashar/jenkins,MadsNielsen/jtemp,luoqii/jenkins,goldchang/jenkins,svanoort/jenkins,chbiel/jenkins,liorhson/jenkins,gitaccountforprashant/gittest,ChrisA89/jenkins,noikiy/jenkins,lvotypko/jenkins3,dennisjlee/jenkins,Krasnyanskiy/jenkins,andresrc/jenkins,huybrechts/hudson,ChrisA89/jenkins,batmat/jenkins,mpeltonen/jenkins,abayer/jenkins,intelchen/jenkins,h4ck3rm1k3/jenkins,Wilfred/jenkins,morficus/jenkins,ydubreuil/jenkins,Jochen-A-Fuerbacher/jenkins,rashmikanta-1984/jenkins,lindzh/jenkins,jk47/jenkins,jenkinsci/jenkins,SebastienGllmt/jenkins,stefanbrausch/hudson-main,intelchen/jenkins,jenkinsci/jenkins,DoctorQ/jenkins,pjanouse/jenkins,lordofthejars/jenkins,Krasnyanskiy/jenkins,pantheon-systems/jenkins,azweb76/jenkins,aquarellian/jenkins,jtnord/jenkins,aheritier/jenkins,ndeloof/jenkins,AustinKwang/jenkins,KostyaSha/jenkins,dariver/jenkins,viqueen/jenkins,albers/jenkins,msrb/jenkins,mrooney/jenkins,wangyikai/jenkins,jglick/jenkins,FarmGeek4Life/jenkins,fbelzunc/jenkins,duzifang/my-jenkins,Ykus/jenkins,MarkEWaite/jenkins,Vlatombe/jenkins,abayer/jenkins,samatdav/jenkins,Ykus/jenkins,FarmGeek4Life/jenkins,ajshastri/jenkins,aquarellian/jenkins,andresrc/jenkins,recena/jenkins,aduprat/jenkins,patbos/jenkins,duzifang/my-jenkins,deadmoose/jenkins,paulwellnerbou/jenkins,samatdav/jenkins,vvv444/jenkins,damianszczepanik/jenkins,scoheb/jenkins,maikeffi/hudson,MichaelPranovich/jenkins_sc,scoheb/jenkins,CodeShane/jenkins,1and1/jenkins,elkingtonmcb/jenkins,goldchang/jenkins,aheritier/jenkins,duzifang/my-jenkins,batmat/jenkins,SenolOzer/jenkins,fbelzunc/jenkins,azweb76/jenkins,brunocvcunha/jenkins,akshayabd/jenkins,aldaris/jenkins,vlajos/jenkins,morficus/jenkins,aldaris/jenkins,vvv444/jenkins,gitaccountforprashant/gittest,iqstack/jenkins,jcarrothers-sap/jenkins,hemantojhaa/jenkins,svanoort/jenkins,mrobinet/jenkins,noikiy/jenkins,mrooney/jenkins,morficus/jenkins,AustinKwang/jenkins,damianszczepanik/jenkins,pjanouse/jenkins,gorcz/jenkins,deadmoose/jenkins,sathiya-mit/jenkins,lvotypko/jenkins2,iterate/coding-dojo,arcivanov/jenkins,jzjzjzj/jenkins,verbitan/jenkins,olivergondza/jenkins,iterate/coding-dojo,rlugojr/jenkins,bkmeneguello/jenkins,Ykus/jenkins,huybrechts/hudson,yonglehou/jenkins,iterate/coding-dojo,wuwen5/jenkins,recena/jenkins,jpederzolli/jenkins-1,lindzh/jenkins,gorcz/jenkins,intelchen/jenkins,iterate/coding-dojo,pselle/jenkins,hudson/hudson-2.x,arunsingh/jenkins,mrobinet/jenkins,deadmoose/jenkins,nandan4/Jenkins,msrb/jenkins,6WIND/jenkins,shahharsh/jenkins,v1v/jenkins,chbiel/jenkins,kohsuke/hudson,hplatou/jenkins,khmarbaise/jenkins,Ykus/jenkins,jcarrothers-sap/jenkins,alvarolobato/jenkins,tangkun75/jenkins,yonglehou/jenkins,jenkinsci/jenkins,jhoblitt/jenkins,Krasnyanskiy/jenkins,protazy/jenkins,FTG-003/jenkins,1and1/jenkins,petermarcoen/jenkins,vlajos/jenkins,daniel-beck/jenkins,andresrc/jenkins,rlugojr/jenkins,gorcz/jenkins,tfennelly/jenkins,csimons/jenkins,soenter/jenkins,alvarolobato/jenkins,DanielWeber/jenkins,ndeloof/jenkins,liupugong/jenkins,lilyJi/jenkins,MarkEWaite/jenkins,jhoblitt/jenkins,tfennelly/jenkins,luoqii/jenkins,jpederzolli/jenkins-1,ns163/jenkins,MichaelPranovich/jenkins_sc,duzifang/my-jenkins,Jochen-A-Fuerbacher/jenkins,protazy/jenkins,ChrisA89/jenkins,github-api-test-org/jenkins,nandan4/Jenkins,mdonohue/jenkins,paulwellnerbou/jenkins,recena/jenkins,arunsingh/jenkins,svanoort/jenkins,elkingtonmcb/jenkins,noikiy/jenkins,aquarellian/jenkins,evernat/jenkins,Jochen-A-Fuerbacher/jenkins,azweb76/jenkins,kohsuke/hudson,SebastienGllmt/jenkins,jpederzolli/jenkins-1,mdonohue/jenkins,abayer/jenkins,luoqii/jenkins,hudson/hudson-2.x,AustinKwang/jenkins,arcivanov/jenkins,jk47/jenkins,jk47/jenkins,vvv444/jenkins,daniel-beck/jenkins,SenolOzer/jenkins,jcsirot/jenkins,yonglehou/jenkins,singh88/jenkins,SenolOzer/jenkins,daspilker/jenkins,synopsys-arc-oss/jenkins,kohsuke/hudson,tangkun75/jenkins,wangyikai/jenkins,292388900/jenkins,batmat/jenkins,hemantojhaa/jenkins,jcarrothers-sap/jenkins,viqueen/jenkins,tastatur/jenkins,lvotypko/jenkins3,petermarcoen/jenkins,hudson/hudson-2.x,duzifang/my-jenkins,ErikVerheul/jenkins,gusreiber/jenkins,hashar/jenkins,bpzhang/jenkins,github-api-test-org/jenkins,liorhson/jenkins,ydubreuil/jenkins,singh88/jenkins,MadsNielsen/jtemp,thomassuckow/jenkins,vlajos/jenkins,evernat/jenkins,tangkun75/jenkins,amuniz/jenkins,jcarrothers-sap/jenkins,bpzhang/jenkins,lvotypko/jenkins,deadmoose/jenkins,gusreiber/jenkins,bkmeneguello/jenkins,jpederzolli/jenkins-1,pjanouse/jenkins,jtnord/jenkins,MadsNielsen/jtemp,jpbriend/jenkins,ChrisA89/jenkins,csimons/jenkins,lvotypko/jenkins3,vvv444/jenkins,soenter/jenkins,protazy/jenkins,luoqii/jenkins,chbiel/jenkins,pjanouse/jenkins,synopsys-arc-oss/jenkins,deadmoose/jenkins,rlugojr/jenkins,aduprat/jenkins,h4ck3rm1k3/jenkins,Jimilian/jenkins,v1v/jenkins,olivergondza/jenkins,maikeffi/hudson,mrooney/jenkins,ns163/jenkins,mpeltonen/jenkins,DanielWeber/jenkins,soenter/jenkins,dbroady1/jenkins,jpbriend/jenkins,SenolOzer/jenkins,escoem/jenkins,pantheon-systems/jenkins,vivek/hudson,synopsys-arc-oss/jenkins,olivergondza/jenkins,Vlatombe/jenkins,recena/jenkins,292388900/jenkins,viqueen/jenkins,dennisjlee/jenkins,my7seven/jenkins,kzantow/jenkins,olivergondza/jenkins,goldchang/jenkins,paulmillar/jenkins,jenkinsci/jenkins,csimons/jenkins,iqstack/jenkins,olivergondza/jenkins,keyurpatankar/hudson,dariver/jenkins,mcanthony/jenkins,gorcz/jenkins,thomassuckow/jenkins,huybrechts/hudson,NehemiahMi/jenkins,ErikVerheul/jenkins,soenter/jenkins,stephenc/jenkins,DoctorQ/jenkins,keyurpatankar/hudson,shahharsh/jenkins,kohsuke/hudson,iqstack/jenkins,goldchang/jenkins,huybrechts/hudson,wangyikai/jenkins,KostyaSha/jenkins,brunocvcunha/jenkins,guoxu0514/jenkins,daspilker/jenkins,dbroady1/jenkins,damianszczepanik/jenkins,hemantojhaa/jenkins,aheritier/jenkins,maikeffi/hudson,thomassuckow/jenkins,daspilker/jenkins,damianszczepanik/jenkins,albers/jenkins,fbelzunc/jenkins,MadsNielsen/jtemp,msrb/jenkins,mpeltonen/jenkins,NehemiahMi/jenkins,DoctorQ/jenkins,fbelzunc/jenkins,seanlin816/jenkins,chbiel/jenkins,hemantojhaa/jenkins,1and1/jenkins,luoqii/jenkins,yonglehou/jenkins,vjuranek/jenkins,brunocvcunha/jenkins,samatdav/jenkins,292388900/jenkins,jzjzjzj/jenkins,pantheon-systems/jenkins,akshayabd/jenkins,oleg-nenashev/jenkins,Vlatombe/jenkins,MichaelPranovich/jenkins_sc,arcivanov/jenkins,ErikVerheul/jenkins,AustinKwang/jenkins,paulmillar/jenkins,patbos/jenkins,ajshastri/jenkins,shahharsh/jenkins,dbroady1/jenkins,damianszczepanik/jenkins,synopsys-arc-oss/jenkins,oleg-nenashev/jenkins,petermarcoen/jenkins,shahharsh/jenkins,rlugojr/jenkins,lvotypko/jenkins,seanlin816/jenkins,hplatou/jenkins,daspilker/jenkins,verbitan/jenkins,vlajos/jenkins,abayer/jenkins,nandan4/Jenkins,fbelzunc/jenkins,amruthsoft9/Jenkis,viqueen/jenkins,DanielWeber/jenkins,maikeffi/hudson,FarmGeek4Life/jenkins,svanoort/jenkins,Krasnyanskiy/jenkins,aldaris/jenkins,kzantow/jenkins,varmenise/jenkins,6WIND/jenkins,aduprat/jenkins,liorhson/jenkins,khmarbaise/jenkins,jpbriend/jenkins,pantheon-systems/jenkins,batmat/jenkins,lvotypko/jenkins3,paulwellnerbou/jenkins,jcsirot/jenkins,mrooney/jenkins,intelchen/jenkins,rashmikanta-1984/jenkins,vlajos/jenkins,patbos/jenkins,jzjzjzj/jenkins,azweb76/jenkins,stephenc/jenkins,arcivanov/jenkins,mcanthony/jenkins,ajshastri/jenkins,godfath3r/jenkins,hemantojhaa/jenkins,lvotypko/jenkins,jglick/jenkins,bpzhang/jenkins,lindzh/jenkins,MarkEWaite/jenkins,damianszczepanik/jenkins,goldchang/jenkins,verbitan/jenkins,lindzh/jenkins,singh88/jenkins,lvotypko/jenkins,vivek/hudson,guoxu0514/jenkins,mcanthony/jenkins,Krasnyanskiy/jenkins,tfennelly/jenkins,MichaelPranovich/jenkins_sc,jglick/jenkins,wuwen5/jenkins,DoctorQ/jenkins,mattclark/jenkins,hplatou/jenkins,lordofthejars/jenkins,h4ck3rm1k3/jenkins,godfath3r/jenkins,jzjzjzj/jenkins,jenkinsci/jenkins,KostyaSha/jenkins,ikedam/jenkins,SebastienGllmt/jenkins,1and1/jenkins,mattclark/jenkins,patbos/jenkins,my7seven/jenkins,pselle/jenkins,Wilfred/jenkins,fbelzunc/jenkins,Jochen-A-Fuerbacher/jenkins,nandan4/Jenkins,rsandell/jenkins,NehemiahMi/jenkins,gusreiber/jenkins,jhoblitt/jenkins,lvotypko/jenkins2,mattclark/jenkins,v1v/jenkins,lordofthejars/jenkins,rsandell/jenkins,ikedam/jenkins,ErikVerheul/jenkins,huybrechts/hudson,varmenise/jenkins,fbelzunc/jenkins,Jimilian/jenkins,everyonce/jenkins,damianszczepanik/jenkins,aldaris/jenkins,mcanthony/jenkins,gorcz/jenkins,pselle/jenkins,noikiy/jenkins,dariver/jenkins,everyonce/jenkins,shahharsh/jenkins,vivek/hudson,Jochen-A-Fuerbacher/jenkins,maikeffi/hudson,rashmikanta-1984/jenkins,amuniz/jenkins,DoctorQ/jenkins,rsandell/jenkins,singh88/jenkins,mattclark/jenkins,pjanouse/jenkins,csimons/jenkins,aduprat/jenkins,petermarcoen/jenkins,arcivanov/jenkins,gorcz/jenkins,abayer/jenkins,gitaccountforprashant/gittest,maikeffi/hudson,aduprat/jenkins,soenter/jenkins,FTG-003/jenkins,SenolOzer/jenkins,vjuranek/jenkins,AustinKwang/jenkins,pselle/jenkins,jhoblitt/jenkins,evernat/jenkins,bkmeneguello/jenkins,gusreiber/jenkins,ajshastri/jenkins,paulmillar/jenkins,ydubreuil/jenkins,stefanbrausch/hudson-main,paulmillar/jenkins,wuwen5/jenkins,FarmGeek4Life/jenkins,h4ck3rm1k3/jenkins,samatdav/jenkins,ajshastri/jenkins,lilyJi/jenkins,paulwellnerbou/jenkins,pselle/jenkins,MichaelPranovich/jenkins_sc,thomassuckow/jenkins,kzantow/jenkins,vvv444/jenkins,ndeloof/jenkins,stephenc/jenkins,kzantow/jenkins,rsandell/jenkins,pjanouse/jenkins,vijayto/jenkins,jglick/jenkins,jenkinsci/jenkins,bpzhang/jenkins,andresrc/jenkins,thomassuckow/jenkins,vjuranek/jenkins,hashar/jenkins,mdonohue/jenkins,rashmikanta-1984/jenkins,vivek/hudson,hashar/jenkins,brunocvcunha/jenkins,amuniz/jenkins,hudson/hudson-2.x,MadsNielsen/jtemp,dariver/jenkins,bkmeneguello/jenkins,gusreiber/jenkins,kohsuke/hudson,hemantojhaa/jenkins,iterate/coding-dojo,paulwellnerbou/jenkins,tfennelly/jenkins,keyurpatankar/hudson,azweb76/jenkins,Krasnyanskiy/jenkins,MichaelPranovich/jenkins_sc,CodeShane/jenkins,wuwen5/jenkins,jcsirot/jenkins,amruthsoft9/Jenkis,jpbriend/jenkins,verbitan/jenkins,jzjzjzj/jenkins,godfath3r/jenkins,akshayabd/jenkins,scoheb/jenkins,Vlatombe/jenkins,paulwellnerbou/jenkins,arunsingh/jenkins,olivergondza/jenkins,paulmillar/jenkins,jtnord/jenkins,shahharsh/jenkins,jpbriend/jenkins,vijayto/jenkins,Vlatombe/jenkins,FTG-003/jenkins,msrb/jenkins,abayer/jenkins,jzjzjzj/jenkins,alvarolobato/jenkins,Ykus/jenkins,ChrisA89/jenkins,amuniz/jenkins,elkingtonmcb/jenkins,vijayto/jenkins,mattclark/jenkins,arcivanov/jenkins,ajshastri/jenkins,ns163/jenkins,seanlin816/jenkins,CodeShane/jenkins,mcanthony/jenkins,intelchen/jenkins,arcivanov/jenkins,Jimilian/jenkins,escoem/jenkins,amuniz/jenkins,keyurpatankar/hudson,dbroady1/jenkins,rlugojr/jenkins,tastatur/jenkins,rashmikanta-1984/jenkins,elkingtonmcb/jenkins,dennisjlee/jenkins,everyonce/jenkins,292388900/jenkins,azweb76/jenkins,amuniz/jenkins,verbitan/jenkins,vjuranek/jenkins,CodeShane/jenkins,christ66/jenkins,ErikVerheul/jenkins,seanlin816/jenkins,gitaccountforprashant/gittest,bpzhang/jenkins,batmat/jenkins,akshayabd/jenkins,wangyikai/jenkins,christ66/jenkins,akshayabd/jenkins,everyonce/jenkins,oleg-nenashev/jenkins,dbroady1/jenkins,andresrc/jenkins,NehemiahMi/jenkins,lvotypko/jenkins2,seanlin816/jenkins,aheritier/jenkins,iqstack/jenkins,lindzh/jenkins,elkingtonmcb/jenkins,h4ck3rm1k3/jenkins,lordofthejars/jenkins,dariver/jenkins,NehemiahMi/jenkins,mdonohue/jenkins,dennisjlee/jenkins,keyurpatankar/hudson,patbos/jenkins,hudson/hudson-2.x,CodeShane/jenkins,liorhson/jenkins,Ykus/jenkins,gorcz/jenkins,daspilker/jenkins,tastatur/jenkins,synopsys-arc-oss/jenkins,noikiy/jenkins,mrobinet/jenkins,MarkEWaite/jenkins,stefanbrausch/hudson-main,tastatur/jenkins,jhoblitt/jenkins,jcsirot/jenkins,brunocvcunha/jenkins,guoxu0514/jenkins,aheritier/jenkins,lilyJi/jenkins,petermarcoen/jenkins,SenolOzer/jenkins,petermarcoen/jenkins,elkingtonmcb/jenkins,DoctorQ/jenkins,SebastienGllmt/jenkins,jk47/jenkins,aquarellian/jenkins,ydubreuil/jenkins
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Stephen Connolly * * 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. */ package hudson.slaves; import hudson.model.*; import hudson.remoting.Channel; import hudson.remoting.VirtualChannel; import hudson.remoting.Callable; import hudson.util.StreamTaskListener; import hudson.util.NullStream; import hudson.util.RingBufferLogHandler; import hudson.util.Futures; import hudson.FilePath; import hudson.lifecycle.WindowsSlaveInstaller; import hudson.Util; import hudson.AbortException; import static hudson.slaves.SlaveComputer.LogHolder.SLAVE_LOG_HANDLER; import java.io.File; import java.io.OutputStream; import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.IOException; import java.io.PrintStream; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import java.util.List; import java.util.Collections; import java.util.ArrayList; import java.nio.charset.Charset; import java.util.concurrent.Future; import java.security.Security; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; /** * {@link Computer} for {@link Slave}s. * * @author Kohsuke Kawaguchi */ public class SlaveComputer extends Computer { private volatile Channel channel; private volatile transient boolean acceptingTasks = true; private Charset defaultCharset; private Boolean isUnix; /** * Effective {@link ComputerLauncher} that hides the details of * how we launch a slave agent on this computer. * * <p> * This is normally the same as {@link Slave#getLauncher()} but * can be different. See {@link #grabLauncher(Node)}. */ private ComputerLauncher launcher; /** * Number of failed attempts to reconnect to this node * (so that if we keep failing to reconnect, we can stop * trying.) */ private transient int numRetryAttempt; /** * Tracks the status of the last launch operation, which is always asynchronous. * This can be used to wait for the completion, or cancel the launch activity. */ private volatile Future<?> lastConnectActivity = null; private Object constructed = new Object(); public SlaveComputer(Slave slave) { super(slave); } /** * {@inheritDoc} */ @Override public boolean isAcceptingTasks() { return acceptingTasks; } /** * Allows a {@linkplain hudson.slaves.ComputerLauncher} or a {@linkplain hudson.slaves.RetentionStrategy} to * suspend tasks being accepted by the slave computer. * * @param acceptingTasks {@code true} if the slave can accept tasks. */ public void setAcceptingTasks(boolean acceptingTasks) { this.acceptingTasks = acceptingTasks; } /** * True if this computer is a Unix machine (as opposed to Windows machine). * * @return * null if the computer is disconnected and therefore we don't know whether it is Unix or not. */ public Boolean isUnix() { return isUnix; } public Slave getNode() { return (Slave)super.getNode(); } @Override public String getIcon() { Future<?> l = lastConnectActivity; if(l!=null && !l.isDone()) return "computer-flash.gif"; return super.getIcon(); } @Override @Deprecated public boolean isJnlpAgent() { return launcher instanceof JNLPLauncher; } @Override public boolean isLaunchSupported() { return launcher.isLaunchSupported(); } public ComputerLauncher getLauncher() { return launcher; } protected Future<?> _connect(boolean forceReconnect) { if(channel!=null) return Futures.precomputed(null); if(!forceReconnect && lastConnectActivity!=null) return lastConnectActivity; if(forceReconnect && lastConnectActivity!=null) logger.fine("Forcing a reconnect"); closeChannel(); return lastConnectActivity = Computer.threadPoolForRemoting.submit(new java.util.concurrent.Callable<Object>() { public Object call() throws Exception { // do this on another thread so that the lengthy launch operation // (which is typical) won't block UI thread. TaskListener listener = new StreamTaskListener(openLogFile()); try { launcher.launch(SlaveComputer.this, listener); return null; } catch (AbortException e) { listener.error(e.getMessage()); throw e; } catch (IOException e) { Util.displayIOException(e,listener); e.printStackTrace(listener.error(Messages.ComputerLauncher_unexpectedError())); throw e; } catch (InterruptedException e) { e.printStackTrace(listener.error(Messages.ComputerLauncher_abortedLaunch())); throw e; } } }); } /** * {@inheritDoc} */ @Override public void taskAccepted(Executor executor, Queue.Task task) { super.taskAccepted(executor, task); if (launcher instanceof ExecutorListener) { ((ExecutorListener)launcher).taskAccepted(executor, task); } if (getNode().getRetentionStrategy() instanceof ExecutorListener) { ((ExecutorListener)getNode().getRetentionStrategy()).taskAccepted(executor, task); } } /** * {@inheritDoc} */ @Override public void taskCompleted(Executor executor, Queue.Task task, long durationMS) { super.taskCompleted(executor, task, durationMS); if (launcher instanceof ExecutorListener) { ((ExecutorListener)launcher).taskCompleted(executor, task, durationMS); } RetentionStrategy r = getNode().getRetentionStrategy(); if (r instanceof ExecutorListener) { ((ExecutorListener) r).taskCompleted(executor, task, durationMS); } } /** * {@inheritDoc} */ @Override public void taskCompletedWithProblems(Executor executor, Queue.Task task, long durationMS, Throwable problems) { super.taskCompletedWithProblems(executor, task, durationMS, problems); if (launcher instanceof ExecutorListener) { ((ExecutorListener)launcher).taskCompletedWithProblems(executor, task, durationMS, problems); } if (getNode().getRetentionStrategy() instanceof ExecutorListener) { ((ExecutorListener)getNode().getRetentionStrategy()).taskCompletedWithProblems(executor, task, durationMS, problems); } } @Override public boolean isConnecting() { Future<?> l = lastConnectActivity; return isOffline() && l!=null && !l.isDone(); } public OutputStream openLogFile() { OutputStream os; try { os = new FileOutputStream(getLogFile()); } catch (FileNotFoundException e) { logger.log(Level.SEVERE, "Failed to create log file "+getLogFile(),e); os = new NullStream(); } return os; } private final Object channelLock = new Object(); public void setChannel(InputStream in, OutputStream out, TaskListener taskListener, Channel.Listener listener) throws IOException, InterruptedException { setChannel(in,out,taskListener.getLogger(),listener); } /** * Creates a {@link Channel} from the given stream and sets that to this slave. * * @param in * Stream connected to the remote "slave.jar". It's the caller's responsibility to do * buffering on this stream, if that's necessary. * @param out * Stream connected to the remote peer. It's the caller's responsibility to do * buffering on this stream, if that's necessary. * @param launchLog * If non-null, receive the portion of data in <tt>is</tt> before * the data goes into the "binary mode". This is useful * when the established communication channel might include some data that might * be useful for debugging/trouble-shooting. * @param listener * Gets a notification when the channel closes, to perform clean up. Can be null. */ public void setChannel(InputStream in, OutputStream out, OutputStream launchLog, Channel.Listener listener) throws IOException, InterruptedException { if(this.channel!=null) throw new IllegalStateException("Already connected"); final TaskListener taskListener = new StreamTaskListener(launchLog); PrintStream log = taskListener.getLogger(); Channel channel = new Channel(nodeName,threadPoolForRemoting, Channel.Mode.NEGOTIATE, in,out, launchLog); channel.addListener(new Channel.Listener() { public void onClosed(Channel c,IOException cause) { SlaveComputer.this.channel = null; launcher.afterDisconnect(SlaveComputer.this, taskListener); } }); if(listener!=null) channel.addListener(listener); boolean _isUnix = channel.call(new DetectOS()); log.println(_isUnix? hudson.model.Messages.Slave_UnixSlave():hudson.model.Messages.Slave_WindowsSlave()); String defaultCharsetName = channel.call(new DetectDefaultCharset()); String remoteFs = getNode().getRemoteFS(); if(_isUnix && !remoteFs.contains("/") && remoteFs.contains("\\")) log.println("WARNING: "+remoteFs+" looks suspiciously like Windows path. Maybe you meant "+remoteFs.replace('\\','/')+"?"); FilePath root = new FilePath(channel,getNode().getRemoteFS()); channel.call(new SlaveInitializer()); channel.call(new WindowsSlaveInstaller(remoteFs)); for (ComputerListener cl : ComputerListener.all()) cl.preOnline(this,channel,root,taskListener); // update the data structure atomically to prevent others from seeing a channel that's not properly initialized yet synchronized(channelLock) { if(this.channel!=null) { // check again. we used to have this entire method in a big sycnhronization block, // but Channel constructor blocks for an external process to do the connection // if CommandLauncher is used, and that cannot be interrupted because it blocks at InputStream. // so if the process hangs, it hangs the thread in a lock, and since Hudson will try to relaunch, // we'll end up queuing the lot of threads in a pseudo deadlock. // This implementation prevents that by avoiding a lock. HUDSON-1705 is likely a manifestation of this. channel.close(); throw new IllegalStateException("Already connected"); } isUnix = _isUnix; numRetryAttempt = 0; this.channel = channel; defaultCharset = Charset.forName(defaultCharsetName); } for (ComputerListener cl : ComputerListener.all()) cl.onOnline(this,taskListener); Hudson.getInstance().getQueue().scheduleMaintenance(); } @Override public VirtualChannel getChannel() { return channel; } public Charset getDefaultCharset() { return defaultCharset; } public List<LogRecord> getLogRecords() throws IOException, InterruptedException { if(channel==null) return Collections.emptyList(); else return channel.call(new Callable<List<LogRecord>,RuntimeException>() { public List<LogRecord> call() { return new ArrayList<LogRecord>(SLAVE_LOG_HANDLER.getView()); } }); } public void doDoDisconnect(StaplerResponse rsp) throws IOException, ServletException { checkPermission(Hudson.ADMINISTER); disconnect(); rsp.sendRedirect("."); } @Override public Future<?> disconnect() { super.disconnect(); return Computer.threadPoolForRemoting.submit(new Runnable() { public void run() { // do this on another thread so that any lengthy disconnect operation // (which could be typical) won't block UI thread. TaskListener listener = new StreamTaskListener(openLogFile()); launcher.beforeDisconnect(SlaveComputer.this, listener); closeChannel(); launcher.afterDisconnect(SlaveComputer.this, listener); } }); } public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { if(channel!=null) { rsp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } connect(true); // TODO: would be nice to redirect the user to "launching..." wait page, // then spend a few seconds there and poll for the completion periodically. rsp.sendRedirect("log"); } public void tryReconnect() { numRetryAttempt++; if(numRetryAttempt<6 || (numRetryAttempt%12)==0) { // initially retry several times quickly, and after that, do it infrequently. logger.info("Attempting to reconnect "+nodeName); connect(true); } } /** * Serves jar files for JNLP slave agents. * * @deprecated * This URL binding is no longer used and moved up directly under to {@link Hudson}, * but it's left here for now just in case some old JNLP slave agents request it. */ public Slave.JnlpJar getJnlpJars(String fileName) { return new Slave.JnlpJar(fileName); } @Override protected void kill() { super.kill(); closeChannel(); } public RetentionStrategy getRetentionStrategy() { return getNode().getRetentionStrategy(); } /** * If still connected, disconnect. */ private void closeChannel() { // TODO: race condition between this and the setChannel method. Channel c = channel; channel = null; isUnix = null; if (c != null) { try { c.close(); } catch (IOException e) { logger.log(Level.SEVERE, "Failed to terminate channel to " + getDisplayName(), e); } } for (ComputerListener cl : ComputerListener.all()) cl.onOffline(this); } @Override protected void setNode(Node node) { super.setNode(node); launcher = grabLauncher(node); // maybe the configuration was changed to relaunch the slave, so try to re-launch now. // "constructed==null" test is an ugly hack to avoid launching before the object is fully // constructed. if(constructed!=null) connect(false); } /** * Grabs a {@link ComputerLauncher} out of {@link Node} to keep it in this {@link Computer}. * The returned launcher will be set to {@link #launcher} and used to carry out the actual launch operation. * * <p> * Subtypes that needs to decorate {@link ComputerLauncher} can do so by overriding this method. * This is useful for {@link SlaveComputer}s for clouds for example, where one normally needs * additional pre-launch step (such as waiting for the provisioned node to become available) * before the user specified launch step (like SSH connection) kicks in. * * @see ComputerLauncherFilter */ protected ComputerLauncher grabLauncher(Node node) { return ((Slave)node).getLauncher(); } private static final Logger logger = Logger.getLogger(SlaveComputer.class.getName()); private static final class DetectOS implements Callable<Boolean,IOException> { public Boolean call() throws IOException { return File.pathSeparatorChar==':'; } } private static final class DetectDefaultCharset implements Callable<String,IOException> { public String call() throws IOException { return Charset.defaultCharset().name(); } } /** * Puts the {@link #SLAVE_LOG_HANDLER} into a separate class so that loading this class * in JVM doesn't end up loading tons of additional classes. */ static final class LogHolder { /** * This field is used on each slave node to record log records on the slave. */ static final RingBufferLogHandler SLAVE_LOG_HANDLER = new RingBufferLogHandler(); } private static class SlaveInitializer implements Callable<Void,RuntimeException> { public Void call() { // avoid double installation of the handler Logger logger = Logger.getLogger("hudson"); logger.removeHandler(SLAVE_LOG_HANDLER); logger.addHandler(SLAVE_LOG_HANDLER); // remove Sun PKCS11 provider if present. See http://hudson.gotdns.com/wiki/display/HUDSON/Solaris+Issue+6276483 try { Security.removeProvider("SunPKCS11-Solaris"); } catch (SecurityException e) { // ignore this error. } return null; } private static final long serialVersionUID = 1L; } }
core/src/main/java/hudson/slaves/SlaveComputer.java
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Stephen Connolly * * 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. */ package hudson.slaves; import hudson.model.*; import hudson.remoting.Channel; import hudson.remoting.VirtualChannel; import hudson.remoting.Callable; import hudson.util.StreamTaskListener; import hudson.util.NullStream; import hudson.util.RingBufferLogHandler; import hudson.util.Futures; import hudson.FilePath; import hudson.lifecycle.WindowsSlaveInstaller; import hudson.Util; import hudson.AbortException; import static hudson.slaves.SlaveComputer.LogHolder.SLAVE_LOG_HANDLER; import java.io.File; import java.io.OutputStream; import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.IOException; import java.io.PrintStream; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; import java.util.List; import java.util.Collections; import java.util.ArrayList; import java.nio.charset.Charset; import java.util.concurrent.Future; import java.security.Security; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; /** * {@link Computer} for {@link Slave}s. * * @author Kohsuke Kawaguchi */ public class SlaveComputer extends Computer { private volatile Channel channel; private volatile transient boolean acceptingTasks = true; private Charset defaultCharset; private Boolean isUnix; /** * Effective {@link ComputerLauncher} that hides the details of * how we launch a slave agent on this computer. * * <p> * This is normally the same as {@link Slave#getLauncher()} but * can be different. See {@link #grabLauncher(Node)}. */ private ComputerLauncher launcher; /** * Number of failed attempts to reconnect to this node * (so that if we keep failing to reconnect, we can stop * trying.) */ private transient int numRetryAttempt; /** * Tracks the status of the last launch operation, which is always asynchronous. * This can be used to wait for the completion, or cancel the launch activity. */ private volatile Future<?> lastConnectActivity = null; private Object constructed = new Object(); public SlaveComputer(Slave slave) { super(slave); } /** * {@inheritDoc} */ @Override public boolean isAcceptingTasks() { return acceptingTasks; } /** * Allows a {@linkplain hudson.slaves.ComputerLauncher} or a {@linkplain hudson.slaves.RetentionStrategy} to * suspend tasks being accepted by the slave computer. * * @param acceptingTasks {@code true} if the slave can accept tasks. */ public void setAcceptingTasks(boolean acceptingTasks) { this.acceptingTasks = acceptingTasks; } /** * True if this computer is a Unix machine (as opposed to Windows machine). * * @return * null if the computer is disconnected and therefore we don't know whether it is Unix or not. */ public Boolean isUnix() { return isUnix; } public Slave getNode() { return (Slave)super.getNode(); } @Override public String getIcon() { Future<?> l = lastConnectActivity; if(l!=null && !l.isDone()) return "computer-flash.gif"; return super.getIcon(); } @Override @Deprecated public boolean isJnlpAgent() { return launcher instanceof JNLPLauncher; } @Override public boolean isLaunchSupported() { return launcher.isLaunchSupported(); } public ComputerLauncher getLauncher() { return launcher; } protected Future<?> _connect(boolean forceReconnect) { if(channel!=null) return Futures.precomputed(null); if(!forceReconnect && lastConnectActivity!=null) return lastConnectActivity; if(forceReconnect && lastConnectActivity!=null) logger.fine("Forcing a reconnect"); closeChannel(); return lastConnectActivity = Computer.threadPoolForRemoting.submit(new java.util.concurrent.Callable<Object>() { public Object call() throws Exception { // do this on another thread so that the lengthy launch operation // (which is typical) won't block UI thread. TaskListener listener = new StreamTaskListener(openLogFile()); try { launcher.launch(SlaveComputer.this, listener); return null; } catch (AbortException e) { listener.error(e.getMessage()); throw e; } catch (IOException e) { Util.displayIOException(e,listener); e.printStackTrace(listener.error(Messages.ComputerLauncher_unexpectedError())); throw e; } catch (InterruptedException e) { e.printStackTrace(listener.error(Messages.ComputerLauncher_abortedLaunch())); throw e; } } }); } /** * {@inheritDoc} */ @Override public void taskAccepted(Executor executor, Queue.Task task) { super.taskAccepted(executor, task); if (launcher instanceof ExecutorListener) { ((ExecutorListener)launcher).taskAccepted(executor, task); } if (getNode().getRetentionStrategy() instanceof ExecutorListener) { ((ExecutorListener)getNode().getRetentionStrategy()).taskAccepted(executor, task); } } /** * {@inheritDoc} */ @Override public void taskCompleted(Executor executor, Queue.Task task, long durationMS) { super.taskCompleted(executor, task, durationMS); if (launcher instanceof ExecutorListener) { ((ExecutorListener)launcher).taskCompleted(executor, task, durationMS); } if (getNode().getRetentionStrategy() instanceof ExecutorListener) { ((ExecutorListener)getNode().getRetentionStrategy()).taskCompleted(executor, task, durationMS); } } /** * {@inheritDoc} */ @Override public void taskCompletedWithProblems(Executor executor, Queue.Task task, long durationMS, Throwable problems) { super.taskCompletedWithProblems(executor, task, durationMS, problems); if (launcher instanceof ExecutorListener) { ((ExecutorListener)launcher).taskCompletedWithProblems(executor, task, durationMS, problems); } if (getNode().getRetentionStrategy() instanceof ExecutorListener) { ((ExecutorListener)getNode().getRetentionStrategy()).taskCompletedWithProblems(executor, task, durationMS, problems); } } @Override public boolean isConnecting() { Future<?> l = lastConnectActivity; return isOffline() && l!=null && !l.isDone(); } public OutputStream openLogFile() { OutputStream os; try { os = new FileOutputStream(getLogFile()); } catch (FileNotFoundException e) { logger.log(Level.SEVERE, "Failed to create log file "+getLogFile(),e); os = new NullStream(); } return os; } private final Object channelLock = new Object(); public void setChannel(InputStream in, OutputStream out, TaskListener taskListener, Channel.Listener listener) throws IOException, InterruptedException { setChannel(in,out,taskListener.getLogger(),listener); } /** * Creates a {@link Channel} from the given stream and sets that to this slave. * * @param in * Stream connected to the remote "slave.jar". It's the caller's responsibility to do * buffering on this stream, if that's necessary. * @param out * Stream connected to the remote peer. It's the caller's responsibility to do * buffering on this stream, if that's necessary. * @param launchLog * If non-null, receive the portion of data in <tt>is</tt> before * the data goes into the "binary mode". This is useful * when the established communication channel might include some data that might * be useful for debugging/trouble-shooting. * @param listener * Gets a notification when the channel closes, to perform clean up. Can be null. */ public void setChannel(InputStream in, OutputStream out, OutputStream launchLog, Channel.Listener listener) throws IOException, InterruptedException { if(this.channel!=null) throw new IllegalStateException("Already connected"); final TaskListener taskListener = new StreamTaskListener(launchLog); PrintStream log = taskListener.getLogger(); Channel channel = new Channel(nodeName,threadPoolForRemoting, Channel.Mode.NEGOTIATE, in,out, launchLog); channel.addListener(new Channel.Listener() { public void onClosed(Channel c,IOException cause) { SlaveComputer.this.channel = null; launcher.afterDisconnect(SlaveComputer.this, taskListener); } }); if(listener!=null) channel.addListener(listener); boolean _isUnix = channel.call(new DetectOS()); log.println(_isUnix? hudson.model.Messages.Slave_UnixSlave():hudson.model.Messages.Slave_WindowsSlave()); String defaultCharsetName = channel.call(new DetectDefaultCharset()); String remoteFs = getNode().getRemoteFS(); if(_isUnix && !remoteFs.contains("/") && remoteFs.contains("\\")) log.println("WARNING: "+remoteFs+" looks suspiciously like Windows path. Maybe you meant "+remoteFs.replace('\\','/')+"?"); FilePath root = new FilePath(channel,getNode().getRemoteFS()); channel.call(new SlaveInitializer()); channel.call(new WindowsSlaveInstaller(remoteFs)); for (ComputerListener cl : ComputerListener.all()) cl.preOnline(this,channel,root,taskListener); // update the data structure atomically to prevent others from seeing a channel that's not properly initialized yet synchronized(channelLock) { if(this.channel!=null) { // check again. we used to have this entire method in a big sycnhronization block, // but Channel constructor blocks for an external process to do the connection // if CommandLauncher is used, and that cannot be interrupted because it blocks at InputStream. // so if the process hangs, it hangs the thread in a lock, and since Hudson will try to relaunch, // we'll end up queuing the lot of threads in a pseudo deadlock. // This implementation prevents that by avoiding a lock. HUDSON-1705 is likely a manifestation of this. channel.close(); throw new IllegalStateException("Already connected"); } isUnix = _isUnix; numRetryAttempt = 0; this.channel = channel; defaultCharset = Charset.forName(defaultCharsetName); } for (ComputerListener cl : ComputerListener.all()) cl.onOnline(this,taskListener); Hudson.getInstance().getQueue().scheduleMaintenance(); } @Override public VirtualChannel getChannel() { return channel; } public Charset getDefaultCharset() { return defaultCharset; } public List<LogRecord> getLogRecords() throws IOException, InterruptedException { if(channel==null) return Collections.emptyList(); else return channel.call(new Callable<List<LogRecord>,RuntimeException>() { public List<LogRecord> call() { return new ArrayList<LogRecord>(SLAVE_LOG_HANDLER.getView()); } }); } public void doDoDisconnect(StaplerResponse rsp) throws IOException, ServletException { checkPermission(Hudson.ADMINISTER); disconnect(); rsp.sendRedirect("."); } @Override public Future<?> disconnect() { super.disconnect(); return Computer.threadPoolForRemoting.submit(new Runnable() { public void run() { // do this on another thread so that any lengthy disconnect operation // (which could be typical) won't block UI thread. TaskListener listener = new StreamTaskListener(openLogFile()); launcher.beforeDisconnect(SlaveComputer.this, listener); closeChannel(); launcher.afterDisconnect(SlaveComputer.this, listener); } }); } public void doLaunchSlaveAgent(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { if(channel!=null) { rsp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } connect(true); // TODO: would be nice to redirect the user to "launching..." wait page, // then spend a few seconds there and poll for the completion periodically. rsp.sendRedirect("log"); } public void tryReconnect() { numRetryAttempt++; if(numRetryAttempt<6 || (numRetryAttempt%12)==0) { // initially retry several times quickly, and after that, do it infrequently. logger.info("Attempting to reconnect "+nodeName); connect(true); } } /** * Serves jar files for JNLP slave agents. * * @deprecated * This URL binding is no longer used and moved up directly under to {@link Hudson}, * but it's left here for now just in case some old JNLP slave agents request it. */ public Slave.JnlpJar getJnlpJars(String fileName) { return new Slave.JnlpJar(fileName); } @Override protected void kill() { super.kill(); closeChannel(); } public RetentionStrategy getRetentionStrategy() { return getNode().getRetentionStrategy(); } /** * If still connected, disconnect. */ private void closeChannel() { // TODO: race condition between this and the setChannel method. Channel c = channel; channel = null; isUnix = null; if (c != null) { try { c.close(); } catch (IOException e) { logger.log(Level.SEVERE, "Failed to terminate channel to " + getDisplayName(), e); } } for (ComputerListener cl : ComputerListener.all()) cl.onOffline(this); } @Override protected void setNode(Node node) { super.setNode(node); launcher = grabLauncher(node); // maybe the configuration was changed to relaunch the slave, so try to re-launch now. // "constructed==null" test is an ugly hack to avoid launching before the object is fully // constructed. if(constructed!=null) connect(false); } /** * Grabs a {@link ComputerLauncher} out of {@link Node} to keep it in this {@link Computer}. * The returned launcher will be set to {@link #launcher} and used to carry out the actual launch operation. * * <p> * Subtypes that needs to decorate {@link ComputerLauncher} can do so by overriding this method. * This is useful for {@link SlaveComputer}s for clouds for example, where one normally needs * additional pre-launch step (such as waiting for the provisioned node to become available) * before the user specified launch step (like SSH connection) kicks in. * * @see ComputerLauncherFilter */ protected ComputerLauncher grabLauncher(Node node) { return ((Slave)node).getLauncher(); } private static final Logger logger = Logger.getLogger(SlaveComputer.class.getName()); private static final class DetectOS implements Callable<Boolean,IOException> { public Boolean call() throws IOException { return File.pathSeparatorChar==':'; } } private static final class DetectDefaultCharset implements Callable<String,IOException> { public String call() throws IOException { return Charset.defaultCharset().name(); } } /** * Puts the {@link #SLAVE_LOG_HANDLER} into a separate class so that loading this class * in JVM doesn't end up loading tons of additional classes. */ static final class LogHolder { /** * This field is used on each slave node to record log records on the slave. */ static final RingBufferLogHandler SLAVE_LOG_HANDLER = new RingBufferLogHandler(); } private static class SlaveInitializer implements Callable<Void,RuntimeException> { public Void call() { // avoid double installation of the handler Logger logger = Logger.getLogger("hudson"); logger.removeHandler(SLAVE_LOG_HANDLER); logger.addHandler(SLAVE_LOG_HANDLER); // remove Sun PKCS11 provider if present. See http://hudson.gotdns.com/wiki/display/HUDSON/Solaris+Issue+6276483 try { Security.removeProvider("SunPKCS11-Solaris"); } catch (SecurityException e) { // ignore this error. } return null; } private static final long serialVersionUID = 1L; } }
fixed a possible race condition git-svn-id: 28f34f9aa52bc55a5ddd5be9e183c5cccadc6ee4@20294 71c3de6d-444a-0410-be80-ed276b4c234a
core/src/main/java/hudson/slaves/SlaveComputer.java
fixed a possible race condition
<ide><path>ore/src/main/java/hudson/slaves/SlaveComputer.java <ide> if (launcher instanceof ExecutorListener) { <ide> ((ExecutorListener)launcher).taskCompleted(executor, task, durationMS); <ide> } <del> if (getNode().getRetentionStrategy() instanceof ExecutorListener) { <del> ((ExecutorListener)getNode().getRetentionStrategy()).taskCompleted(executor, task, durationMS); <add> RetentionStrategy r = getNode().getRetentionStrategy(); <add> if (r instanceof ExecutorListener) { <add> ((ExecutorListener) r).taskCompleted(executor, task, durationMS); <ide> } <ide> } <ide>
Java
apache-2.0
b82dfecac9e1d4c505dab0cc789d0efcbd0f9d1a
0
GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit
// Copyright (C) 2012 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // WARNING: NoteDbUpdateManager cares about the package name RestApiServlet lives in. package com.google.gerrit.httpd.restapi; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.common.flogger.LazyArgs.lazy; import static com.google.common.net.HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS; import static com.google.common.net.HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS; import static com.google.common.net.HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS; import static com.google.common.net.HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN; import static com.google.common.net.HttpHeaders.ACCESS_CONTROL_MAX_AGE; import static com.google.common.net.HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS; import static com.google.common.net.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD; import static com.google.common.net.HttpHeaders.AUTHORIZATION; import static com.google.common.net.HttpHeaders.CONTENT_TYPE; import static com.google.common.net.HttpHeaders.ORIGIN; import static com.google.common.net.HttpHeaders.VARY; import static java.math.RoundingMode.CEILING; import static java.nio.charset.StandardCharsets.ISO_8859_1; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.joining; import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; import static javax.servlet.http.HttpServletResponse.SC_CONFLICT; import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN; import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; import static javax.servlet.http.HttpServletResponse.SC_METHOD_NOT_ALLOWED; import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; import static javax.servlet.http.HttpServletResponse.SC_NOT_IMPLEMENTED; import static javax.servlet.http.HttpServletResponse.SC_NOT_MODIFIED; import static javax.servlet.http.HttpServletResponse.SC_OK; import static javax.servlet.http.HttpServletResponse.SC_PRECONDITION_FAILED; import static javax.servlet.http.HttpServletResponse.SC_SERVICE_UNAVAILABLE; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.CharMatcher; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.flogger.FluentLogger; import com.google.common.io.BaseEncoding; import com.google.common.io.CountingOutputStream; import com.google.common.math.IntMath; import com.google.common.net.HttpHeaders; import com.google.gerrit.common.Nullable; import com.google.gerrit.common.RawInputUtil; import com.google.gerrit.entities.Project; import com.google.gerrit.extensions.registration.DynamicItem; import com.google.gerrit.extensions.registration.DynamicMap; import com.google.gerrit.extensions.registration.DynamicSet; import com.google.gerrit.extensions.registration.PluginName; import com.google.gerrit.extensions.restapi.AuthException; import com.google.gerrit.extensions.restapi.BadRequestException; import com.google.gerrit.extensions.restapi.BinaryResult; import com.google.gerrit.extensions.restapi.CacheControl; import com.google.gerrit.extensions.restapi.DefaultInput; import com.google.gerrit.extensions.restapi.ETagView; import com.google.gerrit.extensions.restapi.IdString; import com.google.gerrit.extensions.restapi.MethodNotAllowedException; import com.google.gerrit.extensions.restapi.NeedsParams; import com.google.gerrit.extensions.restapi.NotImplementedException; import com.google.gerrit.extensions.restapi.PreconditionFailedException; import com.google.gerrit.extensions.restapi.RawInput; import com.google.gerrit.extensions.restapi.ResourceConflictException; import com.google.gerrit.extensions.restapi.ResourceNotFoundException; import com.google.gerrit.extensions.restapi.Response; import com.google.gerrit.extensions.restapi.RestApiException; import com.google.gerrit.extensions.restapi.RestCollection; import com.google.gerrit.extensions.restapi.RestCollectionCreateView; import com.google.gerrit.extensions.restapi.RestCollectionDeleteMissingView; import com.google.gerrit.extensions.restapi.RestCollectionModifyView; import com.google.gerrit.extensions.restapi.RestCollectionView; import com.google.gerrit.extensions.restapi.RestModifyView; import com.google.gerrit.extensions.restapi.RestReadView; import com.google.gerrit.extensions.restapi.RestResource; import com.google.gerrit.extensions.restapi.RestView; import com.google.gerrit.extensions.restapi.TopLevelResource; import com.google.gerrit.extensions.restapi.UnprocessableEntityException; import com.google.gerrit.git.LockFailureException; import com.google.gerrit.httpd.WebSession; import com.google.gerrit.httpd.restapi.ParameterParser.QueryParams; import com.google.gerrit.json.OutputFormat; import com.google.gerrit.server.AccessPath; import com.google.gerrit.server.AnonymousUser; import com.google.gerrit.server.CurrentUser; import com.google.gerrit.server.OptionUtil; import com.google.gerrit.server.RequestInfo; import com.google.gerrit.server.RequestListener; import com.google.gerrit.server.audit.ExtendedHttpAuditEvent; import com.google.gerrit.server.cache.PerThreadCache; import com.google.gerrit.server.change.ChangeFinder; import com.google.gerrit.server.config.GerritServerConfig; import com.google.gerrit.server.group.GroupAuditService; import com.google.gerrit.server.logging.PerformanceLogContext; import com.google.gerrit.server.logging.PerformanceLogger; import com.google.gerrit.server.logging.RequestId; import com.google.gerrit.server.logging.TraceContext; import com.google.gerrit.server.notedb.ChangeNotes; import com.google.gerrit.server.permissions.GlobalPermission; import com.google.gerrit.server.permissions.PermissionBackend; import com.google.gerrit.server.permissions.PermissionBackendException; import com.google.gerrit.server.plugincontext.PluginSetContext; import com.google.gerrit.server.quota.QuotaException; import com.google.gerrit.server.restapi.change.ChangesCollection; import com.google.gerrit.server.restapi.project.ProjectsCollection; import com.google.gerrit.server.update.RetryHelper; import com.google.gerrit.server.update.RetryHelper.Action; import com.google.gerrit.server.update.RetryHelper.ActionType; import com.google.gerrit.server.update.UpdateException; import com.google.gerrit.server.util.time.TimeUtil; import com.google.gerrit.util.http.CacheHeaders; import com.google.gerrit.util.http.RequestUtil; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import com.google.gson.stream.MalformedJsonException; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.TypeLiteral; import com.google.inject.util.Providers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.TimeUnit; import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.Stream; import java.util.zip.GZIPOutputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import org.eclipse.jgit.http.server.ServletUtils; import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.util.TemporaryBuffer; import org.eclipse.jgit.util.TemporaryBuffer.Heap; public class RestApiServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** MIME type used for a JSON response body. */ private static final String JSON_TYPE = "application/json"; private static final String FORM_TYPE = "application/x-www-form-urlencoded"; @VisibleForTesting public static final String X_GERRIT_TRACE = "X-Gerrit-Trace"; private static final String X_REQUESTED_WITH = "X-Requested-With"; private static final String X_GERRIT_AUTH = "X-Gerrit-Auth"; static final ImmutableSet<String> ALLOWED_CORS_METHODS = ImmutableSet.of("GET", "HEAD", "POST", "PUT", "DELETE"); private static final ImmutableSet<String> ALLOWED_CORS_REQUEST_HEADERS = Stream.of(AUTHORIZATION, CONTENT_TYPE, X_GERRIT_AUTH, X_REQUESTED_WITH) .map(s -> s.toLowerCase(Locale.US)) .collect(ImmutableSet.toImmutableSet()); public static final String XD_AUTHORIZATION = "access_token"; public static final String XD_CONTENT_TYPE = "$ct"; public static final String XD_METHOD = "$m"; public static final int SC_UNPROCESSABLE_ENTITY = 422; public static final int SC_TOO_MANY_REQUESTS = 429; private static final int HEAP_EST_SIZE = 10 * 8 * 1024; // Presize 10 blocks. private static final String PLAIN_TEXT = "text/plain"; private static final Pattern TYPE_SPLIT_PATTERN = Pattern.compile("[ ,;][ ,;]*"); /** * Garbage prefix inserted before JSON output to prevent XSSI. * * <p>This prefix is ")]}'\n" and is designed to prevent a web browser from executing the response * body if the resource URI were to be referenced using a &lt;script src="...&gt; HTML tag from * another web site. Clients using the HTTP interface will need to always strip the first line of * response data to remove this magic header. */ public static final byte[] JSON_MAGIC; static { JSON_MAGIC = ")]}'\n".getBytes(UTF_8); } public static class Globals { final Provider<CurrentUser> currentUser; final DynamicItem<WebSession> webSession; final Provider<ParameterParser> paramParser; final PluginSetContext<RequestListener> requestListeners; final PermissionBackend permissionBackend; final GroupAuditService auditService; final RestApiMetrics metrics; final Pattern allowOrigin; final RestApiQuotaEnforcer quotaChecker; final Config config; final DynamicSet<PerformanceLogger> performanceLoggers; final ChangeFinder changeFinder; final RetryHelper retryHelper; @Inject Globals( Provider<CurrentUser> currentUser, DynamicItem<WebSession> webSession, Provider<ParameterParser> paramParser, PluginSetContext<RequestListener> requestListeners, PermissionBackend permissionBackend, GroupAuditService auditService, RestApiMetrics metrics, RestApiQuotaEnforcer quotaChecker, @GerritServerConfig Config config, DynamicSet<PerformanceLogger> performanceLoggers, ChangeFinder changeFinder, RetryHelper retryHelper) { this.currentUser = currentUser; this.webSession = webSession; this.paramParser = paramParser; this.requestListeners = requestListeners; this.permissionBackend = permissionBackend; this.auditService = auditService; this.metrics = metrics; this.quotaChecker = quotaChecker; this.config = config; this.performanceLoggers = performanceLoggers; this.changeFinder = changeFinder; this.retryHelper = retryHelper; allowOrigin = makeAllowOrigin(config); } private static Pattern makeAllowOrigin(Config cfg) { String[] allow = cfg.getStringList("site", null, "allowOriginRegex"); if (allow.length > 0) { return Pattern.compile(Joiner.on('|').join(allow)); } return null; } } private final Globals globals; private final Provider<RestCollection<RestResource, RestResource>> members; private Optional<String> traceId = Optional.empty(); public RestApiServlet( Globals globals, RestCollection<? extends RestResource, ? extends RestResource> members) { this(globals, Providers.of(members)); } public RestApiServlet( Globals globals, Provider<? extends RestCollection<? extends RestResource, ? extends RestResource>> members) { @SuppressWarnings("unchecked") Provider<RestCollection<RestResource, RestResource>> n = (Provider<RestCollection<RestResource, RestResource>>) requireNonNull((Object) members); this.globals = globals; this.members = n; } @Override protected final void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { final long startNanos = System.nanoTime(); long auditStartTs = TimeUtil.nowMs(); res.setHeader("Content-Disposition", "attachment"); res.setHeader("X-Content-Type-Options", "nosniff"); int status = SC_OK; long responseBytes = -1; Response<?> response = null; QueryParams qp = null; Object inputRequestBody = null; RestResource rsrc = TopLevelResource.INSTANCE; ViewData viewData = null; try (TraceContext traceContext = enableTracing(req, res)) { List<IdString> path = splitPath(req); RequestInfo requestInfo = createRequestInfo(traceContext, requestUri(req), path); globals.requestListeners.runEach(l -> l.onRequest(requestInfo)); try (PerThreadCache ignored = PerThreadCache.create()) { // It's important that the PerformanceLogContext is closed before the response is sent to // the client. Only this way it is ensured that the invocation of the PerformanceLogger // plugins happens before the client sees the response. This is needed for being able to // test performance logging from an acceptance test (see // TraceIT#performanceLoggingForRestCall()). try (PerformanceLogContext performanceLogContext = new PerformanceLogContext(globals.config, globals.performanceLoggers)) { traceRequestData(req); if (isCorsPreflight(req)) { doCorsPreflight(req, res); return; } qp = ParameterParser.getQueryParams(req); checkCors(req, res, qp.hasXdOverride()); if (qp.hasXdOverride()) { req = applyXdOverrides(req, qp); } checkUserSession(req); RestCollection<RestResource, RestResource> rc = members.get(); globals .permissionBackend .currentUser() .checkAny(GlobalPermission.fromAnnotation(rc.getClass())); viewData = new ViewData(null, null); if (path.isEmpty()) { globals.quotaChecker.enforce(req); if (rc instanceof NeedsParams) { ((NeedsParams) rc).setParams(qp.params()); } if (isRead(req)) { viewData = new ViewData(null, rc.list()); } else if (isPost(req)) { RestView<RestResource> restCollectionView = rc.views().get(PluginName.GERRIT, "POST_ON_COLLECTION./"); if (restCollectionView != null) { viewData = new ViewData(null, restCollectionView); } else { throw methodNotAllowed(req); } } else { // DELETE on root collections is not supported throw methodNotAllowed(req); } } else { IdString id = path.remove(0); try { rsrc = rc.parse(rsrc, id); globals.quotaChecker.enforce(rsrc, req); if (path.isEmpty()) { checkPreconditions(req); } } catch (ResourceNotFoundException e) { if (!path.isEmpty()) { throw e; } globals.quotaChecker.enforce(req); if (isPost(req) || isPut(req)) { RestView<RestResource> createView = rc.views().get(PluginName.GERRIT, "CREATE./"); if (createView != null) { viewData = new ViewData(null, createView); path.add(id); } else { throw e; } } else if (isDelete(req)) { RestView<RestResource> deleteView = rc.views().get(PluginName.GERRIT, "DELETE_MISSING./"); if (deleteView != null) { viewData = new ViewData(null, deleteView); path.add(id); } else { throw e; } } else { throw e; } } if (viewData.view == null) { viewData = view(rc, req.getMethod(), path); } } checkRequiresCapability(viewData); while (viewData.view instanceof RestCollection<?, ?>) { @SuppressWarnings("unchecked") RestCollection<RestResource, RestResource> c = (RestCollection<RestResource, RestResource>) viewData.view; if (path.isEmpty()) { if (isRead(req)) { viewData = new ViewData(null, c.list()); } else if (isPost(req)) { // TODO: Here and on other collection methods: There is a bug that binds child views // with pluginName="gerrit" instead of the real plugin name. This has never worked // correctly and should be fixed where the binding gets created (DynamicMapProvider) // and here. RestView<RestResource> restCollectionView = c.views().get(PluginName.GERRIT, "POST_ON_COLLECTION./"); if (restCollectionView != null) { viewData = new ViewData(null, restCollectionView); } else { throw methodNotAllowed(req); } } else if (isDelete(req)) { RestView<RestResource> restCollectionView = c.views().get(PluginName.GERRIT, "DELETE_ON_COLLECTION./"); if (restCollectionView != null) { viewData = new ViewData(null, restCollectionView); } else { throw methodNotAllowed(req); } } else { throw methodNotAllowed(req); } break; } IdString id = path.remove(0); try { rsrc = c.parse(rsrc, id); checkPreconditions(req); viewData = new ViewData(null, null); } catch (ResourceNotFoundException e) { if (!path.isEmpty()) { throw e; } if (isPost(req) || isPut(req)) { RestView<RestResource> createView = c.views().get(PluginName.GERRIT, "CREATE./"); if (createView != null) { viewData = new ViewData(viewData.pluginName, createView); path.add(id); } else { throw e; } } else if (isDelete(req)) { RestView<RestResource> deleteView = c.views().get(PluginName.GERRIT, "DELETE_MISSING./"); if (deleteView != null) { viewData = new ViewData(viewData.pluginName, deleteView); path.add(id); } else { throw e; } } else { throw e; } } if (viewData.view == null) { viewData = view(c, req.getMethod(), path); } checkRequiresCapability(viewData); } if (notModified(req, rsrc, viewData.view)) { logger.atFinest().log("REST call succeeded: %d", SC_NOT_MODIFIED); res.sendError(SC_NOT_MODIFIED); return; } if (!globals.paramParser.get().parse(viewData.view, qp.params(), req, res)) { return; } if (viewData.view instanceof RestReadView<?> && isRead(req)) { response = invokeRestReadViewWithRetry( req, traceContext, viewData, (RestReadView<RestResource>) viewData.view, rsrc); } else if (viewData.view instanceof RestModifyView<?, ?>) { @SuppressWarnings("unchecked") RestModifyView<RestResource, Object> m = (RestModifyView<RestResource, Object>) viewData.view; Type type = inputType(m); inputRequestBody = parseRequest(req, type); response = invokeRestModifyViewWithRetry( req, traceContext, viewData, m, rsrc, inputRequestBody); if (inputRequestBody instanceof RawInput) { try (InputStream is = req.getInputStream()) { ServletUtils.consumeRequestBody(is); } } } else if (viewData.view instanceof RestCollectionCreateView<?, ?, ?>) { @SuppressWarnings("unchecked") RestCollectionCreateView<RestResource, RestResource, Object> m = (RestCollectionCreateView<RestResource, RestResource, Object>) viewData.view; Type type = inputType(m); inputRequestBody = parseRequest(req, type); response = invokeRestCollectionCreateViewWithRetry( req, traceContext, viewData, m, rsrc, path.get(0), inputRequestBody); if (inputRequestBody instanceof RawInput) { try (InputStream is = req.getInputStream()) { ServletUtils.consumeRequestBody(is); } } } else if (viewData.view instanceof RestCollectionDeleteMissingView<?, ?, ?>) { @SuppressWarnings("unchecked") RestCollectionDeleteMissingView<RestResource, RestResource, Object> m = (RestCollectionDeleteMissingView<RestResource, RestResource, Object>) viewData.view; Type type = inputType(m); inputRequestBody = parseRequest(req, type); response = invokeRestCollectionDeleteMissingViewWithRetry( req, traceContext, viewData, m, rsrc, path.get(0), inputRequestBody); if (inputRequestBody instanceof RawInput) { try (InputStream is = req.getInputStream()) { ServletUtils.consumeRequestBody(is); } } } else if (viewData.view instanceof RestCollectionModifyView<?, ?, ?>) { @SuppressWarnings("unchecked") RestCollectionModifyView<RestResource, RestResource, Object> m = (RestCollectionModifyView<RestResource, RestResource, Object>) viewData.view; Type type = inputType(m); inputRequestBody = parseRequest(req, type); response = invokeRestCollectionModifyViewWithRetry( req, traceContext, viewData, m, rsrc, inputRequestBody); if (inputRequestBody instanceof RawInput) { try (InputStream is = req.getInputStream()) { ServletUtils.consumeRequestBody(is); } } } else { throw new ResourceNotFoundException(); } if (response instanceof Response.Redirect) { CacheHeaders.setNotCacheable(res); String location = ((Response.Redirect) response).location(); res.sendRedirect(location); logger.atFinest().log("REST call redirected to: %s", location); return; } else if (response instanceof Response.Accepted) { CacheHeaders.setNotCacheable(res); res.setStatus(response.statusCode()); res.setHeader(HttpHeaders.LOCATION, ((Response.Accepted) response).location()); logger.atFinest().log("REST call succeeded: %d", response.statusCode()); return; } status = response.statusCode(); configureCaching(req, res, rsrc, viewData.view, response.caching()); res.setStatus(status); logger.atFinest().log("REST call succeeded: %d", status); } if (response != Response.none()) { Object value = Response.unwrap(response); if (value instanceof BinaryResult) { responseBytes = replyBinaryResult(req, res, (BinaryResult) value); } else { responseBytes = replyJson(req, res, false, qp.config(), value); } } } catch (MalformedJsonException | JsonParseException e) { responseBytes = replyError( req, res, status = SC_BAD_REQUEST, "Invalid " + JSON_TYPE + " in request", e); } catch (BadRequestException e) { responseBytes = replyError( req, res, status = SC_BAD_REQUEST, messageOr(e, "Bad Request"), e.caching(), e); } catch (AuthException e) { responseBytes = replyError(req, res, status = SC_FORBIDDEN, messageOr(e, "Forbidden"), e.caching(), e); } catch (AmbiguousViewException e) { responseBytes = replyError(req, res, status = SC_NOT_FOUND, messageOr(e, "Ambiguous"), e); } catch (ResourceNotFoundException e) { responseBytes = replyError(req, res, status = SC_NOT_FOUND, messageOr(e, "Not Found"), e.caching(), e); } catch (MethodNotAllowedException e) { responseBytes = replyError( req, res, status = SC_METHOD_NOT_ALLOWED, messageOr(e, "Method Not Allowed"), e.caching(), e); } catch (ResourceConflictException e) { responseBytes = replyError(req, res, status = SC_CONFLICT, messageOr(e, "Conflict"), e.caching(), e); } catch (PreconditionFailedException e) { responseBytes = replyError( req, res, status = SC_PRECONDITION_FAILED, messageOr(e, "Precondition Failed"), e.caching(), e); } catch (UnprocessableEntityException e) { responseBytes = replyError( req, res, status = SC_UNPROCESSABLE_ENTITY, messageOr(e, "Unprocessable Entity"), e.caching(), e); } catch (NotImplementedException e) { logger.atSevere().withCause(e).log("Error in %s %s", req.getMethod(), uriForLogging(req)); responseBytes = replyError(req, res, status = SC_NOT_IMPLEMENTED, messageOr(e, "Not Implemented"), e); } catch (UpdateException e) { Throwable t = e.getCause(); if (t instanceof LockFailureException) { logger.atSevere().withCause(t).log("Error in %s %s", req.getMethod(), uriForLogging(req)); responseBytes = replyError(req, res, status = SC_SERVICE_UNAVAILABLE, "Lock failure", e); } else { status = SC_INTERNAL_SERVER_ERROR; responseBytes = handleException(e, req, res); } } catch (QuotaException e) { responseBytes = replyError( req, res, status = SC_TOO_MANY_REQUESTS, messageOr(e, "Quota limit reached"), e.caching(), e); } catch (Exception e) { status = SC_INTERNAL_SERVER_ERROR; responseBytes = handleException(e, req, res); } finally { String metric = getViewName(viewData); globals.metrics.count.increment(metric); if (status >= SC_BAD_REQUEST) { globals.metrics.errorCount.increment(metric, status); } if (responseBytes != -1) { globals.metrics.responseBytes.record(metric, responseBytes); } globals.metrics.serverLatency.record( metric, System.nanoTime() - startNanos, TimeUnit.NANOSECONDS); globals.auditService.dispatch( new ExtendedHttpAuditEvent( globals.webSession.get().getSessionId(), globals.currentUser.get(), req, auditStartTs, qp != null ? qp.params() : ImmutableListMultimap.of(), inputRequestBody, status, response, rsrc, viewData == null ? null : viewData.view)); } } } private Response<?> invokeRestReadViewWithRetry( HttpServletRequest req, TraceContext traceContext, ViewData viewData, RestReadView<RestResource> view, RestResource rsrc) throws Exception { return invokeRestEndpointWithRetry( req, traceContext, viewData, () -> view.apply(rsrc), noRetry()); } private Response<?> invokeRestModifyViewWithRetry( HttpServletRequest req, TraceContext traceContext, ViewData viewData, RestModifyView<RestResource, Object> view, RestResource rsrc, Object inputRequestBody) throws Exception { return invokeRestEndpointWithRetry( req, traceContext, viewData, () -> view.apply(rsrc, inputRequestBody), retryOnLockFailure()); } private Response<?> invokeRestCollectionCreateViewWithRetry( HttpServletRequest req, TraceContext traceContext, ViewData viewData, RestCollectionCreateView<RestResource, RestResource, Object> view, RestResource rsrc, IdString path, Object inputRequestBody) throws Exception { return invokeRestEndpointWithRetry( req, traceContext, viewData, () -> view.apply(rsrc, path, inputRequestBody), retryOnLockFailure()); } private Response<?> invokeRestCollectionDeleteMissingViewWithRetry( HttpServletRequest req, TraceContext traceContext, ViewData viewData, RestCollectionDeleteMissingView<RestResource, RestResource, Object> view, RestResource rsrc, IdString path, Object inputRequestBody) throws Exception { return invokeRestEndpointWithRetry( req, traceContext, viewData, () -> view.apply(rsrc, path, inputRequestBody), retryOnLockFailure()); } private Response<?> invokeRestCollectionModifyViewWithRetry( HttpServletRequest req, TraceContext traceContext, ViewData viewData, RestCollectionModifyView<RestResource, RestResource, Object> view, RestResource rsrc, Object inputRequestBody) throws Exception { return invokeRestEndpointWithRetry( req, traceContext, viewData, () -> view.apply(rsrc, inputRequestBody), retryOnLockFailure()); } private Response<?> invokeRestEndpointWithRetry( HttpServletRequest req, TraceContext traceContext, ViewData viewData, Action<Response<?>> action, Predicate<Throwable> retryExceptionPredicate) throws Exception { RetryHelper.Options.Builder retryOptionsBuilder = RetryHelper.options().caller(getViewName(viewData)); if (!traceContext.isTracing()) { // enable automatic retry with tracing in case of non-recoverable failure retryOptionsBuilder = retryOptionsBuilder .retryWithTrace(t -> !(t instanceof RestApiException)) .onAutoTrace( autoTraceId -> { traceId = Optional.of(autoTraceId); // Include details of the request into the trace. traceRequestData(req); }); } try { return globals.retryHelper.execute( ActionType.REST_REQUEST, action, retryOptionsBuilder.build(), retryExceptionPredicate); } finally { // If auto-tracing got triggered due to a non-recoverable failure, also trace the rest of // this request. This means logging is forced for all further log statements and the logs are // associated with the same trace ID. traceId.ifPresent(tid -> traceContext.addTag(RequestId.Type.TRACE_ID, tid).forceLogging()); } } private static Predicate<Throwable> noRetry() { return t -> false; } private static Predicate<Throwable> retryOnLockFailure() { return t -> { if (t instanceof UpdateException) { t = t.getCause(); } return t instanceof LockFailureException; }; } private String getViewName(ViewData viewData) { return viewData != null && viewData.view != null ? globals.metrics.view(viewData) : "_unknown"; } private static HttpServletRequest applyXdOverrides(HttpServletRequest req, QueryParams qp) throws BadRequestException { if (!isPost(req)) { throw new BadRequestException("POST required"); } String method = qp.xdMethod(); String contentType = qp.xdContentType(); if (method.equals("POST") || method.equals("PUT")) { if (!isType(PLAIN_TEXT, req.getContentType())) { throw new BadRequestException("invalid " + CONTENT_TYPE); } if (Strings.isNullOrEmpty(contentType)) { throw new BadRequestException(XD_CONTENT_TYPE + " required"); } } return new HttpServletRequestWrapper(req) { @Override public String getMethod() { return method; } @Override public String getContentType() { return contentType; } }; } private void checkCors(HttpServletRequest req, HttpServletResponse res, boolean isXd) throws BadRequestException { String origin = req.getHeader(ORIGIN); if (isXd) { // Cross-domain, non-preflighted requests must come from an approved origin. if (Strings.isNullOrEmpty(origin) || !isOriginAllowed(origin)) { throw new BadRequestException("origin not allowed"); } res.addHeader(VARY, ORIGIN); res.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN, origin); res.setHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); } else if (!Strings.isNullOrEmpty(origin)) { // All other requests must be processed, but conditionally set CORS headers. if (globals.allowOrigin != null) { res.addHeader(VARY, ORIGIN); } if (isOriginAllowed(origin)) { setCorsHeaders(res, origin); } } } private static boolean isCorsPreflight(HttpServletRequest req) { return "OPTIONS".equals(req.getMethod()) && !Strings.isNullOrEmpty(req.getHeader(ORIGIN)) && !Strings.isNullOrEmpty(req.getHeader(ACCESS_CONTROL_REQUEST_METHOD)); } private void doCorsPreflight(HttpServletRequest req, HttpServletResponse res) throws BadRequestException { CacheHeaders.setNotCacheable(res); setHeaderList( res, VARY, ImmutableList.of(ORIGIN, ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS)); String origin = req.getHeader(ORIGIN); if (Strings.isNullOrEmpty(origin) || !isOriginAllowed(origin)) { throw new BadRequestException("CORS not allowed"); } String method = req.getHeader(ACCESS_CONTROL_REQUEST_METHOD); if (!ALLOWED_CORS_METHODS.contains(method)) { throw new BadRequestException(method + " not allowed in CORS"); } String headers = req.getHeader(ACCESS_CONTROL_REQUEST_HEADERS); if (headers != null) { for (String reqHdr : Splitter.on(',').trimResults().split(headers)) { if (!ALLOWED_CORS_REQUEST_HEADERS.contains(reqHdr.toLowerCase(Locale.US))) { throw new BadRequestException(reqHdr + " not allowed in CORS"); } } } res.setStatus(SC_OK); setCorsHeaders(res, origin); res.setContentType(PLAIN_TEXT); res.setContentLength(0); } private static void setCorsHeaders(HttpServletResponse res, String origin) { res.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN, origin); res.setHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); res.setHeader(ACCESS_CONTROL_MAX_AGE, "600"); setHeaderList( res, ACCESS_CONTROL_ALLOW_METHODS, Iterables.concat(ALLOWED_CORS_METHODS, ImmutableList.of("OPTIONS"))); setHeaderList(res, ACCESS_CONTROL_ALLOW_HEADERS, ALLOWED_CORS_REQUEST_HEADERS); } private static void setHeaderList(HttpServletResponse res, String name, Iterable<String> values) { res.setHeader(name, Joiner.on(", ").join(values)); } private boolean isOriginAllowed(String origin) { return globals.allowOrigin != null && globals.allowOrigin.matcher(origin).matches(); } private static String messageOr(Throwable t, String defaultMessage) { if (!Strings.isNullOrEmpty(t.getMessage())) { return t.getMessage(); } return defaultMessage; } @SuppressWarnings({"unchecked", "rawtypes"}) private static boolean notModified( HttpServletRequest req, RestResource rsrc, RestView<RestResource> view) { if (!isRead(req)) { return false; } if (view instanceof ETagView) { String have = req.getHeader(HttpHeaders.IF_NONE_MATCH); if (have != null) { return have.equals(((ETagView) view).getETag(rsrc)); } } if (rsrc instanceof RestResource.HasETag) { String have = req.getHeader(HttpHeaders.IF_NONE_MATCH); if (have != null) { return have.equals(((RestResource.HasETag) rsrc).getETag()); } } if (rsrc instanceof RestResource.HasLastModified) { Timestamp m = ((RestResource.HasLastModified) rsrc).getLastModified(); long d = req.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE); // HTTP times are in seconds, database may have millisecond precision. return d / 1000L == m.getTime() / 1000L; } return false; } private static <R extends RestResource> void configureCaching( HttpServletRequest req, HttpServletResponse res, R rsrc, RestView<R> view, CacheControl c) { if (isRead(req)) { switch (c.getType()) { case NONE: default: CacheHeaders.setNotCacheable(res); break; case PRIVATE: addResourceStateHeaders(res, rsrc, view); CacheHeaders.setCacheablePrivate(res, c.getAge(), c.getUnit(), c.isMustRevalidate()); break; case PUBLIC: addResourceStateHeaders(res, rsrc, view); CacheHeaders.setCacheable(req, res, c.getAge(), c.getUnit(), c.isMustRevalidate()); break; } } else { CacheHeaders.setNotCacheable(res); } } private static <R extends RestResource> void addResourceStateHeaders( HttpServletResponse res, R rsrc, RestView<R> view) { if (view instanceof ETagView) { res.setHeader(HttpHeaders.ETAG, ((ETagView<R>) view).getETag(rsrc)); } else if (rsrc instanceof RestResource.HasETag) { res.setHeader(HttpHeaders.ETAG, ((RestResource.HasETag) rsrc).getETag()); } if (rsrc instanceof RestResource.HasLastModified) { res.setDateHeader( HttpHeaders.LAST_MODIFIED, ((RestResource.HasLastModified) rsrc).getLastModified().getTime()); } } private void checkPreconditions(HttpServletRequest req) throws PreconditionFailedException { if ("*".equals(req.getHeader(HttpHeaders.IF_NONE_MATCH))) { throw new PreconditionFailedException("Resource already exists"); } } private static Type inputType(RestModifyView<RestResource, Object> m) { // MyModifyView implements RestModifyView<SomeResource, MyInput> TypeLiteral<?> typeLiteral = TypeLiteral.get(m.getClass()); // RestModifyView<SomeResource, MyInput> // This is smart enough to resolve even when there are intervening subclasses, even if they have // reordered type arguments. TypeLiteral<?> supertypeLiteral = typeLiteral.getSupertype(RestModifyView.class); Type supertype = supertypeLiteral.getType(); checkState( supertype instanceof ParameterizedType, "supertype of %s is not parameterized: %s", typeLiteral, supertypeLiteral); return ((ParameterizedType) supertype).getActualTypeArguments()[1]; } private static Type inputType(RestCollectionView<RestResource, RestResource, Object> m) { // MyCollectionView implements RestCollectionView<SomeResource, SomeResource, MyInput> TypeLiteral<?> typeLiteral = TypeLiteral.get(m.getClass()); // RestCollectionView<SomeResource, SomeResource, MyInput> // This is smart enough to resolve even when there are intervening subclasses, even if they have // reordered type arguments. TypeLiteral<?> supertypeLiteral = typeLiteral.getSupertype(RestCollectionView.class); Type supertype = supertypeLiteral.getType(); checkState( supertype instanceof ParameterizedType, "supertype of %s is not parameterized: %s", typeLiteral, supertypeLiteral); return ((ParameterizedType) supertype).getActualTypeArguments()[2]; } private Object parseRequest(HttpServletRequest req, Type type) throws IOException, BadRequestException, SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException, MethodNotAllowedException { // HTTP/1.1 requires consuming the request body before writing non-error response (less than // 400). Consume the request body for all but raw input request types here. if (isType(JSON_TYPE, req.getContentType())) { try (BufferedReader br = req.getReader(); JsonReader json = new JsonReader(br)) { try { json.setLenient(true); JsonToken first; try { first = json.peek(); } catch (EOFException e) { throw new BadRequestException("Expected JSON object"); } if (first == JsonToken.STRING) { return parseString(json.nextString(), type); } return OutputFormat.JSON.newGson().fromJson(json, type); } finally { // Reader.close won't consume the rest of the input. Explicitly consume the request body. br.skip(Long.MAX_VALUE); } } } String method = req.getMethod(); if (("PUT".equals(method) || "POST".equals(method)) && acceptsRawInput(type)) { return parseRawInput(req, type); } if (isDelete(req) && hasNoBody(req)) { return null; } if (hasNoBody(req)) { return createInstance(type); } if (isType(PLAIN_TEXT, req.getContentType())) { try (BufferedReader br = req.getReader()) { char[] tmp = new char[256]; StringBuilder sb = new StringBuilder(); int n; while (0 < (n = br.read(tmp))) { sb.append(tmp, 0, n); } return parseString(sb.toString(), type); } } if (isPost(req) && isType(FORM_TYPE, req.getContentType())) { return OutputFormat.JSON.newGson().fromJson(ParameterParser.formToJson(req), type); } throw new BadRequestException("Expected Content-Type: " + JSON_TYPE); } private static boolean hasNoBody(HttpServletRequest req) { int len = req.getContentLength(); String type = req.getContentType(); return (len <= 0 && type == null) || (len == 0 && isType(FORM_TYPE, type)); } @SuppressWarnings("rawtypes") private static boolean acceptsRawInput(Type type) { if (type instanceof Class) { for (Field f : ((Class) type).getDeclaredFields()) { if (f.getType() == RawInput.class) { return true; } } } return false; } private Object parseRawInput(HttpServletRequest req, Type type) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, MethodNotAllowedException { Object obj = createInstance(type); for (Field f : obj.getClass().getDeclaredFields()) { if (f.getType() == RawInput.class) { f.setAccessible(true); f.set(obj, RawInputUtil.create(req)); return obj; } } throw new MethodNotAllowedException(); } private Object parseString(String value, Type type) throws BadRequestException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException { if (type == String.class) { return value; } Object obj = createInstance(type); if (Strings.isNullOrEmpty(value)) { return obj; } Field[] fields = obj.getClass().getDeclaredFields(); for (Field f : fields) { if (f.getAnnotation(DefaultInput.class) != null && f.getType() == String.class) { f.setAccessible(true); f.set(obj, value); return obj; } } throw new BadRequestException("Expected JSON object"); } @SuppressWarnings("unchecked") private static Object createInstance(Type type) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { if (type instanceof Class) { Class<Object> clazz = (Class<Object>) type; Constructor<Object> c = clazz.getDeclaredConstructor(); c.setAccessible(true); return c.newInstance(); } if (type instanceof ParameterizedType) { Type rawType = ((ParameterizedType) type).getRawType(); if (rawType instanceof Class && List.class.isAssignableFrom((Class<Object>) rawType)) { return new ArrayList<>(); } if (rawType instanceof Class && Map.class.isAssignableFrom((Class<Object>) rawType)) { return new HashMap<>(); } } throw new InstantiationException("Cannot make " + type); } /** * Sets a JSON reply on the given HTTP servlet response. * * @param req the HTTP servlet request * @param res the HTTP servlet response on which the reply should be set * @param allowTracing whether it is allowed to log the reply if tracing is enabled, must not be * set to {@code true} if the reply may contain sensitive data * @param config config parameters for the JSON formatting * @param result the object that should be formatted as JSON * @return the length of the response * @throws IOException */ public static long replyJson( @Nullable HttpServletRequest req, HttpServletResponse res, boolean allowTracing, ListMultimap<String, String> config, Object result) throws IOException { TemporaryBuffer.Heap buf = heap(HEAP_EST_SIZE, Integer.MAX_VALUE); buf.write(JSON_MAGIC); Writer w = new BufferedWriter(new OutputStreamWriter(buf, UTF_8)); Gson gson = newGson(config, req); if (result instanceof JsonElement) { gson.toJson((JsonElement) result, w); } else { gson.toJson(result, w); } w.write('\n'); w.flush(); if (allowTracing) { logger.atFinest().log( "JSON response body:\n%s", lazy( () -> { try { ByteArrayOutputStream debugOut = new ByteArrayOutputStream(); buf.writeTo(debugOut, null); return debugOut.toString(UTF_8.name()); } catch (IOException e) { return "<JSON formatting failed>"; } })); } return replyBinaryResult( req, res, asBinaryResult(buf).setContentType(JSON_TYPE).setCharacterEncoding(UTF_8)); } private static Gson newGson( ListMultimap<String, String> config, @Nullable HttpServletRequest req) { GsonBuilder gb = OutputFormat.JSON_COMPACT.newGsonBuilder(); enablePrettyPrint(gb, config, req); enablePartialGetFields(gb, config); return gb.create(); } private static void enablePrettyPrint( GsonBuilder gb, ListMultimap<String, String> config, @Nullable HttpServletRequest req) { String pp = Iterables.getFirst(config.get("pp"), null); if (pp == null) { pp = Iterables.getFirst(config.get("prettyPrint"), null); if (pp == null && req != null) { pp = acceptsJson(req) ? "0" : "1"; } } if ("1".equals(pp) || "true".equals(pp)) { gb.setPrettyPrinting(); } } private static void enablePartialGetFields(GsonBuilder gb, ListMultimap<String, String> config) { final Set<String> want = new HashSet<>(); for (String p : config.get("fields")) { Iterables.addAll(want, OptionUtil.splitOptionValue(p)); } if (!want.isEmpty()) { gb.addSerializationExclusionStrategy( new ExclusionStrategy() { private final Map<String, String> names = new HashMap<>(); @Override public boolean shouldSkipField(FieldAttributes field) { String name = names.get(field.getName()); if (name == null) { // Names are supplied by Gson in terms of Java source. // Translate and cache the JSON lower_case_style used. try { name = FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES.translateName( // field.getDeclaringClass().getDeclaredField(field.getName())); names.put(field.getName(), name); } catch (SecurityException | NoSuchFieldException e) { return true; } } return !want.contains(name); } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }); } } @SuppressWarnings("resource") static long replyBinaryResult( @Nullable HttpServletRequest req, HttpServletResponse res, BinaryResult bin) throws IOException { final BinaryResult appResult = bin; try { if (bin.getAttachmentName() != null) { res.setHeader( "Content-Disposition", "attachment; filename=\"" + bin.getAttachmentName() + "\""); } if (bin.isBase64()) { if (req != null && JSON_TYPE.equals(req.getHeader(HttpHeaders.ACCEPT))) { bin = stackJsonString(res, bin); } else { bin = stackBase64(res, bin); } } if (bin.canGzip() && acceptsGzip(req)) { bin = stackGzip(res, bin); } res.setContentType(bin.getContentType()); long len = bin.getContentLength(); if (0 <= len && len < Integer.MAX_VALUE) { res.setContentLength((int) len); } else if (0 <= len) { res.setHeader("Content-Length", Long.toString(len)); } if (req == null || !"HEAD".equals(req.getMethod())) { try (CountingOutputStream dst = new CountingOutputStream(res.getOutputStream())) { bin.writeTo(dst); return dst.getCount(); } } return 0; } finally { appResult.close(); } } private static BinaryResult stackJsonString(HttpServletResponse res, BinaryResult src) throws IOException { TemporaryBuffer.Heap buf = heap(HEAP_EST_SIZE, Integer.MAX_VALUE); buf.write(JSON_MAGIC); try (Writer w = new BufferedWriter(new OutputStreamWriter(buf, UTF_8)); JsonWriter json = new JsonWriter(w)) { json.setLenient(true); json.setHtmlSafe(true); json.value(src.asString()); w.write('\n'); } res.setHeader("X-FYI-Content-Encoding", "json"); res.setHeader("X-FYI-Content-Type", src.getContentType()); return asBinaryResult(buf).setContentType(JSON_TYPE).setCharacterEncoding(UTF_8); } private static BinaryResult stackBase64(HttpServletResponse res, BinaryResult src) throws IOException { BinaryResult b64; long len = src.getContentLength(); if (0 <= len && len <= (7 << 20)) { b64 = base64(src); } else { b64 = new BinaryResult() { @Override public void writeTo(OutputStream out) throws IOException { try (OutputStreamWriter w = new OutputStreamWriter( new FilterOutputStream(out) { @Override public void close() { // Do not close out, but only w and e. } }, ISO_8859_1); OutputStream e = BaseEncoding.base64().encodingStream(w)) { src.writeTo(e); } } }; } res.setHeader("X-FYI-Content-Encoding", "base64"); res.setHeader("X-FYI-Content-Type", src.getContentType()); return b64.setContentType(PLAIN_TEXT).setCharacterEncoding(ISO_8859_1); } private static BinaryResult stackGzip(HttpServletResponse res, BinaryResult src) throws IOException { BinaryResult gz; long len = src.getContentLength(); if (len < 256) { return src; // Do not compress very small payloads. } if (len <= (10 << 20)) { gz = compress(src); if (len <= gz.getContentLength()) { return src; } } else { gz = new BinaryResult() { @Override public void writeTo(OutputStream out) throws IOException { GZIPOutputStream gz = new GZIPOutputStream(out); src.writeTo(gz); gz.finish(); gz.flush(); } }; } res.setHeader("Content-Encoding", "gzip"); return gz.setContentType(src.getContentType()); } private ViewData view( RestCollection<RestResource, RestResource> rc, String method, List<IdString> path) throws AmbiguousViewException, RestApiException { DynamicMap<RestView<RestResource>> views = rc.views(); final IdString projection = path.isEmpty() ? IdString.fromUrl("/") : path.remove(0); if (!path.isEmpty()) { // If there are path components still remaining after this projection // is chosen, look for the projection based upon GET as the method as // the client thinks it is a nested collection. method = "GET"; } else if ("HEAD".equals(method)) { method = "GET"; } List<String> p = splitProjection(projection); if (p.size() == 2) { String viewname = p.get(1); if (Strings.isNullOrEmpty(viewname)) { viewname = "/"; } RestView<RestResource> view = views.get(p.get(0), method + "." + viewname); if (view != null) { return new ViewData(p.get(0), view); } view = views.get(p.get(0), "GET." + viewname); if (view != null) { return new ViewData(p.get(0), view); } throw new ResourceNotFoundException(projection); } String name = method + "." + p.get(0); RestView<RestResource> core = views.get(PluginName.GERRIT, name); if (core != null) { return new ViewData(PluginName.GERRIT, core); } // Check if we want to delegate to a child collection. Child collections are bound with // GET.name so we have to check for this since we haven't found any other views. core = views.get(PluginName.GERRIT, "GET." + p.get(0)); if (core != null) { return new ViewData(PluginName.GERRIT, core); } Map<String, RestView<RestResource>> r = new TreeMap<>(); for (String plugin : views.plugins()) { RestView<RestResource> action = views.get(plugin, name); if (action != null) { r.put(plugin, action); } } if (r.isEmpty()) { // Check if we want to delegate to a child collection. Child collections are bound with // GET.name so we have to check for this since we haven't found any other views. for (String plugin : views.plugins()) { RestView<RestResource> action = views.get(plugin, "GET." + p.get(0)); if (action != null) { r.put(plugin, action); } } } if (r.size() == 1) { Map.Entry<String, RestView<RestResource>> entry = Iterables.getOnlyElement(r.entrySet()); return new ViewData(entry.getKey(), entry.getValue()); } if (r.isEmpty()) { throw new ResourceNotFoundException(projection); } throw new AmbiguousViewException( String.format( "Projection %s is ambiguous: %s", name, r.keySet().stream().map(in -> in + "~" + projection).collect(joining(", ")))); } private static List<IdString> splitPath(HttpServletRequest req) { String path = RequestUtil.getEncodedPathInfo(req); if (Strings.isNullOrEmpty(path)) { return Collections.emptyList(); } List<IdString> out = new ArrayList<>(); for (String p : Splitter.on('/').split(path)) { out.add(IdString.fromUrl(p)); } if (out.size() > 0 && out.get(out.size() - 1).isEmpty()) { out.remove(out.size() - 1); } return out; } private static List<String> splitProjection(IdString projection) { List<String> p = Lists.newArrayListWithCapacity(2); Iterables.addAll(p, Splitter.on('~').limit(2).split(projection.get())); return p; } private void checkUserSession(HttpServletRequest req) throws AuthException { CurrentUser user = globals.currentUser.get(); if (isRead(req)) { user.setAccessPath(AccessPath.REST_API); } else if (user instanceof AnonymousUser) { throw new AuthException("Authentication required"); } else if (!globals.webSession.get().isAccessPathOk(AccessPath.REST_API)) { throw new AuthException( "Invalid authentication method. In order to authenticate, " + "prefix the REST endpoint URL with /a/ (e.g. http://example.com/a/projects/)."); } if (user.isIdentifiedUser()) { user.setLastLoginExternalIdKey(globals.webSession.get().getLastLoginExternalId()); } } private List<String> getParameterNames(HttpServletRequest req) { List<String> parameterNames = new ArrayList<>(req.getParameterMap().keySet()); Collections.sort(parameterNames); return parameterNames; } private TraceContext enableTracing(HttpServletRequest req, HttpServletResponse res) { // There are 2 ways to enable tracing for REST calls: // 1. by using the 'trace' or 'trace=<trace-id>' request parameter // 2. by setting the 'X-Gerrit-Trace:' or 'X-Gerrit-Trace:<trace-id>' header String traceValueFromHeader = req.getHeader(X_GERRIT_TRACE); String traceValueFromRequestParam = req.getParameter(ParameterParser.TRACE_PARAMETER); boolean doTrace = traceValueFromHeader != null || traceValueFromRequestParam != null; // Check whether no trace ID, one trace ID or 2 different trace IDs have been specified. String traceId1; String traceId2; if (!Strings.isNullOrEmpty(traceValueFromHeader)) { traceId1 = traceValueFromHeader; if (!Strings.isNullOrEmpty(traceValueFromRequestParam) && !traceValueFromHeader.equals(traceValueFromRequestParam)) { traceId2 = traceValueFromRequestParam; } else { traceId2 = null; } } else { traceId1 = Strings.emptyToNull(traceValueFromRequestParam); traceId2 = null; } // Use the first trace ID to start tracing. If this trace ID is null, a trace ID will be // generated. TraceContext traceContext = TraceContext.newTrace( doTrace, traceId1, (tagName, traceId) -> res.setHeader(X_GERRIT_TRACE, traceId)); // If a second trace ID was specified, add a tag for it as well. if (traceId2 != null) { traceContext.addTag(RequestId.Type.TRACE_ID, traceId2); res.addHeader(X_GERRIT_TRACE, traceId2); } return traceContext; } private RequestInfo createRequestInfo( TraceContext traceContext, String requestUri, List<IdString> path) { RequestInfo.Builder requestInfo = RequestInfo.builder(RequestInfo.RequestType.REST, globals.currentUser.get(), traceContext) .requestUri(requestUri); if (path.size() < 1) { return requestInfo.build(); } RestCollection<?, ?> rootCollection = members.get(); String resourceId = path.get(0).get(); if (rootCollection instanceof ProjectsCollection) { requestInfo.project(Project.nameKey(resourceId)); } else if (rootCollection instanceof ChangesCollection) { ChangeNotes changeNotes = globals.changeFinder.findOne(resourceId); if (changeNotes != null) { requestInfo.project(changeNotes.getProjectName()); } } return requestInfo.build(); } private void traceRequestData(HttpServletRequest req) { logger.atFinest().log( "Received REST request: %s %s (parameters: %s)", req.getMethod(), req.getRequestURI(), getParameterNames(req)); logger.atFinest().log("Calling user: %s", globals.currentUser.get().getLoggableName()); logger.atFinest().log( "Groups: %s", globals.currentUser.get().getEffectiveGroups().getKnownGroups()); } private boolean isDelete(HttpServletRequest req) { return "DELETE".equals(req.getMethod()); } private static boolean isPost(HttpServletRequest req) { return "POST".equals(req.getMethod()); } private boolean isPut(HttpServletRequest req) { return "PUT".equals(req.getMethod()); } private static boolean isRead(HttpServletRequest req) { return "GET".equals(req.getMethod()) || "HEAD".equals(req.getMethod()); } private static MethodNotAllowedException methodNotAllowed(HttpServletRequest req) { return new MethodNotAllowedException( String.format("Not implemented: %s %s", req.getMethod(), requestUri(req))); } private static String requestUri(HttpServletRequest req) { String uri = req.getRequestURI(); if (uri.startsWith("/a/")) { return uri.substring(2); } return uri; } private void checkRequiresCapability(ViewData d) throws AuthException, PermissionBackendException { try { globals.permissionBackend.currentUser().check(GlobalPermission.ADMINISTRATE_SERVER); } catch (AuthException e) { // Skiping globals .permissionBackend .currentUser() .checkAny(GlobalPermission.fromAnnotation(d.pluginName, d.view.getClass())); } } private long handleException(Throwable err, HttpServletRequest req, HttpServletResponse res) throws IOException { logger.atSevere().withCause(err).log("Error in %s %s", req.getMethod(), uriForLogging(req)); if (!res.isCommitted()) { res.reset(); traceId.ifPresent(traceId -> res.addHeader(X_GERRIT_TRACE, traceId)); return replyError(req, res, SC_INTERNAL_SERVER_ERROR, "Internal server error", err); } return 0; } private static String uriForLogging(HttpServletRequest req) { String uri = req.getRequestURI(); if (!Strings.isNullOrEmpty(req.getQueryString())) { uri += "?" + LogRedactUtil.redactQueryString(req.getQueryString()); } return uri; } public static long replyError( HttpServletRequest req, HttpServletResponse res, int statusCode, String msg, @Nullable Throwable err) throws IOException { return replyError(req, res, statusCode, msg, CacheControl.NONE, err); } public static long replyError( HttpServletRequest req, HttpServletResponse res, int statusCode, String msg, CacheControl c, @Nullable Throwable err) throws IOException { if (err != null) { RequestUtil.setErrorTraceAttribute(req, err); } configureCaching(req, res, null, null, c); checkArgument(statusCode >= 400, "non-error status: %s", statusCode); res.setStatus(statusCode); logger.atFinest().withCause(err).log("REST call failed: %d", statusCode); return replyText(req, res, true, msg); } /** * Sets a text reply on the given HTTP servlet response. * * @param req the HTTP servlet request * @param res the HTTP servlet response on which the reply should be set * @param allowTracing whether it is allowed to log the reply if tracing is enabled, must not be * set to {@code true} if the reply may contain sensitive data * @param text the text reply * @return the length of the response * @throws IOException */ static long replyText( @Nullable HttpServletRequest req, HttpServletResponse res, boolean allowTracing, String text) throws IOException { if ((req == null || isRead(req)) && isMaybeHTML(text)) { return replyJson( req, res, allowTracing, ImmutableListMultimap.of("pp", "0"), new JsonPrimitive(text)); } if (!text.endsWith("\n")) { text += "\n"; } if (allowTracing) { logger.atFinest().log("Text response body:\n%s", text); } return replyBinaryResult(req, res, BinaryResult.create(text).setContentType(PLAIN_TEXT)); } private static boolean isMaybeHTML(String text) { return CharMatcher.anyOf("<&").matchesAnyOf(text); } private static boolean acceptsJson(HttpServletRequest req) { return req != null && isType(JSON_TYPE, req.getHeader(HttpHeaders.ACCEPT)); } private static boolean acceptsGzip(HttpServletRequest req) { if (req != null) { String accepts = req.getHeader(HttpHeaders.ACCEPT_ENCODING); return accepts != null && accepts.contains("gzip"); } return false; } private static boolean isType(String expect, String given) { if (given == null) { return false; } if (expect.equals(given)) { return true; } if (given.startsWith(expect + ",")) { return true; } for (String p : Splitter.on(TYPE_SPLIT_PATTERN).split(given)) { if (expect.equals(p)) { return true; } } return false; } private static int base64MaxSize(long n) { return 4 * IntMath.divide((int) n, 3, CEILING); } private static BinaryResult base64(BinaryResult bin) throws IOException { int maxSize = base64MaxSize(bin.getContentLength()); int estSize = Math.min(base64MaxSize(HEAP_EST_SIZE), maxSize); TemporaryBuffer.Heap buf = heap(estSize, maxSize); try (OutputStream encoded = BaseEncoding.base64().encodingStream(new OutputStreamWriter(buf, ISO_8859_1))) { bin.writeTo(encoded); } return asBinaryResult(buf); } private static BinaryResult compress(BinaryResult bin) throws IOException { TemporaryBuffer.Heap buf = heap(HEAP_EST_SIZE, 20 << 20); try (GZIPOutputStream gz = new GZIPOutputStream(buf)) { bin.writeTo(gz); } return asBinaryResult(buf).setContentType(bin.getContentType()); } @SuppressWarnings("resource") private static BinaryResult asBinaryResult(TemporaryBuffer.Heap buf) { return new BinaryResult() { @Override public void writeTo(OutputStream os) throws IOException { buf.writeTo(os, null); } }.setContentLength(buf.length()); } private static Heap heap(int est, int max) { return new TemporaryBuffer.Heap(est, max); } private static class AmbiguousViewException extends Exception { private static final long serialVersionUID = 1L; AmbiguousViewException(String message) { super(message); } } static class ViewData { String pluginName; RestView<RestResource> view; ViewData(String pluginName, RestView<RestResource> view) { this.pluginName = pluginName; this.view = view; } } }
java/com/google/gerrit/httpd/restapi/RestApiServlet.java
// Copyright (C) 2012 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // WARNING: NoteDbUpdateManager cares about the package name RestApiServlet lives in. package com.google.gerrit.httpd.restapi; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static com.google.common.flogger.LazyArgs.lazy; import static com.google.common.net.HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS; import static com.google.common.net.HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS; import static com.google.common.net.HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS; import static com.google.common.net.HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN; import static com.google.common.net.HttpHeaders.ACCESS_CONTROL_MAX_AGE; import static com.google.common.net.HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS; import static com.google.common.net.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD; import static com.google.common.net.HttpHeaders.AUTHORIZATION; import static com.google.common.net.HttpHeaders.CONTENT_TYPE; import static com.google.common.net.HttpHeaders.ORIGIN; import static com.google.common.net.HttpHeaders.VARY; import static java.math.RoundingMode.CEILING; import static java.nio.charset.StandardCharsets.ISO_8859_1; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.joining; import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; import static javax.servlet.http.HttpServletResponse.SC_CONFLICT; import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN; import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; import static javax.servlet.http.HttpServletResponse.SC_METHOD_NOT_ALLOWED; import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; import static javax.servlet.http.HttpServletResponse.SC_NOT_IMPLEMENTED; import static javax.servlet.http.HttpServletResponse.SC_NOT_MODIFIED; import static javax.servlet.http.HttpServletResponse.SC_OK; import static javax.servlet.http.HttpServletResponse.SC_PRECONDITION_FAILED; import static javax.servlet.http.HttpServletResponse.SC_SERVICE_UNAVAILABLE; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.CharMatcher; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.flogger.FluentLogger; import com.google.common.io.BaseEncoding; import com.google.common.io.CountingOutputStream; import com.google.common.math.IntMath; import com.google.common.net.HttpHeaders; import com.google.gerrit.common.Nullable; import com.google.gerrit.common.RawInputUtil; import com.google.gerrit.entities.Project; import com.google.gerrit.extensions.registration.DynamicItem; import com.google.gerrit.extensions.registration.DynamicMap; import com.google.gerrit.extensions.registration.DynamicSet; import com.google.gerrit.extensions.registration.PluginName; import com.google.gerrit.extensions.restapi.AuthException; import com.google.gerrit.extensions.restapi.BadRequestException; import com.google.gerrit.extensions.restapi.BinaryResult; import com.google.gerrit.extensions.restapi.CacheControl; import com.google.gerrit.extensions.restapi.DefaultInput; import com.google.gerrit.extensions.restapi.ETagView; import com.google.gerrit.extensions.restapi.IdString; import com.google.gerrit.extensions.restapi.MethodNotAllowedException; import com.google.gerrit.extensions.restapi.NeedsParams; import com.google.gerrit.extensions.restapi.NotImplementedException; import com.google.gerrit.extensions.restapi.PreconditionFailedException; import com.google.gerrit.extensions.restapi.RawInput; import com.google.gerrit.extensions.restapi.ResourceConflictException; import com.google.gerrit.extensions.restapi.ResourceNotFoundException; import com.google.gerrit.extensions.restapi.Response; import com.google.gerrit.extensions.restapi.RestApiException; import com.google.gerrit.extensions.restapi.RestCollection; import com.google.gerrit.extensions.restapi.RestCollectionCreateView; import com.google.gerrit.extensions.restapi.RestCollectionDeleteMissingView; import com.google.gerrit.extensions.restapi.RestCollectionModifyView; import com.google.gerrit.extensions.restapi.RestCollectionView; import com.google.gerrit.extensions.restapi.RestModifyView; import com.google.gerrit.extensions.restapi.RestReadView; import com.google.gerrit.extensions.restapi.RestResource; import com.google.gerrit.extensions.restapi.RestView; import com.google.gerrit.extensions.restapi.TopLevelResource; import com.google.gerrit.extensions.restapi.UnprocessableEntityException; import com.google.gerrit.git.LockFailureException; import com.google.gerrit.httpd.WebSession; import com.google.gerrit.httpd.restapi.ParameterParser.QueryParams; import com.google.gerrit.json.OutputFormat; import com.google.gerrit.server.AccessPath; import com.google.gerrit.server.AnonymousUser; import com.google.gerrit.server.CurrentUser; import com.google.gerrit.server.OptionUtil; import com.google.gerrit.server.RequestInfo; import com.google.gerrit.server.RequestListener; import com.google.gerrit.server.audit.ExtendedHttpAuditEvent; import com.google.gerrit.server.cache.PerThreadCache; import com.google.gerrit.server.change.ChangeFinder; import com.google.gerrit.server.config.GerritServerConfig; import com.google.gerrit.server.group.GroupAuditService; import com.google.gerrit.server.logging.PerformanceLogContext; import com.google.gerrit.server.logging.PerformanceLogger; import com.google.gerrit.server.logging.RequestId; import com.google.gerrit.server.logging.TraceContext; import com.google.gerrit.server.notedb.ChangeNotes; import com.google.gerrit.server.permissions.GlobalPermission; import com.google.gerrit.server.permissions.PermissionBackend; import com.google.gerrit.server.permissions.PermissionBackendException; import com.google.gerrit.server.plugincontext.PluginSetContext; import com.google.gerrit.server.quota.QuotaException; import com.google.gerrit.server.restapi.change.ChangesCollection; import com.google.gerrit.server.restapi.project.ProjectsCollection; import com.google.gerrit.server.update.RetryHelper; import com.google.gerrit.server.update.RetryHelper.Action; import com.google.gerrit.server.update.RetryHelper.ActionType; import com.google.gerrit.server.update.UpdateException; import com.google.gerrit.server.util.time.TimeUtil; import com.google.gerrit.util.http.CacheHeaders; import com.google.gerrit.util.http.RequestUtil; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import com.google.gson.stream.MalformedJsonException; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.TypeLiteral; import com.google.inject.util.Providers; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import java.util.stream.Stream; import java.util.zip.GZIPOutputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import org.eclipse.jgit.http.server.ServletUtils; import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.util.TemporaryBuffer; import org.eclipse.jgit.util.TemporaryBuffer.Heap; public class RestApiServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final FluentLogger logger = FluentLogger.forEnclosingClass(); /** MIME type used for a JSON response body. */ private static final String JSON_TYPE = "application/json"; private static final String FORM_TYPE = "application/x-www-form-urlencoded"; @VisibleForTesting public static final String X_GERRIT_TRACE = "X-Gerrit-Trace"; private static final String X_REQUESTED_WITH = "X-Requested-With"; private static final String X_GERRIT_AUTH = "X-Gerrit-Auth"; static final ImmutableSet<String> ALLOWED_CORS_METHODS = ImmutableSet.of("GET", "HEAD", "POST", "PUT", "DELETE"); private static final ImmutableSet<String> ALLOWED_CORS_REQUEST_HEADERS = Stream.of(AUTHORIZATION, CONTENT_TYPE, X_GERRIT_AUTH, X_REQUESTED_WITH) .map(s -> s.toLowerCase(Locale.US)) .collect(ImmutableSet.toImmutableSet()); public static final String XD_AUTHORIZATION = "access_token"; public static final String XD_CONTENT_TYPE = "$ct"; public static final String XD_METHOD = "$m"; public static final int SC_UNPROCESSABLE_ENTITY = 422; public static final int SC_TOO_MANY_REQUESTS = 429; private static final int HEAP_EST_SIZE = 10 * 8 * 1024; // Presize 10 blocks. private static final String PLAIN_TEXT = "text/plain"; private static final Pattern TYPE_SPLIT_PATTERN = Pattern.compile("[ ,;][ ,;]*"); /** * Garbage prefix inserted before JSON output to prevent XSSI. * * <p>This prefix is ")]}'\n" and is designed to prevent a web browser from executing the response * body if the resource URI were to be referenced using a &lt;script src="...&gt; HTML tag from * another web site. Clients using the HTTP interface will need to always strip the first line of * response data to remove this magic header. */ public static final byte[] JSON_MAGIC; static { JSON_MAGIC = ")]}'\n".getBytes(UTF_8); } public static class Globals { final Provider<CurrentUser> currentUser; final DynamicItem<WebSession> webSession; final Provider<ParameterParser> paramParser; final PluginSetContext<RequestListener> requestListeners; final PermissionBackend permissionBackend; final GroupAuditService auditService; final RestApiMetrics metrics; final Pattern allowOrigin; final RestApiQuotaEnforcer quotaChecker; final Config config; final DynamicSet<PerformanceLogger> performanceLoggers; final ChangeFinder changeFinder; final RetryHelper retryHelper; @Inject Globals( Provider<CurrentUser> currentUser, DynamicItem<WebSession> webSession, Provider<ParameterParser> paramParser, PluginSetContext<RequestListener> requestListeners, PermissionBackend permissionBackend, GroupAuditService auditService, RestApiMetrics metrics, RestApiQuotaEnforcer quotaChecker, @GerritServerConfig Config config, DynamicSet<PerformanceLogger> performanceLoggers, ChangeFinder changeFinder, RetryHelper retryHelper) { this.currentUser = currentUser; this.webSession = webSession; this.paramParser = paramParser; this.requestListeners = requestListeners; this.permissionBackend = permissionBackend; this.auditService = auditService; this.metrics = metrics; this.quotaChecker = quotaChecker; this.config = config; this.performanceLoggers = performanceLoggers; this.changeFinder = changeFinder; this.retryHelper = retryHelper; allowOrigin = makeAllowOrigin(config); } private static Pattern makeAllowOrigin(Config cfg) { String[] allow = cfg.getStringList("site", null, "allowOriginRegex"); if (allow.length > 0) { return Pattern.compile(Joiner.on('|').join(allow)); } return null; } } private final Globals globals; private final Provider<RestCollection<RestResource, RestResource>> members; private Optional<String> traceId = Optional.empty(); public RestApiServlet( Globals globals, RestCollection<? extends RestResource, ? extends RestResource> members) { this(globals, Providers.of(members)); } public RestApiServlet( Globals globals, Provider<? extends RestCollection<? extends RestResource, ? extends RestResource>> members) { @SuppressWarnings("unchecked") Provider<RestCollection<RestResource, RestResource>> n = (Provider<RestCollection<RestResource, RestResource>>) requireNonNull((Object) members); this.globals = globals; this.members = n; } @Override protected final void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { final long startNanos = System.nanoTime(); long auditStartTs = TimeUtil.nowMs(); res.setHeader("Content-Disposition", "attachment"); res.setHeader("X-Content-Type-Options", "nosniff"); int status = SC_OK; long responseBytes = -1; Response<?> response = null; QueryParams qp = null; Object inputRequestBody = null; RestResource rsrc = TopLevelResource.INSTANCE; ViewData viewData = null; try (TraceContext traceContext = enableTracing(req, res)) { List<IdString> path = splitPath(req); RequestInfo requestInfo = createRequestInfo(traceContext, requestUri(req), path); globals.requestListeners.runEach(l -> l.onRequest(requestInfo)); try (PerThreadCache ignored = PerThreadCache.create()) { // It's important that the PerformanceLogContext is closed before the response is sent to // the client. Only this way it is ensured that the invocation of the PerformanceLogger // plugins happens before the client sees the response. This is needed for being able to // test performance logging from an acceptance test (see // TraceIT#performanceLoggingForRestCall()). try (PerformanceLogContext performanceLogContext = new PerformanceLogContext(globals.config, globals.performanceLoggers)) { traceRequestData(req); if (isCorsPreflight(req)) { doCorsPreflight(req, res); return; } qp = ParameterParser.getQueryParams(req); checkCors(req, res, qp.hasXdOverride()); if (qp.hasXdOverride()) { req = applyXdOverrides(req, qp); } checkUserSession(req); RestCollection<RestResource, RestResource> rc = members.get(); globals .permissionBackend .currentUser() .checkAny(GlobalPermission.fromAnnotation(rc.getClass())); viewData = new ViewData(null, null); if (path.isEmpty()) { globals.quotaChecker.enforce(req); if (rc instanceof NeedsParams) { ((NeedsParams) rc).setParams(qp.params()); } if (isRead(req)) { viewData = new ViewData(null, rc.list()); } else if (isPost(req)) { RestView<RestResource> restCollectionView = rc.views().get(PluginName.GERRIT, "POST_ON_COLLECTION./"); if (restCollectionView != null) { viewData = new ViewData(null, restCollectionView); } else { throw methodNotAllowed(req); } } else { // DELETE on root collections is not supported throw methodNotAllowed(req); } } else { IdString id = path.remove(0); try { rsrc = rc.parse(rsrc, id); globals.quotaChecker.enforce(rsrc, req); if (path.isEmpty()) { checkPreconditions(req); } } catch (ResourceNotFoundException e) { if (!path.isEmpty()) { throw e; } globals.quotaChecker.enforce(req); if (isPost(req) || isPut(req)) { RestView<RestResource> createView = rc.views().get(PluginName.GERRIT, "CREATE./"); if (createView != null) { viewData = new ViewData(null, createView); path.add(id); } else { throw e; } } else if (isDelete(req)) { RestView<RestResource> deleteView = rc.views().get(PluginName.GERRIT, "DELETE_MISSING./"); if (deleteView != null) { viewData = new ViewData(null, deleteView); path.add(id); } else { throw e; } } else { throw e; } } if (viewData.view == null) { viewData = view(rc, req.getMethod(), path); } } checkRequiresCapability(viewData); while (viewData.view instanceof RestCollection<?, ?>) { @SuppressWarnings("unchecked") RestCollection<RestResource, RestResource> c = (RestCollection<RestResource, RestResource>) viewData.view; if (path.isEmpty()) { if (isRead(req)) { viewData = new ViewData(null, c.list()); } else if (isPost(req)) { // TODO: Here and on other collection methods: There is a bug that binds child views // with pluginName="gerrit" instead of the real plugin name. This has never worked // correctly and should be fixed where the binding gets created (DynamicMapProvider) // and here. RestView<RestResource> restCollectionView = c.views().get(PluginName.GERRIT, "POST_ON_COLLECTION./"); if (restCollectionView != null) { viewData = new ViewData(null, restCollectionView); } else { throw methodNotAllowed(req); } } else if (isDelete(req)) { RestView<RestResource> restCollectionView = c.views().get(PluginName.GERRIT, "DELETE_ON_COLLECTION./"); if (restCollectionView != null) { viewData = new ViewData(null, restCollectionView); } else { throw methodNotAllowed(req); } } else { throw methodNotAllowed(req); } break; } IdString id = path.remove(0); try { rsrc = c.parse(rsrc, id); checkPreconditions(req); viewData = new ViewData(null, null); } catch (ResourceNotFoundException e) { if (!path.isEmpty()) { throw e; } if (isPost(req) || isPut(req)) { RestView<RestResource> createView = c.views().get(PluginName.GERRIT, "CREATE./"); if (createView != null) { viewData = new ViewData(viewData.pluginName, createView); path.add(id); } else { throw e; } } else if (isDelete(req)) { RestView<RestResource> deleteView = c.views().get(PluginName.GERRIT, "DELETE_MISSING./"); if (deleteView != null) { viewData = new ViewData(viewData.pluginName, deleteView); path.add(id); } else { throw e; } } else { throw e; } } if (viewData.view == null) { viewData = view(c, req.getMethod(), path); } checkRequiresCapability(viewData); } if (notModified(req, rsrc, viewData.view)) { logger.atFinest().log("REST call succeeded: %d", SC_NOT_MODIFIED); res.sendError(SC_NOT_MODIFIED); return; } if (!globals.paramParser.get().parse(viewData.view, qp.params(), req, res)) { return; } if (viewData.view instanceof RestReadView<?> && isRead(req)) { response = ((RestReadView<RestResource>) viewData.view).apply(rsrc); } else if (viewData.view instanceof RestModifyView<?, ?>) { @SuppressWarnings("unchecked") RestModifyView<RestResource, Object> m = (RestModifyView<RestResource, Object>) viewData.view; Type type = inputType(m); inputRequestBody = parseRequest(req, type); response = invokeRestModifyViewWithRetry( req, traceContext, viewData, m, rsrc, inputRequestBody); if (inputRequestBody instanceof RawInput) { try (InputStream is = req.getInputStream()) { ServletUtils.consumeRequestBody(is); } } } else if (viewData.view instanceof RestCollectionCreateView<?, ?, ?>) { @SuppressWarnings("unchecked") RestCollectionCreateView<RestResource, RestResource, Object> m = (RestCollectionCreateView<RestResource, RestResource, Object>) viewData.view; Type type = inputType(m); inputRequestBody = parseRequest(req, type); response = invokeRestCollectionCreateViewWithRetry( req, traceContext, viewData, m, rsrc, path.get(0), inputRequestBody); if (inputRequestBody instanceof RawInput) { try (InputStream is = req.getInputStream()) { ServletUtils.consumeRequestBody(is); } } } else if (viewData.view instanceof RestCollectionDeleteMissingView<?, ?, ?>) { @SuppressWarnings("unchecked") RestCollectionDeleteMissingView<RestResource, RestResource, Object> m = (RestCollectionDeleteMissingView<RestResource, RestResource, Object>) viewData.view; Type type = inputType(m); inputRequestBody = parseRequest(req, type); response = invokeRestCollectionDeleteMissingViewWithRetry( req, traceContext, viewData, m, rsrc, path.get(0), inputRequestBody); if (inputRequestBody instanceof RawInput) { try (InputStream is = req.getInputStream()) { ServletUtils.consumeRequestBody(is); } } } else if (viewData.view instanceof RestCollectionModifyView<?, ?, ?>) { @SuppressWarnings("unchecked") RestCollectionModifyView<RestResource, RestResource, Object> m = (RestCollectionModifyView<RestResource, RestResource, Object>) viewData.view; Type type = inputType(m); inputRequestBody = parseRequest(req, type); response = invokeRestCollectionModifyViewWithRetry( req, traceContext, viewData, m, rsrc, inputRequestBody); if (inputRequestBody instanceof RawInput) { try (InputStream is = req.getInputStream()) { ServletUtils.consumeRequestBody(is); } } } else { throw new ResourceNotFoundException(); } if (response instanceof Response.Redirect) { CacheHeaders.setNotCacheable(res); String location = ((Response.Redirect) response).location(); res.sendRedirect(location); logger.atFinest().log("REST call redirected to: %s", location); return; } else if (response instanceof Response.Accepted) { CacheHeaders.setNotCacheable(res); res.setStatus(response.statusCode()); res.setHeader(HttpHeaders.LOCATION, ((Response.Accepted) response).location()); logger.atFinest().log("REST call succeeded: %d", response.statusCode()); return; } status = response.statusCode(); configureCaching(req, res, rsrc, viewData.view, response.caching()); res.setStatus(status); logger.atFinest().log("REST call succeeded: %d", status); } if (response != Response.none()) { Object value = Response.unwrap(response); if (value instanceof BinaryResult) { responseBytes = replyBinaryResult(req, res, (BinaryResult) value); } else { responseBytes = replyJson(req, res, false, qp.config(), value); } } } catch (MalformedJsonException | JsonParseException e) { responseBytes = replyError( req, res, status = SC_BAD_REQUEST, "Invalid " + JSON_TYPE + " in request", e); } catch (BadRequestException e) { responseBytes = replyError( req, res, status = SC_BAD_REQUEST, messageOr(e, "Bad Request"), e.caching(), e); } catch (AuthException e) { responseBytes = replyError(req, res, status = SC_FORBIDDEN, messageOr(e, "Forbidden"), e.caching(), e); } catch (AmbiguousViewException e) { responseBytes = replyError(req, res, status = SC_NOT_FOUND, messageOr(e, "Ambiguous"), e); } catch (ResourceNotFoundException e) { responseBytes = replyError(req, res, status = SC_NOT_FOUND, messageOr(e, "Not Found"), e.caching(), e); } catch (MethodNotAllowedException e) { responseBytes = replyError( req, res, status = SC_METHOD_NOT_ALLOWED, messageOr(e, "Method Not Allowed"), e.caching(), e); } catch (ResourceConflictException e) { responseBytes = replyError(req, res, status = SC_CONFLICT, messageOr(e, "Conflict"), e.caching(), e); } catch (PreconditionFailedException e) { responseBytes = replyError( req, res, status = SC_PRECONDITION_FAILED, messageOr(e, "Precondition Failed"), e.caching(), e); } catch (UnprocessableEntityException e) { responseBytes = replyError( req, res, status = SC_UNPROCESSABLE_ENTITY, messageOr(e, "Unprocessable Entity"), e.caching(), e); } catch (NotImplementedException e) { logger.atSevere().withCause(e).log("Error in %s %s", req.getMethod(), uriForLogging(req)); responseBytes = replyError(req, res, status = SC_NOT_IMPLEMENTED, messageOr(e, "Not Implemented"), e); } catch (UpdateException e) { Throwable t = e.getCause(); if (t instanceof LockFailureException) { logger.atSevere().withCause(t).log("Error in %s %s", req.getMethod(), uriForLogging(req)); responseBytes = replyError(req, res, status = SC_SERVICE_UNAVAILABLE, "Lock failure", e); } else { status = SC_INTERNAL_SERVER_ERROR; responseBytes = handleException(e, req, res); } } catch (QuotaException e) { responseBytes = replyError( req, res, status = SC_TOO_MANY_REQUESTS, messageOr(e, "Quota limit reached"), e.caching(), e); } catch (Exception e) { status = SC_INTERNAL_SERVER_ERROR; responseBytes = handleException(e, req, res); } finally { String metric = getViewName(viewData); globals.metrics.count.increment(metric); if (status >= SC_BAD_REQUEST) { globals.metrics.errorCount.increment(metric, status); } if (responseBytes != -1) { globals.metrics.responseBytes.record(metric, responseBytes); } globals.metrics.serverLatency.record( metric, System.nanoTime() - startNanos, TimeUnit.NANOSECONDS); globals.auditService.dispatch( new ExtendedHttpAuditEvent( globals.webSession.get().getSessionId(), globals.currentUser.get(), req, auditStartTs, qp != null ? qp.params() : ImmutableListMultimap.of(), inputRequestBody, status, response, rsrc, viewData == null ? null : viewData.view)); } } } private Response<?> invokeRestModifyViewWithRetry( HttpServletRequest req, TraceContext traceContext, ViewData viewData, RestModifyView<RestResource, Object> view, RestResource rsrc, Object inputRequestBody) throws Exception { return invokeRestEndpointWithRetry( req, traceContext, viewData, () -> view.apply(rsrc, inputRequestBody)); } private Response<?> invokeRestCollectionCreateViewWithRetry( HttpServletRequest req, TraceContext traceContext, ViewData viewData, RestCollectionCreateView<RestResource, RestResource, Object> view, RestResource rsrc, IdString path, Object inputRequestBody) throws Exception { return invokeRestEndpointWithRetry( req, traceContext, viewData, () -> view.apply(rsrc, path, inputRequestBody)); } private Response<?> invokeRestCollectionDeleteMissingViewWithRetry( HttpServletRequest req, TraceContext traceContext, ViewData viewData, RestCollectionDeleteMissingView<RestResource, RestResource, Object> view, RestResource rsrc, IdString path, Object inputRequestBody) throws Exception { return invokeRestEndpointWithRetry( req, traceContext, viewData, () -> view.apply(rsrc, path, inputRequestBody)); } private Response<?> invokeRestCollectionModifyViewWithRetry( HttpServletRequest req, TraceContext traceContext, ViewData viewData, RestCollectionModifyView<RestResource, RestResource, Object> view, RestResource rsrc, Object inputRequestBody) throws Exception { return invokeRestEndpointWithRetry( req, traceContext, viewData, () -> view.apply(rsrc, inputRequestBody)); } private Response<?> invokeRestEndpointWithRetry( HttpServletRequest req, TraceContext traceContext, ViewData viewData, Action<Response<?>> action) throws Exception { RetryHelper.Options.Builder retryOptionsBuilder = RetryHelper.options().caller(getViewName(viewData)); if (!traceContext.isTracing()) { // enable automatic retry with tracing in case of non-recoverable failure retryOptionsBuilder = retryOptionsBuilder .retryWithTrace(t -> !(t instanceof RestApiException)) .onAutoTrace( autoTraceId -> { traceId = Optional.of(autoTraceId); // Include details of the request into the trace. traceRequestData(req); }); } try { return globals.retryHelper.execute( ActionType.REST_REQUEST, action, retryOptionsBuilder.build(), t -> { if (t instanceof UpdateException) { t = t.getCause(); } return t instanceof LockFailureException; }); } finally { // If auto-tracing got triggered due to a non-recoverable failure, also trace the rest of // this request. This means logging is forced for all further log statements and the logs are // associated with the same trace ID. traceId.ifPresent(tid -> traceContext.addTag(RequestId.Type.TRACE_ID, tid).forceLogging()); } } private String getViewName(ViewData viewData) { return viewData != null && viewData.view != null ? globals.metrics.view(viewData) : "_unknown"; } private static HttpServletRequest applyXdOverrides(HttpServletRequest req, QueryParams qp) throws BadRequestException { if (!isPost(req)) { throw new BadRequestException("POST required"); } String method = qp.xdMethod(); String contentType = qp.xdContentType(); if (method.equals("POST") || method.equals("PUT")) { if (!isType(PLAIN_TEXT, req.getContentType())) { throw new BadRequestException("invalid " + CONTENT_TYPE); } if (Strings.isNullOrEmpty(contentType)) { throw new BadRequestException(XD_CONTENT_TYPE + " required"); } } return new HttpServletRequestWrapper(req) { @Override public String getMethod() { return method; } @Override public String getContentType() { return contentType; } }; } private void checkCors(HttpServletRequest req, HttpServletResponse res, boolean isXd) throws BadRequestException { String origin = req.getHeader(ORIGIN); if (isXd) { // Cross-domain, non-preflighted requests must come from an approved origin. if (Strings.isNullOrEmpty(origin) || !isOriginAllowed(origin)) { throw new BadRequestException("origin not allowed"); } res.addHeader(VARY, ORIGIN); res.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN, origin); res.setHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); } else if (!Strings.isNullOrEmpty(origin)) { // All other requests must be processed, but conditionally set CORS headers. if (globals.allowOrigin != null) { res.addHeader(VARY, ORIGIN); } if (isOriginAllowed(origin)) { setCorsHeaders(res, origin); } } } private static boolean isCorsPreflight(HttpServletRequest req) { return "OPTIONS".equals(req.getMethod()) && !Strings.isNullOrEmpty(req.getHeader(ORIGIN)) && !Strings.isNullOrEmpty(req.getHeader(ACCESS_CONTROL_REQUEST_METHOD)); } private void doCorsPreflight(HttpServletRequest req, HttpServletResponse res) throws BadRequestException { CacheHeaders.setNotCacheable(res); setHeaderList( res, VARY, ImmutableList.of(ORIGIN, ACCESS_CONTROL_REQUEST_METHOD, ACCESS_CONTROL_REQUEST_HEADERS)); String origin = req.getHeader(ORIGIN); if (Strings.isNullOrEmpty(origin) || !isOriginAllowed(origin)) { throw new BadRequestException("CORS not allowed"); } String method = req.getHeader(ACCESS_CONTROL_REQUEST_METHOD); if (!ALLOWED_CORS_METHODS.contains(method)) { throw new BadRequestException(method + " not allowed in CORS"); } String headers = req.getHeader(ACCESS_CONTROL_REQUEST_HEADERS); if (headers != null) { for (String reqHdr : Splitter.on(',').trimResults().split(headers)) { if (!ALLOWED_CORS_REQUEST_HEADERS.contains(reqHdr.toLowerCase(Locale.US))) { throw new BadRequestException(reqHdr + " not allowed in CORS"); } } } res.setStatus(SC_OK); setCorsHeaders(res, origin); res.setContentType(PLAIN_TEXT); res.setContentLength(0); } private static void setCorsHeaders(HttpServletResponse res, String origin) { res.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN, origin); res.setHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); res.setHeader(ACCESS_CONTROL_MAX_AGE, "600"); setHeaderList( res, ACCESS_CONTROL_ALLOW_METHODS, Iterables.concat(ALLOWED_CORS_METHODS, ImmutableList.of("OPTIONS"))); setHeaderList(res, ACCESS_CONTROL_ALLOW_HEADERS, ALLOWED_CORS_REQUEST_HEADERS); } private static void setHeaderList(HttpServletResponse res, String name, Iterable<String> values) { res.setHeader(name, Joiner.on(", ").join(values)); } private boolean isOriginAllowed(String origin) { return globals.allowOrigin != null && globals.allowOrigin.matcher(origin).matches(); } private static String messageOr(Throwable t, String defaultMessage) { if (!Strings.isNullOrEmpty(t.getMessage())) { return t.getMessage(); } return defaultMessage; } @SuppressWarnings({"unchecked", "rawtypes"}) private static boolean notModified( HttpServletRequest req, RestResource rsrc, RestView<RestResource> view) { if (!isRead(req)) { return false; } if (view instanceof ETagView) { String have = req.getHeader(HttpHeaders.IF_NONE_MATCH); if (have != null) { return have.equals(((ETagView) view).getETag(rsrc)); } } if (rsrc instanceof RestResource.HasETag) { String have = req.getHeader(HttpHeaders.IF_NONE_MATCH); if (have != null) { return have.equals(((RestResource.HasETag) rsrc).getETag()); } } if (rsrc instanceof RestResource.HasLastModified) { Timestamp m = ((RestResource.HasLastModified) rsrc).getLastModified(); long d = req.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE); // HTTP times are in seconds, database may have millisecond precision. return d / 1000L == m.getTime() / 1000L; } return false; } private static <R extends RestResource> void configureCaching( HttpServletRequest req, HttpServletResponse res, R rsrc, RestView<R> view, CacheControl c) { if (isRead(req)) { switch (c.getType()) { case NONE: default: CacheHeaders.setNotCacheable(res); break; case PRIVATE: addResourceStateHeaders(res, rsrc, view); CacheHeaders.setCacheablePrivate(res, c.getAge(), c.getUnit(), c.isMustRevalidate()); break; case PUBLIC: addResourceStateHeaders(res, rsrc, view); CacheHeaders.setCacheable(req, res, c.getAge(), c.getUnit(), c.isMustRevalidate()); break; } } else { CacheHeaders.setNotCacheable(res); } } private static <R extends RestResource> void addResourceStateHeaders( HttpServletResponse res, R rsrc, RestView<R> view) { if (view instanceof ETagView) { res.setHeader(HttpHeaders.ETAG, ((ETagView<R>) view).getETag(rsrc)); } else if (rsrc instanceof RestResource.HasETag) { res.setHeader(HttpHeaders.ETAG, ((RestResource.HasETag) rsrc).getETag()); } if (rsrc instanceof RestResource.HasLastModified) { res.setDateHeader( HttpHeaders.LAST_MODIFIED, ((RestResource.HasLastModified) rsrc).getLastModified().getTime()); } } private void checkPreconditions(HttpServletRequest req) throws PreconditionFailedException { if ("*".equals(req.getHeader(HttpHeaders.IF_NONE_MATCH))) { throw new PreconditionFailedException("Resource already exists"); } } private static Type inputType(RestModifyView<RestResource, Object> m) { // MyModifyView implements RestModifyView<SomeResource, MyInput> TypeLiteral<?> typeLiteral = TypeLiteral.get(m.getClass()); // RestModifyView<SomeResource, MyInput> // This is smart enough to resolve even when there are intervening subclasses, even if they have // reordered type arguments. TypeLiteral<?> supertypeLiteral = typeLiteral.getSupertype(RestModifyView.class); Type supertype = supertypeLiteral.getType(); checkState( supertype instanceof ParameterizedType, "supertype of %s is not parameterized: %s", typeLiteral, supertypeLiteral); return ((ParameterizedType) supertype).getActualTypeArguments()[1]; } private static Type inputType(RestCollectionView<RestResource, RestResource, Object> m) { // MyCollectionView implements RestCollectionView<SomeResource, SomeResource, MyInput> TypeLiteral<?> typeLiteral = TypeLiteral.get(m.getClass()); // RestCollectionView<SomeResource, SomeResource, MyInput> // This is smart enough to resolve even when there are intervening subclasses, even if they have // reordered type arguments. TypeLiteral<?> supertypeLiteral = typeLiteral.getSupertype(RestCollectionView.class); Type supertype = supertypeLiteral.getType(); checkState( supertype instanceof ParameterizedType, "supertype of %s is not parameterized: %s", typeLiteral, supertypeLiteral); return ((ParameterizedType) supertype).getActualTypeArguments()[2]; } private Object parseRequest(HttpServletRequest req, Type type) throws IOException, BadRequestException, SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException, MethodNotAllowedException { // HTTP/1.1 requires consuming the request body before writing non-error response (less than // 400). Consume the request body for all but raw input request types here. if (isType(JSON_TYPE, req.getContentType())) { try (BufferedReader br = req.getReader(); JsonReader json = new JsonReader(br)) { try { json.setLenient(true); JsonToken first; try { first = json.peek(); } catch (EOFException e) { throw new BadRequestException("Expected JSON object"); } if (first == JsonToken.STRING) { return parseString(json.nextString(), type); } return OutputFormat.JSON.newGson().fromJson(json, type); } finally { // Reader.close won't consume the rest of the input. Explicitly consume the request body. br.skip(Long.MAX_VALUE); } } } String method = req.getMethod(); if (("PUT".equals(method) || "POST".equals(method)) && acceptsRawInput(type)) { return parseRawInput(req, type); } if (isDelete(req) && hasNoBody(req)) { return null; } if (hasNoBody(req)) { return createInstance(type); } if (isType(PLAIN_TEXT, req.getContentType())) { try (BufferedReader br = req.getReader()) { char[] tmp = new char[256]; StringBuilder sb = new StringBuilder(); int n; while (0 < (n = br.read(tmp))) { sb.append(tmp, 0, n); } return parseString(sb.toString(), type); } } if (isPost(req) && isType(FORM_TYPE, req.getContentType())) { return OutputFormat.JSON.newGson().fromJson(ParameterParser.formToJson(req), type); } throw new BadRequestException("Expected Content-Type: " + JSON_TYPE); } private static boolean hasNoBody(HttpServletRequest req) { int len = req.getContentLength(); String type = req.getContentType(); return (len <= 0 && type == null) || (len == 0 && isType(FORM_TYPE, type)); } @SuppressWarnings("rawtypes") private static boolean acceptsRawInput(Type type) { if (type instanceof Class) { for (Field f : ((Class) type).getDeclaredFields()) { if (f.getType() == RawInput.class) { return true; } } } return false; } private Object parseRawInput(HttpServletRequest req, Type type) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, MethodNotAllowedException { Object obj = createInstance(type); for (Field f : obj.getClass().getDeclaredFields()) { if (f.getType() == RawInput.class) { f.setAccessible(true); f.set(obj, RawInputUtil.create(req)); return obj; } } throw new MethodNotAllowedException(); } private Object parseString(String value, Type type) throws BadRequestException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException { if (type == String.class) { return value; } Object obj = createInstance(type); if (Strings.isNullOrEmpty(value)) { return obj; } Field[] fields = obj.getClass().getDeclaredFields(); for (Field f : fields) { if (f.getAnnotation(DefaultInput.class) != null && f.getType() == String.class) { f.setAccessible(true); f.set(obj, value); return obj; } } throw new BadRequestException("Expected JSON object"); } @SuppressWarnings("unchecked") private static Object createInstance(Type type) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { if (type instanceof Class) { Class<Object> clazz = (Class<Object>) type; Constructor<Object> c = clazz.getDeclaredConstructor(); c.setAccessible(true); return c.newInstance(); } if (type instanceof ParameterizedType) { Type rawType = ((ParameterizedType) type).getRawType(); if (rawType instanceof Class && List.class.isAssignableFrom((Class<Object>) rawType)) { return new ArrayList<>(); } if (rawType instanceof Class && Map.class.isAssignableFrom((Class<Object>) rawType)) { return new HashMap<>(); } } throw new InstantiationException("Cannot make " + type); } /** * Sets a JSON reply on the given HTTP servlet response. * * @param req the HTTP servlet request * @param res the HTTP servlet response on which the reply should be set * @param allowTracing whether it is allowed to log the reply if tracing is enabled, must not be * set to {@code true} if the reply may contain sensitive data * @param config config parameters for the JSON formatting * @param result the object that should be formatted as JSON * @return the length of the response * @throws IOException */ public static long replyJson( @Nullable HttpServletRequest req, HttpServletResponse res, boolean allowTracing, ListMultimap<String, String> config, Object result) throws IOException { TemporaryBuffer.Heap buf = heap(HEAP_EST_SIZE, Integer.MAX_VALUE); buf.write(JSON_MAGIC); Writer w = new BufferedWriter(new OutputStreamWriter(buf, UTF_8)); Gson gson = newGson(config, req); if (result instanceof JsonElement) { gson.toJson((JsonElement) result, w); } else { gson.toJson(result, w); } w.write('\n'); w.flush(); if (allowTracing) { logger.atFinest().log( "JSON response body:\n%s", lazy( () -> { try { ByteArrayOutputStream debugOut = new ByteArrayOutputStream(); buf.writeTo(debugOut, null); return debugOut.toString(UTF_8.name()); } catch (IOException e) { return "<JSON formatting failed>"; } })); } return replyBinaryResult( req, res, asBinaryResult(buf).setContentType(JSON_TYPE).setCharacterEncoding(UTF_8)); } private static Gson newGson( ListMultimap<String, String> config, @Nullable HttpServletRequest req) { GsonBuilder gb = OutputFormat.JSON_COMPACT.newGsonBuilder(); enablePrettyPrint(gb, config, req); enablePartialGetFields(gb, config); return gb.create(); } private static void enablePrettyPrint( GsonBuilder gb, ListMultimap<String, String> config, @Nullable HttpServletRequest req) { String pp = Iterables.getFirst(config.get("pp"), null); if (pp == null) { pp = Iterables.getFirst(config.get("prettyPrint"), null); if (pp == null && req != null) { pp = acceptsJson(req) ? "0" : "1"; } } if ("1".equals(pp) || "true".equals(pp)) { gb.setPrettyPrinting(); } } private static void enablePartialGetFields(GsonBuilder gb, ListMultimap<String, String> config) { final Set<String> want = new HashSet<>(); for (String p : config.get("fields")) { Iterables.addAll(want, OptionUtil.splitOptionValue(p)); } if (!want.isEmpty()) { gb.addSerializationExclusionStrategy( new ExclusionStrategy() { private final Map<String, String> names = new HashMap<>(); @Override public boolean shouldSkipField(FieldAttributes field) { String name = names.get(field.getName()); if (name == null) { // Names are supplied by Gson in terms of Java source. // Translate and cache the JSON lower_case_style used. try { name = FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES.translateName( // field.getDeclaringClass().getDeclaredField(field.getName())); names.put(field.getName(), name); } catch (SecurityException | NoSuchFieldException e) { return true; } } return !want.contains(name); } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }); } } @SuppressWarnings("resource") static long replyBinaryResult( @Nullable HttpServletRequest req, HttpServletResponse res, BinaryResult bin) throws IOException { final BinaryResult appResult = bin; try { if (bin.getAttachmentName() != null) { res.setHeader( "Content-Disposition", "attachment; filename=\"" + bin.getAttachmentName() + "\""); } if (bin.isBase64()) { if (req != null && JSON_TYPE.equals(req.getHeader(HttpHeaders.ACCEPT))) { bin = stackJsonString(res, bin); } else { bin = stackBase64(res, bin); } } if (bin.canGzip() && acceptsGzip(req)) { bin = stackGzip(res, bin); } res.setContentType(bin.getContentType()); long len = bin.getContentLength(); if (0 <= len && len < Integer.MAX_VALUE) { res.setContentLength((int) len); } else if (0 <= len) { res.setHeader("Content-Length", Long.toString(len)); } if (req == null || !"HEAD".equals(req.getMethod())) { try (CountingOutputStream dst = new CountingOutputStream(res.getOutputStream())) { bin.writeTo(dst); return dst.getCount(); } } return 0; } finally { appResult.close(); } } private static BinaryResult stackJsonString(HttpServletResponse res, BinaryResult src) throws IOException { TemporaryBuffer.Heap buf = heap(HEAP_EST_SIZE, Integer.MAX_VALUE); buf.write(JSON_MAGIC); try (Writer w = new BufferedWriter(new OutputStreamWriter(buf, UTF_8)); JsonWriter json = new JsonWriter(w)) { json.setLenient(true); json.setHtmlSafe(true); json.value(src.asString()); w.write('\n'); } res.setHeader("X-FYI-Content-Encoding", "json"); res.setHeader("X-FYI-Content-Type", src.getContentType()); return asBinaryResult(buf).setContentType(JSON_TYPE).setCharacterEncoding(UTF_8); } private static BinaryResult stackBase64(HttpServletResponse res, BinaryResult src) throws IOException { BinaryResult b64; long len = src.getContentLength(); if (0 <= len && len <= (7 << 20)) { b64 = base64(src); } else { b64 = new BinaryResult() { @Override public void writeTo(OutputStream out) throws IOException { try (OutputStreamWriter w = new OutputStreamWriter( new FilterOutputStream(out) { @Override public void close() { // Do not close out, but only w and e. } }, ISO_8859_1); OutputStream e = BaseEncoding.base64().encodingStream(w)) { src.writeTo(e); } } }; } res.setHeader("X-FYI-Content-Encoding", "base64"); res.setHeader("X-FYI-Content-Type", src.getContentType()); return b64.setContentType(PLAIN_TEXT).setCharacterEncoding(ISO_8859_1); } private static BinaryResult stackGzip(HttpServletResponse res, BinaryResult src) throws IOException { BinaryResult gz; long len = src.getContentLength(); if (len < 256) { return src; // Do not compress very small payloads. } if (len <= (10 << 20)) { gz = compress(src); if (len <= gz.getContentLength()) { return src; } } else { gz = new BinaryResult() { @Override public void writeTo(OutputStream out) throws IOException { GZIPOutputStream gz = new GZIPOutputStream(out); src.writeTo(gz); gz.finish(); gz.flush(); } }; } res.setHeader("Content-Encoding", "gzip"); return gz.setContentType(src.getContentType()); } private ViewData view( RestCollection<RestResource, RestResource> rc, String method, List<IdString> path) throws AmbiguousViewException, RestApiException { DynamicMap<RestView<RestResource>> views = rc.views(); final IdString projection = path.isEmpty() ? IdString.fromUrl("/") : path.remove(0); if (!path.isEmpty()) { // If there are path components still remaining after this projection // is chosen, look for the projection based upon GET as the method as // the client thinks it is a nested collection. method = "GET"; } else if ("HEAD".equals(method)) { method = "GET"; } List<String> p = splitProjection(projection); if (p.size() == 2) { String viewname = p.get(1); if (Strings.isNullOrEmpty(viewname)) { viewname = "/"; } RestView<RestResource> view = views.get(p.get(0), method + "." + viewname); if (view != null) { return new ViewData(p.get(0), view); } view = views.get(p.get(0), "GET." + viewname); if (view != null) { return new ViewData(p.get(0), view); } throw new ResourceNotFoundException(projection); } String name = method + "." + p.get(0); RestView<RestResource> core = views.get(PluginName.GERRIT, name); if (core != null) { return new ViewData(PluginName.GERRIT, core); } // Check if we want to delegate to a child collection. Child collections are bound with // GET.name so we have to check for this since we haven't found any other views. core = views.get(PluginName.GERRIT, "GET." + p.get(0)); if (core != null) { return new ViewData(PluginName.GERRIT, core); } Map<String, RestView<RestResource>> r = new TreeMap<>(); for (String plugin : views.plugins()) { RestView<RestResource> action = views.get(plugin, name); if (action != null) { r.put(plugin, action); } } if (r.isEmpty()) { // Check if we want to delegate to a child collection. Child collections are bound with // GET.name so we have to check for this since we haven't found any other views. for (String plugin : views.plugins()) { RestView<RestResource> action = views.get(plugin, "GET." + p.get(0)); if (action != null) { r.put(plugin, action); } } } if (r.size() == 1) { Map.Entry<String, RestView<RestResource>> entry = Iterables.getOnlyElement(r.entrySet()); return new ViewData(entry.getKey(), entry.getValue()); } if (r.isEmpty()) { throw new ResourceNotFoundException(projection); } throw new AmbiguousViewException( String.format( "Projection %s is ambiguous: %s", name, r.keySet().stream().map(in -> in + "~" + projection).collect(joining(", ")))); } private static List<IdString> splitPath(HttpServletRequest req) { String path = RequestUtil.getEncodedPathInfo(req); if (Strings.isNullOrEmpty(path)) { return Collections.emptyList(); } List<IdString> out = new ArrayList<>(); for (String p : Splitter.on('/').split(path)) { out.add(IdString.fromUrl(p)); } if (out.size() > 0 && out.get(out.size() - 1).isEmpty()) { out.remove(out.size() - 1); } return out; } private static List<String> splitProjection(IdString projection) { List<String> p = Lists.newArrayListWithCapacity(2); Iterables.addAll(p, Splitter.on('~').limit(2).split(projection.get())); return p; } private void checkUserSession(HttpServletRequest req) throws AuthException { CurrentUser user = globals.currentUser.get(); if (isRead(req)) { user.setAccessPath(AccessPath.REST_API); } else if (user instanceof AnonymousUser) { throw new AuthException("Authentication required"); } else if (!globals.webSession.get().isAccessPathOk(AccessPath.REST_API)) { throw new AuthException( "Invalid authentication method. In order to authenticate, " + "prefix the REST endpoint URL with /a/ (e.g. http://example.com/a/projects/)."); } if (user.isIdentifiedUser()) { user.setLastLoginExternalIdKey(globals.webSession.get().getLastLoginExternalId()); } } private List<String> getParameterNames(HttpServletRequest req) { List<String> parameterNames = new ArrayList<>(req.getParameterMap().keySet()); Collections.sort(parameterNames); return parameterNames; } private TraceContext enableTracing(HttpServletRequest req, HttpServletResponse res) { // There are 2 ways to enable tracing for REST calls: // 1. by using the 'trace' or 'trace=<trace-id>' request parameter // 2. by setting the 'X-Gerrit-Trace:' or 'X-Gerrit-Trace:<trace-id>' header String traceValueFromHeader = req.getHeader(X_GERRIT_TRACE); String traceValueFromRequestParam = req.getParameter(ParameterParser.TRACE_PARAMETER); boolean doTrace = traceValueFromHeader != null || traceValueFromRequestParam != null; // Check whether no trace ID, one trace ID or 2 different trace IDs have been specified. String traceId1; String traceId2; if (!Strings.isNullOrEmpty(traceValueFromHeader)) { traceId1 = traceValueFromHeader; if (!Strings.isNullOrEmpty(traceValueFromRequestParam) && !traceValueFromHeader.equals(traceValueFromRequestParam)) { traceId2 = traceValueFromRequestParam; } else { traceId2 = null; } } else { traceId1 = Strings.emptyToNull(traceValueFromRequestParam); traceId2 = null; } // Use the first trace ID to start tracing. If this trace ID is null, a trace ID will be // generated. TraceContext traceContext = TraceContext.newTrace( doTrace, traceId1, (tagName, traceId) -> res.setHeader(X_GERRIT_TRACE, traceId)); // If a second trace ID was specified, add a tag for it as well. if (traceId2 != null) { traceContext.addTag(RequestId.Type.TRACE_ID, traceId2); res.addHeader(X_GERRIT_TRACE, traceId2); } return traceContext; } private RequestInfo createRequestInfo( TraceContext traceContext, String requestUri, List<IdString> path) { RequestInfo.Builder requestInfo = RequestInfo.builder(RequestInfo.RequestType.REST, globals.currentUser.get(), traceContext) .requestUri(requestUri); if (path.size() < 1) { return requestInfo.build(); } RestCollection<?, ?> rootCollection = members.get(); String resourceId = path.get(0).get(); if (rootCollection instanceof ProjectsCollection) { requestInfo.project(Project.nameKey(resourceId)); } else if (rootCollection instanceof ChangesCollection) { ChangeNotes changeNotes = globals.changeFinder.findOne(resourceId); if (changeNotes != null) { requestInfo.project(changeNotes.getProjectName()); } } return requestInfo.build(); } private void traceRequestData(HttpServletRequest req) { logger.atFinest().log( "Received REST request: %s %s (parameters: %s)", req.getMethod(), req.getRequestURI(), getParameterNames(req)); logger.atFinest().log("Calling user: %s", globals.currentUser.get().getLoggableName()); logger.atFinest().log( "Groups: %s", globals.currentUser.get().getEffectiveGroups().getKnownGroups()); } private boolean isDelete(HttpServletRequest req) { return "DELETE".equals(req.getMethod()); } private static boolean isPost(HttpServletRequest req) { return "POST".equals(req.getMethod()); } private boolean isPut(HttpServletRequest req) { return "PUT".equals(req.getMethod()); } private static boolean isRead(HttpServletRequest req) { return "GET".equals(req.getMethod()) || "HEAD".equals(req.getMethod()); } private static MethodNotAllowedException methodNotAllowed(HttpServletRequest req) { return new MethodNotAllowedException( String.format("Not implemented: %s %s", req.getMethod(), requestUri(req))); } private static String requestUri(HttpServletRequest req) { String uri = req.getRequestURI(); if (uri.startsWith("/a/")) { return uri.substring(2); } return uri; } private void checkRequiresCapability(ViewData d) throws AuthException, PermissionBackendException { try { globals.permissionBackend.currentUser().check(GlobalPermission.ADMINISTRATE_SERVER); } catch (AuthException e) { // Skiping globals .permissionBackend .currentUser() .checkAny(GlobalPermission.fromAnnotation(d.pluginName, d.view.getClass())); } } private long handleException(Throwable err, HttpServletRequest req, HttpServletResponse res) throws IOException { logger.atSevere().withCause(err).log("Error in %s %s", req.getMethod(), uriForLogging(req)); if (!res.isCommitted()) { res.reset(); traceId.ifPresent(traceId -> res.addHeader(X_GERRIT_TRACE, traceId)); return replyError(req, res, SC_INTERNAL_SERVER_ERROR, "Internal server error", err); } return 0; } private static String uriForLogging(HttpServletRequest req) { String uri = req.getRequestURI(); if (!Strings.isNullOrEmpty(req.getQueryString())) { uri += "?" + LogRedactUtil.redactQueryString(req.getQueryString()); } return uri; } public static long replyError( HttpServletRequest req, HttpServletResponse res, int statusCode, String msg, @Nullable Throwable err) throws IOException { return replyError(req, res, statusCode, msg, CacheControl.NONE, err); } public static long replyError( HttpServletRequest req, HttpServletResponse res, int statusCode, String msg, CacheControl c, @Nullable Throwable err) throws IOException { if (err != null) { RequestUtil.setErrorTraceAttribute(req, err); } configureCaching(req, res, null, null, c); checkArgument(statusCode >= 400, "non-error status: %s", statusCode); res.setStatus(statusCode); logger.atFinest().withCause(err).log("REST call failed: %d", statusCode); return replyText(req, res, true, msg); } /** * Sets a text reply on the given HTTP servlet response. * * @param req the HTTP servlet request * @param res the HTTP servlet response on which the reply should be set * @param allowTracing whether it is allowed to log the reply if tracing is enabled, must not be * set to {@code true} if the reply may contain sensitive data * @param text the text reply * @return the length of the response * @throws IOException */ static long replyText( @Nullable HttpServletRequest req, HttpServletResponse res, boolean allowTracing, String text) throws IOException { if ((req == null || isRead(req)) && isMaybeHTML(text)) { return replyJson( req, res, allowTracing, ImmutableListMultimap.of("pp", "0"), new JsonPrimitive(text)); } if (!text.endsWith("\n")) { text += "\n"; } if (allowTracing) { logger.atFinest().log("Text response body:\n%s", text); } return replyBinaryResult(req, res, BinaryResult.create(text).setContentType(PLAIN_TEXT)); } private static boolean isMaybeHTML(String text) { return CharMatcher.anyOf("<&").matchesAnyOf(text); } private static boolean acceptsJson(HttpServletRequest req) { return req != null && isType(JSON_TYPE, req.getHeader(HttpHeaders.ACCEPT)); } private static boolean acceptsGzip(HttpServletRequest req) { if (req != null) { String accepts = req.getHeader(HttpHeaders.ACCEPT_ENCODING); return accepts != null && accepts.contains("gzip"); } return false; } private static boolean isType(String expect, String given) { if (given == null) { return false; } if (expect.equals(given)) { return true; } if (given.startsWith(expect + ",")) { return true; } for (String p : Splitter.on(TYPE_SPLIT_PATTERN).split(given)) { if (expect.equals(p)) { return true; } } return false; } private static int base64MaxSize(long n) { return 4 * IntMath.divide((int) n, 3, CEILING); } private static BinaryResult base64(BinaryResult bin) throws IOException { int maxSize = base64MaxSize(bin.getContentLength()); int estSize = Math.min(base64MaxSize(HEAP_EST_SIZE), maxSize); TemporaryBuffer.Heap buf = heap(estSize, maxSize); try (OutputStream encoded = BaseEncoding.base64().encodingStream(new OutputStreamWriter(buf, ISO_8859_1))) { bin.writeTo(encoded); } return asBinaryResult(buf); } private static BinaryResult compress(BinaryResult bin) throws IOException { TemporaryBuffer.Heap buf = heap(HEAP_EST_SIZE, 20 << 20); try (GZIPOutputStream gz = new GZIPOutputStream(buf)) { bin.writeTo(gz); } return asBinaryResult(buf).setContentType(bin.getContentType()); } @SuppressWarnings("resource") private static BinaryResult asBinaryResult(TemporaryBuffer.Heap buf) { return new BinaryResult() { @Override public void writeTo(OutputStream os) throws IOException { buf.writeTo(os, null); } }.setContentLength(buf.length()); } private static Heap heap(int est, int max) { return new TemporaryBuffer.Heap(est, max); } private static class AmbiguousViewException extends Exception { private static final long serialVersionUID = 1L; AmbiguousViewException(String message) { super(message); } } static class ViewData { String pluginName; RestView<RestResource> view; ViewData(String pluginName, RestView<RestResource> view) { this.pluginName = pluginName; this.view = view; } } }
Implement auto-tracing for read REST endpoints So far we don't know of any recoverable failure that should trigger retrying of read views, however for read views we want to automatically retry once with tracing enabled if a non-recoverable error occurs. Signed-off-by: Edwin Kempin <[email protected]> Change-Id: I6d15a691f502d1ef1d59b3ccfd191cad28bf3705
java/com/google/gerrit/httpd/restapi/RestApiServlet.java
Implement auto-tracing for read REST endpoints
<ide><path>ava/com/google/gerrit/httpd/restapi/RestApiServlet.java <ide> import java.util.Set; <ide> import java.util.TreeMap; <ide> import java.util.concurrent.TimeUnit; <add>import java.util.function.Predicate; <ide> import java.util.regex.Pattern; <ide> import java.util.stream.Stream; <ide> import java.util.zip.GZIPOutputStream; <ide> } <ide> <ide> if (viewData.view instanceof RestReadView<?> && isRead(req)) { <del> response = ((RestReadView<RestResource>) viewData.view).apply(rsrc); <add> response = <add> invokeRestReadViewWithRetry( <add> req, traceContext, viewData, (RestReadView<RestResource>) viewData.view, rsrc); <ide> } else if (viewData.view instanceof RestModifyView<?, ?>) { <ide> @SuppressWarnings("unchecked") <ide> RestModifyView<RestResource, Object> m = <ide> } <ide> } <ide> <add> private Response<?> invokeRestReadViewWithRetry( <add> HttpServletRequest req, <add> TraceContext traceContext, <add> ViewData viewData, <add> RestReadView<RestResource> view, <add> RestResource rsrc) <add> throws Exception { <add> return invokeRestEndpointWithRetry( <add> req, traceContext, viewData, () -> view.apply(rsrc), noRetry()); <add> } <add> <ide> private Response<?> invokeRestModifyViewWithRetry( <ide> HttpServletRequest req, <ide> TraceContext traceContext, <ide> Object inputRequestBody) <ide> throws Exception { <ide> return invokeRestEndpointWithRetry( <del> req, traceContext, viewData, () -> view.apply(rsrc, inputRequestBody)); <add> req, <add> traceContext, <add> viewData, <add> () -> view.apply(rsrc, inputRequestBody), <add> retryOnLockFailure()); <ide> } <ide> <ide> private Response<?> invokeRestCollectionCreateViewWithRetry( <ide> Object inputRequestBody) <ide> throws Exception { <ide> return invokeRestEndpointWithRetry( <del> req, traceContext, viewData, () -> view.apply(rsrc, path, inputRequestBody)); <add> req, <add> traceContext, <add> viewData, <add> () -> view.apply(rsrc, path, inputRequestBody), <add> retryOnLockFailure()); <ide> } <ide> <ide> private Response<?> invokeRestCollectionDeleteMissingViewWithRetry( <ide> Object inputRequestBody) <ide> throws Exception { <ide> return invokeRestEndpointWithRetry( <del> req, traceContext, viewData, () -> view.apply(rsrc, path, inputRequestBody)); <add> req, <add> traceContext, <add> viewData, <add> () -> view.apply(rsrc, path, inputRequestBody), <add> retryOnLockFailure()); <ide> } <ide> <ide> private Response<?> invokeRestCollectionModifyViewWithRetry( <ide> Object inputRequestBody) <ide> throws Exception { <ide> return invokeRestEndpointWithRetry( <del> req, traceContext, viewData, () -> view.apply(rsrc, inputRequestBody)); <add> req, <add> traceContext, <add> viewData, <add> () -> view.apply(rsrc, inputRequestBody), <add> retryOnLockFailure()); <ide> } <ide> <ide> private Response<?> invokeRestEndpointWithRetry( <ide> HttpServletRequest req, <ide> TraceContext traceContext, <ide> ViewData viewData, <del> Action<Response<?>> action) <add> Action<Response<?>> action, <add> Predicate<Throwable> retryExceptionPredicate) <ide> throws Exception { <ide> RetryHelper.Options.Builder retryOptionsBuilder = <ide> RetryHelper.options().caller(getViewName(viewData)); <ide> } <ide> try { <ide> return globals.retryHelper.execute( <del> ActionType.REST_REQUEST, <del> action, <del> retryOptionsBuilder.build(), <del> t -> { <del> if (t instanceof UpdateException) { <del> t = t.getCause(); <del> } <del> return t instanceof LockFailureException; <del> }); <add> ActionType.REST_REQUEST, action, retryOptionsBuilder.build(), retryExceptionPredicate); <ide> } finally { <ide> // If auto-tracing got triggered due to a non-recoverable failure, also trace the rest of <ide> // this request. This means logging is forced for all further log statements and the logs are <ide> // associated with the same trace ID. <ide> traceId.ifPresent(tid -> traceContext.addTag(RequestId.Type.TRACE_ID, tid).forceLogging()); <ide> } <add> } <add> <add> private static Predicate<Throwable> noRetry() { <add> return t -> false; <add> } <add> <add> private static Predicate<Throwable> retryOnLockFailure() { <add> return t -> { <add> if (t instanceof UpdateException) { <add> t = t.getCause(); <add> } <add> return t instanceof LockFailureException; <add> }; <ide> } <ide> <ide> private String getViewName(ViewData viewData) {
Java
agpl-3.0
8d3510766b3bc244829b8abc50cba161679870c9
0
elki-project/elki,elki-project/elki,elki-project/elki
package de.lmu.ifi.dbs.properties; import de.lmu.ifi.dbs.algorithm.Algorithm; import de.lmu.ifi.dbs.logging.LoggingConfiguration; import de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import java.util.regex.Pattern; /** * Provides management of properties. * * @author Arthur Zimek (<a href="mailto:[email protected]">[email protected]</a>) */ public final class Properties { /** * Holds the debug status. */ private static final boolean DEBUG = LoggingConfiguration.DEBUG; /** * The logger for this class. */ private Logger logger = Logger.getLogger(this.getClass().getName()); /** * The pattern to split for separate entries in a property string, which is * a &quot;,&quot;. */ public static final Pattern PROPERTY_SEPARATOR = Pattern.compile(","); /** * The Properties for the KDDFramework. */ public static final Properties KDD_FRAMEWORK_PROPERTIES = new Properties(Properties.class.getPackage().getName().replace('.',File.separatorChar)+File.separatorChar + "KDDFramework.prp"); /** * Stores the properties as defined by a property-file. */ private final java.util.Properties PROPERTIES; /** * Provides the properties as defined in the designated file. * * @param filename * name of a file to provide property-definitions. */ private Properties(String filename) { this.PROPERTIES = new java.util.Properties(); try { PROPERTIES.load(ClassLoader.getSystemResourceAsStream(filename)); } catch (Exception e) { logger.warning("Unable to load properties file " + filename + ".\n"); } } /** * Provides the entries (separated by * {@link #PROPERTY_SEPARATOR PROPERTY_SEPARATOR}) for a specified * PropertyName. * * @param propertyName * the PropertyName of the property to retrieve * @return the entries (separated by * {@link #PROPERTY_SEPARATOR PROPERTY_SEPARATOR}) for the * specified PropertyName */ public String[] getProperty(PropertyName propertyName) { String property = propertyName == null ? null : PROPERTIES.getProperty(propertyName.getName()); return property == null ? new String[0] : PROPERTY_SEPARATOR.split(property); } /** * Provides a description string listing all classes * for the given superclass or interface as * specified in the properties. * * @param superclass the class to be extended or interface * to be implemented * @return a description string listing all classes * for the given superclass or interface as * specified in the properties */ public String conditionAndAvailableClassesFor(Class superclass) { StringBuilder info = new StringBuilder(); info.append("name of a class "); if(superclass.isInterface()) { info.append("implementing "); } else { info.append("extending "); } info.append(superclass.getName()); info.append(" - available classes:\n"); PropertyName propertyName = PropertyName.getOrCreatePropertyName(superclass); String[] classNames = getProperty(propertyName); for(String name : classNames) { try { Object propertyInstance = propertyName.getType().cast(propertyName.classForName(name).newInstance()); info.append("--"); info.append(name); info.append('\n'); } catch(InstantiationException e) { logger.warning("Invalid classname \"" + name + "\" for property \"" + propertyName.getName() + "\" of class \"" + propertyName.getType().getName() + "\" in property-file: " + e.getMessage() + " - " + e.getClass().getName() + "\n"); } catch(IllegalAccessException e) { logger.warning("Invalid classname \"" + name + "\" for property \"" + propertyName.getName() + "\" of class \"" + propertyName.getType().getName() + "\" in property-file: " + e.getMessage() + " - " + e.getClass().getName() + "\n"); } catch(ClassNotFoundException e) { logger.warning("Invalid classname \"" + name + "\" for property \"" + propertyName.getName() + "\" of class \"" + propertyName.getType().getName() + "\" in property-file: " + e.getMessage() + " - " + e.getClass().getName() + "\n"); } } return info.toString(); } /** * Returns an array of PropertyDescription for all entries for the given * PropertyName. * * @param propertyName * the Propertyname of the property to retrieve * @return PropertyDescriptins for all entries of the given PropertyName */ public PropertyDescription[] getProperties(PropertyName propertyName) { String[] entries = getProperty(propertyName); List<PropertyDescription> result = new ArrayList<PropertyDescription>(); for (String entry : entries) { try { String desc = ""; Object propertyInstance = propertyName.getType().cast(propertyName.classForName(entry).newInstance()); if (propertyInstance instanceof Algorithm) { // TODO: description -- check whether this provides the // desired result desc = ((Algorithm) propertyInstance).getDescription().toString(); } else if (propertyInstance instanceof Parameterizable) { desc = ((Parameterizable) propertyInstance).description(); } result.add(new PropertyDescription(entry, desc)); } catch (InstantiationException e) { logger.warning("Invalid classname \"" + entry + "\" for property \"" + propertyName.getName() + "\" of class \"" + propertyName.getType().getName() + "\" in property-file: " + e.getMessage() + " - " + e.getClass().getName() + "\n"); } catch (IllegalAccessException e) { logger.warning("Invalid classname \"" + entry + "\" for property \"" + propertyName.getName() + "\" of class \"" + propertyName.getType().getName() + "\" in property-file: " + e.getMessage() + " - " + e.getClass().getName() + "\n"); } catch (ClassNotFoundException e) { logger.warning("Invalid classname \"" + entry + "\" for property \"" + propertyName.getName() + "\" of class \"" + propertyName.getType().getName() + "\" in property-file: " + e.getMessage() + " - " + e.getClass().getName() + "\n"); } } PropertyDescription[] propertyDescription = new PropertyDescription[result.size()]; result.toArray(propertyDescription); return propertyDescription; } }
src/de/lmu/ifi/dbs/properties/Properties.java
package de.lmu.ifi.dbs.properties; import de.lmu.ifi.dbs.algorithm.Algorithm; import de.lmu.ifi.dbs.logging.LoggingConfiguration; import de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import java.util.regex.Pattern; /** * Provides management of properties. * * @author Arthur Zimek (<a href="mailto:[email protected]">[email protected]</a>) */ public final class Properties { /** * Holds the debug status. */ private static final boolean DEBUG = LoggingConfiguration.DEBUG; /** * The logger for this class. */ private Logger logger = Logger.getLogger(this.getClass().getName()); /** * The pattern to split for separate entries in a property string, which is * a &quot;,&quot;. */ public static final Pattern PROPERTY_SEPARATOR = Pattern.compile(","); /** * The Properties for the KDDFramework. */ public static final Properties KDD_FRAMEWORK_PROPERTIES = new Properties(Properties.class.getPackage().getName().replace('.',File.separatorChar)+File.separatorChar + "KDDFramework.prp"); /** * Stores the properties as defined by a property-file. */ private final java.util.Properties PROPERTIES; /** * Provides the properties as defined in the designated file. * * @param filename * name of a file to provide property-definitions. */ private Properties(String filename) { this.PROPERTIES = new java.util.Properties(); try { PROPERTIES.load(ClassLoader.getSystemResourceAsStream(filename)); } catch (Exception e) { logger.warning("Unable to load properties file " + filename + ".\n"); } } /** * Provides the entries (separated by * {@link #PROPERTY_SEPARATOR PROPERTY_SEPARATOR}) for a specified * PropertyName. * * @param propertyName * the PropertyName of the property to retrieve * @return the entries (separated by * {@link #PROPERTY_SEPARATOR PROPERTY_SEPARATOR}) for the * specified PropertyName */ public String[] getProperty(PropertyName propertyName) { String property = propertyName == null ? null : PROPERTIES.getProperty(propertyName.getName()); return property == null ? new String[0] : PROPERTY_SEPARATOR.split(property); } /** * * * * @param superclass * @return */ public String availableClassesFor(Class superclass) { StringBuilder info = new StringBuilder(); String[] classNames = getProperty(PropertyName.getOrCreatePropertyName(superclass)); // TODO return info.toString(); } /** * Returns an array of PropertyDescription for all entries for the given * PropertyName. * * @param propertyName * the Propertyname of the property to retrieve * @return PropertyDescriptins for all entries of the given PropertyName */ public PropertyDescription[] getProperties(PropertyName propertyName) { String[] entries = getProperty(propertyName); List<PropertyDescription> result = new ArrayList<PropertyDescription>(); for (String entry : entries) { try { String desc = ""; Object propertyInstance = propertyName.getType().cast(propertyName.classForName(entry).newInstance()); if (propertyInstance instanceof Algorithm) { // TODO: description -- check whether this provides the // desired result desc = ((Algorithm) propertyInstance).getDescription().toString(); } else if (propertyInstance instanceof Parameterizable) { desc = ((Parameterizable) propertyInstance).description(); } result.add(new PropertyDescription(entry, desc)); } catch (InstantiationException e) { logger.warning("Invalid classname \"" + entry + "\" for property \"" + propertyName.getName() + "\" of class \"" + propertyName.getType().getName() + "\" in property-file: " + e.getMessage() + " - " + e.getClass().getName() + "\n"); } catch (IllegalAccessException e) { logger.warning("Invalid classname \"" + entry + "\" for property \"" + propertyName.getName() + "\" of class \"" + propertyName.getType().getName() + "\" in property-file: " + e.getMessage() + " - " + e.getClass().getName() + "\n"); } catch (ClassNotFoundException e) { logger.warning("Invalid classname \"" + entry + "\" for property \"" + propertyName.getName() + "\" of class \"" + propertyName.getType().getName() + "\" in property-file: " + e.getMessage() + " - " + e.getClass().getName() + "\n"); } } PropertyDescription[] propertyDescription = new PropertyDescription[result.size()]; result.toArray(propertyDescription); return propertyDescription; } }
condition
src/de/lmu/ifi/dbs/properties/Properties.java
condition
<ide><path>rc/de/lmu/ifi/dbs/properties/Properties.java <ide> } <ide> <ide> /** <del> * <del> * <del> * <del> * @param superclass <del> * @return <del> */ <del> public String availableClassesFor(Class superclass) <add> * Provides a description string listing all classes <add> * for the given superclass or interface as <add> * specified in the properties. <add> * <add> * @param superclass the class to be extended or interface <add> * to be implemented <add> * @return a description string listing all classes <add> * for the given superclass or interface as <add> * specified in the properties <add> */ <add> public String conditionAndAvailableClassesFor(Class superclass) <ide> { <ide> StringBuilder info = new StringBuilder(); <del> String[] classNames = getProperty(PropertyName.getOrCreatePropertyName(superclass)); <del> // TODO <add> info.append("name of a class "); <add> if(superclass.isInterface()) <add> { <add> info.append("implementing "); <add> } <add> else <add> { <add> info.append("extending "); <add> } <add> info.append(superclass.getName()); <add> info.append(" - available classes:\n"); <add> PropertyName propertyName = PropertyName.getOrCreatePropertyName(superclass); <add> String[] classNames = getProperty(propertyName); <add> for(String name : classNames) <add> { <add> try <add> { <add> Object propertyInstance = propertyName.getType().cast(propertyName.classForName(name).newInstance()); <add> info.append("--"); <add> info.append(name); <add> info.append('\n'); <add> } <add> catch(InstantiationException e) <add> { <add> logger.warning("Invalid classname \"" + name <add> + "\" for property \"" + propertyName.getName() <add> + "\" of class \"" + propertyName.getType().getName() <add> + "\" in property-file: " + e.getMessage() + " - " <add> + e.getClass().getName() + "\n"); <add> } <add> catch(IllegalAccessException e) <add> { <add> logger.warning("Invalid classname \"" + name <add> + "\" for property \"" + propertyName.getName() <add> + "\" of class \"" + propertyName.getType().getName() <add> + "\" in property-file: " + e.getMessage() + " - " <add> + e.getClass().getName() + "\n"); <add> } <add> catch(ClassNotFoundException e) <add> { <add> logger.warning("Invalid classname \"" + name <add> + "\" for property \"" + propertyName.getName() <add> + "\" of class \"" + propertyName.getType().getName() <add> + "\" in property-file: " + e.getMessage() + " - " <add> + e.getClass().getName() + "\n"); <add> } <add> } <ide> return info.toString(); <ide> } <ide> <ide> // TODO: description -- check whether this provides the <ide> // desired result <ide> desc = ((Algorithm) propertyInstance).getDescription().toString(); <del> } else if (propertyInstance instanceof Parameterizable) <add> } <add> else if (propertyInstance instanceof Parameterizable) <ide> { <ide> desc = ((Parameterizable) propertyInstance).description(); <ide> }
Java
apache-2.0
03ff19df45e8e41bf9ca284e48fa5f289101d424
0
davide-maestroni/jroutine,davide-maestroni/jroutine
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gh.bmd.jrt.core; import com.gh.bmd.jrt.builder.InvocationConfiguration; import com.gh.bmd.jrt.channel.InvocationChannel; import com.gh.bmd.jrt.channel.ResultChannel; import com.gh.bmd.jrt.core.DefaultInvocationChannel.InvocationManager; import com.gh.bmd.jrt.invocation.Invocation; import com.gh.bmd.jrt.invocation.InvocationInterruptedException; import com.gh.bmd.jrt.invocation.InvocationTimeoutException; import com.gh.bmd.jrt.invocation.TemplateInvocation; import com.gh.bmd.jrt.log.Logger; import com.gh.bmd.jrt.routine.Routine; import com.gh.bmd.jrt.routine.TemplateRoutine; import com.gh.bmd.jrt.runner.Runner; import com.gh.bmd.jrt.runner.Runners; import com.gh.bmd.jrt.util.TimeDuration; import com.gh.bmd.jrt.util.TimeDuration.Check; import java.util.LinkedList; import javax.annotation.Nonnull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import static com.gh.bmd.jrt.util.TimeDuration.ZERO; /** * Basic abstract implementation of a routine. * <p/> * This class provides a default implementation of all the routine features. The inheriting class * just needs to create invocation objects when required. * <p/> * Created by davide-maestroni on 9/7/14. * * @param <INPUT> the input data type. * @param <OUTPUT> the output data type. */ public abstract class AbstractRoutine<INPUT, OUTPUT> extends TemplateRoutine<INPUT, OUTPUT> { private static final TimeDuration DEFAULT_AVAIL_TIMEOUT = ZERO; private static final int DEFAULT_CORE_INVOCATIONS = 10; private static final int DEFAULT_MAX_INVOCATIONS = Integer.MAX_VALUE; private final LinkedList<Invocation<INPUT, OUTPUT>> mAsyncInvocations = new LinkedList<Invocation<INPUT, OUTPUT>>(); private final Runner mAsyncRunner; private final TimeDuration mAvailTimeout; private final InvocationConfiguration mConfiguration; private final int mCoreInvocations; private final Logger mLogger; private final int mMaxInvocations; private final Object mMutex = new Object(); private final Object mParallelMutex = new Object(); private final LinkedList<Invocation<INPUT, OUTPUT>> mSyncInvocations = new LinkedList<Invocation<INPUT, OUTPUT>>(); private final Runner mSyncRunner; private volatile DefaultInvocationManager mAsyncManager; private AbstractRoutine<INPUT, OUTPUT> mParallelRoutine; private int mRunningCount; private final Check mIsInvocationAvailable = new Check() { public boolean isTrue() { return mRunningCount < mMaxInvocations; } }; private volatile DefaultInvocationManager mSyncManager; /** * Constructor. * * @param configuration the invocation configuration. */ @SuppressWarnings("ConstantConditions") protected AbstractRoutine(@Nonnull final InvocationConfiguration configuration) { mConfiguration = configuration; mSyncRunner = configuration.getSyncRunnerOr(Runners.queuedRunner()); final int priority = configuration.getPriorityOr(InvocationConfiguration.DEFAULT); final Runner asyncRunner = configuration.getAsyncRunnerOr(Runners.sharedRunner()); if (priority != InvocationConfiguration.DEFAULT) { mAsyncRunner = Runners.priorityRunner(asyncRunner).getRunner(priority); } else { mAsyncRunner = asyncRunner; } mMaxInvocations = configuration.getMaxInstancesOr(DEFAULT_MAX_INVOCATIONS); mCoreInvocations = configuration.getCoreInstancesOr(DEFAULT_CORE_INVOCATIONS); mAvailTimeout = configuration.getAvailInstanceTimeoutOr(DEFAULT_AVAIL_TIMEOUT); mLogger = configuration.newLogger(this); mLogger.dbg("building routine with configuration: %s", configuration); } /** * Constructor. * * @param configuration the invocation configuration. * @param syncRunner the runner used for synchronous invocation. * @param asyncRunner the runner used for asynchronous invocation. * @param logger the logger instance. */ private AbstractRoutine(@Nonnull final InvocationConfiguration configuration, @Nonnull final Runner syncRunner, @Nonnull final Runner asyncRunner, @Nonnull final Logger logger) { mConfiguration = configuration; mSyncRunner = syncRunner; mAsyncRunner = asyncRunner; mMaxInvocations = DEFAULT_MAX_INVOCATIONS; mCoreInvocations = DEFAULT_CORE_INVOCATIONS; mAvailTimeout = DEFAULT_AVAIL_TIMEOUT; mLogger = logger.subContextLogger(this); } @Nonnull public InvocationChannel<INPUT, OUTPUT> asyncInvoke() { return invoke(InvocationType.ASYNC); } @Nonnull public InvocationChannel<INPUT, OUTPUT> parallelInvoke() { synchronized (mParallelMutex) { mLogger.dbg("invoking routine: parallel"); if (mParallelRoutine == null) { mParallelRoutine = new AbstractRoutine<INPUT, OUTPUT>(mConfiguration, mSyncRunner, mAsyncRunner, mLogger) { @Nonnull @Override protected Invocation<INPUT, OUTPUT> newInvocation( @Nonnull final InvocationType type) { return new ParallelInvocation<INPUT, OUTPUT>(AbstractRoutine.this); } }; } } return mParallelRoutine.asyncInvoke(); } @Nonnull public InvocationChannel<INPUT, OUTPUT> syncInvoke() { return invoke(InvocationType.SYNC); } @Override public void purge() { synchronized (mMutex) { final Logger logger = mLogger; final LinkedList<Invocation<INPUT, OUTPUT>> syncInvocations = mSyncInvocations; for (final Invocation<INPUT, OUTPUT> invocation : syncInvocations) { try { invocation.onDestroy(); } catch (final InvocationInterruptedException e) { throw e; } catch (final Throwable ignored) { logger.wrn(ignored, "ignoring exception while destroying invocation instance"); } } syncInvocations.clear(); final LinkedList<Invocation<INPUT, OUTPUT>> asyncInvocations = mAsyncInvocations; for (final Invocation<INPUT, OUTPUT> invocation : asyncInvocations) { try { invocation.onDestroy(); } catch (final InvocationInterruptedException e) { throw e; } catch (final Throwable ignored) { logger.wrn(ignored, "ignoring exception while destroying invocation instance"); } } asyncInvocations.clear(); } } /** * Converts an invocation instance to the specified type. * * @param invocation the invocation to convert. * @param type the converted invocation type. * @return the converted invocation. */ @Nonnull @SuppressWarnings("UnusedParameters") protected Invocation<INPUT, OUTPUT> convertInvocation( @Nonnull final Invocation<INPUT, OUTPUT> invocation, @Nonnull final InvocationType type) { return invocation; } /** * Returns the routine logger. * * @return the logger instance. */ @Nonnull protected Logger getLogger() { return mLogger; } /** * Creates a new invocation instance. * * @param type the invocation type. * @return the invocation instance. */ @Nonnull protected abstract Invocation<INPUT, OUTPUT> newInvocation(@Nonnull InvocationType type); @Nonnull private DefaultInvocationManager getInvocationManager(@Nonnull final InvocationType type) { if (type == InvocationType.ASYNC) { if (mAsyncManager == null) { mAsyncManager = new DefaultInvocationManager(type, mAsyncInvocations, mSyncInvocations); } return mAsyncManager; } if (mSyncManager == null) { mSyncManager = new DefaultInvocationManager(type, mSyncInvocations, mAsyncInvocations); } return mSyncManager; } @Nonnull private InvocationChannel<INPUT, OUTPUT> invoke(@Nonnull final InvocationType type) { final Logger logger = mLogger; logger.dbg("invoking routine: %s", type); final Runner runner = (type == InvocationType.ASYNC) ? mAsyncRunner : mSyncRunner; return new DefaultInvocationChannel<INPUT, OUTPUT>(mConfiguration, getInvocationManager(type), runner, logger); } /** * Invocation type enumeration. */ protected enum InvocationType { ASYNC, // asynchronous SYNC // synchronous } /** * Implementation of an invocation handling parallel mode. * * @param <INPUT> the input data type. * @param <OUTPUT> the output data type. */ private static class ParallelInvocation<INPUT, OUTPUT> extends TemplateInvocation<INPUT, OUTPUT> { private final Routine<INPUT, OUTPUT> mRoutine; /** * Constructor. * * @param routine the routine to invoke in parallel mode. */ private ParallelInvocation(@Nonnull final Routine<INPUT, OUTPUT> routine) { mRoutine = routine; } @Override public void onInput(final INPUT input, @Nonnull final ResultChannel<OUTPUT> result) { result.pass(mRoutine.asyncCall(input)); } } /** * Default implementation of an invocation manager supporting recycling of invocation instances. */ private class DefaultInvocationManager implements InvocationManager<INPUT, OUTPUT> { private final LinkedList<Invocation<INPUT, OUTPUT>> mFallbackInvocations; private final InvocationType mInvocationType; private final LinkedList<Invocation<INPUT, OUTPUT>> mPrimaryInvocations; /** * Constructor. * * @param type the invocation type. * @param primaryInvocations the primary pool of invocations. * @param fallbackInvocations the fallback pool of invocations. */ private DefaultInvocationManager(@Nonnull final InvocationType type, @Nonnull final LinkedList<Invocation<INPUT, OUTPUT>> primaryInvocations, @Nonnull final LinkedList<Invocation<INPUT, OUTPUT>> fallbackInvocations) { mInvocationType = type; mPrimaryInvocations = primaryInvocations; mFallbackInvocations = fallbackInvocations; } @Nonnull public Invocation<INPUT, OUTPUT> create() { synchronized (mMutex) { final boolean isTimeout; try { isTimeout = !mAvailTimeout.waitTrue(mMutex, mIsInvocationAvailable); } catch (final InterruptedException e) { mLogger.err(e, "waiting for available instances interrupted [#%d]", mMaxInvocations); throw new InvocationInterruptedException(e); } if (isTimeout) { mLogger.wrn("routine instance not available after timeout [#%d]: %s", mMaxInvocations, mAvailTimeout); throw new InvocationTimeoutException( "timeout while waiting for an available invocation instance"); } final InvocationType invocationType = mInvocationType; final int coreInvocations = mCoreInvocations; final LinkedList<Invocation<INPUT, OUTPUT>> invocations = mPrimaryInvocations; final Invocation<INPUT, OUTPUT> invocation; if (!invocations.isEmpty()) { invocation = invocations.removeFirst(); mLogger.dbg("reusing %s invocation instance [%d/%d]: %s", invocationType, invocations.size() + 1, coreInvocations, invocation); } else { final LinkedList<Invocation<INPUT, OUTPUT>> fallbackInvocations = mFallbackInvocations; if (!fallbackInvocations.isEmpty()) { final Invocation<INPUT, OUTPUT> convertInvocation = fallbackInvocations.removeFirst(); mLogger.dbg("converting %s invocation instance [%d/%d]: %s", invocationType, invocations.size() + 1, coreInvocations, convertInvocation); invocation = convertInvocation(convertInvocation, invocationType); } else { mLogger.dbg("creating %s invocation instance [1/%d]", invocationType, coreInvocations); invocation = newInvocation(invocationType); } } if (invocation == null) { throw new NullPointerException("null invocation returned"); } ++mRunningCount; return invocation; } } @SuppressFBWarnings(value = "NO_NOTIFY_NOT_NOTIFYALL", justification = "only one invocation is released") public void discard(@Nonnull final Invocation<INPUT, OUTPUT> invocation) { synchronized (mMutex) { final Logger logger = mLogger; logger.wrn("discarding invocation instance after error: %s", invocation); try { invocation.onDestroy(); } catch (final InvocationInterruptedException e) { throw e; } catch (final Throwable ignored) { logger.wrn(ignored, "ignoring exception while destroying invocation instance"); } --mRunningCount; mMutex.notify(); } } @SuppressFBWarnings(value = "NO_NOTIFY_NOT_NOTIFYALL", justification = "only one invocation is released") public void recycle(@Nonnull final Invocation<INPUT, OUTPUT> invocation) { synchronized (mMutex) { final Logger logger = mLogger; final int coreInvocations = mCoreInvocations; final LinkedList<Invocation<INPUT, OUTPUT>> primaryInvocations = mPrimaryInvocations; final LinkedList<Invocation<INPUT, OUTPUT>> fallbackInvocations = mFallbackInvocations; if ((primaryInvocations.size() + fallbackInvocations.size()) < coreInvocations) { logger.dbg("recycling %s invocation instance [%d/%d]: %s", mInvocationType, primaryInvocations.size() + 1, coreInvocations, invocation); primaryInvocations.add(invocation); } else { logger.wrn("discarding %s invocation instance [%d/%d]: %s", mInvocationType, coreInvocations, coreInvocations, invocation); try { invocation.onDestroy(); } catch (final InvocationInterruptedException e) { throw e; } catch (final Throwable ignored) { logger.wrn(ignored, "ignoring exception while destroying invocation instance"); } } --mRunningCount; mMutex.notify(); } } } }
library/src/main/java/com/gh/bmd/jrt/core/AbstractRoutine.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gh.bmd.jrt.core; import com.gh.bmd.jrt.builder.InvocationConfiguration; import com.gh.bmd.jrt.channel.DeadlockException; import com.gh.bmd.jrt.channel.InvocationChannel; import com.gh.bmd.jrt.channel.ResultChannel; import com.gh.bmd.jrt.core.DefaultInvocationChannel.InvocationManager; import com.gh.bmd.jrt.invocation.Invocation; import com.gh.bmd.jrt.invocation.InvocationInterruptedException; import com.gh.bmd.jrt.invocation.InvocationTimeoutException; import com.gh.bmd.jrt.invocation.TemplateInvocation; import com.gh.bmd.jrt.log.Logger; import com.gh.bmd.jrt.routine.Routine; import com.gh.bmd.jrt.routine.TemplateRoutine; import com.gh.bmd.jrt.runner.Runner; import com.gh.bmd.jrt.runner.Runners; import com.gh.bmd.jrt.util.TimeDuration; import com.gh.bmd.jrt.util.TimeDuration.Check; import java.util.LinkedList; import javax.annotation.Nonnull; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import static com.gh.bmd.jrt.util.TimeDuration.ZERO; /** * Basic abstract implementation of a routine. * <p/> * This class provides a default implementation of all the routine features. The inheriting class * just needs to create invocation objects when required. * <p/> * Created by davide-maestroni on 9/7/14. * * @param <INPUT> the input data type. * @param <OUTPUT> the output data type. */ public abstract class AbstractRoutine<INPUT, OUTPUT> extends TemplateRoutine<INPUT, OUTPUT> { private static final TimeDuration DEFAULT_AVAIL_TIMEOUT = ZERO; private static final int DEFAULT_CORE_INVOCATIONS = 10; private static final int DEFAULT_MAX_INVOCATIONS = Integer.MAX_VALUE; private final LinkedList<Invocation<INPUT, OUTPUT>> mAsyncInvocations = new LinkedList<Invocation<INPUT, OUTPUT>>(); private final Runner mAsyncRunner; private final TimeDuration mAvailTimeout; private final InvocationConfiguration mConfiguration; private final int mCoreInvocations; private final Logger mLogger; private final int mMaxInvocations; private final Object mMutex = new Object(); private final Object mParallelMutex = new Object(); private final LinkedList<Invocation<INPUT, OUTPUT>> mSyncInvocations = new LinkedList<Invocation<INPUT, OUTPUT>>(); private final Runner mSyncRunner; private volatile DefaultInvocationManager mAsyncManager; private AbstractRoutine<INPUT, OUTPUT> mParallelRoutine; private int mRunningCount; private final Check mIsInvocationAvailable = new Check() { public boolean isTrue() { return mRunningCount < mMaxInvocations; } }; private volatile DefaultInvocationManager mSyncManager; /** * Constructor. * * @param configuration the invocation configuration. */ @SuppressWarnings("ConstantConditions") protected AbstractRoutine(@Nonnull final InvocationConfiguration configuration) { mConfiguration = configuration; mSyncRunner = configuration.getSyncRunnerOr(Runners.queuedRunner()); final int priority = configuration.getPriorityOr(InvocationConfiguration.DEFAULT); final Runner asyncRunner = configuration.getAsyncRunnerOr(Runners.sharedRunner()); if (priority != InvocationConfiguration.DEFAULT) { mAsyncRunner = Runners.priorityRunner(asyncRunner).getRunner(priority); } else { mAsyncRunner = asyncRunner; } mMaxInvocations = configuration.getMaxInstancesOr(DEFAULT_MAX_INVOCATIONS); mCoreInvocations = configuration.getCoreInstancesOr(DEFAULT_CORE_INVOCATIONS); mAvailTimeout = configuration.getAvailInstanceTimeoutOr(DEFAULT_AVAIL_TIMEOUT); mLogger = configuration.newLogger(this); mLogger.dbg("building routine with configuration: %s", configuration); } /** * Constructor. * * @param configuration the invocation configuration. * @param syncRunner the runner used for synchronous invocation. * @param asyncRunner the runner used for asynchronous invocation. * @param logger the logger instance. */ private AbstractRoutine(@Nonnull final InvocationConfiguration configuration, @Nonnull final Runner syncRunner, @Nonnull final Runner asyncRunner, @Nonnull final Logger logger) { mConfiguration = configuration; mSyncRunner = syncRunner; mAsyncRunner = asyncRunner; mMaxInvocations = DEFAULT_MAX_INVOCATIONS; mCoreInvocations = DEFAULT_CORE_INVOCATIONS; mAvailTimeout = DEFAULT_AVAIL_TIMEOUT; mLogger = logger.subContextLogger(this); } @Nonnull public InvocationChannel<INPUT, OUTPUT> asyncInvoke() { return invoke(InvocationType.ASYNC); } @Nonnull public InvocationChannel<INPUT, OUTPUT> parallelInvoke() { synchronized (mParallelMutex) { mLogger.dbg("invoking routine: parallel"); if (mParallelRoutine == null) { mParallelRoutine = new AbstractRoutine<INPUT, OUTPUT>(mConfiguration, mSyncRunner, mAsyncRunner, mLogger) { @Nonnull @Override protected Invocation<INPUT, OUTPUT> newInvocation( @Nonnull final InvocationType type) { return new ParallelInvocation<INPUT, OUTPUT>(AbstractRoutine.this); } }; } } return mParallelRoutine.asyncInvoke(); } @Nonnull public InvocationChannel<INPUT, OUTPUT> syncInvoke() { return invoke(InvocationType.SYNC); } @Override public void purge() { synchronized (mMutex) { final Logger logger = mLogger; final LinkedList<Invocation<INPUT, OUTPUT>> syncInvocations = mSyncInvocations; for (final Invocation<INPUT, OUTPUT> invocation : syncInvocations) { try { invocation.onDestroy(); } catch (final InvocationInterruptedException e) { throw e; } catch (final Throwable ignored) { logger.wrn(ignored, "ignoring exception while destroying invocation instance"); } } syncInvocations.clear(); final LinkedList<Invocation<INPUT, OUTPUT>> asyncInvocations = mAsyncInvocations; for (final Invocation<INPUT, OUTPUT> invocation : asyncInvocations) { try { invocation.onDestroy(); } catch (final InvocationInterruptedException e) { throw e; } catch (final Throwable ignored) { logger.wrn(ignored, "ignoring exception while destroying invocation instance"); } } asyncInvocations.clear(); } } /** * Converts an invocation instance to the specified type. * * @param invocation the invocation to convert. * @param type the converted invocation type. * @return the converted invocation. */ @Nonnull @SuppressWarnings("UnusedParameters") protected Invocation<INPUT, OUTPUT> convertInvocation( @Nonnull final Invocation<INPUT, OUTPUT> invocation, @Nonnull final InvocationType type) { return invocation; } /** * Returns the routine logger. * * @return the logger instance. */ @Nonnull protected Logger getLogger() { return mLogger; } /** * Creates a new invocation instance. * * @param type the invocation type. * @return the invocation instance. */ @Nonnull protected abstract Invocation<INPUT, OUTPUT> newInvocation(@Nonnull InvocationType type); @Nonnull private DefaultInvocationManager getInvocationManager(@Nonnull final InvocationType type) { if (type == InvocationType.ASYNC) { if (mAsyncManager == null) { mAsyncManager = new DefaultInvocationManager(type, mAsyncInvocations, mSyncInvocations); } return mAsyncManager; } if (mSyncManager == null) { mSyncManager = new DefaultInvocationManager(type, mSyncInvocations, mAsyncInvocations); } return mSyncManager; } @Nonnull private InvocationChannel<INPUT, OUTPUT> invoke(@Nonnull final InvocationType type) { final Logger logger = mLogger; logger.dbg("invoking routine: %s", type); final Runner runner = (type == InvocationType.ASYNC) ? mAsyncRunner : mSyncRunner; return new DefaultInvocationChannel<INPUT, OUTPUT>(mConfiguration, getInvocationManager(type), runner, logger); } /** * Invocation type enumeration. */ protected enum InvocationType { ASYNC, // asynchronous SYNC // synchronous } /** * Implementation of an invocation handling parallel mode. * * @param <INPUT> the input data type. * @param <OUTPUT> the output data type. */ private static class ParallelInvocation<INPUT, OUTPUT> extends TemplateInvocation<INPUT, OUTPUT> { private final Routine<INPUT, OUTPUT> mRoutine; /** * Constructor. * * @param routine the routine to invoke in parallel mode. */ private ParallelInvocation(@Nonnull final Routine<INPUT, OUTPUT> routine) { mRoutine = routine; } @Override public void onInput(final INPUT input, @Nonnull final ResultChannel<OUTPUT> result) { result.pass(mRoutine.asyncCall(input)); } } /** * Default implementation of an invocation manager supporting recycling of invocation instances. */ private class DefaultInvocationManager implements InvocationManager<INPUT, OUTPUT> { private final LinkedList<Invocation<INPUT, OUTPUT>> mFallbackInvocations; private final InvocationType mInvocationType; private final LinkedList<Invocation<INPUT, OUTPUT>> mPrimaryInvocations; /** * Constructor. * * @param type the invocation type. * @param primaryInvocations the primary pool of invocations. * @param fallbackInvocations the fallback pool of invocations. */ private DefaultInvocationManager(@Nonnull final InvocationType type, @Nonnull final LinkedList<Invocation<INPUT, OUTPUT>> primaryInvocations, @Nonnull final LinkedList<Invocation<INPUT, OUTPUT>> fallbackInvocations) { mInvocationType = type; mPrimaryInvocations = primaryInvocations; mFallbackInvocations = fallbackInvocations; } @Nonnull public Invocation<INPUT, OUTPUT> create() { synchronized (mMutex) { final Check isInvocationAvailable = mIsInvocationAvailable; if (!isInvocationAvailable.isTrue()) { final TimeDuration availTimeout = mAvailTimeout; if ((mInvocationType == InvocationType.ASYNC) && !availTimeout.isZero() && mAsyncRunner.isExecutionThread()) { throw new DeadlockException("cannot wait on the invocation runner thread"); } final boolean isTimeout; try { isTimeout = !availTimeout.waitTrue(mMutex, isInvocationAvailable); } catch (final InterruptedException e) { mLogger.err(e, "waiting for available instances interrupted [#%d]", mMaxInvocations); throw new InvocationInterruptedException(e); } if (isTimeout) { mLogger.wrn("routine instance not available after timeout [#%d]: %s", mMaxInvocations, availTimeout); throw new InvocationTimeoutException( "timeout while waiting for an available invocation instance"); } } final InvocationType invocationType = mInvocationType; final int coreInvocations = mCoreInvocations; final LinkedList<Invocation<INPUT, OUTPUT>> invocations = mPrimaryInvocations; final Invocation<INPUT, OUTPUT> invocation; if (!invocations.isEmpty()) { invocation = invocations.removeFirst(); mLogger.dbg("reusing %s invocation instance [%d/%d]: %s", invocationType, invocations.size() + 1, coreInvocations, invocation); } else { final LinkedList<Invocation<INPUT, OUTPUT>> fallbackInvocations = mFallbackInvocations; if (!fallbackInvocations.isEmpty()) { final Invocation<INPUT, OUTPUT> convertInvocation = fallbackInvocations.removeFirst(); mLogger.dbg("converting %s invocation instance [%d/%d]: %s", invocationType, invocations.size() + 1, coreInvocations, convertInvocation); invocation = convertInvocation(convertInvocation, invocationType); } else { mLogger.dbg("creating %s invocation instance [1/%d]", invocationType, coreInvocations); invocation = newInvocation(invocationType); } } if (invocation == null) { throw new NullPointerException("null invocation returned"); } ++mRunningCount; return invocation; } } @SuppressFBWarnings(value = "NO_NOTIFY_NOT_NOTIFYALL", justification = "only one invocation is released") public void discard(@Nonnull final Invocation<INPUT, OUTPUT> invocation) { synchronized (mMutex) { final Logger logger = mLogger; logger.wrn("discarding invocation instance after error: %s", invocation); try { invocation.onDestroy(); } catch (final InvocationInterruptedException e) { throw e; } catch (final Throwable ignored) { logger.wrn(ignored, "ignoring exception while destroying invocation instance"); } --mRunningCount; mMutex.notify(); } } @SuppressFBWarnings(value = "NO_NOTIFY_NOT_NOTIFYALL", justification = "only one invocation is released") public void recycle(@Nonnull final Invocation<INPUT, OUTPUT> invocation) { synchronized (mMutex) { final Logger logger = mLogger; final int coreInvocations = mCoreInvocations; final LinkedList<Invocation<INPUT, OUTPUT>> primaryInvocations = mPrimaryInvocations; final LinkedList<Invocation<INPUT, OUTPUT>> fallbackInvocations = mFallbackInvocations; if ((primaryInvocations.size() + fallbackInvocations.size()) < coreInvocations) { logger.dbg("recycling %s invocation instance [%d/%d]: %s", mInvocationType, primaryInvocations.size() + 1, coreInvocations, invocation); primaryInvocations.add(invocation); } else { logger.wrn("discarding %s invocation instance [%d/%d]: %s", mInvocationType, coreInvocations, coreInvocations, invocation); try { invocation.onDestroy(); } catch (final InvocationInterruptedException e) { throw e; } catch (final Throwable ignored) { logger.wrn(ignored, "ignoring exception while destroying invocation instance"); } } --mRunningCount; mMutex.notify(); } } } }
Reverted commit
library/src/main/java/com/gh/bmd/jrt/core/AbstractRoutine.java
Reverted commit
<ide><path>ibrary/src/main/java/com/gh/bmd/jrt/core/AbstractRoutine.java <ide> package com.gh.bmd.jrt.core; <ide> <ide> import com.gh.bmd.jrt.builder.InvocationConfiguration; <del>import com.gh.bmd.jrt.channel.DeadlockException; <ide> import com.gh.bmd.jrt.channel.InvocationChannel; <ide> import com.gh.bmd.jrt.channel.ResultChannel; <ide> import com.gh.bmd.jrt.core.DefaultInvocationChannel.InvocationManager; <ide> <ide> synchronized (mMutex) { <ide> <del> final Check isInvocationAvailable = mIsInvocationAvailable; <del> <del> if (!isInvocationAvailable.isTrue()) { <del> <del> final TimeDuration availTimeout = mAvailTimeout; <del> <del> if ((mInvocationType == InvocationType.ASYNC) && !availTimeout.isZero() <del> && mAsyncRunner.isExecutionThread()) { <del> <del> throw new DeadlockException("cannot wait on the invocation runner thread"); <del> } <del> <del> final boolean isTimeout; <del> <del> try { <del> <del> isTimeout = !availTimeout.waitTrue(mMutex, isInvocationAvailable); <del> <del> } catch (final InterruptedException e) { <del> <del> mLogger.err(e, "waiting for available instances interrupted [#%d]", <del> mMaxInvocations); <del> throw new InvocationInterruptedException(e); <del> } <del> <del> if (isTimeout) { <del> <del> mLogger.wrn("routine instance not available after timeout [#%d]: %s", <del> mMaxInvocations, availTimeout); <del> throw new InvocationTimeoutException( <del> "timeout while waiting for an available invocation instance"); <del> } <add> final boolean isTimeout; <add> <add> try { <add> <add> isTimeout = !mAvailTimeout.waitTrue(mMutex, mIsInvocationAvailable); <add> <add> } catch (final InterruptedException e) { <add> <add> mLogger.err(e, "waiting for available instances interrupted [#%d]", <add> mMaxInvocations); <add> throw new InvocationInterruptedException(e); <add> } <add> <add> if (isTimeout) { <add> <add> mLogger.wrn("routine instance not available after timeout [#%d]: %s", <add> mMaxInvocations, mAvailTimeout); <add> throw new InvocationTimeoutException( <add> "timeout while waiting for an available invocation instance"); <ide> } <ide> <ide> final InvocationType invocationType = mInvocationType;
Java
bsd-2-clause
dd409aeb0b1d481eb7c8d22a6aa2392051af0206
0
edgehosting/jira-dvcs-connector,edgehosting/jira-dvcs-connector,edgehosting/jira-dvcs-connector,markphip/testing,markphip/testing,markphip/testing
package it.restart.com.atlassian.jira.plugins.dvcs; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import org.hamcrest.Matcher; import org.openqa.selenium.By; import com.atlassian.jira.plugins.dvcs.util.PageElementUtils; import com.atlassian.pageobjects.Page; import com.atlassian.pageobjects.PageBinder; import com.atlassian.pageobjects.elements.ElementBy; import com.atlassian.pageobjects.elements.PageElement; import com.atlassian.pageobjects.elements.PageElementFinder; import com.atlassian.pageobjects.elements.SelectElement; import com.atlassian.pageobjects.elements.query.Poller; /** * Represents the page to link repositories to projects */ public class RepositoriesPage implements Page { @Inject private PageBinder pageBinder; @Inject private PageElementFinder elementFinder; @ElementBy(id = "aui-message-bar") private PageElement messageBarDiv; @ElementBy(id = "organization-list") private PageElement organizationsElement; @ElementBy(id = "repoEntry") private PageElement repoEntry; @ElementBy(id = "urlSelect") private SelectElement dvcsTypeSelect; @ElementBy(id = "organization") private PageElement organization; @ElementBy(id = "autoLinking") private PageElement autoLinkNewRepos; @ElementBy(id = "linkRepositoryButton") private PageElement linkRepositoryButton; @ElementBy(className = "button-panel-submit-button") private PageElement addOrgButton; // @ElementBy(className = "gh_messages") // private PageElement syncStatusDiv; @Override public String getUrl() { return "/secure/admin/ConfigureDvcsOrganizations!default.jspa"; } public void addOrganisation(int accountType, String accountName, boolean autoSync) { linkRepositoryButton.click(); waitFormBecomeVisible(); dvcsTypeSelect.select(dvcsTypeSelect.getAllOptions().get(accountType)); organization.clear().type(accountName); if (!autoSync) { autoLinkNewRepos.click(); } addOrgButton.click(); } public OrganizationDiv getOrganization(String repositoryType, String repositoryName) { List<OrganizationDiv> organizations = getOrganizations(); for (OrganizationDiv organizationDiv : organizations) { if (repositoryType.equals(organizationDiv.getRepositoryType()) && repositoryName.equals(organizationDiv.getRepositoryName())) { return organizationDiv; } } return null; } public List<OrganizationDiv> getOrganizations() { List<OrganizationDiv> list = new ArrayList<OrganizationDiv>(); for (PageElement orgContainer : organizationsElement.findAll(By.className("dvcs-orgdata-container"))) { Poller.waitUntilTrue(orgContainer.find(By.className("dvcs-org-container")).timed().isVisible()); list.add(pageBinder.bind(OrganizationDiv.class, orgContainer)); } return list; } public void deleteAllOrganizations() { List<OrganizationDiv> orgs; while (!(orgs = getOrganizations()).isEmpty()) { orgs.get(0).delete(); } } public void assertThatErrorMessage(Matcher<String> matcher) { Poller.waitUntil(messageBarDiv.find(By.className("error")).timed().getText(), matcher); } protected void waitFormBecomeVisible() { Poller.waitUntilTrue("Expected add repository form to be visible", repoEntry.timed().isVisible()); } /** * The current error status message * @return error status message */ public String getErrorStatusMessage() { return messageBarDiv.find(By.className("error")).timed().getText().by(1000l); } public boolean containsRepositoryWithName(String askedRepositoryName) { // parsing following HTML: // <td class="dvcs-org-reponame"> // <a href="...">browsermob-proxy</a> // </td> for (PageElement repositoryNameTableRow : elementFinder.findAll(By.className("dvcs-org-reponame"))) { String repositoryName = repositoryNameTableRow.find(By.tagName("a")).getText(); if (repositoryName.equals(askedRepositoryName)) { return true; } } return false; } public String getRepositoryIdFromRepositoryName(String queriedRepositoryName) { for (PageElement repositoryRow : elementFinder.findAll(By.className("dvcs-repo-row"))) { String repositoryName = repositoryRow.find(By.className("dvcs-org-reponame")).find(By.tagName("a")).getText(); if (repositoryName.equals(queriedRepositoryName)) { PageElement syncRepoLink = PageElementUtils.findTagWithAttribute(repositoryRow, "a", "onclick"); String onclickAttributeValue = syncRepoLink.getAttribute("onclick"); // parsing: // onclick="forceSync(90); AJS.$('.gh_messages.repository90').slideDown(); return false;" int openBraceIndex = onclickAttributeValue.indexOf('('); int closeBraceIndex = onclickAttributeValue.indexOf(')'); return onclickAttributeValue.substring(openBraceIndex + 1, closeBraceIndex); } } return null; } public int getRepositoriesCount(int organisationIndex) { return getOrganizations().get(organisationIndex).getRepositories().size(); } }
jira-dvcs-connector-plugin/src/test/java/it/restart/com/atlassian/jira/plugins/dvcs/RepositoriesPage.java
package it.restart.com.atlassian.jira.plugins.dvcs; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import org.hamcrest.Matcher; import org.openqa.selenium.By; import com.atlassian.jira.plugins.dvcs.util.PageElementUtils; import com.atlassian.pageobjects.Page; import com.atlassian.pageobjects.PageBinder; import com.atlassian.pageobjects.elements.ElementBy; import com.atlassian.pageobjects.elements.PageElement; import com.atlassian.pageobjects.elements.PageElementFinder; import com.atlassian.pageobjects.elements.SelectElement; import com.atlassian.pageobjects.elements.query.Poller; /** * Represents the page to link repositories to projects */ public class RepositoriesPage implements Page { @Inject private PageBinder pageBinder; @Inject private PageElementFinder elementFinder; @ElementBy(id = "aui-message-bar") private PageElement messageBarDiv; @ElementBy(id = "organization-list") private PageElement organizationsElement; @ElementBy(id = "repoEntry") private PageElement repoEntry; @ElementBy(id = "urlSelect") private SelectElement dvcsTypeSelect; @ElementBy(id = "organization") private PageElement organization; @ElementBy(id = "autoLinking") private PageElement autoLinkNewRepos; @ElementBy(id = "linkRepositoryButton") private PageElement linkRepositoryButton; @ElementBy(id = "Submit") private PageElement addOrgButton; // @ElementBy(className = "gh_messages") // private PageElement syncStatusDiv; @Override public String getUrl() { return "/secure/admin/ConfigureDvcsOrganizations!default.jspa"; } public void addOrganisation(int accountType, String accountName, boolean autoSync) { linkRepositoryButton.click(); waitFormBecomeVisible(); dvcsTypeSelect.select(dvcsTypeSelect.getAllOptions().get(accountType)); organization.clear().type(accountName); if (!autoSync) { autoLinkNewRepos.click(); } addOrgButton.click(); } public OrganizationDiv getOrganization(String repositoryType, String repositoryName) { List<OrganizationDiv> organizations = getOrganizations(); for (OrganizationDiv organizationDiv : organizations) { if (repositoryType.equals(organizationDiv.getRepositoryType()) && repositoryName.equals(organizationDiv.getRepositoryName())) { return organizationDiv; } } return null; } public List<OrganizationDiv> getOrganizations() { List<OrganizationDiv> list = new ArrayList<OrganizationDiv>(); for (PageElement orgContainer : organizationsElement.findAll(By.className("dvcs-orgdata-container"))) { Poller.waitUntilTrue(orgContainer.find(By.className("dvcs-org-container")).timed().isVisible()); list.add(pageBinder.bind(OrganizationDiv.class, orgContainer)); } return list; } public void deleteAllOrganizations() { List<OrganizationDiv> orgs; while (!(orgs = getOrganizations()).isEmpty()) { orgs.get(0).delete(); } } public void assertThatErrorMessage(Matcher<String> matcher) { Poller.waitUntil(messageBarDiv.find(By.className("error")).timed().getText(), matcher); } protected void waitFormBecomeVisible() { Poller.waitUntilTrue("Expected add repository form to be visible", repoEntry.timed().isVisible()); } /** * The current error status message * @return error status message */ public String getErrorStatusMessage() { return messageBarDiv.find(By.className("error")).timed().getText().by(1000l); } public boolean containsRepositoryWithName(String askedRepositoryName) { // parsing following HTML: // <td class="dvcs-org-reponame"> // <a href="...">browsermob-proxy</a> // </td> for (PageElement repositoryNameTableRow : elementFinder.findAll(By.className("dvcs-org-reponame"))) { String repositoryName = repositoryNameTableRow.find(By.tagName("a")).getText(); if (repositoryName.equals(askedRepositoryName)) { return true; } } return false; } public String getRepositoryIdFromRepositoryName(String queriedRepositoryName) { for (PageElement repositoryRow : elementFinder.findAll(By.className("dvcs-repo-row"))) { String repositoryName = repositoryRow.find(By.className("dvcs-org-reponame")).find(By.tagName("a")).getText(); if (repositoryName.equals(queriedRepositoryName)) { PageElement syncRepoLink = PageElementUtils.findTagWithAttribute(repositoryRow, "a", "onclick"); String onclickAttributeValue = syncRepoLink.getAttribute("onclick"); // parsing: // onclick="forceSync(90); AJS.$('.gh_messages.repository90').slideDown(); return false;" int openBraceIndex = onclickAttributeValue.indexOf('('); int closeBraceIndex = onclickAttributeValue.indexOf(')'); return onclickAttributeValue.substring(openBraceIndex + 1, closeBraceIndex); } } return null; } public int getRepositoriesCount(int organisationIndex) { return getOrganizations().get(organisationIndex).getRepositories().size(); } }
BBC-472 Fixing Bitbucket Organization and Github Organization integration tests
jira-dvcs-connector-plugin/src/test/java/it/restart/com/atlassian/jira/plugins/dvcs/RepositoriesPage.java
BBC-472 Fixing Bitbucket Organization and Github Organization integration tests
<ide><path>ira-dvcs-connector-plugin/src/test/java/it/restart/com/atlassian/jira/plugins/dvcs/RepositoriesPage.java <ide> @ElementBy(id = "linkRepositoryButton") <ide> private PageElement linkRepositoryButton; <ide> <del> @ElementBy(id = "Submit") <add> @ElementBy(className = "button-panel-submit-button") <ide> private PageElement addOrgButton; <ide> <ide> // @ElementBy(className = "gh_messages")
Java
apache-2.0
64c40f61d12cccb678c74797c2a70d5d2b56fd62
0
b2ihealthcare/snow-owl,IHTSDO/snow-owl,IHTSDO/snow-owl,IHTSDO/snow-owl,b2ihealthcare/snow-owl,b2ihealthcare/snow-owl,IHTSDO/snow-owl,b2ihealthcare/snow-owl
/* * Copyright 2011-2015 B2i Healthcare Pte Ltd, http://b2i.sg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.b2international.snowowl.datastore.server.index; import java.util.Collection; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.emf.cdo.CDOObject; import org.eclipse.emf.ecore.EObject; import org.slf4j.Logger; import com.b2international.commons.CancelableProgressMonitorWrapper; import com.b2international.commons.LogProgressMonitorWrapper; import com.b2international.snowowl.core.api.IBranchPath; import com.b2international.snowowl.core.api.SnowowlServiceException; import com.b2international.snowowl.core.api.index.IIndexEntry; import com.b2international.snowowl.core.api.index.IIndexMappingStrategy; import com.b2international.snowowl.core.api.index.IIndexUpdater; import com.b2international.snowowl.datastore.BranchPathUtils; import com.b2international.snowowl.datastore.CDOEditingContext; import com.google.common.collect.Iterables; /** * {@link AbstractReIndexJob} to reIndex element on terminologies. * * @param T * - the persisted {@link CDOObject} element type for the terminology * @param E * - the {@link IIndexEntry} type for the terminology * @since 2.7 */ public abstract class AbstractReIndexJob<T extends CDOObject, E extends IIndexEntry> extends Job { private IBranchPath branchPath = BranchPathUtils.createMainPath(); public AbstractReIndexJob(final String name) { super(name); } @Override protected IStatus run(final IProgressMonitor monitor) { try { return reIndex(createSubMonitor(monitor, getLogger())); } catch (final OperationCanceledException e) { return Status.CANCEL_STATUS; } catch (final SnowowlServiceException e) { return new Status(Status.ERROR, getPluginId(), String.format("Caught exception while reIndexing %s", getIndexName()), e); } finally { monitor.done(); } } /** * Returns the {@link IBranchPath}. * * @return */ public IBranchPath getBranchPath() { return branchPath; } protected abstract String getIndexName(); protected abstract String getPluginId(); protected abstract Logger getLogger(); /** * Do the reindex job within this method. * * @param monitor * @return * @throws SnowowlServiceException */ protected IStatus reIndex(final SubMonitor monitor) throws SnowowlServiceException { CDOEditingContext context = null; try { context = createEditingContext(); doReIndex(context, getIndexUpdater(), monitor); } finally { if (context != null) { context.close(); } } // create editing context return Status.OK_STATUS; } protected void doReIndex(final CDOEditingContext context, final IIndexUpdater<E> indexUpdater, final SubMonitor monitor) { cleanIndex(context, indexUpdater, monitor.newChild(15)); reIndex(context, indexUpdater, monitor.newChild(80)); postProcess(indexUpdater, monitor.newChild(5)); } protected void reIndex(final CDOEditingContext context, final IIndexUpdater<E> indexUpdater, final SubMonitor monitor) { monitor.setWorkRemaining(getTargetClasses().length); for (final Class<? extends T> targetClass : getTargetClasses()) { reIndex(context, indexUpdater, targetClass, monitor.newChild(1)); } } protected abstract Class<? extends T>[] getTargetClasses(); /** * Reindexes each desired target component in the containment list of the given {@link CDOEditingContext}'s * rootResource by using the given {@link IIndexUpdater} with {@link #getMappingStrategy(CDOObject)}. * * @param context * @param indexUpdater * @param monitor */ protected void reIndex(final CDOEditingContext context, final IIndexUpdater<E> indexUpdater, final Class<? extends T> targetClass, final SubMonitor monitor) { final Collection<EObject> contents = context.getContents(); final int size = contents.size(); monitor.setWorkRemaining(size + 5); for (final T component : Iterables.filter(contents, targetClass)) { reIndex(component, indexUpdater); monitor.worked(1); } monitor.done(); } protected void reIndex(final T component, final IIndexUpdater<E> indexUpdater) { indexUpdater.index(branchPath, getMappingStrategy(component)); } /** * Executes post process steps at the end of the reIndex task. * * @param indexUpdater * @param monitor */ protected void postProcess(final IIndexUpdater<E> indexUpdater, final SubMonitor monitor) { monitor.setWorkRemaining(1); indexUpdater.commit(branchPath); monitor.done(); } /** * Cleans the actual index content using the given {@link IIndexUpdater}. * * @param context * @param indexUpdater * @param monitor */ protected void cleanIndex(final CDOEditingContext context, final IIndexUpdater<E> indexUpdater, final SubMonitor monitor) { monitor.setWorkRemaining(3); monitor.worked(1); monitor.worked(1); indexUpdater.deleteAll(branchPath); monitor.done(); } /** * Create new EditingContext based on which terminology you want to reIndex. * * @return * @throws SnowowlServiceException */ protected abstract CDOEditingContext createEditingContext() throws SnowowlServiceException; /** * Returns the {@link IIndexUpdater} implementation for this {@link AbstractReIndexJob}. * * @return */ protected abstract IIndexUpdater<E> getIndexUpdater(); /** * Returns an {@link IIndexMappingStrategy} for the given component. * * @return */ protected abstract IIndexMappingStrategy getMappingStrategy(T component); /** * Converts the given monitor to log progress into the given {@link Logger} instance. * * @param monitor * @return */ private SubMonitor createSubMonitor(final IProgressMonitor monitor, final Logger logger) { final IProgressMonitor loggingMonitor = new LogProgressMonitorWrapper(monitor, logger); final IProgressMonitor cancelableMonitor = new CancelableProgressMonitorWrapper(loggingMonitor); final SubMonitor subMonitor = SubMonitor.convert(cancelableMonitor, getName(), 100); return subMonitor; } }
core/com.b2international.snowowl.datastore.server/src/com/b2international/snowowl/datastore/server/index/AbstractReIndexJob.java
/* * Copyright 2011-2015 B2i Healthcare Pte Ltd, http://b2i.sg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.b2international.snowowl.datastore.server.index; import java.util.Collection; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.emf.cdo.CDOObject; import org.eclipse.emf.ecore.EObject; import org.slf4j.Logger; import com.b2international.commons.CancelableProgressMonitorWrapper; import com.b2international.commons.LogProgressMonitorWrapper; import com.b2international.snowowl.core.api.IBranchPath; import com.b2international.snowowl.core.api.SnowowlServiceException; import com.b2international.snowowl.core.api.index.IIndexEntry; import com.b2international.snowowl.core.api.index.IIndexMappingStrategy; import com.b2international.snowowl.core.api.index.IIndexUpdater; import com.b2international.snowowl.datastore.BranchPathUtils; import com.b2international.snowowl.datastore.CDOEditingContext; import com.google.common.collect.Iterables; /** * {@link AbstractReIndexJob} to reIndex element on terminologies. * * @param T * - the persisted {@link CDOObject} element type for the terminology * @param E * - the {@link IIndexEntry} type for the terminology * @since 2.7 */ public abstract class AbstractReIndexJob<T extends CDOObject, E extends IIndexEntry> extends Job { private IBranchPath branchPath = BranchPathUtils.createMainPath(); public AbstractReIndexJob(final String name) { super(name); } @Override protected IStatus run(final IProgressMonitor monitor) { try { return reIndex(createSubMonitor(monitor, getLogger())); } catch (final OperationCanceledException e) { return Status.CANCEL_STATUS; } catch (final SnowowlServiceException e) { return new Status(Status.ERROR, getPluginId(), String.format("Caught exception while reIndexing %s", getIndexName()), e); } finally { monitor.done(); } } /** * Returns the {@link IBranchPath}. * * @return */ public IBranchPath getBranchPath() { return branchPath; } protected abstract String getIndexName(); protected abstract String getPluginId(); protected abstract Logger getLogger(); /** * Do the reindex job within this method. * * @param monitor * @return * @throws SnowowlServiceException */ protected IStatus reIndex(final SubMonitor monitor) throws SnowowlServiceException { CDOEditingContext context = null; try { context = createEditingContext(); doReIndex(context, getIndexUpdater(), monitor); } finally { if (context != null) { context.close(); } } // create editing context return Status.OK_STATUS; } protected void doReIndex(final CDOEditingContext context, final IIndexUpdater<E> indexUpdater, final SubMonitor monitor) { cleanIndex(context, indexUpdater, monitor.newChild(15)); reIndex(context, indexUpdater, monitor.newChild(80)); postProcess(indexUpdater, monitor.newChild(5)); } protected void reIndex(final CDOEditingContext context, final IIndexUpdater<E> indexUpdater, final SubMonitor monitor) { monitor.setWorkRemaining(getTargetClasses().length); for (final Class<? extends T> targetClass : getTargetClasses()) { reIndex(context, indexUpdater, targetClass, monitor.newChild(1)); } } protected abstract Class<? extends T>[] getTargetClasses(); /** * Reindexes each desired target component in the containment list of the given {@link CDOEditingContext}'s * rootResource by using the given {@link IIndexUpdater} with {@link #getMappingStrategy(CDOObject)}. * * @param context * @param indexUpdater * @param monitor */ protected void reIndex(final CDOEditingContext context, final IIndexUpdater<E> indexUpdater, final Class<? extends T> targetClass, final SubMonitor monitor) { final Collection<EObject> contents = context.getContents(); final int size = contents.size(); monitor.setWorkRemaining(size + 5); for (final T component : Iterables.filter(contents, targetClass)) { indexUpdater.index(branchPath, getMappingStrategy(component)); monitor.worked(1); } monitor.done(); } /** * Executes post process steps at the end of the reIndex task. * * @param indexUpdater * @param monitor */ protected void postProcess(final IIndexUpdater<E> indexUpdater, final SubMonitor monitor) { monitor.setWorkRemaining(1); indexUpdater.commit(branchPath); monitor.done(); } /** * Cleans the actual index content using the given {@link IIndexUpdater}. * * @param context * @param indexUpdater * @param monitor */ protected void cleanIndex(final CDOEditingContext context, final IIndexUpdater<E> indexUpdater, final SubMonitor monitor) { monitor.setWorkRemaining(3); monitor.worked(1); monitor.worked(1); indexUpdater.deleteAll(branchPath); monitor.done(); } /** * Create new EditingContext based on which terminology you want to reIndex. * * @return * @throws SnowowlServiceException */ protected abstract CDOEditingContext createEditingContext() throws SnowowlServiceException; /** * Returns the {@link IIndexUpdater} implementation for this {@link AbstractReIndexJob}. * * @return */ protected abstract IIndexUpdater<E> getIndexUpdater(); /** * Returns an {@link IIndexMappingStrategy} for the given component. * * @return */ protected abstract IIndexMappingStrategy getMappingStrategy(T component); /** * Converts the given monitor to log progress into the given {@link Logger} instance. * * @param monitor * @return */ private SubMonitor createSubMonitor(final IProgressMonitor monitor, final Logger logger) { final IProgressMonitor loggingMonitor = new LogProgressMonitorWrapper(monitor, logger); final IProgressMonitor cancelableMonitor = new CancelableProgressMonitorWrapper(loggingMonitor); final SubMonitor subMonitor = SubMonitor.convert(cancelableMonitor, getName(), 100); return subMonitor; } }
[core] extracted component based reIndex method
core/com.b2international.snowowl.datastore.server/src/com/b2international/snowowl/datastore/server/index/AbstractReIndexJob.java
[core] extracted component based reIndex method
<ide><path>ore/com.b2international.snowowl.datastore.server/src/com/b2international/snowowl/datastore/server/index/AbstractReIndexJob.java <ide> final int size = contents.size(); <ide> monitor.setWorkRemaining(size + 5); <ide> for (final T component : Iterables.filter(contents, targetClass)) { <del> indexUpdater.index(branchPath, getMappingStrategy(component)); <add> reIndex(component, indexUpdater); <ide> monitor.worked(1); <ide> } <ide> monitor.done(); <add> } <add> <add> protected void reIndex(final T component, final IIndexUpdater<E> indexUpdater) { <add> indexUpdater.index(branchPath, getMappingStrategy(component)); <ide> } <ide> <ide> /**
Java
mit
0b4ace26ce492969147f694ad72b374ec2e35b43
0
nls-oskari/oskari-server,nls-oskari/oskari-server,nls-oskari/oskari-server
package fi.nls.oskari; import fi.nls.oskari.control.*; import fi.nls.oskari.log.LogFactory; import fi.nls.oskari.log.Logger; import fi.nls.oskari.spring.extension.OskariParam; import fi.nls.oskari.util.ResponseHelper; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletResponse; /** * Handles ajax routing to Oskari Action handlers */ @Controller public class AjaxController { private final static Logger log = LogFactory.getLogger(AjaxController.class); @RequestMapping("/action") @ResponseBody public void handleAction(@OskariParam ActionParameters params, @RequestParam("action_route") String route) { // ActionHandlers write the response internally. // ResponseBody with void return type is needed so Spring doesn't try to show a view/JSP. if(!ActionControl.hasAction(route)) { ResponseHelper.writeError(params, "No such route registered: " + route, HttpServletResponse.SC_NOT_IMPLEMENTED); return; } try { ActionControl.routeAction(route, params); // TODO: HANDLE THE EXCEPTION, LOG USER AGENT ETC. on exceptions } catch (ActionParamsException e) { // For cases where we dont want a stack trace log.error("Couldn't handle action:", route, ". Message: ", e.getMessage(), ". Parameters: ", params.getRequest().getParameterMap()); ResponseHelper.writeError(params, e.getMessage(), HttpServletResponse.SC_NOT_IMPLEMENTED, e.getOptions()); } catch (ActionDeniedException e) { // User tried to execute action he/she is not authorized to execute or session had expired if(params.getUser().isGuest()) { log.error("Action was denied:", route, ", Error msg:", e.getMessage(), ". Parameters: ", params.getRequest().getParameterMap()); } else { log.error("Action was denied:", route, ", Error msg:", e.getMessage(), ". User: ", params.getUser(), ". Parameters: ", params.getRequest().getParameterMap()); } ResponseHelper.writeError(params, e.getMessage(), HttpServletResponse.SC_FORBIDDEN, e.getOptions()); } catch (ActionException e) { // Internal failure -> print stack trace log.error(e, "Couldn't handle action:", route, ". Parameters: ", params.getRequest().getParameterMap()); ResponseHelper.writeError(params, e.getMessage()); } } }
servlet-map/src/main/java/fi/nls/oskari/AjaxController.java
package fi.nls.oskari; import fi.nls.oskari.control.*; import fi.nls.oskari.log.LogFactory; import fi.nls.oskari.log.Logger; import fi.nls.oskari.spring.extension.OskariParam; import fi.nls.oskari.util.ResponseHelper; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletResponse; /** * Handles ajax routing to Oskari Action handlers */ @Controller public class AjaxController { private final static Logger log = LogFactory.getLogger(AjaxController.class); @RequestMapping("/action") @ResponseBody public void getMap(@OskariParam ActionParameters params, @RequestParam("action_route") String route) { // ActionHandlers write the response internally. // ResponseBody with void return type is needed so Spring doesn't try to show a view/JSP. if(!ActionControl.hasAction(route)) { ResponseHelper.writeError(params, "No such route registered: " + route, HttpServletResponse.SC_NOT_IMPLEMENTED); return; } try { ActionControl.routeAction(route, params); // TODO: HANDLE THE EXCEPTION, LOG USER AGENT ETC. on exceptions } catch (ActionParamsException e) { // For cases where we dont want a stack trace log.error("Couldn't handle action:", route, ". Message: ", e.getMessage(), ". Parameters: ", params.getRequest().getParameterMap()); ResponseHelper.writeError(params, e.getMessage(), HttpServletResponse.SC_NOT_IMPLEMENTED, e.getOptions()); } catch (ActionDeniedException e) { // User tried to execute action he/she is not authorized to execute or session had expired if(params.getUser().isGuest()) { log.error("Action was denied:", route, ", Error msg:", e.getMessage(), ". Parameters: ", params.getRequest().getParameterMap()); } else { log.error("Action was denied:", route, ", Error msg:", e.getMessage(), ". User: ", params.getUser(), ". Parameters: ", params.getRequest().getParameterMap()); } ResponseHelper.writeError(params, e.getMessage(), HttpServletResponse.SC_FORBIDDEN, e.getOptions()); } catch (ActionException e) { // Internal failure -> print stack trace log.error(e, "Couldn't handle action:", route, ". Parameters: ", params.getRequest().getParameterMap()); ResponseHelper.writeError(params, e.getMessage()); } } }
Changed request handling method name in AjaxController
servlet-map/src/main/java/fi/nls/oskari/AjaxController.java
Changed request handling method name in AjaxController
<ide><path>ervlet-map/src/main/java/fi/nls/oskari/AjaxController.java <ide> <ide> @RequestMapping("/action") <ide> @ResponseBody <del> public void getMap(@OskariParam ActionParameters params, @RequestParam("action_route") String route) { <add> public void handleAction(@OskariParam ActionParameters params, @RequestParam("action_route") String route) { <ide> // ActionHandlers write the response internally. <ide> // ResponseBody with void return type is needed so Spring doesn't try to show a view/JSP. <ide>