This repository has been archived by the owner on Nov 22, 2019. It is now read-only.
/
KomodoMetadataService.java
2863 lines (2457 loc) · 128 KB
/
KomodoMetadataService.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
/*
* Copyright Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags and
* the COPYRIGHT.txt file distributed with this work.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.komodo.rest.service;
import java.io.File;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import org.komodo.core.KEngine;
import org.komodo.openshift.BuildStatus;
import org.komodo.openshift.PublishConfiguration;
import org.komodo.openshift.TeiidOpenShiftClient;
import org.komodo.relational.DeployStatus;
import org.komodo.relational.connection.Connection;
import org.komodo.relational.dataservice.Dataservice;
import org.komodo.relational.resource.Driver;
import org.komodo.relational.vdb.Vdb;
import org.komodo.relational.vdb.VdbImport;
import org.komodo.relational.vdb.internal.VdbImpl;
import org.komodo.relational.workspace.WorkspaceManager;
import org.komodo.rest.AuthHandlingFilter.OAuthCredentials;
import org.komodo.rest.CallbackTimeoutException;
import org.komodo.rest.KomodoRestException;
import org.komodo.rest.KomodoRestV1Application.V1Constants;
import org.komodo.rest.KomodoService;
import org.komodo.rest.relational.KomodoProperties;
import org.komodo.rest.relational.RelationalMessages;
import org.komodo.rest.relational.connection.RestConnection;
import org.komodo.rest.relational.json.KomodoJsonMarshaller;
import org.komodo.rest.relational.request.KomodoFileAttributes;
import org.komodo.rest.relational.request.KomodoPathAttribute;
import org.komodo.rest.relational.request.KomodoQueryAttribute;
import org.komodo.rest.relational.request.KomodoSyndesisDataSourceAttributes;
import org.komodo.rest.relational.request.PublishRequestPayload;
import org.komodo.rest.relational.response.KomodoStatusObject;
import org.komodo.rest.relational.response.RestConnectionDriver;
import org.komodo.rest.relational.response.RestQueryResult;
import org.komodo.rest.relational.response.RestSyndesisDataSource;
import org.komodo.rest.relational.response.RestVdb;
import org.komodo.rest.relational.response.RestVdbTranslator;
import org.komodo.rest.relational.response.metadata.RestMetadataConnection;
import org.komodo.rest.relational.response.metadata.RestMetadataStatus;
import org.komodo.rest.relational.response.metadata.RestMetadataTemplate;
import org.komodo.rest.relational.response.metadata.RestMetadataTemplateEntry;
import org.komodo.rest.relational.response.metadata.RestMetadataVdb;
import org.komodo.rest.relational.response.metadata.RestMetadataVdbStatus;
import org.komodo.rest.relational.response.metadata.RestMetadataVdbTranslator;
import org.komodo.rest.relational.response.virtualization.RestVirtualizationStatus;
import org.komodo.spi.KException;
import org.komodo.spi.constants.StringConstants;
import org.komodo.spi.lexicon.vdb.VdbLexicon;
import org.komodo.spi.metadata.MetadataInstance;
import org.komodo.spi.query.QSResult;
import org.komodo.spi.repository.KomodoObject;
import org.komodo.spi.repository.Repository;
import org.komodo.spi.repository.Repository.UnitOfWork;
import org.komodo.spi.repository.Repository.UnitOfWork.State;
import org.komodo.spi.runtime.ConnectionDriver;
import org.komodo.spi.runtime.SyndesisDataSource;
import org.komodo.spi.runtime.TeiidDataSource;
import org.komodo.spi.runtime.TeiidPropertyDefinition;
import org.komodo.spi.runtime.TeiidTranslator;
import org.komodo.spi.runtime.TeiidVdb;
import org.komodo.utils.FileUtils;
import org.komodo.utils.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
/**
* A Komodo REST service for obtaining information from a metadata instance.
*/
@Path( V1Constants.METADATA_SEGMENT )
@Api( tags = {V1Constants.METADATA_SEGMENT} )
public class KomodoMetadataService extends KomodoService {
/**
* Default translator mappings for different drivers
*/
private final static String DRIVER_TRANSLATOR_MAPPING_FILE = "driverTranslatorMappings.xml"; //$NON-NLS-1$
/**
* Default translator mappings for connection URL content
*/
private final static String URLCONTENT_TRANSLATOR_MAPPING_FILE = "urlContentTranslatorMappings.xml"; //$NON-NLS-1$
/**
* Translator mapping file elements and attributes
*/
private final static String ELEM_TRANSLATOR = "translator"; //$NON-NLS-1$
private final static String ATTR_DRIVER = "driver"; //$NON-NLS-1$
private final static String ATTR_URLCONTENT = "urlcontent"; //$NON-NLS-1$
/**
* Unknown translator
*/
private final static String UNKNOWN_TRANSLATOR = "unknown"; //$NON-NLS-1$
/**
* Time to wait after deploying/undeploying an artifact from the metadata instance
*/
private final static int DEPLOYMENT_WAIT_TIME = 10000;
private static final String[] PRIORITY_TEMPLATE_NAMES = {"connection-url", "user-name", "password", "port"};
private static class TeiidPropertyDefinitionComparator implements Comparator<TeiidPropertyDefinition> {
@Override
public int compare(TeiidPropertyDefinition entry1, TeiidPropertyDefinition entry2) {
String entry1Name = null;
boolean entry1Advanced = false;
String entry2Name = null;
boolean entry2Advanced = false;
try {
entry1Name = entry1.getName();
entry1Advanced = entry1.isAdvanced();
entry2Name = entry2.getName();
entry2Advanced = entry2.isAdvanced();
} catch (Exception e) {
// Ignore exception. Will be dealt with below
}
if (entry1Name == null && entry2Name == null)
return 0; // Not a lot
else if (entry1Name == null)
return -1;
else if (entry2Name == null)
return 1;
if (entry1Name.equals(entry2Name))
return 0;
for (String name : PRIORITY_TEMPLATE_NAMES) {
if (name.equals(entry1Name))
return -1;
if (name.equals(entry2Name))
return 1;
}
if (entry1Advanced && !entry2Advanced)
return 1; // De-prioritise advanced
else if (! entry1Advanced && entry2Advanced)
return -1; // De-prioritise advanced
return entry1Name.compareTo(entry2Name);
}
}
/**
* Mapping of driverName to default translator
*/
private Map<String, String> driverTranslatorMap = new HashMap<String,String>();
/**
* Mapping of urlContent to default translator
*/
private Map<String, String> urlContentTranslatorMap = new HashMap<String,String>();
private TeiidOpenShiftClient openshiftClient;
/**
* @param engine
* the Komodo Engine (cannot be <code>null</code> and must be started)
* @param openshiftClient OpenShift client to access service catalog
* @throws WebApplicationException
* if there is a problem obtaining the {@link WorkspaceManager workspace manager}
*/
public KomodoMetadataService(final KEngine engine, TeiidOpenShiftClient openshiftClient) throws WebApplicationException {
super(engine);
// Loads default translator mappings
loadDriverTranslatorMap();
loadUrlContentTranslatorMap();
this.openshiftClient = openshiftClient;
}
private synchronized MetadataInstance getMetadataInstance() throws KException {
return this.kengine.getMetadataInstance();
}
private String getSchema(UnitOfWork uow, String vdbName, String modelName) throws Exception {
MetadataInstance mServer = getMetadataInstance();
return mServer.getSchema(vdbName, "1", modelName);
}
private Response createTimeoutResponse(List<MediaType> mediaTypes) {
Object responseEntity = createErrorResponseEntity(mediaTypes,
RelationalMessages.getString(
RelationalMessages.Error.VDB_SAMPLE_IMPORT_TIMEOUT));
return Response.status(Status.FORBIDDEN).entity(responseEntity).build();
}
private Response checkFileAttributes(KomodoFileAttributes kfa, List<MediaType> mediaTypes) throws Exception {
if (kfa == null || (kfa.getName() == null && kfa.getContent() == null))
return createErrorResponseWithForbidden(mediaTypes, RelationalMessages.Error.METADATA_SERVICE_FILE_ATTRIB_NO_PARAMETERS);
if (kfa.getName() == null)
return createErrorResponseWithForbidden(mediaTypes, RelationalMessages.Error.METADATA_SERVICE_FILE_ATTRIB_NO_NAME);
if (kfa.getContent() == null)
return createErrorResponseWithForbidden(mediaTypes, RelationalMessages.Error.METADATA_SERVICE_FILE_ATTRIB_NO_CONTENT);
return Response.ok().build();
}
private boolean hasDriver(String driverName) throws Exception {
boolean hasDriver = false;
try {
Collection<ConnectionDriver> drivers = getMetadataInstance().getDataSourceDrivers();
for (ConnectionDriver driver : drivers) {
if (driver.getName().startsWith(driverName)) {
hasDriver = true;
break;
}
}
return hasDriver;
} catch (KException ex) {
this.kengine.getErrorHandler().error(ex);
throw ex;
}
}
private boolean hasDynamicVdb(String vdbName) throws Exception {
boolean hasVdb = false;
try {
Collection<TeiidVdb> vdbs = getMetadataInstance().getVdbs();
for (TeiidVdb vdb : vdbs) {
if (vdb.getName().startsWith(vdbName)) {
hasVdb = true;
break;
}
}
return hasVdb;
} catch (KException ex) {
this.kengine.getErrorHandler().error(ex);
throw ex;
}
}
private boolean hasDataSource(String dataSourceName) throws Exception {
boolean hasDataSource = false;
try {
Collection<TeiidDataSource> datasources = getMetadataInstance().getDataSources();
for (TeiidDataSource datasource : datasources) {
if (datasource.getName().startsWith(dataSourceName)) {
hasDataSource = true;
break;
}
}
return hasDataSource;
} catch (KException ex) {
this.kengine.getErrorHandler().error(ex);
throw ex;
}
}
/**
* @param headers
* the request headers (never <code>null</code>)
* @param uriInfo
* the request URI information (never <code>null</code>)
* @return a JSON document representing the status of the local metadata instance (never <code>null</code>)
* @throws KomodoRestException
* if there is a problem constructing the VDBs JSON document
*/
@GET
@Path(V1Constants.STATUS_SEGMENT)
@Produces( MediaType.APPLICATION_JSON )
@ApiOperation(value = "Display the status of the metadata instance",
response = RestMetadataStatus.class)
@ApiResponses(value = {
@ApiResponse(code = 403, message = "An error has occurred.")
})
public Response status(final @Context HttpHeaders headers,
final @Context UriInfo uriInfo) throws KomodoRestException {
SecurityPrincipal principal = checkSecurityContext(headers);
if (principal.hasErrorResponse())
return principal.getErrorResponse();
List<MediaType> mediaTypes = headers.getAcceptableMediaTypes();
try {
MetadataInstance mServer = getMetadataInstance();
RestMetadataStatus status = new RestMetadataStatus(uriInfo.getBaseUri(), mServer);
return commit(mediaTypes, status);
} catch (Throwable e) {
if ( e instanceof KomodoRestException ) {
throw ( KomodoRestException )e;
}
return createErrorResponseWithForbidden(mediaTypes, e, RelationalMessages.Error.METADATA_SERVICE_STATUS_ERROR);
}
}
/**
* @param headers
* the request headers (never <code>null</code>)
* @param uriInfo
* the request URI information (never <code>null</code>)
* @return a JSON document the status of the VDBs in the local teiid server (never <code>null</code>)
* @throws KomodoRestException
* if there is a problem constructing the VDBs JSON document
*/
@GET
@Path(V1Constants.STATUS_SEGMENT + StringConstants.FORWARD_SLASH +
V1Constants.VDBS_SEGMENT)
@Produces( MediaType.APPLICATION_JSON )
@ApiOperation(value = "Display the status of the vdbs of the metadata instance",
response = RestMetadataVdbStatus.class)
@ApiResponses(value = {
@ApiResponse(code = 403, message = "An error has occurred.")
})
public Response vdbs(final @Context HttpHeaders headers,
final @Context UriInfo uriInfo) throws KomodoRestException {
SecurityPrincipal principal = checkSecurityContext(headers);
if (principal.hasErrorResponse())
return principal.getErrorResponse();
List<MediaType> mediaTypes = headers.getAcceptableMediaTypes();
try {
RestMetadataVdbStatus status = new RestMetadataVdbStatus(uriInfo.getBaseUri(), getMetadataInstance());
// create response
return commit(mediaTypes, status);
} catch (Throwable e) {
if ( e instanceof KomodoRestException ) {
throw ( KomodoRestException )e;
}
return createErrorResponseWithForbidden(mediaTypes, e, RelationalMessages.Error.METADATA_SERVICE_VDBS_STATUS_ERROR);
}
}
/**
* @param headers
* the request headers (never <code>null</code>)
* @param uriInfo
* the request URI information (never <code>null</code>)
* @return a JSON document representing all the VDBs deployed to teiid (never <code>null</code>)
* @throws KomodoRestException
* if there is a problem constructing the VDBs JSON document
*/
@GET
@Path(V1Constants.VDBS_SEGMENT)
@Produces( MediaType.APPLICATION_JSON )
@ApiOperation(value = "Display the collection of vdbs",
response = RestVdb[].class)
@ApiResponses(value = {
@ApiResponse(code = 403, message = "An error has occurred.")
})
public Response getVdbs(final @Context HttpHeaders headers,
final @Context UriInfo uriInfo) throws KomodoRestException {
SecurityPrincipal principal = checkSecurityContext(headers);
if (principal.hasErrorResponse())
return principal.getErrorResponse();
List<MediaType> mediaTypes = headers.getAcceptableMediaTypes();
UnitOfWork uow = null;
try {
uow = createTransaction(principal, "convertVdbs", true);
// find VDBs
Collection<TeiidVdb> vdbs = getMetadataInstance().getVdbs();
LOGGER.debug("getVdbs:found '{0}' VDBs", vdbs.size()); //$NON-NLS-1$
final List<RestMetadataVdb> entities = new ArrayList<>();
Repository repo = this.kengine.getDefaultRepository();
for (final TeiidVdb vdb : vdbs) {
RestMetadataVdb entity = entityFactory.createMetadataVdb(uow, repo, vdb, uriInfo.getBaseUri());
entities.add(entity);
LOGGER.debug("getVdbs:VDB '{0}' entity was constructed", vdb.getName()); //$NON-NLS-1$
}
// create response
return commit(uow, mediaTypes, entities);
} catch (CallbackTimeoutException ex) {
return createTimeoutResponse(mediaTypes);
} catch (Throwable e) {
if ((uow != null) && (uow.getState() != State.ROLLED_BACK)) {
uow.rollback();
}
if ( e instanceof KomodoRestException ) {
throw ( KomodoRestException )e;
}
return createErrorResponseWithForbidden(mediaTypes, e, RelationalMessages.Error.METADATA_SERVICE_GET_VDBS_ERROR);
}
}
/**
* Get the specified VDB
* @param headers
* the request headers (never <code>null</code>)
* @param uriInfo
* the request URI information (never <code>null</code>)
* @param vdbName
* the id of the VDB being retrieved (cannot be empty)
* @return the JSON representation of the VDB (never <code>null</code>)
* @throws KomodoRestException
* if there is a problem finding the specified workspace VDB or constructing the JSON representation
*/
@GET
@Path( V1Constants.VDBS_SEGMENT + StringConstants.FORWARD_SLASH +
V1Constants.VDB_PLACEHOLDER )
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML } )
@ApiOperation(value = "Find vdb by name", response = RestMetadataVdb.class)
@ApiResponses(value = {
@ApiResponse(code = 404, message = "No vdb could be found with name"),
@ApiResponse(code = 406, message = "Only JSON or XML is returned by this operation"),
@ApiResponse(code = 403, message = "An error has occurred.")
})
public Response getVdb( final @Context HttpHeaders headers,
final @Context UriInfo uriInfo,
@ApiParam(value = "Id of the vdb to be fetched", required = true)
final @PathParam( "vdbName" ) String vdbName) throws KomodoRestException {
SecurityPrincipal principal = checkSecurityContext(headers);
if (principal.hasErrorResponse())
return principal.getErrorResponse();
List<MediaType> mediaTypes = headers.getAcceptableMediaTypes();
UnitOfWork uow = null;
try {
// find VDB
uow = createTransaction(principal, "getVdb-" + vdbName, true); //$NON-NLS-1$
TeiidVdb vdb = getMetadataInstance().getVdb(vdbName);
if (vdb == null)
return commitNoVdbFound(uow, mediaTypes, vdbName);
Repository repo = this.kengine.getDefaultRepository();
KomodoProperties properties = new KomodoProperties();
properties.addProperty(VDB_EXPORT_XML_PROPERTY, mediaTypes.contains(MediaType.APPLICATION_XML_TYPE));
RestMetadataVdb entity = entityFactory.createMetadataVdb(uow, repo, vdb, uriInfo.getBaseUri());
LOGGER.debug("getVdb:VDB '{0}' entity was constructed", vdb.getName()); //$NON-NLS-1$
return commit(uow, mediaTypes, entity);
} catch (CallbackTimeoutException ex) {
return createTimeoutResponse(mediaTypes);
} catch ( final Throwable e ) {
if ( ( uow != null ) && ( uow.getState() != State.ROLLED_BACK ) ) {
uow.rollback();
}
if ( e instanceof KomodoRestException ) {
throw ( KomodoRestException )e;
}
return createErrorResponseWithForbidden(mediaTypes, e, RelationalMessages.Error.VDB_SERVICE_GET_VDB_ERROR, vdbName);
}
}
/**
* Remove a VDB from the server
* @param headers
* the request headers (never <code>null</code>)
* @param uriInfo
* the request URI information (never <code>null</code>)
* @param vdbName
* the dynamic VDB name (never <code>null</code>)
* @return a JSON representation of the status (never <code>null</code>)
* @throws KomodoRestException
* if there is an error removing the VDB
*/
@DELETE
@Path( V1Constants.VDBS_SEGMENT + StringConstants.FORWARD_SLASH + V1Constants.VDB_PLACEHOLDER )
@Produces( MediaType.APPLICATION_JSON )
@ApiOperation(value = "Removes a Vdb from the teiid server")
@ApiResponses(value = {
@ApiResponse(code = 403, message = "An error has occurred.")
})
public Response removeVdb(final @Context HttpHeaders headers,
final @Context UriInfo uriInfo,
@ApiParam(value = "Name of the VDB to be removed", required = true)
final @PathParam( "vdbName" ) String vdbName) throws KomodoRestException {
SecurityPrincipal principal = checkSecurityContext(headers);
if (principal.hasErrorResponse())
return principal.getErrorResponse();
List<MediaType> mediaTypes = headers.getAcceptableMediaTypes();
if (! isAcceptable(mediaTypes, MediaType.APPLICATION_JSON_TYPE))
return notAcceptableMediaTypesBuilder().build();
UnitOfWork uow = null;
try {
uow = createTransaction(principal, "unDeployTeiidDriver", false); //$NON-NLS-1$
getMetadataInstance().undeployDynamicVdb(vdbName);
// Await the undeployment to end
Thread.sleep(DEPLOYMENT_WAIT_TIME);
String title = RelationalMessages.getString(RelationalMessages.Info.VDB_DEPLOYMENT_STATUS_TITLE);
KomodoStatusObject status = new KomodoStatusObject(title);
if (! hasDynamicVdb(vdbName)) {
status.addAttribute(vdbName,
RelationalMessages.getString(RelationalMessages.Info.VDB_SUCCESSFULLY_UNDEPLOYED));
} else
status.addAttribute(vdbName,
RelationalMessages.getString(RelationalMessages.Info.VDB_UNDEPLOYMENT_REQUEST_SENT));
return commit(uow, mediaTypes, status);
} catch (final Exception e) {
if ((uow != null) && (uow.getState() != State.ROLLED_BACK)) {
uow.rollback();
}
if (e instanceof KomodoRestException) {
throw (KomodoRestException)e;
}
return createErrorResponseWithForbidden(mediaTypes, e, RelationalMessages.Error.METADATA_SERVICE_UNDEPLOY_VDB_ERROR, vdbName);
}
}
/**
* Remove a Connection from the server
* @param headers
* the request headers (never <code>null</code>)
* @param uriInfo
* the request URI information (never <code>null</code>)
* @param connectionName
* the Connection name (never <code>null</code>)
* @return a JSON representation of the status (never <code>null</code>)
* @throws KomodoRestException
* if there is an error removing the Connection
*/
@DELETE
@Path( V1Constants.CONNECTIONS_SEGMENT + StringConstants.FORWARD_SLASH + V1Constants.CONNECTION_PLACEHOLDER )
@Produces( MediaType.APPLICATION_JSON )
@ApiOperation(value = "Removes a Connection from the teiid server")
@ApiResponses(value = {
@ApiResponse(code = 403, message = "An error has occurred.")
})
public Response removeConnection(final @Context HttpHeaders headers,
final @Context UriInfo uriInfo,
@ApiParam(value = "Name of the connection to be removed", required = true)
final @PathParam( "connectionName" ) String connectionName) throws KomodoRestException {
SecurityPrincipal principal = checkSecurityContext(headers);
if (principal.hasErrorResponse())
return principal.getErrorResponse();
List<MediaType> mediaTypes = headers.getAcceptableMediaTypes();
if (! isAcceptable(mediaTypes, MediaType.APPLICATION_JSON_TYPE))
return notAcceptableMediaTypesBuilder().build();
UnitOfWork uow = null;
String title = RelationalMessages.getString(RelationalMessages.Info.CONNECTION_DEPLOYMENT_STATUS_TITLE);
KomodoStatusObject status = new KomodoStatusObject(title);
try {
uow = createTransaction(principal, "removeConnection", false); //$NON-NLS-1$
if (! getMetadataInstance().dataSourceExists(connectionName)) {
status.addAttribute(connectionName,
RelationalMessages.getString(RelationalMessages.Error.METADATA_SERVICE_NO_CONNECTION_FOUND, connectionName));
return commit(uow, mediaTypes, status);
}
getMetadataInstance().deleteDataSource(connectionName);
// Await the undeployment to end
Thread.sleep(DEPLOYMENT_WAIT_TIME);
if (! hasDataSource(connectionName)) {
status.addAttribute(connectionName,
RelationalMessages.getString(RelationalMessages.Info.CONNECTION_SUCCESSFULLY_UNDEPLOYED, connectionName));
} else
status.addAttribute(connectionName,
RelationalMessages.getString(RelationalMessages.Info.CONNECTION_UNDEPLOYMENT_REQUEST_SENT, connectionName));
return commit(uow, mediaTypes, status);
} catch (final Exception e) {
if ((uow != null) && (uow.getState() != State.ROLLED_BACK)) {
uow.rollback();
}
if (e instanceof KomodoRestException) {
throw (KomodoRestException)e;
}
return createErrorResponseWithForbidden(mediaTypes, e, RelationalMessages.Error.METADATA_SERVICE_UNDEPLOY_CONNECTION_ERROR, connectionName);
}
}
/**
* Get the schema for a model in a deployed VDB
* @param headers
* the request headers (never <code>null</code>)
* @param uriInfo
* the request URI information (never <code>null</code>)
* @param vdbName
* the id of the VDB (cannot be empty)
* @param modelName
* the id of the Model (cannot be empty)
* @return the VDB model ddl (never <code>null</code>)
* @throws KomodoRestException
* if there is a problem retrieving the schema
*/
@GET
@Path( V1Constants.VDBS_SEGMENT + StringConstants.FORWARD_SLASH + V1Constants.VDB_PLACEHOLDER + StringConstants.FORWARD_SLASH +
V1Constants.MODELS_SEGMENT + StringConstants.FORWARD_SLASH + V1Constants.MODEL_PLACEHOLDER + StringConstants.FORWARD_SLASH +
V1Constants.SCHEMA_SEGMENT )
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML } )
@ApiOperation(value = "Get schema for a VDB Model")
@ApiResponses(value = {
@ApiResponse(code = 404, message = "No vdb could be found with name"),
@ApiResponse(code = 404, message = "No model could be found with name"),
@ApiResponse(code = 403, message = "An error has occurred.")
})
public Response getVdbModelSchema( final @Context HttpHeaders headers,
final @Context UriInfo uriInfo,
@ApiParam(value = "Name of the vdb", required = true)
final @PathParam( "vdbName" ) String vdbName,
@ApiParam(value = "Name of the model", required = true)
final @PathParam( "modelName" ) String modelName) throws KomodoRestException {
SecurityPrincipal principal = checkSecurityContext(headers);
if (principal.hasErrorResponse())
return principal.getErrorResponse();
List<MediaType> mediaTypes = headers.getAcceptableMediaTypes();
UnitOfWork uow = null;
try {
// Get the model schema
uow = createTransaction(principal, "getModelSchema", true); //$NON-NLS-1$
String schema = getSchema(uow, vdbName, modelName);
KomodoStatusObject kso = new KomodoStatusObject("VdbModelSchema"); //$NON-NLS-1$
kso.addAttribute("schema", schema); //$NON-NLS-1$
return commit(uow, mediaTypes, kso);
} catch (CallbackTimeoutException ex) {
return createTimeoutResponse(mediaTypes);
} catch ( final Throwable e ) {
if ( ( uow != null ) && ( uow.getState() != State.ROLLED_BACK ) ) {
uow.rollback();
}
if ( e instanceof KomodoRestException ) {
throw ( KomodoRestException )e;
}
return createErrorResponseWithForbidden(mediaTypes, e, RelationalMessages.Error.VDB_SERVICE_GET_VDB_ERROR, vdbName);
}
}
/**
* @param headers
* the request headers (never <code>null</code>)
* @param uriInfo
* the request URI information (never <code>null</code>)
* @return a JSON document representing all the translators deployed to teiid (never <code>null</code>)
* @throws KomodoRestException
* if there is a problem constructing the JSON document
*/
@GET
@Path(V1Constants.TRANSLATORS_SEGMENT)
@Produces( MediaType.APPLICATION_JSON )
@ApiOperation(value = "Display the collection of translators",
response = RestVdbTranslator[].class)
@ApiResponses(value = {
@ApiResponse(code = 403, message = "An error has occurred.")
})
public Response getTranslators(final @Context HttpHeaders headers,
final @Context UriInfo uriInfo) throws KomodoRestException {
SecurityPrincipal principal = checkSecurityContext(headers);
if (principal.hasErrorResponse())
return principal.getErrorResponse();
List<MediaType> mediaTypes = headers.getAcceptableMediaTypes();
UnitOfWork uow = null;
try {
Repository repo = this.kengine.getDefaultRepository();
// find translators
uow = createTransaction(principal, "getTranslators", true); //$NON-NLS-1$
Collection<TeiidTranslator> translators = getMetadataInstance().getTranslators();
LOGGER.debug("getTranslators:found '{0}' Translators", translators.size()); //$NON-NLS-1$
final List<RestMetadataVdbTranslator> entities = new ArrayList<>();
for (TeiidTranslator translator : translators) {
RestMetadataVdbTranslator entity = entityFactory.createMetadataTranslator(uow, repo, translator, uriInfo.getBaseUri());
entities.add(entity);
LOGGER.debug("getTranslators:Translator '{0}' entity was constructed", translator.getName()); //$NON-NLS-1$
}
// create response
return commit(uow, mediaTypes, entities);
} catch (CallbackTimeoutException ex) {
return createTimeoutResponse(mediaTypes);
} catch (Throwable e) {
if ((uow != null) && (uow.getState() != State.ROLLED_BACK)) {
uow.rollback();
}
if ( e instanceof KomodoRestException ) {
throw ( KomodoRestException )e;
}
return createErrorResponseWithForbidden(mediaTypes, e, RelationalMessages.Error.METADATA_SERVICE_GET_TRANSLATORS_ERROR);
}
}
/**
* @param headers
* the request headers (never <code>null</code>)
* @param uriInfo
* the request URI information (never <code>null</code>)
* @return a JSON document representing all the connections deployed to teiid (never <code>null</code>)
* @throws KomodoRestException
* if there is a problem constructing the JSON document
*/
@GET
@Path(V1Constants.CONNECTIONS_SEGMENT)
@Produces( MediaType.APPLICATION_JSON )
@ApiOperation(value = "Display the collection of connections",
response = RestConnection[].class)
@ApiResponses(value = {
@ApiResponse(code = 403, message = "An error has occurred.")
})
public Response getConnections(final @Context HttpHeaders headers,
final @Context UriInfo uriInfo) throws KomodoRestException {
SecurityPrincipal principal = checkSecurityContext(headers);
if (principal.hasErrorResponse())
return principal.getErrorResponse();
List<MediaType> mediaTypes = headers.getAcceptableMediaTypes();
UnitOfWork uow = null;
try {
Repository repo = this.kengine.getDefaultRepository();
uow = createTransaction(principal, "getConnections", true); //$NON-NLS-1$
// Get teiid datasources
Collection<TeiidDataSource> dataSources = getMetadataInstance().getDataSources();
LOGGER.debug("getConnections:found '{0}' DataSources", dataSources.size()); //$NON-NLS-1$
final List<RestMetadataConnection> entities = new ArrayList<>();
for (TeiidDataSource dataSource : dataSources) {
RestMetadataConnection entity = entityFactory.createMetadataDataSource(uow, repo, dataSource, uriInfo.getBaseUri());
entities.add(entity);
LOGGER.debug("getConnections:Data Source '{0}' entity was constructed", dataSource.getName()); //$NON-NLS-1$
}
// create response
return commit(uow, mediaTypes, entities);
} catch (CallbackTimeoutException ex) {
return createTimeoutResponse(mediaTypes);
} catch (Throwable e) {
if ((uow != null) && (uow.getState() != State.ROLLED_BACK)) {
uow.rollback();
}
if ( e instanceof KomodoRestException ) {
throw ( KomodoRestException )e;
}
return createErrorResponseWithForbidden(mediaTypes, e, RelationalMessages.Error.METADATA_SERVICE_GET_DATA_SOURCES_ERROR);
}
}
/**
* @param headers
* the request headers (never <code>null</code>)
* @param uriInfo
* the request URI information (never <code>null</code>)
* @param connectionName
* the id of the Connection being retrieved (cannot be empty)
* @return the JSON representation of the Connection (never <code>null</code>)
* @throws KomodoRestException
* if there is a problem finding the specified connection or constructing the JSON representation
*/
@GET
@Path( V1Constants.CONNECTIONS_SEGMENT + StringConstants.FORWARD_SLASH + V1Constants.CONNECTION_PLACEHOLDER )
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML } )
@ApiOperation(value = "Find connection by name", response = RestConnection.class)
@ApiResponses(value = {
@ApiResponse(code = 404, message = "No connection could be found with name"),
@ApiResponse(code = 406, message = "Only JSON or XML is returned by this operation"),
@ApiResponse(code = 403, message = "An error has occurred.")
})
public Response getConnection( final @Context HttpHeaders headers,
final @Context UriInfo uriInfo,
@ApiParam(value = "Name of the connection", required = true)
final @PathParam( "connectionName" ) String connectionName) throws KomodoRestException {
SecurityPrincipal principal = checkSecurityContext(headers);
if (principal.hasErrorResponse())
return principal.getErrorResponse();
List<MediaType> mediaTypes = headers.getAcceptableMediaTypes();
UnitOfWork uow = null;
try {
Repository repo = this.kengine.getDefaultRepository();
// find DataSource
uow = createTransaction(principal, "getConnection-" + connectionName, true); //$NON-NLS-1$
TeiidDataSource dataSource = getMetadataInstance().getDataSource(connectionName);
if (dataSource == null)
return commitNoConnectionFound(uow, mediaTypes, connectionName);
final RestMetadataConnection restDataSource = entityFactory.createMetadataDataSource(uow, repo, dataSource, uriInfo.getBaseUri());
LOGGER.debug("getConnection:Datasource '{0}' entity was constructed", dataSource.getName()); //$NON-NLS-1$
return commit( uow, mediaTypes, restDataSource );
} catch (CallbackTimeoutException ex) {
return createTimeoutResponse(mediaTypes);
} catch ( final Throwable e ) {
if ( ( uow != null ) && ( uow.getState() != State.ROLLED_BACK ) ) {
uow.rollback();
}
if ( e instanceof KomodoRestException ) {
throw ( KomodoRestException )e;
}
return createErrorResponseWithForbidden(mediaTypes, e, RelationalMessages.Error.METADATA_SERVICE_GET_DATA_SOURCE_ERROR, connectionName);
}
}
/**
* Return the default translator to be used for a Connection
* @param headers
* the request headers (never <code>null</code>)
* @param uriInfo
* the request URI information (never <code>null</code>)
* @param connectionName
* the id of the Connection being retrieved (cannot be empty)
* @return the translator for the connection (never <code>null</code>)
* @throws KomodoRestException
* if there is a problem finding the specified connection
*/
@GET
@Path( V1Constants.CONNECTIONS_SEGMENT + StringConstants.FORWARD_SLASH + V1Constants.CONNECTION_PLACEHOLDER
+ StringConstants.FORWARD_SLASH + V1Constants.TRANSLATOR_DEFAULT_SEGMENT)
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML } )
@ApiOperation(value = "Get the default translator recommended for a connection")
@ApiResponses(value = {
@ApiResponse(code = 404, message = "No Connection could be found with name"),
@ApiResponse(code = 406, message = "Only JSON or XML is returned by this operation"),
@ApiResponse(code = 403, message = "An error has occurred.")
})
public Response getConnectionDefaultTranslator( final @Context HttpHeaders headers,
final @Context UriInfo uriInfo,
@ApiParam(value = "Id of the connection", required = true)
final @PathParam( "connectionName" ) String connectionName) throws KomodoRestException {
SecurityPrincipal principal = checkSecurityContext(headers);
if (principal.hasErrorResponse())
return principal.getErrorResponse();
List<MediaType> mediaTypes = headers.getAcceptableMediaTypes();
UnitOfWork uow = null;
try {
// find Connection
uow = createTransaction(principal, "getConnectionDefaultTranslator-" + connectionName, true); //$NON-NLS-1$
TeiidDataSource dataSource = getMetadataInstance().getDataSource(connectionName);
if (dataSource == null)
return commitNoConnectionFound(uow, mediaTypes, connectionName);
// Get the driver name for the source
String driverName = dataSource.getType();
// Get the translator name from the default driver - translator mappings
String translatorName = driverTranslatorMap.get(driverName);
// If translator not found using driver mappings, use the connection url if available.
// The urlContentTranslatorMap keys are unique strings within the connection url which would identify the required translator
if(translatorName==null) {
String connectionUrl = dataSource.getPropertyValue("connection-url"); //$NON-NLS-1$
// No connection url property - unknown translator
if(connectionUrl == null || connectionUrl.isEmpty()) {
translatorName = UNKNOWN_TRANSLATOR;
// Connection url property found - use mappings to get translator, if possible
} else {
for(String contentKey : urlContentTranslatorMap.keySet()) {
if(connectionUrl.contains(contentKey)) {
translatorName = urlContentTranslatorMap.get(contentKey);
break;
}
}
if(translatorName==null) {
translatorName = UNKNOWN_TRANSLATOR;
}
}
}
// Return a status object with the translator
KomodoStatusObject kso = new KomodoStatusObject();
kso.addAttribute("Translator", translatorName); //$NON-NLS-1$
return commit(uow, mediaTypes, kso);
} catch ( final Exception e ) {
if ( ( uow != null ) && ( uow.getState() != State.ROLLED_BACK ) ) {
uow.rollback();
}
if ( e instanceof KomodoRestException ) {
throw ( KomodoRestException )e;
}
return createErrorResponseWithForbidden(mediaTypes, e, RelationalMessages.Error.METADATA_SERVICE_GET_DATA_SOURCE_TRANSLATOR_ERROR, connectionName);
}
}
/**
* Copy connections from the server into the workspace that are not present in the workspace
* @param headers
* the request headers (never <code>null</code>)
* @param uriInfo
* the request URI information (never <code>null</code>)
* @return a JSON representation of the status of the copying (never <code>null</code>)
* @throws KomodoRestException
* if there is an error copying the connections
*/