-
Notifications
You must be signed in to change notification settings - Fork 1
/
SWBPortal.java
3166 lines (2972 loc) · 146 KB
/
SWBPortal.java
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
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* SemanticWebBuilder es una plataforma para el desarrollo de portales y aplicaciones de integración,
* colaboración y conocimiento, que gracias al uso de tecnología semántica puede generar contextos de
* información alrededor de algún tema de interés o bien integrar información y aplicaciones de diferentes
* fuentes, donde a la información se le asigna un significado, de forma que pueda ser interpretada y
* procesada por personas y/o sistemas, es una creación original del Fondo de Información y Documentación
* para la Industria INFOTEC, cuyo registro se encuentra actualmente en trámite.
*
* INFOTEC pone a su disposición la herramienta SemanticWebBuilder a través de su licenciamiento abierto al público (‘open source’),
* en virtud del cual, usted podrá usarlo en las mismas condiciones con que INFOTEC lo ha diseñado y puesto a su disposición;
* aprender de él; distribuirlo a terceros; acceder a su código fuente y modificarlo, y combinarlo o enlazarlo con otro software,
* todo ello de conformidad con los términos y condiciones de la LICENCIA ABIERTA AL PÚBLICO que otorga INFOTEC para la utilización
* del SemanticWebBuilder 4.0.
*
* INFOTEC no otorga garantía sobre SemanticWebBuilder, de ninguna especie y naturaleza, ni implícita ni explícita,
* siendo usted completamente responsable de la utilización que le dé y asumiendo la totalidad de los riesgos que puedan derivar
* de la misma.
*
* Si usted tiene cualquier duda o comentario sobre SemanticWebBuilder, INFOTEC pone a su disposición la siguiente
* dirección electrónica:
* http://www.semanticwebbuilder.org.mx
*/
package org.semanticwb;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.servlet.Filter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.semanticwb.SWBUtils.IO;
import org.semanticwb.css.parser.Attribute;
import org.semanticwb.css.parser.CSSParser;
import org.semanticwb.css.parser.Selector;
import org.semanticwb.model.FriendlyURL;
import org.semanticwb.model.Language;
import org.semanticwb.model.ResourceType;
import org.semanticwb.model.Rule;
import org.semanticwb.model.SWBContext;
import org.semanticwb.model.User;
import org.semanticwb.model.UserGroup;
import org.semanticwb.model.UserRepository;
import org.semanticwb.model.WebSite;
import org.semanticwb.platform.SWBMessageCenter;
import org.semanticwb.platform.SemanticModel;
import org.semanticwb.portal.PFlowManager;
import org.semanticwb.portal.SWBAdminFilterMgr;
import org.semanticwb.portal.SWBMessageProcesor;
import org.semanticwb.portal.SWBMonitor;
import org.semanticwb.portal.SWBResourceMgr;
import org.semanticwb.portal.SWBServiceMgr;
import org.semanticwb.portal.SWBTemplateMgr;
import org.semanticwb.portal.SWBUserMgr;
import org.semanticwb.portal.access.SWBAccessIncrement;
import org.semanticwb.portal.access.SWBAccessLog;
import org.semanticwb.portal.api.SWBResource;
import org.semanticwb.portal.db.SWBDBAdmLog;
import org.semanticwb.portal.indexer.SWBIndexMgr;
import org.semanticwb.portal.resources.ImageGallery;
import org.semanticwb.portal.services.SWBCloud;
import org.semanticwb.portal.util.CaptchaUtil;
import org.semanticwb.portal.util.ContentStyles;
import org.semanticwb.portal.util.SWBSoundEngine;
import org.semanticwb.repository.Workspace;
import org.semanticwb.util.JarFile;
import org.semanticwb.util.db.GenericDB;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.arthurdo.parser.HtmlStreamTokenizer;
import com.arthurdo.parser.HtmlTag;
// TODO: Auto-generated Javadoc
/**
* Executes initialization operations for the environment necesary to provide
* Portal services, so users, templates, publication flows, resources, services,
* indexes, and access and data bases can be managed.
* <p>
* Realiza operaciones de inicialización del ambiente necesario para
* proporcionar servicios de Portal, a fin de poder administrar usuarios,
* plantillas, flujos de publicación, recursos, servicios, indizado, así
* como de bitácoras de acceso y de base de datos.</p>
*
* @author Javier Solís
* @author Jorge Jiménez
* @version 1.0
*/
public class SWBPortal {
/**
* Holds the names and values for the variables declared in
* {@literal web.properties} file.
* <p>
* Almacena los nombres y valores de las variables declaradas en el archivo
* {@literal web.properties}.</p>
*/
private static Properties props = null;
/**
* Holds the names and values for the variables declared in
* {@literal security.properties} file.
* <p>
* Almacena los nombres y valores de las variables declaradas en el archivo
* {@literal security.properties}.</p>
*/
private static Properties secProps = null;
/**
* Stores the context path's value configured for this portal instance.
* <p>
* Almacena el valor de la ruta de contexto configurada para esta instancia
* de portal.</p>
*/
private String contextPath = "/";
/**
* Stores the work directory's web path value
* <p>
* Almacena el valor de la ruta web del directorio de trabajo</p>.
*/
private static String webWorkPath = "";
/**
* The WORKPAT h_ relative.
*/
public static String WORKPATH_RELATIVE = "relative";
/**
* The WORKPAT h_ absolute.
*/
public static String WORKPATH_ABSOLUTE = "absolute";
/**
* The WORKPAT h_ remote.
*/
public static String WORKPATH_REMOTE = "remote";
/**
* Stores the work directory's path.
* <p>
* Almacena la ruta del directorio de trabajo.</p>
*/
private static String workPath = "";
/**
* Store the work path type Almcaena el tipo de ruta de trabajo.
*/
private static String workPathType = WORKPATH_RELATIVE;
/**
* Holds a reference to the {@code ServletContext} used by this web
* application.
* <p>
* Mantiene una referencia hacia el objeto {@code ServletContext} utilizado
* por esta aplicación.</p>
*/
private static ServletContext servletContext = null;
/**
* Holds a reference to the {@code Filter} used by this web application.
* <p>
* Mantiene una referencia hacia el objeto {@code Filter} utilizado por esta
* aplicación.</p>
*/
private static Filter virtualHostFilter = null;
/**
* Indicates whether this instance of portal has an existing database
* related to it.
* <p>
* Indica si esta instancia de portal tiene relacionada una base de datos
* existente.</p>
*/
private static boolean haveDB = false;
/**
* Indicates whether the database related to this portal instance has the
* necessary tables to work with.
* <p>
* Indica si la base de datos relacionada a esta instancia de portal tiene
* las tablas necesarias para trabajar.</p>
*/
private static boolean haveDBTables = false;
/**
* Indicates whether or not to use a database.
* <p>
* Indica si usar o no una base de datos.</p>
*/
private static boolean useDB = true;
/**
* Indicates if this portal instance is client of another one.
* <p>
* Indica si esta instancia de portal es o no cliente de otra.</p>
*/
private static boolean client = false;
/**
* Indicates if this portal instance is stand alone.
* <p>
* Indica si esta instancia de portal esta sola (no en balanceo).</p>
*/
private static boolean standalone = true;
/**
* Creates the messages to the log files.
* <p>
* Crea los mensajes hacia los archivos de bitácora.</p>
*/
private static Logger log = SWBUtils.getLogger(SWBPortal.class);
/**
* Holds the only one instance of this object in the application.
* <p>
* Mantiene la única instancia de este objeto en la
* aplicación</p>
*/
private static SWBPortal instance = null;
/**
* Contains all the anchors found in the HTML code analized.
* <p>
* Contiene todas las anclas encontradas en el código HTML
* analizado.</p>
*/
private static HashMap hAnchors = null;
/**
* Contains the names and content of all files within SWBAdmin.jar and
* dojo.jar files.
* <p>
* Contiene los nombres y el contenido de todos los archivos dentro de los
* archivos SWBAdmin.jar y dojo.jar.</p>
*/
private static ConcurrentHashMap admFiles = null;
/**
* Is the manager for the user objects in this portal.
* <p>
* Es el administrador de los objetos de usuarios en este portal.</p>
*/
private static SWBUserMgr usrMgr;
/**
* Is the manager for the publication flows in this portal.
* <p>
* Es el administrador de los flujos de publicación en este
* portal.</p>
*/
private static PFlowManager pflowMgr;
/**
* Is the monitor in this portal.
* <p>
* Es el monitor en este portal.</p>
*/
private static SWBMonitor monitor = null;
/**
* Is the manager for the resource objects in this portal.
* <p>
* Es el administrador de los objetos de recursos en este portal.</p>
*/
private static SWBResourceMgr resmgr = null;
/**
* Is the manager for the template objects in this portal.
* <p>
* Es el administrador de los objetos de plantillas en este portal.</p>
*/
private static SWBTemplateMgr templatemgr = null;
/**
* Is the manager for the service objects in this portal.
* <p>
* Es el administrador de los objetos de servicios en este portal.</p>
*/
private static SWBServiceMgr servicemgr = null;
/**
* Is the manager for the admin filters.
* <p>
* Es el administrador de los filtros de administracion.</p>
*/
private static SWBAdminFilterMgr adminfiltermgr = null;
/**
* Is the manager for the database log objects in this portal.
* <p>
* Es el administrador de los objetos de bitácoras de base de datos
* en este portal.</p>
*/
private static SWBDBAdmLog admlog = null;
/**
* Is the message center in this portal.
* <p>
* Es el centro de mensajes en este portal.</p>
*/
private static SWBMessageCenter msgcenter = null;
/**
* The procesor.
*/
private static SWBMessageProcesor procesor = null;
/**
* Is the manager for the access logs in this portal.
* <p>
* Es el administrador de las bitácoras de acceso en este portal.</p>
*/
private static SWBAccessLog acclog = null;
/**
* Is the manager for the access increment object in this portal.
* <p>
* Es el administrador del incremento de accesos a objetos en este
* portal.</p>
*/
private static SWBAccessIncrement accInc = null;
/**
* Is the manager for the index objects in this portal.
* <p>
* Es el administrador de los objetos de indizado en este portal.</p>
*/
private static SWBIndexMgr indmgr = null;
/**
* GeoIp Service Interface
*/
private static com.maxmind.geoip.LookupService geoip = null;
/**
* Link to AWS Services
*/
private static SWBCloud cloudServices = null;
/**
* Creates an object of this class, calling method {@code createInstance(ServletContext, Filter) with.
*
* @param servletContext the {@code ServletContex} agregated to the new instance
*
* @return SWBPortal the new instance of this component
* {@code Filter}'s value equal to {@code null}.
* <p>
* Crea un objeto de esta clase, llamando al método {@code createInstance(ServletContext, Filter)
* con el valor de {@code Filter} igual a {@code null}.</p>
*/
static public synchronized SWBPortal createInstance(ServletContext servletContext) {
return createInstance(servletContext, null);
}
/**
* Creates an object of this class with the {@code ServletContext} and
* {@code Filter} indicated.
* <p>
* Crea un objeto de esta clase con el {@code ServletContext} y
* {@code Filter} indicados.</p>
*
* @param servletContext the {@code ServletContex} agregated to the new
* instance
* @param filter the {@code Filter} assigned to the new instance's virtual
* host filter
* @return SWBPortal the new instance of this component
*/
static public synchronized SWBPortal createInstance(ServletContext servletContext, Filter filter) {
if (instance == null) {
SWBPortal.virtualHostFilter = filter;
instance = new SWBPortal();
SWBPortal.servletContext = servletContext;
String dbfile = SWBUtils.getApplicationPath() + "/swbadmin/geoip/GeoIP.dat";
try {
SWBPortal.geoip = new com.maxmind.geoip.LookupService(dbfile, com.maxmind.geoip.LookupService.GEOIP_MEMORY_CACHE);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
SWBPortal.geoip.close();
}
});
} catch (IOException ioe) {
log.warn("can't find GeoIP.dat file", ioe);
SWBPortal.geoip = null;
}
}
return instance;
}
/**
* Constructor that initializes the environment of its new instance by
* calling method {@code init()}
* <p>
* Constructor que inicia el ambiente de su nueva instancia llamando al
* método {@code init()}</p>.
*/
private SWBPortal() {
log.event("Initializing SemanticWebBuilder Portal...");
init();
}
/**
* Prepares the environment necessary to provide site and content management
* services. This involves the following operations:<ul>
* <li>configuring the values for workpath and SMTPServer environment
* variables, and some other variables from SWBPlatform</li>
* <li>verifing the existence of the database and its tables</li>
* <li>loading of classes indicated in startup.properties file</li>
* <li>executing method {@code loadSemanticModels}</li>
* <li>creating the administration site, if it does not exist yet</li>
* <li>creating the onthology editor site, if it does not exist yet</li>
* <li>creating the administration user repository, if it does not exist
* yet</li>
* <li>creating the global site, if it does not exist yet</li>
* <li>creating the default user repository, if it does not exist yet</li>
* <li>creating the log tables</li>
* <li>initializing the objects: {@code SWBUserMgr}, {@code SWBMonitor},
* {@code SWBResourceMgr}, {@code PFlowManager}, {@code SWBTemplateMgr},
* {@code SWBServiceMgr}, {@code SWBDBAdmLog}, {@code SWBMessageCenter},
* {@code SWBAccessLog}, {@code SWBAccessIncrement} and {@code SWBIndexMgr},
* wich can be accesed directly from this class, and {@code RuleMgr}</li>
* <li>loading of files in SWBAdmin.jar and dojo.jar</li>
* </ul>
* <p>
* Prepara el ambiente necesario para proveer servicios de
* administración de sitios y contenido. Esto involucra las
* siguientes operaciones: <ul>
*
* <li>configurar valores de variables de ambiente de SWBPortal y
* {@link SWBPlatform} como: la ruta del directorio de trabajo o el dominio
* de servidor SMTP</li>
* <li>verificar la existencia de una base de datos y sus tablas</li>
* <li>cargar las clases indicadas en el archivo startup.properties</li>
* <li>executar el método {@code loadSemanticModels}</li>
* <li>crear el sitio de administración, si aún no existe</li>
* <li>crear el sitio de edición de ontologías, si aún
* no existe</li>
* <li>crear el repositorio de usuarios del sitio de administración,
* si aún no existe</li>
* <li>crear el sitio global, si aún no existe</li>
* <li>crear el repositorio de usuarios por defecto, si aún no
* existe</li>
* <li>crear las tablas de base de datos para la bitácora</li>
* <li>inicializar los objetos: {@code SWBUserMgr}, {@code SWBMonitor},
* {@code SWBResourceMgr}, {@code PFlowManager}, {@code SWBTemplateMgr},
* {@code SWBServiceMgr}, {@code SWBDBAdmLog}, {@code SWBMessageCenter},
* {@code SWBAccessLog}, {@code SWBAccessIncrement} y {@code SWBIndexMgr},
* que se pueden acceder directamente de esta clase, y {@code RuleMgr}</li>
* <li>cargar los archivos contenidos en SWBAdmin.jar y dojo.jar</li>
* </ul>
* </p>
*/
private void init() {
props = SWBUtils.TEXT.getPropertyFile("/web.properties");
try {
secProps = SWBUtils.TEXT.getPropertyFile("/security.properties");
} catch (NullPointerException npe) {
secProps = null;
}
workPath = getEnv("swb/workPath");
SWBUtils.EMAIL.setSMTPSsl(Boolean.parseBoolean(getEnv("swb/smtpSsl", "false")));
SWBUtils.EMAIL.setSMTPServer(getEnv("swb/smtpServer"));
SWBUtils.EMAIL.setSMTPPort(Integer.parseInt(getEnv("swb/smtpPort", "0")));
SWBUtils.EMAIL.setSMTPTls(Boolean.parseBoolean(getEnv("swb/smtpTls", "false")));
SWBUtils.EMAIL.setSMTPUser(getEnv("swb/smtpUser"));
SWBUtils.EMAIL.setSMTPPassword(getEnv("swb/smtpPassword"));
SWBUtils.EMAIL.setAdminEmail(getEnv("af/adminEmail"));
standalone = getEnv("swb/clientServer", "SASC").equalsIgnoreCase("SASC");
client = !getEnv("swb/clientServer", "SASC").equalsIgnoreCase("Server") && !getEnv("swb/clientServer", "SASC").equalsIgnoreCase("SAS") && !standalone;
try {
//TODO:revisar sincronizacion
//if (confCS.equalsIgnoreCase("Client")) remoteWorkPath = (String) AFUtils.getInstance().getEnv("swb/remoteWorkPath");
workPath = (String) getEnv("swb/workPath", "/work");
if (workPath.startsWith("file:")) {
workPath = (new File(workPath.substring(5))).toString();
workPathType = WORKPATH_ABSOLUTE;
} else if (workPath.startsWith("http://")) {
workPath = (URLEncoder.encode(workPath));
workPathType = WORKPATH_REMOTE;
} else {
workPath = SWBUtils.getApplicationPath() + workPath;
workPathType = WORKPATH_RELATIVE;
}
} catch (Exception e) {
log.error("Can't read the context path...", e);
workPath = "";
}
//Insercion de parametros a Platform
SWBPlatform platform = SWBPlatform.createInstance();
SWBPlatform.setPortalLoaded(true);
platform.setPlatformWorkPath(workPath);
platform.setStatementsCache(getEnv("swb/ts_statementsCache", "false").equals("false"));
String persistType = getEnv("swb/triplepersist", SWBPlatform.PRESIST_TYPE_DEFAULT);
platform.setPersistenceType(persistType);
platform.setAdminDev(getEnv("swb/adminDev", "false").equalsIgnoreCase("true"));
platform.setAdminFile(getEnv("swb/adminFile", "/swbadmin/rdf/SWBAdmin.nt"));
platform.setOntEditFile(getEnv("swb/ontEditFile", "/swbadmin/rdf/SWBOntEdit.nt"));
platform.setProperties(props);
platform.setSecurityProperties(secProps);
try {
SWBUtils.DB.setDefaultPool(getEnv("swb/db/nameconn", getEnv("wb/db/nameconn", "swb")));
Connection con = SWBUtils.DB.getDefaultConnection();
if (con != null) {
log.info("-->Database: " + SWBUtils.DB.getDatabaseName());
if (SWBUtils.DB.getDatabaseName().startsWith("HSQL")) {
checkHSQLHack(con); //MAPS74
}
haveDB = true;
haveDBTables = true;
con.close();
}
if (!haveDB()) {
log.warn("-->Default SemanticWebBuilder database not found...");
return;
}
if (!haveDBTables()) {
log.warn("-->Default SemanticWebBuilder database tables not found...");
return;
}
try {
System.setProperty("sun.net.client.defaultConnectTimeout", getEnv("swb/defaultConnectTimeout", "5000"));
System.setProperty("sun.net.client.defaultReadTimeout", getEnv("swb/defaultReadTimeout", "30000"));
} catch (Exception e) {
log.error("Error seting defaultConnectTimeout, defaultReadTimeout");
}
//TODO: agregar modelos
//semanticMgr.init(this);
// Timestamp initime = null;
// util.log(com.infotec.appfw.util.AFUtils.getLocaleString("locale_core", "log_WBLoader_Init_InstanceConfiguration") + util.getEnv("wb/clientServer"), true);
// cpus = getNumProcessors();
// util.log(com.infotec.appfw.util.AFUtils.getLocaleString("locale_core", "log_WBLoader_Init_ProcessorNumber") + cpus, true);
// util.log("IP:\t\t\t"+java.net.InetAddress.getLocalHost(),true);
//
// try
// {
// UpdateVersion updater = new UpdateVersion(version);
// updater.update();
// } catch (Exception e)
// {
// AFUtils.log(e, com.infotec.appfw.util.AFUtils.getLocaleString("locale_core", "error_WBLoader_Init_versioneerror"), true);
// }
//
if (!"ignore".equals(getEnv("swb/security.auth.login.config", "ignore"))) {
System.setProperty("java.security.auth.login.config", SWBUtils.getApplicationPath() + "/WEB-INF/classes" + getEnv("swb/security.auth.login.config", "/wb_jaas.config"));
log.info("-->Login Config:" + System.getProperty("java.security.auth.login.config"));
}
// String dbsync = util.getEnv("wb/DBSync","false");
// if (wbutil.isClient() || dbsync.trim().equalsIgnoreCase("true"))
// {
// initime = DBDbSync.getInstance().getLastUpdate();
// objs.add(DBDbSync.getInstance());
// }
//
// //if admin
// if (!wbutil.isClient())
// {
// objs.add(DBResHits.getInstance());
// objs.add(DBAdmLog.getInstance());
// objs.add(WBAccessLog.getInstance());
// objs.add(WBIndexMgr.getInstance());
// //objs.add(WBFileReplicatorSrv.getInstance());
// } else
// {
// util.log("remoteWorkPath --> " + wbutil.getRemoteWorkPath(), true);
// }
//
// if (wbutil.isClient() || dbsync.trim().equalsIgnoreCase("true"))
// {
// timer = WBDBSyncTimer.getInstance();
// timer.init();
// objs.add(timer);
// }
//
//
// Runtime.getRuntime().gc();
// util.log(com.infotec.appfw.util.AFUtils.getLocaleString("locale_core", "log_WBLoader_Init_totalMemory") + Runtime.getRuntime().totalMemory(), true);
// util.log(com.infotec.appfw.util.AFUtils.getLocaleString("locale_core", "log_WBLoader_Init_FreeMemory") + "\t\t" + Runtime.getRuntime().freeMemory(), true);
// util.log(com.infotec.appfw.util.AFUtils.getLocaleString("locale_core", "log_WBLoader_Init_MemoryUsed") + "\t\t" + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()), true);
// util.log(com.infotec.appfw.util.AFUtils.getLocaleString("locale_core", "log_WBLoader_Init_MemoryUsedbyWb") + "\t" + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() - inimem), true);
//
// util.log(com.infotec.appfw.util.AFUtils.getLocaleString("locale_core", "log_WBLoader_Init_WbInicializing"), true);
} catch (Throwable e) {
log.error("Error loading SemanticWebBuilder Instance...", e);
}
loadSemanticModels();
loadAdminFiles();
resmgr = new SWBResourceMgr();
try {
WebSite site = SWBContext.getAdminWebSite();
if (site == null) {
log.event("Creating Admin WebSite...");
SWBPlatform.getSemanticMgr().createModel(SWBContext.WEBSITE_ADMIN, "http://www.semanticwb.org/SWBAdmin#");
//MAPS74
SWBPlatform.getSemanticMgr().createKeyPair();
}
// site = SWBContext.getOntEditor();
// if (site == null)
// {
// log.event("Creating Ontology Editor WebSite...");
// SWBPlatform.getSemanticMgr().createModel(SWBContext.WEBSITE_ONTEDITOR, "http://www.semanticwb.org/SWBOntEdit#");
// }
UserRepository urep = SWBContext.getAdminRepository();
if (urep == null) {
File nt=new File(SWBUtils.getApplicationPath()+"/swbadmin/rdf/uradm.nt");
if(nt.exists())
{
log.event("Importing Admin User Repository...");
SemanticModel model=SWBPlatform.getSemanticMgr().createDBModelByRDF(SWBContext.USERREPOSITORY_ADMIN, "http://www.semanticwb.org/uradm#", new FileInputStream(nt), "N-TRIPLE");
urep = SWBContext.getAdminRepository();
}else
{
log.event("Creating Admin User Repository...");
urep = SWBContext.createUserRepository(SWBContext.USERREPOSITORY_ADMIN, "http://www.semanticwb.org/uradm#");
urep.setTitle("Admin User Repository");
urep.setDescription("Admin User Repository");
//MAPS74 - Cambiado a semantic prop
urep.setAuthMethod("FORM");
urep.setLoginContext("swb4TripleStoreModule");
urep.setCallBackHandlerClassName("org.semanticwb.security.auth.SWB4CallbackHandlerLoginPasswordImp");
urep.setUndeleteable(true);
//Create User
User user = urep.createUser();
user.setLogin("admin");
user.setPassword("webbuilder");
user.setEmail("admin@semanticwb.org");
user.setFirstName("Admin");
user.setLanguage("es");
user.setCreated(new Date());
user.setUpdated(new Date());
user.setActive(true);
UserGroup grp1 = urep.createUserGroup("admin");
grp1.setTitle("Administrator", "en");
grp1.setTitle("Administrador", "es");
grp1.setCreated(new Date());
grp1.setUpdated(new Date());
grp1.setCreator(user);
grp1.setModifiedBy(user);
grp1.setUndeleteable(true);
UserGroup grp2 = urep.createUserGroup("su");
grp2.setTitle("Super User", "en");
grp2.setTitle("Super Usuario", "es");
grp2.setCreated(new Date());
grp2.setUpdated(new Date());
grp2.setCreator(user);
grp2.setModifiedBy(user);
grp2.setUndeleteable(true);
grp2.setParent(grp1);
user.addUserGroup(grp1);
}
try {
site = SWBContext.getWebSite("basico");
if (site == null) {
File file = new File(getWorkPath() + "/sitetemplates/basico.zip");
if (file.exists()) {
log.event("Creating Demo WebSite...");
UTIL.InstallZip(file);
}
}
} catch (Exception e) {
log.error(e);
}
}
//Check for GlobalWebSite
site = SWBContext.getGlobalWebSite();
if (site == null) {
File file = new File(getWorkPath() + "/sitetemplates/"+SWBContext.WEBSITE_GLOBAL+".zip");
if (file.exists()) {
log.event("Importing Global WebSite...");
UTIL.InstallZip(file);
site = SWBContext.getGlobalWebSite();
}else
{
log.event("Creating Global WebSite...");
site = SWBContext.createWebSite(SWBContext.WEBSITE_GLOBAL, "http://www.semanticwb.org/wsglobal#");
site.setTitle("Global");
site.setDescription("Global WebSite");
site.setActive(true);
site.setUndeleteable(true);
//Crear lenguajes por defecto
Language lang = site.createLanguage("es");
lang.setTitle("Español", "es");
lang.setTitle("Spanish", "en");
lang = site.createLanguage("en");
lang.setTitle("Ingles", "es");
lang.setTitle("English", "en");
//Create HomePage
// WebPage home = site.createWebPage("home");
// site.setHomePage(home);
// home.setActive(true);
//Create DNS
// Dns dns = site.createDns("localhost");
// dns.setTitle("localhost");
// dns.setDescription("DNS por default", "es");
// dns.setDescription("Default DNS", "en");
// dns.setDefault(true);
// dns.setWebPage(home);
}
}
urep = SWBContext.getDefaultRepository();
if (urep == null) {
log.event("Creating Default User Repository...");
urep = SWBContext.createUserRepository(SWBContext.USERREPOSITORY_DEFAULT, "http://www.semanticwb.org/urswb#");
urep.setTitle("Default UserRepository");
urep.setDescription("Default UserRpository");
//MAPS74 - Cambiado a semantic prop
urep.setAuthMethod("FORM");
urep.setLoginContext("swb4TripleStoreModule");
urep.setCallBackHandlerClassName("org.semanticwb.security.auth.SWB4CallbackHandlerLoginPasswordImp");
site.setUserRepository(urep);
}
} catch (Exception e) {
e.printStackTrace();
}
//Crear tablas LOGS
try {
Connection con = SWBUtils.DB.getDefaultConnection();
try {
ResultSet rs = con.getMetaData().getTables(null, null, "%", null);
boolean hasTable = false;
while (rs.next()) {
if (rs.getString(3).toLowerCase().indexOf("swb_admlog") > -1) {
hasTable = true;
}
}
if (!hasTable) {
log.event("Creating Logs Tables... " + SWBUtils.DB.getDatabaseName());
GenericDB db = new GenericDB();
String xml = SWBUtils.IO.getFileFromPath(SWBUtils.getApplicationPath() + "/WEB-INF/xml/swb_logs.xml");
db.executeSQLScript(xml, SWBUtils.DB.getDatabaseName(), null);
}
rs.close();
} catch (SQLException e) {
log.error(e);
}
con.close();
} catch (SQLException e) {
log.error(e);
}
usrMgr = new SWBUserMgr();
usrMgr.init();
monitor = new SWBMonitor();
monitor.init();
resmgr.init();
pflowMgr = new PFlowManager();
pflowMgr.init();
templatemgr = new SWBTemplateMgr();
templatemgr.init();
admlog = new SWBDBAdmLog();
admlog.init();
msgcenter = new SWBMessageCenter();
msgcenter.init();
platform.setMessageCenter(msgcenter);
procesor = new SWBMessageProcesor(msgcenter);
procesor.init();
acclog = new SWBAccessLog();
acclog.init();
accInc = new SWBAccessIncrement();
accInc.init();
adminfiltermgr = new SWBAdminFilterMgr();
adminfiltermgr.init();
servicemgr = new SWBServiceMgr();
servicemgr.init();
indmgr = new SWBIndexMgr();
indmgr.init();
log.event("Loading Friendly Urls...");
FriendlyURL.refresh();
//Inicializa el RuleMgr
Rule.getRuleMgr();
if (!"ignore".equals(getEnv("swb/cloudImplementation", "ignore"))) {
String cloudClass = getEnv("swb/cloudImplementation");
try {
Class clazz = Class.forName(cloudClass);
cloudServices = (SWBCloud) clazz.newInstance();
new Thread() {
public void run() {
cloudServices.launch();
}
}.start();
log.event("CloudServices enabled...");
} catch (Exception roe) { //catching Reflection and Thread Exceptions
log.event("Can't instantiate cloud services", roe);
assert false;
}
}
try {
//cargando clases de startup.properties
SWBStartup startup = new SWBStartup(new ArrayList()); //objs);
startup.load("startup.properties");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Load admin files.
*/
public void loadAdminFiles() {
log.event("Loading Admin Files...");
admFiles = new ConcurrentHashMap();
try {
log.debug("Loading admin Files from: /WEB-INF/lib/SWBAdmin.jar");
String zipPath = SWBUtils.getApplicationPath() + "/WEB-INF/lib/SWBAdmin.jar";
ZipFile zf = new ZipFile(zipPath);
Enumeration e = zf.entries();
while (e.hasMoreElements()) {
ZipEntry ze = (ZipEntry) e.nextElement();
log.debug("/" + ze.getName() + ", " + ze.getSize() + ", " + ze.getTime());
admFiles.put("/" + ze.getName(), new JarFile(ze, zf));
}
zf.close();
//log.event("-->Admin Files in Memory:\t" + admFiles.size());
} catch (Exception e) {
log.warn("Error loading files for Webbuilder Administration:" + SWBUtils.getApplicationPath() + "/WEB-INF/lib/SWBAdmin.jar", e);
}
try {
log.debug("Loading admin Files from: /WEB-INF/lib/dojo.zip");
String zipPath = SWBUtils.getApplicationPath() + "/WEB-INF/lib/dojo.zip";
ZipFile zf = new ZipFile(zipPath);
Enumeration e = zf.entries();
while (e.hasMoreElements()) {
ZipEntry ze = (ZipEntry) e.nextElement();
log.debug("/" + ze.getName() + ", " + ze.getSize() + ", " + ze.getTime());
admFiles.put("/" + ze.getName(), new JarFile(ze, zf));
}
zf.close();
log.event("-->Admin Files in Memory:\t" + admFiles.size());
} catch (Exception e) {
log.warn("Error loading files for Webbuilder Administration:" + SWBUtils.getApplicationPath() + "/WEB-INF/lib/dojo.zip", e);
}
}
/**
* Loads the model discribed by each onthology indicated in
* {@code swb/ontologyFiles} environment variable.
* <p>
* Carga el modelo descrito para cada ontología indicada en
* {@code swb/ontologyFiles}.</p>
*/
public void loadSemanticModels() {
log.event("Loading SemanticModels...");
String owlPath = getEnv("swb/ontologyFiles", "/WEB-INF/owl/swb.owl");
SWBPlatform.getSemanticMgr().initializeDB();
//Load Ontology from file
StringTokenizer st = new StringTokenizer(owlPath, ",;");
while (st.hasMoreTokens()) {
String file = st.nextToken();
String swbowl = "file:" + SWBUtils.getApplicationPath() + file;
log.info("Loading OWL:" + swbowl);
SemanticModel model = SWBPlatform.getSemanticMgr().addBaseOntology(swbowl);
}
SWBPlatform.getSemanticMgr().loadBaseVocabulary();
//System.out.println("End Vocabulary");
// ontoModel.loadImports();
// ontoModel.getDocumentManager().addAltEntry(source,"file:"+SWBUtils.getApplicationPath()+"/WEB-INF/owl/swb.owl" );
// ontoModel.read(source);
// Reasoner reasoner = ReasonerRegistry.getOWLReasoner();
// reasoner = reasoner.bindSchema(swbSquema);
// InfModel infmodel = ModelFactory.createInfModel(reasoner, adminModel);
//adminModel.createResource("http://www.sep.gob.mx/site/WBAdmin",ontoModel.getResource("http://www.semanticwebbuilder.org/swb4/ontology#WebSite"));
//adminModel.createResource(ontoModel.getResource("http://www.semanticwebbuilder.org/swb4/ontology#WebPage"));
//debugClasses(ontoModel);
//debugModel(ontoModel);
//load SWBSystem Model
// log.debug("Loading DBModel:"+"SWBSystem");
// m_system=new SemanticModel("SWBSystem",loadRDFDBModel("SWBSystem"));
//// debugModel(m_system);
// if(SWBPlatform.isUseDB())m_ontology.addSubModel(m_system,false);
SWBPlatform.getSemanticMgr().loadDBModels();
if (getEnv("swb/addModel_DBPedia", "false").equals("true")) {
SWBPlatform.getSemanticMgr().loadRemoteModel("DBPedia", "http://dbpedia.org/sparql", "http://dbpedia.org/resource/", false);
}
// if(SWBPlatform.getEnv("swb/addOnt_DBPedia","false").equals("true"))
// {
// loadRemoteModel("Books", "http://www.sparql.org/books", "http://example.org/book/",false);
// }
//TODO agregar RDFa
SWBPlatform.getSemanticMgr().rebind();
}
/**
* Gets the context path for this resource's instance. For example:
* {@literal /swb}, or {@literal /} if the context is the root context.
* <p>
* Obtiene la ruta del contexto para esta instancia de portal. <br/>Por
* ejemplo:
*
* @return the string representing the context path for this resource's
* instance. {@literal /swb}, o {@literal /} si es el contexto
* raíz</p>
*/
public static String getContextPath() {
if (instance != null) {
return instance.contextPath;
}
return "";
}
/**
* Sets the value for this portal instance's context path.
* <p>
* Fija el valor de la ruta del contexto de esta instancia de portal</p>
*
* @param contextPath the string representing the new path for the portal
* context. If the string ends with a {@literal /}, the value stored won't
* contain it. This is: <br/>value received {@literal /swb/} -> value stored
* {@literal /swb}
*/
public void setContextPath(String contextPath) {
log.event("ContextPath:" + contextPath);
this.contextPath = contextPath;
try {
if (getEnv("swb/webWorkPath", "/work").startsWith("/")) {
if (contextPath.endsWith("/")) {
webWorkPath = contextPath + getEnv("swb/webWorkPath", "/work").substring(1);
} else {
webWorkPath = contextPath + getEnv("swb/webWorkPath", "/work");
}
} else {
webWorkPath = getEnv("swb/webWorkPath", "/work");
}
} catch (Exception e) {
log.error("Can't read the context path...", e);
webWorkPath = "";
}
SWBPlatform.createInstance().setContextPath(contextPath);
}
/**
* Gets this portal work directory's physical path. For
* example:<br/>/opt/swb/work
* <p>
* Obtiene la ruta física del directorio de trabajo del portal
* Ejemplo: /opt/swb/work</p>
*
* @return a string representing the work directory's physical path
*/
public static String getWorkPath() {
return workPath;
}
/**