-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
956 lines (621 loc) · 46.2 KB
/
Copy pathindex.html
File metadata and controls
956 lines (621 loc) · 46.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>javio's Blog</title>
<meta name="author" content="javio">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta property="og:site_name" content="javio's Blog"/>
<meta property="og:image" content="undefined"/>
<link href="/favicon.png" rel="icon">
<link rel="alternate" href="/atom.xml" title="javio's Blog" type="application/atom+xml">
<link rel="stylesheet" href="/css/style.css" media="screen" type="text/css">
<!--[if lt IE 9]><script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
</head>
<body>
<header id="header" class="inner"><div class="alignleft">
<h1><a href="/">javio's Blog</a></h1>
<h2><a href="/"></a></h2>
</div>
<nav id="main-nav" class="alignright">
<ul>
<li><a href="/">Home</a></li>
<li><a href="/archives">Archives</a></li>
</ul>
<div class="clearfix"></div>
</nav>
<div class="clearfix"></div></header>
<div id="content" class="inner">
<div id="main-col" class="alignleft"><div id="wrapper">
<article class="post">
<div class="post-content">
<header>
<div class="icon"></div>
<time datetime="2013-07-09T02:35:04.000Z"><a href="/2013/07/09/guava_optional_1/">7月 9 2013</a></time>
<h1 class="title"><a href="/2013/07/09/guava_optional_1/">Guava Optaional</a></h1>
</header>
<div class="entry">
<p>Using and avoiding null</p>
<pre><code><figure class="highlight"><pre> Many <span class="keyword">of</span> <span class="keyword">the</span> cases <span class="keyword">where</span> programmers use null <span class="keyword">is</span> <span class="keyword">to</span> indicate
<span class="keyword">some</span> sort <span class="keyword">of</span> absence: perhaps <span class="keyword">where</span> there might have been a value,
there <span class="keyword">is</span> none, <span class="keyword">or</span> one could <span class="keyword">not</span> be found.
For example, Map.<span class="keyword">get</span> returns null when no value <span class="keyword">is</span> found <span class="keyword">for</span> a key.
Optional<T> <span class="keyword">is</span> a way <span class="keyword">of</span> replacing a nullable T <span class="keyword">reference</span> <span class="keyword">with</span> a non-null value.
An Optional may either <span class="keyword">contain</span> a non-null T <span class="keyword">reference</span>
(<span class="keyword">in</span> which case we <span class="command">say</span> <span class="keyword">the</span> <span class="keyword">reference</span> <span class="keyword">is</span> <span class="string">"present"</span>),
<span class="keyword">or</span> <span class="keyword">it</span> may <span class="keyword">contain</span> nothing (<span class="keyword">in</span> which case we <span class="command">say</span> <span class="keyword">the</span> <span class="keyword">reference</span> <span class="keyword">is</span> <span class="string">"absent"</span>).
It <span class="keyword">is</span> never said <span class="keyword">to</span> <span class="string">"contain null."</span>
Making an Optional
Static method
Optional.<span class="keyword">of</span>(T) Make an Optional containing <span class="keyword">the</span> <span class="keyword">given</span> non
-null value, <span class="keyword">or</span> fail fast <span class="function_start"><span class="keyword">on</span> <span class="title">null</span></span>.
(java.lang.NullPointerException)
Optional.absent() Return an absent Optional <span class="keyword">of</span> <span class="keyword">some</span> type.
<span class="command">
return</span> rs.next() ? rs.getString(<span class="string">"nickname"</span>) : null;
==>
<span class="command"> return</span> rs.next() ? Optional.<span class="keyword">of</span>(rs.getString(<span class="string">"nickname"</span>)) : Optional.absent();
Optional.fromNullable(T) Turn <span class="keyword">the</span> <span class="keyword">given</span> possibly-null <span class="keyword">reference</span> <span class="keyword">into</span> an Optional,
treating non-null <span class="keyword">as</span> present <span class="keyword">and</span> null <span class="keyword">as</span> absent.
許多程式庫中使用了不少 null,Guava 提供fromNullabe(T)用來銜接程式庫中 null 的方法
String nickName = Optional.fromNullable(getNickName(<span class="string">"Duke"</span>)).<span class="keyword">or</span>(<span class="string">"CoDeData User"</span>);
Query methods
non-static methods
<span class="type">boolean</span> isPresent() Returns <span class="constant">true</span> <span class="keyword">if</span> this Optional <span class="keyword">contains</span> a non-null instance.
T <span class="keyword">get</span>() Returns <span class="keyword">the</span> contained T instance, which must be present;
otherwise, throws an IllegalStateException.
T <span class="keyword">or</span>(T) Returns <span class="keyword">the</span> present value <span class="keyword">in</span> this Optional,
<span class="keyword">or</span> <span class="keyword">if</span> there <span class="keyword">is</span> none, returns <span class="keyword">the</span> specified default.
String nickName = Optional.fromNullable(getNickName(<span class="string">"Duke"</span>)).<span class="keyword">or</span>(<span class="string">"CoDeData User"</span>);
T orNull() Returns <span class="keyword">the</span> present value <span class="keyword">in</span> this Optional, <span class="keyword">or</span> <span class="keyword">if</span> there <span class="keyword">is</span> none, returns null.
The inverse operation <span class="keyword">of</span> fromNullable.
String nickName = Optional.fromNullable(getNickName(<span class="string">"Duke"</span>)).orNull();
Set<T> asSet() Returns an immutable singleton Set containing <span class="keyword">the</span> instance <span class="keyword">in</span> this Optional,
<span class="keyword">if</span> there <span class="keyword">is</span> one, <span class="keyword">or</span> otherwise an empty immutable <span class="keyword">set</span>.
</pre></figure></code></pre>
</div>
<footer>
<div class="clearfix"></div>
</footer>
</div>
</article>
<article class="post">
<div class="post-content">
<header>
<div class="icon"></div>
<time datetime="2013-07-08T14:03:20.000Z"><a href="/2013/07/08/vertx_common_util/">7月 8 2013</a></time>
<h1 class="title"><a href="/2013/07/08/vertx_common_util/">vertx_common_util</a></h1>
</header>
<div class="entry">
<p>Logger
...
import org.vertx.java.core.logging.Logger;
....</p>
<pre><code><figure class="highlight"><pre> <span class="comment">private</span> <span class="comment">Logger</span> <span class="comment">logger;</span>
<span class="comment">public</span> <span class="comment">void</span> <span class="comment">start()</span> <span class="comment">{</span>
<span class="comment">logger</span> <span class="comment">=</span> <span class="comment">getContainer()</span>.<span class="comment">getLogger();</span>
<span class="string">.</span><span class="string">.</span><span class="string">.</span><span class="string">.</span>
<span class="comment">}
</pre></figure></code></pre>
</div>
<footer>
<div class="clearfix"></div>
</footer>
</div>
</article>
<article class="post">
<div class="post-content">
<header>
<div class="icon"></div>
<time datetime="2013-07-08T08:55:17.000Z"><a href="/2013/07/08/vertx_concept_eventbox/">7月 8 2013</a></time>
<h1 class="title"><a href="/2013/07/08/vertx_concept_eventbox/">Event Box</a></h1>
</header>
<div class="entry">
<p>Event Box </p>
<pre><code><figure class="highlight"><pre>Addressing:
-String
-Dot-style namespacing recommended
- e.g. <span class="string">"messages.inbound.A"</span>
Handlers
-A handler <span class="keyword">is</span> a thing <span class="keyword">that</span> receives messages <span class="keyword">from</span> <span class="keyword">the</span> bus.
-You register a handler <span class="keyword">at</span> an address.
-Many different handlers <span class="keyword">from</span> <span class="keyword">the</span> same <span class="keyword">or</span> different verticles
can be registered <span class="keyword">at</span> <span class="keyword">the</span> same address.
-A single handler can be registered <span class="keyword">by</span> <span class="keyword">the</span> verticle <span class="keyword">at</span> many different addresses.
Handler Registration
EventBus eb = vertx.eventbus();
Handler<Message> myHandler = new Handle<Message>() {
public boid handle(Message message)
System.out.println(<span class="string">"received a message "</span> + message);
};
eb.registerHandle(<span class="string">"test.address"</span>,myHandler);
Pub/Sub (Publish / subscribe messaging)
The event bus supports publishing messages.
Messages are published <span class="keyword">to</span> an address.
Publishing means delivering <span class="keyword">the</span> message <span class="keyword">to</span> all handlers <span class="keyword">that</span> are registered <span class="keyword">at</span> <span class="keyword">that</span> address.
This <span class="keyword">is</span> <span class="keyword">the</span> familiar publish/subscribe messaging pattern.
P2P (Point <span class="keyword">to</span> point messaging)
The event bus supports point <span class="keyword">to</span> point messaging.
Messages are sent <span class="keyword">to</span> an address.
This means a message <span class="keyword">is</span> delivered <span class="keyword">to</span> <span class="keyword">at</span> most one <span class="keyword">of</span> <span class="keyword">the</span> handlers registered <span class="keyword">at</span> <span class="keyword">that</span> address.
If there <span class="keyword">is</span> more than one handler regsitered <span class="keyword">at</span> <span class="keyword">the</span> address,
one will be chosen using a non-strict <span class="command">round</span>-robin algorithm.
With point <span class="keyword">to</span> point messaging, an optional reply handler can be specified when sending <span class="keyword">the</span> message. When a message <span class="keyword">is</span> received <span class="keyword">by</span> a recipient, <span class="keyword">and</span> has been processed, <span class="keyword">the</span> recipient can optionally decide <span class="keyword">to</span> reply <span class="keyword">to</span> <span class="keyword">the</span> message.
If they do so <span class="keyword">that</span> reply handler will be called.
When <span class="keyword">the</span> reply <span class="keyword">is</span> received <span class="keyword">back</span> <span class="keyword">at</span> <span class="keyword">the</span> sender, <span class="keyword">it</span> too can be replied <span class="keyword">to</span>.
This can be repeated ad-infinitum, <span class="keyword">and</span> allows a dialog <span class="keyword">to</span> be <span class="keyword">set</span>-up <span class="keyword">between</span> two different verticles. This <span class="keyword">is</span> a common messaging pattern called <span class="keyword">the</span> Request-Response pattern.
Sender :
//eb.send
eb.send(<span class="string">"test.address"</span>,<span class="string">"This is a message"</span> ,new Handler<Message<String>>(){
public void handle(Message<String> message) {
System.our.println(<span class="string">"receuved a reply"</span> + message.body);
}
});
Receiver:
Handler<Message<String>> myHandler = new Handler<Message<String>>(){
public void handle(Message<String> message) {
System.out.println(<span class="string">"I received a message "</span> +message.body);
message.reply(<span class="string">"This is a reply"</span>);
}
}
eb.registerHandler(<span class="string">"test.address"</span>,myHandler);
Message Types
-String
-Primitives
-Boxed Primitives
-<span class="type">boolean</span>/Boolean
-org.vertx.java.core.json.JsonObject
-org.vertx.java.core.buffer.Buffer
Transient
All messages <span class="keyword">in</span> <span class="keyword">the</span> event bus are transient, <span class="keyword">and</span> <span class="keyword">in</span> case <span class="keyword">of</span> failure <span class="keyword">of</span> all <span class="keyword">or</span>
parts <span class="keyword">of</span> <span class="keyword">the</span> event bus, there <span class="keyword">is</span> a possibility messages will be lost.
If your <span class="type">application</span> cares <span class="keyword">about</span> lost messages, you should code your handlers <span class="keyword">to</span> be idempotent, <span class="keyword">and</span> your senders <span class="keyword">to</span> retry <span class="keyword">after</span> recovery.
If you want <span class="keyword">to</span> persist your messages you can use a persistent work queue module <span class="keyword">for</span> <span class="keyword">that</span>.
</pre></figure></code></pre>
</div>
<footer>
<div class="clearfix"></div>
</footer>
</div>
</article>
<article class="post">
<div class="post-content">
<header>
<div class="icon"></div>
<time datetime="2013-07-08T08:27:16.000Z"><a href="/2013/07/08/vertx_concept_verticle/">7月 8 2013</a></time>
<h1 class="title"><a href="/2013/07/08/vertx_concept_verticle/">Verticle</a></h1>
</header>
<div class="entry">
<p>Verticle
-unit of deployment
-Script/Java Class</p>
<p>Verticle run inside a vert.x instance </p>
<p>A single vert.x instance runs inside its own JVM instance.</p>
<p>Concuurency
-Verticle instance assigned thread/event loop
-Verticle instance ALWAYS executes on assigned thread
-Verticles have isolated classloaders and cnnot shared global satae (static members,global variables etc)
-can write all code assuming single threading</p>
<p>Verticles are executed using the same thread</p>
<p>Every Java verticle must extend the class org.vertx.java.deploy.Verticle.
You must override the start method - this is called by Vert.x when the verticle is started.</p>
<p>Verticle clean-up</p>
<p>Servers, clients and event bus handlers will be automatically closed when the verticle is stopped.
However, if you have any other clean-up logic that you want to execute when the verticle is stopped,
you can implement a stop method which will be called when the verticle is undeployed.</p>
<p>Specifying number of instances</p>
<p>By default, when you deploy a verticle only one instance of the verticle is deployed.
If you want more than one instance to be deployed, e.g. so you can scale over your cores better,
you can specify the number of instances as follows:
container.deployVerticle("foo.ChildVerticle", 10);
The above example would deploy 10 instances.</p>
</div>
<footer>
<div class="clearfix"></div>
</footer>
</div>
</article>
<article class="post">
<div class="post-content">
<header>
<div class="icon"></div>
<time datetime="2013-07-08T06:32:08.000Z"><a href="/2013/07/08/spring_security_filter_2/">7月 8 2013</a></time>
<h1 class="title"><a href="/2013/07/08/spring_security_filter_2/">logoutFilter</a></h1>
</header>
<div class="entry">
<p>1.notices that the URL that is being requested is for logout</p>
<p>2.The filter calls the configured LogoutHandle(implement the LogoutHandler interface)
SecurityContextLogoutHandler
invalidates the Servlet session, in the standard Servlet way, calling the invalidate method
on the HttpSession object and also clearing the SecurityContext from Spring Security
(JSESSIONID cookie not clear)
TokenBasedRememberMeServices
removes the remember-me cookie by setting its age to 0.</p>
<pre><code><figure class="highlight"><pre>JSESSIONID cookie
<span class="tag"><<span class="title">security:http</span>></span>
....
<span class="tag"><<span class="title">security:logout</span> <span class="attribute">delete-cookies</span>=<span class="value">"JSESSIONID"</span>/></span>.
...
<span class="tag"></<span class="title">security:http</span>></span>
To enable the CookieClearingLogoutHandler handler (removes cookies)
</pre></figure></code></pre>
<p>3.calls the LogoutSuccessHandler’s onLogoutSuccess method
in the default configuration, redirects to a target URL
The target URL ( default the root of the application) can be configured using </p>
<pre><code><figure class="highlight"><pre> request parameter
<span class="tag"><<span class="title">security:logout</span> <span class="attribute">logout-success-url</span>=<span class="value">"/index"</span> /></span>
the referrer header from the request
<span class="tag"><<span class="title">security:logout</span> <span class="attribute">delete-cookies</span>=<span class="value">"JSESSIONID"</span> <span class="attribute">success-handler-ref</span>=<span class="value">"logoutRedirectToAny"</span>/></span>
...
<span class="tag"><<span class="title">bean</span> <span class="attribute">id</span>=<span class="value">"logoutRedirectToAny"</span>
<span class="attribute">class</span>=<span class="value">"org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler"</span>></span>
<span class="tag"><<span class="title">property</span> <span class="attribute">name</span>=<span class="value">"targetUrlParameter"</span> <span class="attribute">value</span>=<span class="value">"redirectTo"</span>/></span>
<span class="tag"></<span class="title">bean</span>></span>
request the following URL
/j_spring_security_logout?redirectTo=http://www.google.com
You will be logged out and redirected to Google
The current implementation LogoutSuccessHandler (SimpleUrlLogoutSuccessHandler)
extends from AbstractAuthenticationTargetUrlRequestHandler, which is also used by
the authentication process to redirect to a determined URL after authenticating successfully
</pre></figure></code></pre>
<p>LogoutFilter extends GenericFilterBean</p>
<pre><code><figure class="highlight"><pre> ....
<span class="keyword">private</span> String filterProcessesUrl = <span class="string">"/j_spring_security_logout"</span>;
<span class="keyword">private</span> final List<LogoutHandler> handlers;
<span class="keyword">private</span> final LogoutSuccessHandler logoutSuccessHandler;
...
<span class="keyword">public</span> <span class="keyword">void</span> doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
<span class="comment">//if the request's URL is /j_spring_security_logout</span>
<span class="keyword">if</span> (requiresLogout(request, response)) {
Authentication auth = SecurityContextHolder<span class="variable">.getContext</span>()<span class="variable">.getAuthentication</span>();
<span class="keyword">if</span> (logger<span class="variable">.isDebugEnabled</span>()) {
logger<span class="variable">.debug</span>(<span class="string">"Logging out user '"</span> + auth + <span class="string">"' and transferring to logout destination"</span>);
}
<span class="keyword">for</span> (LogoutHandler handler : handlers) {
handler<span class="variable">.logout</span>(request, response, auth);
}
logoutSuccessHandler<span class="variable">.onLogoutSuccess</span>(request, response, auth);
<span class="keyword">return</span>;
}
chain<span class="variable">.doFilter</span>(request, response);
}
....
<span class="keyword">protected</span> boolean requiresLogout(HttpServletRequest request, HttpServletResponse response) {
String uri = request<span class="variable">.getRequestURI</span>();
<span class="keyword">int</span> pathParamIndex = uri<span class="variable">.indexOf</span>(<span class="string">';'</span>);
<span class="keyword">if</span> (pathParamIndex > <span class="number">0</span>) {
<span class="comment">// strip everything from the first semi-colon</span>
uri = uri<span class="variable">.substring</span>(<span class="number">0</span>, pathParamIndex);
}
<span class="keyword">int</span> queryParamIndex = uri<span class="variable">.indexOf</span>(<span class="string">'?'</span>);
<span class="keyword">if</span> (queryParamIndex > <span class="number">0</span>) {
<span class="comment">// strip everything from the first question mark</span>
uri = uri<span class="variable">.substring</span>(<span class="number">0</span>, queryParamIndex);
}
<span class="keyword">if</span> (<span class="string">""</span><span class="variable">.equals</span>(request<span class="variable">.getContextPath</span>())) {
<span class="keyword">return</span> uri<span class="variable">.endsWith</span>(filterProcessesUrl);
}
<span class="keyword">return</span> uri<span class="variable">.endsWith</span>(request<span class="variable">.getContextPath</span>() + filterProcessesUrl);
}
</pre></figure></code></pre>
</div>
<footer>
<div class="clearfix"></div>
</footer>
</div>
</article>
<article class="post">
<div class="post-content">
<header>
<div class="icon"></div>
<time datetime="2013-07-08T05:49:34.000Z"><a href="/2013/07/08/spring_security_filter_1/">7月 8 2013</a></time>
<h1 class="title"><a href="/2013/07/08/spring_security_filter_1/">SecurityContextPersistenceFilter</a></h1>
</header>
<div class="entry">
<ul>
<li>The first security filter that gets hit by the request is SecurityContextPersistenceFilter.</li>
<li>When the request hits this filter, the framework tries to retrieve a SecurityContext from the standard Servlet session
(javax.servlet.http.HttpSession).</li>
<li><p>If there is not a context in the session, or the session itself is null (that is, it still doesn’t exist because it hasn’t been
created yet), the framework creates a new empty SecurityContext(or, more accurately, an instance of its implementation class SecurityContextImpl).</p>
</li>
<li><p>A new SecurityContext is created and associated to the current thread of execution.</p>
</li>
</ul>
<p>SecurityContextPersistenceFilter</p>
<pre><code><figure class="highlight"><pre> ....
static final String FILTER_APPLIED = <span class="string">"__spring_security_scpf_applied"</span><span class="comment">;</span>
private SecurityContextRepository repo<span class="comment">;</span>
private boolean forceEagerSessionCreation = false<span class="comment">;</span>
.....
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req<span class="comment">;</span>
HttpServletResponse response = (HttpServletResponse) res<span class="comment">;</span>
if (request<span class="preprocessor">.getAttribute</span>(FILTER_APPLIED) != null) {
// ensure that filter is only applied once per request
chain<span class="preprocessor">.doFilter</span>(request, response)<span class="comment">;</span>
return<span class="comment">;</span>
}
final boolean debug = logger<span class="preprocessor">.isDebugEnabled</span>()<span class="comment">;</span>
request<span class="preprocessor">.setAttribute</span>(FILTER_APPLIED, Boolean<span class="preprocessor">.TRUE</span>)<span class="comment">;</span>
if (forceEagerSessionCreation) {
HttpSession session = request<span class="preprocessor">.getSession</span>()<span class="comment">;</span>
if (debug && session<span class="preprocessor">.isNew</span>()) {
logger<span class="preprocessor">.debug</span>(<span class="string">"Eagerly created session: "</span> + session<span class="preprocessor">.getId</span>())<span class="comment">;</span>
}
}
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response)<span class="comment">;</span>
//repo<span class="preprocessor">.loadContext</span>(holder)
<span class="comment">/*retrieve a SecurityContext from the standard Servlet session (javax.servlet.http.HttpSession).
If there is not a context in the session, or the session itself is null (that is, it still doesn’t exist because it
hasn’t been created yet), the framework creates a new empty SecurityContext(or, more accurately, an instance of its
implementation class SecurityContextImpl).
*/</span>
SecurityContext contextBeforeChainExecution = repo<span class="preprocessor">.loadContext</span>(holder)<span class="comment">;</span>
try {
SecurityContextHolder<span class="preprocessor">.setContext</span>(contextBeforeChainExecution)<span class="comment">;</span>
chain<span class="preprocessor">.doFilter</span>(holder<span class="preprocessor">.getRequest</span>(), holder<span class="preprocessor">.getResponse</span>())<span class="comment">;</span>
} finally {
SecurityContext contextAfterChainExecution = SecurityContextHolder<span class="preprocessor">.getContext</span>()<span class="comment">;</span>
// Crucial removal of SecurityContextHolder contents - do this before anything else.
SecurityContextHolder<span class="preprocessor">.clearContext</span>()<span class="comment">;</span>
repo<span class="preprocessor">.saveContext</span>(contextAfterChainExecution, holder<span class="preprocessor">.getRequest</span>(), holder<span class="preprocessor">.getResponse</span>())<span class="comment">;</span>
request<span class="preprocessor">.removeAttribute</span>(FILTER_APPLIED)<span class="comment">;</span>
if (debug) {
logger<span class="preprocessor">.debug</span>(<span class="string">"SecurityContextHolder now cleared, as request processing completed"</span>)<span class="comment">;</span>
}
}
}
</pre></figure></code></pre>
<p>HttpSessionSecurityContextRepository implements SecurityContextRepository</p>
<pre><code><figure class="highlight"><pre> ....
<span class="keyword">private</span> String springSecurityContextKey = SPRING_SECURITY_CONTEXT_KEY;
....
<span class="keyword">public</span> SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {
HttpServletRequest request = requestResponseHolder.getRequest();
HttpServletResponse response = requestResponseHolder.getResponse();
HttpSession httpSession = request.getSession(<span class="literal">false</span>);
SecurityContext context = readSecurityContextFromSession(httpSession);
<span class="keyword">if</span> (context == <span class="literal">null</span>) {
<span class="keyword">if</span> (logger.isDebugEnabled()) {
logger.<span class="keyword">debug</span>(<span class="string">"No SecurityContext was available from the HttpSession: "</span> + httpSession +<span class="string">". "</span> +
<span class="string">"A new one will be created."</span>);
}
context = generateNewContext();
}
requestResponseHolder.setResponse(<span class="keyword">new</span> SaveToSessionResponseWrapper(response, request, httpSession != <span class="literal">null</span>, context));
<span class="keyword">return</span> context;
}
<span class="keyword">private</span> SecurityContext readSecurityContextFromSession(HttpSession httpSession) {
<span class="keyword">final</span> boolean <span class="keyword">debug</span> = logger.isDebugEnabled();
<span class="keyword">if</span> (httpSession == <span class="literal">null</span>) {
<span class="keyword">if</span> (<span class="keyword">debug</span>) {
logger.<span class="keyword">debug</span>(<span class="string">"No HttpSession currently exists"</span>);
}
<span class="keyword">return</span> <span class="literal">null</span>;
}
<span class="comment">// Session exists, so try to obtain a context from it.</span>
Object contextFromSession = httpSession.getAttribute(springSecurityContextKey);
<span class="keyword">if</span> (contextFromSession == <span class="literal">null</span>) {
<span class="keyword">if</span> (<span class="keyword">debug</span>) {
logger.<span class="keyword">debug</span>(<span class="string">"HttpSession returned null object for SPRING_SECURITY_CONTEXT"</span>);
}
<span class="keyword">return</span> <span class="literal">null</span>;
}
<span class="comment">// We now have the security context object from the session.</span>
<span class="keyword">if</span> (!(contextFromSession instanceof SecurityContext)) {
<span class="keyword">if</span> (logger.isWarnEnabled()) {
logger.warn(springSecurityContextKey + <span class="string">" did not contain a SecurityContext but contained: '"</span>
+ contextFromSession + <span class="string">"'; are you improperly modifying the HttpSession directly "</span>
+ <span class="string">"(you should always use SecurityContextHolder) or using the HttpSession attribute "</span>
+ <span class="string">"reserved for this class?"</span>);
}
<span class="keyword">return</span> <span class="literal">null</span>;
}
<span class="keyword">if</span> (<span class="keyword">debug</span>) {
logger.<span class="keyword">debug</span>(<span class="string">"Obtained a valid SecurityContext from "</span> + springSecurityContextKey + <span class="string">": '"</span> + contextFromSession + <span class="string">"'"</span>);
}
<span class="comment">// Everything OK. The only non-null return from this method.</span>
<span class="keyword">return</span> (SecurityContext) contextFromSession;
}
</pre></figure></code></pre>
</div>
<footer>
<div class="clearfix"></div>
</footer>
</div>
</article>
<article class="post">
<div class="post-content">
<header>
<div class="icon"></div>
<time datetime="2013-07-08T03:03:47.000Z"><a href="/2013/07/08/spring_security_service_layer/">7月 8 2013</a></time>
<h1 class="title"><a href="/2013/07/08/spring_security_service_layer/">spring_security_service_layer</a></h1>
</header>
<div class="entry">
<p>security.xml
1.<security:global-method-security secured-annotations="enabled" /></p>
</div>
<footer>
<div class="clearfix"></div>
</footer>
</div>
</article>
<article class="post">
<div class="post-content">
<header>
<div class="icon"></div>
<time datetime="2013-07-08T01:49:11.000Z"><a href="/2013/07/08/spring_security_note/">7月 8 2013</a></time>
<h1 class="title"><a href="/2013/07/08/spring_security_note/">spring_security_note</a></h1>
</header>
<div class="entry">
<p>Spring security
(1) uses Spring Security to access our current user.
The Authentication object represents all the information we gathered at the time of authentication (username,password, roles, and so on).</p>
<pre><code><figure class="highlight"><pre> String username = SecurityContextHolder<span class="preprocessor">.getContext</span>() //o<span class="preprocessor">.s</span><span class="preprocessor">.s</span><span class="preprocessor">.core</span><span class="preprocessor">.context</span><span class="preprocessor">.SecurityContext</span>
<span class="preprocessor">.getAuthentication</span>() //o<span class="preprocessor">.s</span><span class="preprocessor">.s</span><span class="preprocessor">.core</span><span class="preprocessor">.Authentication</span>
<span class="preprocessor">.getName</span>()<span class="comment">; //login user name</span>
===============================================================
SecurityContext context = SecurityContextHolder<span class="preprocessor">.getContext</span>()<span class="comment">;</span>
Authentication authentication = context<span class="preprocessor">.getAuthentication</span>()<span class="comment">;</span>
if (authentication == null) {
return null<span class="comment">;</span>
}
String email = authentication<span class="preprocessor">.getName</span>()<span class="comment">;</span>
return calendarService<span class="preprocessor">.findUserByEmail</span>(email)<span class="comment">;</span>
note:It should be noted that null checks should always be done on the Authentication object,
as it could be null if the user is not logged <span class="keyword">in</span>.
===============================================================
User user = (User)SecurityContextHolder<span class="preprocessor">.getContext</span>()<span class="preprocessor">.getAuthentication</span>()<span class="preprocessor">.getPrincipal</span>()<span class="comment">;</span>
</pre></figure></code></pre>
</div>
<footer>
<div class="clearfix"></div>
</footer>
</div>
</article>
<article class="post">
<div class="post-content">
<header>
<div class="icon"></div>
<time datetime="2013-07-06T23:56:55.000Z"><a href="/2013/07/07/spring_security_simple_example/">7月 7 2013</a></time>
<h1 class="title"><a href="/2013/07/07/spring_security_simple_example/">spring_security_simple_example</a></h1>
</header>
<div class="entry">
<p>簡單的security 設定檔
securiy.xml
<!--excluse /resources/** -->
<http pattern="/resources/**" security="none"/></p>
<pre><code><figure class="highlight"><pre> <span class="comment"><!-- auto-config="true" 使用spring secuirty 一些基本的設定--></span>
<span class="comment"><!-- use-expressions="true" 使用SpEL --></span>
<span class="tag"><<span class="title">http</span> <span class="attribute">auto-config</span>=<span class="value">"true"</span> <span class="attribute">use-expressions</span>=<span class="value">"true"</span>></span>
<span class="comment"><!-- ConfigAttribute : ROLE_ADMIN , ROLE_USER --></span>
<span class="comment"><!-- Security Metadata <intercept-url pattern=... access=... --></span>
<span class="tag"><<span class="title">intercept-url</span> <span class="attribute">pattern</span>=<span class="value">"/"</span> <span class="attribute">access</span>=<span class="value">"permitAll"</span>/></span>
<span class="tag"><<span class="title">intercept-url</span> <span class="attribute">pattern</span>=<span class="value">"/login/*"</span> <span class="attribute">access</span>=<span class="value">"permitAll"</span>/></span>
<span class="tag"><<span class="title">intercept-url</span> <span class="attribute">pattern</span>=<span class="value">"/logout"</span> <span class="attribute">access</span>=<span class="value">"permitAll"</span>/></span>
<span class="tag"><<span class="title">intercept-url</span> <span class="attribute">pattern</span>=<span class="value">"/errors/**"</span> <span class="attribute">access</span>=<span class="value">"permitAll"</span>/></span>
<span class="tag"><<span class="title">intercept-url</span> <span class="attribute">pattern</span>=<span class="value">"/events/"</span> <span class="attribute">access</span>=<span class="value">"hasRole('ROLE_ADMIN')"</span>/></span>
<span class="tag"><<span class="title">intercept-url</span> <span class="attribute">pattern</span>=<span class="value">"/admin/**"</span> <span class="attribute">access</span>=<span class="value">"hasRole('ROLE_ADMIN')"</span>/></span>
<span class="tag"><<span class="title">intercept-url</span> <span class="attribute">pattern</span>=<span class="value">"/**"</span> <span class="attribute">access</span>=<span class="value">"hasRole('ROLE_USER')"</span>/></span>
<span class="tag"><<span class="title">access-denied-handler</span> <span class="attribute">error-page</span>=<span class="value">"/errors/403"</span>/></span>
<span class="comment"><!-- spring security filter --></span>
<span class="tag"><<span class="title">form-login
</span> <!<span class="attribute">--</span> <span class="attribute">customer</span> <span class="attribute">login</span> <span class="attribute">use</span> /<span class="attribute">login</span>/<span class="attribute">form</span>
<span class="attribute">If</span> <span class="attribute">a</span> <span class="attribute">login</span> <span class="attribute">page</span> <span class="attribute">is</span> <span class="attribute">not</span> <span class="attribute">specified</span>,
<span class="attribute">Spring</span> <span class="attribute">Security</span> <span class="attribute">will</span> <span class="attribute">redirect</span> <span class="attribute">the</span> <span class="attribute">user</span> <span class="attribute">to</span> /<span class="attribute">spring_security_login.</span>
<span class="attribute">--</span>></span>
login-page="/login/form"
login-processing-url="/login"
username-parameter="username"
password-parameter="password"
authentication-failure-url="/login/form?error"
<span class="comment"><!-- default-target-url will be the context root of the application
depending on the user's role
send the user to a different default-target-url attribute
ref controller that processes /default
--></span>
default-target-url="/default"/>
<span class="comment"><!-- spring security filter --></span>
<span class="tag"><<span class="title">logout</span> <span class="attribute">logout-success-url</span>=<span class="value">"/login/form?logout"</span>/></span>
<span class="tag"></<span class="title">http</span>></span>
<span class="tag"><<span class="title">authentication-manager</span>></span>
<span class="tag"><<span class="title">authentication-provider</span>></span>
<span class="tag"><<span class="title">user-service</span>></span>
<span class="tag"><<span class="title">user</span> <span class="attribute">name</span>=<span class="value">"user"</span> <span class="attribute">password</span>=<span class="value">"user"</span> <span class="attribute">authorities</span>=<span class="value">"ROLE_USER"</span>/></span>
<span class="tag"><<span class="title">user</span> <span class="attribute">name</span>=<span class="value">"admin"</span> <span class="attribute">password</span>=<span class="value">"admin"</span><span class="attribute">authorities</span>=<span class="value">"ROLE_USER,ROLE_ADMIN"</span>/></span>
<span class="tag"></<span class="title">user-service</span>></span>
<span class="tag"></<span class="title">authentication-provider</span>></span>
<span class="tag"></<span class="title">authentication-manager</span>></span>
</pre></figure></code></pre>
<p>DefaultController.java</p>
<pre><code><figure class="highlight"><pre> <span class="comment">// imports omitted</span>
<span class="annotation">@Controller</span>
<span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DefaultController</span> {</span>
<span class="annotation">@RequestMapping</span>(<span class="string">"/default"</span>)
<span class="keyword">public</span> String defaultAfterLogin(HttpServletRequest request) {
<span class="keyword">if</span> (request.isUserInRole(<span class="string">"ROLE_ADMIN"</span>)) {
<span class="keyword">return</span> <span class="string">"redirect:/events/"</span>;
}
<span class="keyword">return</span> <span class="string">"redirect:/"</span>;
}
}
</pre></figure></code></pre>
</div>
<footer>
<div class="clearfix"></div>
</footer>
</div>
</article>
<article class="post">
<div class="post-content">
<header>
<div class="icon"></div>
<time datetime="2013-07-06T13:05:41.000Z"><a href="/2013/07/06/number-format/">7月 6 2013</a></time>
<h1 class="title"><a href="/2013/07/06/number-format/">number format</a></h1>
</header>
<div class="entry">
<p>number format</p>
<pre><code><figure class="highlight"><pre> ....
<fmt:formatNumber value=<span class="string">"<span class="subst">${item.PRICE}</span>"</span> pattern=<span class="string">"#,##0.00"</span>/>
....
</pre></figure></code></pre>
</div>
<footer>
<div class="clearfix"></div>
</footer>
</div>
</article>
<nav id="pagination">
<a href="/page/2/" class="alignright next">下一頁</a>
<div class="clearfix"></div>
</nav></div></div>
<aside id="sidebar" class="alignright">
<div class="search">
<form action="//google.com/search" method="get" accept-charset="utf-8">
<input type="search" name="q" results="0" placeholder="搜尋">
<input type="hidden" name="q" value="site:yoursite.com">
</form>
</div>
<div class="widget tag">
<h3 class="title">分類</h3>
<ul class="entry">
<li><a href="/categories/guava/">guava</a><small>1</small></li>
<li><a href="/categories/jstl/">jstl</a><small>2</small></li>
<li><a href="/categories/spring/">spring</a><small>6</small></li>
<li><a href="/categories/vertx/">vertx</a><small>3</small></li>
</ul>
</div>
<div class="widget tag">
<h3 class="title">標籤</h3>
<ul class="entry">
<li><a href="/tags/filter/">filter</a><small>2</small></li>
<li><a href="/tags/guava/">guava</a><small>1</small></li>
<li><a href="/tags/jstl/">jstl</a><small>2</small></li>
<li><a href="/tags/spring-1/">spring</a><small>6</small></li>
<li><a href="/tags/spring_security/">spring_security</a><small>6</small></li>
<li><a href="/tags/vertx/">vert.x</a><small>3</small></li>
</ul>
</div>
</aside>
<div class="clearfix"></div>
</div>
<footer id="footer" class="inner"><div class="alignleft">
© 2013 javio
</div>
<div class="clearfix"></div></footer>
<script src="/js/jquery.imagesloaded.min.js"></script>
<script src="/js/gallery.js"></script>
<link rel="stylesheet" href="/fancybox/jquery.fancybox.css" media="screen" type="text/css">
<script src="/fancybox/jquery.fancybox.pack.js"></script>
<script type="text/javascript">
(function($){
$('.fancybox').fancybox();
})(jQuery);
</script>
</body>
</html>