text
stringlengths 30
1.67M
|
|---|
<s> package com . mapr . stats ; import org . uncommons . maths . random . MersenneTwisterRNG ; import java . util . Random ; public class BetaBayesModel extends BayesianBandit { public BetaBayesModel ( ) { this ( <NUM_LIT:2> , new MersenneTwisterRNG ( ) ) ; } public BetaBayesModel ( int bandits , Random gen ) { for ( int i = <NUM_LIT:0> ; i < bandits ; i ++ ) { addModelDistribution ( new BetaBinomialDistribution ( <NUM_LIT:1> , <NUM_LIT:1> , gen ) ) ; } } } </s>
|
<s> package com . mapr . stats ; import org . uncommons . maths . random . MersenneTwisterRNG ; import java . util . Random ; public class BetaWalk { private final Random rand = new MersenneTwisterRNG ( ) ; private final double stepSize ; private final BetaDistribution bd ; private double x ; private double pdf = <NUM_LIT:0> ; public BetaWalk ( double alpha , double beta , double stepSize ) { this . bd = new BetaDistribution ( alpha , beta , rand ) ; this . stepSize = stepSize ; x = bd . nextDouble ( ) ; if ( x < <NUM_LIT:0> ) { System . out . printf ( "<STR_LIT>" ) ; } pdf = bd . pdf ( x ) ; } public double step ( ) { double x1 = x + rand . nextGaussian ( ) * stepSize ; double pdf1 = bd . pdf ( x1 ) ; if ( x1 < <NUM_LIT:0> || x1 > <NUM_LIT:1> ) { pdf1 = <NUM_LIT:0> ; } if ( pdf1 > <NUM_LIT:0> && ( pdf1 > pdf || rand . nextDouble ( ) < pdf1 / pdf ) ) { if ( x1 < <NUM_LIT:0> ) { System . out . printf ( "<STR_LIT>" ) ; } x = x1 ; pdf = pdf1 ; } return x ; } } </s>
|
<s> package com . mapr . stats ; import java . util . Random ; public class EpsilonGreedyFactory extends BanditFactory { private double epsilon ; public EpsilonGreedyFactory ( double epsilon ) { this . epsilon = epsilon ; } @ Override public BayesianBandit createBandit ( int bandits , Random gen ) { return new EpsilonGreedy ( bandits , epsilon , gen ) ; } } </s>
|
<s> package com . mapr . stats ; import org . apache . mahout . math . jet . random . AbstractContinousDistribution ; import org . apache . mahout . math . jet . random . Gamma ; import org . apache . mahout . math . jet . random . Normal ; import org . uncommons . maths . random . MersenneTwisterRNG ; import java . util . Random ; public class GammaNormalDistribution extends AbstractBayesianDistribution { private Random gen = new MersenneTwisterRNG ( ) ; private double m , n ; private double ss ; private final Gamma gd = new Gamma ( <NUM_LIT:1> , <NUM_LIT:1> , gen ) ; private final Normal nd = new Normal ( <NUM_LIT:0> , <NUM_LIT:1> , gen ) ; public GammaNormalDistribution ( double m , double n , double sd , Random gen ) { this . gen = gen ; this . m = m ; this . n = n ; this . ss = sd * sd ; } @ Override public double nextDouble ( ) { double variance = nextVariance ( ) ; double mean = nd . nextDouble ( ) * Math . sqrt ( variance / n ) + m ; return nd . nextDouble ( ) * Math . sqrt ( variance ) + mean ; } @ Override public void add ( double x ) { n += <NUM_LIT:1> ; final double delta = ( x - m ) ; m += delta / n ; ss = ss + delta * ( x - m ) ; } @ Override public double nextMean ( ) { double sd = Math . sqrt ( nextVariance ( ) / n ) ; return nd . nextDouble ( ) * sd + m ; } @ Override public AbstractContinousDistribution posteriorDistribution ( ) { return new Normal ( m , Math . sqrt ( ss / n ) , gen ) ; } double nextSD ( ) { return Math . sqrt ( nextVariance ( ) ) ; } private double nextVariance ( ) { return <NUM_LIT:1> / gd . nextDouble ( n / <NUM_LIT:2> , ss / <NUM_LIT:2> ) ; } } </s>
|
<s> package com . mapr . stats ; import java . util . Random ; class GammaNormalBayesFactory extends BanditFactory { @ Override public BayesianBandit createBandit ( int bandits , Random gen ) { return new GammaNormalBayesModel ( bandits , gen ) ; } } </s>
|
<s> package com . mapr . stats ; import com . google . common . collect . Lists ; import org . apache . mahout . math . stats . OnlineSummarizer ; import java . util . List ; import java . util . Random ; public class EpsilonGreedy extends BayesianBandit { private Random gen ; private double epsilon ; private final List < OnlineSummarizer > summaries ; public EpsilonGreedy ( int bandits , double epsilon , Random gen ) { this . gen = gen ; this . epsilon = epsilon ; summaries = Lists . newArrayList ( ) ; for ( int i = <NUM_LIT:0> ; i < bandits ; i ++ ) { final OnlineSummarizer s = new OnlineSummarizer ( ) ; summaries . add ( s ) ; s . add ( <NUM_LIT:1> ) ; } } @ Override public int sample ( ) { if ( gen . nextDouble ( ) < epsilon ) { return gen . nextInt ( summaries . size ( ) ) ; } else { double max = summaries . get ( <NUM_LIT:0> ) . getMean ( ) ; int i = <NUM_LIT:0> ; int maxIndex = <NUM_LIT:0> ; for ( OnlineSummarizer summary : summaries ) { if ( summary . getMean ( ) > max ) { max = summary . getMean ( ) ; maxIndex = i ; } i ++ ; } return maxIndex ; } } @ Override public void train ( int bandit , double reward ) { summaries . get ( bandit ) . add ( reward ) ; } @ Override public boolean addModelDistribution ( AbstractBayesianDistribution distribution ) { throw new UnsupportedOperationException ( "<STR_LIT>" ) ; } } </s>
|
<s> package com . mapr . stats ; import org . apache . mahout . math . jet . random . AbstractContinousDistribution ; import java . util . Random ; public class BinomialDistributionSampler extends DistributionGenerator { private final BetaDistribution bd ; private final Random gen ; public BinomialDistributionSampler ( double alpha , double beta , Random gen ) { this . gen = gen ; bd = new BetaDistribution ( alpha , beta ) ; } @ Override public DistributionWithMean nextDistribution ( ) { final double p = bd . nextDouble ( ) ; return new DistributionWithMean ( new AbstractContinousDistribution ( ) { @ Override public double nextDouble ( ) { return gen . nextDouble ( ) < p ? <NUM_LIT:1> : <NUM_LIT:0> ; } } , p ) ; } } </s>
|
<s> package com . mapr . stats ; import org . apache . mahout . math . jet . random . AbstractContinousDistribution ; import org . apache . mahout . math . jet . random . Gamma ; import org . uncommons . maths . random . MersenneTwisterRNG ; import java . util . Random ; public class BetaDistribution extends AbstractContinousDistribution { private final Gamma gAlpha ; private final Gamma gBeta ; private double alpha , beta ; public BetaDistribution ( double alpha , double beta , Random random ) { this . alpha = alpha ; this . beta = beta ; gAlpha = new Gamma ( alpha , <NUM_LIT:1> , random ) ; gBeta = new Gamma ( beta , <NUM_LIT:1> , random ) ; } public BetaDistribution ( double alpha , double beta ) { this ( alpha , beta , new MersenneTwisterRNG ( ) ) ; } @ Override public double nextDouble ( ) { double x = gAlpha . nextDouble ( alpha , <NUM_LIT:1> ) ; double y = gBeta . nextDouble ( beta , <NUM_LIT:1> ) ; return x / ( x + y ) ; } public double nextDouble ( double alpha , double beta ) { double x = gAlpha . nextDouble ( alpha , <NUM_LIT:1> ) ; double y = gBeta . nextDouble ( beta , <NUM_LIT:1> ) ; return x / ( x + y ) ; } @ Override public double pdf ( double x ) { return Math . pow ( x , alpha - <NUM_LIT:1> ) * Math . pow ( <NUM_LIT:1> - x , beta - <NUM_LIT:1> ) / org . apache . mahout . math . jet . stat . Gamma . beta ( alpha , beta ) ; } public double logPdf ( double x ) { return x * ( alpha - <NUM_LIT:1> ) + ( <NUM_LIT:1> - x ) * ( beta - <NUM_LIT:1> ) - Math . log ( org . apache . mahout . math . jet . stat . Gamma . beta ( alpha , beta ) ) ; } @ Override public double cdf ( double x ) { return org . apache . mahout . math . jet . stat . Gamma . incompleteBeta ( alpha , beta , x ) ; } public void setAlpha ( double alpha ) { this . alpha = alpha ; } public void setBeta ( double beta ) { this . beta = beta ; } public double getBeta ( ) { return beta ; } public double getAlpha ( ) { return alpha ; } public double mean ( ) { return alpha / ( alpha + beta ) ; } @ Override public void setRandomGenerator ( Random rand ) { gAlpha . setRandomGenerator ( rand ) ; gBeta . setRandomGenerator ( rand ) ; } } </s>
|
<s> package com . mapr . stats ; import java . util . Random ; class BetaBayesFactory extends BanditFactory { @ Override public BayesianBandit createBandit ( int bandits , Random gen ) { return new BetaBayesModel ( bandits , gen ) ; } } </s>
|
<s> package com . mapr . storm ; import backtype . storm . task . OutputCollector ; import backtype . storm . task . TopologyContext ; import backtype . storm . topology . IRichBolt ; import backtype . storm . topology . OutputFieldsDeclarer ; import backtype . storm . tuple . Fields ; import backtype . storm . tuple . Tuple ; import com . google . common . collect . ImmutableList ; import com . google . common . collect . Lists ; import com . google . common . collect . Maps ; import java . util . Arrays ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; import java . util . Queue ; public class TimeLimitedJoin implements IRichBolt { private final long expirationTime ; private final int maxTuplesToRetain ; private final Fields joinKey ; private OutputCollector collector ; private final Queue < TimedTuple > queue = new LinkedList < TimedTuple > ( ) ; private final Map < Key , TimedTuple > pendingByKey = Maps . newHashMap ( ) ; public TimeLimitedJoin ( long expirationTime , int maxTuplesToRetain , Fields joinKey ) { this . expirationTime = expirationTime ; this . maxTuplesToRetain = maxTuplesToRetain ; this . joinKey = joinKey ; } @ Override public void prepare ( Map config , TopologyContext context , OutputCollector collector ) { this . collector = collector ; } @ Override public synchronized void execute ( Tuple input ) { long cutoff = now ( ) - expirationTime ; while ( queue . size ( ) > <NUM_LIT:0> && ( queue . size ( ) > maxTuplesToRetain || queue . peek ( ) . time < cutoff ) ) { TimedTuple expiringTuple = queue . poll ( ) ; if ( expiringTuple . tuple != null ) { collector . ack ( expiringTuple . tuple ) ; Key key = extractJoinKey ( input ) ; if ( pendingByKey . get ( key ) . time < cutoff ) { pendingByKey . remove ( key ) ; } } } final Key key = extractJoinKey ( input ) ; TimedTuple match = pendingByKey . get ( key ) ; if ( match != null ) { if ( match . tuple != null ) { pendingByKey . remove ( key ) ; collector . emit ( Arrays . asList ( input , match . tuple ) , ImmutableList . of ( Lists . newArrayList ( key ) , match . tuple , input ) ) ; collector . ack ( input ) ; collector . ack ( match . tuple ) ; match . tuple = null ; } } else { final TimedTuple t = new TimedTuple ( now ( ) , input ) ; queue . add ( t ) ; pendingByKey . put ( key , t ) ; } } private Key extractJoinKey ( Tuple input ) { List < Object > keys = Lists . newArrayList ( ) ; for ( String key : joinKey ) { keys . add ( input . getValueByField ( key ) ) ; } return new Key ( keys ) ; } private long now ( ) { return System . nanoTime ( ) / <NUM_LIT> ; } @ Override public void cleanup ( ) { } @ Override public void declareOutputFields ( OutputFieldsDeclarer declarer ) { declarer . declare ( new Fields ( "<STR_LIT>" , "<STR_LIT>" ) ) ; } private static class Key implements Iterable < Object > { final List < Object > values ; private Key ( List < Object > values ) { this . values = values ; } @ Override public boolean equals ( Object o ) { if ( this == o ) { return true ; } if ( ! ( o instanceof Key ) ) { return false ; } Key other = ( Key ) o ; if ( values == other . values ) { return true ; } else if ( values == null || other . values == null ) { return values == other . values ; } else { if ( values . size ( ) != other . values . size ( ) ) { return false ; } Iterator i = other . values . iterator ( ) ; for ( Object value : values ) { if ( ! i . hasNext ( ) || ! value . equals ( i . next ( ) ) ) { return false ; } } return true ; } } @ Override public int hashCode ( ) { int hash = <NUM_LIT:0> ; for ( Object value : values ) { hash = hash ^ value . hashCode ( ) ; } return hash ; } @ Override public Iterator < Object > iterator ( ) { return values . iterator ( ) ; } } private static class TimedTuple implements Comparable < TimedTuple > { private final long time ; public Tuple tuple ; public TimedTuple ( long time , Tuple tuple ) { this . time = time ; this . tuple = tuple ; } @ Override public int compareTo ( TimedTuple other ) { long r = ( time - other . time ) ; if ( r < <NUM_LIT:0> ) { return - <NUM_LIT:1> ; } else if ( r > <NUM_LIT:0> ) { return <NUM_LIT:1> ; } else { return <NUM_LIT:0> ; } } } } </s>
|
<s> package com . mapr . storm ; import backtype . storm . task . TopologyContext ; import backtype . storm . topology . BasicOutputCollector ; import backtype . storm . topology . IBasicBolt ; import backtype . storm . topology . OutputFieldsDeclarer ; import backtype . storm . tuple . Fields ; import backtype . storm . tuple . Tuple ; import java . io . FileNotFoundException ; import java . io . FileOutputStream ; import java . io . PrintWriter ; import java . util . Map ; public class FileBolt implements IBasicBolt { private PrintWriter output ; private String base ; public FileBolt ( String base ) { this . base = base ; } @ Override public void prepare ( Map conf , TopologyContext context ) { String outputName = base + context . getThisComponentId ( ) + "<STR_LIT:->" + context . getThisTaskId ( ) ; try { output = new PrintWriter ( new FileOutputStream ( outputName ) ) ; } catch ( FileNotFoundException e ) { throw new RuntimeException ( "<STR_LIT>" + outputName , e ) ; } } @ Override public void execute ( Tuple input , BasicOutputCollector collector ) { String separator = "<STR_LIT>" ; for ( Object v : input . getValues ( ) ) { output . print ( separator ) ; output . print ( v ) ; separator = "<STR_LIT:t>" ; } output . println ( ) ; } @ Override public void cleanup ( ) { output . close ( ) ; } @ Override public void declareOutputFields ( OutputFieldsDeclarer declarer ) { declarer . declare ( new Fields ( ) ) ; } } </s>
|
<s> package com . mapr . storm ; import backtype . storm . task . OutputCollector ; import backtype . storm . task . TopologyContext ; import backtype . storm . topology . IRichBolt ; import backtype . storm . topology . OutputFieldsDeclarer ; import backtype . storm . tuple . Fields ; import backtype . storm . tuple . Tuple ; import backtype . storm . tuple . Values ; import com . google . common . collect . HashMultiset ; import com . google . common . collect . Multiset ; import org . apache . log4j . Logger ; import java . util . Map ; import java . util . Queue ; import java . util . concurrent . LinkedBlockingQueue ; import java . util . concurrent . atomic . AtomicInteger ; import java . util . concurrent . atomic . AtomicReference ; public class CounterBolt implements IRichBolt { private static final transient Logger logger = Logger . getLogger ( CounterBolt . class ) ; private final AtomicInteger count = new AtomicInteger ( ) ; private final long reportingInterval ; private final int maxBufferedTuples ; private final AtomicReference < Queue < Tuple > > tupleLog = new AtomicReference < Queue < Tuple > > ( new LinkedBlockingQueue < Tuple > ( ) ) ; private OutputCollector outputCollector ; private long lastRecordOutput = <NUM_LIT:0> ; public CounterBolt ( ) { this ( <NUM_LIT:10> * <NUM_LIT:1000> , <NUM_LIT> ) ; } public CounterBolt ( long reportingInterval , int maxBufferedTuples ) { this . reportingInterval = reportingInterval ; this . maxBufferedTuples = maxBufferedTuples ; } @ Override public void prepare ( Map map , TopologyContext topologyContext , OutputCollector outputCollector ) { this . outputCollector = outputCollector ; } @ Override public void execute ( Tuple tuple ) { tupleLog . get ( ) . add ( tuple ) ; recordCounts ( false ) ; } private void recordCounts ( boolean force ) { long currentRecordWindowStart = ( now ( ) / reportingInterval ) * reportingInterval ; if ( lastRecordOutput == <NUM_LIT:0> ) { lastRecordOutput = currentRecordWindowStart ; } final int bufferedTuples = tupleLog . get ( ) . size ( ) ; if ( force || currentRecordWindowStart > lastRecordOutput || bufferedTuples > maxBufferedTuples ) { if ( force ) { logger . info ( "<STR_LIT>" ) ; } else if ( bufferedTuples > maxBufferedTuples ) { logger . info ( "<STR_LIT>" ) ; } else { logger . info ( "<STR_LIT>" ) ; } Queue < Tuple > oldLog = tupleLog . getAndSet ( new LinkedBlockingQueue < Tuple > ( ) ) ; Multiset < String > counts = HashMultiset . create ( ) ; for ( Tuple tuple : oldLog ) { counts . add ( tuple . getString ( <NUM_LIT:0> ) + "<STR_LIT:t>" + tuple . getString ( <NUM_LIT:1> ) ) ; } for ( String keyValue : counts . elementSet ( ) ) { final int n = counts . count ( keyValue ) ; outputCollector . emit ( oldLog , new Values ( keyValue , n ) ) ; count . addAndGet ( n ) ; } logger . info ( String . format ( "<STR_LIT>" , count . get ( ) ) ) ; for ( Tuple tuple : oldLog ) { outputCollector . ack ( tuple ) ; } lastRecordOutput = currentRecordWindowStart ; } } private long now ( ) { return System . nanoTime ( ) / <NUM_LIT> ; } @ Override public void cleanup ( ) { recordCounts ( true ) ; logger . warn ( String . format ( "<STR_LIT>" , count . get ( ) ) ) ; } @ Override public void declareOutputFields ( OutputFieldsDeclarer declarer ) { declarer . declare ( new Fields ( "<STR_LIT>" , "<STR_LIT:count>" ) ) ; } public int getTotal ( ) { return count . get ( ) ; } } </s>
|
<s> package com . mapr . storm ; import backtype . storm . spout . SpoutOutputCollector ; import backtype . storm . task . TopologyContext ; import backtype . storm . topology . IRichSpout ; import backtype . storm . topology . OutputFieldsDeclarer ; import backtype . storm . tuple . Fields ; import backtype . storm . tuple . Values ; import backtype . storm . utils . Utils ; import java . util . Map ; import java . util . Random ; public class EventSpout implements IRichSpout { private final boolean isDistributed ; private SpoutOutputCollector collector ; private int n ; private int emitted = <NUM_LIT:0> ; public EventSpout ( int n ) { this ( true ) ; this . n = n ; } public EventSpout ( boolean isDistributed ) { this . isDistributed = isDistributed ; this . n = <NUM_LIT:1000> ; } public boolean isDistributed ( ) { return isDistributed ; } public void open ( Map conf , TopologyContext context , SpoutOutputCollector collector ) { this . collector = collector ; } public void close ( ) { } private final String [ ] keys = new String [ ] { "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" } ; private final String [ ] words = new String [ ] { "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" } ; private final Random rand = new Random ( ) ; public void nextTuple ( ) { if ( emitted < n ) { Utils . sleep ( <NUM_LIT:1> ) ; collector . emit ( new Values ( keys [ rand . nextInt ( keys . length ) ] , words [ rand . nextInt ( words . length ) ] ) ) ; emitted ++ ; } else { Utils . sleep ( <NUM_LIT:1000> ) ; } } public void ack ( Object msgId ) { } public void fail ( Object msgId ) { } public void declareOutputFields ( OutputFieldsDeclarer declarer ) { declarer . declare ( new Fields ( "<STR_LIT:key>" , "<STR_LIT>" ) ) ; } } </s>
|
<s> package com . mapr . stats ; import org . apache . mahout . common . RandomUtils ; import org . apache . mahout . math . DenseMatrix ; import org . apache . mahout . math . DenseVector ; import org . apache . mahout . math . Matrix ; import org . apache . mahout . math . Vector ; import org . apache . mahout . math . function . DoubleFunction ; import org . junit . Test ; import java . util . Random ; public class ContextualBayesBanditTest { @ Test public void testConvergence ( ) { final Random rand = RandomUtils . getRandom ( ) ; Matrix recipes = new DenseMatrix ( <NUM_LIT:100> , <NUM_LIT:10> ) . assign ( new DoubleFunction ( ) { @ Override public double apply ( double arg1 ) { return rand . nextDouble ( ) < <NUM_LIT> ? <NUM_LIT:1> : <NUM_LIT:0> ; } } ) ; recipes . viewColumn ( <NUM_LIT:9> ) . assign ( <NUM_LIT:1> ) ; Vector actualWeights = new DenseVector ( new double [ ] { <NUM_LIT:1> , <NUM_LIT> , - <NUM_LIT> , <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:0> , - <NUM_LIT:1> } ) ; Vector probs = recipes . times ( actualWeights ) ; ContextualBayesBandit banditry = new ContextualBayesBandit ( recipes ) ; for ( int i = <NUM_LIT:0> ; i < <NUM_LIT:1000> ; i ++ ) { int k = banditry . sample ( ) ; final boolean success = rand . nextDouble ( ) < probs . get ( k ) ; banditry . train ( k , success ) ; } } } </s>
|
<s> package com . mapr . stats ; import org . apache . mahout . math . DenseVector ; import org . apache . mahout . math . Vector ; import org . apache . mahout . math . function . Functions ; import org . apache . mahout . math . jet . random . AbstractContinousDistribution ; import org . junit . Test ; import java . util . Arrays ; import java . util . Random ; import static org . junit . Assert . assertEquals ; public class GammaNormalDistributionTest { @ Test public void testEstimation ( ) { final Random gen = new Random ( <NUM_LIT:1> ) ; GammaNormalDistribution gnd = new GammaNormalDistribution ( <NUM_LIT:0> , <NUM_LIT:1> , <NUM_LIT:1> , gen ) ; for ( int i = <NUM_LIT:0> ; i < <NUM_LIT> ; i ++ ) { gnd . add ( gen . nextGaussian ( ) * <NUM_LIT:2> + <NUM_LIT:1> ) ; } assertEquals ( <NUM_LIT:1.0> , gnd . nextMean ( ) , <NUM_LIT> ) ; assertEquals ( <NUM_LIT> , gnd . nextSD ( ) , <NUM_LIT> ) ; double [ ] x = new double [ <NUM_LIT> ] ; double [ ] y = new double [ <NUM_LIT> ] ; double [ ] z = new double [ <NUM_LIT> ] ; AbstractContinousDistribution dist = gnd . posteriorDistribution ( ) ; for ( int i = <NUM_LIT:0> ; i < <NUM_LIT> ; i ++ ) { x [ i ] = gnd . nextDouble ( ) ; y [ i ] = dist . nextDouble ( ) ; z [ i ] = gen . nextGaussian ( ) * <NUM_LIT:2> + <NUM_LIT:1> ; } Arrays . sort ( x ) ; Arrays . sort ( y ) ; Arrays . sort ( z ) ; final Vector xv = new DenseVector ( x ) . viewPart ( <NUM_LIT:1000> , <NUM_LIT> ) ; final Vector yv = new DenseVector ( y ) . viewPart ( <NUM_LIT:1000> , <NUM_LIT> ) ; final Vector zv = new DenseVector ( z ) . viewPart ( <NUM_LIT:1000> , <NUM_LIT> ) ; final double diffX = xv . minus ( zv ) . assign ( Functions . ABS ) . maxValue ( ) ; final double diffY = yv . minus ( zv ) . assign ( Functions . ABS ) . maxValue ( ) ; assertEquals ( <NUM_LIT:0> , diffX , <NUM_LIT> ) ; assertEquals ( <NUM_LIT:0> , diffY , <NUM_LIT> ) ; } } </s>
|
<s> package com . mapr . stats ; import org . junit . Test ; import static org . junit . Assert . assertEquals ; public class BetaDistributionTest extends DistributionTest { @ Test public void testPdf1 ( ) { pdfCheck ( new double [ ] { <NUM_LIT:0> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT:1> } , new double [ ] { <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:1> } , new BetaDistribution ( <NUM_LIT:1> , <NUM_LIT:1> ) ) ; } @ Test public void testPdf2 ( ) { pdfCheck ( new double [ ] { <NUM_LIT:0> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT:1> } , new double [ ] { <NUM_LIT:0> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT:0> } , new BetaDistribution ( <NUM_LIT:2> , <NUM_LIT:3> ) ) ; } @ Test public void testCdf1 ( ) { double [ ] x = { <NUM_LIT:0> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT:1> } ; cdfCheck ( x , x , new BetaDistribution ( <NUM_LIT:1> , <NUM_LIT:1> ) ) ; } @ Test public void testCdf2 ( ) { cdfCheck ( new double [ ] { <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> } , new double [ ] { <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT:1> } , new BetaDistribution ( <NUM_LIT:2> , <NUM_LIT:3> ) ) ; } @ Test public void testMean ( ) { assertEquals ( <NUM_LIT> , new BetaDistribution ( <NUM_LIT:1> , <NUM_LIT:1> ) . mean ( ) , <NUM_LIT> ) ; assertEquals ( <NUM_LIT> , new BetaDistribution ( <NUM_LIT:2> , <NUM_LIT:3> ) . mean ( ) , <NUM_LIT> ) ; assertEquals ( <NUM_LIT> / <NUM_LIT> , new BetaDistribution ( <NUM_LIT> , <NUM_LIT:10> ) . mean ( ) , <NUM_LIT> ) ; } @ Test public void testSampleDistribution1 ( ) { checkDistribution ( new BetaDistribution ( <NUM_LIT:1> , <NUM_LIT:1> ) , String . format ( "<STR_LIT>" , <NUM_LIT:1.0> , <NUM_LIT:1.0> ) , <NUM_LIT> ) ; final BetaDistribution bd = new BetaDistribution ( <NUM_LIT:1> , <NUM_LIT:1> ) ; bd . setAlpha ( <NUM_LIT:2> ) ; bd . setBeta ( <NUM_LIT:3> ) ; checkDistribution ( bd , String . format ( "<STR_LIT>" , <NUM_LIT> , <NUM_LIT> ) , <NUM_LIT> ) ; checkDistribution ( new BetaDistribution ( <NUM_LIT> , <NUM_LIT> ) , String . format ( "<STR_LIT>" , <NUM_LIT> , <NUM_LIT> ) , <NUM_LIT> ) ; } } </s>
|
<s> package com . mapr . stats ; import com . google . common . collect . Lists ; import java . util . List ; public class Walk { public static void main ( String [ ] args ) { List < BetaWalk > x = Lists . newArrayList ( ) ; for ( int i = <NUM_LIT:0> ; i < <NUM_LIT:30> ; i ++ ) { x . add ( new BetaWalk ( <NUM_LIT:1> , <NUM_LIT> , <NUM_LIT> ) ) ; } double [ ] p = new double [ x . size ( ) ] ; for ( long j = <NUM_LIT:0> ; j < <NUM_LIT> ; j ++ ) { for ( int i = <NUM_LIT:0> ; i < <NUM_LIT:30> ; i ++ ) { p [ i ] = x . get ( i ) . step ( ) ; } print ( j , p ) ; } } private static void print ( long step , double [ ] p ) { System . out . printf ( "<STR_LIT>" , step ) ; for ( int i = <NUM_LIT:0> ; i < <NUM_LIT:30> ; i ++ ) { System . out . printf ( "<STR_LIT>" , p [ i ] ) ; } System . out . printf ( "<STR_LIT:n>" ) ; } } </s>
|
<s> package com . mapr . stats ; import org . apache . mahout . math . jet . random . AbstractContinousDistribution ; import java . util . Arrays ; import static org . junit . Assert . assertEquals ; public class DistributionTest { protected void checkDistribution ( AbstractContinousDistribution d , String test , double epsilon ) { int n = <NUM_LIT> ; double [ ] s = new double [ n ] ; for ( int i = <NUM_LIT:0> ; i < n ; i ++ ) { s [ i ] = d . nextDouble ( ) ; } Arrays . sort ( s ) ; for ( int q = <NUM_LIT:0> ; q <= <NUM_LIT:4> ; q ++ ) { assertEquals ( test + "<STR_LIT>" + q , d . cdf ( s [ ( n - <NUM_LIT:1> ) * q / <NUM_LIT:4> ] ) , q / <NUM_LIT> , epsilon ) ; } } protected void cdfCheck ( double [ ] expected , double [ ] cdf , AbstractContinousDistribution d ) { for ( int i = <NUM_LIT:0> ; i < expected . length ; i ++ ) { assertEquals ( expected [ i ] , d . cdf ( cdf [ i ] ) , <NUM_LIT> ) ; } } protected void pdfCheck ( double [ ] xValues , double [ ] expected , AbstractContinousDistribution d ) { int i = <NUM_LIT:0> ; for ( double x : xValues ) { assertEquals ( expected [ i ] , d . pdf ( x ) , <NUM_LIT> ) ; i ++ ; } } } </s>
|
<s> package com . mapr . stats ; import org . junit . Test ; import java . io . FileNotFoundException ; import static org . junit . Assert . assertEquals ; public class BayesBanditTest { @ Test public void testConvergence ( ) throws FileNotFoundException { double r = BanditTrainer . averageRegret ( "<STR_LIT>" , new int [ ] { <NUM_LIT> } , <NUM_LIT> , <NUM_LIT:2> ) ; assertEquals ( <NUM_LIT:0> , r , <NUM_LIT> ) ; } @ Test public void testSlowConvergence ( ) throws FileNotFoundException { double r = BanditTrainer . commitTime ( "<STR_LIT>" , <NUM_LIT> , <NUM_LIT> , <NUM_LIT> , <NUM_LIT:1000> ) ; assertEquals ( <NUM_LIT> , r , <NUM_LIT> ) ; } } </s>
|
<s> package com . mapr . storm ; import backtype . storm . task . OutputCollector ; import backtype . storm . task . TopologyContext ; import backtype . storm . tuple . Fields ; import backtype . storm . tuple . Tuple ; import com . google . common . collect . Lists ; import mockit . Mock ; import mockit . MockUp ; import java . lang . reflect . Field ; import java . util . Collection ; import java . util . Formatter ; import java . util . List ; import java . util . Set ; @ SuppressWarnings ( "<STR_LIT>" ) public class Fake { private static final long [ ] time = { <NUM_LIT> } ; private static final Clock adjuster = new Clock ( ) ; public static Tuple tuple ( Object ... data ) { final List < String > fields = Lists . newArrayList ( ) ; final List < Object > values = Lists . newArrayList ( ) ; for ( int i = <NUM_LIT:0> ; i < data . length ; i += <NUM_LIT:2> ) { fields . add ( ( String ) data [ i ] ) ; values . add ( data [ i + <NUM_LIT:1> ] ) ; } new MockUp < Tuple > ( ) { FakeTuple it ; @ Mock public void $init ( TopologyContext context , List < Object > values , int taskId , String streamId ) throws IllegalAccessException , NoSuchFieldException { Field f = Tuple . class . getDeclaredField ( "<STR_LIT>" ) ; f . setAccessible ( true ) ; f . set ( it , values ) ; } @ Mock public Fields getFields ( ) { return it . fields ; } } ; return new FakeTuple ( fields , values ) ; } public static class FakeTuple extends Tuple { final Fields fields ; public FakeTuple ( List < String > fields , List < Object > values ) { super ( null , values , <NUM_LIT:0> , null ) ; this . fields = new Fields ( fields ) ; } @ Override public String toString ( ) { int i = <NUM_LIT:0> ; Formatter f = new Formatter ( ) ; f . format ( "<STR_LIT:[>" ) ; String separator = "<STR_LIT>" ; for ( String field : fields ) { f . format ( "<STR_LIT>" , separator , field , getValue ( i ++ ) ) ; separator = "<STR_LIT:U+002CU+0020>" ; } f . format ( "<STR_LIT:]>" ) ; return f . toString ( ) ; } } public static OutputCollector collector ( final List < AnchoredTuple > output , final Set < Tuple > acknowledgements , final Set < Tuple > failures ) { new MockUp < FakeOutputCollector > ( ) { public FakeOutputCollector it ; @ Mock public List < Integer > emit ( String streamId , Collection < Tuple > anchors , List < Object > tuple ) { it . output . add ( new AnchoredTuple ( anchors , tuple ) ) ; return null ; } @ Mock public void ack ( Tuple input ) { it . acknowledgements . add ( input ) ; } @ Mock public void fail ( Tuple tuple ) { it . failures . add ( tuple ) ; } } ; return new FakeOutputCollector ( output , acknowledgements , failures ) ; } private static class FakeOutputCollector extends OutputCollector { final List < AnchoredTuple > output ; final Set < Tuple > acknowledgements ; private final Set < Tuple > failures ; private FakeOutputCollector ( List < AnchoredTuple > output , Set < Tuple > acknowledgements , Set < Tuple > failures ) { this . output = output ; this . acknowledgements = acknowledgements ; this . failures = failures ; } @ Override public List < Integer > emit ( String streamId , Collection < Tuple > anchors , List < Object > tuple ) { output . add ( new AnchoredTuple ( anchors , tuple ) ) ; return null ; } @ Override public void emitDirect ( int taskId , String streamId , Collection < Tuple > anchors , List < Object > tuple ) { throw new UnsupportedOperationException ( "<STR_LIT>" ) ; } @ Override public void ack ( Tuple input ) { throw new UnsupportedOperationException ( "<STR_LIT>" ) ; } @ Override public void fail ( Tuple input ) { throw new UnsupportedOperationException ( "<STR_LIT>" ) ; } @ Override public void reportError ( Throwable error ) { throw new UnsupportedOperationException ( "<STR_LIT>" ) ; } } public static class AnchoredTuple { private final Collection < Tuple > anchors ; private final List < Object > tuple ; public AnchoredTuple ( Collection < Tuple > anchors , List < Object > tuple ) { this . anchors = anchors ; this . tuple = tuple ; } public Collection < Tuple > getAnchors ( ) { return anchors ; } public List < Object > getTuple ( ) { return tuple ; } } public static Clock clock ( ) { new MockUp < System > ( ) { @ Mock public long nanoTime ( ) { return time [ <NUM_LIT:0> ] * <NUM_LIT> ; } } ; return adjuster ; } public static class Clock { public Clock ( ) { } public void advance ( long delta ) { time [ <NUM_LIT:0> ] += delta ; } } } </s>
|
<s> package com . mapr . storm ; import backtype . storm . tuple . Fields ; import backtype . storm . tuple . Tuple ; import com . google . common . collect . ImmutableList ; import com . google . common . collect . Sets ; import org . junit . Test ; import java . util . ArrayList ; import java . util . List ; import java . util . Set ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . assertTrue ; public class TimeLimitedJoinTest { @ Test public void testJoinWithExpiration ( ) throws InterruptedException { TimeLimitedJoin tlj = new TimeLimitedJoin ( <NUM_LIT:1000> , <NUM_LIT:100> , new Fields ( "<STR_LIT:key1>" , "<STR_LIT>" ) ) ; final Fake . Clock clock = Fake . clock ( ) ; List < Fake . AnchoredTuple > out = new ArrayList < Fake . AnchoredTuple > ( ) ; Set < Tuple > acks = Sets . newHashSet ( ) ; Set < Tuple > failures = Sets . newHashSet ( ) ; tlj . prepare ( null , null , Fake . collector ( out , acks , failures ) ) ; Tuple t1 = Fake . tuple ( "<STR_LIT:key1>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ; Tuple t2 = Fake . tuple ( "<STR_LIT:key1>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ; Tuple t3 = Fake . tuple ( "<STR_LIT:key1>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ; Tuple t4 = Fake . tuple ( "<STR_LIT:key1>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ; tlj . execute ( t1 ) ; clock . advance ( <NUM_LIT> ) ; tlj . execute ( t2 ) ; tlj . execute ( t3 ) ; clock . advance ( <NUM_LIT> ) ; tlj . execute ( t4 ) ; assertEquals ( <NUM_LIT:1> , out . size ( ) ) ; Fake . AnchoredTuple r = out . get ( <NUM_LIT:0> ) ; assertTrue ( Sets . newHashSet ( r . getAnchors ( ) ) . containsAll ( ImmutableList . of ( t1 , t3 ) ) ) ; assertEquals ( "<STR_LIT>" , r . getTuple ( ) . toString ( ) ) ; assertTrue ( acks . containsAll ( ImmutableList . of ( t1 , t2 , t3 ) ) ) ; assertEquals ( <NUM_LIT:0> , failures . size ( ) ) ; } @ Test public void testJoinWithResurrection ( ) throws InterruptedException { TimeLimitedJoin tlj = new TimeLimitedJoin ( <NUM_LIT:1000> , <NUM_LIT:100> , new Fields ( "<STR_LIT:key1>" , "<STR_LIT>" ) ) ; Fake . Clock clock = Fake . clock ( ) ; List < Fake . AnchoredTuple > out = new ArrayList < Fake . AnchoredTuple > ( ) ; Set < Tuple > acks = Sets . newHashSet ( ) ; Set < Tuple > failures = Sets . newHashSet ( ) ; tlj . prepare ( null , null , Fake . collector ( out , acks , failures ) ) ; Tuple t1 = Fake . tuple ( "<STR_LIT:key1>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ; Tuple t2 = Fake . tuple ( "<STR_LIT:key1>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ; Tuple t3 = Fake . tuple ( "<STR_LIT:key1>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ; Tuple t4 = Fake . tuple ( "<STR_LIT:key1>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ; Tuple t5 = Fake . tuple ( "<STR_LIT:key1>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ; tlj . execute ( t1 ) ; clock . advance ( <NUM_LIT> ) ; tlj . execute ( t2 ) ; tlj . execute ( t3 ) ; clock . advance ( <NUM_LIT> ) ; tlj . execute ( t4 ) ; clock . advance ( <NUM_LIT> ) ; tlj . execute ( t5 ) ; assertEquals ( <NUM_LIT:2> , out . size ( ) ) ; Fake . AnchoredTuple r = out . get ( <NUM_LIT:0> ) ; assertTrue ( Sets . newHashSet ( r . getAnchors ( ) ) . containsAll ( ImmutableList . of ( t1 , t3 ) ) ) ; assertEquals ( "<STR_LIT>" , r . getTuple ( ) . toString ( ) ) ; r = out . get ( <NUM_LIT:1> ) ; assertTrue ( Sets . newHashSet ( r . getAnchors ( ) ) . containsAll ( ImmutableList . of ( t4 , t5 ) ) ) ; assertEquals ( "<STR_LIT>" , r . getTuple ( ) . toString ( ) ) ; assertTrue ( acks . containsAll ( ImmutableList . of ( t1 , t2 , t3 , t4 ) ) ) ; assertEquals ( <NUM_LIT:0> , failures . size ( ) ) ; } } </s>
|
<s> package com . mapr . storm ; import backtype . storm . tuple . Tuple ; import com . google . common . collect . Sets ; import org . junit . Test ; import java . io . FileNotFoundException ; import java . util . ArrayList ; import java . util . List ; import java . util . Set ; import static org . junit . Assert . assertEquals ; public class CounterBoltTest { @ Test public void testShort ( ) throws FileNotFoundException , InterruptedException { CounterBolt cb = new CounterBolt ( <NUM_LIT:100> , <NUM_LIT:5> ) ; final Fake . Clock clock = Fake . clock ( ) ; List < Fake . AnchoredTuple > out = new ArrayList < Fake . AnchoredTuple > ( ) ; Set < Tuple > acks = Sets . newHashSet ( ) ; Set < Tuple > failures = Sets . newHashSet ( ) ; cb . prepare ( null , null , Fake . collector ( out , acks , failures ) ) ; Tuple t1 = Fake . tuple ( "<STR_LIT:key>" , "<STR_LIT>" , "<STR_LIT:value>" , "<STR_LIT>" ) ; Tuple t2 = Fake . tuple ( "<STR_LIT:key>" , "<STR_LIT>" , "<STR_LIT:value>" , "<STR_LIT>" ) ; Tuple t3 = Fake . tuple ( "<STR_LIT:key>" , "<STR_LIT>" , "<STR_LIT:value>" , "<STR_LIT>" ) ; Tuple t4 = Fake . tuple ( "<STR_LIT:key>" , "<STR_LIT>" , "<STR_LIT:value>" , "<STR_LIT>" ) ; Tuple t5 = Fake . tuple ( "<STR_LIT:key>" , "<STR_LIT>" , "<STR_LIT:value>" , "<STR_LIT>" ) ; Tuple t6 = Fake . tuple ( "<STR_LIT:key>" , "<STR_LIT>" , "<STR_LIT:value>" , "<STR_LIT>" ) ; Tuple t7 = Fake . tuple ( "<STR_LIT:key>" , "<STR_LIT>" , "<STR_LIT:value>" , "<STR_LIT>" ) ; Tuple t8 = Fake . tuple ( "<STR_LIT:key>" , "<STR_LIT>" , "<STR_LIT:value>" , "<STR_LIT>" ) ; cb . execute ( t1 ) ; clock . advance ( <NUM_LIT:10> ) ; cb . execute ( t1 ) ; clock . advance ( <NUM_LIT:10> ) ; cb . execute ( t2 ) ; clock . advance ( <NUM_LIT:10> ) ; cb . execute ( t1 ) ; clock . advance ( <NUM_LIT:10> ) ; cb . execute ( t3 ) ; clock . advance ( <NUM_LIT:10> ) ; cb . execute ( t3 ) ; clock . advance ( <NUM_LIT:10> ) ; cb . execute ( t4 ) ; clock . advance ( <NUM_LIT:10> ) ; cb . execute ( t5 ) ; cb . execute ( t6 ) ; assertEquals ( <NUM_LIT:5> , out . size ( ) ) ; cb . execute ( t7 ) ; cb . execute ( t8 ) ; cb . execute ( t7 ) ; clock . advance ( <NUM_LIT> ) ; cb . execute ( t7 ) ; assertEquals ( <NUM_LIT:8> , out . size ( ) ) ; cb . cleanup ( ) ; assertEquals ( <NUM_LIT> , cb . getTotal ( ) ) ; } } </s>
|
<s> package com . greboid . lock ; import com . sun . jna . Native ; import com . sun . jna . platform . win32 . WinDef . HWND ; import com . sun . jna . win32 . StdCallLibrary ; import com . sun . jna . win32 . W32APIOptions ; interface Wtsapi32 extends StdCallLibrary { public static final int NOTIFY_FOR_ALL_SESSIONS = <NUM_LIT:1> ; public static final int NOTIFY_FOR_THIS_SESSION = <NUM_LIT:0> ; public static final int WTS_SESSION_CHANGE = <NUM_LIT> ; public static final int WTS_SESSION_LOCK = <NUM_LIT:7> ; public static final int WTS_SESSION_UNLOCK = <NUM_LIT:8> ; Wtsapi32 INSTANCE = ( Wtsapi32 ) Native . loadLibrary ( "<STR_LIT>" , Wtsapi32 . class , W32APIOptions . UNICODE_OPTIONS ) ; public boolean WTSRegisterSessionNotification ( final HWND hWnd , final int dwFlags ) ; public boolean WTSUnRegisterSessionNotification ( final HWND hWnd ) ; } </s>
|
<s> package com . greboid . lock ; import com . sun . jna . Native ; import com . sun . jna . Pointer ; import com . sun . jna . win32 . W32APIOptions ; interface User32 extends com . sun . jna . platform . win32 . User32 { public static final int WS_EX_NOACTIVATE = <NUM_LIT> ; public static final int WS_DISABLED = <NUM_LIT> ; public static final int CS_GLOBALCLASS = <NUM_LIT> ; public static final User32 INSTANCE = ( User32 ) Native . loadLibrary ( "<STR_LIT>" , User32 . class , W32APIOptions . UNICODE_OPTIONS ) ; public static final int GWLP_WNDPROC = - <NUM_LIT:4> ; public HWND CreateWindowEx ( int dwExStyle , String lpClassName , String lpWindowName , int dwStyle , int x , int y , final int nWidth , int nHeight , int parent , int hMenu , int hInstance , Pointer lpParam ) ; public boolean DestroyWindow ( HWND hWnd ) ; } </s>
|
<s> package com . greboid . lock ; public interface LockListener { void locked ( ) ; void unlocked ( ) ; } </s>
|
<s> package com . greboid . lock ; import com . sun . jna . platform . win32 . WinDef . HWND ; import com . sun . jna . platform . win32 . WinUser . MSG ; import java . util . List ; import java . util . concurrent . CopyOnWriteArrayList ; public class LockAdapter { private final List < LockListener > listeners = new CopyOnWriteArrayList < LockListener > ( ) ; private boolean listening = false ; private HWND hwnd ; public LockAdapter ( ) { } private void start ( ) { new Thread ( new Runnable ( ) { @ Override public void run ( ) { attach ( ) ; } } ) . start ( ) ; } private void stop ( ) { listening = false ; detach ( ) ; } private void checkHandle ( ) { if ( hwnd == null ) { hwnd = User32 . INSTANCE . CreateWindowEx ( User32 . WS_EX_NOACTIVATE , "<STR_LIT>" , "<STR_LIT>" , User32 . WS_DISABLED , <NUM_LIT:0> , <NUM_LIT:0> , <NUM_LIT:100> , <NUM_LIT:100> , <NUM_LIT:0> , <NUM_LIT:0> , User32 . CS_GLOBALCLASS , null ) ; } } private void attach ( ) { checkHandle ( ) ; if ( ! listening ) { Wtsapi32 . INSTANCE . WTSRegisterSessionNotification ( hwnd , Wtsapi32 . NOTIFY_FOR_THIS_SESSION ) ; listening = true ; } MSG msg = new MSG ( ) ; while ( listening && User32 . INSTANCE . GetMessage ( msg , hwnd , <NUM_LIT:0> , <NUM_LIT:0> ) > <NUM_LIT:0> ) { if ( msg . message == Wtsapi32 . WTS_SESSION_CHANGE ) { switch ( msg . wParam . intValue ( ) ) { case <NUM_LIT:7> : fireLocked ( ) ; break ; case <NUM_LIT:8> : fireUnlocked ( ) ; break ; default : break ; } } User32 . INSTANCE . TranslateMessage ( msg ) ; User32 . INSTANCE . DispatchMessage ( msg ) ; } } private void detach ( ) { checkHandle ( ) ; Wtsapi32 . INSTANCE . WTSUnRegisterSessionNotification ( hwnd ) ; User32 . INSTANCE . DestroyWindow ( hwnd ) ; hwnd = null ; listening = false ; } public void addLockListener ( final LockListener l ) { if ( ! listeners . contains ( l ) ) { listeners . add ( l ) ; } if ( ! listeners . isEmpty ( ) ) { start ( ) ; } } public void removeLockListener ( final LockListener l ) { listeners . remove ( l ) ; if ( listeners . isEmpty ( ) ) { stop ( ) ; } } void fireLocked ( ) { for ( LockListener l : listeners ) { l . locked ( ) ; } } void fireUnlocked ( ) { for ( LockListener l : listeners ) { l . unlocked ( ) ; } } } </s>
|
<s> package org . ardverk . coding ; public class BencodingUtils { public static final String UTF_8 = "<STR_LIT:UTF-8>" ; public static final int LENGTH_DELIMITER = '<CHAR_LIT::>' ; public static final int DICTIONARY = '<CHAR_LIT>' ; public static final int LIST = '<CHAR_LIT>' ; public static final int NUMBER = '<CHAR_LIT>' ; public static final int EOF = '<CHAR_LIT:e>' ; public static final Integer TRUE = Integer . valueOf ( <NUM_LIT:1> ) ; public static final Integer FALSE = Integer . valueOf ( <NUM_LIT:0> ) ; private BencodingUtils ( ) { } } </s>
|
<s> package org . ardverk . coding ; import java . io . DataOutput ; import java . io . FilterOutputStream ; import java . io . IOException ; import java . io . OutputStream ; import java . lang . reflect . Array ; import java . util . Collection ; import java . util . Map ; import java . util . SortedMap ; import java . util . TreeMap ; public class BencodingOutputStream extends FilterOutputStream implements DataOutput { private final String charset ; public BencodingOutputStream ( OutputStream out ) { this ( out , BencodingUtils . UTF_8 ) ; } public BencodingOutputStream ( OutputStream out , String charset ) { super ( out ) ; if ( charset == null ) { throw new NullPointerException ( "<STR_LIT>" ) ; } this . charset = charset ; } public String getCharset ( ) { return charset ; } @ SuppressWarnings ( "<STR_LIT:unchecked>" ) public void writeObject ( Object value ) throws IOException { if ( value == null ) { writeNull ( ) ; } else if ( value instanceof byte [ ] ) { writeBytes ( ( byte [ ] ) value ) ; } else if ( value instanceof Boolean ) { writeBoolean ( ( Boolean ) value ) ; } else if ( value instanceof Character ) { writeChar ( ( Character ) value ) ; } else if ( value instanceof Number ) { writeNumber ( ( Number ) value ) ; } else if ( value instanceof String ) { writeString ( ( String ) value ) ; } else if ( value instanceof Collection < ? > ) { writeCollection ( ( Collection < ? > ) value ) ; } else if ( value instanceof Map < ? , ? > ) { writeMap ( ( Map < String , ? > ) value ) ; } else if ( value instanceof Enum < ? > ) { writeEnum ( ( Enum < ? > ) value ) ; } else if ( value . getClass ( ) . isArray ( ) ) { writeArray ( value ) ; } else { writeCustom ( value ) ; } } public void writeNull ( ) throws IOException { throw new IOException ( "<STR_LIT>" ) ; } protected void writeCustom ( Object value ) throws IOException { throw new IOException ( "<STR_LIT>" + value ) ; } public void writeBytes ( byte [ ] value ) throws IOException { writeBytes ( value , <NUM_LIT:0> , value . length ) ; } public void writeBytes ( byte [ ] value , int offset , int length ) throws IOException { if ( offset < <NUM_LIT:0> || length < <NUM_LIT:0> || value . length < ( offset + length ) ) { throw new ArrayIndexOutOfBoundsException ( ) ; } write ( Long . toString ( length ) . getBytes ( charset ) ) ; write ( BencodingUtils . LENGTH_DELIMITER ) ; write ( value , offset , length ) ; } @ Override public void writeBoolean ( boolean value ) throws IOException { writeNumber ( value ? BencodingUtils . TRUE : BencodingUtils . FALSE ) ; } @ Override public void writeChar ( int value ) throws IOException { writeString ( Character . toString ( ( char ) value ) ) ; } @ Override public void writeByte ( int value ) throws IOException { writeNumber ( Byte . valueOf ( ( byte ) value ) ) ; } @ Override public void writeShort ( int value ) throws IOException { writeNumber ( Short . valueOf ( ( short ) value ) ) ; } @ Override public void writeInt ( int value ) throws IOException { writeNumber ( Integer . valueOf ( value ) ) ; } @ Override public void writeLong ( long value ) throws IOException { writeNumber ( Long . valueOf ( value ) ) ; } @ Override public void writeFloat ( float value ) throws IOException { writeNumber ( Float . valueOf ( value ) ) ; } @ Override public void writeDouble ( double value ) throws IOException { writeNumber ( Double . valueOf ( value ) ) ; } public void writeNumber ( Number value ) throws IOException { String num = value . toString ( ) ; write ( BencodingUtils . NUMBER ) ; write ( num . getBytes ( charset ) ) ; write ( BencodingUtils . EOF ) ; } public void writeString ( String value ) throws IOException { writeBytes ( value . getBytes ( charset ) ) ; } public void writeCollection ( Collection < ? > value ) throws IOException { write ( BencodingUtils . LIST ) ; for ( Object element : value ) { writeObject ( element ) ; } write ( BencodingUtils . EOF ) ; } public void writeMap ( Map < ? , ? > map ) throws IOException { if ( ! ( map instanceof SortedMap < ? , ? > ) ) { map = new TreeMap < Object , Object > ( map ) ; } write ( BencodingUtils . DICTIONARY ) ; for ( Map . Entry < ? , ? > entry : map . entrySet ( ) ) { Object key = entry . getKey ( ) ; Object value = entry . getValue ( ) ; if ( key instanceof String ) { writeString ( ( String ) key ) ; } else { writeBytes ( ( byte [ ] ) key ) ; } writeObject ( value ) ; } write ( BencodingUtils . EOF ) ; } public void writeEnum ( Enum < ? > value ) throws IOException { writeString ( value . name ( ) ) ; } public void writeArray ( Object value ) throws IOException { write ( BencodingUtils . LIST ) ; int length = Array . getLength ( value ) ; for ( int i = <NUM_LIT:0> ; i < length ; i ++ ) { writeObject ( Array . get ( value , i ) ) ; } write ( BencodingUtils . EOF ) ; } @ Override public void writeBytes ( String value ) throws IOException { writeString ( value ) ; } @ Override public void writeChars ( String value ) throws IOException { writeString ( value ) ; } @ Override public void writeUTF ( String value ) throws IOException { writeBytes ( value . getBytes ( BencodingUtils . UTF_8 ) ) ; } } </s>
|
<s> package org . ardverk . coding ; import java . io . DataInput ; import java . io . EOFException ; import java . io . IOException ; import java . io . InputStream ; import java . io . PushbackInputStream ; import java . math . BigDecimal ; import java . math . BigInteger ; import java . util . ArrayList ; import java . util . Collection ; import java . util . List ; import java . util . Map ; import java . util . TreeMap ; public class BencodingInputStream extends PushbackInputStream implements DataInput { private static final ObjectFactory < Object > DEFAULT = new ObjectFactory < Object > ( ) { @ Override public Object read ( BencodingInputStream in ) throws IOException { int token = in . peek ( ) ; if ( token == BencodingUtils . DICTIONARY ) { return in . readMap ( ) ; } else if ( token == BencodingUtils . LIST ) { return in . readList ( ) ; } else if ( token == BencodingUtils . NUMBER ) { return in . readNumber ( ) ; } else if ( isDigit ( token ) ) { byte [ ] data = in . raw ( ) ; return in . decodeAsString ? new String ( data , in . charset ) : data ; } else { return in . readCustom ( ) ; } } } ; private final String charset ; private final boolean decodeAsString ; public BencodingInputStream ( InputStream in ) { this ( in , BencodingUtils . UTF_8 , false ) ; } public BencodingInputStream ( InputStream in , String charset ) { this ( in , charset , false ) ; } public BencodingInputStream ( InputStream in , boolean decodeAsString ) { this ( in , BencodingUtils . UTF_8 , decodeAsString ) ; } public BencodingInputStream ( InputStream in , String charset , boolean decodeAsString ) { super ( in ) ; if ( charset == null ) { throw new NullPointerException ( "<STR_LIT>" ) ; } this . charset = charset ; this . decodeAsString = decodeAsString ; } public String getCharset ( ) { return charset ; } public boolean isDecodeAsString ( ) { return decodeAsString ; } protected int pop ( ) throws IOException { int value = read ( ) ; if ( value == - <NUM_LIT:1> ) { throw new EOFException ( ) ; } return value ; } protected int peek ( ) throws IOException { int value = pop ( ) ; unread ( value ) ; return value ; } private byte [ ] raw ( ) throws IOException { return raw ( pop ( ) ) ; } private byte [ ] raw ( int length ) throws IOException { byte [ ] data = new byte [ length ] ; readFully ( data ) ; return data ; } private void check ( int expected ) throws IOException { int actual = - <NUM_LIT:1> ; if ( ( actual = pop ( ) ) != expected ) { throw new IOException ( "<STR_LIT>" + expected + "<STR_LIT>" + actual ) ; } } public byte [ ] readBytes ( ) throws IOException { StringBuilder sb = new StringBuilder ( ) ; int value = - <NUM_LIT:1> ; while ( ( value = pop ( ) ) != BencodingUtils . LENGTH_DELIMITER ) { sb . append ( ( char ) value ) ; } return raw ( Integer . parseInt ( sb . toString ( ) ) ) ; } public Object readObject ( ) throws IOException { return readObject ( DEFAULT ) ; } public < T > T readObject ( ObjectFactory < ? extends T > factory ) throws IOException { return factory . read ( this ) ; } protected Object readCustom ( ) throws IOException { throw new IOException ( ) ; } public String readString ( ) throws IOException { return readString ( charset ) ; } public String readString ( String encoding ) throws IOException { return new String ( readBytes ( ) , encoding ) ; } public < T extends Enum < T > > T readEnum ( Class < T > clazz ) throws IOException { return Enum . valueOf ( clazz , readString ( ) ) ; } public Number readNumber ( ) throws IOException { check ( BencodingUtils . NUMBER ) ; StringBuilder sb = new StringBuilder ( ) ; boolean decimal = false ; int token = - <NUM_LIT:1> ; while ( ( token = pop ( ) ) != BencodingUtils . EOF ) { if ( token == '<CHAR_LIT:.>' ) { decimal = true ; } sb . append ( ( char ) token ) ; } try { if ( decimal ) { return new BigDecimal ( sb . toString ( ) ) ; } else { return new BigInteger ( sb . toString ( ) ) ; } } catch ( NumberFormatException err ) { throw new IOException ( "<STR_LIT>" , err ) ; } } public Object [ ] readArray ( ) throws IOException { return readList ( ) . toArray ( ) ; } public < T > T [ ] readArray ( T [ ] a ) throws IOException { return readList ( ) . toArray ( a ) ; } public < T > T [ ] readArray ( ObjectFactory < ? extends T > factory , T [ ] a ) throws IOException { return readList ( factory ) . toArray ( a ) ; } public List < Object > readList ( ) throws IOException { return readList ( DEFAULT ) ; } public < T > List < T > readList ( ObjectFactory < ? extends T > factory ) throws IOException { return readCollection ( new ArrayList < T > ( ) , factory ) ; } public < T extends Collection < Object > > T readCollection ( T dst ) throws IOException { return readCollection ( dst , DEFAULT ) ; } public < E , T extends Collection < E > > T readCollection ( T dst , ObjectFactory < ? extends E > factory ) throws IOException { check ( BencodingUtils . LIST ) ; while ( peek ( ) != BencodingUtils . EOF ) { dst . add ( readObject ( factory ) ) ; } pop ( ) ; return dst ; } public Map < String , Object > readMap ( ) throws IOException { return readMap ( DEFAULT ) ; } public Map < String , Object > readMap ( Map < String , Object > dst ) throws IOException { return readMap ( dst , DEFAULT ) ; } public < T > Map < String , T > readMap ( ObjectFactory < ? extends T > factory ) throws IOException { return readMap ( new TreeMap < String , T > ( ) , factory ) ; } public < T > Map < String , T > readMap ( Map < String , T > dst , ObjectFactory < ? extends T > factory ) throws IOException { check ( BencodingUtils . DICTIONARY ) ; while ( peek ( ) != BencodingUtils . EOF ) { String key = new String ( raw ( ) , charset ) ; T value = readObject ( factory ) ; dst . put ( key , value ) ; } pop ( ) ; return dst ; } @ Override public char readChar ( ) throws IOException { return readString ( ) . charAt ( <NUM_LIT:0> ) ; } @ Override public boolean readBoolean ( ) throws IOException { return readInt ( ) != <NUM_LIT:0> ; } @ Override public byte readByte ( ) throws IOException { return readNumber ( ) . byteValue ( ) ; } @ Override public short readShort ( ) throws IOException { return readNumber ( ) . shortValue ( ) ; } @ Override public int readInt ( ) throws IOException { return readNumber ( ) . intValue ( ) ; } @ Override public float readFloat ( ) throws IOException { return readNumber ( ) . floatValue ( ) ; } @ Override public long readLong ( ) throws IOException { return readNumber ( ) . longValue ( ) ; } @ Override public double readDouble ( ) throws IOException { return readNumber ( ) . doubleValue ( ) ; } @ Override public void readFully ( byte [ ] dst ) throws IOException { readFully ( dst , <NUM_LIT:0> , dst . length ) ; } @ Override public void readFully ( byte [ ] dst , int off , int len ) throws IOException { int total = <NUM_LIT:0> ; while ( total < len ) { int r = read ( dst , total , len - total ) ; if ( r == - <NUM_LIT:1> ) { throw new EOFException ( ) ; } total += r ; } } @ Override public String readLine ( ) throws IOException { return readString ( ) ; } @ Override public int readUnsignedByte ( ) throws IOException { return readByte ( ) & <NUM_LIT> ; } @ Override public int readUnsignedShort ( ) throws IOException { return readShort ( ) & <NUM_LIT> ; } @ Override public String readUTF ( ) throws IOException { return readString ( BencodingUtils . UTF_8 ) ; } @ Override public int skipBytes ( int n ) throws IOException { return ( int ) skip ( n ) ; } private static boolean isDigit ( int token ) { return '<CHAR_LIT:0>' <= token && token <= '<CHAR_LIT:9>' ; } public static interface ObjectFactory < T > { public T read ( BencodingInputStream in ) throws IOException ; } } </s>
|
<s> package org . ardverk . coding ; public class BencodingTest { } </s>
|
<s> package org . gatein . wsrp . cxf ; import java . io . File ; public class Utils { public static final String GATEIN_WSRP_CONF_DIR = "<STR_LIT>" ; public static final String GATEIN_CONF_DIR = "<STR_LIT>" ; public static final String DEFAULT_WSRP_CONF_DIR_NAME = "<STR_LIT>" ; public static final String DEFAULT_WSRP_CXF_CONF_DIR_NAME = "<STR_LIT>" ; public static String getWSRPCXFConfigDirectory ( ) { String gateinWSRPConfDir = System . getProperty ( GATEIN_WSRP_CONF_DIR ) ; if ( gateinWSRPConfDir == null ) { String gateinConfDir = System . getProperty ( GATEIN_CONF_DIR ) ; gateinWSRPConfDir = gateinConfDir + File . separator + DEFAULT_WSRP_CONF_DIR_NAME ; } String wsrpCXFConfDir = gateinWSRPConfDir + File . separator + DEFAULT_WSRP_CXF_CONF_DIR_NAME ; return wsrpCXFConfDir ; } } </s>
|
<s> package org . gatein . wsrp . cxf ; import java . io . BufferedReader ; import java . io . File ; import java . io . FileInputStream ; import java . io . InputStreamReader ; import java . util . ArrayList ; import java . util . List ; import org . apache . cxf . feature . AbstractFeature ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class FeatureIntegratorFactory { private static Logger log = LoggerFactory . getLogger ( FeatureIntegratorFactory . class ) ; protected final static FeatureIntegratorFactory instance = new FeatureIntegratorFactory ( ) ; protected List < AbstractFeature > features = new ArrayList < AbstractFeature > ( ) ; public static final String DEFAULT_CXF_FEATURES_CONFIG_FILE_NAME = "<STR_LIT>" ; public FeatureIntegratorFactory ( ) { try { String wsrpCXFConfDir = Utils . getWSRPCXFConfigDirectory ( ) ; File featuresPropertyFile = new File ( wsrpCXFConfDir + File . separator + DEFAULT_CXF_FEATURES_CONFIG_FILE_NAME ) ; if ( featuresPropertyFile . exists ( ) ) { FileInputStream fileInStream = new FileInputStream ( featuresPropertyFile ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( fileInStream ) ) ; String featureClassName = reader . readLine ( ) ; while ( featureClassName != null ) { if ( ! featureClassName . trim ( ) . startsWith ( "<STR_LIT:#>" ) && ! featureClassName . trim ( ) . startsWith ( "<STR_LIT:!>" ) ) { AbstractFeature feature = createFeature ( featureClassName ) ; if ( feature != null ) { features . add ( feature ) ; } } featureClassName = reader . readLine ( ) ; } reader . close ( ) ; } else { log . debug ( "<STR_LIT>" + featuresPropertyFile + "<STR_LIT>" ) ; } } catch ( Exception e ) { log . error ( "<STR_LIT>" , e ) ; } } public static FeatureIntegratorFactory getInstance ( ) { return instance ; } public List < AbstractFeature > getFeatures ( ) { return features ; } protected AbstractFeature createFeature ( String className ) { try { Class clazz = Class . forName ( className ) ; Object object = clazz . getConstructor ( ) . newInstance ( ) ; if ( object instanceof AbstractFeature ) { return ( AbstractFeature ) object ; } else { log . error ( "<STR_LIT>" + className + "<STR_LIT>" ) ; } } catch ( Exception e ) { log . error ( "<STR_LIT>" + className + "<STR_LIT>" , e ) ; } return null ; } } </s>
|
<s> package org . gatein . wsrp . cxf ; import org . apache . cxf . Bus ; import org . apache . cxf . endpoint . Client ; import org . apache . cxf . endpoint . Server ; import org . apache . cxf . feature . AbstractFeature ; import org . apache . cxf . interceptor . InterceptorProvider ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; public class WSRPEndpointFeature extends AbstractFeature { private static Logger log = LoggerFactory . getLogger ( WSRPEndpointFeature . class ) ; FeatureIntegratorFactory featureIntergrator ; public WSRPEndpointFeature ( ) { log . debug ( "<STR_LIT>" ) ; featureIntergrator = FeatureIntegratorFactory . getInstance ( ) ; } @ Override public void initialize ( Bus bus ) { for ( AbstractFeature feature : featureIntergrator . getFeatures ( ) ) { log . debug ( "<STR_LIT>" + feature . toString ( ) ) ; feature . initialize ( bus ) ; } } @ Override public void initialize ( Client client , Bus bus ) { for ( AbstractFeature feature : featureIntergrator . getFeatures ( ) ) { log . debug ( "<STR_LIT>" + feature . toString ( ) ) ; feature . initialize ( client , bus ) ; } } @ Override public void initialize ( InterceptorProvider interceptorProvider , Bus bus ) { for ( AbstractFeature feature : featureIntergrator . getFeatures ( ) ) { log . debug ( "<STR_LIT>" + feature . toString ( ) ) ; feature . initialize ( interceptorProvider , bus ) ; } } @ Override public void initialize ( Server server , Bus bus ) { for ( AbstractFeature feature : featureIntergrator . getFeatures ( ) ) { log . debug ( "<STR_LIT>" + feature . toString ( ) ) ; feature . initialize ( server , bus ) ; } } } </s>
|
<s> package org . gatein . wsrp . consumer . registry ; import org . chromattic . api . ChromatticBuilder ; import org . gatein . pc . federation . impl . FederatingPortletInvokerService ; import org . gatein . wsrp . jcr . BaseChromatticPersister ; import org . gatein . wsrp . jcr . ChromatticPersister ; import javax . jcr . Node ; import javax . jcr . NodeIterator ; import javax . jcr . Session ; public class JCRConsumerRegistryTestCase extends ConsumerRegistryTestCase { private String workspaceName ; @ Override protected void setUp ( ) throws Exception { final long random = Math . round ( Math . abs ( <NUM_LIT> * Math . random ( ) ) ) ; workspaceName = "<STR_LIT>" + random ; BaseChromatticPersister persister = new BaseChromatticPersister ( workspaceName ) { @ Override protected void setBuilderOptions ( ChromatticBuilder builder ) { builder . setOptionValue ( ChromatticBuilder . ROOT_NODE_PATH , workspaceName ) ; builder . setOptionValue ( ChromatticBuilder . ROOT_NODE_TYPE , "<STR_LIT>" ) ; builder . setOptionValue ( ChromatticBuilder . CREATE_ROOT_NODE , true ) ; } } ; persister . initializeBuilderFor ( JCRConsumerRegistry . mappingClasses ) ; registry = new JCRConsumerRegistry ( persister , false , workspaceName ) ; registry . setFederatingPortletInvoker ( new FederatingPortletInvokerService ( ) ) ; } @ Override protected void tearDown ( ) throws Exception { final ChromatticPersister persister = ( ( JCRConsumerRegistry ) registry ) . getPersister ( ) ; final Session session = persister . getSession ( ) . getJCRSession ( ) ; final Node rootNode = session . getRootNode ( ) ; final NodeIterator nodes = rootNode . getNodes ( ) ; while ( nodes . hasNext ( ) ) { nodes . nextNode ( ) . remove ( ) ; } persister . closeSession ( true ) ; } @ Override public void testStoppingShouldNotStartConsumers ( ) throws Exception { } } </s>
|
<s> package org . gatein . wsrp . registration ; import org . chromattic . api . ChromatticBuilder ; import org . gatein . registration . AbstractRegistrationPersistenceManagerTestCase ; import org . gatein . registration . RegistrationPersistenceManager ; import org . gatein . wsrp . jcr . BaseChromatticPersister ; import org . gatein . wsrp . jcr . ChromatticPersister ; import javax . jcr . Node ; import javax . jcr . NodeIterator ; import javax . jcr . Session ; public class JCRRegistrationPersistenceManagerTestCase extends AbstractRegistrationPersistenceManagerTestCase { JCRRegistrationPersistenceManager persistenceManager ; @ Override public void setUp ( ) throws Exception { super . setUp ( ) ; String workspaceName = "<STR_LIT>" + Math . round ( Math . abs ( <NUM_LIT> * Math . random ( ) ) ) ; BaseChromatticPersister persister = new BaseChromatticPersister ( workspaceName ) { @ Override protected void setBuilderOptions ( ChromatticBuilder builder ) { builder . setOptionValue ( ChromatticBuilder . ROOT_NODE_PATH , workspaceName ) ; builder . setOptionValue ( ChromatticBuilder . ROOT_NODE_TYPE , "<STR_LIT>" ) ; builder . setOptionValue ( ChromatticBuilder . CREATE_ROOT_NODE , true ) ; } } ; persister . initializeBuilderFor ( JCRRegistrationPersistenceManager . mappingClasses ) ; persistenceManager = new JCRRegistrationPersistenceManager ( persister , workspaceName ) ; } @ Override protected void tearDown ( ) throws Exception { final ChromatticPersister persister = persistenceManager . getPersister ( ) ; final Session session = persister . getSession ( ) . getJCRSession ( ) ; final Node rootNode = session . getRootNode ( ) ; final NodeIterator nodes = rootNode . getNodes ( ) ; while ( nodes . hasNext ( ) ) { nodes . nextNode ( ) . remove ( ) ; } persister . closeSession ( true ) ; } @ Override public RegistrationPersistenceManager getManager ( ) throws Exception { return persistenceManager ; } } </s>
|
<s> package org . gatein . wsrp . jcr . mapping ; import junit . framework . TestCase ; import java . util . HashMap ; import java . util . Map ; public class MappedMapTestCase extends TestCase { private MappedMap < String , String > mapped ; public void testInitFrom ( ) { Map < String , String > external = new HashMap < String , String > ( ) ; external . put ( "<STR_LIT:bar>" , "<STR_LIT>" ) ; Map < String , Object > internal = new HashMap < String , Object > ( ) ; internal . put ( "<STR_LIT:foo>" , "<STR_LIT>" ) ; internal . put ( "<STR_LIT:baz>" , "<STR_LIT>" ) ; mapped . initFrom ( external , internal ) ; assertEquals ( "<STR_LIT>" , internal . get ( "<STR_LIT:foo>" ) ) ; assertEquals ( "<STR_LIT>" , internal . get ( "<STR_LIT:bar>" ) ) ; assertNull ( "<STR_LIT>" , internal . get ( "<STR_LIT:baz>" ) ) ; } public void testToExternalMap ( ) { Map < String , Object > internal = new HashMap < String , Object > ( ) ; internal . put ( "<STR_LIT:foo>" , "<STR_LIT>" ) ; internal . put ( "<STR_LIT:baz>" , "<STR_LIT>" ) ; Map < String , String > external = mapped . toExternalMap ( internal ) ; assertNull ( external . get ( "<STR_LIT:foo>" ) ) ; assertEquals ( "<STR_LIT>" , external . get ( "<STR_LIT:baz>" ) ) ; } protected void setUp ( ) throws Exception { super . setUp ( ) ; mapped = new MappedMap < String , String > ( new MappedMap . Converter < String , String > ( ) { public String fromInternal ( String s ) { return s ; } public String toInternal ( String s ) { return s ; } } , new MappedMap . Converter < Object , String > ( ) { public String fromInternal ( Object o ) { return o . toString ( ) ; } public Object toInternal ( String s ) { return s ; } } , "<STR_LIT:foo>" ) ; } } </s>
|
<s> package org . gatein . wsrp . producer . config ; import org . chromattic . api . ChromatticBuilder ; import org . gatein . wsrp . jcr . BaseChromatticPersister ; import java . net . URL ; public class JCRProducerConfigurationServiceTestCase extends ProducerConfigurationTestCase { private JCRProducerConfigurationService service ; @ Override public void setUp ( ) throws Exception { String workspaceName = "<STR_LIT>" + Math . round ( Math . abs ( <NUM_LIT> * Math . random ( ) ) ) ; BaseChromatticPersister persister = new BaseChromatticPersister ( workspaceName ) { @ Override protected void setBuilderOptions ( ChromatticBuilder builder ) { builder . setOptionValue ( ChromatticBuilder . ROOT_NODE_PATH , workspaceName ) ; builder . setOptionValue ( ChromatticBuilder . ROOT_NODE_TYPE , "<STR_LIT>" ) ; builder . setOptionValue ( ChromatticBuilder . CREATE_ROOT_NODE , true ) ; } } ; persister . initializeBuilderFor ( JCRProducerConfigurationService . mappingClasses ) ; service = new JCRProducerConfigurationService ( persister ) ; } @ Override protected ProducerConfiguration getProducerConfiguration ( URL location ) throws Exception { service . setConfigurationIS ( location . openStream ( ) ) ; service . loadConfiguration ( ) ; return service . getConfiguration ( ) ; } } </s>
|
<s> package org . gatein . wsrp . consumer . registry ; import org . chromattic . api . ChromatticSession ; import org . gatein . wsrp . WSRPConsumer ; import org . gatein . wsrp . consumer . ConsumerException ; import org . gatein . wsrp . consumer . ProducerInfo ; import org . gatein . wsrp . consumer . registry . mapping . EndpointInfoMapping ; import org . gatein . wsrp . consumer . registry . mapping . ProducerInfoMapping ; import org . gatein . wsrp . consumer . registry . mapping . ProducerInfosMapping ; import org . gatein . wsrp . consumer . registry . mapping . RegistrationInfoMapping ; import org . gatein . wsrp . consumer . registry . mapping . RegistrationPropertyMapping ; import org . gatein . wsrp . consumer . registry . xml . XMLConsumerRegistry ; import org . gatein . wsrp . jcr . ChromatticPersister ; import org . gatein . wsrp . jcr . StoresByPathManager ; import org . gatein . wsrp . jcr . mapping . mixins . LastModified ; import org . gatein . wsrp . jcr . mapping . mixins . ModifyRegistrationRequired ; import org . gatein . wsrp . jcr . mapping . mixins . WSSEndpointEnabled ; import org . gatein . wsrp . registration . mapping . RegistrationPropertyDescriptionMapping ; import javax . jcr . RepositoryException ; import javax . jcr . Session ; import javax . jcr . Value ; import javax . jcr . query . Query ; import javax . jcr . query . QueryResult ; import javax . jcr . query . Row ; import javax . jcr . query . RowIterator ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; public class JCRConsumerRegistry extends AbstractConsumerRegistry implements StoresByPathManager < ProducerInfo > { private ChromatticPersister persister ; private boolean loadFromXMLIfNeeded ; private final String rootNodePath ; static final String PRODUCER_INFOS_PATH = ProducerInfosMapping . NODE_NAME ; public static final List < Class > mappingClasses = new ArrayList < Class > ( <NUM_LIT:6> ) ; private InputStream configurationIS ; static { Collections . addAll ( mappingClasses , ProducerInfosMapping . class , ProducerInfoMapping . class , EndpointInfoMapping . class , RegistrationInfoMapping . class , RegistrationPropertyMapping . class , RegistrationPropertyDescriptionMapping . class , LastModified . class , ModifyRegistrationRequired . class , WSSEndpointEnabled . class ) ; } public JCRConsumerRegistry ( ChromatticPersister persister ) throws Exception { this ( persister , true ) ; } protected JCRConsumerRegistry ( ChromatticPersister persister , boolean loadFromXMLIfNeeded ) { this ( persister , loadFromXMLIfNeeded , "<STR_LIT:/>" ) ; } protected JCRConsumerRegistry ( ChromatticPersister persister , boolean loadFromXMLIfNeeded , String rootNodePath ) { this . persister = persister ; this . loadFromXMLIfNeeded = loadFromXMLIfNeeded ; this . rootNodePath = rootNodePath . endsWith ( "<STR_LIT:/>" ) ? rootNodePath : rootNodePath + "<STR_LIT:/>" ; initConsumerCache ( ) ; } @ Override protected void initConsumerCache ( ) { setConsumerCache ( new InMemoryConsumerCache ( this ) ) ; } public void setConfigurationIS ( InputStream is ) { this . configurationIS = is ; } public void save ( ProducerInfo info , String messageOnError ) { try { ChromatticSession session = persister . getSession ( ) ; final long now = System . currentTimeMillis ( ) ; ProducerInfosMapping pims = getProducerInfosMapping ( session ) ; pims . setLastModified ( now ) ; ProducerInfoMapping pim = pims . createProducerInfo ( info . getId ( ) ) ; String key = session . persist ( pims , pim , info . getId ( ) ) ; info . setKey ( key ) ; info . setLastModified ( now ) ; pim . initFrom ( info ) ; persister . closeSession ( true ) ; } catch ( Exception e ) { persister . closeSession ( false ) ; throw new ConsumerException ( messageOnError , e ) ; } } public void delete ( ProducerInfo info ) { if ( ! persister . delete ( info , this ) ) { throw new ConsumerException ( "<STR_LIT>" + info ) ; } } public String update ( ProducerInfo producerInfo ) { String key = producerInfo . getKey ( ) ; if ( key == null ) { throw new IllegalArgumentException ( "<STR_LIT>" + producerInfo . getId ( ) + "<STR_LIT>" ) ; } String oldId ; String newId ; boolean idUnchanged ; ChromatticSession session = persister . getSession ( ) ; final long now = System . currentTimeMillis ( ) ; ProducerInfoMapping pim = session . findById ( ProducerInfoMapping . class , key ) ; if ( pim == null ) { throw new IllegalArgumentException ( "<STR_LIT>" + key ) ; } oldId = pim . getId ( ) ; newId = producerInfo . getId ( ) ; producerInfo . setLastModified ( now ) ; pim . initFrom ( producerInfo ) ; idUnchanged = oldId . equals ( newId ) ; ProducerInfosMapping pims = getProducerInfosMapping ( session ) ; pims . setLastModified ( now ) ; if ( ! idUnchanged ) { Map < String , ProducerInfoMapping > nameToProducerInfoMap = pims . getNameToProducerInfoMap ( ) ; nameToProducerInfoMap . put ( pim . getId ( ) , pim ) ; } persister . closeSession ( true ) ; return idUnchanged ? null : oldId ; } public Iterator < ProducerInfo > getProducerInfosFromStorage ( ) { ChromatticSession session = persister . getSession ( ) ; try { List < ProducerInfoMapping > pims = getProducerInfosMapping ( session ) . getProducerInfos ( ) ; List < ProducerInfo > infos = new ArrayList < ProducerInfo > ( pims . size ( ) ) ; for ( ProducerInfoMapping pim : pims ) { infos . add ( pim . toModel ( null , this ) ) ; } return infos . iterator ( ) ; } finally { persister . closeSession ( false ) ; } } public ProducerInfo loadProducerInfo ( String id ) { try { ChromatticSession session = persister . getSession ( ) ; ProducerInfoMapping pim = getProducerInfoMapping ( id , session ) ; if ( pim != null ) { return pim . toModel ( null , this ) ; } else { return null ; } } finally { persister . closeSession ( false ) ; } } @ Override public long getPersistedLastModifiedForProducerInfoWith ( String id ) { try { ChromatticSession session = persister . getSession ( ) ; ProducerInfoMapping pim = getProducerInfoMapping ( id , session ) ; if ( pim != null ) { return pim . getLastModified ( ) ; } else { log . debug ( "<STR_LIT>" + id + "<STR_LIT>" ) ; return Long . MIN_VALUE ; } } finally { persister . closeSession ( false ) ; } } private ProducerInfoMapping getProducerInfoMapping ( String id , ChromatticSession session ) { return session . findByPath ( ProducerInfoMapping . class , getPathFor ( id ) ) ; } @ Override public boolean containsConsumer ( String id ) { ChromatticSession session = persister . getSession ( ) ; try { return session . getJCRSession ( ) . itemExists ( rootNodePath + getPathFor ( id ) ) ; } catch ( RepositoryException e ) { throw new RuntimeException ( e ) ; } finally { persister . closeSession ( false ) ; } } public Collection < String > getConfiguredConsumersIds ( ) { ChromatticSession session = persister . getSession ( ) ; try { final RowIterator rows = getProducerInfoIds ( session ) ; final long size = rows . getSize ( ) ; if ( size == <NUM_LIT:0> ) { return Collections . emptyList ( ) ; } else { List < String > ids = new ArrayList < String > ( size != - <NUM_LIT:1> ? ( int ) size : <NUM_LIT:7> ) ; while ( rows . hasNext ( ) ) { final Row row = rows . nextRow ( ) ; final Value rowValue = row . getValue ( "<STR_LIT>" ) ; ids . add ( rowValue . getString ( ) ) ; } return ids ; } } catch ( RepositoryException e ) { throw new RuntimeException ( e ) ; } finally { persister . closeSession ( false ) ; } } private RowIterator getProducerInfoIds ( ChromatticSession session ) throws RepositoryException { final Session jcrSession = session . getJCRSession ( ) ; final Query query = jcrSession . getWorkspace ( ) . getQueryManager ( ) . createQuery ( "<STR_LIT>" , Query . SQL ) ; final QueryResult queryResult = query . execute ( ) ; return queryResult . getRows ( ) ; } @ Override public int getConfiguredConsumerNumber ( ) { ChromatticSession session = persister . getSession ( ) ; try { final RowIterator ids = getProducerInfoIds ( session ) ; return ( int ) ids . getSize ( ) ; } catch ( RepositoryException e ) { throw new RuntimeException ( e ) ; } finally { persister . closeSession ( false ) ; } } private ProducerInfosMapping getProducerInfosMapping ( ChromatticSession session ) { ProducerInfosMapping producerInfosMapping = session . findByPath ( ProducerInfosMapping . class , PRODUCER_INFOS_PATH ) ; if ( producerInfosMapping == null ) { producerInfosMapping = session . insert ( ProducerInfosMapping . class , ProducerInfosMapping . NODE_NAME ) ; if ( loadFromXMLIfNeeded ) { XMLConsumerRegistry fromXML = new XMLConsumerRegistry ( configurationIS ) ; fromXML . reloadConsumers ( ) ; List < ProducerInfoMapping > infos = producerInfosMapping . getProducerInfos ( ) ; List < WSRPConsumer > xmlConsumers = fromXML . getConfiguredConsumers ( ) ; for ( WSRPConsumer consumer : xmlConsumers ) { ProducerInfo info = consumer . getProducerInfo ( ) ; ProducerInfoMapping pim = producerInfosMapping . createProducerInfo ( info . getId ( ) ) ; infos . add ( pim ) ; pim . initFrom ( info ) ; info . setKey ( pim . getKey ( ) ) ; consumerCache . putConsumer ( info . getId ( ) , consumer ) ; } producerInfosMapping . setLastModified ( System . currentTimeMillis ( ) ) ; session . save ( ) ; } } return producerInfosMapping ; } public String getChildPath ( ProducerInfo needsComputedPath ) { return getPathFor ( needsComputedPath ) ; } public LastModified lastModifiedToUpdateOnDelete ( ChromatticSession session ) { final ProducerInfosMapping pims = session . findByPath ( ProducerInfosMapping . class , PRODUCER_INFOS_PATH ) ; if ( pims != null ) { return pims . getLastModifiedMixin ( ) ; } else { return null ; } } private static String getPathFor ( ProducerInfo info ) { return getPathFor ( info . getId ( ) ) ; } private static String getPathFor ( final String producerInfoId ) { return PRODUCER_INFOS_PATH + "<STR_LIT:/>" + producerInfoId ; } private static ProducerInfoMapping toProducerInfoMapping ( ProducerInfo producerInfo , ChromatticSession session ) { ProducerInfoMapping pim = session . findById ( ProducerInfoMapping . class , producerInfo . getKey ( ) ) ; if ( pim == null ) { pim = session . insert ( ProducerInfoMapping . class , getPathFor ( producerInfo ) ) ; } pim . initFrom ( producerInfo ) ; return pim ; } ChromatticPersister getPersister ( ) { return persister ; } } </s>
|
<s> package org . gatein . wsrp . consumer . registry . mapping ; import org . chromattic . api . RelationshipType ; import org . chromattic . api . annotations . Create ; import org . chromattic . api . annotations . OneToOne ; import org . chromattic . api . annotations . Owner ; import org . chromattic . api . annotations . PrimaryType ; import org . chromattic . api . annotations . Property ; import org . gatein . wsrp . consumer . EndpointConfigurationInfo ; import org . gatein . wsrp . consumer . ProducerInfo ; import org . gatein . wsrp . jcr . mapping . BaseMapping ; import org . gatein . wsrp . jcr . mapping . mixins . MixinHolder ; import org . gatein . wsrp . jcr . mapping . mixins . WSSEndpointEnabled ; @ PrimaryType ( name = EndpointInfoMapping . NODE_NAME ) public abstract class EndpointInfoMapping extends MixinHolder < WSSEndpointEnabled > implements BaseMapping < EndpointConfigurationInfo , ProducerInfo > { public static final String NODE_NAME = "<STR_LIT>" ; @ Property ( name = "<STR_LIT>" ) public abstract String getWSDLURL ( ) ; public abstract void setWSDLURL ( String wsdlURL ) ; @ Property ( name = "<STR_LIT>" ) public abstract Integer getWSTimeoutMilliseconds ( ) ; public abstract void setWSTimeoutMilliseconds ( Integer expiration ) ; @ OneToOne ( type = RelationshipType . EMBEDDED ) @ Owner public abstract WSSEndpointEnabled getWSSEndpointEnabledMixin ( ) ; protected abstract void setWSSEndpointEnabledMixin ( WSSEndpointEnabled mixin ) ; @ Create protected abstract WSSEndpointEnabled createWSSEndpointEnabledMixin ( ) ; public void setWSSEnabled ( boolean wssEnabled ) { getCreatedMixin ( ) . setWSSEnabled ( wssEnabled ) ; } public boolean isWSSEnabled ( ) { return getCreatedMixin ( ) . getWSSEnabled ( ) ; } public void initFrom ( EndpointConfigurationInfo info ) { setWSDLURL ( info . getWsdlDefinitionURL ( ) ) ; setWSTimeoutMilliseconds ( info . getWSOperationTimeOut ( ) ) ; setWSSEnabled ( info . getWSSEnabled ( ) ) ; } public EndpointConfigurationInfo toModel ( EndpointConfigurationInfo initial , ProducerInfo registry ) { initial . setWsdlDefinitionURL ( getWSDLURL ( ) ) ; initial . setWSOperationTimeOut ( getWSTimeoutMilliseconds ( ) ) ; initial . setWSSEnabled ( isWSSEnabled ( ) ) ; return initial ; } public Class < EndpointConfigurationInfo > getModelClass ( ) { return EndpointConfigurationInfo . class ; } @ Override public WSSEndpointEnabled getMixin ( ) { return getWSSEndpointEnabledMixin ( ) ; } @ Override protected void setMixin ( WSSEndpointEnabled mixin ) { setWSSEndpointEnabledMixin ( mixin ) ; } @ Override protected WSSEndpointEnabled createMixin ( ) { return createWSSEndpointEnabledMixin ( ) ; } } </s>
|
<s> package org . gatein . wsrp . consumer . registry . mapping ; import org . chromattic . api . annotations . Create ; import org . chromattic . api . annotations . MappedBy ; import org . chromattic . api . annotations . OneToOne ; import org . chromattic . api . annotations . Owner ; import org . chromattic . api . annotations . PrimaryType ; import org . chromattic . api . annotations . Property ; import org . gatein . wsrp . consumer . RegistrationProperty ; import org . gatein . wsrp . registration . RegistrationPropertyDescription ; import org . gatein . wsrp . registration . mapping . RegistrationPropertyDescriptionMapping ; @ PrimaryType ( name = RegistrationPropertyMapping . NODE_NAME ) public abstract class RegistrationPropertyMapping { public static final String NODE_NAME = "<STR_LIT>" ; @ Property ( name = "<STR_LIT:name>" ) public abstract String getName ( ) ; public abstract void setName ( String name ) ; @ Property ( name = "<STR_LIT:value>" ) public abstract String getValue ( ) ; public abstract void setValue ( String value ) ; @ OneToOne @ Owner @ MappedBy ( "<STR_LIT:description>" ) public abstract RegistrationPropertyDescriptionMapping getDescription ( ) ; public abstract void setDescription ( RegistrationPropertyDescriptionMapping rpdm ) ; @ Create public abstract RegistrationPropertyDescriptionMapping createDescription ( ) ; @ Property ( name = "<STR_LIT:status>" ) public abstract RegistrationProperty . Status getStatus ( ) ; public abstract void setStatus ( RegistrationProperty . Status status ) ; public void initFrom ( RegistrationProperty property ) { setName ( property . getName ( ) . toString ( ) ) ; setStatus ( property . getStatus ( ) ) ; setValue ( property . getValue ( ) ) ; RegistrationPropertyDescription desc = property . getDescription ( ) ; if ( desc != null ) { RegistrationPropertyDescriptionMapping rpdm = createDescription ( ) ; setDescription ( rpdm ) ; rpdm . initFrom ( desc ) ; } } } </s>
|
<s> package org . gatein . wsrp . consumer . registry . mapping ; import org . chromattic . api . annotations . Create ; import org . chromattic . api . annotations . FormattedBy ; import org . chromattic . api . annotations . OneToMany ; import org . chromattic . api . annotations . PrimaryType ; import org . chromattic . api . annotations . Property ; import org . gatein . common . io . IOTools ; import org . gatein . wsrp . consumer . ProducerInfo ; import org . gatein . wsrp . consumer . RegistrationInfo ; import org . gatein . wsrp . consumer . RegistrationProperty ; import org . gatein . wsrp . jcr . ChromatticPersister ; import org . gatein . wsrp . jcr . mapping . BaseMapping ; import org . gatein . wsrp . registration . RegistrationPropertyDescription ; import org . gatein . wsrp . registration . mapping . RegistrationPropertyDescriptionMapping ; import java . io . ByteArrayInputStream ; import java . io . InputStream ; import java . util . List ; @ PrimaryType ( name = RegistrationInfoMapping . NODE_NAME ) @ FormattedBy ( ChromatticPersister . QNameFormatter . class ) public abstract class RegistrationInfoMapping implements BaseMapping < RegistrationInfo , ProducerInfo > { public static final String NODE_NAME = "<STR_LIT>" ; @ Property ( name = "<STR_LIT>" ) public abstract String getConsumerName ( ) ; public abstract void setConsumerName ( String name ) ; @ Property ( name = "<STR_LIT>" ) public abstract String getRegistrationHandle ( ) ; public abstract void setRegistrationHandle ( String handle ) ; @ Property ( name = "<STR_LIT:state>" ) public abstract InputStream getRegistrationState ( ) ; public abstract void setRegistrationState ( InputStream state ) ; @ OneToMany public abstract List < RegistrationPropertyMapping > getRegistrationProperties ( ) ; @ Create public abstract RegistrationPropertyMapping createRegistrationProperty ( String propertyName ) ; public void initFrom ( RegistrationInfo regInfo ) { setConsumerName ( regInfo . getConsumerName ( ) ) ; setRegistrationHandle ( regInfo . getRegistrationHandle ( ) ) ; byte [ ] bytes = regInfo . getRegistrationState ( ) ; if ( bytes != null && bytes . length > <NUM_LIT:0> ) { ByteArrayInputStream is = new ByteArrayInputStream ( bytes ) ; setRegistrationState ( is ) ; } List < RegistrationPropertyMapping > rpms = getRegistrationProperties ( ) ; rpms . clear ( ) ; for ( RegistrationProperty property : regInfo . getRegistrationProperties ( ) . values ( ) ) { RegistrationPropertyMapping rpm = createRegistrationProperty ( property . getName ( ) . toString ( ) ) ; rpms . add ( rpm ) ; rpm . initFrom ( property ) ; } } public RegistrationInfo toModel ( RegistrationInfo initial , ProducerInfo registry ) { initial . setConsumerName ( getConsumerName ( ) ) ; initial . setRegistrationHandle ( getRegistrationHandle ( ) ) ; initial . setRegistrationState ( IOTools . safeGetBytes ( getRegistrationState ( ) ) ) ; for ( RegistrationPropertyMapping rpm : getRegistrationProperties ( ) ) { RegistrationProperty prop = initial . setRegistrationPropertyValue ( rpm . getName ( ) , rpm . getValue ( ) ) ; RegistrationPropertyDescriptionMapping rpdm = rpm . getDescription ( ) ; if ( rpdm != null ) { RegistrationPropertyDescription desc = rpdm . toRegistrationPropertyDescription ( ) ; prop . setDescription ( desc ) ; } prop . setStatus ( rpm . getStatus ( ) ) ; prop . setListener ( initial ) ; } return initial ; } public Class < RegistrationInfo > getModelClass ( ) { return RegistrationInfo . class ; } } </s>
|
<s> package org . gatein . wsrp . consumer . registry . mapping ; import org . chromattic . api . RelationshipType ; import org . chromattic . api . annotations . Create ; import org . chromattic . api . annotations . DefaultValue ; import org . chromattic . api . annotations . Id ; import org . chromattic . api . annotations . MappedBy ; import org . chromattic . api . annotations . OneToOne ; import org . chromattic . api . annotations . Owner ; import org . chromattic . api . annotations . PrimaryType ; import org . chromattic . api . annotations . Property ; import org . gatein . wsrp . consumer . EndpointConfigurationInfo ; import org . gatein . wsrp . consumer . ProducerInfo ; import org . gatein . wsrp . consumer . RegistrationInfo ; import org . gatein . wsrp . consumer . spi . ConsumerRegistrySPI ; import org . gatein . wsrp . jcr . mapping . BaseMapping ; import org . gatein . wsrp . jcr . mapping . mixins . LastModifiedMixinHolder ; import org . gatein . wsrp . jcr . mapping . mixins . ModifyRegistrationRequired ; @ PrimaryType ( name = ProducerInfoMapping . NODE_NAME ) public abstract class ProducerInfoMapping extends LastModifiedMixinHolder implements BaseMapping < ProducerInfo , ConsumerRegistrySPI > { public static final String NODE_NAME = "<STR_LIT>" ; @ OneToOne @ Owner @ MappedBy ( "<STR_LIT>" ) public abstract EndpointInfoMapping getEndpointInfo ( ) ; @ OneToOne @ Owner @ MappedBy ( "<STR_LIT>" ) public abstract RegistrationInfoMapping getRegistrationInfo ( ) ; @ Property ( name = "<STR_LIT>" ) public abstract String getId ( ) ; public abstract void setId ( String id ) ; @ Property ( name = "<STR_LIT>" ) public abstract Integer getExpirationCacheSeconds ( ) ; public abstract void setExpirationCacheSeconds ( Integer expiration ) ; @ Property ( name = "<STR_LIT>" ) @ DefaultValue ( "<STR_LIT:false>" ) public abstract boolean getActive ( ) ; public abstract void setActive ( boolean active ) ; @ Id public abstract String getKey ( ) ; @ OneToOne ( type = RelationshipType . EMBEDDED ) @ Owner public abstract ModifyRegistrationRequired getModifyRegistrationRequiredMixin ( ) ; protected abstract void setModifyRegistrationRequiredMixin ( ModifyRegistrationRequired mmr ) ; @ Create protected abstract ModifyRegistrationRequired createModifyRegistrationRequiredMixin ( ) ; public void setModifyRegistrationRequired ( boolean modifyRegistrationRequired ) { getCreatedModifyRegistrationRequiredMixin ( ) . setModifyRegistrationRequired ( modifyRegistrationRequired ) ; } public boolean getModifyRegistrationRequired ( ) { return getCreatedModifyRegistrationRequiredMixin ( ) . isModifyRegistrationRequired ( ) ; } public void initFrom ( ProducerInfo producerInfo ) { setActive ( producerInfo . isActive ( ) ) ; setExpirationCacheSeconds ( producerInfo . getExpirationCacheSeconds ( ) ) ; setId ( producerInfo . getId ( ) ) ; setLastModified ( producerInfo . getLastModified ( ) ) ; setModifyRegistrationRequired ( producerInfo . isModifyRegistrationRequired ( ) ) ; EndpointInfoMapping eim = getEndpointInfo ( ) ; eim . initFrom ( producerInfo . getEndpointConfigurationInfo ( ) ) ; RegistrationInfoMapping rim = getRegistrationInfo ( ) ; RegistrationInfo regInfo = producerInfo . getRegistrationInfo ( ) ; rim . initFrom ( regInfo ) ; } public ProducerInfo toModel ( ProducerInfo initial , ConsumerRegistrySPI registry ) { ProducerInfo info = initial ; if ( initial == null ) { info = new ProducerInfo ( registry ) ; } info . setKey ( getKey ( ) ) ; info . setId ( getId ( ) ) ; info . setActive ( getActive ( ) ) ; info . setExpirationCacheSeconds ( getExpirationCacheSeconds ( ) ) ; info . setLastModified ( getLastModified ( ) ) ; info . setModifyRegistrationRequired ( getModifyRegistrationRequired ( ) ) ; EndpointConfigurationInfo endInfo = getEndpointInfo ( ) . toModel ( info . getEndpointConfigurationInfo ( ) , info ) ; info . setEndpointConfigurationInfo ( endInfo ) ; RegistrationInfo regInfo = getRegistrationInfo ( ) . toModel ( info . getRegistrationInfo ( ) , info ) ; info . setRegistrationInfo ( regInfo ) ; return info ; } public Class < ProducerInfo > getModelClass ( ) { return ProducerInfo . class ; } private ModifyRegistrationRequired getCreatedModifyRegistrationRequiredMixin ( ) { ModifyRegistrationRequired mmr = getModifyRegistrationRequiredMixin ( ) ; if ( mmr == null ) { mmr = createModifyRegistrationRequiredMixin ( ) ; setModifyRegistrationRequiredMixin ( mmr ) ; mmr . initializeValue ( ) ; } return mmr ; } } </s>
|
<s> package org . gatein . wsrp . consumer . registry . mapping ; import org . chromattic . api . annotations . Create ; import org . chromattic . api . annotations . OneToMany ; import org . chromattic . api . annotations . PrimaryType ; import org . gatein . wsrp . jcr . mapping . mixins . LastModifiedMixinHolder ; import java . util . List ; import java . util . Map ; @ PrimaryType ( name = ProducerInfosMapping . NODE_NAME ) public abstract class ProducerInfosMapping extends LastModifiedMixinHolder { public static final String NODE_NAME = "<STR_LIT>" ; @ OneToMany public abstract List < ProducerInfoMapping > getProducerInfos ( ) ; @ OneToMany public abstract Map < String , ProducerInfoMapping > getNameToProducerInfoMap ( ) ; @ Create public abstract ProducerInfoMapping createProducerInfo ( String producerId ) ; } </s>
|
<s> package org . gatein . wsrp . consumer . migration . mapping ; import org . chromattic . api . annotations . Create ; import org . chromattic . api . annotations . OneToMany ; import org . chromattic . api . annotations . PrimaryType ; import java . util . List ; @ PrimaryType ( name = ExportInfosMapping . NODE_NAME ) public abstract class ExportInfosMapping { public static final String NODE_NAME = "<STR_LIT>" ; @ OneToMany public abstract List < ExportInfoMapping > getExportInfos ( ) ; @ Create public abstract ExportInfoMapping createExportInfo ( String exportTimeAsString ) ; } </s>
|
<s> package org . gatein . wsrp . consumer . migration . mapping ; import org . chromattic . api . annotations . PrimaryType ; import org . chromattic . api . annotations . Property ; import org . gatein . common . util . ParameterValidation ; import javax . xml . namespace . QName ; import java . util . Arrays ; import java . util . List ; @ PrimaryType ( name = ExportErrorMapping . NODE_NAME ) public abstract class ExportErrorMapping { public static final String NODE_NAME = "<STR_LIT>" ; private static final String COMMA = "<STR_LIT:U+002C>" ; @ Property ( name = "<STR_LIT>" ) public abstract String getCode ( ) ; public abstract void setCode ( String code ) ; @ Property ( name = "<STR_LIT>" ) public abstract String getHandles ( ) ; public abstract void setHandles ( String handles ) ; public QName getErrorCode ( ) { return QName . valueOf ( getCode ( ) ) ; } public List < String > getPortletHandles ( ) { return Arrays . asList ( getHandles ( ) . split ( COMMA ) ) ; } public void initFrom ( QName errorCode , List < String > handles ) { setCode ( errorCode . toString ( ) ) ; if ( ParameterValidation . existsAndIsNotEmpty ( handles ) ) { StringBuilder sb = new StringBuilder ( ) ; int size = handles . size ( ) ; int index = <NUM_LIT:0> ; for ( String handle : handles ) { sb . append ( handle ) ; if ( index ++ < size ) { sb . append ( COMMA ) ; } } setHandles ( sb . toString ( ) ) ; } } } </s>
|
<s> package org . gatein . wsrp . consumer . migration . mapping ; import org . chromattic . api . annotations . Create ; import org . chromattic . api . annotations . OneToMany ; import org . chromattic . api . annotations . PrimaryType ; import org . chromattic . api . annotations . Property ; import org . gatein . common . io . IOTools ; import org . gatein . wsrp . consumer . migration . ExportInfo ; import org . gatein . wsrp . jcr . ChromatticPersister ; import org . gatein . wsrp . jcr . mapping . BaseMapping ; import javax . xml . namespace . QName ; import java . io . ByteArrayInputStream ; import java . io . InputStream ; import java . util . List ; import java . util . Map ; import java . util . SortedMap ; import java . util . TreeMap ; @ PrimaryType ( name = ExportInfoMapping . NODE_NAME ) public abstract class ExportInfoMapping implements BaseMapping < ExportInfo , Object > { public static final String NODE_NAME = "<STR_LIT>" ; @ Property ( name = "<STR_LIT>" ) public abstract long getExportTime ( ) ; public abstract void setExportTime ( long exportTime ) ; @ Property ( name = "<STR_LIT>" ) public abstract long getExpirationTime ( ) ; public abstract void setExpirationTime ( long expirationTime ) ; @ Property ( name = "<STR_LIT>" ) public abstract InputStream getExportContext ( ) ; public abstract void setExportContext ( InputStream exportContext ) ; @ OneToMany public abstract List < ExportedStateMapping > getExportedStates ( ) ; @ Create public abstract ExportedStateMapping internalCreateExportedState ( String portletHandle ) ; public ExportedStateMapping createExportedState ( String portletHandle ) { return internalCreateExportedState ( ChromatticPersister . PortletNameFormatter . encode ( portletHandle ) ) ; } @ OneToMany protected abstract List < ExportErrorMapping > getErrors ( ) ; @ Create public abstract ExportErrorMapping internalCreateError ( String errorCode ) ; public ExportErrorMapping createError ( String errorCode ) { return internalCreateError ( ChromatticPersister . QNameFormatter . encode ( errorCode ) ) ; } public void initFrom ( ExportInfo exportInfo ) { setExportTime ( exportInfo . getExportTime ( ) ) ; setExpirationTime ( exportInfo . getExpirationTime ( ) ) ; byte [ ] exportContext = exportInfo . getExportContext ( ) ; if ( exportContext != null && exportContext . length > <NUM_LIT:0> ) { ByteArrayInputStream is = new ByteArrayInputStream ( exportContext ) ; setExportContext ( is ) ; } List < ExportedStateMapping > exportedStates = getExportedStates ( ) ; exportedStates . clear ( ) ; for ( String handle : exportInfo . getExportedPortletHandles ( ) ) { ExportedStateMapping exportedState = createExportedState ( handle ) ; exportedStates . add ( exportedState ) ; exportedState . initFrom ( handle , exportInfo . getPortletStateFor ( handle ) ) ; } List < ExportErrorMapping > errors = getErrors ( ) ; errors . clear ( ) ; for ( Map . Entry < QName , List < String > > entry : exportInfo . getErrorCodesToFailedPortletHandlesMapping ( ) . entrySet ( ) ) { QName errorCode = entry . getKey ( ) ; ExportErrorMapping error = createError ( errorCode . toString ( ) ) ; errors . add ( error ) ; error . initFrom ( errorCode , entry . getValue ( ) ) ; } } public ExportInfo toModel ( ExportInfo initial , Object registry ) { List < ExportedStateMapping > exportedStates = getExportedStates ( ) ; SortedMap < String , byte [ ] > states = new TreeMap < String , byte [ ] > ( ) ; for ( ExportedStateMapping exportedState : exportedStates ) { states . put ( ChromatticPersister . PortletNameFormatter . decode ( exportedState . getHandle ( ) ) , IOTools . safeGetBytes ( exportedState . getState ( ) ) ) ; } List < ExportErrorMapping > errors = getErrors ( ) ; SortedMap < QName , List < String > > errorCodesToHandles = new TreeMap < QName , List < String > > ( ) ; for ( ExportErrorMapping error : errors ) { errorCodesToHandles . put ( error . getErrorCode ( ) , error . getPortletHandles ( ) ) ; } return new ExportInfo ( getExportTime ( ) , errorCodesToHandles , states , IOTools . safeGetBytes ( getExportContext ( ) ) ) ; } public Class < ExportInfo > getModelClass ( ) { return ExportInfo . class ; } } </s>
|
<s> package org . gatein . wsrp . consumer . migration . mapping ; import org . chromattic . api . annotations . PrimaryType ; import org . chromattic . api . annotations . Property ; import java . io . ByteArrayInputStream ; import java . io . InputStream ; @ PrimaryType ( name = ExportedStateMapping . NODE_NAME ) public abstract class ExportedStateMapping { public static final String NODE_NAME = "<STR_LIT>" ; @ Property ( name = "<STR_LIT>" ) public abstract String getHandle ( ) ; public abstract void setHandle ( String handle ) ; @ Property ( name = "<STR_LIT:state>" ) public abstract InputStream getState ( ) ; public abstract void setState ( InputStream state ) ; public void initFrom ( String handle , byte [ ] state ) { setHandle ( handle ) ; if ( state != null && state . length > <NUM_LIT:0> ) { ByteArrayInputStream is = new ByteArrayInputStream ( state ) ; setState ( is ) ; } } } </s>
|
<s> package org . gatein . wsrp . consumer . migration ; import org . chromattic . api . ChromatticSession ; import org . gatein . common . util . ParameterValidation ; import org . gatein . wsrp . api . context . ConsumerStructureProvider ; import org . gatein . wsrp . consumer . migration . mapping . ExportErrorMapping ; import org . gatein . wsrp . consumer . migration . mapping . ExportInfoMapping ; import org . gatein . wsrp . consumer . migration . mapping . ExportInfosMapping ; import org . gatein . wsrp . consumer . migration . mapping . ExportedStateMapping ; import org . gatein . wsrp . jcr . ChromatticPersister ; import org . gatein . wsrp . jcr . StoresByPathManager ; import org . gatein . wsrp . jcr . mapping . mixins . LastModified ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; public class JCRMigrationService implements MigrationService , StoresByPathManager < ExportInfo > { private ConsumerStructureProvider structureProvider ; private ChromatticPersister persister ; private static final String EXPORT_INFOS_PATH = ExportInfosMapping . NODE_NAME ; private int exportInfosCount = - <NUM_LIT:1> ; public static final List < Class > mappingClasses = new ArrayList < Class > ( <NUM_LIT:4> ) ; static { Collections . addAll ( mappingClasses , ExportInfosMapping . class , ExportInfoMapping . class , ExportedStateMapping . class , ExportErrorMapping . class ) ; } public JCRMigrationService ( ChromatticPersister persister ) throws Exception { this . persister = persister ; } public ConsumerStructureProvider getStructureProvider ( ) { return structureProvider ; } public void setStructureProvider ( ConsumerStructureProvider structureProvider ) { ParameterValidation . throwIllegalArgExceptionIfNull ( structureProvider , "<STR_LIT>" ) ; this . structureProvider = structureProvider ; } public List < ExportInfo > getAvailableExportInfos ( ) { ChromatticSession session = persister . getSession ( ) ; ExportInfosMapping exportInfosMapping = getExportInfosMapping ( session ) ; List < ExportInfoMapping > exportInfoMappings = exportInfosMapping . getExportInfos ( ) ; List < ExportInfo > exportInfos = new ArrayList < ExportInfo > ( exportInfoMappings . size ( ) ) ; for ( ExportInfoMapping eim : exportInfoMappings ) { exportInfos . add ( eim . toModel ( null , null ) ) ; } persister . closeSession ( false ) ; exportInfosCount = exportInfos . size ( ) ; return exportInfos ; } private ExportInfosMapping getExportInfosMapping ( ChromatticSession session ) { ExportInfosMapping exportInfosMapping = session . findByPath ( ExportInfosMapping . class , ExportInfosMapping . NODE_NAME ) ; if ( exportInfosMapping == null ) { exportInfosMapping = session . insert ( ExportInfosMapping . class , ExportInfosMapping . NODE_NAME ) ; exportInfosCount = <NUM_LIT:0> ; } return exportInfosMapping ; } public ExportInfo getExportInfo ( long exportTime ) { ChromatticSession session = persister . getSession ( ) ; ExportInfoMapping eim = session . findByPath ( ExportInfoMapping . class , getPathFor ( exportTime ) ) ; try { if ( eim != null ) { return eim . toModel ( null , null ) ; } else { return null ; } } finally { persister . closeSession ( false ) ; } } public void add ( ExportInfo info ) { ChromatticSession session = persister . getSession ( ) ; ExportInfoMapping eim = session . findByPath ( ExportInfoMapping . class , getChildPath ( info ) ) ; long exportTime = info . getExportTime ( ) ; if ( eim != null ) { persister . closeSession ( false ) ; throw new IllegalArgumentException ( "<STR_LIT>" + exportTime + "<STR_LIT>" ) ; } else { ExportInfosMapping exportInfosMapping = getExportInfosMapping ( session ) ; String exportTimeAsString = "<STR_LIT>" + exportTime ; ExportInfoMapping exportInfo = exportInfosMapping . createExportInfo ( exportTimeAsString ) ; session . persist ( exportInfosMapping , exportInfo , exportTimeAsString ) ; exportInfo . initFrom ( info ) ; persister . closeSession ( true ) ; exportInfosCount ++ ; } } public ExportInfo remove ( ExportInfo info ) { if ( persister . delete ( info , this ) ) { exportInfosCount -- ; return info ; } else { return null ; } } public boolean isAvailableExportInfosEmpty ( ) { if ( exportInfosCount == - <NUM_LIT:1> ) { ChromatticSession session = persister . getSession ( ) ; ExportInfosMapping mappings = getExportInfosMapping ( session ) ; exportInfosCount = mappings . getExportInfos ( ) . size ( ) ; persister . closeSession ( false ) ; } return exportInfosCount == <NUM_LIT:0> ; } public String getParentPath ( ) { return EXPORT_INFOS_PATH ; } public String getChildPath ( ExportInfo exportInfo ) { return getPathFor ( exportInfo . getExportTime ( ) ) ; } public LastModified lastModifiedToUpdateOnDelete ( ChromatticSession session ) { return null ; } private String getPathFor ( final long exportTime ) { return getParentPath ( ) + "<STR_LIT:/>" + exportTime ; } } </s>
|
<s> package org . gatein . wsrp . registration ; import org . chromattic . api . ChromatticSession ; import org . gatein . common . util . ParameterValidation ; import org . gatein . registration . Consumer ; import org . gatein . registration . ConsumerGroup ; import org . gatein . registration . Registration ; import org . gatein . registration . RegistrationException ; import org . gatein . registration . impl . AbstractRegistrationPersistenceManager ; import org . gatein . registration . spi . ConsumerGroupSPI ; import org . gatein . registration . spi . ConsumerSPI ; import org . gatein . registration . spi . RegistrationSPI ; import org . gatein . wsrp . jcr . ChromatticPersister ; import org . gatein . wsrp . jcr . mapping . BaseMapping ; import org . gatein . wsrp . registration . mapping . ConsumerCapabilitiesMapping ; import org . gatein . wsrp . registration . mapping . ConsumerGroupMapping ; import org . gatein . wsrp . registration . mapping . ConsumerMapping ; import org . gatein . wsrp . registration . mapping . ConsumersAndGroupsMapping ; import org . gatein . wsrp . registration . mapping . RegistrationMapping ; import org . gatein . wsrp . registration . mapping . RegistrationPropertiesMapping ; import javax . jcr . RepositoryException ; import javax . jcr . query . Query ; import javax . jcr . query . QueryResult ; import javax . jcr . query . RowIterator ; import javax . xml . namespace . QName ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . List ; import java . util . Map ; public class JCRRegistrationPersistenceManager extends AbstractRegistrationPersistenceManager { private ChromatticPersister persister ; private final String rootNodePath ; public static final List < Class > mappingClasses = new ArrayList < Class > ( <NUM_LIT:6> ) ; static { Collections . addAll ( mappingClasses , ConsumersAndGroupsMapping . class , ConsumerMapping . class , ConsumerGroupMapping . class , RegistrationMapping . class , ConsumerCapabilitiesMapping . class , RegistrationPropertiesMapping . class ) ; } public JCRRegistrationPersistenceManager ( ChromatticPersister persister ) throws Exception { this ( persister , "<STR_LIT:/>" ) ; } protected JCRRegistrationPersistenceManager ( ChromatticPersister persister , String rootNodePath ) throws Exception { ParameterValidation . throwIllegalArgExceptionIfNull ( persister , "<STR_LIT>" ) ; this . rootNodePath = rootNodePath . endsWith ( "<STR_LIT:/>" ) ? rootNodePath : rootNodePath + "<STR_LIT:/>" ; this . persister = persister ; ChromatticSession session = persister . getSession ( ) ; try { ConsumersAndGroupsMapping mappings = session . findByPath ( ConsumersAndGroupsMapping . class , ConsumersAndGroupsMapping . NODE_NAME ) ; if ( mappings == null ) { session . insert ( ConsumersAndGroupsMapping . class , ConsumersAndGroupsMapping . NODE_NAME ) ; } } finally { persister . closeSession ( true ) ; } } protected ChromatticPersister getPersister ( ) { return persister ; } @ Override public void removeRegistration ( String registrationId ) throws RegistrationException { internalRemoveRegistration ( registrationId ) ; } protected RegistrationSPI internalRemoveRegistration ( String registrationId ) throws RegistrationException { ParameterValidation . throwIllegalArgExceptionIfNullOrEmpty ( registrationId , "<STR_LIT>" , null ) ; final Registration reg = getRegistration ( registrationId ) ; if ( reg != null ) { try { final ChromatticSession session = persister . getSession ( ) ; final RegistrationMapping mapping = session . findById ( RegistrationMapping . class , registrationId ) ; session . remove ( mapping ) ; persister . save ( ) ; } finally { persister . closeSession ( false ) ; } return ( RegistrationSPI ) reg ; } else { return null ; } } @ Override protected RegistrationSPI internalCreateRegistration ( ConsumerSPI consumer , Map < QName , Object > registrationProperties ) throws RegistrationException { RegistrationSPI registration = super . internalCreateRegistration ( consumer , registrationProperties ) ; ChromatticSession session = persister . getSession ( ) ; try { ConsumerMapping cm = session . findById ( ConsumerMapping . class , consumer . getPersistentKey ( ) ) ; RegistrationMapping rm = cm . createAndAddRegistrationMappingFrom ( null ) ; rm . initFrom ( registration ) ; registration . setPersistentKey ( rm . getPersistentKey ( ) ) ; persister . closeSession ( true ) ; } catch ( Exception e ) { persister . closeSession ( false ) ; throw new RegistrationException ( e ) ; } return registration ; } @ Override protected void internalAddConsumer ( ConsumerSPI consumer ) throws RegistrationException { } @ Override protected ConsumerSPI internalRemoveConsumer ( String consumerId ) throws RegistrationException { return remove ( consumerId , ConsumerMapping . class , ConsumerSPI . class ) ; } private < T extends BaseMapping , U > U remove ( String name , Class < T > mappingClass , Class < U > modelClass ) { ChromatticSession session = persister . getSession ( ) ; try { T toRemove = getMapping ( session , mappingClass , name ) ; if ( toRemove == null ) { return null ; } final U result = getModelFrom ( toRemove , mappingClass , modelClass ) ; session . remove ( toRemove ) ; persister . closeSession ( true ) ; return result ; } catch ( Exception e ) { persister . closeSession ( false ) ; throw new RuntimeException ( e ) ; } } private < T extends BaseMapping , U > U getModelFrom ( T mapping , Class < T > mappingClass , Class < U > modelClass ) { Class aClass = mapping . getModelClass ( ) ; if ( ! modelClass . isAssignableFrom ( aClass ) ) { throw new IllegalArgumentException ( "<STR_LIT>" + mappingClass . getSimpleName ( ) + "<STR_LIT>" + modelClass . getSimpleName ( ) ) ; } return modelClass . cast ( mapping . toModel ( null , this ) ) ; } private < T extends BaseMapping > T getMapping ( ChromatticSession session , Class < T > mappingClass , String name ) throws RepositoryException , NoSuchFieldException , IllegalAccessException { String jcrType = ( String ) mappingClass . getField ( BaseMapping . JCR_TYPE_NAME_CONSTANT_NAME ) . get ( null ) ; String id ; final Query query = session . getJCRSession ( ) . getWorkspace ( ) . getQueryManager ( ) . createQuery ( "<STR_LIT>" + jcrType + "<STR_LIT>" + name + "<STR_LIT:'>" , Query . SQL ) ; final QueryResult queryResult = query . execute ( ) ; final RowIterator rows = queryResult . getRows ( ) ; final long size = rows . getSize ( ) ; if ( size == <NUM_LIT:0> ) { return null ; } else { if ( size != <NUM_LIT:1> ) { throw new IllegalArgumentException ( "<STR_LIT>" + mappingClass . getSimpleName ( ) + "<STR_LIT>" + name ) ; } id = rows . nextRow ( ) . getValue ( "<STR_LIT>" ) . getString ( ) ; } return session . findById ( mappingClass , id ) ; } @ Override protected ConsumerSPI internalCreateConsumer ( String consumerId , String consumerName ) throws RegistrationException { ConsumerSPI consumer = super . internalCreateConsumer ( consumerId , consumerName ) ; ChromatticSession session = persister . getSession ( ) ; try { ConsumersAndGroupsMapping mappings = session . findByPath ( ConsumersAndGroupsMapping . class , ConsumersAndGroupsMapping . NODE_NAME ) ; ConsumerMapping cm = mappings . createConsumer ( consumerId ) ; mappings . getConsumers ( ) . add ( cm ) ; cm . initFrom ( consumer ) ; consumer . setPersistentKey ( cm . getPersistentKey ( ) ) ; persister . closeSession ( true ) ; } catch ( Exception e ) { persister . closeSession ( false ) ; throw new RegistrationException ( e ) ; } return consumer ; } @ Override protected ConsumerSPI internalSaveChangesTo ( Consumer consumer ) throws RegistrationException { ConsumerSPI consumerSPI = ( ConsumerSPI ) consumer ; ChromatticSession session = persister . getSession ( ) ; try { ConsumerMapping cm = session . findById ( ConsumerMapping . class , consumer . getPersistentKey ( ) ) ; cm . initFrom ( consumerSPI ) ; persister . closeSession ( true ) ; } catch ( Exception e ) { persister . closeSession ( false ) ; throw new RegistrationException ( e ) ; } return consumerSPI ; } protected RegistrationSPI internalSaveChangesTo ( Registration registration ) throws RegistrationException { RegistrationSPI registrationSPI = ( RegistrationSPI ) registration ; ChromatticSession session = persister . getSession ( ) ; try { RegistrationMapping cm = session . findById ( RegistrationMapping . class , registration . getPersistentKey ( ) ) ; cm . initFrom ( registrationSPI ) ; persister . closeSession ( true ) ; } catch ( Exception e ) { persister . closeSession ( false ) ; throw new RegistrationException ( e ) ; } return registrationSPI ; } @ Override protected void internalAddConsumerGroup ( ConsumerGroupSPI group ) throws RegistrationException { } @ Override protected ConsumerGroupSPI internalRemoveConsumerGroup ( String name ) throws RegistrationException { return remove ( name , ConsumerGroupMapping . class , ConsumerGroupSPI . class ) ; } @ Override protected ConsumerGroupSPI internalCreateConsumerGroup ( String name ) throws RegistrationException { ConsumerGroupSPI group = super . internalCreateConsumerGroup ( name ) ; ChromatticSession session = persister . getSession ( ) ; try { ConsumersAndGroupsMapping mappings = session . findByPath ( ConsumersAndGroupsMapping . class , ConsumersAndGroupsMapping . NODE_NAME ) ; ConsumerGroupMapping cgm = mappings . createConsumerGroup ( name ) ; mappings . getConsumerGroups ( ) . add ( cgm ) ; group . setPersistentKey ( cgm . getPersistentKey ( ) ) ; cgm . initFrom ( group ) ; persister . closeSession ( true ) ; } catch ( Exception e ) { persister . closeSession ( false ) ; throw new RegistrationException ( e ) ; } return group ; } @ Override protected ConsumerSPI getConsumerSPIById ( String consumerId ) throws RegistrationException { return getModel ( consumerId , ConsumerSPI . class , ConsumerMapping . class ) ; } private < T , B extends BaseMapping > T getModel ( String id , Class < T > modelClass , Class < B > mappingClass ) throws RegistrationException { ParameterValidation . throwIllegalArgExceptionIfNullOrEmpty ( id , "<STR_LIT>" , null ) ; final ChromatticSession session = persister . getSession ( ) ; try { return getModel ( id , modelClass , mappingClass , session ) ; } catch ( Exception e ) { throw new RegistrationException ( e ) ; } finally { persister . closeSession ( false ) ; } } private < T , B extends BaseMapping > T getModel ( String id , Class < T > modelClass , Class < B > mappingClass , ChromatticSession session ) throws RegistrationException { try { final B mapping = getMapping ( session , mappingClass , id ) ; if ( mapping == null ) { return null ; } else { return getModelFrom ( mapping , mappingClass , modelClass ) ; } } catch ( Exception e ) { throw new RegistrationException ( e ) ; } } public ConsumerGroup getConsumerGroup ( String name ) throws RegistrationException { return getModel ( name , ConsumerGroup . class , ConsumerGroupMapping . class ) ; } public Consumer getConsumerById ( String consumerId ) throws IllegalArgumentException , RegistrationException { return getConsumerSPIById ( consumerId ) ; } public Collection < ? extends ConsumerGroup > getConsumerGroups ( ) throws RegistrationException { final ChromatticSession session = persister . getSession ( ) ; try { ConsumersAndGroupsMapping mappings = session . findByPath ( ConsumersAndGroupsMapping . class , ConsumersAndGroupsMapping . NODE_NAME ) ; final List < ConsumerGroupMapping > groupMappings = mappings . getConsumerGroups ( ) ; List < ConsumerGroup > groups = new ArrayList < ConsumerGroup > ( groupMappings . size ( ) ) ; for ( ConsumerGroupMapping cgm : groupMappings ) { groups . add ( cgm . toModel ( newConsumerGroupSPI ( cgm . getName ( ) ) , this ) ) ; } return groups ; } finally { persister . closeSession ( false ) ; } } public Registration getRegistration ( String registrationId ) throws RegistrationException { ParameterValidation . throwIllegalArgExceptionIfNullOrEmpty ( registrationId , "<STR_LIT>" , null ) ; final ChromatticSession session = persister . getSession ( ) ; try { final RegistrationMapping mapping = session . findById ( RegistrationMapping . class , registrationId ) ; if ( mapping == null ) { return null ; } else { final ConsumerMapping parent = mapping . getParent ( ) ; return parent . toModel ( null , this ) . getRegistration ( registrationId ) ; } } catch ( Exception e ) { throw new RegistrationException ( e ) ; } finally { persister . closeSession ( false ) ; } } public Collection < ? extends Consumer > getConsumers ( ) throws RegistrationException { final ChromatticSession session = persister . getSession ( ) ; try { ConsumersAndGroupsMapping mappings = session . findByPath ( ConsumersAndGroupsMapping . class , ConsumersAndGroupsMapping . NODE_NAME ) ; final List < ConsumerMapping > consumerMappings = mappings . getConsumers ( ) ; List < Consumer > consumers = new ArrayList < Consumer > ( consumerMappings . size ( ) ) ; for ( ConsumerMapping consumerMapping : consumerMappings ) { consumers . add ( consumerMapping . toModel ( newConsumerSPI ( consumerMapping . getId ( ) , consumerMapping . getName ( ) ) , this ) ) ; } return consumers ; } finally { persister . closeSession ( false ) ; } } public Collection < ? extends Registration > getRegistrations ( ) throws RegistrationException { final Collection < ? extends Consumer > consumers = getConsumers ( ) ; List < Registration > registrations = new ArrayList < Registration > ( consumers . size ( ) * <NUM_LIT:2> ) ; for ( Consumer consumer : consumers ) { registrations . addAll ( consumer . getRegistrations ( ) ) ; } return registrations ; } public boolean isConsumerExisting ( String consumerId ) throws RegistrationException { return exists ( consumerId ) ; } private boolean exists ( String name ) { ChromatticSession session = persister . getSession ( ) ; try { return session . getJCRSession ( ) . itemExists ( rootNodePath + ConsumersAndGroupsMapping . NODE_NAME + "<STR_LIT:/>" + name ) ; } catch ( RepositoryException e ) { throw new RuntimeException ( e ) ; } finally { persister . closeSession ( false ) ; } } public boolean isConsumerGroupExisting ( String consumerGroupId ) throws RegistrationException { return exists ( consumerGroupId ) ; } @ Override protected void internalAddRegistration ( RegistrationSPI registration ) throws RegistrationException { } } </s>
|
<s> package org . gatein . wsrp . registration . mapping ; import org . chromattic . api . annotations . PrimaryType ; import org . chromattic . api . annotations . Properties ; import javax . xml . namespace . QName ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; @ PrimaryType ( name = RegistrationPropertiesMapping . NODE_NAME ) public abstract class RegistrationPropertiesMapping { public static final String NODE_NAME = "<STR_LIT>" ; @ Properties public abstract Map < String , String > getProperties ( ) ; public Map < QName , Object > toPropMap ( ) { Map < String , String > propMap = getProperties ( ) ; if ( ! propMap . isEmpty ( ) ) { Map < QName , Object > properties = new HashMap < QName , Object > ( propMap . size ( ) ) ; for ( Map . Entry < String , String > entry : propMap . entrySet ( ) ) { String key = entry . getKey ( ) ; properties . put ( QName . valueOf ( key ) , entry . getValue ( ) ) ; } return properties ; } else { return Collections . emptyMap ( ) ; } } public void initFrom ( Map < QName , Object > properties ) { if ( properties != null ) { Map < String , String > map = getProperties ( ) ; for ( Map . Entry < QName , Object > entry : properties . entrySet ( ) ) { map . put ( entry . getKey ( ) . toString ( ) , entry . getValue ( ) . toString ( ) ) ; } } } } </s>
|
<s> package org . gatein . wsrp . registration . mapping ; import org . chromattic . api . annotations . PrimaryType ; import org . chromattic . api . annotations . Property ; import java . io . ByteArrayInputStream ; import java . io . InputStream ; @ PrimaryType ( name = PortletContextMapping . NODE_NAME ) public abstract class PortletContextMapping { public static final String NODE_NAME = "<STR_LIT>" ; @ Property ( name = "<STR_LIT:id>" ) public abstract String getId ( ) ; public abstract void setId ( String id ) ; @ Property ( name = "<STR_LIT:state>" ) public abstract InputStream getState ( ) ; public abstract void setState ( InputStream state ) ; public void initFrom ( String id , byte [ ] state ) { setId ( id ) ; if ( state != null && state . length > <NUM_LIT:0> ) { ByteArrayInputStream is = new ByteArrayInputStream ( state ) ; setState ( is ) ; } } } </s>
|
<s> package org . gatein . wsrp . registration . mapping ; import org . chromattic . api . annotations . Create ; import org . chromattic . api . annotations . Id ; import org . chromattic . api . annotations . ManyToOne ; import org . chromattic . api . annotations . MappedBy ; import org . chromattic . api . annotations . OneToMany ; import org . chromattic . api . annotations . OneToOne ; import org . chromattic . api . annotations . Owner ; import org . chromattic . api . annotations . Path ; import org . chromattic . api . annotations . PrimaryType ; import org . chromattic . api . annotations . Property ; import org . gatein . common . io . IOTools ; import org . gatein . common . util . ParameterValidation ; import org . gatein . pc . api . PortletContext ; import org . gatein . pc . api . PortletStateType ; import org . gatein . pc . api . StatefulPortletContext ; import org . gatein . registration . RegistrationException ; import org . gatein . registration . RegistrationStatus ; import org . gatein . registration . spi . ConsumerSPI ; import org . gatein . registration . spi . RegistrationSPI ; import org . gatein . wsrp . jcr . mapping . BaseMapping ; import org . gatein . wsrp . registration . JCRRegistrationPersistenceManager ; import javax . xml . namespace . QName ; import java . util . Collection ; import java . util . Collections ; import java . util . Map ; @ PrimaryType ( name = RegistrationMapping . NODE_NAME ) public abstract class RegistrationMapping implements BaseMapping < RegistrationSPI , JCRRegistrationPersistenceManager > { public static final String NODE_NAME = "<STR_LIT>" ; @ Id public abstract String getPersistentKey ( ) ; @ Property ( name = "<STR_LIT:status>" ) public abstract RegistrationStatus getStatus ( ) ; public abstract void setStatus ( RegistrationStatus status ) ; @ Property ( name = "<STR_LIT>" ) public abstract String getRegistrationHandle ( ) ; public abstract void setRegistrationHandle ( String handle ) ; @ OneToMany public abstract Collection < PortletContextMapping > getPortletContexts ( ) ; @ Create public abstract PortletContextMapping createPortletContext ( String id ) ; @ OneToOne @ Owner @ MappedBy ( "<STR_LIT>" ) public abstract RegistrationPropertiesMapping getProperties ( ) ; public abstract void setProperties ( RegistrationPropertiesMapping rpm ) ; @ Create public abstract RegistrationPropertiesMapping createProperties ( ) ; @ Path public abstract String getPath ( ) ; @ ManyToOne public abstract ConsumerMapping getParent ( ) ; public void initFrom ( RegistrationSPI registration ) { setStatus ( registration . getStatus ( ) ) ; setRegistrationHandle ( registration . getRegistrationHandle ( ) ) ; Collection < PortletContextMapping > contextMappings = getPortletContexts ( ) ; contextMappings . clear ( ) ; for ( PortletContext portletContext : registration . getKnownPortletContexts ( ) ) { String id = portletContext . getId ( ) ; PortletContextMapping contextMapping = createPortletContext ( id ) ; contextMappings . add ( contextMapping ) ; if ( portletContext instanceof StatefulPortletContext ) { StatefulPortletContext context = ( StatefulPortletContext ) portletContext ; if ( PortletStateType . OPAQUE . equals ( context . getType ( ) ) ) { contextMapping . initFrom ( id , ( ( StatefulPortletContext < byte [ ] > ) context ) . getState ( ) ) ; } else { throw new IllegalArgumentException ( "<STR_LIT>" + context . getState ( ) ) ; } } else { contextMapping . initFrom ( id , null ) ; } } Map < QName , Object > properties = registration . getProperties ( ) ; if ( ParameterValidation . existsAndIsNotEmpty ( properties ) ) { RegistrationPropertiesMapping rpm = getProperties ( ) ; if ( rpm != null ) { setProperties ( null ) ; } rpm = createProperties ( ) ; setProperties ( rpm ) ; rpm . initFrom ( properties ) ; } } public RegistrationSPI toModel ( RegistrationSPI initial , JCRRegistrationPersistenceManager persistenceManager ) { ParameterValidation . throwIllegalArgExceptionIfNull ( initial , "<STR_LIT>" ) ; initial . setStatus ( getStatus ( ) ) ; initial . setRegistrationHandle ( getRegistrationHandle ( ) ) ; initial . setPersistentKey ( getPersistentKey ( ) ) ; Collection < PortletContextMapping > pcms = getPortletContexts ( ) ; for ( PortletContextMapping pcm : pcms ) { PortletContext pc = PortletContext . createPortletContext ( pcm . getId ( ) , IOTools . safeGetBytes ( pcm . getState ( ) ) ) ; try { initial . addPortletContext ( pc , false ) ; } catch ( RegistrationException e ) { throw new RuntimeException ( e ) ; } } return initial ; } public Class < RegistrationSPI > getModelClass ( ) { return RegistrationSPI . class ; } public RegistrationSPI toRegistration ( ConsumerSPI consumer , JCRRegistrationPersistenceManager persistenceManager ) throws RegistrationException { RegistrationPropertiesMapping rpm = getProperties ( ) ; Map < QName , Object > props = Collections . emptyMap ( ) ; if ( rpm != null ) { props = rpm . toPropMap ( ) ; } RegistrationSPI reg = persistenceManager . newRegistrationSPI ( consumer , props ) ; return toModel ( reg , persistenceManager ) ; } } </s>
|
<s> package org . gatein . wsrp . registration . mapping ; import org . chromattic . api . annotations . Create ; import org . chromattic . api . annotations . OneToMany ; import org . chromattic . api . annotations . PrimaryType ; import java . util . List ; @ PrimaryType ( name = ConsumersAndGroupsMapping . NODE_NAME ) public abstract class ConsumersAndGroupsMapping { public static final String NODE_NAME = "<STR_LIT>" ; @ OneToMany public abstract List < ConsumerMapping > getConsumers ( ) ; @ OneToMany public abstract List < ConsumerGroupMapping > getConsumerGroups ( ) ; @ Create public abstract ConsumerMapping createConsumer ( String id ) ; @ Create public abstract ConsumerGroupMapping createConsumerGroup ( String name ) ; } </s>
|
<s> package org . gatein . wsrp . registration . mapping ; import org . chromattic . api . annotations . PrimaryType ; import org . chromattic . api . annotations . Property ; import org . gatein . common . util . ParameterValidation ; import org . gatein . pc . api . Mode ; import org . gatein . pc . api . WindowState ; import org . gatein . registration . ConsumerCapabilities ; import org . gatein . registration . impl . ConsumerCapabilitiesImpl ; import java . util . ArrayList ; import java . util . List ; @ PrimaryType ( name = ConsumerCapabilitiesMapping . NODE_NAME ) public abstract class ConsumerCapabilitiesMapping { public static final String NODE_NAME = "<STR_LIT>" ; @ Property ( name = "<STR_LIT>" ) public abstract boolean getSupportsGetMethod ( ) ; public abstract void setSupportsGetMethod ( boolean supportsGetMethod ) ; @ Property ( name = "<STR_LIT>" ) public abstract List < String > getSupportedModes ( ) ; public abstract void setSupportedModes ( List < String > modes ) ; @ Property ( name = "<STR_LIT>" ) public abstract List < String > getSupportedWindowStates ( ) ; public abstract void setSupportedWindowStates ( List < String > windowStates ) ; @ Property ( name = "<STR_LIT>" ) public abstract List < String > getSupportedUserScopes ( ) ; public abstract void setSupportedUserScopes ( List < String > userScopes ) ; @ Property ( name = "<STR_LIT>" ) public abstract List < String > getSupportedUserProfileData ( ) ; public abstract void setSupportedUserProfileData ( List < String > userProfileData ) ; public void initFrom ( ConsumerCapabilities capabilities ) { setSupportsGetMethod ( capabilities . supportsGetMethod ( ) ) ; List < String > modes = convertToStringList ( capabilities . getSupportedModes ( ) ) ; if ( modes != null ) { setSupportedModes ( modes ) ; } List < String > states = convertToStringList ( capabilities . getSupportedWindowStates ( ) ) ; if ( states != null ) { setSupportedWindowStates ( states ) ; } List < String > scopes = capabilities . getSupportedUserScopes ( ) ; if ( ParameterValidation . existsAndIsNotEmpty ( scopes ) ) { setSupportedUserScopes ( scopes ) ; } List < String > userProfileData = capabilities . getSupportedUserProfileData ( ) ; if ( ParameterValidation . existsAndIsNotEmpty ( userProfileData ) ) { setSupportedUserProfileData ( userProfileData ) ; } } private List < String > convertToStringList ( List list ) { if ( ParameterValidation . existsAndIsNotEmpty ( list ) ) { List < String > result = new ArrayList < String > ( list . size ( ) ) ; for ( Object object : list ) { result . add ( object . toString ( ) ) ; } return result ; } return null ; } public ConsumerCapabilities toConsumerCapabilities ( ) { ConsumerCapabilitiesImpl consumerCapabilities = new ConsumerCapabilitiesImpl ( ) ; consumerCapabilities . setSupportsGetMethod ( getSupportsGetMethod ( ) ) ; List < String > modeStrings = getSupportedModes ( ) ; if ( ParameterValidation . existsAndIsNotEmpty ( modeStrings ) ) { List < Mode > modes = new ArrayList < Mode > ( modeStrings . size ( ) ) ; for ( String modeString : modeStrings ) { modes . add ( Mode . create ( modeString ) ) ; } consumerCapabilities . setSupportedModes ( modes ) ; } List < String > windowStateStrings = getSupportedWindowStates ( ) ; if ( ParameterValidation . existsAndIsNotEmpty ( windowStateStrings ) ) { List < WindowState > windowStates = new ArrayList < WindowState > ( windowStateStrings . size ( ) ) ; for ( String windowStateString : windowStateStrings ) { windowStates . add ( WindowState . create ( windowStateString ) ) ; } consumerCapabilities . setSupportedWindowStates ( windowStates ) ; } List < String > userProfileData = getSupportedUserProfileData ( ) ; if ( ParameterValidation . existsAndIsNotEmpty ( userProfileData ) ) { consumerCapabilities . setSupportedUserProfileData ( userProfileData ) ; } List < String > userScopes = getSupportedUserScopes ( ) ; if ( ParameterValidation . existsAndIsNotEmpty ( userScopes ) ) { consumerCapabilities . setSupportedUserScopes ( userScopes ) ; } return consumerCapabilities ; } } </s>
|
<s> package org . gatein . wsrp . registration . mapping ; import org . chromattic . api . annotations . Id ; import org . chromattic . api . annotations . PrimaryType ; import org . chromattic . api . annotations . Property ; import org . gatein . common . util . ParameterValidation ; import org . gatein . wsrp . registration . LocalizedString ; import org . gatein . wsrp . registration . RegistrationPropertyDescription ; import javax . xml . namespace . QName ; @ PrimaryType ( name = RegistrationPropertyDescriptionMapping . NODE_NAME ) public abstract class RegistrationPropertyDescriptionMapping { public static final String NODE_NAME = "<STR_LIT>" ; @ Id public abstract String getPersistentKey ( ) ; @ Property ( name = "<STR_LIT:name>" ) public abstract String getName ( ) ; public abstract void setName ( String name ) ; @ Property ( name = "<STR_LIT:type>" ) public abstract String getType ( ) ; public abstract void setType ( String type ) ; @ Property ( name = "<STR_LIT:description>" ) public abstract String getDescription ( ) ; public abstract void setDescription ( String description ) ; @ Property ( name = "<STR_LIT>" ) public abstract String getHint ( ) ; public abstract void setHint ( String hint ) ; @ Property ( name = "<STR_LIT:label>" ) public abstract String getLabel ( ) ; public abstract void setLabel ( String label ) ; public void initFrom ( RegistrationPropertyDescription desc ) { LocalizedString description = desc . getDescription ( ) ; if ( description != null ) { setDescription ( description . getValue ( ) ) ; } LocalizedString hint = desc . getHint ( ) ; if ( hint != null ) { setHint ( hint . getValue ( ) ) ; } LocalizedString label = desc . getLabel ( ) ; if ( label != null ) { setLabel ( label . getValue ( ) ) ; } setName ( desc . getName ( ) . toString ( ) ) ; setType ( desc . getType ( ) . toString ( ) ) ; } public RegistrationPropertyDescription toRegistrationPropertyDescription ( ) { RegistrationPropertyDescription desc = new RegistrationPropertyDescription ( getName ( ) , QName . valueOf ( getType ( ) ) ) ; desc . setPersistentKey ( getPersistentKey ( ) ) ; String description = getDescription ( ) ; if ( ! ParameterValidation . isNullOrEmpty ( description ) ) { desc . setDefaultDescription ( description ) ; } String hint = getHint ( ) ; if ( ! ParameterValidation . isNullOrEmpty ( hint ) ) { desc . setHint ( new LocalizedString ( hint ) ) ; } String label = getLabel ( ) ; if ( ! ParameterValidation . isNullOrEmpty ( label ) ) { desc . setLabel ( new LocalizedString ( label ) ) ; } return desc ; } } </s>
|
<s> package org . gatein . wsrp . registration . mapping ; import org . chromattic . api . RelationshipType ; import org . chromattic . api . annotations . FindById ; import org . chromattic . api . annotations . Id ; import org . chromattic . api . annotations . MappedBy ; import org . chromattic . api . annotations . OneToMany ; import org . chromattic . api . annotations . PrimaryType ; import org . chromattic . api . annotations . Property ; import org . gatein . common . util . ParameterValidation ; import org . gatein . registration . Consumer ; import org . gatein . registration . RegistrationException ; import org . gatein . registration . RegistrationStatus ; import org . gatein . registration . spi . ConsumerGroupSPI ; import org . gatein . registration . spi . ConsumerSPI ; import org . gatein . wsrp . jcr . mapping . BaseMapping ; import org . gatein . wsrp . registration . JCRRegistrationPersistenceManager ; import java . util . Collection ; @ PrimaryType ( name = ConsumerGroupMapping . NODE_NAME ) public abstract class ConsumerGroupMapping implements BaseMapping < ConsumerGroupSPI , JCRRegistrationPersistenceManager > { public static final String NODE_NAME = "<STR_LIT>" ; @ OneToMany ( type = RelationshipType . PATH ) @ MappedBy ( "<STR_LIT>" ) public abstract Collection < ConsumerMapping > getConsumers ( ) ; @ Property ( name = "<STR_LIT:name>" ) public abstract String getName ( ) ; public abstract void setName ( String name ) ; @ Property ( name = "<STR_LIT:status>" ) public abstract RegistrationStatus getStatus ( ) ; public abstract void setStatus ( RegistrationStatus status ) ; @ Id public abstract String getPersistentKey ( ) ; @ FindById public abstract ConsumerMapping findConsumerById ( String id ) ; public void initFrom ( ConsumerGroupSPI group ) { setName ( group . getName ( ) ) ; setStatus ( group . getStatus ( ) ) ; try { for ( Consumer consumer : group . getConsumers ( ) ) { String id = consumer . getPersistentKey ( ) ; ConsumerMapping cm = findConsumerById ( id ) ; ParameterValidation . throwIllegalArgExceptionIfNull ( cm , "<STR_LIT>" + id + "<STR_LIT:)>" ) ; getConsumers ( ) . add ( cm ) ; cm . initFrom ( ( ConsumerSPI ) consumer ) ; } } catch ( RegistrationException e ) { throw new RuntimeException ( e ) ; } } public ConsumerGroupSPI toModel ( ConsumerGroupSPI initial , JCRRegistrationPersistenceManager persistenceManager ) { ConsumerGroupSPI group = ( initial != null ? initial : persistenceManager . newConsumerGroupSPI ( getName ( ) ) ) ; group . setPersistentKey ( getPersistentKey ( ) ) ; RegistrationStatus status = getStatus ( ) ; if ( status == null ) { status = RegistrationStatus . PENDING ; } group . setStatus ( status ) ; try { for ( ConsumerMapping cm : getConsumers ( ) ) { Consumer consumer = persistenceManager . getConsumerById ( cm . getPersistentKey ( ) ) ; if ( consumer == null ) { consumer = cm . toModel ( ( ConsumerSPI ) consumer , persistenceManager ) ; } group . addConsumer ( consumer ) ; } return group ; } catch ( RegistrationException e ) { throw new RuntimeException ( e ) ; } } public Class < ConsumerGroupSPI > getModelClass ( ) { return ConsumerGroupSPI . class ; } } </s>
|
<s> package org . gatein . wsrp . registration . mapping ; import org . chromattic . api . RelationshipType ; import org . chromattic . api . annotations . Create ; import org . chromattic . api . annotations . FindById ; import org . chromattic . api . annotations . Id ; import org . chromattic . api . annotations . ManyToOne ; import org . chromattic . api . annotations . MappedBy ; import org . chromattic . api . annotations . OneToMany ; import org . chromattic . api . annotations . OneToOne ; import org . chromattic . api . annotations . Owner ; import org . chromattic . api . annotations . PrimaryType ; import org . chromattic . api . annotations . Property ; import org . gatein . registration . ConsumerGroup ; import org . gatein . registration . Registration ; import org . gatein . registration . RegistrationException ; import org . gatein . registration . spi . ConsumerSPI ; import org . gatein . registration . spi . RegistrationSPI ; import org . gatein . wsrp . jcr . mapping . BaseMapping ; import org . gatein . wsrp . registration . JCRRegistrationPersistenceManager ; import java . util . List ; @ PrimaryType ( name = ConsumerMapping . NODE_NAME ) public abstract class ConsumerMapping implements BaseMapping < ConsumerSPI , JCRRegistrationPersistenceManager > { public static final String NODE_NAME = "<STR_LIT>" ; @ Id public abstract String getPersistentKey ( ) ; @ Property ( name = "<STR_LIT:name>" ) public abstract String getName ( ) ; public abstract void setName ( String name ) ; @ Property ( name = "<STR_LIT:id>" ) public abstract String getId ( ) ; public abstract void setId ( String id ) ; @ Property ( name = "<STR_LIT>" ) public abstract String getConsumerAgent ( ) ; public abstract void setConsumerAgent ( String consumerAgent ) ; @ OneToMany public abstract List < RegistrationMapping > getRegistrations ( ) ; @ Create public abstract RegistrationMapping createRegistration ( String path ) ; @ ManyToOne ( type = RelationshipType . PATH ) @ MappedBy ( "<STR_LIT>" ) public abstract ConsumerGroupMapping getGroup ( ) ; public abstract void setGroup ( ConsumerGroupMapping group ) ; @ OneToOne @ Owner @ MappedBy ( "<STR_LIT>" ) public abstract ConsumerCapabilitiesMapping getCapabilities ( ) ; @ FindById public abstract ConsumerGroupMapping findGroupById ( String id ) ; @ FindById public abstract RegistrationMapping findRegistrationById ( String id ) ; public RegistrationMapping createAndAddRegistrationMappingFrom ( Registration registration ) { RegistrationMapping rm ; if ( registration != null ) { String key = registration . getPersistentKey ( ) ; if ( key != null ) { rm = findRegistrationById ( key ) ; } else { rm = createRegistration ( "<STR_LIT>" + System . nanoTime ( ) ) ; getRegistrations ( ) . add ( rm ) ; } rm . initFrom ( ( RegistrationSPI ) registration ) ; } else { rm = createRegistration ( "<STR_LIT>" + System . nanoTime ( ) ) ; getRegistrations ( ) . add ( rm ) ; } return rm ; } public void initFrom ( ConsumerSPI consumer ) { setName ( consumer . getName ( ) ) ; setId ( consumer . getId ( ) ) ; setConsumerAgent ( consumer . getConsumerAgent ( ) ) ; ConsumerGroup group = consumer . getGroup ( ) ; if ( group != null ) { ConsumerGroupMapping cgm = findGroupById ( group . getPersistentKey ( ) ) ; setGroup ( cgm ) ; } ConsumerCapabilitiesMapping ccm = getCapabilities ( ) ; ccm . initFrom ( consumer . getCapabilities ( ) ) ; try { for ( Registration reg : consumer . getRegistrations ( ) ) { createAndAddRegistrationMappingFrom ( reg ) ; } } catch ( RegistrationException e ) { throw new RuntimeException ( e ) ; } } public ConsumerSPI toModel ( ConsumerSPI initial , JCRRegistrationPersistenceManager persistenceManager ) { ConsumerSPI consumer = ( initial != null ? initial : persistenceManager . newConsumerSPI ( getId ( ) , getName ( ) ) ) ; consumer . setConsumerAgent ( getConsumerAgent ( ) ) ; consumer . setPersistentKey ( getPersistentKey ( ) ) ; consumer . setCapabilities ( getCapabilities ( ) . toConsumerCapabilities ( ) ) ; try { ConsumerGroupMapping cgm = getGroup ( ) ; if ( cgm != null ) { consumer . setGroup ( persistenceManager . getConsumerGroup ( cgm . getName ( ) ) ) ; } for ( RegistrationMapping rm : getRegistrations ( ) ) { consumer . addRegistration ( rm . toRegistration ( consumer , persistenceManager ) ) ; } } catch ( RegistrationException e ) { throw new RuntimeException ( e ) ; } return consumer ; } public Class < ConsumerSPI > getModelClass ( ) { return ConsumerSPI . class ; } } </s>
|
<s> package org . gatein . wsrp . jcr ; import org . chromattic . api . ChromatticSession ; import org . gatein . wsrp . jcr . mapping . mixins . LastModified ; public interface StoresByPathManager < C > { String getChildPath ( C needsComputedPath ) ; LastModified lastModifiedToUpdateOnDelete ( ChromatticSession session ) ; } </s>
|
<s> package org . gatein . wsrp . jcr ; import org . chromattic . api . ChromatticSession ; import org . chromattic . api . format . FormatterContext ; import org . chromattic . api . format . ObjectFormatter ; public interface ChromatticPersister { ChromatticSession getSession ( ) ; void closeSession ( boolean save ) ; void save ( ) ; < T > boolean delete ( T toDelete , StoresByPathManager < T > manager ) ; public static class QNameFormatter implements ObjectFormatter { private static final String OPEN_BRACE_REPLACEMENT = "<STR_LIT>" ; private static final String CLOSE_BRACE_REPLACEMENT = "<STR_LIT>" ; private static final String COLON_REPLACEMENT = "<STR_LIT>" ; private static final String CLOSE_BRACE = "<STR_LIT:}>" ; private static final String OPEN_BRACE = "<STR_LIT:{>" ; private static final String COLON = "<STR_LIT::>" ; public String decodeNodeName ( FormatterContext formatterContext , String s ) { return decode ( s ) ; } public String encodeNodeName ( FormatterContext formatterContext , String s ) { return encode ( s ) ; } public String decodePropertyName ( FormatterContext formatterContext , String s ) { return decode ( s ) ; } public String encodePropertyName ( FormatterContext formatterContext , String s ) { return encode ( s ) ; } public static String decode ( String s ) { return s . replace ( CLOSE_BRACE_REPLACEMENT , CLOSE_BRACE ) . replace ( OPEN_BRACE_REPLACEMENT , OPEN_BRACE ) . replace ( COLON_REPLACEMENT , COLON ) ; } public static String encode ( String s ) { return s . replace ( OPEN_BRACE , OPEN_BRACE_REPLACEMENT ) . replace ( CLOSE_BRACE , CLOSE_BRACE_REPLACEMENT ) . replace ( COLON , COLON_REPLACEMENT ) ; } } public static class PortletNameFormatter implements ObjectFormatter { public static final String SLASH_REPLACEMENT = "<STR_LIT>" ; private static final String SLASH = "<STR_LIT:/>" ; public String decodeNodeName ( FormatterContext formatterContext , String s ) { return decode ( s ) ; } public static String decode ( String s ) { return s . replace ( SLASH_REPLACEMENT , SLASH ) ; } public String encodeNodeName ( FormatterContext formatterContext , String s ) throws IllegalArgumentException , NullPointerException { return encode ( s ) ; } public static String encode ( String s ) { return s . replace ( SLASH , SLASH_REPLACEMENT ) ; } } } </s>
|
<s> package org . gatein . wsrp . jcr . mapping ; import org . gatein . common . util . ParameterValidation ; import org . gatein . common . util . Tools ; import java . util . Arrays ; import java . util . Collections ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Map ; import java . util . Set ; public class MappedMap < Key , Value > { private static final Set < String > jcrBlacklistedPropertyKeys = Tools . toSet ( "<STR_LIT>" , "<STR_LIT>" ) ; private Set < String > blacklistedPropertyKeys ; private Converter < String , Key > keyConverter ; private Converter < Object , Value > valueConverter ; public static final Converter < String , String > IDENTITY_KEY_CONVERTER = new Converter < String , String > ( ) { public String fromInternal ( String s ) { return s ; } public String toInternal ( String s ) { return s ; } } ; public MappedMap ( Converter < String , Key > keyConverter , Converter < Object , Value > valueConverter , String ... blacklistedPropertyNames ) { this . keyConverter = keyConverter ; this . valueConverter = valueConverter ; int blacklistedNumber = blacklistedPropertyNames . length ; if ( blacklistedNumber > <NUM_LIT:0> ) { blacklistedPropertyKeys = new HashSet < String > ( jcrBlacklistedPropertyKeys ) ; blacklistedPropertyKeys . addAll ( Arrays . asList ( blacklistedPropertyNames ) ) ; } } public Map < Key , Value > toExternalMap ( Map < String , Object > internalMap ) { if ( ! internalMap . isEmpty ( ) ) { Map < Key , Value > externalMap = new HashMap < Key , Value > ( internalMap . size ( ) ) ; for ( Map . Entry < String , Object > entry : internalMap . entrySet ( ) ) { String key = entry . getKey ( ) ; if ( ! blacklistedPropertyKeys . contains ( key ) ) { externalMap . put ( keyConverter . fromInternal ( key ) , valueConverter . fromInternal ( entry . getValue ( ) ) ) ; } } return externalMap ; } else { return Collections . emptyMap ( ) ; } } public void initFrom ( Map < Key , Value > externalMap , Map < String , Object > internalMap ) { if ( ParameterValidation . existsAndIsNotEmpty ( externalMap ) ) { Set < String > keys = new HashSet < String > ( internalMap . keySet ( ) ) ; for ( String key : keys ) { if ( ! blacklistedPropertyKeys . contains ( key ) ) { internalMap . remove ( key ) ; } } for ( Map . Entry < Key , Value > entry : externalMap . entrySet ( ) ) { internalMap . put ( keyConverter . toInternal ( entry . getKey ( ) ) , valueConverter . toInternal ( entry . getValue ( ) ) ) ; } } } public static interface Converter < Internal , External > { External fromInternal ( Internal internal ) ; Internal toInternal ( External external ) ; } } </s>
|
<s> package org . gatein . wsrp . jcr . mapping ; public interface BaseMapping < T , R > { public static final String JCR_TYPE_NAME_CONSTANT_NAME = "<STR_LIT>" ; void initFrom ( T model ) ; T toModel ( T initial , R registry ) ; Class < T > getModelClass ( ) ; } </s>
|
<s> package org . gatein . wsrp . jcr . mapping . mixins ; import org . chromattic . api . RelationshipType ; import org . chromattic . api . annotations . Create ; import org . chromattic . api . annotations . OneToOne ; import org . chromattic . api . annotations . Owner ; public abstract class LastModifiedMixinHolder extends MixinHolder < LastModified > { @ OneToOne ( type = RelationshipType . EMBEDDED ) @ Owner public abstract LastModified getLastModifiedMixin ( ) ; protected abstract void setLastModifiedMixin ( LastModified lastModifiedMixin ) ; @ Create protected abstract LastModified createLastModifiedMixin ( ) ; public void setLastModified ( long lastModified ) { getCreatedMixin ( ) . setLastModified ( lastModified ) ; } public long getLastModified ( ) { return getCreatedMixin ( ) . getLastModified ( ) ; } @ Override public LastModified getMixin ( ) { return getLastModifiedMixin ( ) ; } @ Override protected void setMixin ( LastModified mixin ) { setLastModifiedMixin ( mixin ) ; } @ Override protected LastModified createMixin ( ) { return createLastModifiedMixin ( ) ; } } </s>
|
<s> package org . gatein . wsrp . jcr . mapping . mixins ; import org . chromattic . api . annotations . DefaultValue ; import org . chromattic . api . annotations . MixinType ; import org . chromattic . api . annotations . Property ; @ MixinType ( name = "<STR_LIT>" ) public abstract class WSSEndpointEnabled implements BaseMixin { @ Property ( name = "<STR_LIT>" ) @ DefaultValue ( "<STR_LIT:false>" ) public abstract boolean getWSSEnabled ( ) ; public abstract void setWSSEnabled ( boolean enable ) ; public void initializeValue ( ) { setWSSEnabled ( false ) ; } } </s>
|
<s> package org . gatein . wsrp . jcr . mapping . mixins ; import org . chromattic . api . annotations . MixinType ; import org . chromattic . api . annotations . Property ; @ MixinType ( name = "<STR_LIT>" ) public abstract class LastModified implements BaseMixin { @ Property ( name = "<STR_LIT>" ) public abstract long getLastModified ( ) ; public abstract void setLastModified ( long lastModified ) ; public void initializeValue ( ) { setLastModified ( System . currentTimeMillis ( ) ) ; } } </s>
|
<s> package org . gatein . wsrp . jcr . mapping . mixins ; public interface BaseMixin { void initializeValue ( ) ; } </s>
|
<s> package org . gatein . wsrp . jcr . mapping . mixins ; import org . chromattic . api . annotations . MixinType ; import org . chromattic . api . annotations . Property ; @ MixinType ( name = "<STR_LIT>" ) public abstract class ModifyRegistrationRequired implements BaseMixin { @ Property ( name = "<STR_LIT>" ) public abstract boolean isModifyRegistrationRequired ( ) ; public abstract void setModifyRegistrationRequired ( boolean modifyRegistrationRequired ) ; public void initializeValue ( ) { setModifyRegistrationRequired ( false ) ; } } </s>
|
<s> package org . gatein . wsrp . jcr . mapping . mixins ; public abstract class MixinHolder < M extends BaseMixin > { protected M getCreatedMixin ( ) { M mixin = getMixin ( ) ; if ( mixin == null ) { mixin = createMixin ( ) ; setMixin ( mixin ) ; mixin . initializeValue ( ) ; } return mixin ; } public abstract M getMixin ( ) ; protected abstract void setMixin ( M mixin ) ; protected abstract M createMixin ( ) ; } </s>
|
<s> package org . gatein . wsrp . jcr ; import org . chromattic . api . Chromattic ; import org . chromattic . api . ChromatticBuilder ; import org . chromattic . api . ChromatticSession ; import org . gatein . common . util . ParameterValidation ; import org . gatein . wsrp . jcr . mapping . BaseMapping ; import org . gatein . wsrp . jcr . mapping . mixins . LastModified ; import java . lang . reflect . ParameterizedType ; import java . lang . reflect . Type ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; public abstract class BaseChromatticPersister implements ChromatticPersister { private Chromattic chrome ; public static final String WSRP_WORKSPACE_NAME = "<STR_LIT>" ; public static final String PORTLET_STATES_WORKSPACE_NAME = "<STR_LIT>" ; protected static final String REPOSITORY_NAME = "<STR_LIT>" ; protected String workspaceName ; private Map < Class , Class < ? extends BaseMapping > > modelToMapping ; private ThreadLocal < ChromatticSession > sessionHolder = new ThreadLocal < ChromatticSession > ( ) ; public BaseChromatticPersister ( String workspaceName ) { this . workspaceName = workspaceName ; } public void initializeBuilderFor ( List < Class > mappingClasses ) throws Exception { ChromatticBuilder builder = ChromatticBuilder . create ( ) ; builder . setOptionValue ( ChromatticBuilder . INSTRUMENTOR_CLASSNAME , "<STR_LIT>" ) ; setBuilderOptions ( builder ) ; modelToMapping = new HashMap < Class , Class < ? extends BaseMapping > > ( mappingClasses . size ( ) ) ; for ( Class mappingClass : mappingClasses ) { if ( BaseMapping . class . isAssignableFrom ( mappingClass ) ) { Type [ ] interfaces = mappingClass . getGenericInterfaces ( ) ; if ( ParameterValidation . existsAndIsNotEmpty ( interfaces ) ) { Class type = ( Class ) ( ( ParameterizedType ) interfaces [ <NUM_LIT:0> ] ) . getActualTypeArguments ( ) [ <NUM_LIT:0> ] ; modelToMapping . put ( type , mappingClass ) ; } } builder . add ( mappingClass ) ; } chrome = builder . build ( ) ; } protected abstract void setBuilderOptions ( ChromatticBuilder builder ) ; public ChromatticSession getSession ( ) { ChromatticSession chromatticSession = sessionHolder . get ( ) ; if ( chromatticSession == null ) { ChromatticSession session = chrome . openSession ( ) ; sessionHolder . set ( session ) ; return session ; } else { return chromatticSession ; } } public void closeSession ( boolean save ) { ChromatticSession session = getOpenedSessionOrFail ( ) ; if ( save ) { synchronized ( this ) { session . save ( ) ; } } session . close ( ) ; sessionHolder . set ( null ) ; } private ChromatticSession getOpenedSessionOrFail ( ) { ChromatticSession session = sessionHolder . get ( ) ; if ( session == null ) { throw new IllegalStateException ( "<STR_LIT>" ) ; } return session ; } public synchronized void save ( ) { getOpenedSessionOrFail ( ) . save ( ) ; } public < T > boolean delete ( T toDelete , StoresByPathManager < T > manager ) { Class < ? extends Object > modelClass = toDelete . getClass ( ) ; Class < ? extends BaseMapping > baseMappingClass = modelToMapping . get ( modelClass ) ; if ( baseMappingClass == null ) { throw new IllegalArgumentException ( "<STR_LIT>" + modelClass . getName ( ) ) ; } ChromatticSession session = getSession ( ) ; Object old = session . findByPath ( baseMappingClass , manager . getChildPath ( toDelete ) ) ; if ( old != null ) { session . remove ( old ) ; final LastModified lastModified = manager . lastModifiedToUpdateOnDelete ( session ) ; if ( lastModified != null ) { lastModified . setLastModified ( System . currentTimeMillis ( ) ) ; } closeSession ( true ) ; return true ; } else { closeSession ( false ) ; return false ; } } } </s>
|
<s> package org . gatein . wsrp . producer . state ; import org . chromattic . api . ChromatticSession ; import org . gatein . common . util . ParameterValidation ; import org . gatein . pc . api . state . PropertyMap ; import org . gatein . pc . portlet . state . InvalidStateIdException ; import org . gatein . pc . portlet . state . NoSuchStateException ; import org . gatein . pc . portlet . state . producer . AbstractPortletStatePersistenceManager ; import org . gatein . pc . portlet . state . producer . PortletStateContext ; import org . gatein . wsrp . jcr . ChromatticPersister ; import org . gatein . wsrp . producer . state . mapping . PortletStateContextMapping ; import org . gatein . wsrp . producer . state . mapping . PortletStateContextsMapping ; import org . gatein . wsrp . producer . state . mapping . PortletStateMapping ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; public class JCRPortletStatePersistenceManager extends AbstractPortletStatePersistenceManager { private ChromatticPersister persister ; private static final String PATH = PortletStateContextsMapping . NODE_NAME + "<STR_LIT:/>" ; public static final List < Class > mappingClasses = new ArrayList < Class > ( <NUM_LIT:3> ) ; static { Collections . addAll ( mappingClasses , PortletStateContextsMapping . class , PortletStateContextMapping . class , PortletStateMapping . class ) ; } public JCRPortletStatePersistenceManager ( ChromatticPersister persister ) throws Exception { ParameterValidation . throwIllegalArgExceptionIfNull ( persister , "<STR_LIT>" ) ; this . persister = persister ; } private PortletStateContextsMapping getContexts ( ChromatticSession session ) { PortletStateContextsMapping portletStateContexts = session . findByPath ( PortletStateContextsMapping . class , PortletStateContextsMapping . NODE_NAME ) ; if ( portletStateContexts == null ) { portletStateContexts = session . insert ( PortletStateContextsMapping . class , PortletStateContextsMapping . NODE_NAME ) ; } return portletStateContexts ; } @ Override public void updateState ( String stateId , PropertyMap propertyMap ) throws NoSuchStateException , InvalidStateIdException { ParameterValidation . throwIllegalArgExceptionIfNull ( propertyMap , "<STR_LIT>" ) ; ChromatticSession session = persister . getSession ( ) ; PortletStateContextMapping pscm = getPortletStateContextMapping ( session , stateId ) ; PortletStateMapping psm = pscm . getState ( ) ; psm . setProperties ( propertyMap ) ; persister . closeSession ( true ) ; } @ Override protected PortletStateContext getStateContext ( String stateId ) { ChromatticSession session = persister . getSession ( ) ; PortletStateContextMapping pscm = getPortletStateContextMapping ( session , stateId ) ; PortletStateContext context ; if ( pscm == null ) { context = null ; } else { context = pscm . toPortletStateContext ( ) ; } persister . closeSession ( false ) ; return context ; } @ Override protected String createStateContext ( String portletId , PropertyMap propertyMap ) { ChromatticSession session = persister . getSession ( ) ; String encodedForPath = ChromatticPersister . PortletNameFormatter . encode ( portletId ) ; PortletStateContextMapping pscm = session . findByPath ( PortletStateContextMapping . class , PATH + encodedForPath ) ; if ( pscm == null ) { PortletStateContextsMapping portletStateContexts = getContexts ( session ) ; pscm = portletStateContexts . createPortletStateContext ( portletId ) ; portletStateContexts . getPortletStateContexts ( ) . add ( pscm ) ; } PortletStateMapping psm = pscm . getState ( ) ; psm . setPortletID ( pscm . getPortletId ( ) ) ; psm . setProperties ( propertyMap ) ; persister . closeSession ( true ) ; return pscm . getPersistentKey ( ) ; } @ Override protected PortletStateContext destroyStateContext ( String stateId ) { ChromatticSession session = persister . getSession ( ) ; PortletStateContextMapping pscm = getPortletStateContextMapping ( session , stateId ) ; PortletStateContext result ; if ( pscm == null ) { result = null ; } else { getContexts ( session ) . getPortletStateContexts ( ) . remove ( pscm ) ; result = pscm . toPortletStateContext ( ) ; } persister . closeSession ( true ) ; return result ; } @ Override protected void updateStateContext ( PortletStateContext stateContext ) { throw new UnsupportedOperationException ( "<STR_LIT>" ) ; } private PortletStateContextMapping getPortletStateContextMapping ( ChromatticSession session , String stateId ) { return getContexts ( session ) . findPortletStateContextById ( stateId ) ; } } </s>
|
<s> package org . gatein . wsrp . producer . state . mapping ; import org . chromattic . api . annotations . Create ; import org . chromattic . api . annotations . FindById ; import org . chromattic . api . annotations . FormattedBy ; import org . chromattic . api . annotations . OneToMany ; import org . chromattic . api . annotations . PrimaryType ; import org . gatein . wsrp . jcr . ChromatticPersister ; import java . util . Collection ; @ PrimaryType ( name = PortletStateContextsMapping . NODE_NAME ) @ FormattedBy ( ChromatticPersister . PortletNameFormatter . class ) public abstract class PortletStateContextsMapping { public static final String NODE_NAME = "<STR_LIT>" ; @ OneToMany public abstract Collection < PortletStateContextMapping > getPortletStateContexts ( ) ; @ Create public abstract PortletStateContextMapping createPortletStateContext ( String id ) ; @ FindById public abstract PortletStateContextMapping findPortletStateContextById ( String id ) ; } </s>
|
<s> package org . gatein . wsrp . producer . state . mapping ; import org . chromattic . api . annotations . Id ; import org . chromattic . api . annotations . MappedBy ; import org . chromattic . api . annotations . Name ; import org . chromattic . api . annotations . OneToOne ; import org . chromattic . api . annotations . Owner ; import org . chromattic . api . annotations . PrimaryType ; import org . gatein . pc . portlet . impl . state . producer . PortletStateContextImpl ; import org . gatein . pc . portlet . state . producer . PortletStateContext ; @ PrimaryType ( name = PortletStateContextMapping . NODE_NAME ) public abstract class PortletStateContextMapping { public static final String NODE_NAME = "<STR_LIT>" ; @ Id public abstract String getPersistentKey ( ) ; @ Name public abstract String getPortletId ( ) ; @ OneToOne @ Owner @ MappedBy ( "<STR_LIT:state>" ) public abstract PortletStateMapping getState ( ) ; public PortletStateContext toPortletStateContext ( ) { PortletStateMapping psm = getState ( ) ; String portletId = psm . getPortletID ( ) ; if ( getPortletId ( ) . equals ( portletId ) ) { PortletStateContextImpl context = new PortletStateContextImpl ( getPersistentKey ( ) , portletId , psm . getPropertiesAsPropertyMap ( ) ) ; context . getState ( ) . setTerminationTime ( psm . getTerminationTime ( ) ) ; return context ; } else { throw new IllegalStateException ( "<STR_LIT>" + getPortletId ( ) + "<STR_LIT>" + portletId + "<STR_LIT:'>" ) ; } } } </s>
|
<s> package org . gatein . wsrp . producer . state . mapping ; import org . chromattic . api . annotations . PrimaryType ; import org . chromattic . api . annotations . Properties ; import org . chromattic . api . annotations . Property ; import org . gatein . pc . api . state . PropertyMap ; import org . gatein . pc . portlet . state . SimplePropertyMap ; import org . gatein . wsrp . jcr . mapping . MappedMap ; import java . util . Arrays ; import java . util . Date ; import java . util . List ; import java . util . Map ; @ PrimaryType ( name = PortletStateMapping . NODE_NAME ) public abstract class PortletStateMapping { public static final String NODE_NAME = "<STR_LIT>" ; private static final String PORTLET_ID = "<STR_LIT>" ; private static final String TERMINATION_TIME = "<STR_LIT>" ; private static final ObjectToStringListConverter VALUE_CONVERTER = new ObjectToStringListConverter ( ) ; private static final MappedMap < String , List < String > > mappedMap = new MappedMap < String , List < String > > ( MappedMap . IDENTITY_KEY_CONVERTER , VALUE_CONVERTER , PORTLET_ID , TERMINATION_TIME ) ; @ Property ( name = PORTLET_ID ) public abstract String getPortletID ( ) ; public abstract void setPortletID ( String portletId ) ; @ Properties public abstract Map < String , Object > getProperties ( ) ; @ Property ( name = TERMINATION_TIME ) public abstract Date getTerminationTime ( ) ; public abstract void setTerminationTime ( Date terminationTime ) ; public PropertyMap getPropertiesAsPropertyMap ( ) { Map < String , Object > map = getProperties ( ) ; if ( ! map . isEmpty ( ) ) { return new SimplePropertyMap ( mappedMap . toExternalMap ( map ) ) ; } else { return new SimplePropertyMap ( ) ; } } public void setProperties ( PropertyMap props ) { mappedMap . initFrom ( props , getProperties ( ) ) ; } public static String join ( String separator , List < String > strings ) { if ( strings == null ) { return null ; } StringBuilder sb = new StringBuilder ( ) ; for ( int i = <NUM_LIT:0> ; i < strings . size ( ) ; i ++ ) { Object o = strings . get ( i ) ; if ( i > <NUM_LIT:0> ) { sb . append ( separator ) ; } sb . append ( o ) ; } return sb . toString ( ) ; } public static String [ ] split ( String separator , String s ) { if ( s == null ) { return null ; } return split ( s , <NUM_LIT:0> , <NUM_LIT:0> , separator ) ; } private static String [ ] split ( String s , int fromIndex , int index , String separator ) { int toIndex = s . indexOf ( separator , fromIndex ) ; String [ ] chunks ; if ( toIndex == - <NUM_LIT:1> ) { chunks = new String [ index + <NUM_LIT:1> ] ; toIndex = s . length ( ) ; } else { chunks = split ( s , toIndex + separator . length ( ) , index + <NUM_LIT:1> , separator ) ; } chunks [ index ] = s . substring ( fromIndex , toIndex ) ; return chunks ; } private static class ObjectToStringListConverter implements MappedMap . Converter < Object , List < String > > { public List < String > fromInternal ( Object o ) { return Arrays . asList ( split ( "<STR_LIT:U+002C>" , ( String ) o ) ) ; } public String toInternal ( List < String > strings ) { return join ( "<STR_LIT:U+002C>" , strings ) ; } } } </s>
|
<s> package org . gatein . wsrp . producer . config ; import org . chromattic . api . ChromatticSession ; import org . gatein . common . util . ParameterValidation ; import org . gatein . wsrp . jcr . ChromatticPersister ; import org . gatein . wsrp . producer . config . impl . AbstractProducerConfigurationService ; import org . gatein . wsrp . producer . config . impl . xml . SimpleXMLProducerConfigurationService ; import org . gatein . wsrp . producer . config . mapping . ProducerConfigurationMapping ; import org . gatein . wsrp . producer . config . mapping . RegistrationRequirementsMapping ; import org . gatein . wsrp . registration . mapping . RegistrationPropertyDescriptionMapping ; import java . io . InputStream ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; public class JCRProducerConfigurationService extends AbstractProducerConfigurationService { private static String PRODUCER_CONFIGURATION_PATH = ProducerConfigurationMapping . NODE_NAME ; private InputStream defaultConfigurationIS ; private ChromatticPersister persister ; public static final List < Class > mappingClasses = new ArrayList < Class > ( <NUM_LIT:3> ) ; static { Collections . addAll ( mappingClasses , ProducerConfigurationMapping . class , RegistrationRequirementsMapping . class , RegistrationPropertyDescriptionMapping . class ) ; } public JCRProducerConfigurationService ( ChromatticPersister persister ) throws Exception { ParameterValidation . throwIllegalArgExceptionIfNull ( persister , "<STR_LIT>" ) ; this . persister = persister ; } public void setConfigurationIS ( InputStream is ) { this . defaultConfigurationIS = is ; } protected void loadConfiguration ( ) throws Exception { ChromatticSession session = persister . getSession ( ) ; ProducerConfigurationMapping pcm = session . findByPath ( ProducerConfigurationMapping . class , PRODUCER_CONFIGURATION_PATH ) ; if ( pcm == null ) { pcm = session . insert ( ProducerConfigurationMapping . class , PRODUCER_CONFIGURATION_PATH ) ; ProducerConfigurationService service = new SimpleXMLProducerConfigurationService ( defaultConfigurationIS ) ; service . reloadConfiguration ( ) ; configuration = service . getConfiguration ( ) ; pcm . initFrom ( configuration ) ; } else { configuration = pcm . toProducerConfiguration ( ) ; } persister . closeSession ( true ) ; } public void saveConfiguration ( ) throws Exception { ChromatticSession session = persister . getSession ( ) ; ProducerConfigurationMapping pcm = session . findByPath ( ProducerConfigurationMapping . class , PRODUCER_CONFIGURATION_PATH ) ; if ( pcm == null ) { pcm = session . insert ( ProducerConfigurationMapping . class , PRODUCER_CONFIGURATION_PATH ) ; } pcm . initFrom ( configuration ) ; persister . closeSession ( true ) ; } } </s>
|
<s> package org . gatein . wsrp . producer . config . mapping ; import org . chromattic . api . annotations . Create ; import org . chromattic . api . annotations . FindById ; import org . chromattic . api . annotations . OneToMany ; import org . chromattic . api . annotations . PrimaryType ; import org . chromattic . api . annotations . Property ; import org . gatein . registration . RegistrationPolicy ; import org . gatein . registration . policies . DefaultRegistrationPolicy ; import org . gatein . registration . policies . RegistrationPolicyWrapper ; import org . gatein . wsrp . producer . config . ProducerRegistrationRequirements ; import org . gatein . wsrp . producer . config . impl . ProducerRegistrationRequirementsImpl ; import org . gatein . wsrp . registration . RegistrationPropertyDescription ; import org . gatein . wsrp . registration . mapping . RegistrationPropertyDescriptionMapping ; import java . util . List ; @ PrimaryType ( name = RegistrationRequirementsMapping . NODE_NAME ) public abstract class RegistrationRequirementsMapping { public static final String NODE_NAME = "<STR_LIT>" ; @ Property ( name = "<STR_LIT>" ) public abstract boolean getRegistrationRequired ( ) ; public abstract void setRegistrationRequired ( boolean requiresRegistration ) ; @ Property ( name = "<STR_LIT>" ) public abstract boolean getRegistrationRequiredForFullDescription ( ) ; public abstract void setRegistrationRequiredForFullDescription ( boolean fullServiceDescriptionRequiresRegistration ) ; @ Property ( name = "<STR_LIT>" ) public abstract String getPolicyClassName ( ) ; public abstract void setPolicyClassName ( String policyClassName ) ; @ Property ( name = "<STR_LIT>" ) public abstract String getValidatorClassName ( ) ; public abstract void setValidatorClassName ( String validatorClassName ) ; @ OneToMany public abstract List < RegistrationPropertyDescriptionMapping > getRegistrationPropertyDescriptions ( ) ; @ Create public abstract RegistrationPropertyDescriptionMapping createRegistrationPropertyDescription ( String propertyName ) ; @ FindById public abstract RegistrationPropertyDescriptionMapping findRegistrationPropertyDescriptionById ( String id ) ; public void initFrom ( ProducerRegistrationRequirements registrationRequirements ) { setRegistrationRequired ( registrationRequirements . isRegistrationRequired ( ) ) ; setRegistrationRequiredForFullDescription ( registrationRequirements . isRegistrationRequiredForFullDescription ( ) ) ; RegistrationPolicy policy = registrationRequirements . getPolicy ( ) ; if ( policy != null ) { setPolicyClassName ( policy . getClassName ( ) ) ; RegistrationPolicy unwrap = RegistrationPolicyWrapper . unwrap ( policy ) ; if ( unwrap instanceof DefaultRegistrationPolicy ) { DefaultRegistrationPolicy drp = ( DefaultRegistrationPolicy ) unwrap ; setValidatorClassName ( drp . getValidator ( ) . getClass ( ) . getName ( ) ) ; } } List < RegistrationPropertyDescriptionMapping > rpdms = getRegistrationPropertyDescriptions ( ) ; rpdms . clear ( ) ; for ( RegistrationPropertyDescription desc : registrationRequirements . getRegistrationProperties ( ) . values ( ) ) { RegistrationPropertyDescriptionMapping rpdm = createRegistrationPropertyDescription ( desc . getNameAsString ( ) ) ; rpdms . add ( rpdm ) ; rpdm . initFrom ( desc ) ; } } public ProducerRegistrationRequirements toProducerRegistrationRequirements ( ) { ProducerRegistrationRequirements req = new ProducerRegistrationRequirementsImpl ( ) ; req . setRegistrationRequired ( getRegistrationRequired ( ) ) ; req . setRegistrationRequiredForFullDescription ( getRegistrationRequiredForFullDescription ( ) ) ; req . reloadPolicyFrom ( getPolicyClassName ( ) , getValidatorClassName ( ) ) ; for ( RegistrationPropertyDescriptionMapping rpdm : getRegistrationPropertyDescriptions ( ) ) { req . addRegistrationProperty ( rpdm . toRegistrationPropertyDescription ( ) ) ; } return req ; } } </s>
|
<s> package org . gatein . wsrp . producer . config . mapping ; import org . chromattic . api . annotations . MappedBy ; import org . chromattic . api . annotations . OneToOne ; import org . chromattic . api . annotations . Owner ; import org . chromattic . api . annotations . PrimaryType ; import org . chromattic . api . annotations . Property ; import org . gatein . wsrp . producer . config . ProducerConfiguration ; import org . gatein . wsrp . producer . config . ProducerRegistrationRequirements ; import org . gatein . wsrp . producer . config . impl . ProducerConfigurationImpl ; @ PrimaryType ( name = ProducerConfigurationMapping . NODE_NAME ) public abstract class ProducerConfigurationMapping { public static final String NODE_NAME = "<STR_LIT>" ; @ Property ( name = "<STR_LIT>" ) public abstract boolean getUsingStrictMode ( ) ; public abstract void setUsingStrictMode ( boolean strict ) ; @ OneToOne @ Owner @ MappedBy ( "<STR_LIT>" ) public abstract RegistrationRequirementsMapping getRegistrationRequirements ( ) ; public void initFrom ( ProducerConfiguration configuration ) { setUsingStrictMode ( configuration . isUsingStrictMode ( ) ) ; RegistrationRequirementsMapping rrm = getRegistrationRequirements ( ) ; rrm . initFrom ( configuration . getRegistrationRequirements ( ) ) ; } public ProducerConfiguration toProducerConfiguration ( ) { ProducerConfigurationImpl configuration = new ProducerConfigurationImpl ( ) ; configuration . setUsingStrictMode ( getUsingStrictMode ( ) ) ; ProducerRegistrationRequirements req = getRegistrationRequirements ( ) . toProducerRegistrationRequirements ( ) ; configuration . setRegistrationRequirements ( req ) ; return configuration ; } } </s>
|
<s> package org . gatein . wsrp ; import junit . framework . TestCase ; import org . gatein . pc . api . ContainerURL ; import org . gatein . pc . api . Mode ; import org . gatein . pc . api . ParametersStateString ; import org . gatein . pc . api . ResourceURL ; import org . gatein . pc . api . StateString ; import org . gatein . pc . api . WindowState ; import org . gatein . pc . api . cache . CacheLevel ; import org . gatein . wsrp . spec . v2 . WSRP2RewritingConstants ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Map ; import java . util . Set ; public class WSRPPortletURLTestCase extends TestCase { @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; WSRPPortletURL . setStrict ( true ) ; } public void testResourceURL ( ) { String expected = "<STR_LIT>" + "<STR_LIT>" ; WSRPPortletURL url = WSRPPortletURL . create ( expected ) ; assertTrue ( url instanceof WSRPResourceURL ) ; WSRPResourceURL resource = ( WSRPResourceURL ) url ; assertFalse ( resource . requiresRewrite ( ) ) ; assertEquals ( "<STR_LIT>" , resource . getResourceURL ( ) . toExternalForm ( ) ) ; Map < String , String > resourceMap = WSRPResourceURL . decodeResource ( resource . getResourceId ( ) ) ; String resourceURL = resourceMap . get ( WSRPRewritingConstants . RESOURCE_URL ) ; assertEquals ( "<STR_LIT>" , resourceURL ) ; assertNull ( resourceMap . get ( WSRP2RewritingConstants . RESOURCE_ID ) ) ; assertEquals ( "<STR_LIT:false>" , resourceMap . get ( WSRP2RewritingConstants . RESOURCE_PREFER_OPERATION ) ) ; } public void testResourceID ( ) { String expected = "<STR_LIT>" + "<STR_LIT>" ; WSRPPortletURL url = WSRPPortletURL . create ( expected ) ; assertTrue ( url instanceof WSRPResourceURL ) ; WSRPResourceURL resource = ( WSRPResourceURL ) url ; assertFalse ( resource . requiresRewrite ( ) ) ; assertNull ( resource . getResourceURL ( ) ) ; Map < String , String > resourceMap = WSRPResourceURL . decodeResource ( resource . getResourceId ( ) ) ; String resourceID = resourceMap . get ( WSRP2RewritingConstants . RESOURCE_ID ) ; assertEquals ( "<STR_LIT>" , resourceID ) ; assertNull ( resourceMap . get ( WSRPRewritingConstants . RESOURCE_URL ) ) ; assertEquals ( "<STR_LIT:false>" , resourceMap . get ( WSRP2RewritingConstants . RESOURCE_PREFER_OPERATION ) ) ; } public void testResourceIDToken ( ) { Map < String , String > resourceMap = WSRPResourceURL . decodeResource ( "<STR_LIT>" ) ; String resourceID = resourceMap . get ( WSRP2RewritingConstants . RESOURCE_ID ) ; assertEquals ( "<STR_LIT>" , resourceID ) ; assertNull ( resourceMap . get ( WSRPRewritingConstants . RESOURCE_URL ) ) ; assertNull ( resourceMap . get ( WSRP2RewritingConstants . RESOURCE_PREFER_OPERATION ) ) ; } public void testResources ( ) { String expected = "<STR_LIT>" + "<STR_LIT>" ; WSRPPortletURL url = WSRPPortletURL . create ( expected ) ; assertTrue ( url instanceof WSRPResourceURL ) ; WSRPResourceURL resource = ( WSRPResourceURL ) url ; assertFalse ( resource . requiresRewrite ( ) ) ; assertEquals ( "<STR_LIT>" , resource . getResourceURL ( ) . toExternalForm ( ) ) ; Map < String , String > resourceMap = WSRPResourceURL . decodeResource ( resource . getResourceId ( ) ) ; String resourceID = resourceMap . get ( WSRP2RewritingConstants . RESOURCE_ID ) ; assertEquals ( "<STR_LIT>" , resourceID ) ; String resourceURL = resourceMap . get ( WSRPRewritingConstants . RESOURCE_URL ) ; assertEquals ( "<STR_LIT>" , resourceURL ) ; assertEquals ( "<STR_LIT:false>" , resourceMap . get ( WSRP2RewritingConstants . RESOURCE_PREFER_OPERATION ) ) ; } public void testResourcesNoRequiresRewrite ( ) { String expected = "<STR_LIT>" + "<STR_LIT>" ; WSRPPortletURL url = WSRPPortletURL . create ( expected ) ; assertTrue ( url instanceof WSRPResourceURL ) ; WSRPResourceURL resource = ( WSRPResourceURL ) url ; assertFalse ( resource . requiresRewrite ( ) ) ; assertEquals ( "<STR_LIT>" , resource . getResourceURL ( ) . toExternalForm ( ) ) ; Map < String , String > resourceMap = WSRPResourceURL . decodeResource ( resource . getResourceId ( ) ) ; String resourceID = resourceMap . get ( WSRP2RewritingConstants . RESOURCE_ID ) ; assertEquals ( "<STR_LIT>" , resourceID ) ; String resourceURL = resourceMap . get ( WSRPRewritingConstants . RESOURCE_URL ) ; assertEquals ( "<STR_LIT>" , resourceURL ) ; assertEquals ( "<STR_LIT:false>" , resourceMap . get ( WSRP2RewritingConstants . RESOURCE_PREFER_OPERATION ) ) ; } public void testResourcesNoResourceURL ( ) { String expected = "<STR_LIT>" + "<STR_LIT>" ; WSRPPortletURL url = WSRPPortletURL . create ( expected ) ; assertTrue ( url instanceof WSRPResourceURL ) ; WSRPResourceURL resource = ( WSRPResourceURL ) url ; assertFalse ( resource . requiresRewrite ( ) ) ; Map < String , String > resourceMap = WSRPResourceURL . decodeResource ( resource . getResourceId ( ) ) ; String resourceID = resourceMap . get ( WSRP2RewritingConstants . RESOURCE_ID ) ; assertEquals ( "<STR_LIT>" , resourceID ) ; assertEquals ( "<STR_LIT:false>" , resourceMap . get ( WSRP2RewritingConstants . RESOURCE_PREFER_OPERATION ) ) ; } public void testPreferOperation ( ) { String expected = "<STR_LIT>" + "<STR_LIT>" ; WSRPPortletURL url = WSRPPortletURL . create ( expected ) ; assertTrue ( url instanceof WSRPResourceURL ) ; WSRPResourceURL resource = ( WSRPResourceURL ) url ; assertFalse ( resource . requiresRewrite ( ) ) ; assertEquals ( "<STR_LIT>" , resource . getResourceURL ( ) . toExternalForm ( ) ) ; Map < String , String > resourceMap = WSRPResourceURL . decodeResource ( resource . getResourceId ( ) ) ; String resourceID = resourceMap . get ( WSRP2RewritingConstants . RESOURCE_ID ) ; assertEquals ( "<STR_LIT>" , resourceID ) ; String resourceURL = resourceMap . get ( WSRPRewritingConstants . RESOURCE_URL ) ; assertEquals ( "<STR_LIT>" , resourceURL ) ; String preferOperation = resourceMap . get ( WSRP2RewritingConstants . RESOURCE_PREFER_OPERATION ) ; assertEquals ( "<STR_LIT:true>" , preferOperation ) ; } public void testShouldSetPreferOperationToTrueWhenResourceIdIsPresent ( ) { ResourceURL resourceURL = new TestResourceURL ( TestResourceURL . RESID , TestResourceURL . DEFAULT_NS , CacheLevel . FULL ) ; WSRPPortletURL url = WSRPPortletURL . create ( resourceURL , false , WSRPPortletURL . URLContext . EMPTY ) ; String actual = url . toString ( ) ; assertTrue ( actual . contains ( "<STR_LIT>" ) ) ; assertTrue ( actual . contains ( "<STR_LIT>" + TestResourceURL . RESID ) ) ; assertTrue ( actual . contains ( "<STR_LIT>" ) ) ; } public void testShouldProperlyTransmitResourceState ( ) { ResourceURL resourceURL = new TestResourceURL ( "<STR_LIT>" , "<STR_LIT>" ) ; WSRPPortletURL url = WSRPPortletURL . create ( resourceURL , false , WSRPPortletURL . URLContext . EMPTY ) ; assertTrue ( url instanceof WSRPResourceURL ) ; WSRPResourceURL resource = ( WSRPResourceURL ) url ; StateString resourceState = resource . getResourceState ( ) ; assertNotNull ( resourceState ) ; String resourceAsString = resource . toString ( ) ; url = WSRPPortletURL . create ( resourceAsString ) ; assertTrue ( url instanceof WSRPResourceURL ) ; resource = ( WSRPResourceURL ) url ; resourceState = resource . getResourceState ( ) ; assertNotNull ( resourceState ) ; Map < String , String [ ] > state = StateString . decodeOpaqueValue ( resourceState . getStringValue ( ) ) ; assertEquals ( "<STR_LIT>" , state . get ( "<STR_LIT>" ) [ <NUM_LIT:0> ] ) ; } public void testSecureInteraction ( ) { String expected = "<STR_LIT>" + "<STR_LIT>" ; WSRPPortletURL url = WSRPPortletURL . create ( expected ) ; assertTrue ( url instanceof WSRPActionURL ) ; WSRPActionURL actionURL = ( WSRPActionURL ) url ; assertTrue ( url . isSecure ( ) ) ; assertEquals ( "<STR_LIT>" , actionURL . getNavigationalState ( ) . getStringValue ( ) ) ; assertEquals ( "<STR_LIT>" , actionURL . getInteractionState ( ) . getStringValue ( ) ) ; } public void testDifferentModeAndWindowState ( ) { String expected = "<STR_LIT>" ; WSRPPortletURL url = WSRPPortletURL . create ( expected ) ; assertTrue ( url instanceof WSRPRenderURL ) ; assertEquals ( Mode . HELP , url . getMode ( ) ) ; assertEquals ( WindowState . MAXIMIZED , url . getWindowState ( ) ) ; } public void testMinimal ( ) { String minimalURLType = "<STR_LIT>" ; WSRPPortletURL url = WSRPPortletURL . create ( minimalURLType ) ; assertTrue ( url instanceof WSRPRenderURL ) ; } public void testInvalidParameterName ( ) { String message = "<STR_LIT>" ; String invalid = "<STR_LIT>" ; checkInvalidURL ( invalid , message , "<STR_LIT:foo>" ) ; } public void testExtraParametersRelaxedValidation ( ) { WSRPPortletURL . setStrict ( false ) ; String validInRelaxedMode = "<STR_LIT>" ; WSRPPortletURL url = WSRPPortletURL . create ( validInRelaxedMode ) ; assertTrue ( url instanceof WSRPRenderURL ) ; assertTrue ( url . toString ( ) . contains ( "<STR_LIT>" ) ) ; validInRelaxedMode = "<STR_LIT>" ; url = WSRPPortletURL . create ( validInRelaxedMode ) ; assertTrue ( url instanceof WSRPRenderURL ) ; assertTrue ( url . toString ( ) . endsWith ( "<STR_LIT>" ) ) ; String stillInvalid = "<STR_LIT>" ; checkInvalidURL ( stillInvalid , "<STR_LIT>" , WSRPRewritingConstants . END_WSRP_REWRITE ) ; } public void testExtraParameters ( ) { String validInRelaxedMode = "<STR_LIT>" ; checkInvalidURL ( validInRelaxedMode , "<STR_LIT>" , "<STR_LIT:foo>" ) ; validInRelaxedMode = "<STR_LIT>" ; checkInvalidURL ( validInRelaxedMode , "<STR_LIT>" , WSRPRewritingConstants . END_WSRP_REWRITE ) ; } public void testInvalidMode ( ) { String message = "<STR_LIT>" ; String invalid = "<STR_LIT>" ; checkInvalidURL ( invalid , message , "<STR_LIT:foo>" ) ; } public void testCustomModeAndWindowState ( ) { Set < String > modes = new HashSet < String > ( ) ; modes . add ( "<STR_LIT>" ) ; Set < String > windowStates = new HashSet < String > ( ) ; windowStates . add ( "<STR_LIT>" ) ; String urlString = "<STR_LIT>" ; WSRPPortletURL url = WSRPPortletURL . create ( urlString , modes , windowStates ) ; assertEquals ( "<STR_LIT>" , url . getMode ( ) . toString ( ) ) ; assertEquals ( "<STR_LIT>" , url . getWindowState ( ) . toString ( ) ) ; } public void testEncodedMode ( ) { String encoded = "<STR_LIT>" ; WSRPPortletURL url = WSRPPortletURL . create ( encoded ) ; assertEquals ( Mode . VIEW , url . getMode ( ) ) ; encoded = "<STR_LIT>" ; url = WSRPPortletURL . create ( encoded ) ; assertEquals ( Mode . EDIT , url . getMode ( ) ) ; } public void testEncodedWindowState ( ) { String encoded = "<STR_LIT>" ; WSRPPortletURL url = WSRPPortletURL . create ( encoded ) ; assertEquals ( WindowState . MAXIMIZED , url . getWindowState ( ) ) ; encoded = "<STR_LIT>" ; url = WSRPPortletURL . create ( encoded ) ; assertEquals ( WindowState . MINIMIZED , url . getWindowState ( ) ) ; } public void testInvalidResourceURLV1 ( ) { String message = "<STR_LIT>" ; String invalid = "<STR_LIT>" ; checkInvalidURL ( invalid , message , WSRPRewritingConstants . RESOURCE_URL ) ; invalid = "<STR_LIT>" ; checkInvalidURL ( invalid , "<STR_LIT>" , "<STR_LIT>" ) ; } public void testNullURL ( ) { try { WSRPPortletURL . create ( null ) ; fail ( "<STR_LIT>" ) ; } catch ( IllegalArgumentException e ) { } } public void testInvalidURLType ( ) { String wrongURLType = "<STR_LIT>" ; try { WSRPPortletURL . create ( wrongURLType ) ; fail ( "<STR_LIT>" ) ; } catch ( IllegalArgumentException e ) { } } public void testProperEndTokenInRelaxedMode ( ) { WSRPPortletURL . setStrict ( false ) ; WSRPPortletURL url = new WSRPPortletURL ( ) { @ Override protected String getURLType ( ) { return WSRPRewritingConstants . URL_TYPE_BLOCKING_ACTION ; } @ Override protected void appendEnd ( StringBuffer sb ) { } } ; assertTrue ( url . toString ( ) . contains ( WSRPRewritingConstants . END_WSRP_REWRITE ) ) ; } private void checkInvalidURL ( String invalid , String message , String mustBeInException ) { try { WSRPPortletURL . create ( invalid ) ; fail ( message + mustBeInException ) ; } catch ( IllegalArgumentException e ) { assertTrue ( e . getLocalizedMessage ( ) . contains ( mustBeInException ) ) ; } } private static class TestContainerURL implements ContainerURL { private Mode mode ; private WindowState ws ; private StateString ns ; private Map < String , String > props ; static final StateString DEFAULT_NS ; static final Map < String , String [ ] > DEFAULT_PARAMS = new HashMap < String , String [ ] > ( <NUM_LIT:3> ) ; static final String PARAM = "<STR_LIT>" ; static final String VALUE = "<STR_LIT:value>" ; static { DEFAULT_PARAMS . put ( PARAM , new String [ ] { VALUE } ) ; DEFAULT_NS = ParametersStateString . create ( DEFAULT_PARAMS ) ; } private TestContainerURL ( Mode mode , WindowState ws , StateString ns , Map < String , String > props ) { this . mode = mode ; this . ws = ws ; this . ns = ns ; this . props = props ; } public Mode getMode ( ) { return mode ; } public WindowState getWindowState ( ) { return ws ; } public StateString getNavigationalState ( ) { return ns ; } public Map < String , String > getProperties ( ) { return props ; } } private static class TestResourceURL extends TestContainerURL implements ResourceURL { private static final String RESID = "<STR_LIT>" ; private String id ; private StateString state ; private CacheLevel cache ; private TestResourceURL ( String id , StateString state , CacheLevel cache ) { super ( Mode . VIEW , WindowState . NORMAL , DEFAULT_NS , null ) ; init ( id , state , cache ) ; } private void init ( String id , StateString state , CacheLevel cache ) { this . id = id ; this . state = state ; this . cache = cache ; } private TestResourceURL ( String param , String value ) { super ( Mode . VIEW , WindowState . NORMAL , DEFAULT_NS , null ) ; HashMap < String , String [ ] > params = new HashMap < String , String [ ] > ( <NUM_LIT:3> ) ; params . put ( param , new String [ ] { value } ) ; init ( RESID , ParametersStateString . create ( params ) , CacheLevel . FULL ) ; } public String getResourceId ( ) { return id ; } public StateString getResourceState ( ) { return state ; } public CacheLevel getCacheability ( ) { return cache ; } } } </s>
|
<s> package org . gatein . wsrp ; import junit . framework . TestCase ; import org . gatein . wsrp . spec . v1 . WSRP1ExceptionFactory ; import org . gatein . wsrp . spec . v2 . WSRP2ExceptionFactory ; import org . oasis . wsrp . v1 . V1OperationFailed ; import org . oasis . wsrp . v1 . V1OperationFailedFault ; import org . oasis . wsrp . v2 . OperationFailed ; import org . oasis . wsrp . v2 . OperationFailedFault ; public class WSRPExceptionFactoryTestCase extends TestCase { public void testCreateWSExceptionV1 ( ) throws Exception { Throwable throwable = new Throwable ( ) ; V1OperationFailed operationFailed = WSRP1ExceptionFactory . createWSException ( V1OperationFailed . class , "<STR_LIT:foo>" , throwable ) ; assertNotNull ( operationFailed ) ; assertEquals ( "<STR_LIT:foo>" , operationFailed . getMessage ( ) ) ; assertNotNull ( operationFailed . getFaultInfo ( ) ) ; assertEquals ( V1OperationFailedFault . class , operationFailed . getFaultInfo ( ) . getClass ( ) ) ; assertEquals ( throwable , operationFailed . getCause ( ) ) ; try { WSRP1ExceptionFactory . createWSException ( Exception . class , "<STR_LIT:foo>" , null ) ; fail ( "<STR_LIT>" ) ; } catch ( IllegalArgumentException e ) { } } public void testCreateWSExceptionV2 ( ) throws Exception { Throwable throwable = new Throwable ( ) ; OperationFailed operationFailed = WSRP2ExceptionFactory . createWSException ( OperationFailed . class , "<STR_LIT:foo>" , throwable ) ; assertNotNull ( operationFailed ) ; assertEquals ( "<STR_LIT:foo>" , operationFailed . getMessage ( ) ) ; assertNotNull ( operationFailed . getFaultInfo ( ) ) ; assertEquals ( OperationFailedFault . class , operationFailed . getFaultInfo ( ) . getClass ( ) ) ; assertEquals ( throwable , operationFailed . getCause ( ) ) ; try { WSRP2ExceptionFactory . createWSException ( Exception . class , "<STR_LIT:foo>" , null ) ; fail ( "<STR_LIT>" ) ; } catch ( IllegalArgumentException e ) { } } } </s>
|
<s> package org . gatein . wsrp ; import junit . framework . TestCase ; public class WSRPConstantsTestCase extends TestCase { public void testServiceVersion ( ) { System . out . println ( "<STR_LIT>" + WSRPConstants . WSRP_SERVICE_VERSION ) ; assertFalse ( WSRPConstants . WSRP_SERVICE_VERSION . equals ( "<STR_LIT>" ) ) ; } } </s>
|
<s> package org . gatein . wsrp ; import junit . framework . TestCase ; import org . gatein . wsrp . spec . v2 . WSRP2RewritingConstants ; import org . gatein . wsrp . test . ExtendedAssert ; import java . util . Collections ; import java . util . Map ; import java . util . TreeMap ; public class WSRPRenderURLTestCase extends TestCase { public void testNullPublicNavigationalState ( ) { WSRPRenderURL url = new WSRPRenderURL ( null , null , false , null , null , WSRPPortletURL . URLContext . EMPTY ) ; assertFalse ( url . toString ( ) . contains ( WSRP2RewritingConstants . NAVIGATIONAL_VALUES ) ) ; } public void testEmptyPublicNavigationalState ( ) { WSRPRenderURL url = new WSRPRenderURL ( null , null , false , null , Collections . < String , String [ ] > emptyMap ( ) , WSRPPortletURL . URLContext . EMPTY ) ; assertFalse ( url . toString ( ) . contains ( WSRP2RewritingConstants . NAVIGATIONAL_VALUES ) ) ; } public void testPublicNavigationalStateEncoding ( ) { Map < String , String [ ] > publicNS = new TreeMap < String , String [ ] > ( ) ; publicNS . put ( "<STR_LIT>" , new String [ ] { "<STR_LIT:value1>" , "<STR_LIT>" } ) ; publicNS . put ( "<STR_LIT>" , null ) ; String actual = WSRPUtils . encodePublicNS ( publicNS ) ; assertEquals ( "<STR_LIT>" , actual ) ; } public void testPublicNavigationalStateDecoding ( ) { Map < String , String [ ] > publicNS = WSRPUtils . decodePublicNS ( "<STR_LIT>" ) ; assertEquals ( <NUM_LIT:2> , publicNS . size ( ) ) ; assertTrue ( publicNS . containsKey ( "<STR_LIT>" ) ) ; assertEquals ( null , publicNS . get ( "<STR_LIT>" ) ) ; ExtendedAssert . assertEquals ( new String [ ] { "<STR_LIT:value1>" , "<STR_LIT>" } , publicNS . get ( "<STR_LIT>" ) ) ; } } </s>
|
<s> package org . gatein . wsrp . handler ; import junit . framework . TestCase ; import org . gatein . wsrp . test . handler . MockSOAPMessage ; import org . gatein . wsrp . test . handler . MockSOAPMessageContext ; import javax . xml . soap . SOAPBody ; import javax . xml . soap . SOAPException ; import javax . xml . ws . handler . soap . SOAPMessageContext ; public class WSRPExtensionHandlerTestCase extends TestCase { private WSRPExtensionHandler handler ; @ Override protected void setUp ( ) throws Exception { handler = new WSRPExtensionHandler ( ) ; } public void testRemoveExtensions ( ) throws SOAPException { MockSOAPMessage message = new MockSOAPMessage ( ) ; message . setMessageBody ( "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" ) ; SOAPMessageContext msgContext = MockSOAPMessageContext . createMessageContext ( message , getClass ( ) . getClassLoader ( ) ) ; handler . handleMessage ( msgContext ) ; SOAPBody body = msgContext . getMessage ( ) . getSOAPBody ( ) ; String asString = body . toString ( ) ; assertFalse ( asString . contains ( "<STR_LIT>" ) ) ; assertFalse ( asString . contains ( "<STR_LIT>" ) ) ; assertFalse ( asString . contains ( "<STR_LIT>" ) ) ; } } </s>
|
<s> package org . gatein . wsrp . spec . v1 ; import java . util . ArrayList ; import java . util . List ; import junit . framework . TestCase ; import org . gatein . wsrp . WSRPTypeFactory ; import org . gatein . wsrp . spec . v2 . ErrorCodes ; import org . gatein . wsrp . spec . v2 . ErrorCodes . Codes ; import org . gatein . wsrp . test . ExtendedAssert ; import org . oasis . wsrp . v1 . V1DestroyFailed ; import org . oasis . wsrp . v1 . V1InvalidSession ; import org . oasis . wsrp . v1 . V1ItemDescription ; import org . oasis . wsrp . v1 . V1MarkupContext ; import org . oasis . wsrp . v1 . V1NamedString ; import org . oasis . wsrp . v1 . V1OperationFailed ; import org . oasis . wsrp . v1 . V1SessionContext ; import org . oasis . wsrp . v2 . FailedPortlets ; import org . oasis . wsrp . v2 . ItemDescription ; import org . oasis . wsrp . v2 . LocalizedString ; import org . oasis . wsrp . v2 . MarkupContext ; import org . oasis . wsrp . v2 . NamedString ; import org . oasis . wsrp . v2 . OperationFailed ; import org . oasis . wsrp . v2 . SessionContext ; import com . google . common . collect . Lists ; public class V2ToV1ConverterTestCase extends TestCase { public void testException ( ) throws Exception { Throwable throwable = new Throwable ( ) ; OperationFailed operationFailed = new OperationFailed ( "<STR_LIT:foo>" , WSRPTypeFactory . createOperationFailedFault ( ) , throwable ) ; V1OperationFailed v1OperationFailed = V2ToV1Converter . toV1Exception ( V1OperationFailed . class , operationFailed ) ; assertNotNull ( v1OperationFailed ) ; assertEquals ( "<STR_LIT:foo>" , v1OperationFailed . getMessage ( ) ) ; assertEquals ( throwable , v1OperationFailed . getCause ( ) ) ; } public void testExceptionMismatch ( ) { Throwable throwable = new Throwable ( ) ; OperationFailed operationFailed = new OperationFailed ( "<STR_LIT:foo>" , WSRPTypeFactory . createOperationFailedFault ( ) , throwable ) ; try { V2ToV1Converter . toV1Exception ( V1InvalidSession . class , operationFailed ) ; fail ( "<STR_LIT>" ) ; } catch ( IllegalArgumentException e ) { } } public void testExceptionWrongRequestedException ( ) { Throwable throwable = new Throwable ( ) ; OperationFailed operationFailed = new OperationFailed ( "<STR_LIT:foo>" , WSRPTypeFactory . createOperationFailedFault ( ) , throwable ) ; try { V2ToV1Converter . toV1Exception ( IllegalArgumentException . class , operationFailed ) ; fail ( "<STR_LIT>" ) ; } catch ( IllegalArgumentException e ) { } } public void testExceptionWrongException ( ) { try { V2ToV1Converter . toV1Exception ( V1OperationFailed . class , new IllegalArgumentException ( ) ) ; fail ( "<STR_LIT>" ) ; } catch ( IllegalArgumentException e ) { } } public void testNamedString ( ) { NamedString namedString = WSRPTypeFactory . createNamedString ( "<STR_LIT>" , "<STR_LIT:value1>" ) ; V1NamedString v1NamedString = convertNamedStringToV1NamedString ( namedString ) ; assertEquals ( "<STR_LIT>" , v1NamedString . getName ( ) ) ; assertEquals ( "<STR_LIT:value1>" , v1NamedString . getValue ( ) ) ; namedString = WSRPTypeFactory . createNamedString ( "<STR_LIT>" , null ) ; v1NamedString = convertNamedStringToV1NamedString ( namedString ) ; assertEquals ( "<STR_LIT>" , v1NamedString . getName ( ) ) ; assertEquals ( "<STR_LIT>" , v1NamedString . getValue ( ) ) ; namedString = WSRPTypeFactory . createNamedString ( "<STR_LIT>" , "<STR_LIT>" ) ; v1NamedString = convertNamedStringToV1NamedString ( namedString ) ; assertEquals ( "<STR_LIT>" , v1NamedString . getName ( ) ) ; assertEquals ( "<STR_LIT>" , v1NamedString . getValue ( ) ) ; } private V1NamedString convertNamedStringToV1NamedString ( NamedString namedString ) { List < NamedString > namedStringList = new ArrayList < NamedString > ( ) ; namedStringList . add ( namedString ) ; List < V1NamedString > v1NamedStringList = Lists . transform ( namedStringList , V2ToV1Converter . NAMEDSTRING ) ; assertEquals ( <NUM_LIT:1> , v1NamedStringList . size ( ) ) ; return v1NamedStringList . iterator ( ) . next ( ) ; } public void testSessionContext ( ) { SessionContext sessionContext = WSRPTypeFactory . createSessionContext ( "<STR_LIT>" , <NUM_LIT:0> ) ; V1SessionContext v1SessionContext = V2ToV1Converter . toV1SessionContext ( sessionContext ) ; assertEquals ( "<STR_LIT>" , v1SessionContext . getSessionID ( ) ) ; assertEquals ( <NUM_LIT:0> , v1SessionContext . getExpires ( ) ) ; sessionContext = WSRPTypeFactory . createSessionContext ( null , <NUM_LIT:0> ) ; v1SessionContext = V2ToV1Converter . toV1SessionContext ( sessionContext ) ; assertNull ( v1SessionContext ) ; sessionContext = WSRPTypeFactory . createSessionContext ( "<STR_LIT>" , <NUM_LIT:0> ) ; v1SessionContext = V2ToV1Converter . toV1SessionContext ( sessionContext ) ; assertNull ( v1SessionContext ) ; } public void testItemDescription ( ) { V1ItemDescription v1ItemDescription = convertItemDescriptionToV1ItemDescription ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ; assertEquals ( "<STR_LIT>" , v1ItemDescription . getDescription ( ) . getValue ( ) ) ; assertEquals ( "<STR_LIT>" , v1ItemDescription . getItemName ( ) ) ; v1ItemDescription = convertItemDescriptionToV1ItemDescription ( null , "<STR_LIT>" , "<STR_LIT>" ) ; assertEquals ( "<STR_LIT>" , v1ItemDescription . getDescription ( ) . getValue ( ) ) ; assertEquals ( "<STR_LIT>" , v1ItemDescription . getItemName ( ) ) ; v1ItemDescription = convertItemDescriptionToV1ItemDescription ( "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ) ; assertEquals ( "<STR_LIT>" , v1ItemDescription . getDescription ( ) . getValue ( ) ) ; assertEquals ( "<STR_LIT>" , v1ItemDescription . getItemName ( ) ) ; v1ItemDescription = convertItemDescriptionToV1ItemDescription ( null , null , "<STR_LIT>" ) ; assertNotNull ( v1ItemDescription . getDescription ( ) . getValue ( ) ) ; assertEquals ( "<STR_LIT>" , v1ItemDescription . getItemName ( ) ) ; } private V1ItemDescription convertItemDescriptionToV1ItemDescription ( String description , String displayName , String itemName ) { LocalizedString descriptionLS = null ; if ( description != null ) { descriptionLS = WSRPTypeFactory . createLocalizedString ( description ) ; } LocalizedString displayNameLS = null ; if ( displayName != null ) { displayNameLS = WSRPTypeFactory . createLocalizedString ( displayName ) ; } ItemDescription itemDescription = WSRPTypeFactory . createItemDescription ( descriptionLS , displayNameLS , itemName ) ; List < ItemDescription > itemDescriptionList = new ArrayList < ItemDescription > ( ) ; itemDescriptionList . add ( itemDescription ) ; List < V1ItemDescription > v1ItemDesciptionList = Lists . transform ( itemDescriptionList , V2ToV1Converter . ITEMDESCRIPTION ) ; assertEquals ( <NUM_LIT:1> , v1ItemDesciptionList . size ( ) ) ; return v1ItemDesciptionList . iterator ( ) . next ( ) ; } public void testDestroyedFailed ( ) { V1DestroyFailed destroyFailed = convertFailedPortletsToDestroyFailed ( "<STR_LIT>" , Codes . OPERATIONFAILED , "<STR_LIT>" ) ; assertEquals ( "<STR_LIT>" , destroyFailed . getPortletHandle ( ) ) ; assertTrue ( destroyFailed . getReason ( ) . contains ( ErrorCodes . getQname ( Codes . OPERATIONFAILED ) . toString ( ) ) ) ; assertTrue ( destroyFailed . getReason ( ) . contains ( "<STR_LIT>" ) ) ; destroyFailed = convertFailedPortletsToDestroyFailed ( "<STR_LIT>" , Codes . OPERATIONFAILED , null ) ; assertEquals ( "<STR_LIT>" , destroyFailed . getPortletHandle ( ) ) ; assertEquals ( ErrorCodes . getQname ( Codes . OPERATIONFAILED ) . toString ( ) , destroyFailed . getReason ( ) ) ; } private V1DestroyFailed convertFailedPortletsToDestroyFailed ( String portletHandle , Codes errorCode , String reason ) { List < String > portletHandles = new ArrayList < String > ( ) ; portletHandles . add ( portletHandle ) ; FailedPortlets failedPortlets = WSRPTypeFactory . createFailedPortlets ( portletHandles , errorCode , reason ) ; List < FailedPortlets > failedPortletsList = new ArrayList < FailedPortlets > ( ) ; failedPortletsList . add ( failedPortlets ) ; List < V1DestroyFailed > destroyFailedList = V2ToV1Converter . toV1DestroyFailed ( failedPortletsList ) ; assertEquals ( <NUM_LIT:1> , destroyFailedList . size ( ) ) ; return destroyFailedList . iterator ( ) . next ( ) ; } public void testToV1MarkupContext ( ) { MarkupContext markupContext = new MarkupContext ( ) ; markupContext . setMimeType ( "<STR_LIT>" ) ; markupContext . setItemString ( "<STR_LIT>" ) ; V1MarkupContext v1MarkupContext = V2ToV1Converter . toV1MarkupContext ( markupContext ) ; assertEquals ( "<STR_LIT>" , v1MarkupContext . getMimeType ( ) ) ; assertEquals ( "<STR_LIT>" , v1MarkupContext . getMarkupString ( ) ) ; assertNull ( v1MarkupContext . getMarkupBinary ( ) ) ; markupContext . setMimeType ( null ) ; try { V2ToV1Converter . toV1MarkupContext ( markupContext ) ; fail ( ) ; } catch ( IllegalArgumentException e ) { } markupContext = new MarkupContext ( ) ; markupContext . setMimeType ( "<STR_LIT>" ) ; markupContext . setItemBinary ( new byte [ ] { <NUM_LIT:2> , <NUM_LIT:1> , <NUM_LIT:3> } ) ; v1MarkupContext = V2ToV1Converter . toV1MarkupContext ( markupContext ) ; assertEquals ( "<STR_LIT>" , v1MarkupContext . getMimeType ( ) ) ; ExtendedAssert . assertEquals ( new byte [ ] { <NUM_LIT:2> , <NUM_LIT:1> , <NUM_LIT:3> } , v1MarkupContext . getMarkupBinary ( ) ) ; assertNull ( v1MarkupContext . getMarkupString ( ) ) ; markupContext . setMimeType ( null ) ; try { V2ToV1Converter . toV1MarkupContext ( markupContext ) ; fail ( ) ; } catch ( IllegalArgumentException e ) { } markupContext = new MarkupContext ( ) ; markupContext . setUseCachedItem ( Boolean . TRUE ) ; v1MarkupContext = V2ToV1Converter . toV1MarkupContext ( markupContext ) ; assertNull ( v1MarkupContext . getMarkupString ( ) ) ; assertNull ( v1MarkupContext . getMarkupBinary ( ) ) ; assertTrue ( v1MarkupContext . isUseCachedMarkup ( ) . booleanValue ( ) ) ; markupContext = new MarkupContext ( ) ; markupContext . setUseCachedItem ( Boolean . FALSE ) ; try { V2ToV1Converter . toV1MarkupContext ( markupContext ) ; fail ( ) ; } catch ( IllegalArgumentException e ) { } } } </s>
|
<s> package org . gatein . wsrp . spec . v1 ; import junit . framework . TestCase ; import org . gatein . wsrp . test . ExtendedAssert ; import org . oasis . wsrp . v1 . V1MarkupContext ; import org . oasis . wsrp . v1 . V1OperationFailed ; import org . oasis . wsrp . v1 . V1OperationFailedFault ; import org . oasis . wsrp . v2 . InvalidSession ; import org . oasis . wsrp . v2 . MarkupContext ; import org . oasis . wsrp . v2 . OperationFailed ; public class V1ToV2ConverterTestCase extends TestCase { public void testToV2Exception ( ) throws Exception { Throwable throwable = new Throwable ( ) ; V1OperationFailed v1OF = new V1OperationFailed ( "<STR_LIT:foo>" , new V1OperationFailedFault ( ) , throwable ) ; OperationFailed operationFailed = V1ToV2Converter . toV2Exception ( OperationFailed . class , v1OF ) ; assertNotNull ( operationFailed ) ; assertEquals ( "<STR_LIT:foo>" , operationFailed . getMessage ( ) ) ; assertEquals ( throwable , operationFailed . getCause ( ) ) ; } public void testToV2ExceptionMismatch ( ) { Throwable throwable = new Throwable ( ) ; V1OperationFailed v1OF = new V1OperationFailed ( "<STR_LIT:foo>" , new V1OperationFailedFault ( ) , throwable ) ; try { V1ToV2Converter . toV2Exception ( InvalidSession . class , v1OF ) ; fail ( "<STR_LIT>" ) ; } catch ( IllegalArgumentException e ) { } } public void testToV2ExceptionWrongRequestedException ( ) { Throwable throwable = new Throwable ( ) ; V1OperationFailed v1OF = new V1OperationFailed ( "<STR_LIT:foo>" , new V1OperationFailedFault ( ) , throwable ) ; try { V1ToV2Converter . toV2Exception ( IllegalArgumentException . class , v1OF ) ; fail ( "<STR_LIT>" ) ; } catch ( IllegalArgumentException e ) { } } public void testToV2ExceptionWrongV1Exception ( ) { try { V1ToV2Converter . toV2Exception ( OperationFailed . class , new IllegalArgumentException ( ) ) ; fail ( "<STR_LIT>" ) ; } catch ( IllegalArgumentException e ) { } } public void testToV2MarkupContext ( ) { V1MarkupContext v1MarkupContext = new V1MarkupContext ( ) ; v1MarkupContext . setMarkupString ( "<STR_LIT>" ) ; v1MarkupContext . setMimeType ( "<STR_LIT>" ) ; MarkupContext markupContext = V1ToV2Converter . toV2MarkupContext ( v1MarkupContext ) ; assertEquals ( "<STR_LIT>" , markupContext . getItemString ( ) ) ; assertEquals ( "<STR_LIT>" , markupContext . getMimeType ( ) ) ; assertNull ( markupContext . getItemBinary ( ) ) ; v1MarkupContext . setMimeType ( null ) ; try { V1ToV2Converter . toV2MarkupContext ( v1MarkupContext ) ; ExtendedAssert . fail ( ) ; } catch ( IllegalArgumentException e ) { } v1MarkupContext = new V1MarkupContext ( ) ; v1MarkupContext . setMarkupBinary ( new byte [ ] { <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> } ) ; v1MarkupContext . setMimeType ( "<STR_LIT>" ) ; markupContext = V1ToV2Converter . toV2MarkupContext ( v1MarkupContext ) ; ExtendedAssert . assertEquals ( new byte [ ] { <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> } , markupContext . getItemBinary ( ) ) ; assertEquals ( "<STR_LIT>" , markupContext . getMimeType ( ) ) ; assertNull ( markupContext . getItemString ( ) ) ; v1MarkupContext . setMimeType ( null ) ; try { V1ToV2Converter . toV2MarkupContext ( v1MarkupContext ) ; fail ( ) ; } catch ( IllegalArgumentException e ) { } v1MarkupContext = new V1MarkupContext ( ) ; v1MarkupContext . setUseCachedMarkup ( Boolean . TRUE ) ; markupContext = V1ToV2Converter . toV2MarkupContext ( v1MarkupContext ) ; assertNull ( markupContext . getItemString ( ) ) ; assertNull ( markupContext . getItemBinary ( ) ) ; assertTrue ( markupContext . isUseCachedItem ( ) . booleanValue ( ) ) ; v1MarkupContext = new V1MarkupContext ( ) ; v1MarkupContext . setUseCachedMarkup ( Boolean . FALSE ) ; try { V1ToV2Converter . toV2MarkupContext ( v1MarkupContext ) ; fail ( ) ; } catch ( IllegalArgumentException e ) { } } } </s>
|
<s> package org . gatein . wsrp . other ; import junit . framework . TestCase ; import org . jboss . xb . binding . SimpleTypeBindings ; import java . util . Calendar ; public class UserContextConverterTestCase extends TestCase { public void testDateFormat ( ) { String dateAsString = "<STR_LIT>" ; Calendar bdate = SimpleTypeBindings . unmarshalDateTime ( dateAsString ) ; String result = SimpleTypeBindings . marshalDateTime ( bdate ) ; assertEquals ( dateAsString , result ) ; } } </s>
|
<s> package org . gatein . wsrp ; import junit . framework . TestCase ; public class WSRPUtilsTestCase extends TestCase { public void testURLRewritingIsActiveByDefault ( ) { assertTrue ( WSRPUtils . getPropertyAccessor ( ) . isURLRewritingActive ( ) ) ; } public void testURLRewritingCanBeDeactivatedUsingASystemProperty ( ) throws ClassNotFoundException , InstantiationException , IllegalAccessException { System . setProperty ( WSRPUtils . DEACTIVATE_URL_REWRITING , "<STR_LIT:true>" ) ; assertFalse ( WSRPUtils . getPropertyAccessor ( true ) . isURLRewritingActive ( ) ) ; } } </s>
|
<s> package org . gatein . wsrp ; import junit . framework . TestCase ; import org . gatein . wsrp . test . support . MockHttpServletRequest ; import static org . gatein . common . net . URLTools . PORT_END ; import static org . gatein . common . net . URLTools . SCH_END ; import static org . gatein . wsrp . test . support . MockHttpServletRequest . * ; public class AbsoluteURLReplacementGeneratorTestCase extends TestCase { private WSRPUtils . AbsoluteURLReplacementGenerator gen ; @ Override protected void setUp ( ) throws Exception { super . setUp ( ) ; gen = new WSRPUtils . AbsoluteURLReplacementGenerator ( MockHttpServletRequest . createMockRequest ( null ) ) ; } public void testNonAbsoluteURL ( ) { String url = "<STR_LIT:foo>" ; assertEquals ( url , gen . getAbsoluteURLFor ( url ) ) ; } public void testAbsoluteURL ( ) { String url = "<STR_LIT>" ; assertEquals ( scheme + SCH_END + serverName + PORT_END + serverPort + url , gen . getAbsoluteURLFor ( url ) ) ; } public void testWSRPEncodedURL ( ) { String url = "<STR_LIT>" ; assertEquals ( url , gen . getAbsoluteURLFor ( url ) ) ; } } </s>
|
<s> package org . gatein . wsrp ; public final class WSRPRewritingConstants { public static final String WSRP_REWRITE = "<STR_LIT>" ; public static final String BEGIN_WSRP_REWRITE_END = "<STR_LIT:?>" ; public static final String BEGIN_WSRP_REWRITE = WSRP_REWRITE + BEGIN_WSRP_REWRITE_END ; public static final int WSRP_REWRITE_PREFIX_LENGTH = <NUM_LIT> ; public static final String END_WSRP_REWRITE = "<STR_LIT:/>" + WSRP_REWRITE ; public static final int WSRP_REWRITE_SUFFIX_LENGTH = <NUM_LIT> ; public static final String URL_TYPE_NAME = "<STR_LIT>" ; public static final String URL_TYPE_BLOCKING_ACTION = "<STR_LIT>" ; public static final String URL_TYPE_RENDER = "<STR_LIT>" ; public static final String URL_TYPE_RESOURCE = "<STR_LIT>" ; public static final String RESOURCE_URL = "<STR_LIT>" ; public static final String RESOURCE_REQUIRES_REWRITE = "<STR_LIT>" ; public static final String NAVIGATIONAL_STATE = "<STR_LIT>" ; public static final String INTERACTION_STATE = "<STR_LIT>" ; public static final String MODE = "<STR_LIT>" ; public static final String WINDOW_STATE = "<STR_LIT>" ; public static final String FRAGMENT_ID = "<STR_LIT>" ; public static final String SECURE_URL = "<STR_LIT>" ; public static final String WSRP_REWRITE_TOKEN_END = "<STR_LIT:_>" ; public static final String WSRP_REWRITE_TOKEN = WSRP_REWRITE + WSRP_REWRITE_TOKEN_END ; public static final String REWRITE_PARAMETER_OPEN = "<STR_LIT:{>" ; public static final String REWRITE_PARAMETER_CLOSE = "<STR_LIT:}>" ; public static final String ENC_OPEN = "<STR_LIT>" ; public static final String ENC_CLOSE = "<STR_LIT>" ; public static final String RESOURCE_URL_DELIMITER = "<STR_LIT:*>" ; public static final String FAKE_RESOURCE_START = WSRP_REWRITE + RESOURCE_URL_DELIMITER ; public static final String FAKE_RESOURCE_REQ_REW = RESOURCE_URL_DELIMITER ; public static final String WSRP_URL = REWRITE_PARAMETER_OPEN + RESOURCE_URL + REWRITE_PARAMETER_CLOSE ; public static final String WSRP_REQUIRES_REWRITE = REWRITE_PARAMETER_OPEN + RESOURCE_REQUIRES_REWRITE + REWRITE_PARAMETER_CLOSE ; public static final String FAKE_RESOURCE_URL = FAKE_RESOURCE_START + WSRP_URL + RESOURCE_URL_DELIMITER + WSRP_REQUIRES_REWRITE + END_WSRP_REWRITE ; public static final String GTNRESOURCE = "<STR_LIT>" ; private WSRPRewritingConstants ( ) { } } </s>
|
<s> package org . gatein . wsrp . registration ; import org . gatein . common . util . ParameterValidation ; import java . io . Serializable ; import java . util . Locale ; public class LocalizedString implements Serializable { private String value ; private Locale locale ; private String resourceName ; public LocalizedString ( String value , Locale locale ) { setValue ( value ) ; this . locale = locale ; } public LocalizedString ( String value ) { this ( value , Locale . getDefault ( ) ) ; } public LocalizedString ( ) { } public LocalizedString ( LocalizedString other ) { ParameterValidation . throwIllegalArgExceptionIfNull ( other , "<STR_LIT>" ) ; this . value = other . value ; this . locale = other . locale ; this . resourceName = other . resourceName ; } public String toString ( ) { return "<STR_LIT>" + "<STR_LIT>" + value + '<STR_LIT>' + "<STR_LIT>" + locale + "<STR_LIT>" + resourceName + '<STR_LIT>' + '<CHAR_LIT:}>' ; } public boolean equals ( Object o ) { if ( this == o ) { return true ; } if ( o == null || getClass ( ) != o . getClass ( ) ) { return false ; } LocalizedString that = ( LocalizedString ) o ; if ( ! locale . equals ( that . locale ) ) { return false ; } if ( resourceName != null ? ! resourceName . equals ( that . resourceName ) : that . resourceName != null ) { return false ; } if ( value != null ? ! value . equals ( that . value ) : that . value != null ) { return false ; } return true ; } public int hashCode ( ) { int result ; result = ( value != null ? value . hashCode ( ) : <NUM_LIT:0> ) ; result = <NUM_LIT:31> * result + locale . hashCode ( ) ; result = <NUM_LIT:31> * result + ( resourceName != null ? resourceName . hashCode ( ) : <NUM_LIT:0> ) ; return result ; } public String getValue ( ) { return value ; } public void setValue ( String value ) { ParameterValidation . throwIllegalArgExceptionIfNullOrEmpty ( value , "<STR_LIT:value>" , "<STR_LIT>" ) ; this . value = value ; } public Locale getLocale ( ) { return locale ; } public void setLocale ( Locale locale ) { ParameterValidation . throwIllegalArgExceptionIfNull ( locale , "<STR_LIT>" ) ; this . locale = locale ; } public String getResourceName ( ) { return resourceName ; } public void setResourceName ( String resourceName ) { this . resourceName = resourceName ; } } </s>
|
<s> package org . gatein . wsrp . registration ; public interface ValueChangeListener { void valueHasChanged ( RegistrationPropertyDescription originating , Object oldValue , Object newValue , boolean isName ) ; } </s>
|
<s> package org . gatein . wsrp . registration ; import org . gatein . common . util . ParameterValidation ; import javax . xml . namespace . QName ; import java . io . Serializable ; import java . net . URI ; import java . net . URISyntaxException ; import java . util . Arrays ; import java . util . Locale ; public class RegistrationPropertyDescription implements PropertyDescription , Serializable { public static final ParameterValidation . ValidationErrorHandler HANDLER = new ParameterValidation . ValidationErrorHandler ( null ) { @ Override protected String internalValidationErrorHandling ( String failedValue ) { throw new IllegalArgumentException ( failedValue + "<STR_LIT>" ) ; } } ; private String key ; private QName name ; private QName type ; private String schemaLocation ; private LocalizedString description ; private LocalizedString hint ; private LocalizedString label ; private String [ ] usages ; private QName [ ] aliases ; private transient ValueChangeListener valueChangeListener ; public RegistrationPropertyDescription ( QName name , QName type ) { this . name = name ; this . type = type ; } public RegistrationPropertyDescription ( String name , QName type ) { this ( new QName ( name ) , type ) ; } public RegistrationPropertyDescription ( ) { } public RegistrationPropertyDescription ( RegistrationPropertyDescription other ) { ParameterValidation . throwIllegalArgExceptionIfNull ( other , "<STR_LIT>" ) ; setName ( QName . valueOf ( other . name . toString ( ) ) ) ; setType ( QName . valueOf ( other . type . toString ( ) ) ) ; if ( other . aliases != null ) { aliases = new QName [ other . aliases . length ] ; System . arraycopy ( other . aliases , <NUM_LIT:0> , aliases , <NUM_LIT:0> , other . aliases . length ) ; } if ( other . description != null ) { setDescription ( new LocalizedString ( other . description ) ) ; } if ( other . hint != null ) { setHint ( new LocalizedString ( other . hint ) ) ; } if ( other . label != null ) { setLabel ( new LocalizedString ( other . label ) ) ; } if ( other . schemaLocation != null ) { setSchemaLocation ( other . schemaLocation ) ; } if ( other . usages != null ) { usages = new String [ other . usages . length ] ; System . arraycopy ( other . usages , <NUM_LIT:0> , usages , <NUM_LIT:0> , other . usages . length ) ; } } @ Override public boolean equals ( Object o ) { if ( this == o ) { return true ; } if ( o == null || getClass ( ) != o . getClass ( ) ) { return false ; } RegistrationPropertyDescription that = ( RegistrationPropertyDescription ) o ; return name . equals ( that . name ) && type . equals ( that . type ) ; } @ Override public int hashCode ( ) { int result = name . hashCode ( ) ; result = <NUM_LIT:31> * result + type . hashCode ( ) ; return result ; } public String toString ( ) { return "<STR_LIT>" + name + "<STR_LIT>" + type + "<STR_LIT>" + hint + "<STR_LIT>" + label ; } public int compareTo ( PropertyDescription o ) { return getName ( ) . toString ( ) . compareTo ( o . getName ( ) . toString ( ) ) ; } public String getPersistentKey ( ) { return key ; } public void setPersistentKey ( String key ) { this . key = key ; } public QName getName ( ) { return name ; } public void setName ( QName name ) { if ( ParameterValidation . isOldAndNewDifferent ( this . name , name ) ) { QName oldName = this . name ; this . name = name ; if ( valueChangeListener != null ) { valueChangeListener . valueHasChanged ( this , oldName , name , true ) ; } } } public void setNameAsString ( String name ) { final String sanitizedName = ParameterValidation . sanitizeFromPatternWithHandler ( name , ParameterValidation . XSS_CHECK , HANDLER ) ; setName ( new QName ( sanitizedName ) ) ; } public String getNameAsString ( ) { return getName ( ) . getLocalPart ( ) ; } public QName getType ( ) { return type ; } public void setType ( QName type ) { this . type = ( QName ) modifyIfNeeded ( this . type , type ) ; } public String getSchemaLocation ( ) { return schemaLocation ; } public URI getSchemaLocationAsURI ( ) { try { return new URI ( schemaLocation ) ; } catch ( URISyntaxException e ) { throw new IllegalArgumentException ( "<STR_LIT>" + schemaLocation + "<STR_LIT>" + e . getLocalizedMessage ( ) ) ; } } public void setSchemaLocation ( String schemaLocation ) { if ( schemaLocation != null ) { try { new URI ( schemaLocation ) ; } catch ( URISyntaxException e ) { throw new IllegalArgumentException ( "<STR_LIT>" + schemaLocation + "<STR_LIT>" + e . getLocalizedMessage ( ) ) ; } this . schemaLocation = ( String ) modifyIfNeeded ( this . schemaLocation , schemaLocation ) ; } } public LocalizedString getDescription ( ) { return description ; } public void setDescription ( LocalizedString description ) { this . description = ( LocalizedString ) modifyIfNeeded ( this . description , description ) ; } public void setDefaultDescription ( String value ) { setDescription ( value == null ? null : new LocalizedString ( value ) ) ; } public LocalizedString getHint ( ) { return hint ; } public void setHint ( LocalizedString hint ) { this . hint = ( LocalizedString ) modifyIfNeeded ( this . hint , hint ) ; } public void setDefaultHint ( String value ) { setHint ( value == null ? null : new LocalizedString ( value ) ) ; } public LocalizedString getLabel ( ) { return label ; } public void setLabel ( LocalizedString label ) { this . label = ( LocalizedString ) modifyIfNeeded ( this . label , label ) ; } public void setDefaultLabel ( String value ) { setLabel ( value == null ? null : new LocalizedString ( value ) ) ; } public String [ ] getUsages ( ) { return usages ; } public void setUsages ( String [ ] usages ) { if ( ! Arrays . equals ( this . usages , usages ) ) { notifyParentOfChangeIfNeeded ( this . usages , usages ) ; if ( usages != null ) { this . usages = new String [ usages . length ] ; System . arraycopy ( usages , <NUM_LIT:0> , this . usages , <NUM_LIT:0> , usages . length ) ; } else { this . usages = null ; } } } public QName [ ] getAliases ( ) { return aliases ; } public void setAliases ( QName [ ] aliases ) { if ( ! Arrays . equals ( this . aliases , aliases ) ) { notifyParentOfChangeIfNeeded ( this . aliases , aliases ) ; if ( aliases != null ) { this . aliases = new QName [ aliases . length ] ; System . arraycopy ( aliases , <NUM_LIT:0> , this . aliases , <NUM_LIT:0> , aliases . length ) ; } else { this . aliases = null ; } } } public void setValueChangeListener ( ValueChangeListener listener ) { this . valueChangeListener = listener ; } public ValueChangeListener getValueChangeListener ( ) { return valueChangeListener ; } private void notifyParentOfChangeIfNeeded ( Object oldValue , Object newValue ) { if ( valueChangeListener != null ) { valueChangeListener . valueHasChanged ( this , oldValue , newValue , false ) ; } } public Object modifyIfNeeded ( Object oldValue , Object newValue ) { if ( ParameterValidation . isOldAndNewDifferent ( oldValue , newValue ) ) { notifyParentOfChangeIfNeeded ( oldValue , newValue ) ; oldValue = newValue ; } return oldValue ; } public Locale getLang ( ) { Locale defaultLocale = Locale . getDefault ( ) ; Locale locale ; locale = label != null ? label . getLocale ( ) : defaultLocale ; if ( ! defaultLocale . equals ( locale ) ) { return locale ; } locale = hint != null ? hint . getLocale ( ) : defaultLocale ; if ( ! defaultLocale . equals ( locale ) ) { return locale ; } locale = description != null ? description . getLocale ( ) : defaultLocale ; if ( ! defaultLocale . equals ( locale ) ) { return locale ; } return defaultLocale ; } } </s>
|
<s> package org . gatein . wsrp . registration ; import javax . xml . namespace . QName ; public interface PropertyDescription extends Comparable < PropertyDescription > { QName getName ( ) ; QName getType ( ) ; } </s>
|
<s> package org . gatein . wsrp ; import org . gatein . common . text . FastURLDecoder ; import org . gatein . common . text . TextTools ; import org . gatein . pc . api . ActionURL ; import org . gatein . pc . api . ContainerURL ; import org . gatein . pc . api . Mode ; import org . gatein . pc . api . OpaqueStateString ; import org . gatein . pc . api . ParametersStateString ; import org . gatein . pc . api . RenderURL ; import org . gatein . pc . api . ResourceURL ; import org . gatein . pc . api . StateString ; import org . gatein . pc . api . WindowState ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import java . util . Collections ; import java . util . HashMap ; import java . util . Map ; import java . util . Set ; public abstract class WSRPPortletURL implements ContainerURL { protected static final Logger log = LoggerFactory . getLogger ( WSRPPortletURL . class ) ; protected static final String EQUALS = "<STR_LIT:=>" ; protected static final String AMPERSAND = "<STR_LIT:&>" ; private static final String ENCODED_AMPERSAND = "<STR_LIT>" ; private static final String AMP_AMP = "<STR_LIT>" ; private static final String PARAM_SEPARATOR = "<STR_LIT:|>" ; private static final int URL_TYPE_END = WSRPRewritingConstants . URL_TYPE_NAME . length ( ) + EQUALS . length ( ) ; private boolean secure ; private Mode mode ; private WindowState windowState ; protected StateString navigationalState ; protected static boolean strict = true ; private Map < String , String > extraParams ; protected String extra ; private boolean extraParamsAfterEndToken = false ; public static void setStrict ( boolean strict ) { WSRPPortletURL . strict = strict ; log . debug ( "<STR_LIT>" + ( strict ? "<STR_LIT>" : "<STR_LIT>" ) + "<STR_LIT>" ) ; } public static WSRPPortletURL create ( ContainerURL containerURL , boolean secure , URLContext context ) { if ( containerURL == null ) { throw new IllegalArgumentException ( "<STR_LIT>" ) ; } Mode mode = containerURL . getMode ( ) ; WindowState windowState = containerURL . getWindowState ( ) ; StateString navigationalState = containerURL . getNavigationalState ( ) ; WSRPPortletURL url ; if ( containerURL instanceof ActionURL ) { StateString interactionState = ( ( ActionURL ) containerURL ) . getInteractionState ( ) ; url = new WSRPActionURL ( mode , windowState , secure , navigationalState , interactionState , context ) ; } else if ( containerURL instanceof RenderURL ) { url = new WSRPRenderURL ( mode , windowState , secure , navigationalState , ( ( RenderURL ) containerURL ) . getPublicNavigationalStateChanges ( ) , context ) ; } else if ( containerURL instanceof ResourceURL ) { ResourceURL resource = ( ResourceURL ) containerURL ; url = new WSRPResourceURL ( mode , windowState , secure , navigationalState , resource . getResourceState ( ) , resource . getResourceId ( ) , resource . getCacheability ( ) , context ) ; } else { throw new IllegalArgumentException ( "<STR_LIT>" + containerURL . getClass ( ) . getName ( ) ) ; } if ( strict && containerURL instanceof WSRPPortletURL ) { WSRPPortletURL other = ( WSRPPortletURL ) containerURL ; url . setParams ( other . extraParams , other . toString ( ) ) ; url . setExtra ( other . extra ) ; } return url ; } public static WSRPPortletURL create ( String encodedURL , Set < String > customModes , Set < String > customWindowStates ) { return create ( encodedURL , customModes , customWindowStates , false ) ; } public static WSRPPortletURL create ( String encodedURL , Set < String > customModes , Set < String > customWindowStates , boolean noBoundaries ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "<STR_LIT>" + encodedURL + "<STR_LIT:>>" ) ; } if ( encodedURL == null || encodedURL . length ( ) == <NUM_LIT:0> ) { throw new IllegalArgumentException ( "<STR_LIT>" ) ; } String originalURL = encodedURL ; boolean extraAfterEnd = false ; String extra = null ; if ( ! noBoundaries ) { if ( ! encodedURL . startsWith ( WSRPRewritingConstants . BEGIN_WSRP_REWRITE ) ) { throw new IllegalArgumentException ( encodedURL + "<STR_LIT>" + WSRPRewritingConstants . BEGIN_WSRP_REWRITE ) ; } if ( ! encodedURL . endsWith ( WSRPRewritingConstants . END_WSRP_REWRITE ) ) { encodedURL = encodedURL . substring ( WSRPRewritingConstants . WSRP_REWRITE_PREFIX_LENGTH ) ; int endTokenIndex = encodedURL . indexOf ( '<CHAR_LIT:/>' ) ; if ( endTokenIndex < <NUM_LIT:0> ) { throw new IllegalArgumentException ( originalURL + "<STR_LIT>" + WSRPRewritingConstants . END_WSRP_REWRITE ) ; } encodedURL = encodedURL . substring ( <NUM_LIT:0> , endTokenIndex ) + encodedURL . substring ( endTokenIndex + WSRPRewritingConstants . WSRP_REWRITE_SUFFIX_LENGTH ) ; int concatenationIndex = encodedURL . indexOf ( '<CHAR_LIT:/>' ) ; if ( strict && concatenationIndex != endTokenIndex ) { throw new IllegalArgumentException ( encodedURL + "<STR_LIT>" + WSRPRewritingConstants . END_WSRP_REWRITE + "<STR_LIT>" ) ; } else { if ( concatenationIndex != - <NUM_LIT:1> ) { String tmp = encodedURL ; encodedURL = encodedURL . substring ( <NUM_LIT:0> , concatenationIndex ) ; extra = tmp . substring ( concatenationIndex ) ; } extraAfterEnd = true ; } } else { encodedURL = encodedURL . substring ( WSRPRewritingConstants . WSRP_REWRITE_PREFIX_LENGTH , encodedURL . length ( ) - WSRPRewritingConstants . WSRP_REWRITE_SUFFIX_LENGTH ) ; } } if ( ! encodedURL . startsWith ( WSRPRewritingConstants . URL_TYPE_NAME + EQUALS ) ) { throw new IllegalArgumentException ( originalURL + "<STR_LIT>" ) ; } encodedURL = TextTools . replace ( encodedURL , AMP_AMP , PARAM_SEPARATOR ) ; encodedURL = TextTools . replace ( encodedURL , ENCODED_AMPERSAND , PARAM_SEPARATOR ) ; encodedURL = TextTools . replace ( encodedURL , AMPERSAND , PARAM_SEPARATOR ) ; encodedURL = encodedURL . substring ( URL_TYPE_END ) ; String urlType ; WSRPPortletURL url ; if ( encodedURL . startsWith ( WSRPRewritingConstants . URL_TYPE_RENDER ) ) { urlType = WSRPRewritingConstants . URL_TYPE_RENDER ; url = new WSRPRenderURL ( ) ; } else if ( encodedURL . startsWith ( WSRPRewritingConstants . URL_TYPE_BLOCKING_ACTION ) ) { urlType = WSRPRewritingConstants . URL_TYPE_BLOCKING_ACTION ; url = new WSRPActionURL ( ) ; } else if ( encodedURL . startsWith ( WSRPRewritingConstants . URL_TYPE_RESOURCE ) ) { urlType = WSRPRewritingConstants . URL_TYPE_RESOURCE ; url = new WSRPResourceURL ( ) ; } else { throw new IllegalArgumentException ( "<STR_LIT>" + encodedURL . substring ( <NUM_LIT:0> , encodedURL . indexOf ( PARAM_SEPARATOR ) ) + "<STR_LIT>" + originalURL ) ; } Map < String , String > params = null ; int urlTypeLength = urlType . length ( ) ; if ( encodedURL . length ( ) > urlTypeLength ) { encodedURL = encodedURL . substring ( urlTypeLength + PARAM_SEPARATOR . length ( ) ) ; params = extractParams ( encodedURL , originalURL , customModes , customWindowStates ) ; } url . setParams ( params , originalURL ) ; url . setExtraParamsAfterEndToken ( extraAfterEnd ) ; url . setExtra ( extra ) ; return url ; } public static WSRPPortletURL create ( String encodedURL ) { return create ( encodedURL , Collections . < String > emptySet ( ) , Collections . < String > emptySet ( ) ) ; } protected WSRPPortletURL ( Mode mode , WindowState windowState , boolean secure , StateString navigationalState , URLContext context ) { this . mode = mode ; this . windowState = windowState ; this . secure = secure ; this . navigationalState = navigationalState ; } protected WSRPPortletURL ( ) { } protected final void setParams ( Map < String , String > params , String originalURL ) { dealWithSpecificParams ( params , originalURL ) ; if ( ! strict ) { extraParams = new HashMap < String , String > ( ) ; extraParams . putAll ( params ) ; } } protected void dealWithSpecificParams ( Map < String , String > params , String originalURL ) { String paramValue = getRawParameterValueFor ( params , WSRPRewritingConstants . MODE ) ; if ( paramValue != null ) { mode = WSRPUtils . getJSR168PortletModeFromWSRPName ( paramValue ) ; params . remove ( WSRPRewritingConstants . MODE ) ; } paramValue = getRawParameterValueFor ( params , WSRPRewritingConstants . WINDOW_STATE ) ; if ( paramValue != null ) { windowState = WSRPUtils . getJSR168WindowStateFromWSRPName ( paramValue ) ; params . remove ( WSRPRewritingConstants . WINDOW_STATE ) ; } paramValue = getRawParameterValueFor ( params , WSRPRewritingConstants . SECURE_URL ) ; if ( paramValue != null ) { secure = Boolean . valueOf ( paramValue ) ; params . remove ( WSRPRewritingConstants . SECURE_URL ) ; } paramValue = getRawParameterValueFor ( params , WSRPRewritingConstants . NAVIGATIONAL_STATE ) ; if ( paramValue != null ) { navigationalState = new OpaqueStateString ( paramValue ) ; params . remove ( WSRPRewritingConstants . NAVIGATIONAL_STATE ) ; } } protected String getRawParameterValueFor ( Map params , String parameterName ) { if ( params != null ) { return ( String ) params . get ( parameterName ) ; } else { return null ; } } public Mode getMode ( ) { return mode ; } public WindowState getWindowState ( ) { return windowState ; } public boolean isSecure ( ) { return secure ; } protected abstract String getURLType ( ) ; public String toString ( ) { StringBuffer sb = new StringBuffer ( <NUM_LIT:255> ) ; sb . append ( WSRPRewritingConstants . BEGIN_WSRP_REWRITE ) . append ( WSRPRewritingConstants . URL_TYPE_NAME ) . append ( EQUALS ) . append ( getURLType ( ) ) ; if ( secure ) { createURLParameter ( sb , WSRPRewritingConstants . SECURE_URL , "<STR_LIT:true>" ) ; } if ( mode != null ) { createURLParameter ( sb , WSRPRewritingConstants . MODE , WSRPUtils . getWSRPNameFromJSR168PortletMode ( mode ) ) ; } if ( windowState != null ) { createURLParameter ( sb , WSRPRewritingConstants . WINDOW_STATE , WSRPUtils . getWSRPNameFromJSR168WindowState ( windowState ) ) ; } if ( navigationalState != null ) { createURLParameter ( sb , WSRPRewritingConstants . NAVIGATIONAL_STATE , navigationalState . getStringValue ( ) ) ; } appendEnd ( sb ) ; if ( strict ) { sb . append ( WSRPRewritingConstants . END_WSRP_REWRITE ) ; } else { if ( extraParams != null && ! extraParams . isEmpty ( ) ) { StringBuffer extras = new StringBuffer ( ) ; appendExtraParams ( extras ) ; if ( extraParamsAfterEndToken ) { sb . append ( WSRPRewritingConstants . END_WSRP_REWRITE ) ; sb . append ( extras ) ; if ( extra != null ) { sb . append ( extra ) ; } } else { sb . append ( extras ) ; sb . append ( WSRPRewritingConstants . END_WSRP_REWRITE ) ; } } else { sb . append ( WSRPRewritingConstants . END_WSRP_REWRITE ) ; } } return sb . toString ( ) ; } protected void appendExtraParams ( StringBuffer buffer ) { if ( extraParams != null ) { for ( Map . Entry < String , String > entry : extraParams . entrySet ( ) ) { createURLParameter ( buffer , entry . getKey ( ) , entry . getValue ( ) ) ; } } } protected abstract void appendEnd ( StringBuffer sb ) ; protected final void createURLParameter ( StringBuffer sb , String name , String value ) { if ( value != null ) { sb . append ( AMPERSAND ) . append ( name ) . append ( EQUALS ) . append ( value ) ; } } private static Map < String , String > extractParams ( String encodedURL , String originalURL , Set < String > customModes , Set < String > customWindowStates ) { Map < String , String > params = new HashMap < String , String > ( ) ; boolean finished = false ; while ( encodedURL . length ( ) > <NUM_LIT:0> && ! finished ) { int endParamIndex = encodedURL . indexOf ( PARAM_SEPARATOR ) ; String param ; if ( endParamIndex < <NUM_LIT:0> ) { param = encodedURL ; finished = true ; } else { param = encodedURL . substring ( <NUM_LIT:0> , endParamIndex ) ; } int equalsIndex = param . indexOf ( EQUALS ) ; if ( equalsIndex < <NUM_LIT:0> ) { throw new IllegalArgumentException ( param + "<STR_LIT>" + originalURL ) ; } String name = param . substring ( <NUM_LIT:0> , equalsIndex ) ; if ( ! name . startsWith ( "<STR_LIT>" ) ) { if ( strict ) { throw new IllegalArgumentException ( "<STR_LIT>" + name + "<STR_LIT>" + originalURL ) ; } else { log . debug ( "<STR_LIT>" + name + "<STR_LIT>" + originalURL ) ; } } String value = param . substring ( equalsIndex + EQUALS . length ( ) , param . length ( ) ) ; if ( WSRPRewritingConstants . MODE . equals ( name ) ) { value = checkModeOrWindowState ( value , true , customModes ) ; } if ( WSRPRewritingConstants . WINDOW_STATE . equals ( name ) ) { value = checkModeOrWindowState ( value , false , customWindowStates ) ; } params . put ( name , value ) ; if ( log . isTraceEnabled ( ) ) { if ( WSRPRewritingConstants . INTERACTION_STATE . equals ( name ) || WSRPRewritingConstants . NAVIGATIONAL_STATE . equals ( name ) ) { StateString clear = ParametersStateString . create ( value ) ; log . trace ( name + "<STR_LIT>" + clear ) ; } } encodedURL = encodedURL . substring ( endParamIndex + PARAM_SEPARATOR . length ( ) ) ; } return params ; } private static String checkModeOrWindowState ( String value , boolean mode , Set < String > supportedValues ) { value = FastURLDecoder . getUTF8Instance ( ) . encode ( value ) ; boolean standard ; if ( mode ) { standard = WSRPUtils . isDefaultWSRPMode ( value ) ; } else { standard = WSRPUtils . isDefaultWSRPWindowState ( value ) ; } if ( ! standard ) { if ( supportedValues . contains ( value ) ) { return value ; } else { throw new IllegalArgumentException ( "<STR_LIT>" + ( mode ? "<STR_LIT>" : "<STR_LIT>" ) + value ) ; } } return value ; } private void setExtraParamsAfterEndToken ( boolean extraParamsAfterEndToken ) { this . extraParamsAfterEndToken = extraParamsAfterEndToken ; } public void setExtra ( String extra ) { this . extra = extra ; } public StateString getNavigationalState ( ) { return navigationalState ; } public Map < String , String > getProperties ( ) { return Collections . emptyMap ( ) ; } public static class URLContext { public static final String SERVER_ADDRESS = "<STR_LIT>" ; public static final String PORTLET_CONTEXT = "<STR_LIT>" ; public static final String REGISTRATION_HANDLE = "<STR_LIT>" ; public static final String INSTANCE_KEY = "<STR_LIT>" ; public static final String NAMESPACE = "<STR_LIT>" ; public static final URLContext EMPTY = new URLContext ( ) { @ Override public Object getValueFor ( String name ) { return null ; } @ Override public void setValueFor ( String name , Object value ) { } } ; private Map < String , Object > context ; public URLContext ( ) { context = new HashMap < String , Object > ( <NUM_LIT:7> ) ; } public URLContext ( String name1 , Object value1 , String name2 , Object value2 ) { this ( ) ; context . put ( name1 , value1 ) ; context . put ( name2 , value2 ) ; } public Object getValueFor ( String name ) { return context . get ( name ) ; } public void setValueFor ( String name , Object value ) { context . put ( name , value ) ; } } } </s>
|
<s> package org . gatein . wsrp ; import org . gatein . pc . api . ActionURL ; import org . gatein . pc . api . Mode ; import org . gatein . pc . api . OpaqueStateString ; import org . gatein . pc . api . StateString ; import org . gatein . pc . api . WindowState ; import java . util . Map ; public class WSRPActionURL extends WSRPPortletURL implements ActionURL { private StateString interactionState ; protected WSRPActionURL ( Mode mode , WindowState windowState , boolean secure , StateString navigationalState , StateString interactionState , URLContext context ) { super ( mode , windowState , secure , navigationalState , context ) ; this . interactionState = interactionState ; } protected WSRPActionURL ( ) { } @ Override protected void dealWithSpecificParams ( Map < String , String > params , String originalURL ) { super . dealWithSpecificParams ( params , originalURL ) ; String paramValue = getRawParameterValueFor ( params , WSRPRewritingConstants . INTERACTION_STATE ) ; if ( paramValue != null ) { interactionState = new OpaqueStateString ( paramValue ) ; params . remove ( WSRPRewritingConstants . INTERACTION_STATE ) ; } } protected String getURLType ( ) { return WSRPRewritingConstants . URL_TYPE_BLOCKING_ACTION ; } public StateString getInteractionState ( ) { return interactionState ; } protected void appendEnd ( StringBuffer sb ) { if ( interactionState != null ) { createURLParameter ( sb , WSRPRewritingConstants . INTERACTION_STATE , interactionState . getStringValue ( ) ) ; } } } </s>
|
<s> package org . gatein . wsrp ; import java . io . BufferedInputStream ; import java . io . ByteArrayOutputStream ; import java . io . File ; import java . io . IOException ; import java . io . InputStream ; import java . net . HttpURLConnection ; import java . net . JarURLConnection ; import java . net . MalformedURLException ; import java . net . URL ; import java . net . URLConnection ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Enumeration ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Properties ; import java . util . Vector ; import java . util . jar . JarEntry ; import java . util . jar . JarFile ; public class ResourceFinder { private final URL [ ] urls ; private final String path ; private final ClassLoader classLoader ; private final List < String > resourcesNotLoaded = new ArrayList < String > ( ) ; public ResourceFinder ( URL ... urls ) { this ( null , Thread . currentThread ( ) . getContextClassLoader ( ) , urls ) ; } public ResourceFinder ( String path ) { this ( path , Thread . currentThread ( ) . getContextClassLoader ( ) , null ) ; } public ResourceFinder ( String path , URL ... urls ) { this ( path , Thread . currentThread ( ) . getContextClassLoader ( ) , urls ) ; } public ResourceFinder ( String path , ClassLoader classLoader ) { this ( path , classLoader , null ) ; } public ResourceFinder ( String path , ClassLoader classLoader , URL ... urls ) { if ( path == null ) { path = "<STR_LIT>" ; } else if ( path . length ( ) > <NUM_LIT:0> && ! path . endsWith ( "<STR_LIT:/>" ) ) { path += "<STR_LIT:/>" ; } this . path = path ; if ( classLoader == null ) { classLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; } this . classLoader = classLoader ; for ( int i = <NUM_LIT:0> ; urls != null && i < urls . length ; i ++ ) { URL url = urls [ i ] ; if ( url == null || isDirectory ( url ) || url . getProtocol ( ) . equals ( "<STR_LIT>" ) ) { continue ; } try { urls [ i ] = new URL ( "<STR_LIT>" , "<STR_LIT>" , - <NUM_LIT:1> , url . toString ( ) + "<STR_LIT>" ) ; } catch ( MalformedURLException e ) { } } this . urls = ( urls == null || urls . length == <NUM_LIT:0> ) ? null : urls ; } private static boolean isDirectory ( URL url ) { String file = url . getFile ( ) ; return ( file . length ( ) > <NUM_LIT:0> && file . charAt ( file . length ( ) - <NUM_LIT:1> ) == '<CHAR_LIT:/>' ) ; } public List < String > getResourcesNotLoaded ( ) { return Collections . unmodifiableList ( resourcesNotLoaded ) ; } public URL find ( String uri ) throws IOException { String fullUri = path + uri ; URL resource = getResource ( fullUri ) ; if ( resource == null ) { throw new IOException ( "<STR_LIT>" + path + uri + "<STR_LIT:'>" ) ; } return resource ; } public List < URL > findAll ( String uri ) throws IOException { String fullUri = path + uri ; Enumeration < URL > resources = getResources ( fullUri ) ; List < URL > list = new ArrayList ( ) ; while ( resources . hasMoreElements ( ) ) { URL url = resources . nextElement ( ) ; list . add ( url ) ; } return list ; } public String findString ( String uri ) throws IOException { String fullUri = path + uri ; URL resource = getResource ( fullUri ) ; if ( resource == null ) { throw new IOException ( "<STR_LIT>" + fullUri ) ; } return readContents ( resource ) ; } public List < String > findAllStrings ( String uri ) throws IOException { String fulluri = path + uri ; List < String > strings = new ArrayList < String > ( ) ; Enumeration < URL > resources = getResources ( fulluri ) ; while ( resources . hasMoreElements ( ) ) { URL url = resources . nextElement ( ) ; String string = readContents ( url ) ; Collections . addAll ( strings , string . split ( "<STR_LIT>" ) ) ; } return strings ; } public List < String > findAvailableStrings ( String uri ) throws IOException { resourcesNotLoaded . clear ( ) ; String fulluri = path + uri ; List < String > strings = new ArrayList < String > ( ) ; Enumeration < URL > resources = getResources ( fulluri ) ; while ( resources . hasMoreElements ( ) ) { URL url = resources . nextElement ( ) ; try { String string = readContents ( url ) ; Collections . addAll ( strings , string . split ( "<STR_LIT>" ) ) ; } catch ( IOException notAvailable ) { resourcesNotLoaded . add ( url . toExternalForm ( ) ) ; } } return strings ; } public Map < String , String > mapAllStrings ( String uri ) throws IOException { Map < String , String > strings = new HashMap < String , String > ( ) ; Map < String , URL > resourcesMap = getResourcesMap ( uri ) ; for ( Iterator iterator = resourcesMap . entrySet ( ) . iterator ( ) ; iterator . hasNext ( ) ; ) { Map . Entry entry = ( Map . Entry ) iterator . next ( ) ; String name = ( String ) entry . getKey ( ) ; URL url = ( URL ) entry . getValue ( ) ; String value = readContents ( url ) ; strings . put ( name , value ) ; } return strings ; } public Map < String , String > mapAvailableStrings ( String uri ) throws IOException { resourcesNotLoaded . clear ( ) ; Map < String , String > strings = new HashMap < String , String > ( ) ; Map < String , URL > resourcesMap = getResourcesMap ( uri ) ; for ( Iterator iterator = resourcesMap . entrySet ( ) . iterator ( ) ; iterator . hasNext ( ) ; ) { Map . Entry entry = ( Map . Entry ) iterator . next ( ) ; String name = ( String ) entry . getKey ( ) ; URL url = ( URL ) entry . getValue ( ) ; try { String value = readContents ( url ) ; final String [ ] split = value . split ( "<STR_LIT>" ) ; for ( String s : split ) { strings . put ( name , s ) ; } } catch ( IOException notAvailable ) { resourcesNotLoaded . add ( url . toExternalForm ( ) ) ; } } return strings ; } public Class < ? > findClass ( String uri ) throws IOException , ClassNotFoundException { String className = findString ( uri ) ; return classLoader . loadClass ( className ) ; } public < T > Class < ? extends T > findClass ( String className , Class < T > pluginClass ) throws IOException , ClassNotFoundException { List < String > strings = findAllStrings ( pluginClass . getCanonicalName ( ) ) ; for ( String name : strings ) { if ( className . equals ( name ) ) { return classLoader . loadClass ( className ) . asSubclass ( pluginClass ) ; } } throw new ClassNotFoundException ( "<STR_LIT>" + pluginClass . getCanonicalName ( ) + "<STR_LIT>" + className ) ; } public List < Class < ? > > findAllClasses ( String uri ) throws IOException , ClassNotFoundException { List < Class < ? > > classes = new ArrayList < Class < ? > > ( ) ; List < String > strings = findAllStrings ( uri ) ; for ( String className : strings ) { Class < ? > clazz = classLoader . loadClass ( className ) ; classes . add ( clazz ) ; } return classes ; } public List < Class < ? > > findAvailableClasses ( String uri ) throws IOException { resourcesNotLoaded . clear ( ) ; List < Class < ? > > classes = new ArrayList < Class < ? > > ( ) ; List < String > strings = findAvailableStrings ( uri ) ; for ( String className : strings ) { try { Class < ? > clazz = classLoader . loadClass ( className ) ; classes . add ( clazz ) ; } catch ( Exception notAvailable ) { resourcesNotLoaded . add ( className ) ; } } return classes ; } public Map < String , Class < ? > > mapAllClasses ( String uri ) throws IOException , ClassNotFoundException { Map < String , Class < ? > > classes = new HashMap < String , Class < ? > > ( ) ; Map < String , String > map = mapAllStrings ( uri ) ; for ( Map . Entry < String , String > entry : map . entrySet ( ) ) { String string = entry . getKey ( ) ; String className = entry . getValue ( ) ; Class < ? > clazz = classLoader . loadClass ( className ) ; classes . put ( string , clazz ) ; } return classes ; } public Map < String , Class < ? > > mapAvailableClasses ( String uri ) throws IOException { resourcesNotLoaded . clear ( ) ; Map < String , Class < ? > > classes = new HashMap < String , Class < ? > > ( ) ; Map < String , String > map = mapAvailableStrings ( uri ) ; for ( Map . Entry < String , String > entry : map . entrySet ( ) ) { String string = entry . getKey ( ) ; String className = entry . getValue ( ) ; try { Class < ? > clazz = classLoader . loadClass ( className ) ; classes . put ( string , clazz ) ; } catch ( Exception notAvailable ) { resourcesNotLoaded . add ( className ) ; } } return classes ; } public Class < ? > findImplementation ( Class < ? > interfase ) throws IOException , ClassNotFoundException { String className = findString ( interfase . getName ( ) ) ; Class < ? > impl = classLoader . loadClass ( className ) ; if ( ! interfase . isAssignableFrom ( impl ) ) { throw new ClassCastException ( "<STR_LIT>" + interfase . getName ( ) ) ; } return impl ; } public < T > List < Class < ? extends T > > findAllImplementations ( Class < T > interfase ) throws IOException , ClassNotFoundException { List < Class < ? extends T > > implementations = new ArrayList < Class < ? extends T > > ( ) ; List < String > strings = findAllStrings ( interfase . getName ( ) ) ; for ( String className : strings ) { Class < ? extends T > impl = classLoader . loadClass ( className ) . asSubclass ( interfase ) ; implementations . add ( impl ) ; } return implementations ; } public < T > List < Class < ? extends T > > findAvailableImplementations ( Class < T > interfase ) throws IOException { resourcesNotLoaded . clear ( ) ; List < Class < ? extends T > > implementations = new ArrayList < Class < ? extends T > > ( ) ; List < String > strings = findAvailableStrings ( interfase . getName ( ) ) ; for ( String className : strings ) { try { Class < ? > impl = classLoader . loadClass ( className ) ; if ( interfase . isAssignableFrom ( impl ) ) { implementations . add ( impl . asSubclass ( interfase ) ) ; } else { resourcesNotLoaded . add ( className ) ; } } catch ( Exception notAvailable ) { resourcesNotLoaded . add ( className ) ; } } return implementations ; } public < T > Map < String , Class < ? extends T > > mapAllImplementations ( Class < T > interfase ) throws IOException , ClassNotFoundException { Map < String , Class < ? extends T > > implementations = new HashMap < String , Class < ? extends T > > ( ) ; Map < String , String > map = mapAllStrings ( interfase . getName ( ) ) ; for ( Map . Entry < String , String > entry : map . entrySet ( ) ) { String string = entry . getKey ( ) ; String className = entry . getValue ( ) ; Class < ? extends T > impl = classLoader . loadClass ( className ) . asSubclass ( interfase ) ; implementations . put ( string , impl ) ; } return implementations ; } public < T > Map < String , Class < ? extends T > > mapAvailableImplementations ( Class < T > interfase ) throws IOException { resourcesNotLoaded . clear ( ) ; Map < String , Class < ? extends T > > implementations = new HashMap < String , Class < ? extends T > > ( ) ; Map < String , String > map = mapAvailableStrings ( interfase . getName ( ) ) ; for ( Map . Entry < String , String > entry : map . entrySet ( ) ) { String string = entry . getKey ( ) ; String className = entry . getValue ( ) ; try { Class < ? > impl = classLoader . loadClass ( className ) ; if ( interfase . isAssignableFrom ( impl ) ) { implementations . put ( string , impl . asSubclass ( interfase ) ) ; } else { resourcesNotLoaded . add ( className ) ; } } catch ( Exception notAvailable ) { resourcesNotLoaded . add ( className ) ; } } return implementations ; } public Properties findProperties ( String uri ) throws IOException { String fulluri = path + uri ; URL resource = getResource ( fulluri ) ; if ( resource == null ) { throw new IOException ( "<STR_LIT>" + fulluri ) ; } return loadProperties ( resource ) ; } public List < Properties > findAllProperties ( String uri ) throws IOException { String fulluri = path + uri ; List < Properties > properties = new ArrayList < Properties > ( ) ; Enumeration < URL > resources = getResources ( fulluri ) ; while ( resources . hasMoreElements ( ) ) { URL url = resources . nextElement ( ) ; Properties props = loadProperties ( url ) ; properties . add ( props ) ; } return properties ; } public List < Properties > findAvailableProperties ( String uri ) throws IOException { resourcesNotLoaded . clear ( ) ; String fulluri = path + uri ; List < Properties > properties = new ArrayList < Properties > ( ) ; Enumeration < URL > resources = getResources ( fulluri ) ; while ( resources . hasMoreElements ( ) ) { URL url = resources . nextElement ( ) ; try { Properties props = loadProperties ( url ) ; properties . add ( props ) ; } catch ( Exception notAvailable ) { resourcesNotLoaded . add ( url . toExternalForm ( ) ) ; } } return properties ; } public Map < String , Properties > mapAllProperties ( String uri ) throws IOException { Map < String , Properties > propertiesMap = new HashMap < String , Properties > ( ) ; Map < String , URL > map = getResourcesMap ( uri ) ; for ( Iterator iterator = map . entrySet ( ) . iterator ( ) ; iterator . hasNext ( ) ; ) { Map . Entry entry = ( Map . Entry ) iterator . next ( ) ; String string = ( String ) entry . getKey ( ) ; URL url = ( URL ) entry . getValue ( ) ; Properties properties = loadProperties ( url ) ; propertiesMap . put ( string , properties ) ; } return propertiesMap ; } public Map < String , Properties > mapAvailableProperties ( String uri ) throws IOException { resourcesNotLoaded . clear ( ) ; Map < String , Properties > propertiesMap = new HashMap < String , Properties > ( ) ; Map < String , URL > map = getResourcesMap ( uri ) ; for ( Iterator iterator = map . entrySet ( ) . iterator ( ) ; iterator . hasNext ( ) ; ) { Map . Entry entry = ( Map . Entry ) iterator . next ( ) ; String string = ( String ) entry . getKey ( ) ; URL url = ( URL ) entry . getValue ( ) ; try { Properties properties = loadProperties ( url ) ; propertiesMap . put ( string , properties ) ; } catch ( Exception notAvailable ) { resourcesNotLoaded . add ( url . toExternalForm ( ) ) ; } } return propertiesMap ; } public Map < String , URL > getResourcesMap ( String uri ) throws IOException { String basePath = path + uri ; Map < String , URL > resources = new HashMap < String , URL > ( ) ; if ( ! basePath . endsWith ( "<STR_LIT:/>" ) ) { basePath += "<STR_LIT:/>" ; } Enumeration < URL > urls = getResources ( basePath ) ; while ( urls . hasMoreElements ( ) ) { URL location = urls . nextElement ( ) ; try { if ( location . getProtocol ( ) . equals ( "<STR_LIT>" ) ) { readJarEntries ( location , basePath , resources ) ; } else if ( location . getProtocol ( ) . equals ( "<STR_LIT:file>" ) ) { readDirectoryEntries ( location , resources ) ; } } catch ( Exception e ) { } } return resources ; } private static void readDirectoryEntries ( URL location , Map < String , URL > resources ) throws MalformedURLException { File dir = new File ( decode ( location . getPath ( ) ) ) ; if ( dir . isDirectory ( ) ) { File [ ] files = dir . listFiles ( ) ; for ( File file : files ) { if ( ! file . isDirectory ( ) ) { String name = file . getName ( ) ; URL url = file . toURI ( ) . toURL ( ) ; resources . put ( name , url ) ; } } } } private static void readJarEntries ( URL location , String basePath , Map < String , URL > resources ) throws IOException { JarURLConnection conn = ( JarURLConnection ) location . openConnection ( ) ; JarFile jarfile = null ; jarfile = conn . getJarFile ( ) ; Enumeration < JarEntry > entries = jarfile . entries ( ) ; while ( entries != null && entries . hasMoreElements ( ) ) { JarEntry entry = entries . nextElement ( ) ; String name = entry . getName ( ) ; if ( entry . isDirectory ( ) || ! name . startsWith ( basePath ) || name . length ( ) == basePath . length ( ) ) { continue ; } name = name . substring ( basePath . length ( ) ) ; if ( name . contains ( "<STR_LIT:/>" ) ) { continue ; } URL resource = new URL ( location , name ) ; resources . put ( name , resource ) ; } } private Properties loadProperties ( URL resource ) throws IOException { InputStream in = resource . openStream ( ) ; BufferedInputStream reader = null ; try { reader = new BufferedInputStream ( in ) ; Properties properties = new Properties ( ) ; properties . load ( reader ) ; return properties ; } finally { try { in . close ( ) ; reader . close ( ) ; } catch ( Exception e ) { } } } private String readContents ( URL resource ) throws IOException { InputStream in = resource . openStream ( ) ; BufferedInputStream reader = null ; StringBuffer sb = new StringBuffer ( ) ; try { reader = new BufferedInputStream ( in ) ; int b = reader . read ( ) ; while ( b != - <NUM_LIT:1> ) { sb . append ( ( char ) b ) ; b = reader . read ( ) ; } return sb . toString ( ) . trim ( ) ; } finally { try { in . close ( ) ; reader . close ( ) ; } catch ( Exception e ) { } } } public URL getResource ( String fullUri ) { if ( urls == null ) { return classLoader . getResource ( fullUri ) ; } return findResource ( fullUri , urls ) ; } private Enumeration < URL > getResources ( String fulluri ) throws IOException { if ( urls == null ) { return classLoader . getResources ( fulluri ) ; } Vector < URL > resources = new Vector ( ) ; for ( URL url : urls ) { URL resource = findResource ( fulluri , url ) ; if ( resource != null ) { resources . add ( resource ) ; } } return resources . elements ( ) ; } private URL findResource ( String resourceName , URL ... search ) { for ( int i = <NUM_LIT:0> ; i < search . length ; i ++ ) { URL currentUrl = search [ i ] ; if ( currentUrl == null ) { continue ; } try { String protocol = currentUrl . getProtocol ( ) ; if ( protocol . equals ( "<STR_LIT>" ) ) { URL jarURL = ( ( JarURLConnection ) currentUrl . openConnection ( ) ) . getJarFileURL ( ) ; JarFile jarFile ; JarURLConnection juc ; try { juc = ( JarURLConnection ) new URL ( "<STR_LIT>" , "<STR_LIT>" , jarURL . toExternalForm ( ) + "<STR_LIT>" ) . openConnection ( ) ; jarFile = juc . getJarFile ( ) ; } catch ( IOException e ) { search [ i ] = null ; throw e ; } try { juc = ( JarURLConnection ) new URL ( "<STR_LIT>" , "<STR_LIT>" , jarURL . toExternalForm ( ) + "<STR_LIT>" ) . openConnection ( ) ; jarFile = juc . getJarFile ( ) ; String entryName ; if ( currentUrl . getFile ( ) . endsWith ( "<STR_LIT>" ) ) { entryName = resourceName ; } else { String file = currentUrl . getFile ( ) ; int sepIdx = file . lastIndexOf ( "<STR_LIT>" ) ; if ( sepIdx == - <NUM_LIT:1> ) { search [ i ] = null ; continue ; } sepIdx += <NUM_LIT:2> ; StringBuffer sb = new StringBuffer ( file . length ( ) - sepIdx + resourceName . length ( ) ) ; sb . append ( file . substring ( sepIdx ) ) ; sb . append ( resourceName ) ; entryName = sb . toString ( ) ; } if ( entryName . equals ( "<STR_LIT>" ) && jarFile . getEntry ( "<STR_LIT>" ) != null ) { return targetURL ( currentUrl , "<STR_LIT>" ) ; } if ( jarFile . getEntry ( entryName ) != null ) { return targetURL ( currentUrl , resourceName ) ; } } finally { if ( ! juc . getUseCaches ( ) ) { try { jarFile . close ( ) ; } catch ( Exception e ) { } } } } else if ( protocol . equals ( "<STR_LIT:file>" ) ) { String baseFile = currentUrl . getFile ( ) ; String host = currentUrl . getHost ( ) ; int hostLength = <NUM_LIT:0> ; if ( host != null ) { hostLength = host . length ( ) ; } StringBuffer buf = new StringBuffer ( <NUM_LIT:2> + hostLength + baseFile . length ( ) + resourceName . length ( ) ) ; if ( hostLength > <NUM_LIT:0> ) { buf . append ( "<STR_LIT>" ) . append ( host ) ; } buf . append ( baseFile ) ; String fixedResName = resourceName ; while ( fixedResName . startsWith ( "<STR_LIT:/>" ) || fixedResName . startsWith ( "<STR_LIT:\\>" ) ) { fixedResName = fixedResName . substring ( <NUM_LIT:1> ) ; } buf . append ( fixedResName ) ; String filename = buf . toString ( ) ; File file = new File ( filename ) ; File file2 = new File ( decode ( filename ) ) ; if ( file . exists ( ) || file2 . exists ( ) ) { return targetURL ( currentUrl , fixedResName ) ; } } else { URL resourceURL = targetURL ( currentUrl , resourceName ) ; URLConnection urlConnection = resourceURL . openConnection ( ) ; try { urlConnection . getInputStream ( ) . close ( ) ; } catch ( SecurityException e ) { return null ; } if ( ! resourceURL . getProtocol ( ) . equals ( "<STR_LIT:http>" ) ) { return resourceURL ; } int code = ( ( HttpURLConnection ) urlConnection ) . getResponseCode ( ) ; if ( code >= <NUM_LIT> && code < <NUM_LIT> ) { return resourceURL ; } } } catch ( MalformedURLException e ) { } catch ( IOException e ) { } catch ( SecurityException e ) { } } return null ; } private URL targetURL ( URL base , String name ) throws MalformedURLException { StringBuffer sb = new StringBuffer ( base . getFile ( ) . length ( ) + name . length ( ) ) ; sb . append ( base . getFile ( ) ) ; sb . append ( name ) ; String file = sb . toString ( ) ; return new URL ( base . getProtocol ( ) , base . getHost ( ) , base . getPort ( ) , file , null ) ; } public static String decode ( String fileName ) { if ( fileName . indexOf ( '<CHAR_LIT>' ) == - <NUM_LIT:1> ) { return fileName ; } StringBuilder result = new StringBuilder ( fileName . length ( ) ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; for ( int i = <NUM_LIT:0> ; i < fileName . length ( ) ; ) { char c = fileName . charAt ( i ) ; if ( c == '<CHAR_LIT>' ) { out . reset ( ) ; do { if ( i + <NUM_LIT:2> >= fileName . length ( ) ) { throw new IllegalArgumentException ( "<STR_LIT>" + i ) ; } int d1 = Character . digit ( fileName . charAt ( i + <NUM_LIT:1> ) , <NUM_LIT:16> ) ; int d2 = Character . digit ( fileName . charAt ( i + <NUM_LIT:2> ) , <NUM_LIT:16> ) ; if ( d1 == - <NUM_LIT:1> || d2 == - <NUM_LIT:1> ) { throw new IllegalArgumentException ( "<STR_LIT>" + fileName . substring ( i , i + <NUM_LIT:3> ) + "<STR_LIT>" + String . valueOf ( i ) ) ; } out . write ( ( byte ) ( ( d1 << <NUM_LIT:4> ) + d2 ) ) ; i += <NUM_LIT:3> ; } while ( i < fileName . length ( ) && fileName . charAt ( i ) == '<CHAR_LIT>' ) ; result . append ( out . toString ( ) ) ; continue ; } else { result . append ( c ) ; } i ++ ; } return result . toString ( ) ; } } </s>
|
<s> package org . gatein . wsrp ; import org . gatein . common . util . ParameterValidation ; import org . gatein . wsrp . spec . v1 . WSRP1ExceptionFactory ; import org . gatein . wsrp . spec . v2 . WSRP2ExceptionFactory ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import java . lang . reflect . Constructor ; import java . util . HashMap ; import java . util . Map ; public abstract class WSRPExceptionFactory { protected static final Logger log = LoggerFactory . getLogger ( WSRPExceptionFactory . class ) ; protected static final Map < Class < ? extends Exception > , ExceptionFactory < ? extends Exception > > exceptionClassToFactory = new HashMap < Class < ? extends Exception > , ExceptionFactory < ? extends Exception > > ( <NUM_LIT> ) ; static { WSRP1ExceptionFactory . getInstance ( ) . loadExceptionFactories ( ) ; WSRP2ExceptionFactory . getInstance ( ) . loadExceptionFactories ( ) ; } protected abstract void loadExceptionFactories ( ) ; protected WSRPExceptionFactory ( ) { } public static < E extends Exception > E throwWSException ( Class < E > exceptionClass , String message , Throwable cause ) throws E { throw createWSException ( exceptionClass , message , cause ) ; } public static < E extends Exception > E createWSException ( Class < E > exceptionClass , String message , Throwable cause ) { ExceptionFactory < E > exceptionFactory = ( ExceptionFactory < E > ) exceptionClassToFactory . get ( exceptionClass ) ; if ( exceptionFactory == null ) { throw new IllegalArgumentException ( "<STR_LIT>" + exceptionClass ) ; } return exceptionFactory . newInstance ( message , cause ) ; } protected abstract static class ExceptionFactory < E extends Exception > { private static final String CAUSE = "<STR_LIT>" ; private final Constructor < E > exceptionConstructor ; protected Object fault ; private static final String FAULT = "<STR_LIT>" ; public ExceptionFactory ( Class < E > exceptionClass ) throws NoSuchMethodException , IllegalAccessException , InstantiationException , ClassNotFoundException { String faultClassName = exceptionClass . getName ( ) + FAULT ; Class < ? > clazz = Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( faultClassName ) ; exceptionConstructor = exceptionClass . getConstructor ( String . class , initFaultAndGetClass ( clazz ) , Throwable . class ) ; } protected abstract Class initFaultAndGetClass ( Class clazz ) throws IllegalAccessException , InstantiationException ; public E newInstance ( String message , Throwable cause ) { try { if ( cause != null ) { String causeMsg = cause . getLocalizedMessage ( ) ; if ( ! ParameterValidation . isNullOrEmpty ( causeMsg ) && ! message . contains ( CAUSE ) ) { message += CAUSE + causeMsg ; } } return exceptionConstructor . newInstance ( message , fault , cause ) ; } catch ( Exception e ) { log . debug ( "<STR_LIT>" + fault . getClass ( ) . getSimpleName ( ) + "<STR_LIT>" + message + "<STR_LIT>" + cause ) ; return null ; } } } } </s>
|
<s> package org . gatein . wsrp . handler ; import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import org . w3c . dom . NodeList ; import javax . xml . namespace . QName ; import javax . xml . soap . SOAPBody ; import javax . xml . soap . SOAPMessage ; import javax . xml . ws . handler . MessageContext ; import javax . xml . ws . handler . soap . SOAPHandler ; import javax . xml . ws . handler . soap . SOAPMessageContext ; import java . util . Set ; public class WSRPExtensionHandler implements SOAPHandler < SOAPMessageContext > { private static Logger log = LoggerFactory . getLogger ( WSRPExtensionHandler . class ) ; private boolean debug = false ; private boolean removeExtensions = false ; private static final String EXTENSIONS = "<STR_LIT>" ; public boolean handleMessage ( SOAPMessageContext messageContext ) { removeExtensions ( messageContext ) ; return true ; } public boolean handleFault ( SOAPMessageContext messageContext ) { return true ; } public void close ( MessageContext messageContext ) { } public Set < QName > getHeaders ( ) { return null ; } private void removeExtensions ( SOAPMessageContext msgContext ) { SOAPMessage soapMessage = msgContext . getMessage ( ) ; try { if ( debug ) { soapMessage . writeTo ( System . out ) ; } if ( removeExtensions ) { SOAPBody soapBody = soapMessage . getSOAPBody ( ) ; traverseAndRemoveExtensions ( soapBody ) ; } } catch ( Exception e ) { log . error ( "<STR_LIT>" , e ) ; } } private void traverseAndRemoveExtensions ( org . w3c . dom . Node node ) { NodeList children = node . getChildNodes ( ) ; int childrenNb = children . getLength ( ) ; for ( int i = <NUM_LIT:0> ; i < childrenNb ; i ++ ) { org . w3c . dom . Node child = children . item ( i ) ; if ( org . w3c . dom . Node . ELEMENT_NODE == child . getNodeType ( ) ) { String name = child . getLocalName ( ) ; if ( EXTENSIONS . equals ( name ) ) { if ( debug ) { log . debug ( "<STR_LIT>" + name ) ; } node . removeChild ( child ) ; break ; } else { traverseAndRemoveExtensions ( child ) ; } } } } } </s>
|
<s> package org . gatein . wsrp ; import org . gatein . pc . api . Mode ; import org . gatein . pc . api . RenderURL ; import org . gatein . pc . api . StateString ; import org . gatein . pc . api . WindowState ; import org . gatein . wsrp . spec . v2 . WSRP2RewritingConstants ; import java . util . Map ; public class WSRPRenderURL extends WSRPPortletURL implements RenderURL { private Map < String , String [ ] > publicNSChanges ; protected WSRPRenderURL ( Mode mode , WindowState windowState , boolean secure , StateString navigationalState , Map < String , String [ ] > publicNavigationalStateChanges , URLContext context ) { super ( mode , windowState , secure , navigationalState , context ) ; this . publicNSChanges = publicNavigationalStateChanges ; } protected WSRPRenderURL ( ) { } @ Override protected void dealWithSpecificParams ( Map < String , String > params , String originalURL ) { super . dealWithSpecificParams ( params , originalURL ) ; String paramValue = getRawParameterValueFor ( params , WSRP2RewritingConstants . NAVIGATIONAL_VALUES ) ; if ( paramValue != null ) { publicNSChanges = WSRPUtils . decodePublicNS ( paramValue ) ; params . remove ( WSRP2RewritingConstants . NAVIGATIONAL_VALUES ) ; } } protected String getURLType ( ) { return WSRPRewritingConstants . URL_TYPE_RENDER ; } public Map < String , String [ ] > getPublicNavigationalStateChanges ( ) { return publicNSChanges ; } protected void appendEnd ( StringBuffer sb ) { if ( publicNSChanges != null ) { createURLParameter ( sb , WSRP2RewritingConstants . NAVIGATIONAL_VALUES , WSRPUtils . encodePublicNS ( publicNSChanges ) ) ; } } } </s>
|
<s> package org . gatein . wsrp . payload ; import org . w3c . dom . Element ; import java . io . Serializable ; public class SerializablePayload implements Serializable { protected final Element element ; public SerializablePayload ( Element element ) { this . element = element ; } public Element getElement ( ) { return element ; } } </s>
|
<s> package org . gatein . wsrp . payload ; import org . gatein . wsrp . WSRPConstants ; import javax . xml . namespace . QName ; import java . io . Serializable ; import java . math . BigDecimal ; import java . math . BigInteger ; import java . util . Calendar ; import static javax . xml . bind . DatatypeConverter . * ; public enum XSDTypeConverter { ANY_SIMPLE_TYPE ( "<STR_LIT>" ) { @ Override public Serializable parseFromXML ( String value ) { return parseAnySimpleType ( value ) ; } @ Override public String printToXML ( Serializable value ) { return printAnySimpleType ( ( String ) value ) ; } @ Override public Class getJavaType ( ) { return Object . class ; } @ Override public QName getXSDType ( ) { return WSRPConstants . XSD_ANY_SIMPLE_TYPE ; } } , BASE64_BINARY ( "<STR_LIT>" ) { @ Override public Serializable parseFromXML ( String value ) { return parseBase64Binary ( value ) ; } @ Override public String printToXML ( Serializable value ) { return printBase64Binary ( ( byte [ ] ) value ) ; } @ Override public Class getJavaType ( ) { return byte [ ] . class ; } @ Override public QName getXSDType ( ) { return WSRPConstants . XSD_BASE_64_BINARY ; } } , BOOLEAN ( "<STR_LIT:boolean>" ) { @ Override public Serializable parseFromXML ( String value ) { return parseBoolean ( value ) ; } @ Override public String printToXML ( Serializable value ) { return printBoolean ( ( Boolean ) value ) ; } @ Override public Class getJavaType ( ) { return boolean . class ; } @ Override public QName getXSDType ( ) { return WSRPConstants . XSD_BOOLEAN ; } } , BYTE ( "<STR_LIT>" ) { @ Override public Serializable parseFromXML ( String value ) { return parseByte ( value ) ; } @ Override public String printToXML ( Serializable value ) { return printByte ( ( Byte ) value ) ; } @ Override public Class getJavaType ( ) { return byte . class ; } @ Override public QName getXSDType ( ) { return WSRPConstants . XSD_BYTE ; } } , DATE ( "<STR_LIT:date>" ) { @ Override public Serializable parseFromXML ( String value ) { return parseDate ( value ) ; } @ Override public String printToXML ( Serializable value ) { return printDate ( ( Calendar ) value ) ; } @ Override public Class getJavaType ( ) { return null ; } @ Override public QName getXSDType ( ) { return WSRPConstants . XSD_DATE ; } } , DATE_TIME ( "<STR_LIT>" ) { @ Override public Serializable parseFromXML ( String value ) { return parseDateTime ( value ) ; } @ Override public String printToXML ( Serializable value ) { return printDateTime ( ( Calendar ) value ) ; } @ Override public Class getJavaType ( ) { return Calendar . class ; } @ Override public QName getXSDType ( ) { return WSRPConstants . XSD_DATE_TIME ; } } , DECIMAL ( "<STR_LIT>" ) { @ Override public Serializable parseFromXML ( String value ) { return parseDecimal ( value ) ; } @ Override public String printToXML ( Serializable value ) { return printDecimal ( ( BigDecimal ) value ) ; } @ Override public Class getJavaType ( ) { return BigDecimal . class ; } @ Override public QName getXSDType ( ) { return WSRPConstants . XSD_DECIMAL ; } } , DOUBLE ( "<STR_LIT:double>" ) { @ Override public Serializable parseFromXML ( String value ) { return parseDouble ( value ) ; } @ Override public String printToXML ( Serializable value ) { return printDouble ( ( Double ) value ) ; } @ Override public Class getJavaType ( ) { return double . class ; } @ Override public QName getXSDType ( ) { return WSRPConstants . XSD_DOUBLE ; } } , FLOAT ( "<STR_LIT:float>" ) { @ Override public Serializable parseFromXML ( String value ) { return parseFloat ( value ) ; } @ Override public String printToXML ( Serializable value ) { return printFloat ( ( Float ) value ) ; } @ Override public Class getJavaType ( ) { return float . class ; } @ Override public QName getXSDType ( ) { return WSRPConstants . XSD_FLOAT ; } } , HEX_BINARY ( "<STR_LIT>" ) { @ Override public Serializable parseFromXML ( String value ) { return parseHexBinary ( value ) ; } @ Override public String printToXML ( Serializable value ) { return printHexBinary ( ( byte [ ] ) value ) ; } @ Override public Class getJavaType ( ) { return null ; } @ Override public QName getXSDType ( ) { return WSRPConstants . XSD_HEX_BINARY ; } } , INT ( "<STR_LIT:int>" ) { @ Override public Serializable parseFromXML ( String value ) { return parseInt ( value ) ; } @ Override public String printToXML ( Serializable value ) { return printInt ( ( Integer ) value ) ; } @ Override public Class getJavaType ( ) { return int . class ; } @ Override public QName getXSDType ( ) { return WSRPConstants . XSD_INT ; } } , INTEGER ( "<STR_LIT>" ) { @ Override public Serializable parseFromXML ( String value ) { return parseInteger ( value ) ; } @ Override public String printToXML ( Serializable value ) { return printInteger ( ( BigInteger ) value ) ; } @ Override public Class getJavaType ( ) { return BigInteger . class ; } @ Override public QName getXSDType ( ) { return WSRPConstants . XSD_INTEGER ; } } , LONG ( "<STR_LIT:long>" ) { @ Override public Serializable parseFromXML ( String value ) { return parseLong ( value ) ; } @ Override public String printToXML ( Serializable value ) { return printLong ( ( Long ) value ) ; } @ Override public Class getJavaType ( ) { return long . class ; } @ Override public QName getXSDType ( ) { return WSRPConstants . XSD_LONG ; } } , SHORT ( "<STR_LIT>" ) { @ Override public Serializable parseFromXML ( String value ) { return parseShort ( value ) ; } @ Override public String printToXML ( Serializable value ) { return printShort ( ( Short ) value ) ; } @ Override public Class getJavaType ( ) { return short . class ; } @ Override public QName getXSDType ( ) { return WSRPConstants . XSD_SHORT ; } } , STRING ( "<STR_LIT:string>" ) { @ Override public Serializable parseFromXML ( String value ) { return parseString ( value ) ; } @ Override public String printToXML ( Serializable value ) { return printString ( ( String ) value ) ; } @ Override public Class getJavaType ( ) { return String . class ; } @ Override public QName getXSDType ( ) { return WSRPConstants . XSD_STRING ; } } , TIME ( "<STR_LIT>" ) { @ Override public Serializable parseFromXML ( String value ) { return parseTime ( value ) ; } @ Override public String printToXML ( Serializable value ) { return printTime ( ( Calendar ) value ) ; } @ Override public Class getJavaType ( ) { return null ; } @ Override public QName getXSDType ( ) { return WSRPConstants . XSD_TIME ; } } , UNSIGNED_INT ( "<STR_LIT>" ) { @ Override public Serializable parseFromXML ( String value ) { return parseUnsignedInt ( value ) ; } @ Override public String printToXML ( Serializable value ) { return printUnsignedInt ( ( Long ) value ) ; } @ Override public Class getJavaType ( ) { return null ; } @ Override public QName getXSDType ( ) { return WSRPConstants . XSD_UNSIGNED_INT ; } } , UNSIGNED_SHORT ( "<STR_LIT>" ) { @ Override public Serializable parseFromXML ( String value ) { return parseUnsignedShort ( value ) ; } @ Override public String printToXML ( Serializable value ) { return printUnsignedShort ( ( Integer ) value ) ; } @ Override public Class getJavaType ( ) { return null ; } @ Override public QName getXSDType ( ) { return WSRPConstants . XSD_UNSIGNED_SHORT ; } } ; private XSDTypeConverter ( String typeName ) { this . typeName = typeName ; } private String typeName ; public String typeName ( ) { return typeName ; } public abstract Serializable parseFromXML ( String value ) ; public abstract String printToXML ( Serializable value ) ; public abstract Class getJavaType ( ) ; public abstract QName getXSDType ( ) ; } </s>
|
<s> package org . gatein . wsrp . payload ; import org . gatein . wsrp . WSRPTypeFactory ; import org . oasis . wsrp . v2 . NamedString ; import org . oasis . wsrp . v2 . NamedStringArray ; import java . io . Serializable ; import java . util . ArrayList ; import java . util . List ; public class SerializableNamedStringArray implements Serializable { private SerializableNamedString [ ] strings ; SerializableNamedStringArray ( NamedStringArray array ) { initFrom ( array ) ; } void initFrom ( NamedStringArray array ) { List < NamedString > namedString = array . getNamedString ( ) ; strings = new SerializableNamedString [ namedString . size ( ) ] ; int i = <NUM_LIT:0> ; for ( NamedString string : namedString ) { strings [ i ++ ] = new SerializableNamedString ( string . getName ( ) , string . getValue ( ) ) ; } } NamedStringArray toNamedStringArray ( ) { NamedStringArray array = WSRPTypeFactory . createNamedStringArray ( ) ; List < NamedString > namedString = new ArrayList < NamedString > ( strings . length ) ; for ( SerializableNamedString string : strings ) { namedString . add ( WSRPTypeFactory . createNamedString ( string . name , string . value ) ) ; } array . getNamedString ( ) . addAll ( namedString ) ; return array ; } private static class SerializableNamedString implements Serializable { String name ; String value ; private SerializableNamedString ( String name , String value ) { this . name = name ; this . value = value ; } } } </s>
|
<s> package org . gatein . wsrp . payload ; import org . gatein . common . logging . Logger ; import org . gatein . common . logging . LoggerFactory ; import org . gatein . pc . api . PortletInvokerException ; import org . gatein . pc . api . info . EventInfo ; import org . gatein . pc . api . info . EventingInfo ; import org . gatein . pc . api . info . PortletInfo ; import org . gatein . pc . api . invocation . EventInvocation ; import org . gatein . pc . api . invocation . PortletInvocation ; import org . gatein . pc . api . invocation . response . PortletInvocationResponse ; import org . gatein . pc . portlet . PortletInvokerInterceptor ; import org . gatein . pc . portlet . container . ContainerPortletInvoker ; import org . gatein . pc . portlet . container . PortletApplication ; import org . gatein . pc . portlet . container . PortletApplicationContext ; import org . gatein . pc . portlet . container . PortletContainer ; import org . gatein . pc . portlet . impl . info . ContainerTypeInfo ; import javax . xml . bind . JAXBContext ; import javax . xml . bind . JAXBElement ; import javax . xml . bind . Unmarshaller ; import javax . xml . namespace . QName ; import java . io . Serializable ; import java . util . Map ; public class WSRPEventPayloadInterceptor extends PortletInvokerInterceptor { private final static Logger log = LoggerFactory . getLogger ( WSRPEventPayloadInterceptor . class ) ; public PortletInvocationResponse invoke ( PortletInvocation invocation ) throws IllegalArgumentException , PortletInvokerException { if ( invocation instanceof EventInvocation ) { EventInvocation eventInvocation = ( EventInvocation ) invocation ; Serializable srcPayload = eventInvocation . getPayload ( ) ; Serializable dstPayload = srcPayload ; if ( srcPayload instanceof SerializablePayload ) { PortletContainer container = ( PortletContainer ) invocation . getAttribute ( ContainerPortletInvoker . PORTLET_CONTAINER ) ; String containerId = container . getId ( ) ; QName eventName = eventInvocation . getName ( ) ; boolean trace = log . isTraceEnabled ( ) ; PortletInfo info = container . getInfo ( ) ; EventingInfo eventingInfo = info . getEventing ( ) ; Map < QName , ? extends EventInfo > consumedEventInfos = eventingInfo . getConsumedEvents ( ) ; EventInfo eventInfo = consumedEventInfos . get ( eventName ) ; Class dstPayloadClass ; if ( eventInfo != null ) { ContainerTypeInfo typeInfo = ( ContainerTypeInfo ) eventInfo . getType ( ) ; if ( typeInfo != null ) { dstPayloadClass = typeInfo . getType ( ) ; if ( trace ) { log . trace ( "<STR_LIT>" + eventName + "<STR_LIT>" + dstPayloadClass . getName ( ) + "<STR_LIT>" + containerId ) ; } PortletApplication application = container . getPortletApplication ( ) ; PortletApplicationContext applicationContext = application . getContext ( ) ; ClassLoader loader = applicationContext . getClassLoader ( ) ; if ( srcPayload instanceof SerializableSimplePayload ) { dstPayload = ( ( SerializableSimplePayload ) srcPayload ) . getPayload ( ) ; } else { SerializablePayload scp = ( SerializablePayload ) srcPayload ; try { Class < ? extends Serializable > clazz = loader . loadClass ( dstPayloadClass . getName ( ) ) . asSubclass ( Serializable . class ) ; JAXBContext jaxbContext = JAXBContext . newInstance ( clazz ) ; Unmarshaller unmarshaller = jaxbContext . createUnmarshaller ( ) ; JAXBElement < ? extends Serializable > result = unmarshaller . unmarshal ( scp . getElement ( ) , clazz ) ; dstPayload = result . getValue ( ) ; } catch ( Exception e ) { throw new PortletInvokerException ( "<STR_LIT>" , e ) ; } } } else { if ( trace ) { log . trace ( "<STR_LIT>" + eventName + "<STR_LIT>" + containerId ) ; } } } } eventInvocation . setPayload ( dstPayload ) ; try { return super . invoke ( invocation ) ; } finally { eventInvocation . setPayload ( srcPayload ) ; } } else { return super . invoke ( invocation ) ; } } } </s>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.