My favorites | Sign in
Project Home Downloads Wiki Issues Source
Checkout   Browse   Changes    
 
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
/*******************************************************************************
* Copyright (c) 2010 Stefan A. Tzeggai
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-3.0.html
*
* Contributors:
* Stefan A. Tzeggai - initial API and implementation
******************************************************************************/
package org.geopublishing;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import sun.misc.BASE64Encoder;

public class GsRest {

@Override
public String toString() {
return "GsRest [restUrl=" + restUrl + ", username=" + username + "]";
}

final static Pattern workspaceNameRegEx = Pattern.compile("<workspace>.*?<name>(.*?)</name>.*?</workspace>",
Pattern.DOTALL);
final static Pattern datastoreNameRegEx = Pattern.compile("<dataStore>.*?<name>(.*?)</name>.*?</dataStore>",
Pattern.DOTALL);
final static Pattern coverageNameRegEx = Pattern.compile("<coverage>.*?<name>(.*?)</name>.*?</coverage>",
Pattern.DOTALL);
final static Pattern coverageStoreNameRegEx = Pattern.compile(
"<coverageStore>.*?<name>(.*?)</name>.*?</coverageStore>", Pattern.DOTALL);
static final Pattern featuretypesNameRegEx = Pattern.compile("<featureType>.*?<name>(.*?)</name>.*?</featureType>",
Pattern.DOTALL + Pattern.MULTILINE);
final static Pattern layerNamesRegExPattern = Pattern.compile("<layer>.*?<name>(.*?)</name>.*?</layer>",
Pattern.DOTALL + Pattern.MULTILINE);
final static Pattern coverageNamesRegExPattern = Pattern.compile("<coverage>.*?<name>(.*?)</name>.*?</coverage>",
Pattern.DOTALL + Pattern.MULTILINE);
/**
* <code>
<styles>
<style>
<name>point</name>
<atom:link rel="alternate" href="http://localhost:8085/geoserver/rest/styles/point.xml" type="application/xml"/>
</style>
<style>
<name>line</name>
<atom:link rel="alternate" href="http://localhost:8085/geoserver/rest/styles/line.xml" type="application/xml"/>
</style>
...
</styles>
</code>
*/
static final Pattern stylesNameRegEx = Pattern.compile("<style>.*?<name>(.*?)</name>.*?</style>", Pattern.DOTALL
+ Pattern.MULTILINE);

public final String METHOD_DELETE = "DELETE";
public final String METHOD_GET = "GET";
public final String METHOD_POST = "POST";

public final String METHOD_PUT = "PUT";

private String password;

private String restUrl;

private String username;

/**
* Creates a {@link GsRest} instance to work on a Geoserver that allows anonymous read- and write access.
*
* @param gsBaseUrl
* The base URL of Geoserver. Usually ending with "../geoserver"
*/
public GsRest(String gsBaseUrl) {

if (!gsBaseUrl.endsWith("rest")) {
if (!gsBaseUrl.endsWith("/"))
gsBaseUrl += "/";
this.restUrl = gsBaseUrl + "rest";
}

this.username = null;
this.password = null;
}

/**
* Creates a {@link GsRest} instance to work on a Geoserver which needs authorization (default in 2.0.2).
*
* @param gsBaseUrl
* The base URL of Geoserver. Usually ending with "../geoserver"
* @param username
* plain text username
* @param password
* plain text password
*/
public GsRest(String gsBaseUrl, String username, String password) {

if (gsBaseUrl != null && !gsBaseUrl.endsWith("/"))
gsBaseUrl += "/";

this.restUrl = gsBaseUrl + "rest";
this.username = username;
this.password = password;
}

/**
* This method does not upload a shapefile via zip. It rather creates a reference to a Shapefile that has already
* exists in the GS data directory. <br/>
*
* TODO: This is buggy and always puts the coveragestore in the default workspace. Therefore we set the default
* workspace defore every command, and reset it afterwards. This will change the default workspace for a moment!
*
* @param relpath
* A path to the file, relative to gsdata dir, e.g. "file:data/water.shp"
*/
public boolean createCoverageGeoTiff(String wsName, String csName, String csNamespace, String relpath,
Configure autoConfig) throws IOException {

String oldDefault = getDefaultWs();

try {
setDefaultWs(wsName);

if (relpath == null)
throw new IllegalArgumentException("parameter relpath may not be null");

if (autoConfig == null)
autoConfig = Configure.first;

String urlParamter = "<url>" + relpath + "</url>";

// String namespaceParamter = "<entry key=\"namespace\">" + dsName
// + "</entry>";

String typeParamter = "<type>GeoTIFF</type>";

String xml = "<coverageStore><name>" + csName + "</name><enabled>true</enabled>" + typeParamter
+ urlParamter + "</coverageStore>";

int returnCode = sendRESTint(METHOD_POST, "/workspaces/" + wsName + "/coveragestores?configure="
+ autoConfig.toString(), xml);
return 201 == returnCode;
} catch (IOException e) {
setDefaultWs(oldDefault);
throw e;
} finally {
reload();
}

}

public boolean setDefaultWs(String wsName) throws IOException {
String xml = "<workspace><name>" + wsName + "</name></workspace>";

return 200 == sendRESTint(METHOD_PUT, "/workspaces/default.xml", xml);
}

/**
* Returns the name of the default workspace
*
* @throws IOException
*/
public String getDefaultWs() throws IOException {
String xml = sendRESTstring(METHOD_GET, "/workspaces/default", null);
List<String> workspaces = parseXmlWithregEx(xml, workspaceNameRegEx);
return workspaces.get(0);
}

public boolean createDatastorePg(String workspace, String dsName, String dsNamespace, String host, String port,
String db, String user, String pwd, boolean exposePKs) throws IOException {

String dbType = "postgis";

return createDbDatastore(workspace, dsName, dsNamespace, host, port, db, user, pwd, dbType, exposePKs);
}

public boolean createDatastoreShapefile(String workspace, String dsName, String dsNamespace, String relpath,
String chartset) throws IOException {

return createDatastoreShapefile(workspace, dsName, dsNamespace, relpath, chartset, null, null, null);
}

/**
* − <dataStore> <name>xxx</name> <description>xxx</description> <type>Shapefile</type> <enabled>true</enabled> −
* <workspace> <name>ws</name> <atom:link rel="alternate"
* href="http://localhost:8085/geoserver/rest/workspaces/ws.xml" type="application/xml"/> </workspace> −
* <connectionParameters> <entry key="memory mapped buffer">true</entry> <entry
* key="create spatial index">true</entry> <entry key="charset">ISO-8859-1</entry> <entry
* key="url">file:data/ad2/soils.shp</entry> <entry key="namespace">http://ws</entry> </connectionParameters> −
* <featureTypes> <atom:link rel="alternate" href=
* "http://localhost:8085/geoserver/rest/workspaces/ws/datastores/xxx/featuretypes.xml" type="application/xml"/>
* </featureTypes> </dataStore>
*/
/**
* This method does not upload a shapefile via zip. It rather creates a reference to a Shapefile that has already
* exists in the GS data directory.
*
* @param charset
* defaults to UTF-8 if not set. Charset, that any text content is stored in.
*
* @param relpath
* A path to the file, relative to gsdata dir, e.g. "file:data/water.shp"
*/
public boolean createDatastoreShapefile(String workspace, String dsName, String dsNamespace, String relpath,
String charset, Boolean memoryMappedBuffer, Boolean createSpatialIndex, Configure autoConfig)
throws IOException {

if (autoConfig == Configure.first)
autoConfig = null;

if (relpath == null)
throw new IllegalArgumentException("parameter relpath may not be null");

String createSpatialIndexParam = RestUtil.entryKey("create spatial index", createSpatialIndex);

String memoryMappedBufferParamter = RestUtil.entryKey("memory mapped buffer", memoryMappedBuffer);

String charsetParamter = "<entry key=\"charset\">" + (charset == null ? "UTF-8" : charset) + "</entry>";

String urlParamter = "<entry key=\"url\">" + relpath + "</entry>";

String namespaceParamter = "<entry key=\"namespace\">" + dsName + "</entry>";

String typeParamter = "<type>Shapefile</type>";

String xml = "<dataStore><name>" + dsName + "</name><enabled>true</enabled>" + typeParamter
+ "<connectionParameters>" + createSpatialIndexParam + memoryMappedBufferParamter + charsetParamter
+ urlParamter + namespaceParamter + typeParamter + "</connectionParameters></dataStore>";

String configureParam = autoConfig == null ? "" : "?configure=" + autoConfig.toString();

int returnCode = sendRESTint(METHOD_POST, "/workspaces/" + workspace + "/datastores.xml" + configureParam, xml);
return 201 == returnCode;
}

public boolean createDbDatastore(String workspace, String dsName, String dsNamespace, String host, String port,
String db, String user, String pwd, String dbType, boolean exposePKs) throws IOException {

String exposePKsParamter = "<entry key=\"Expose primary keys\">" + exposePKs + "</entry>";

String xml = "<dataStore><name>" + dsName + "</name><enabled>true</enabled><connectionParameters><host>" + host
+ "</host><port>" + port + "</port><database>" + db + "</database><user>" + user + "</user><passwd>"
+ pwd + "</passwd><dbtype>" + dbType + "</dbtype><namespace>" + dsNamespace + "</namespace>"
+ exposePKsParamter + "</connectionParameters></dataStore>";

int returnCode = sendRESTint(METHOD_POST, "/workspaces/" + workspace + "/datastores", xml);
return 201 == returnCode;
}

// /**
// * Create a link between a PostGIS table and the given GeoServer datastore.<br/>
// *
// * Works: <code>curl -u admin:geoserver -v -XPOST -H 'Content-type:text/xml'</code>
// *
// * @param wsName
// * the GeoServer workspace name
// * @param dsName
// * the GeoServer datastore name
// * @param postGISTableName
// * the name of the PostGIS table to associate
// * @return <code>true</code> if uploaded, false otherwise
// * @throws IOException
// *
// * @author Eric Grosso, 10.5.2011
// */
// public boolean createfeatureTypePg(String wsName, String dsName, String postGISTableName) throws IOException {
//
// String xml = "<featureType><name>" + postGISTableName + "</name></featureType>";
//
// int sendRESTint = sendRESTint(METHOD_POST, "/workspaces/" + wsName + "/datastores/" + dsName + "/featuretypes",
// xml, "text/xml", null);
//
// return 201 == sendRESTint;
// }

/**
* Create a <em>Featuretype</em> based on an existing datastore.
*
* @param wsName
* the GeoServer workspace name
* @param dsName
* the GeoServer datastore name
* @param ftName
* the featureTypeName you want to create, e.g. the name of a PostGIS table or the name of a Shapefile
* (without .shp)
* @param srs
* <code>null</code> or <code>EPSG:????</code> syntax.
* @param nativeWKT
* <code>null</code> or WKT declaration of the CRS.
*
* @return <code>true</code> if the creation was successful.
*
* @throws IOException
*/
public boolean createFeatureType(String wsName, String dsName, String ftName, String srs, String nativeWKT)
throws IOException {

// "<entry key=\"namespace\"><name>" + dsName
// + "</name></entry>";

String nameTitleParam = "<name>" + ftName + "</name><title>" + ftName + "</title>";

String enabledTag = "<enabled>" + true + "</enabled>";

String srsTag = srs != null ? "<srs>" + srs + "</srs>" : "";

String nativeCrsTag = nativeWKT != null ? "<nativeCRS>" + nativeWKT + "</nativeCRS>" : "";

String prjPolTag = "<projectionPolicy>FORCE_DECLARED</projectionPolicy>";

String xml = "<featureType>" + nameTitleParam + srsTag + prjPolTag + enabledTag + nativeCrsTag
+ "</featureType>";

int sendRESTint = sendRESTint(METHOD_POST, "/workspaces/" + wsName + "/datastores/" + dsName + "/featuretypes",
xml);
return 201 == sendRESTint;
}

/**
* Uploads an SLD to the Geoserver
*
* @param stylename
* @param sldString
* SLD-XML as String
* @return <code>true</code> successfully uploaded
*/
public boolean createSld(String stylename, String sldString) throws IOException {

return null != createSld_location(stylename, sldString);
}

/**
* Add an existing style to a layer.
*
* @param styleName
* name of the stlye to associate with the layer.
* @param layername
* name of the layer to associate with the style.
* @return <code>true</code> for operation success.
* @throws java.io.IOException
* @see #createSld
*/
public boolean addStyleToLayer(String styleName, String layername) throws IOException {
return addStyleToLayer(styleName, layername, false);
}

/**
* Add an existing style to a layer.
*
* @param styleName
* name of the stlye to associate with the layer.
* @param layername
* name of the layer to associate with the style.
* @param asDefault
* Set <code>true</code> if this shall be setup as a default style
* @return <code>true</code> for operation success.
* @throws java.io.IOException
* @see #createSld
*/
public boolean addStyleToLayer(String styleName, String layername, Boolean asDefault) throws IOException {
String xml = "<style><name>" + styleName + "</name></style>";
int result = sendRESTint(METHOD_POST, "/layers/" + layername + "/styles.xml", xml);
if (result != 201)
return false;

if (asDefault) {
xml = "<layer><defaultStyle><name>" + styleName + "</name></defaultStyle><enabled>true</enabled></layer>";
return 200 == sendRESTint(METHOD_PUT, "/layers/" + layername, xml);
}
return true;
}

public List<String> getStylesForLayer(String layername) throws IOException {
String xml = sendRESTstring(METHOD_GET, "/layers/" + layername + "/styles", null);
return parseXmlWithregEx(xml, stylesNameRegEx);
}

/**
* @param stylename
* @param sldString
* @return REST location URL string to the new style
* @throws IOException
*/
public String createSld_location(String stylename, String sldString) throws IOException {

String location = sendRESTlocation(METHOD_POST, "/styles/" + "?name=" + stylename, sldString,
"application/vnd.ogc.sld+xml", "application/vnd.ogc.sld+xml");
return location;
}

public boolean createWorkspace(String workspaceName) throws IOException {
return 201 == sendRESTint(METHOD_POST, "/workspaces", "<workspace><name>" + workspaceName
+ "</name></workspace>");
}

/**
* Deletes a datastore
*
* @param wsName
* name of the workspace
* @param dsName
* name of the datastore
* @param recusively
* delete all contained featureytpes also
*/
public boolean deleteDatastore(String wsName, String dsName, boolean recusively) throws IOException {
if (recusively == true) {
List<String> layerNames = getLayersUsingDataStore(wsName, dsName);

for (String lName : layerNames) {
if (!deleteLayer(lName))
throw new RuntimeException("Could not delete layer " + wsName + ":" + dsName + ":" + lName);
}
if (getDatastores(wsName).contains(dsName)) {
List<String> ftNames = getFeatureTypes(wsName, dsName);
for (String ftName : ftNames) {
// it happens that this returns false, e.g maybe for
// notpublished featuretypes!?
deleteFeatureType(wsName, dsName, ftName);
}
}
}
return 200 == sendRESTint(METHOD_DELETE, "/workspaces/" + wsName + "/datastores/" + dsName, null);
}

/**
* Deletes a coveragestore
*
* @param wsName
* name of the workspace
* @param csName
* name of the coveragestore
* @param recusively
* delete all contained coverages also
* @throws IOException
*/
public boolean deleteCoveragestore(String wsName, String csName, boolean recusively) throws IOException {
if (recusively == true) {
deleteLayersUsingCoveragestore(wsName, csName);

List<String> covNames = getCoverages(wsName, csName);
//
for (String ftName : covNames) {
// it happens that this returns false, e.g maybe for
// notpublished featuretypes!?
deleteCoverage(wsName, csName, ftName);
}
}
return 200 == sendRESTint(METHOD_DELETE, "/workspaces/" + wsName + "/coveragestores/" + csName, null);
}

private void deleteLayersUsingCoveragestore(String wsName, String csName) throws IOException {
List<String> layerNames = getLayersUsingCoverageStore(wsName, csName);

for (String lName : layerNames) {
if (!deleteLayer(lName))
throw new RuntimeException("Could not delete layer " + lName);
}
}

public boolean deleteCoverage(String wsName, String csName, String covName) throws IOException {

deleteLayersUsingCoveragestore(wsName, csName);

int result = sendRESTint(METHOD_DELETE, "/workspaces/" + wsName + "/coveragestores/" + csName + "/coverages/"
+ covName, null);

return result == 200;
}

/**
* To avoid
* "org.geoserver.rest.RestletException: java.lang.IllegalArgumentException: Unable to delete resource referenced by layer"
* use deleteLayer first.
*/
public boolean deleteFeatureType(String wsName, String dsName, String ftName) {
try {
return sendRESTint(METHOD_DELETE, "/workspaces/" + wsName + "/datastores/" + dsName + "/featuretypes/"
+ ftName, null) == 200;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

public boolean deleteLayer(String lName) {
try {

int result = sendRESTint(METHOD_DELETE, "/layers/" + lName, null);
return result == 200;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

public boolean deleteSld(String styleName, Boolean... purge_) throws IOException {
Boolean purge = null;
if (purge_.length > 1)
throw new IllegalArgumentException("only one purge paramter allowed");
if (purge_.length == 1) {
purge = purge_[0];
}
if (purge == null)
purge = false;
int result = sendRESTint(METHOD_DELETE, "/styles/" + styleName + ".sld?purge=" + purge.toString(), null);
// + "&name=" + styleName
return result == 200;
}

/**
* Deletes a workspace recursively.
*
* @param wsName
* name of the workspace to delete recursively.
*/
public boolean deleteWorkspace(String wsName) throws IOException {
return deleteWorkspace(wsName, true);
}

/**
* Deletes a workspace recursively. If the workspace could not be deleted (e.g. didn't exist, or not recursively
* deleting and not empty) returns <code>false</code>
*
* @param wsName
* name of the workspace to delete, including all content.
*/
public boolean deleteWorkspace(String wsName, boolean recursive) {

try {

if (recursive) {

reload();

// Selete all datastores
// recusively
List<String> datastores = getDatastores(wsName);
for (String dsName : datastores) {
if (!deleteDatastore(wsName, dsName, true))
throw new IOException("Could not delete dataStore " + dsName + " in workspace " + wsName);
}

// Selete all datastores
// recusively
List<String> coveragestores = getCoveragestores(wsName);
for (String csName : coveragestores) {
if (!deleteCoveragestore(wsName, csName, true))
throw new IOException("Could not delete coverageStore " + csName + " in workspace " + wsName);
}

}

return 200 == sendRESTint(METHOD_DELETE, "/workspaces/" + wsName, null, "application/xml",
"application/xml");
} catch (Exception e) {
e.printStackTrace();
// Workspace didn't exist
return false;
} finally {
try {
reload();
} catch (IOException e) {
e.printStackTrace();
}
}

}

/**
* A list of coveragestores
*/
public List<String> getCoveragestores(String wsName) throws IOException {
try {
String coveragesXml = sendRESTstring(METHOD_GET, "/workspaces/" + wsName + "/coveragestores.xml", null);
List<String> coveragestores = parseXmlWithregEx(coveragesXml, coverageStoreNameRegEx);
return coveragestores;

} catch (Exception e) {
e.printStackTrace();
return new ArrayList<String>();
}
}

/**
* A list of datastorenames
*/
public List<String> getDatastores(String wsName) {
try {

String datastoresXml = sendRESTstring(METHOD_GET, "/workspaces/" + wsName + "/datastores.xml", null);
List<String> datastores = parseXmlWithregEx(datastoresXml, datastoreNameRegEx);
return datastores;
} catch (Exception e) {
e.printStackTrace();
return new ArrayList<String>();
}
}

/**
* A list of all workspaces
*/
public List<String> getWorkspaces() {
try {
String xml = sendRESTstring(METHOD_GET, "/workspaces", null);
List<String> workspaces = parseXmlWithregEx(xml, workspaceNameRegEx);
return workspaces;
} catch (IOException e) {
e.printStackTrace();
return new ArrayList<String>();
}
}

/**
* Tell this instance of {@link GsRest} to not use authorization
*/
public void disableAuthorization() {
this.password = null;
this.username = null;
}

/**
* Tell this {@link GsRest} instance to use authorization
*
* @param username
* cleartext username
* @param password
* cleartext password
*/
public void enableAuthorization(String username, String password) {
this.password = password;
this.username = username;
}

public String getDatastore(String wsName, String dsName) throws MalformedURLException, ProtocolException,
IOException {
return sendRESTstring(METHOD_GET, "/workspaces/" + wsName + "/datastores/" + dsName, null);
}

public String getFeatureType(String wsName, String dsName, String ftName) throws IOException {
return sendRESTstring(METHOD_GET,
"/workspaces/" + wsName + "/datastores/" + dsName + "/featuretypes/" + ftName, null);
}

/**
* Returns a list of all featuretypes inside a a datastore
*
* @param wsName
* @param dsName
* @throws IOException
*/
public List<String> getFeatureTypes(String wsName, String dsName) {
try {

String xml = sendRESTstring(METHOD_GET,
"/workspaces/" + wsName + "/datastores/" + dsName + "/featuretypes", null);

return parseXmlWithregEx(xml, featuretypesNameRegEx);
} catch (Exception e) {
e.printStackTrace();
return new ArrayList<String>();
}

}

/**
* Returns a {@link List} of all layer names
*
* @param wsName
*/
public List<String> getLayerNames() throws IOException {
String xml = sendRESTstring(METHOD_GET, "/layers", null);
return parseXmlWithregEx(xml, layerNamesRegExPattern);
}

/**
* Returns a list of all coverageNames inside a a coveragestore
*/
public List<String> getCoverages(String wsName, String csName) {
try {

String xml = sendRESTstring(METHOD_GET, "/workspaces/" + wsName + "/coveragestores/" + csName
+ "/coverages", null);

return parseXmlWithregEx(xml, coverageNameRegEx);
} catch (Exception e) {
e.printStackTrace();
return new ArrayList<String>();
}

}

/**
* Returns a list of all layers using a specific dataStore
*/

public List<String> getLayersUsingCoverageStore(String wsName, String csName) {
try {

final Pattern pattern = Pattern.compile("<layer>.*?<name>(.*?)</name>.*?/rest/workspaces/" + wsName
+ "/coveragestores/" + csName + "/coverages/.*?</layer>", Pattern.DOTALL + Pattern.MULTILINE);

List<String> coveragesUsingStore = new ArrayList<String>();
for (String cName : getLayerNames()) {
String xml = sendRESTstring(METHOD_GET, "/layers/" + cName, null);
// System.out.println(xml);

Matcher matcher = pattern.matcher(xml);
if (matcher.find())
coveragesUsingStore.add(cName);
}

return coveragesUsingStore;
} catch (Exception e) {
e.printStackTrace();
return new ArrayList<String>();
}
}

/**
* Returns a list of all layers using a specific dataStore
*/
public List<String> getLayersUsingDataStore(String wsName, String dsName) {
try {
final Pattern layersUsingStoreRegEx = Pattern.compile("<layer>.*?<name>(.*?)</name>.*?/rest/workspaces/"
+ wsName + "/datastores/" + dsName + "/featuretypes/.*?</layer>", Pattern.DOTALL
+ Pattern.MULTILINE);

List<String> layersUsingDs = new ArrayList<String>();
for (String lName : getLayerNames()) {
String xml = sendRESTstring(METHOD_GET, "/layers/" + lName, null);
// System.out.println(xml);

Matcher matcher = layersUsingStoreRegEx.matcher(xml);
if (matcher.find())
layersUsingDs.add(lName);
}

return layersUsingDs;
} catch (Exception e) {
e.printStackTrace();
return new ArrayList<String>();
}
}

/**
* @return A list of all stylenames stored in geoserver. Includes "default" stylenames like <code>point</code>,
* <code>line</code>,etc.
*/
public List<String> getStyles() throws IOException {
String xml = sendRESTstring(METHOD_GET, "/styles", null);
return parseXmlWithregEx(xml, stylesNameRegEx);
}

/**
* @return <code>true</code> if authorization is used for requests
*/
public boolean isAuthorization() {
return password != null && username != null;
}

private List<String> parseXmlWithregEx(String xml, Pattern pattern) {
ArrayList<String> list = new ArrayList<String>();

Matcher nameMatcher = pattern.matcher(xml);
while (nameMatcher.find()) {
String name = nameMatcher.group(1);
list.add(name.trim());
}
return list;
}

public boolean purgeSld(String styleName) throws IOException {
return deleteSld(styleName, true);
}

private HttpURLConnection sendREST(String method, String urlAppend, Reader postDataReader, String contentType,
String accept) throws MalformedURLException, IOException {
boolean doOut = !METHOD_DELETE.equals(method) && postDataReader != null;
// boolean doIn = true; // !doOut

String link = restUrl + urlAppend;
URL url = new URL(link);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(doOut);
// uc.setDoInput(false);
if (contentType != null && !"".equals(contentType)) {
connection.setRequestProperty("Content-type", contentType);
connection.setRequestProperty("Content-Type", contentType);
}
if (accept != null && !"".equals(accept)) {
connection.setRequestProperty("Accept", accept);
}

connection.setRequestMethod(method.toString());

if (isAuthorization()) {
String userPasswordEncoded = new BASE64Encoder().encode((username + ":" + password).getBytes());
connection.setRequestProperty("Authorization", "Basic " + userPasswordEncoded);
}

connection.connect();
if (connection.getDoOutput()) {
Writer writer = new OutputStreamWriter(connection.getOutputStream());
char[] buffer = new char[1024];

Reader reader = new BufferedReader(postDataReader);
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}

writer.flush();
writer.close();
}
return connection;
}

private HttpURLConnection sendREST(String method, String urlEncoded, String postData, String contentType,
String accept) throws MalformedURLException, IOException {
StringReader postDataReader = postData == null ? null : new StringReader(postData);
return sendREST(method, urlEncoded, postDataReader, contentType, accept);
}

public int sendRESTint(String method, String url, String xmlPostContent) throws IOException {
return sendRESTint(method, url, xmlPostContent, "application/xml", "application/xml");
}

/**
* @param method
* e.g. 'POST', 'GET', 'PUT' or 'DELETE'
* @param urlEncoded
* e.g. '/workspaces' or '/workspaces.xml'
* @param contentType
* format of postData, e.g. null or 'text/xml'
* @param accept
* format of response, e.g. null or 'text/xml'
* @param postData
* e.g. xml data
* @throws IOException
* @return null, or response of server
*/
public int sendRESTint(String method, String urlEncoded, String postData, String contentType, String accept)
throws IOException {
HttpURLConnection connection = sendREST(method, urlEncoded, postData, contentType, accept);

return connection.getResponseCode();
}

/**
* @param method
* e.g. 'POST', 'GET', 'PUT' or 'DELETE'
* @param urlEncoded
* e.g. '/workspaces' or '/workspaces.xml'
* @param contentType
* format of postData, e.g. null or 'text/xml'
* @param accept
* format of response, e.g. null or 'text/xml'
* @param postData
* e.g. xml data
* @return null, or location field of the response header
*/
public String sendRESTlocation(String method, String urlEncoded, String postData, String contentType, String accept)
throws IOException {
HttpURLConnection connection = sendREST(method, urlEncoded, postData, contentType, accept);

return connection.getHeaderField("Location");
}

/**
* Sends a REST request and return the answer as a String.
*
* @param method
* e.g. 'POST', 'GET', 'PUT' or 'DELETE'
* @param urlEncoded
* e.g. '/workspaces' or '/workspaces.xml'
* @param contentType
* format of postData, e.g. null or 'text/xml'
* @param accept
* format of response, e.g. null or 'text/xml'
* @param is
* where to read the data from
* @throws IOException
* @return null, or response of server
*/
public String sendRESTstring(String method, String urlEncoded, Reader is, String contentType, String accept)
throws IOException {
HttpURLConnection connection = sendREST(method, urlEncoded, is, contentType, accept);

// Read response
InputStream in = connection.getInputStream();
try {

int len;
byte[] buf = new byte[1024];
StringBuffer sbuf = new StringBuffer();
while ((len = in.read(buf)) > 0) {
sbuf.append(new String(buf, 0, len));
}
return sbuf.toString();
} finally {
in.close();
}
}

public String sendRESTstring(String method, String url, String xmlPostContent) throws IOException {
return sendRESTstring(method, url, xmlPostContent, "application/xml", "application/xml");
}

/**
* Sends a REST request and return the answer as a String
*
* @param method
* e.g. 'POST', 'GET', 'PUT' or 'DELETE'
* @param urlEncoded
* e.g. '/workspaces' or '/workspaces.xml'
* @param contentType
* format of postData, e.g. null or 'text/xml'
* @param accept
* format of response, e.g. null or 'text/xml'
* @param postData
* e.g. xml data
* @throws IOException
* @return null, or response of server
*/
public String sendRESTstring(String method, String urlEncoded, String postData, String contentType, String accept)
throws IOException {
HttpURLConnection connection = sendREST(method, urlEncoded, postData, contentType, accept);

// Read response
InputStream in = connection.getInputStream();
try {

int len;
byte[] buf = new byte[1024];
StringBuffer sbuf = new StringBuffer();
while ((len = in.read(buf)) > 0) {
sbuf.append(new String(buf, 0, len));
}
return sbuf.toString();
} finally {
in.close();
}
}

/**
* Works: curl -u admin:geoserver -v -XPUT -H 'Content-type: application/zip' --data-binary
*
* @/home/stefan/Desktop/arabicData.zip http:/
* /localhost:8085/geoserver/rest/workspaces/ws/datastores/test1/file.shp
*/
public String uploadShape(String workspace, String dsName, URL zip) throws IOException {

InputStream os = zip.openStream();
try {
InputStreamReader postDataReader = new InputStreamReader(os);

String returnString = sendRESTstring(METHOD_PUT, "/workspaces/" + workspace + "/datastores/" + dsName
+ "/file.shp", postDataReader, "application/zip", null);

// "?configure=all"
return returnString;
} finally {
os.close();
}
}

/**
* @throws IOException
*/
public boolean createCoverage(String wsName, String csName, String cName) throws IOException {

String xml = "<coverage><name>" + cName + "</name><title>" + cName + "</title></coverage>";

int sendRESTint = sendRESTint(METHOD_POST,
"/workspaces/" + wsName + "/coveragestores/" + csName + "/coverages", xml);

return 201 == sendRESTint;
}

public boolean reload() throws IOException {
return 201 == sendRESTint(METHOD_POST, "/reload", null);
}

}

Change log

r49 by skgoo...@wikisquare.de on May 10, 2011   Diff
* Better documentation of
createFeatureType
* uploadShapefile is now public (not
protected anymore) thanks to Eric Grosso
Go to: 
Project members, sign in to write a code review

Older revisions

r48 by skgoo...@wikisquare.de on Apr 28, 2011   Diff
Thanks to a patch by Wilian F. Costa,
addStyleToLayer() can now also define
the style as the default style.
r47 by skgoo...@wikisquare.de on Feb 8, 2011   Diff
* some GUI tweaking, making buttons
smaller
* added tje GpOptios dialog
r46 by skgoo...@wikisquare.de on Feb 1, 2011   Diff
[No log message]
All revisions of this file

File info

Size: 32786 bytes, 1000 lines
Powered by Google Project Hosting