src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
DataSetsResource { @PreAuthorize("isAuthenticated()") @PostMapping public ResponseEntity<Void> createDataSet( HttpServletRequest httpServletRequest, @PathVariable String providerId, @RequestParam String dataSetId, @RequestParam(required = false) String description) throws ProviderNotExistsException, DataSetAlreadyExistsException { DataSet dataSet = dataSetService.createDataSet(providerId, dataSetId, description); EnrichUriUtil.enrich(httpServletRequest, dataSet); String creatorName = SpringUserUtils.getUsername(); if (creatorName != null) { ObjectIdentity dataSetIdentity = new ObjectIdentityImpl(DATASET_CLASS_NAME, dataSetId + "/" + providerId); MutableAcl datasetAcl = mutableAclService.createAcl(dataSetIdentity); datasetAcl.insertAce(0, BasePermission.READ, new PrincipalSid(creatorName), true); datasetAcl.insertAce(1, BasePermission.WRITE, new PrincipalSid(creatorName), true); datasetAcl.insertAce(2, BasePermission.DELETE, new PrincipalSid(creatorName), true); datasetAcl.insertAce(3, BasePermission.ADMINISTRATION, new PrincipalSid(creatorName), true); mutableAclService.updateAcl(datasetAcl); } return ResponseEntity.created(dataSet.getUri()).build(); } DataSetsResource(DataSetService dataSetService, MutableAclService mutableAclService); @GetMapping(produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) @ResponseBody ResultSlice<DataSet> getDataSets(
@PathVariable String providerId,
@RequestParam(required = false) String startFrom); @PreAuthorize("isAuthenticated()") @PostMapping ResponseEntity<Void> createDataSet(
HttpServletRequest httpServletRequest,
@PathVariable String providerId,
@RequestParam String dataSetId,
@RequestParam(required = false) String description); } | @Test public void shouldNotCreateTwoDatasetsWithSameId() throws Exception { Mockito.doReturn(new DataProvider()).when(uisHandler) .getProvider("provId"); String dataSetId = "dataset"; dataSetService.createDataSet("provId", dataSetId, ""); ResultActions createResponse = mockMvc.perform(post(dataSetsWebTarget, "provId") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param(F_DATASET, dataSetId)).andExpect(status().isConflict()); ErrorInfo errorInfo = responseContentAsErrorInfo(createResponse); assertEquals(McsErrorCode.DATASET_ALREADY_EXISTS.toString(), errorInfo.getErrorCode()); } |
RepresentationRevisionsResource { @GetMapping(produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) @ResponseBody public RepresentationsListWrapper getRepresentationRevisions( HttpServletRequest httpServletRequest, @PathVariable String cloudId, @PathVariable String representationName, @PathVariable String revisionName, @RequestParam String revisionProviderId, @RequestParam(required = false) String revisionTimestamp) throws RepresentationNotExistsException { Date revisionDate = null; if (revisionTimestamp != null) { DateTime utc = new DateTime(revisionTimestamp, DateTimeZone.UTC); revisionDate = utc.toDate(); } List<RepresentationRevisionResponse> info = recordService.getRepresentationRevisions(cloudId, representationName, revisionProviderId, revisionName, revisionDate); List<Representation> representations = new ArrayList<>(); if (info != null) { for (RepresentationRevisionResponse representationRevisionsResource : info) { Representation representation; representation = recordService.getRepresentation( representationRevisionsResource.getCloudId(), representationRevisionsResource.getRepresentationName(), representationRevisionsResource.getVersion()); EnrichUriUtil.enrich(httpServletRequest, representation); if (userHasAccessTo(representation)) { representations.add(representation); } } } else { throw new RepresentationNotExistsException("No representation was found"); } return new RepresentationsListWrapper(representations); } RepresentationRevisionsResource(RecordService recordService,
PermissionEvaluator permissionEvaluator); @GetMapping(produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) @ResponseBody RepresentationsListWrapper getRepresentationRevisions(
HttpServletRequest httpServletRequest,
@PathVariable String cloudId,
@PathVariable String representationName,
@PathVariable String revisionName,
@RequestParam String revisionProviderId,
@RequestParam(required = false) String revisionTimestamp); } | @Test @Parameters(method = "mimeTypes") public void getRepresentationByRevisionResponse(MediaType mediaType) throws Exception { RepresentationRevisionResponse representationRevisionResponse = new RepresentationRevisionResponse(representationResponse); ArrayList<File> files = new ArrayList<>(1); files.add(new File("1.xml", "text/xml", "91162629d258a876ee994e9233b2ad87", "2013-01-01", 12345L, URI.create("http: + "/representations/" + schema + "/versions/" + version + "/files/1.xml"))); representationRevisionResponse.setFiles(files); Representation representation = new Representation(representationRevisionResponse.getCloudId(), representationRevisionResponse.getRepresentationName(), representationRevisionResponse.getVersion(), null, null, representationRevisionResponse.getRevisionProviderId(), representationRevisionResponse.getFiles(), new ArrayList<Revision>(), false, representationRevisionResponse.getRevisionTimestamp()); List<RepresentationRevisionResponse> expectedResponse = new ArrayList<>(); expectedResponse.add(representationRevisionResponse); doReturn(expectedResponse).when(recordService).getRepresentationRevisions(globalId, schema, revisionProviderId, revisionName, null); when(recordService.getRepresentation(globalId, representationResponse.getRepresentationName(), representationResponse.getVersion())).thenReturn(representation); ResultActions response = mockMvc.perform(get(URITools.getRepresentationRevisionsPath(globalId, schema, revisionName)) .queryParam(ParamConstants.F_REVISION_PROVIDER_ID, revisionProviderId).accept(mediaType)) .andExpect(status().isOk()) .andExpect(content().contentType(mediaType)); List<Representation> entity = responseContentAsRepresentationList(response, mediaType); assertThat(entity.size(), is(1)); assertThat(entity.get(0), is(representation)); verify(recordService, times(1)).getRepresentationRevisions(globalId, schema, revisionProviderId, revisionName, null); verify(recordService, times(1)).getRepresentation(globalId, schema, representationRevisionResponse.getVersion()); verifyNoMoreInteractions(recordService); }
@Test public void getRepresentationByRevisionsThrowExceptionWhenReturnsEmptyObjectIfRevisionDoesNotExists() throws Exception { List<RepresentationRevisionResponse> expectedResponse = new ArrayList<>(); expectedResponse.add(new RepresentationRevisionResponse()); doReturn(expectedResponse).when(recordService).getRepresentationRevisions(globalId, schema, revisionProviderId, revisionName, null); doThrow(RepresentationNotExistsException.class).when(recordService).getRepresentation(anyString(), anyString(), anyString()); mockMvc.perform(get(URITools.getRepresentationRevisionsPath(globalId, schema, revisionName)) .queryParam(ParamConstants.F_REVISION_PROVIDER_ID, revisionProviderId) .accept(MediaType.APPLICATION_XML)) .andExpect(status().isNotFound()); verify(recordService, times(1)).getRepresentationRevisions(globalId, schema, revisionProviderId, revisionName, null); verify(recordService, times(1)).getRepresentation(anyString(), anyString(), anyString()); }
@Test public void getRepresentationByRevisionsThrowExceptionWhenReturnsRepresentationRevisionResponseIsNull() throws Exception { when(recordService.getRepresentationRevisions(globalId, schema, revisionProviderId, revisionName, null)).thenReturn(null); mockMvc.perform(get(URITools.getRepresentationRevisionsPath(globalId, schema, revisionName)) .queryParam(ParamConstants.F_REVISION_PROVIDER_ID, revisionProviderId) .accept(MediaType.APPLICATION_XML)) .andExpect(status().isNotFound()); verify(recordService, times(1)).getRepresentationRevisions(globalId, schema, revisionProviderId, revisionName, null); } |
RepresentationResource { @GetMapping(produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE }) @PostAuthorize("hasPermission" + "( " + " (#cloudId).concat('/').concat(#representationName).concat('/').concat(returnObject.version) ," + " 'eu.europeana.cloud.common.model.Representation', read" + ")") @ResponseBody public Representation getRepresentation( HttpServletRequest httpServletRequest, @PathVariable String cloudId, @PathVariable String representationName) throws RepresentationNotExistsException { Representation info = recordService.getRepresentation(cloudId, representationName); prepare(httpServletRequest, info); return info; } RepresentationResource(RecordService recordService,
MutableAclService mutableAclService); @GetMapping(produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE }) @PostAuthorize("hasPermission" + "( " + " (#cloudId).concat('/').concat(#representationName).concat('/').concat(returnObject.version) ," + " 'eu.europeana.cloud.common.model.Representation', read" + ")") @ResponseBody Representation getRepresentation(
HttpServletRequest httpServletRequest,
@PathVariable String cloudId,
@PathVariable String representationName); @DeleteMapping @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize("hasRole('ROLE_ADMIN')") void deleteRepresentation(
@PathVariable String cloudId,
@PathVariable String representationName); @PostMapping(consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE}) @PreAuthorize("isAuthenticated()") ResponseEntity<Void> createRepresentation(
HttpServletRequest httpServletRequest,
@PathVariable String cloudId,
@PathVariable String representationName,
@RequestParam String providerId); } | @Test @Parameters(method = "mimeTypes") public void getRepresentation(MediaType mediaType) throws Exception { Representation expected = new Representation(representation); expected.setUri(URITools.getVersionUri(getBaseUri(), globalId, schema, version)); expected.setAllVersionsUri(URITools.getAllVersionsUri(getBaseUri(), globalId, schema)); ArrayList<File> files = new ArrayList<>(1); files.add(new File("1.xml", "text/xml", "91162629d258a876ee994e9233b2ad87", "2013-01-01", 12345L, URI.create("http: + "/representations/" + schema + "/versions/" + version + "/files/1.xml"))); expected.setFiles(files); when(recordService.getRepresentation(globalId, schema)).thenReturn(new Representation(representation)); ResultActions response = mockMvc.perform(get(URITools.getRepresentationPath(globalId, schema)).accept(mediaType)) .andExpect(status().isOk()) .andExpect(content().contentType(mediaType)); Representation entity = responseContent(response,Representation.class, mediaType); assertThat(entity, is(expected)); verify(recordService, times(1)).getRepresentation(globalId, schema); verifyNoMoreInteractions(recordService); }
@Test @Parameters(method = "representationErrors") public void getRepresentationReturns404IfRepresentationOrRecordDoesNotExists(Throwable exception, String errorCode) throws Exception { when(recordService.getRepresentation(globalId, schema)).thenThrow(exception); ResultActions response = mockMvc.perform(get(URITools.getRepresentationPath(globalId, schema)) .accept(MediaType.APPLICATION_XML)) .andExpect(status().isNotFound()); ErrorInfo errorInfo = responseContent(response,ErrorInfo.class,MediaType.APPLICATION_XML); assertThat(errorInfo.getErrorCode(), is(errorCode)); verify(recordService, times(1)).getRepresentation(globalId, schema); verifyNoMoreInteractions(recordService); } |
RepresentationResource { @DeleteMapping @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize("hasRole('ROLE_ADMIN')") public void deleteRepresentation( @PathVariable String cloudId, @PathVariable String representationName) throws RepresentationNotExistsException { recordService.deleteRepresentation(cloudId, representationName); } RepresentationResource(RecordService recordService,
MutableAclService mutableAclService); @GetMapping(produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE }) @PostAuthorize("hasPermission" + "( " + " (#cloudId).concat('/').concat(#representationName).concat('/').concat(returnObject.version) ," + " 'eu.europeana.cloud.common.model.Representation', read" + ")") @ResponseBody Representation getRepresentation(
HttpServletRequest httpServletRequest,
@PathVariable String cloudId,
@PathVariable String representationName); @DeleteMapping @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize("hasRole('ROLE_ADMIN')") void deleteRepresentation(
@PathVariable String cloudId,
@PathVariable String representationName); @PostMapping(consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE}) @PreAuthorize("isAuthenticated()") ResponseEntity<Void> createRepresentation(
HttpServletRequest httpServletRequest,
@PathVariable String cloudId,
@PathVariable String representationName,
@RequestParam String providerId); } | @Test public void deleteRecord() throws Exception { mockMvc.perform(delete(URITools.getRepresentationPath(globalId, schema))) .andExpect(status().isNoContent()); verify(recordService, times(1)).deleteRepresentation(globalId, schema); verifyNoMoreInteractions(recordService); }
@Test @Parameters(method = "representationErrors") public void deleteRepresentationReturns404IfRecordOrRepresentationDoesNotExists(Throwable exception, String errorCode) throws Exception { Mockito.doThrow(exception).when(recordService).deleteRepresentation(globalId, schema); ResultActions response = mockMvc.perform(delete(URITools.getRepresentationPath(globalId, schema))) .andExpect(status().isNotFound()); ErrorInfo errorInfo = responseContentAsErrorInfo(response); assertThat(errorInfo.getErrorCode(), is(errorCode)); verify(recordService, times(1)).deleteRepresentation(globalId, schema); verifyNoMoreInteractions(recordService); } |
RepresentationResource { @PostMapping(consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE}) @PreAuthorize("isAuthenticated()") public ResponseEntity<Void> createRepresentation( HttpServletRequest httpServletRequest, @PathVariable String cloudId, @PathVariable String representationName, @RequestParam String providerId) throws RecordNotExistsException, ProviderNotExistsException { Representation version = recordService.createRepresentation(cloudId, representationName, providerId); EnrichUriUtil.enrich(httpServletRequest, version); String creatorName = SpringUserUtils.getUsername(); if (creatorName != null) { ObjectIdentity versionIdentity = new ObjectIdentityImpl(REPRESENTATION_CLASS_NAME, cloudId + "/" + representationName + "/" + version.getVersion()); MutableAcl versionAcl = mutableAclService .createAcl(versionIdentity); versionAcl.insertAce(0, BasePermission.READ, new PrincipalSid(creatorName), true); versionAcl.insertAce(1, BasePermission.WRITE, new PrincipalSid(creatorName), true); versionAcl.insertAce(2, BasePermission.DELETE, new PrincipalSid(creatorName), true); versionAcl.insertAce(3, BasePermission.ADMINISTRATION, new PrincipalSid(creatorName), true); mutableAclService.updateAcl(versionAcl); } return ResponseEntity.created(version.getUri()).build(); } RepresentationResource(RecordService recordService,
MutableAclService mutableAclService); @GetMapping(produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE }) @PostAuthorize("hasPermission" + "( " + " (#cloudId).concat('/').concat(#representationName).concat('/').concat(returnObject.version) ," + " 'eu.europeana.cloud.common.model.Representation', read" + ")") @ResponseBody Representation getRepresentation(
HttpServletRequest httpServletRequest,
@PathVariable String cloudId,
@PathVariable String representationName); @DeleteMapping @ResponseStatus(HttpStatus.NO_CONTENT) @PreAuthorize("hasRole('ROLE_ADMIN')") void deleteRepresentation(
@PathVariable String cloudId,
@PathVariable String representationName); @PostMapping(consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE}) @PreAuthorize("isAuthenticated()") ResponseEntity<Void> createRepresentation(
HttpServletRequest httpServletRequest,
@PathVariable String cloudId,
@PathVariable String representationName,
@RequestParam String providerId); } | @Test public void createRepresentation() throws Exception { when(recordService.createRepresentation(globalId, schema, providerID)).thenReturn( new Representation(representation)); mockMvc.perform(post(URITools.getRepresentationPath(globalId, schema)) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param(ParamConstants.F_PROVIDER, providerID)) .andExpect(status().isCreated()) .andExpect(header().string(HttpHeaders.LOCATION, URITools.getVersionUri(getBaseUri(), globalId, schema, version).toString())); verify(recordService, times(1)).createRepresentation(globalId, schema, providerID); verifyNoMoreInteractions(recordService); }
@Test @Parameters(method = "recordErrors") public void createRepresentationReturns404IfRecordOrRepresentationDoesNotExists(Throwable exception, String errorCode) throws Exception { Mockito.doThrow(exception).when(recordService).createRepresentation(globalId, schema, providerID); ResultActions response = mockMvc.perform(post(URITools.getRepresentationPath(globalId, schema)) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param(ParamConstants.F_PROVIDER, providerID)) .andExpect(status().isNotFound()); ErrorInfo errorInfo = responseContentAsErrorInfo(response); assertThat(errorInfo.getErrorCode(), is(errorCode)); verify(recordService, times(1)).createRepresentation(globalId, schema, providerID); verifyNoMoreInteractions(recordService); } |
CSVReader implements RevisionsReader { @Override public List<RevisionInformation> getRevisionsInformation(String filePath) throws IOException { List<RevisionInformation> revisionInformationList = new ArrayList<>(); try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { String line = ""; br.readLine(); while ((line = br.readLine()) != null) { String[] lines = line.split(LINE_SEPARATOR); RevisionInformation revisionInformation = new RevisionInformation(lines[0], lines[1], lines[2], lines[3], lines[4], lines[5]); revisionInformationList.add(revisionInformation); } } return revisionInformationList; } @Override List<RevisionInformation> getRevisionsInformation(String filePath); } | @Test public void shouldReadAndReturnTaskIdsForCSVFile() throws IOException { List<RevisionInformation> taskIds = csvReader.getRevisionsInformation(Paths.get("src/test/resources/revisions.csv").toString()); assertNotNull(taskIds); assertEquals(8, taskIds.size()); } |
RepresentationsResource { @GetMapping(produces = {MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @ResponseBody public RepresentationsListWrapper getRepresentations( HttpServletRequest httpServletRequest, @PathVariable String cloudId) throws RecordNotExistsException { List<Representation> representationInfos = recordService.getRecord(cloudId).getRepresentations(); prepare(httpServletRequest, representationInfos); return new RepresentationsListWrapper(representationInfos); } RepresentationsResource(RecordService recordService); @GetMapping(produces = {MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @ResponseBody RepresentationsListWrapper getRepresentations(
HttpServletRequest httpServletRequest,
@PathVariable String cloudId); } | @Test @Parameters(method = "mimeTypes") public void getRepresentations(MediaType mediaType) throws Exception { Record expected = new Record(record); Representation expectedRepresentation = expected.getRepresentations().get(0); expectedRepresentation.setUri(URITools.getVersionUri(getBaseUri(), globalId, schema, version)); expectedRepresentation.setAllVersionsUri(URITools.getAllVersionsUri(getBaseUri(), globalId, schema)); expectedRepresentation.setFiles(new ArrayList<File>()); when(recordService.getRecord(globalId)).thenReturn(new Record(record)); ResultActions response = mockMvc.perform(get(URITools.getRepresentationsPath(globalId).toString()).accept(mediaType)) .andExpect(status().isOk()) .andExpect(content().contentType(mediaType)); List<Representation> entity = responseContentAsRepresentationList(response, mediaType); assertThat(entity, is(expected.getRepresentations())); verify(recordService, times(1)).getRecord(globalId); verifyNoMoreInteractions(recordService); } |
ContentStreamDetector { public static MediaType detectMediaType(InputStream inputStream) throws IOException { if (!inputStream.markSupported()) { throw new UnsupportedOperationException("InputStream marking support is required!"); } return new AutoDetectParser().getDetector().detect(inputStream, new Metadata()); } private ContentStreamDetector(); static MediaType detectMediaType(InputStream inputStream); } | @Test @Parameters({ "example_metadata.xml, application/xml", "example_jpg2000.jp2, image/jp2" }) public void shouldProperlyGuessMimeType_Xml(String fileName, String expectedMimeType) throws IOException { URL resource = Resources.getResource(fileName); byte[] expected = Resources.toByteArray(resource); BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream( resource.getFile())); String mimeType = detectMediaType(inputStream).toString(); assertThat(mimeType,is(expectedMimeType)); byte[] actual = readFully(inputStream, expected.length); assertThat(actual,is(expected)); } |
StorageSelector { public Storage selectStorage() { return decide(assertUserMediaType(), getAvailable()); } StorageSelector(final PreBufferedInputStream inputStream, final String userMediaType); Storage selectStorage(); } | @Test @Parameters({ "example_metadata.xml, DATA_BASE, application/xml", "example_jpg2000.jp2, OBJECT_STORAGE, image/jp2" }) public void shouldDetectStorage(String fileName, String expectedDecision, String mediaType) throws IOException { URL resource = Resources.getResource(fileName); byte[] expected = Resources.toByteArray(resource); PreBufferedInputStream inputStream = new PreBufferedInputStream( new FileInputStream(resource.getFile()), 512 * 1024); StorageSelector instance = new StorageSelector(inputStream, mediaType); Storage decision = instance.selectStorage(); assertThat(decision.toString(), is(expectedDecision)); byte[] actual = readFully(inputStream, expected.length); assertThat(actual, is(expected)); }
@Test(expected = BadRequestException.class) @Parameters({ "example_metadata.xml, image/jp2", "example_jpg2000.jp2, application/xml" }) public void shouldThrowBadRequestOnDifferentMimeTypeProvidedByUser(String fileName, String mediaType) throws IOException { URL resource = Resources.getResource(fileName); byte[] expected = Resources.toByteArray(resource); PreBufferedInputStream inputStream = new PreBufferedInputStream( new FileInputStream(resource.getFile()), 512 * 1024); StorageSelector instance = new StorageSelector(inputStream, mediaType); Storage decision = instance.selectStorage(); } |
PreBufferedInputStream extends BufferedInputStream { @Override public synchronized int available() throws IOException { ensureIsNotClosed(); int inBufferAvailable = bufferFill - position; int avail = super.available(); return inBufferAvailable > (Integer.MAX_VALUE - avail) ? Integer.MAX_VALUE : inBufferAvailable + avail; } PreBufferedInputStream(InputStream stream, int bufferSize); static PreBufferedInputStream wrap(final byte[] data,
final int preloadChunkSize); int getBufferSize(); @Override synchronized int read(); @Override synchronized int read(final byte[] b, final int offset, final int length); @Override synchronized int available(); @Override boolean markSupported(); @Override synchronized void mark(int readLimit); @Override synchronized void reset(); @Override synchronized void close(); @Override synchronized long skip(final long length); } | @Test @Parameters({ "10, 20", "20, 10", "10, 10000", "10000, 20", "10000, 3000", "10000, 4000", "10, 20", "20, 10" }) public void shouldProperlyCheckAvailableForByteArrayInputStream(int size, int bufferSize) throws IOException { byte[] expected = Helper.generateRandom(size); ByteArrayInputStream inputStream = new ByteArrayInputStream(expected); PreBufferedInputStream instance = new PreBufferedInputStream(inputStream, bufferSize); int available = instance.available(); assertThat(available, is(size)); assertUnchangedStream(expected, instance); }
@Test @Parameters({ "10, example_metadata.xml", "200, example_metadata.xml", "2000, example_metadata.xml", "3000, example_metadata.xml", "10, example_jpg2000.jp2", "2000, example_jpg2000.jp2", "3000, example_jpg2000.jp2" }) public void shouldProperlyCheckAvailableForFile(final int bufferSize, final String fileName) throws IOException { URL resourceUri = Resources.getResource(fileName); final byte[] expected = Resources.toByteArray(resourceUri); FileInputStream inputStream = new FileInputStream( resourceUri.getFile()); PreBufferedInputStream instance = new PreBufferedInputStream(inputStream, bufferSize); int available = instance.available(); assertThat(available,is((expected.length))); assertThat(available,is(((int) new File(resourceUri.getFile()).length()))); assertUnchangedStream(expected, instance); } |
PreBufferedInputStream extends BufferedInputStream { @Override public synchronized int read() throws IOException { ensureIsNotClosed(); if (position < bufferFill) { return buffer[position++] & 0xff; } return super.read(); } PreBufferedInputStream(InputStream stream, int bufferSize); static PreBufferedInputStream wrap(final byte[] data,
final int preloadChunkSize); int getBufferSize(); @Override synchronized int read(); @Override synchronized int read(final byte[] b, final int offset, final int length); @Override synchronized int available(); @Override boolean markSupported(); @Override synchronized void mark(int readLimit); @Override synchronized void reset(); @Override synchronized void close(); @Override synchronized long skip(final long length); } | @Test @Parameters({ "10, 20", "200, 10", "100, 10000", "100, 200", "200, 100" }) public void shouldReadStreamPerByte(int size, int bufferSize) throws IOException { byte[] randomByes = Helper.generateSeq(size); ByteArrayInputStream inputStream = new ByteArrayInputStream(randomByes); PreBufferedInputStream instance = new PreBufferedInputStream(inputStream, bufferSize); int[] actual = new int[randomByes.length]; for (int i = 0; i < actual.length; i++) { actual[i] = instance.read(); } int[] randomIntegers = new int[actual.length]; for (int i = 0; i < randomIntegers.length; i++) { randomIntegers[i] = randomByes[i] & 0xff; } assertThat(actual, is(randomIntegers)); } |
PreBufferedInputStream extends BufferedInputStream { @Override public synchronized void close() throws IOException { if (in == null && buffer == null) { return; } buffer = null; in.close(); in = null; } PreBufferedInputStream(InputStream stream, int bufferSize); static PreBufferedInputStream wrap(final byte[] data,
final int preloadChunkSize); int getBufferSize(); @Override synchronized int read(); @Override synchronized int read(final byte[] b, final int offset, final int length); @Override synchronized int available(); @Override boolean markSupported(); @Override synchronized void mark(int readLimit); @Override synchronized void reset(); @Override synchronized void close(); @Override synchronized long skip(final long length); } | @Test public void shouldCloseClosedStream() throws IOException { PreBufferedInputStream instance = new PreBufferedInputStream(new NullInputStream(1), 1); instance.close(); instance.close(); } |
CassandraDataSetService implements DataSetService { @Override public DataSet createDataSet(String providerId, String dataSetId, String description) throws ProviderNotExistsException, DataSetAlreadyExistsException { Date now = new Date(); if (uis.getProvider(providerId) == null) { throw new ProviderNotExistsException(); } DataSet ds = dataSetDAO.getDataSet(providerId, dataSetId); if (ds != null) { throw new DataSetAlreadyExistsException("Data set with provided name already exists"); } return dataSetDAO .createDataSet(providerId, dataSetId, description, now); } @Override ResultSlice<Representation> listDataSet(String providerId, String dataSetId, String thresholdParam, int limit); @Override void addAssignment(String providerId, String dataSetId,
String recordId, String schema, String version); @Override void removeAssignment(String providerId, String dataSetId,
String recordId, String schema, String versionId); @Override DataSet createDataSet(String providerId, String dataSetId,
String description); @Override DataSet updateDataSet(String providerId, String dataSetId,
String description); @Override ResultSlice<DataSet> getDataSets(String providerId,
String thresholdDatasetId, int limit); @Override ResultSlice<CloudTagsResponse> getDataSetsRevisions(String providerId, String dataSetId, String revisionProviderId, String revisionName, Date revisionTimestamp, String representationName, String startFrom, int limit); @Override void addDataSetsRevisions(String providerId, String dataSetId, Revision revision,
String representationName, String cloudId); @Override ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationPublished(String
dataSetId, String providerId, String representationName, Date dateFrom, String startFrom,
int numberOfElementsPerPage); @Override void updateAllRevisionDatasetsEntries(String globalId, String schema, String
version, Revision revision); @Override void deleteDataSet(String providerId, String dataSetId); @Override Set<String> getAllDataSetRepresentationsNames(String providerId, String dataSetId); @Override void updateProviderDatasetRepresentation(String globalId, String schema, String version, Revision revision); @Override String getLatestVersionForGivenRevision(String dataSetId, String providerId, String cloudId, String
representationName, String revisionName, String revisionProviderId); @Override void addLatestRevisionForGivenVersionInDataset(DataSet dataSet, Representation representation, Revision
revision); @Override ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision(String dataSetId, String providerId, String revisionName, String revisionProvider, String representationName, String startFrom, Boolean isDeleted, int numberOfElementsPerPage); @Override void deleteRevision(String cloudId, String representationName, String version, String revisionName, String revisionProviderId, Date revisionTimestamp); } | @Test public void shouldCreateDataSet() throws Exception { makeUISProviderSuccess(); String dsName = "ds"; String description = "description of data set"; DataSet ds = cassandraDataSetService.createDataSet(PROVIDER_ID, dsName, description); assertThat(ds.getId(), is(dsName)); assertThat(ds.getDescription(), is(description)); assertThat(ds.getProviderId(), is(PROVIDER_ID)); }
@Test(expected = ProviderNotExistsException.class) public void shouldThrowExceptionWhenCreatingDatasetForNotExistingProvider() throws Exception { makeUISProviderFailure(); cassandraDataSetService.createDataSet("not-existing-provider", "ds", "description"); }
@Test(expected = DataSetAlreadyExistsException.class) public void shouldNotCreateTwoDatasetsWithSameNameForProvider() throws Exception { String dsName = "ds"; makeUISProviderSuccess(); cassandraDataSetService .createDataSet(PROVIDER_ID, dsName, "description"); cassandraDataSetService.createDataSet(PROVIDER_ID, dsName, "description of another"); } |
CassandraDataSetService implements DataSetService { @Override public void addAssignment(String providerId, String dataSetId, String recordId, String schema, String version) throws DataSetNotExistsException, RepresentationNotExistsException { checkIfDatasetExists(dataSetId, providerId); Representation rep = getRepresentationIfExist(recordId, schema, version); if (!isAssignmentExists(providerId, dataSetId, recordId, schema, rep.getVersion())) { dataSetDAO.addAssignment(providerId, dataSetId, recordId, schema, rep.getVersion()); DataProvider dataProvider = uis.getProvider(providerId); dataSetDAO.addDataSetsRepresentationName(providerId, dataSetId, schema); Map<String, Revision> latestRevisions = new HashMap<>(); for (Revision revision : rep.getRevisions()) { String revisionKey = revision.getRevisionName() + "_" + revision.getRevisionProviderId(); Revision currentRevision = latestRevisions.get(revisionKey); if (currentRevision == null || revision.getCreationTimeStamp().getTime() > currentRevision.getCreationTimeStamp().getTime()) { latestRevisions.put(revisionKey, revision); } dataSetDAO.addDataSetsRevision(providerId, dataSetId, revision, schema, recordId); dataSetDAO.insertProviderDatasetRepresentationInfo(dataSetId, providerId, recordId, rep.getVersion(), schema, RevisionUtils.getRevisionKey(revision), revision.getCreationTimeStamp(), revision.isAcceptance(), revision.isPublished(), revision.isDeleted()); dataSetDAO.addLatestRevisionForDatasetAssignment(dataSetDAO.getDataSet(providerId, dataSetId), rep, revision); } updateLatestProviderDatasetRevisions(providerId, dataSetId, recordId, schema, version, latestRevisions); } } @Override ResultSlice<Representation> listDataSet(String providerId, String dataSetId, String thresholdParam, int limit); @Override void addAssignment(String providerId, String dataSetId,
String recordId, String schema, String version); @Override void removeAssignment(String providerId, String dataSetId,
String recordId, String schema, String versionId); @Override DataSet createDataSet(String providerId, String dataSetId,
String description); @Override DataSet updateDataSet(String providerId, String dataSetId,
String description); @Override ResultSlice<DataSet> getDataSets(String providerId,
String thresholdDatasetId, int limit); @Override ResultSlice<CloudTagsResponse> getDataSetsRevisions(String providerId, String dataSetId, String revisionProviderId, String revisionName, Date revisionTimestamp, String representationName, String startFrom, int limit); @Override void addDataSetsRevisions(String providerId, String dataSetId, Revision revision,
String representationName, String cloudId); @Override ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationPublished(String
dataSetId, String providerId, String representationName, Date dateFrom, String startFrom,
int numberOfElementsPerPage); @Override void updateAllRevisionDatasetsEntries(String globalId, String schema, String
version, Revision revision); @Override void deleteDataSet(String providerId, String dataSetId); @Override Set<String> getAllDataSetRepresentationsNames(String providerId, String dataSetId); @Override void updateProviderDatasetRepresentation(String globalId, String schema, String version, Revision revision); @Override String getLatestVersionForGivenRevision(String dataSetId, String providerId, String cloudId, String
representationName, String revisionName, String revisionProviderId); @Override void addLatestRevisionForGivenVersionInDataset(DataSet dataSet, Representation representation, Revision
revision); @Override ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision(String dataSetId, String providerId, String revisionName, String revisionProvider, String representationName, String startFrom, Boolean isDeleted, int numberOfElementsPerPage); @Override void deleteRevision(String cloudId, String representationName, String version, String revisionName, String revisionProviderId, Date revisionTimestamp); } | @Test(expected = DataSetNotExistsException.class) public void shouldNotAssignToNotExistingDataSet() throws Exception { makeUISProviderSuccess(); Representation r = insertDummyPersistentRepresentation("cloud-id", "schema", PROVIDER_ID); cassandraDataSetService.addAssignment(PROVIDER_ID, "not-existing", r.getCloudId(), r.getRepresentationName(), r.getVersion()); } |
CassandraDataSetService implements DataSetService { @Override public void deleteDataSet(String providerId, String dataSetId) throws DataSetNotExistsException { checkIfDatasetExists(dataSetId, providerId); String nextToken = null; int maxSize = 10000; List<Properties> representations = dataSetDAO.listDataSet(providerId, dataSetId, null, maxSize); for (Properties representation : representations) { removeAssignment(providerId, dataSetId, representation.getProperty("cloudId"), representation.getProperty("schema"), representation.getProperty("versionId")); } while (representations.size() == maxSize + 1) { nextToken = representations.get(maxSize).getProperty("nextSlice"); representations = dataSetDAO.listDataSet(providerId, dataSetId, nextToken, maxSize); for (Properties representation : representations) { removeAssignment(providerId, dataSetId, representation.getProperty("cloudId"), representation.getProperty("schema"), representation.getProperty("versionId")); } } dataSetDAO.deleteDataSet(providerId, dataSetId); } @Override ResultSlice<Representation> listDataSet(String providerId, String dataSetId, String thresholdParam, int limit); @Override void addAssignment(String providerId, String dataSetId,
String recordId, String schema, String version); @Override void removeAssignment(String providerId, String dataSetId,
String recordId, String schema, String versionId); @Override DataSet createDataSet(String providerId, String dataSetId,
String description); @Override DataSet updateDataSet(String providerId, String dataSetId,
String description); @Override ResultSlice<DataSet> getDataSets(String providerId,
String thresholdDatasetId, int limit); @Override ResultSlice<CloudTagsResponse> getDataSetsRevisions(String providerId, String dataSetId, String revisionProviderId, String revisionName, Date revisionTimestamp, String representationName, String startFrom, int limit); @Override void addDataSetsRevisions(String providerId, String dataSetId, Revision revision,
String representationName, String cloudId); @Override ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationPublished(String
dataSetId, String providerId, String representationName, Date dateFrom, String startFrom,
int numberOfElementsPerPage); @Override void updateAllRevisionDatasetsEntries(String globalId, String schema, String
version, Revision revision); @Override void deleteDataSet(String providerId, String dataSetId); @Override Set<String> getAllDataSetRepresentationsNames(String providerId, String dataSetId); @Override void updateProviderDatasetRepresentation(String globalId, String schema, String version, Revision revision); @Override String getLatestVersionForGivenRevision(String dataSetId, String providerId, String cloudId, String
representationName, String revisionName, String revisionProviderId); @Override void addLatestRevisionForGivenVersionInDataset(DataSet dataSet, Representation representation, Revision
revision); @Override ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision(String dataSetId, String providerId, String revisionName, String revisionProvider, String representationName, String startFrom, Boolean isDeleted, int numberOfElementsPerPage); @Override void deleteRevision(String cloudId, String representationName, String version, String revisionName, String revisionProviderId, Date revisionTimestamp); } | @Test(expected = DataSetNotExistsException.class) public void shouldThrowExceptionWhenDeletingNotExistingDataSet() throws Exception { cassandraDataSetService.deleteDataSet("xxx", "xxx"); } |
CassandraDataSetService implements DataSetService { @Override public ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationPublished(String dataSetId, String providerId, String representationName, Date dateFrom, String startFrom, int numberOfElementsPerPage) throws ProviderNotExistsException, DataSetNotExistsException { validateRequest(dataSetId, providerId); List<Properties> list = dataSetDAO.getDataSetCloudIdsByRepresentationPublished(providerId, dataSetId, representationName, dateFrom, startFrom, numberOfElementsPerPage); String nextToken = null; if (list.size() == numberOfElementsPerPage + 1) { nextToken = list.get(numberOfElementsPerPage).getProperty("nextSlice"); list.remove(numberOfElementsPerPage); } return new ResultSlice<>(nextToken, prepareResponseList(list)); } @Override ResultSlice<Representation> listDataSet(String providerId, String dataSetId, String thresholdParam, int limit); @Override void addAssignment(String providerId, String dataSetId,
String recordId, String schema, String version); @Override void removeAssignment(String providerId, String dataSetId,
String recordId, String schema, String versionId); @Override DataSet createDataSet(String providerId, String dataSetId,
String description); @Override DataSet updateDataSet(String providerId, String dataSetId,
String description); @Override ResultSlice<DataSet> getDataSets(String providerId,
String thresholdDatasetId, int limit); @Override ResultSlice<CloudTagsResponse> getDataSetsRevisions(String providerId, String dataSetId, String revisionProviderId, String revisionName, Date revisionTimestamp, String representationName, String startFrom, int limit); @Override void addDataSetsRevisions(String providerId, String dataSetId, Revision revision,
String representationName, String cloudId); @Override ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationPublished(String
dataSetId, String providerId, String representationName, Date dateFrom, String startFrom,
int numberOfElementsPerPage); @Override void updateAllRevisionDatasetsEntries(String globalId, String schema, String
version, Revision revision); @Override void deleteDataSet(String providerId, String dataSetId); @Override Set<String> getAllDataSetRepresentationsNames(String providerId, String dataSetId); @Override void updateProviderDatasetRepresentation(String globalId, String schema, String version, Revision revision); @Override String getLatestVersionForGivenRevision(String dataSetId, String providerId, String cloudId, String
representationName, String revisionName, String revisionProviderId); @Override void addLatestRevisionForGivenVersionInDataset(DataSet dataSet, Representation representation, Revision
revision); @Override ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision(String dataSetId, String providerId, String revisionName, String revisionProvider, String representationName, String startFrom, Boolean isDeleted, int numberOfElementsPerPage); @Override void deleteRevision(String cloudId, String representationName, String version, String revisionName, String revisionProviderId, Date revisionTimestamp); } | @Test(expected = DataSetNotExistsException.class) public void shouldThrowExceptionWhenRequestingCloudIdsForNonExistingDataSet() throws Exception { makeUISProviderExistsSuccess(); cassandraDataSetService.getDataSetCloudIdsByRepresentationPublished("non-existent-ds", "provider", "representation", new Date(), null, 1); }
@Test(expected = ProviderNotExistsException.class) public void shouldThrowExceptionWhenRequestingCloudIdsForNonExistingProvider() throws Exception { makeUISProviderExistsFailure(); cassandraDataSetService.getDataSetCloudIdsByRepresentationPublished("ds", "non-existent-provider", "representation", new Date(), null, 1); } |
CassandraDataSetService implements DataSetService { @Override public ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision(String dataSetId, String providerId, String revisionName, String revisionProvider, String representationName, String startFrom, Boolean isDeleted, int numberOfElementsPerPage) throws ProviderNotExistsException, DataSetNotExistsException { validateRequest(dataSetId, providerId); List<CloudIdAndTimestampResponse> list = dataSetDAO.getLatestDataSetCloudIdByRepresentationAndRevision(providerId, dataSetId, revisionName, revisionProvider, representationName, startFrom, isDeleted, numberOfElementsPerPage); String nextToken = null; if (list.size() == numberOfElementsPerPage + 1) { nextToken = list.get(numberOfElementsPerPage).getCloudId(); list.remove(numberOfElementsPerPage); } return new ResultSlice<>(nextToken, list); } @Override ResultSlice<Representation> listDataSet(String providerId, String dataSetId, String thresholdParam, int limit); @Override void addAssignment(String providerId, String dataSetId,
String recordId, String schema, String version); @Override void removeAssignment(String providerId, String dataSetId,
String recordId, String schema, String versionId); @Override DataSet createDataSet(String providerId, String dataSetId,
String description); @Override DataSet updateDataSet(String providerId, String dataSetId,
String description); @Override ResultSlice<DataSet> getDataSets(String providerId,
String thresholdDatasetId, int limit); @Override ResultSlice<CloudTagsResponse> getDataSetsRevisions(String providerId, String dataSetId, String revisionProviderId, String revisionName, Date revisionTimestamp, String representationName, String startFrom, int limit); @Override void addDataSetsRevisions(String providerId, String dataSetId, Revision revision,
String representationName, String cloudId); @Override ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationPublished(String
dataSetId, String providerId, String representationName, Date dateFrom, String startFrom,
int numberOfElementsPerPage); @Override void updateAllRevisionDatasetsEntries(String globalId, String schema, String
version, Revision revision); @Override void deleteDataSet(String providerId, String dataSetId); @Override Set<String> getAllDataSetRepresentationsNames(String providerId, String dataSetId); @Override void updateProviderDatasetRepresentation(String globalId, String schema, String version, Revision revision); @Override String getLatestVersionForGivenRevision(String dataSetId, String providerId, String cloudId, String
representationName, String revisionName, String revisionProviderId); @Override void addLatestRevisionForGivenVersionInDataset(DataSet dataSet, Representation representation, Revision
revision); @Override ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision(String dataSetId, String providerId, String revisionName, String revisionProvider, String representationName, String startFrom, Boolean isDeleted, int numberOfElementsPerPage); @Override void deleteRevision(String cloudId, String representationName, String version, String revisionName, String revisionProviderId, Date revisionTimestamp); } | @Test public void shouldReturnTheLatestCloudIdsAndTimeStampInsideRevisionDataSet() throws Exception { int size = 10; prepareTestForTheLatestCloudIdAndTimeStampInsideDataSet(size); ResultSlice<CloudIdAndTimestampResponse> cloudIdsAndTimestampResponseResultSlice = cassandraDataSetService.getLatestDataSetCloudIdByRepresentationAndRevision(DATA_SET_NAME, PROVIDER_ID, REVISION, PROVIDER_ID, REPRESENTATION, null, true, 100); List<CloudIdAndTimestampResponse> cloudIdsAndTimestampResponse = cloudIdsAndTimestampResponseResultSlice.getResults(); assertFalse(cloudIdsAndTimestampResponse.isEmpty()); assertEquals(cloudIdsAndTimestampResponse.size(), size); }
@Test public void shouldReturnTheLatestCloudIdsAndTimeStampInsideRevisionDataSetWhenIsMarkedDeleted() throws Exception { int size = 10; prepareTestForTheLatestCloudIdAndTimeStampInsideDataSet(size); ResultSlice<CloudIdAndTimestampResponse> cloudIdsAndTimestampResponseResultSlice = cassandraDataSetService.getLatestDataSetCloudIdByRepresentationAndRevision(DATA_SET_NAME, PROVIDER_ID, REVISION, PROVIDER_ID, REPRESENTATION, null, false, 100); List<CloudIdAndTimestampResponse> cloudIdsAndTimestampResponse = cloudIdsAndTimestampResponseResultSlice.getResults(); assertTrue(cloudIdsAndTimestampResponse.isEmpty()); cloudIdsAndTimestampResponseResultSlice = cassandraDataSetService.getLatestDataSetCloudIdByRepresentationAndRevision(DATA_SET_NAME, PROVIDER_ID, REVISION, PROVIDER_ID, REPRESENTATION, null, true, 100); cloudIdsAndTimestampResponse = cloudIdsAndTimestampResponseResultSlice.getResults(); assertFalse(cloudIdsAndTimestampResponse.isEmpty()); assertEquals(cloudIdsAndTimestampResponse.size(), size); }
@Test public void shouldReturnTheLatestCloudIdsAndTimeStampInsideRevisionDataSetBatchByBatch() throws Exception { int size = 10; prepareTestForTheLatestCloudIdAndTimeStampInsideDataSet(size); ResultSlice<CloudIdAndTimestampResponse> cloudIdsAndTimestampResponseResultSlice = cassandraDataSetService.getLatestDataSetCloudIdByRepresentationAndRevision(DATA_SET_NAME, PROVIDER_ID, REVISION, PROVIDER_ID, REPRESENTATION, null, true, 1); List<CloudIdAndTimestampResponse> cloudIdsAndTimestampResponse = cloudIdsAndTimestampResponseResultSlice.getResults(); assertFalse(cloudIdsAndTimestampResponse.isEmpty()); assertEquals(cloudIdsAndTimestampResponse.size(), 1); String cloudId = cloudIdsAndTimestampResponse.get(0).getCloudId(); cloudIdsAndTimestampResponseResultSlice = cassandraDataSetService.getLatestDataSetCloudIdByRepresentationAndRevision(DATA_SET_NAME, PROVIDER_ID, REVISION, PROVIDER_ID, REPRESENTATION, cloudId, true, 1); cloudIdsAndTimestampResponse = cloudIdsAndTimestampResponseResultSlice.getResults(); int batchCounter = 1; while (!cloudIdsAndTimestampResponse.isEmpty()) { batchCounter++; cloudId = cloudIdsAndTimestampResponse.get(0).getCloudId(); cloudIdsAndTimestampResponseResultSlice = cassandraDataSetService.getLatestDataSetCloudIdByRepresentationAndRevision(DATA_SET_NAME, PROVIDER_ID, REVISION, PROVIDER_ID, REPRESENTATION, cloudId, true, 1); cloudIdsAndTimestampResponse = cloudIdsAndTimestampResponseResultSlice.getResults(); } assertEquals(batchCounter, size); }
@Test(expected = DataSetNotExistsException.class) public void shouldThrowDataSetNotExistedException() throws Exception { int size = 10; prepareTestForTheLatestCloudIdAndTimeStampInsideDataSet(size); cassandraDataSetService.getLatestDataSetCloudIdByRepresentationAndRevision("Non_Existed_Dataset", PROVIDER_ID, REVISION, PROVIDER_ID, REPRESENTATION, null, null, 1); } |
CassandraDataSetService implements DataSetService { @Override public void deleteRevision(String cloudId, String representationName, String version, String revisionName, String revisionProviderId, Date revisionTimestamp) throws RepresentationNotExistsException { checkIfRepresentationExists(representationName, version, cloudId); Revision revision = new Revision(revisionName, revisionProviderId); revision.setCreationTimeStamp(revisionTimestamp); Collection<CompoundDataSetId> compoundDataSetIds = dataSetDAO.getDataSetAssignmentsByRepresentationVersion(cloudId, representationName, version); for (CompoundDataSetId compoundDataSetId : compoundDataSetIds) { dataSetDAO.removeDataSetsRevision(compoundDataSetId.getDataSetProviderId(), compoundDataSetId.getDataSetId(), revision, representationName, cloudId); dataSetDAO.deleteProviderDatasetRepresentationInfo(compoundDataSetId.getDataSetId(), compoundDataSetId.getDataSetProviderId(), cloudId, representationName, revisionTimestamp); } recordDAO.deleteRepresentationRevision(cloudId, representationName, version, revisionProviderId, revisionName, revisionTimestamp); recordDAO.removeRevisionFromRepresentationVersion(cloudId, representationName, version,revision); } @Override ResultSlice<Representation> listDataSet(String providerId, String dataSetId, String thresholdParam, int limit); @Override void addAssignment(String providerId, String dataSetId,
String recordId, String schema, String version); @Override void removeAssignment(String providerId, String dataSetId,
String recordId, String schema, String versionId); @Override DataSet createDataSet(String providerId, String dataSetId,
String description); @Override DataSet updateDataSet(String providerId, String dataSetId,
String description); @Override ResultSlice<DataSet> getDataSets(String providerId,
String thresholdDatasetId, int limit); @Override ResultSlice<CloudTagsResponse> getDataSetsRevisions(String providerId, String dataSetId, String revisionProviderId, String revisionName, Date revisionTimestamp, String representationName, String startFrom, int limit); @Override void addDataSetsRevisions(String providerId, String dataSetId, Revision revision,
String representationName, String cloudId); @Override ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationPublished(String
dataSetId, String providerId, String representationName, Date dateFrom, String startFrom,
int numberOfElementsPerPage); @Override void updateAllRevisionDatasetsEntries(String globalId, String schema, String
version, Revision revision); @Override void deleteDataSet(String providerId, String dataSetId); @Override Set<String> getAllDataSetRepresentationsNames(String providerId, String dataSetId); @Override void updateProviderDatasetRepresentation(String globalId, String schema, String version, Revision revision); @Override String getLatestVersionForGivenRevision(String dataSetId, String providerId, String cloudId, String
representationName, String revisionName, String revisionProviderId); @Override void addLatestRevisionForGivenVersionInDataset(DataSet dataSet, Representation representation, Revision
revision); @Override ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision(String dataSetId, String providerId, String revisionName, String revisionProvider, String representationName, String startFrom, Boolean isDeleted, int numberOfElementsPerPage); @Override void deleteRevision(String cloudId, String representationName, String version, String revisionName, String revisionProviderId, Date revisionTimestamp); } | @Test(expected = RepresentationNotExistsException.class) public void shouldThrowRepresentationNotExistsException() throws Exception { makeUISProviderSuccess(); makeUISSuccess(); makeDatasetExists(); Date date = new Date(); String cloudId = "2EEN23VWNXOW7LGLM6SKTDOZUBUOTKEWZ3IULSYEWEMERHISS6XA"; cassandraDataSetService.deleteRevision(cloudId, REPRESENTATION, "3d6381c0-a3cf-11e9-960f-fa163e8d4ae3", REVISION, PROVIDER_ID, date); } |
DynamicContentDAO { public void deleteContent(String fileName, Storage stored) throws FileNotExistsException { getContentDAO(stored).deleteContent(fileName); } @Autowired DynamicContentDAO(Map<Storage,ContentDAO> contentDAOs); void copyContent(String sourceObjectId, String trgObjectId, Storage stored); void deleteContent(String fileName, Storage stored); void getContent(String fileName, long start, long end, OutputStream os, Storage stored); PutResult putContent(String fileName, InputStream data, Storage stored); } | @Test(expected = ContentDaoNotFoundException.class) public void shouldThrowExceptionOnNonExistingDAO() throws FileNotExistsException { final DynamicContentDAO instance = new DynamicContentDAO(prepareDAOMap( mock(SwiftContentDAO.class) )); instance.deleteContent("exampleFileName",Storage.DATA_BASE); }
@Test public void shouldProperlySelectDataBaseDeleteContent() throws FileNotExistsException { SwiftContentDAO daoMock = mock(SwiftContentDAO.class); final DynamicContentDAO instance = new DynamicContentDAO(prepareDAOMap(daoMock)); instance.deleteContent("exampleFileName",Storage.OBJECT_STORAGE); verify(daoMock).deleteContent(anyString()); } |
CassandraRecordService implements RecordService { @Override public Representation createRepresentation(String cloudId, String representationName, String providerId) throws ProviderNotExistsException, RecordNotExistsException { Date now = new Date(); DataProvider dataProvider; if ((dataProvider = uis.getProvider(providerId)) == null) { throw new ProviderNotExistsException(String.format("Provider %s does not exist.", providerId)); } if (uis.existsCloudId(cloudId)) { Representation rep = recordDAO.createRepresentation(cloudId, representationName, providerId, now); return rep; } else { throw new RecordNotExistsException(cloudId); } } @Override Record getRecord(String cloudId); @Override void deleteRecord(String cloudId); @Override void deleteRepresentation(String globalId, String schema); @Override Representation createRepresentation(String cloudId, String representationName, String providerId); @Override Representation getRepresentation(String globalId, String schema); @Override Representation getRepresentation(String globalId, String schema, String version); @Override void deleteRepresentation(String globalId, String schema, String version); @Override Representation persistRepresentation(String globalId, String schema, String version); @Override List<Representation> listRepresentationVersions(String globalId, String schema); @Override boolean putContent(String globalId, String schema, String version, File file, InputStream content); @Override Consumer<OutputStream> getContent(String globalId, String schema, String version, String fileName, long rangeStart,
long rangeEnd); @Override String getContent(String globalId, String schema, String version, String fileName, OutputStream os); @Override void deleteContent(String globalId, String schema, String version, String fileName); @Override Representation copyRepresentation(String globalId, String schema, String version); @Override File getFile(String globalId, String schema, String version, String fileName); @Override void addRevision(String globalId, String schema, String version, Revision revision); @Override List<RepresentationRevisionResponse> getRepresentationRevisions(String globalId, String schema, String revisionProviderId, String revisionName, Date revisionTimestamp); @Override void insertRepresentationRevision(String globalId, String schema, String revisionProviderId, String revisionName, String versionId, Date revisionTimestamp); @Override Revision getRevision(String globalId, String schema, String version, String revisionKey); } | @Test(expected = RecordNotExistsException.class) public void shouldThrowExpWhileCreatingRepresentationIfNoRecordInUis() throws Exception { makeUISThrowRecordNotExist(); mockUISProvider1Success(); cassandraRecordService.createRepresentation("globalId", "dc", PROVIDER_1_ID); }
@Test(expected = SystemException.class) public void shouldThrowSystemExpWhileCreatingRepresentationIfUisFails() throws Exception { mockUISProvider1Success(); makeUISThrowSystemException(); cassandraRecordService.createRepresentation("globalId", "dc", PROVIDER_1_ID); }
@Test(expected = ProviderNotExistsException.class) public void shouldNotCreateRepresentationForNotExistingProvider() throws Exception { makeUISFailure(); makeUISProviderFailure(); cassandraRecordService.createRepresentation("globalId", "dc", "not-existing"); } |
CassandraRecordService implements RecordService { @Override public Record getRecord(String cloudId) throws RecordNotExistsException { Record record = null; if (uis.existsCloudId(cloudId)) { record = recordDAO.getRecord(cloudId); if (record.getRepresentations().isEmpty()) { throw new RecordNotExistsException(cloudId); } } else { throw new RecordNotExistsException(cloudId); } return record; } @Override Record getRecord(String cloudId); @Override void deleteRecord(String cloudId); @Override void deleteRepresentation(String globalId, String schema); @Override Representation createRepresentation(String cloudId, String representationName, String providerId); @Override Representation getRepresentation(String globalId, String schema); @Override Representation getRepresentation(String globalId, String schema, String version); @Override void deleteRepresentation(String globalId, String schema, String version); @Override Representation persistRepresentation(String globalId, String schema, String version); @Override List<Representation> listRepresentationVersions(String globalId, String schema); @Override boolean putContent(String globalId, String schema, String version, File file, InputStream content); @Override Consumer<OutputStream> getContent(String globalId, String schema, String version, String fileName, long rangeStart,
long rangeEnd); @Override String getContent(String globalId, String schema, String version, String fileName, OutputStream os); @Override void deleteContent(String globalId, String schema, String version, String fileName); @Override Representation copyRepresentation(String globalId, String schema, String version); @Override File getFile(String globalId, String schema, String version, String fileName); @Override void addRevision(String globalId, String schema, String version, Revision revision); @Override List<RepresentationRevisionResponse> getRepresentationRevisions(String globalId, String schema, String revisionProviderId, String revisionName, Date revisionTimestamp); @Override void insertRepresentationRevision(String globalId, String schema, String revisionProviderId, String revisionName, String versionId, Date revisionTimestamp); @Override Revision getRevision(String globalId, String schema, String version, String revisionKey); } | @Test(expected = RecordNotExistsException.class) public void shouldThrowExpWhileGettingRecordIfNoRecordInUis() throws Exception { makeUISThrowRecordNotExist(); cassandraRecordService.getRecord("globalId"); }
@Test(expected = SystemException.class) public void shouldThrowSystemExpWhileGettingRecordIfUisFails() throws Exception { makeUISThrowSystemException(); cassandraRecordService.getRecord("globalId"); } |
CassandraRecordService implements RecordService { @Override public void deleteRecord(String cloudId) throws RecordNotExistsException, RepresentationNotExistsException { if (uis.existsCloudId(cloudId)) { List<Representation> allRecordRepresentationsInAllVersions = recordDAO.listRepresentationVersions(cloudId); if (allRecordRepresentationsInAllVersions.isEmpty()) { throw new RepresentationNotExistsException(String.format( "No representation found for given cloudId %s", cloudId)); } sortByProviderId(allRecordRepresentationsInAllVersions); String dPId = null; for (Representation repVersion : allRecordRepresentationsInAllVersions) { removeFilesFromRepresentationVersion(cloudId, repVersion); removeRepresentationAssignmentFromDataSets(cloudId, repVersion); deleteRepresentationRevision(cloudId, repVersion); recordDAO.deleteRepresentation(cloudId, repVersion.getRepresentationName(), repVersion.getVersion()); } } else { throw new RecordNotExistsException(cloudId); } } @Override Record getRecord(String cloudId); @Override void deleteRecord(String cloudId); @Override void deleteRepresentation(String globalId, String schema); @Override Representation createRepresentation(String cloudId, String representationName, String providerId); @Override Representation getRepresentation(String globalId, String schema); @Override Representation getRepresentation(String globalId, String schema, String version); @Override void deleteRepresentation(String globalId, String schema, String version); @Override Representation persistRepresentation(String globalId, String schema, String version); @Override List<Representation> listRepresentationVersions(String globalId, String schema); @Override boolean putContent(String globalId, String schema, String version, File file, InputStream content); @Override Consumer<OutputStream> getContent(String globalId, String schema, String version, String fileName, long rangeStart,
long rangeEnd); @Override String getContent(String globalId, String schema, String version, String fileName, OutputStream os); @Override void deleteContent(String globalId, String schema, String version, String fileName); @Override Representation copyRepresentation(String globalId, String schema, String version); @Override File getFile(String globalId, String schema, String version, String fileName); @Override void addRevision(String globalId, String schema, String version, Revision revision); @Override List<RepresentationRevisionResponse> getRepresentationRevisions(String globalId, String schema, String revisionProviderId, String revisionName, Date revisionTimestamp); @Override void insertRepresentationRevision(String globalId, String schema, String revisionProviderId, String revisionName, String versionId, Date revisionTimestamp); @Override Revision getRevision(String globalId, String schema, String version, String revisionKey); } | @Test(expected = RecordNotExistsException.class) public void shouldThrowExpWhileDeletingRecordIfNoRecordInUis() throws Exception { makeUISThrowRecordNotExist(); cassandraRecordService.deleteRecord("globalId"); }
@Test(expected = SystemException.class) public void shouldThrowSystemExpWhileDeletingRecordIfUisFails() throws Exception { makeUISThrowSystemException(); cassandraRecordService.deleteRecord("globalId"); }
@Test(expected = RepresentationNotExistsException.class) public void shouldThrowExcWhenDeletingRecordHasNoRepresentations() throws Exception { makeUISSuccess(); mockUISProvider1Success(); cassandraRecordService.deleteRecord("globalId"); } |
CassandraRecordService implements RecordService { @Override public Representation getRepresentation(String globalId, String schema) throws RepresentationNotExistsException { Representation rep = recordDAO.getLatestPersistentRepresentation(globalId, schema); if (rep == null) { throw new RepresentationNotExistsException(); } else { return rep; } } @Override Record getRecord(String cloudId); @Override void deleteRecord(String cloudId); @Override void deleteRepresentation(String globalId, String schema); @Override Representation createRepresentation(String cloudId, String representationName, String providerId); @Override Representation getRepresentation(String globalId, String schema); @Override Representation getRepresentation(String globalId, String schema, String version); @Override void deleteRepresentation(String globalId, String schema, String version); @Override Representation persistRepresentation(String globalId, String schema, String version); @Override List<Representation> listRepresentationVersions(String globalId, String schema); @Override boolean putContent(String globalId, String schema, String version, File file, InputStream content); @Override Consumer<OutputStream> getContent(String globalId, String schema, String version, String fileName, long rangeStart,
long rangeEnd); @Override String getContent(String globalId, String schema, String version, String fileName, OutputStream os); @Override void deleteContent(String globalId, String schema, String version, String fileName); @Override Representation copyRepresentation(String globalId, String schema, String version); @Override File getFile(String globalId, String schema, String version, String fileName); @Override void addRevision(String globalId, String schema, String version, Revision revision); @Override List<RepresentationRevisionResponse> getRepresentationRevisions(String globalId, String schema, String revisionProviderId, String revisionName, Date revisionTimestamp); @Override void insertRepresentationRevision(String globalId, String schema, String revisionProviderId, String revisionName, String versionId, Date revisionTimestamp); @Override Revision getRevision(String globalId, String schema, String version, String revisionKey); } | @Test(expected = RepresentationNotExistsException.class) public void shouldThrowRepresentationNotFoundExpWhenNoSuchRepresentation() throws Exception { makeUISSuccess(); cassandraRecordService.getRepresentation("globalId", "not_existing_schema"); } |
CustomFileNameMigrator extends SwiftMigrator { @Override public String nameConversion(final String s) { return s.contains("|") ? s.replace("|", "_") : null; } @Override String nameConversion(final String s); } | @Test public void shouldRetrunNullString() { final String fileName = ""; final String output = migrator.nameConversion(fileName); assertEquals(null, output); }
@Test public void shouldConvertFileProperly() { final String fileName = "test2|test1|tes2"; final String output = migrator.nameConversion(fileName); assertEquals("test2_test1_tes2", output); }
@Test public void shouldConvertFileProperly2() { final String fileName = "test2_test1|tes2"; final String output = migrator.nameConversion(fileName); assertEquals("test2_test1_tes2", output); } |
CassandraRecordService implements RecordService { @Override public void deleteRepresentation(String globalId, String schema) throws RepresentationNotExistsException { List<Representation> listRepresentations = recordDAO.listRepresentationVersions(globalId, schema); sortByProviderId(listRepresentations); String dPId = null; for (Representation rep : listRepresentations) { removeFilesFromRepresentationVersion(globalId, rep); removeRepresentationAssignmentFromDataSets(globalId, rep); deleteRepresentationRevision(globalId, rep); } recordDAO.deleteRepresentation(globalId, schema); } @Override Record getRecord(String cloudId); @Override void deleteRecord(String cloudId); @Override void deleteRepresentation(String globalId, String schema); @Override Representation createRepresentation(String cloudId, String representationName, String providerId); @Override Representation getRepresentation(String globalId, String schema); @Override Representation getRepresentation(String globalId, String schema, String version); @Override void deleteRepresentation(String globalId, String schema, String version); @Override Representation persistRepresentation(String globalId, String schema, String version); @Override List<Representation> listRepresentationVersions(String globalId, String schema); @Override boolean putContent(String globalId, String schema, String version, File file, InputStream content); @Override Consumer<OutputStream> getContent(String globalId, String schema, String version, String fileName, long rangeStart,
long rangeEnd); @Override String getContent(String globalId, String schema, String version, String fileName, OutputStream os); @Override void deleteContent(String globalId, String schema, String version, String fileName); @Override Representation copyRepresentation(String globalId, String schema, String version); @Override File getFile(String globalId, String schema, String version, String fileName); @Override void addRevision(String globalId, String schema, String version, Revision revision); @Override List<RepresentationRevisionResponse> getRepresentationRevisions(String globalId, String schema, String revisionProviderId, String revisionName, Date revisionTimestamp); @Override void insertRepresentationRevision(String globalId, String schema, String revisionProviderId, String revisionName, String versionId, Date revisionTimestamp); @Override Revision getRevision(String globalId, String schema, String version, String revisionKey); } | @Test public void shouldDeletePersistentRepresentation() throws Exception { makeUISSuccess(); mockUISProvider1Success(); Representation r = insertDummyPersistentRepresentation("globalId", "dc", PROVIDER_1_ID); cassandraRecordService.deleteRepresentation(r.getCloudId(), r.getRepresentationName(), r.getVersion()); } |
CassandraRecordService implements RecordService { @Override public boolean putContent(String globalId, String schema, String version, File file, InputStream content) throws CannotModifyPersistentRepresentationException, RepresentationNotExistsException { DateTime now = new DateTime(); Representation representation = getRepresentation(globalId, schema, version); if (representation.isPersistent()) { throw new CannotModifyPersistentRepresentationException(); } boolean isCreate = true; for (File f : representation.getFiles()) { if (f.getFileName().equals(file.getFileName())) { isCreate = false; break; } } String keyForFile = FileUtils.generateKeyForFile(globalId, schema, version, file.getFileName()); PutResult result; try { result = contentDAO.putContent(keyForFile, content, file.getFileStorage()); } catch (IOException ex) { throw new SystemException(ex); } file.setMd5(result.getMd5()); DateTimeFormatter fmt = ISODateTimeFormat.dateTime(); file.setDate(fmt.print(now)); file.setContentLength(result.getContentLength()); recordDAO.addOrReplaceFileInRepresentation(globalId, schema, version, file); for (Revision revision : representation.getRevisions()) { recordDAO.addOrReplaceFileInRepresentationRevision(globalId, schema, version, revision.getRevisionProviderId(), revision.getRevisionName(), revision.getCreationTimeStamp(), file); } return isCreate; } @Override Record getRecord(String cloudId); @Override void deleteRecord(String cloudId); @Override void deleteRepresentation(String globalId, String schema); @Override Representation createRepresentation(String cloudId, String representationName, String providerId); @Override Representation getRepresentation(String globalId, String schema); @Override Representation getRepresentation(String globalId, String schema, String version); @Override void deleteRepresentation(String globalId, String schema, String version); @Override Representation persistRepresentation(String globalId, String schema, String version); @Override List<Representation> listRepresentationVersions(String globalId, String schema); @Override boolean putContent(String globalId, String schema, String version, File file, InputStream content); @Override Consumer<OutputStream> getContent(String globalId, String schema, String version, String fileName, long rangeStart,
long rangeEnd); @Override String getContent(String globalId, String schema, String version, String fileName, OutputStream os); @Override void deleteContent(String globalId, String schema, String version, String fileName); @Override Representation copyRepresentation(String globalId, String schema, String version); @Override File getFile(String globalId, String schema, String version, String fileName); @Override void addRevision(String globalId, String schema, String version, Revision revision); @Override List<RepresentationRevisionResponse> getRepresentationRevisions(String globalId, String schema, String revisionProviderId, String revisionName, Date revisionTimestamp); @Override void insertRepresentationRevision(String globalId, String schema, String revisionProviderId, String revisionName, String versionId, Date revisionTimestamp); @Override Revision getRevision(String globalId, String schema, String version, String revisionKey); } | @Test(expected = CannotModifyPersistentRepresentationException.class) public void shouldNotAddFileToPersistentRepresentation() throws Exception { makeUISSuccess(); mockUISProvider1Success(); Representation r = insertDummyPersistentRepresentation("globalId", "dc", PROVIDER_1_ID); byte[] dummyContent = {1, 2, 3}; File f = new File("content.xml", "application/xml", null, null, 0, null, OBJECT_STORAGE); cassandraRecordService.putContent(r.getCloudId(), r.getRepresentationName(), r.getVersion(), f, new ByteArrayInputStream(dummyContent)); } |
CassandraRecordService implements RecordService { @Override public void deleteContent(String globalId, String schema, String version, String fileName) throws FileNotExistsException, CannotModifyPersistentRepresentationException, RepresentationNotExistsException { Representation representation = getRepresentation(globalId, schema, version); if (representation.isPersistent()) { throw new CannotModifyPersistentRepresentationException(); } recordDAO.removeFileFromRepresentation(globalId, schema, version, fileName); recordDAO.removeFileFromRepresentationRevisionsTable(representation, fileName); File file = findFileInRepresentation(representation, fileName); contentDAO.deleteContent(FileUtils.generateKeyForFile(globalId, schema, version, fileName), file.getFileStorage()); } @Override Record getRecord(String cloudId); @Override void deleteRecord(String cloudId); @Override void deleteRepresentation(String globalId, String schema); @Override Representation createRepresentation(String cloudId, String representationName, String providerId); @Override Representation getRepresentation(String globalId, String schema); @Override Representation getRepresentation(String globalId, String schema, String version); @Override void deleteRepresentation(String globalId, String schema, String version); @Override Representation persistRepresentation(String globalId, String schema, String version); @Override List<Representation> listRepresentationVersions(String globalId, String schema); @Override boolean putContent(String globalId, String schema, String version, File file, InputStream content); @Override Consumer<OutputStream> getContent(String globalId, String schema, String version, String fileName, long rangeStart,
long rangeEnd); @Override String getContent(String globalId, String schema, String version, String fileName, OutputStream os); @Override void deleteContent(String globalId, String schema, String version, String fileName); @Override Representation copyRepresentation(String globalId, String schema, String version); @Override File getFile(String globalId, String schema, String version, String fileName); @Override void addRevision(String globalId, String schema, String version, Revision revision); @Override List<RepresentationRevisionResponse> getRepresentationRevisions(String globalId, String schema, String revisionProviderId, String revisionName, Date revisionTimestamp); @Override void insertRepresentationRevision(String globalId, String schema, String revisionProviderId, String revisionName, String versionId, Date revisionTimestamp); @Override Revision getRevision(String globalId, String schema, String version, String revisionKey); } | @Test(expected = CannotModifyPersistentRepresentationException.class) public void shouldNotRemoveFileFromPersistentRepresentation() throws Exception { makeUISSuccess(); mockUISProvider1Success(); Representation r = insertDummyPersistentRepresentation("globalId", "dc", PROVIDER_1_ID); File f = r.getFiles().get(0); cassandraRecordService.deleteContent(r.getCloudId(), r.getRepresentationName(), r.getVersion(), f.getFileName()); } |
CassandraRecordService implements RecordService { @Override public void addRevision(String globalId, String schema, String version, Revision revision) throws RevisionIsNotValidException { recordDAO.addOrReplaceRevisionInRepresentation(globalId, schema, version, revision); } @Override Record getRecord(String cloudId); @Override void deleteRecord(String cloudId); @Override void deleteRepresentation(String globalId, String schema); @Override Representation createRepresentation(String cloudId, String representationName, String providerId); @Override Representation getRepresentation(String globalId, String schema); @Override Representation getRepresentation(String globalId, String schema, String version); @Override void deleteRepresentation(String globalId, String schema, String version); @Override Representation persistRepresentation(String globalId, String schema, String version); @Override List<Representation> listRepresentationVersions(String globalId, String schema); @Override boolean putContent(String globalId, String schema, String version, File file, InputStream content); @Override Consumer<OutputStream> getContent(String globalId, String schema, String version, String fileName, long rangeStart,
long rangeEnd); @Override String getContent(String globalId, String schema, String version, String fileName, OutputStream os); @Override void deleteContent(String globalId, String schema, String version, String fileName); @Override Representation copyRepresentation(String globalId, String schema, String version); @Override File getFile(String globalId, String schema, String version, String fileName); @Override void addRevision(String globalId, String schema, String version, Revision revision); @Override List<RepresentationRevisionResponse> getRepresentationRevisions(String globalId, String schema, String revisionProviderId, String revisionName, Date revisionTimestamp); @Override void insertRepresentationRevision(String globalId, String schema, String revisionProviderId, String revisionName, String versionId, Date revisionTimestamp); @Override Revision getRevision(String globalId, String schema, String version, String revisionKey); } | @Test public void addRevision() throws Exception { makeUISSuccess(); mockUISProvider1Success(); Representation r = cassandraRecordService.createRepresentation( "globalId", "edm", PROVIDER_1_ID); Revision revision = new Revision(REVISION_NAME, REVISION_PROVIDER); cassandraRecordService.addRevision(r.getCloudId(), r.getRepresentationName(), r.getVersion(), revision); r = cassandraRecordService.getRepresentation(r.getCloudId(), r.getRepresentationName(), r.getVersion()); assertNotNull(r.getRevisions()); assertFalse(r.getRevisions().isEmpty()); assertEquals(r.getRevisions().size(), 1); } |
CassandraRecordService implements RecordService { @Override public Revision getRevision(String globalId, String schema, String version, String revisionKey) throws RevisionNotExistsException, RepresentationNotExistsException { Representation rep = getRepresentation(globalId, schema, version); for (Revision revision : rep.getRevisions()) { if (revision != null) { if (RevisionUtils.getRevisionKey(revision).equals(revisionKey)) { return revision; } } } throw new RevisionNotExistsException(); } @Override Record getRecord(String cloudId); @Override void deleteRecord(String cloudId); @Override void deleteRepresentation(String globalId, String schema); @Override Representation createRepresentation(String cloudId, String representationName, String providerId); @Override Representation getRepresentation(String globalId, String schema); @Override Representation getRepresentation(String globalId, String schema, String version); @Override void deleteRepresentation(String globalId, String schema, String version); @Override Representation persistRepresentation(String globalId, String schema, String version); @Override List<Representation> listRepresentationVersions(String globalId, String schema); @Override boolean putContent(String globalId, String schema, String version, File file, InputStream content); @Override Consumer<OutputStream> getContent(String globalId, String schema, String version, String fileName, long rangeStart,
long rangeEnd); @Override String getContent(String globalId, String schema, String version, String fileName, OutputStream os); @Override void deleteContent(String globalId, String schema, String version, String fileName); @Override Representation copyRepresentation(String globalId, String schema, String version); @Override File getFile(String globalId, String schema, String version, String fileName); @Override void addRevision(String globalId, String schema, String version, Revision revision); @Override List<RepresentationRevisionResponse> getRepresentationRevisions(String globalId, String schema, String revisionProviderId, String revisionName, Date revisionTimestamp); @Override void insertRepresentationRevision(String globalId, String schema, String revisionProviderId, String revisionName, String versionId, Date revisionTimestamp); @Override Revision getRevision(String globalId, String schema, String version, String revisionKey); } | @Test public void getRevision() throws Exception { makeUISSuccess(); mockUISProvider1Success(); Representation r = cassandraRecordService.createRepresentation( "globalId", "edm", PROVIDER_1_ID); Revision revision = new Revision(REVISION_NAME, REVISION_PROVIDER, new Date(), true, false, true); cassandraRecordService.addRevision(r.getCloudId(), r.getRepresentationName(), r.getVersion(), revision); String revisionKey = RevisionUtils.getRevisionKey(revision); Revision storedRevision = cassandraRecordService.getRevision(r.getCloudId(), r.getRepresentationName(), r.getVersion(), revisionKey); assertNotNull(storedRevision); assertThat(storedRevision, is(revision)); }
@Test(expected = RepresentationNotExistsException.class) public void getRevisionFromNonExistedRepresentation() throws Exception { makeUISSuccess(); mockUISProvider1Success(); String revisionKey = RevisionUtils.getRevisionKey(REVISION_PROVIDER, REVISION_NAME, new Date().getTime()); cassandraRecordService.getRevision("globalId", "not_existing_schema", "5573dbf0-5979-11e6-9061-1c6f653f9042", revisionKey); } |
InMemoryDataSetService implements DataSetService { @Override public ResultSlice<Representation> listDataSet(String providerId, String dataSetId, String thresholdParam, int limit) throws DataSetNotExistsException { int treshold = 0; if (thresholdParam != null) { treshold = parseInteger(thresholdParam); } List<Representation> listOfAllStubs = dataSetDAO.listDataSet(providerId, dataSetId); if (listOfAllStubs.size() != 0 && treshold >= listOfAllStubs.size()) { throw new IllegalArgumentException("Illegal threshold param value: '" + thresholdParam + "'."); } int newOffset = -1; List<Representation> listOfStubs = listOfAllStubs; if (limit > 0) { listOfStubs = listOfAllStubs.subList(treshold, Math.min(treshold + limit, listOfAllStubs.size())); if (listOfAllStubs.size() > treshold + limit) { newOffset = treshold + limit; } } List<Representation> toReturn = new ArrayList<>(listOfStubs.size()); for (Representation stub : listOfStubs) { Representation realContent; try { realContent = recordDAO.getRepresentation(stub.getCloudId(), stub.getRepresentationName(), stub.getVersion()); } catch (RepresentationNotExistsException e) { continue; } toReturn.add(realContent); } return newOffset == -1 ? new ResultSlice<>(null, toReturn) : new ResultSlice<>(Integer.toString(newOffset), toReturn); } InMemoryDataSetService(InMemoryDataSetDAO dataSetDAO, InMemoryRecordDAO recordDAO,
UISClientHandler dataProviderDao); InMemoryDataSetService(); @Override ResultSlice<Representation> listDataSet(String providerId, String dataSetId, String thresholdParam, int limit); @Override void addAssignment(String providerId, String dataSetId, String recordId, String schema, String version); @Override void removeAssignment(String providerId, String dataSetId, String recordId, String schema); @Override DataSet createDataSet(String providerId, String dataSetId, String description); @Override ResultSlice<DataSet> getDataSets(String providerId, String thresholdDatasetId, int limit); @Override void deleteDataSet(String providerId, String dataSetId); @Override DataSet updateDataSet(String providerId, String dataSetId, String description); } | @Test @Parameters(method = "listDatasetParams") public void shouldListDataSet(String threshold, int limit, String nextSlice, int fromIndex, int toIndex) throws Exception { ResultSlice<Representation> actual = dataSetService.listDataSet(providerId, dataSetId, threshold, limit); assertThat("Next slice should be equal '" + nextSlice + "' but was '" + actual.getNextSlice() + "'", actual.getNextSlice(), equalTo(nextSlice)); assertThat("Lists of representations are not equal", actual.getResults(), equalTo(representations.subList(fromIndex, toIndex))); }
@Test public void shouldListEmptyDataSet() throws Exception { when(datasetDao.listDataSet(providerId, dataSetId)).thenReturn(new ArrayList<Representation>()); InMemoryRecordDAO recordDao = new InMemoryRecordListDAO(new ArrayList<Representation>()); dataSetService = new InMemoryDataSetService(datasetDao, recordDao, uisHandler); ResultSlice<Representation> actual = dataSetService.listDataSet(providerId, dataSetId, null, 100); assertThat("Next slice should be null, but was '" + actual.getNextSlice() + "'", actual.getNextSlice(), nullValue()); assertTrue("List of representations should be empty, but was: " + actual.getResults(), actual.getResults() .isEmpty()); } |
InMemoryRecordService implements RecordService { public ResultSlice<Representation> search(RepresentationSearchParams searchParams, String thresholdParam, int limit) { int threshold = 0; if (thresholdParam != null) { threshold = parseInteger(thresholdParam); } String providerId = searchParams.getDataProvider(); String schema = searchParams.getSchema(); String dataSetId = searchParams.getDataSetId(); List<Representation> allRecords; if (providerId != null && dataSetId != null) { List<Representation> toReturn = new ArrayList<>(); try { List<Representation> representationStubs = dataSetDAO.listDataSet(providerId, dataSetId); for (Representation stub : representationStubs) { if (schema == null || schema.equals(stub.getRepresentationName())) { Representation realContent; try { realContent = recordDAO.getRepresentation(stub.getCloudId(), stub.getRepresentationName(), stub.getVersion()); toReturn.add(realContent); } catch (RepresentationNotExistsException ex) { } } } } catch (DataSetNotExistsException ex) { allRecords = Collections.emptyList(); } allRecords = toReturn; } else { allRecords = recordDAO.findRepresentations(providerId, schema); } if (allRecords.size() != 0 && threshold >= allRecords.size()) { throw new IllegalArgumentException("Illegal threshold param value: '" + thresholdParam + "'."); } return prepareResultSlice(limit, threshold, allRecords); } InMemoryRecordService(); InMemoryRecordService(InMemoryRecordDAO recordDAO, InMemoryContentDAO contentDAO,
InMemoryDataSetDAO dataSetDAO, UISClientHandler uisHandler); @Override Record getRecord(String globalId); @Override void deleteRecord(String globalId); @Override void deleteRepresentation(String globalId, String schema); @Override Representation createRepresentation(String globalId, String representationName, String providerId); @Override Representation getRepresentation(String globalId, String schema); @Override Representation getRepresentation(String globalId, String schema, String version); @Override void deleteRepresentation(String globalId, String schema, String version); @Override Representation persistRepresentation(String globalId, String schema, String version); @Override List<Representation> listRepresentationVersions(String globalId, String schema); @Override boolean putContent(String globalId, String schema, String version, File file, InputStream content); @Override void getContent(String globalId, String schema, String version, String fileName, long rangeStart,
long rangeEnd, OutputStream os); @Override String getContent(String globalId, String schema, String version, String fileName, OutputStream os); @Override void deleteContent(String globalId, String schema, String version, String fileName); @Override Representation copyRepresentation(String globalId, String schema, String version); ResultSlice<Representation> search(RepresentationSearchParams searchParams, String thresholdParam, int limit); @Override File getFile(String globalId, String schema, String version, String fileName); } | @Test @Parameters(method = "searchRepresentatonsParams") public void shouldSearchRepresentations(String threshold, int limit, int fromIndex, int toIndex, String nextSlice) { List<Representation> representations = createRepresentations(5, PROVIDER_ID, SCHEMA); when(recordDAO.findRepresentations(PROVIDER_ID, SCHEMA)).thenReturn(representations); InMemoryRecordService recordService = new InMemoryRecordService(recordDAO, null, null, null); RepresentationSearchParams searchParams = RepresentationSearchParams.builder().setDataProvider(PROVIDER_ID) .setSchema(SCHEMA).build(); ResultSlice<Representation> actual = recordService.search(searchParams, threshold, limit); assertEquals("List of representations are not equal. ", representations.subList(fromIndex, toIndex), actual.getResults()); assertEquals("Next slice ", actual.getNextSlice(), nextSlice); } |
DataSetServiceClient extends MCSClient { public ResultSlice<DataSet> getDataSetsForProviderChunk(String providerId, String startFrom) throws MCSException { WebTarget target = client .target(this.baseUrl) .path(DATA_SETS_RESOURCE) .resolveTemplate(PROVIDER_ID, providerId); if (startFrom != null) { target = target.queryParam(ParamConstants.F_START_FROM, startFrom); } return prepareResultSliceResponse(target); } DataSetServiceClient(String baseUrl); DataSetServiceClient(String baseUrl, final String authorization); DataSetServiceClient(String baseUrl, final String username, final String password); DataSetServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); ResultSlice<DataSet> getDataSetsForProviderChunk(String providerId, String startFrom); List<DataSet> getDataSetsForProvider(String providerId); DataSetIterator getDataSetIteratorForProvider(String providerId); URI createDataSet(String providerId, String dataSetId, String description); ResultSlice<Representation> getDataSetRepresentationsChunk(
String providerId, String dataSetId, String startFrom); List<Representation> getDataSetRepresentations(String providerId, String dataSetId); RepresentationIterator getRepresentationIterator(String providerId, String dataSetId); void updateDescriptionOfDataSet(String providerId, String dataSetId, String description); void deleteDataSet(String providerId, String dataSetId); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName,
String version, String key, String value); void unassignRepresentationFromDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); ResultSlice<CloudTagsResponse> getDataSetRevisionsChunk(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp,
String startFrom, Integer limit); List<CloudTagsResponse> getDataSetRevisions(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp); ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationChunk(String dataSetId, String providerId, String representationName, String dateFrom, String tag, String startFrom); List<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentation(String dataSetId, String providerId,
String representationName, String dateFrom, String tag); ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevisionChunk(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted, String startFrom); List<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted); String getLatelyTaggedRecords(
String dataSetId, String providerId, String cloudId, String representationName,
String revisionName, String revisionProviderId); void useAuthorizationHeader(final String headerValue); void close(); } | @Betamax(tape = "dataSets_shouldRetrieveDataSetsFirstChunk") @Test public void shouldRetrieveDataSetsFirstChunk() throws MCSException { String providerId = "Provider002"; int resultSize = 100; String startFrom = "dataset000101"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); ResultSlice<DataSet> result = instance.getDataSetsForProviderChunk(providerId, null); assertNotNull(result.getResults()); assertEquals(result.getResults().size(), resultSize); assertEquals(result.getNextSlice(), startFrom); }
@Betamax(tape = "dataSets_shouldRetrieveDataSetsSecondChunk") @Test public void shouldRetrieveDataSetsSecondChunk() throws MCSException { String providerId = "Provider002"; int resultSize = 100; String startFrom = "dataset000101"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); ResultSlice<DataSet> result = instance.getDataSetsForProviderChunk(providerId, startFrom); assertNotNull(result.getResults()); assertEquals(result.getResults().size(), resultSize); assertNull(result.getNextSlice()); }
@Betamax(tape = "dataSets_shouldNotThrowProviderNotExistsForDataSetsChunk") @Test public void shouldNotThrowProviderNotExistsForDataSetsChunk() throws MCSException { String providerId = "notFoundProviderId"; String startFrom = null; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); ResultSlice<DataSet> result = instance.getDataSetsForProviderChunk(providerId, startFrom); assertNotNull(result.getResults()); assertEquals(result.getResults().size(), 0); }
@Betamax(tape = "dataSets_shouldThrowDriverExceptionForGetDataSetsChunk") @Test(expected = DriverException.class) public void shouldThrowDriverExceptionForGetDataSetsChunk() throws MCSException { String providerId = "Provider001"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); instance.getDataSetsForProviderChunk(providerId, null); }
@Betamax(tape = "dataSets_shouldThrowDriverExceptionForGetDataSets") @Test(expected = DriverException.class) public void shouldThrowDriverExceptionForGetDataSets() throws MCSException { String providerId = "Provider001"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); instance.getDataSetsForProviderChunk(providerId, null); } |
DataSetServiceClient extends MCSClient { public List<DataSet> getDataSetsForProvider(String providerId) throws MCSException { List<DataSet> resultList = new ArrayList<>(); ResultSlice resultSlice; String startFrom = null; do { resultSlice = getDataSetsForProviderChunk(providerId, startFrom); if (resultSlice == null || resultSlice.getResults() == null) { throw new DriverException("Getting DataSet: result chunk obtained but is empty."); } resultList.addAll(resultSlice.getResults()); startFrom = resultSlice.getNextSlice(); } while (resultSlice.getNextSlice() != null); return resultList; } DataSetServiceClient(String baseUrl); DataSetServiceClient(String baseUrl, final String authorization); DataSetServiceClient(String baseUrl, final String username, final String password); DataSetServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); ResultSlice<DataSet> getDataSetsForProviderChunk(String providerId, String startFrom); List<DataSet> getDataSetsForProvider(String providerId); DataSetIterator getDataSetIteratorForProvider(String providerId); URI createDataSet(String providerId, String dataSetId, String description); ResultSlice<Representation> getDataSetRepresentationsChunk(
String providerId, String dataSetId, String startFrom); List<Representation> getDataSetRepresentations(String providerId, String dataSetId); RepresentationIterator getRepresentationIterator(String providerId, String dataSetId); void updateDescriptionOfDataSet(String providerId, String dataSetId, String description); void deleteDataSet(String providerId, String dataSetId); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName,
String version, String key, String value); void unassignRepresentationFromDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); ResultSlice<CloudTagsResponse> getDataSetRevisionsChunk(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp,
String startFrom, Integer limit); List<CloudTagsResponse> getDataSetRevisions(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp); ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationChunk(String dataSetId, String providerId, String representationName, String dateFrom, String tag, String startFrom); List<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentation(String dataSetId, String providerId,
String representationName, String dateFrom, String tag); ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevisionChunk(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted, String startFrom); List<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted); String getLatelyTaggedRecords(
String dataSetId, String providerId, String cloudId, String representationName,
String revisionName, String revisionProviderId); void useAuthorizationHeader(final String headerValue); void close(); } | @Betamax(tape = "dataSets_shouldReturnAllDataSets") @Test public void shouldReturnAllDataSets() throws MCSException { String providerId = "Provider002"; int resultSize = 200; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); List<DataSet> result = instance.getDataSetsForProvider(providerId); assertNotNull(result); assertEquals(result.size(), resultSize); }
@Betamax(tape = "dataSets_shouldNotThrowProviderNotExistsForDataSetsAll") @Test public void shouldNotThrowProviderNotExistsForDataSetsAll() throws MCSException { String providerId = "notFoundProviderId"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); List<DataSet> result = instance.getDataSetsForProvider(providerId); assertNotNull(result); assertEquals(result.size(), 0); } |
DataSetServiceClient extends MCSClient { public URI createDataSet(String providerId, String dataSetId, String description) throws MCSException { WebTarget target = client .target(this.baseUrl) .path(DATA_SETS_RESOURCE) .resolveTemplate(PROVIDER_ID, providerId); Form form = new Form(); form.param(ParamConstants.F_DATASET, dataSetId); form.param(ParamConstants.F_DESCRIPTION, description); Response response = null; try { response = target .request() .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE)); if (response.getStatus() == Status.CREATED.getStatusCode()) { return response.getLocation(); } ErrorInfo errorInfo = response.readEntity(ErrorInfo.class); throw MCSExceptionProvider.generateException(errorInfo); } finally { if (response != null) { response.close(); } } } DataSetServiceClient(String baseUrl); DataSetServiceClient(String baseUrl, final String authorization); DataSetServiceClient(String baseUrl, final String username, final String password); DataSetServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); ResultSlice<DataSet> getDataSetsForProviderChunk(String providerId, String startFrom); List<DataSet> getDataSetsForProvider(String providerId); DataSetIterator getDataSetIteratorForProvider(String providerId); URI createDataSet(String providerId, String dataSetId, String description); ResultSlice<Representation> getDataSetRepresentationsChunk(
String providerId, String dataSetId, String startFrom); List<Representation> getDataSetRepresentations(String providerId, String dataSetId); RepresentationIterator getRepresentationIterator(String providerId, String dataSetId); void updateDescriptionOfDataSet(String providerId, String dataSetId, String description); void deleteDataSet(String providerId, String dataSetId); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName,
String version, String key, String value); void unassignRepresentationFromDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); ResultSlice<CloudTagsResponse> getDataSetRevisionsChunk(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp,
String startFrom, Integer limit); List<CloudTagsResponse> getDataSetRevisions(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp); ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationChunk(String dataSetId, String providerId, String representationName, String dateFrom, String tag, String startFrom); List<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentation(String dataSetId, String providerId,
String representationName, String dateFrom, String tag); ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevisionChunk(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted, String startFrom); List<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted); String getLatelyTaggedRecords(
String dataSetId, String providerId, String cloudId, String representationName,
String revisionName, String revisionProviderId); void useAuthorizationHeader(final String headerValue); void close(); } | @Betamax(tape = "dataSets_shouldSuccessfullyCreateDataSet") @Test public void shouldSuccessfullyCreateDataSet() throws MCSException { String providerId = "Provider001"; String dataSetId = "dataset000008"; String description = "description01"; String expectedLocation = baseUrl + "/data-providers/" + providerId + "/data-sets/" + dataSetId; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); URI result = instance.createDataSet(providerId, dataSetId, description); assertEquals(result.toString(), expectedLocation); }
@Betamax(tape = "dataSets_shouldThrowDataSetAlreadyExists") @Test(expected = DataSetAlreadyExistsException.class) public void shouldThrowDataSetAlreadyExists() throws MCSException { String providerId = "Provider001"; String dataSetId = "dataset000002"; String description = "description"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); instance.createDataSet(providerId, dataSetId, description); }
@Betamax(tape = "dataSets_shouldThrowProviderNotExists") @Test(expected = ProviderNotExistsException.class) public void shouldThrowProviderNotExists() throws MCSException { String providerId = "notFoundProviderId"; String dataSetId = "dataSetId"; String description = "description"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); instance.createDataSet(providerId, dataSetId, description); }
@Betamax(tape = "dataSets_shouldThrowDriverExceptionForCreateDataSet") @Test(expected = DriverException.class) public void shouldThrowDriverExceptionForCreateDataSet() throws MCSException { String providerId = "providerId"; String dataSetId = "dataSetId"; String description = "description"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); instance.createDataSet(providerId, dataSetId, description); } |
DataSetServiceClient extends MCSClient { public ResultSlice<Representation> getDataSetRepresentationsChunk( String providerId, String dataSetId, String startFrom) throws MCSException { WebTarget target = client .target(this.baseUrl) .path(DATA_SET_RESOURCE) .resolveTemplate(PROVIDER_ID, providerId) .resolveTemplate(DATA_SET_ID, dataSetId); if (startFrom != null) { target = target.queryParam(ParamConstants.F_START_FROM, startFrom); } Response response = null; try { response = target.request().get(); if (response.getStatus() == Status.OK.getStatusCode()) { return response.readEntity(ResultSlice.class); } ErrorInfo errorInfo = response.readEntity(ErrorInfo.class); throw MCSExceptionProvider.generateException(errorInfo); } finally { if (response != null) { response.close(); } } } DataSetServiceClient(String baseUrl); DataSetServiceClient(String baseUrl, final String authorization); DataSetServiceClient(String baseUrl, final String username, final String password); DataSetServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); ResultSlice<DataSet> getDataSetsForProviderChunk(String providerId, String startFrom); List<DataSet> getDataSetsForProvider(String providerId); DataSetIterator getDataSetIteratorForProvider(String providerId); URI createDataSet(String providerId, String dataSetId, String description); ResultSlice<Representation> getDataSetRepresentationsChunk(
String providerId, String dataSetId, String startFrom); List<Representation> getDataSetRepresentations(String providerId, String dataSetId); RepresentationIterator getRepresentationIterator(String providerId, String dataSetId); void updateDescriptionOfDataSet(String providerId, String dataSetId, String description); void deleteDataSet(String providerId, String dataSetId); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName,
String version, String key, String value); void unassignRepresentationFromDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); ResultSlice<CloudTagsResponse> getDataSetRevisionsChunk(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp,
String startFrom, Integer limit); List<CloudTagsResponse> getDataSetRevisions(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp); ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationChunk(String dataSetId, String providerId, String representationName, String dateFrom, String tag, String startFrom); List<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentation(String dataSetId, String providerId,
String representationName, String dateFrom, String tag); ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevisionChunk(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted, String startFrom); List<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted); String getLatelyTaggedRecords(
String dataSetId, String providerId, String cloudId, String representationName,
String revisionName, String revisionProviderId); void useAuthorizationHeader(final String headerValue); void close(); } | @Betamax(tape = "dataSets_shouldRetrieveRepresentationsFirstChunk") @Test public void shouldRetrieveRepresentationsFirstChunk() throws MCSException { String providerId = "Provider001"; String dataSetId = "dataset000002"; int resultSize = 100; String startFrom = "G5DFUSCILJFVGQSEJYFHGY3IMVWWCMI="; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); ResultSlice<Representation> result = instance.getDataSetRepresentationsChunk(providerId, dataSetId, null); assertNotNull(result.getResults()); assertEquals(result.getResults().size(), resultSize); assertEquals(result.getNextSlice(), startFrom); }
@Betamax(tape = "dataSets_shouldRetrieveRepresentationsSecondChunk") @Test public void shouldRetrieveRepresentationsSecondChunk() throws MCSException { String providerId = "Provider001"; String dataSetId = "dataset000002"; int resultSize = 100; String startFrom = "G5DFUSCILJFVGQSEJYFHGY3IMVWWCMI="; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); ResultSlice<Representation> result = instance.getDataSetRepresentationsChunk(providerId, dataSetId, startFrom); assertNotNull(result.getResults()); assertEquals(result.getResults().size(), resultSize); assertNull(result.getNextSlice()); }
@Betamax(tape = "dataSets_shouldThrowDataSetNotExistsForRepresentationsChunk") @Test(expected = DataSetNotExistsException.class) public void shouldThrowDataSetNotExistsForRepresentationsChunk() throws MCSException { String providerId = "Provider001"; String dataSetId = "dataset000042"; String startFrom = "G5DFUSCILJFVGQSEJYFHGY3IMVWWCMI="; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); instance.getDataSetRepresentationsChunk(providerId, dataSetId, startFrom); }
@Betamax(tape = "dataSets_shouldThrowDriverExceptionForGetRepresentationsChunk") @Test(expected = DriverException.class) public void shouldThrowDriverExceptionForGetRepresentationsChunk() throws MCSException { String providerId = "Provider001"; String dataSetId = "dataset000002"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); instance.getDataSetRepresentationsChunk(providerId, dataSetId, null); } |
DataSetServiceClient extends MCSClient { public List<Representation> getDataSetRepresentations(String providerId, String dataSetId) throws MCSException { List<Representation> resultList = new ArrayList<>(); ResultSlice<Representation> resultSlice; String startFrom = null; do { resultSlice = getDataSetRepresentationsChunk(providerId, dataSetId, startFrom); if (resultSlice == null || resultSlice.getResults() == null) { throw new DriverException("Getting DataSet: result chunk obtained but is empty."); } resultList.addAll(resultSlice.getResults()); startFrom = resultSlice.getNextSlice(); } while (resultSlice.getNextSlice() != null); return resultList; } DataSetServiceClient(String baseUrl); DataSetServiceClient(String baseUrl, final String authorization); DataSetServiceClient(String baseUrl, final String username, final String password); DataSetServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); ResultSlice<DataSet> getDataSetsForProviderChunk(String providerId, String startFrom); List<DataSet> getDataSetsForProvider(String providerId); DataSetIterator getDataSetIteratorForProvider(String providerId); URI createDataSet(String providerId, String dataSetId, String description); ResultSlice<Representation> getDataSetRepresentationsChunk(
String providerId, String dataSetId, String startFrom); List<Representation> getDataSetRepresentations(String providerId, String dataSetId); RepresentationIterator getRepresentationIterator(String providerId, String dataSetId); void updateDescriptionOfDataSet(String providerId, String dataSetId, String description); void deleteDataSet(String providerId, String dataSetId); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName,
String version, String key, String value); void unassignRepresentationFromDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); ResultSlice<CloudTagsResponse> getDataSetRevisionsChunk(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp,
String startFrom, Integer limit); List<CloudTagsResponse> getDataSetRevisions(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp); ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationChunk(String dataSetId, String providerId, String representationName, String dateFrom, String tag, String startFrom); List<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentation(String dataSetId, String providerId,
String representationName, String dateFrom, String tag); ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevisionChunk(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted, String startFrom); List<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted); String getLatelyTaggedRecords(
String dataSetId, String providerId, String cloudId, String representationName,
String revisionName, String revisionProviderId); void useAuthorizationHeader(final String headerValue); void close(); } | @Betamax(tape = "dataSets_shouldReturnAllRepresentations") @Test public void shouldReturnAllRepresentations() throws MCSException { String providerId = "Provider001"; String dataSetId = "dataset000002"; int resultSize = 200; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); List<Representation> result = instance.getDataSetRepresentations(providerId, dataSetId); assertNotNull(result); assertEquals(result.size(), resultSize); }
@Betamax(tape = "dataSets_shouldThrowDataSetNotExistsForRepresentationsAll") @Test(expected = DataSetNotExistsException.class) public void shouldThrowDataSetNotExistsForRepresentationsAll() throws MCSException { String providerId = "Provider001"; String dataSetId = "dataset000042"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); instance.getDataSetRepresentations(providerId, dataSetId); }
@Betamax(tape = "dataSets_shouldThrowDriverExceptionForGetRepresentations") @Test(expected = DriverException.class) public void shouldThrowDriverExceptionForGetRepresentations() throws MCSException { String providerId = "Provider001"; String dataSetId = "dataset000002"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); instance.getDataSetRepresentations(providerId, dataSetId); } |
DataSetServiceClient extends MCSClient { public void updateDescriptionOfDataSet(String providerId, String dataSetId, String description) throws MCSException { WebTarget target = client .target(this.baseUrl) .path(DATA_SET_RESOURCE) .resolveTemplate(PROVIDER_ID, providerId) .resolveTemplate(DATA_SET_ID, dataSetId); Form form = new Form(); form.param(ParamConstants.F_DESCRIPTION, description); Response response = null; try { response = target.request().put(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE)); if (response.getStatus() != Status.NO_CONTENT.getStatusCode()) { ErrorInfo errorInfo = response.readEntity(ErrorInfo.class); throw MCSExceptionProvider.generateException(errorInfo); } } finally { if (response != null) { response.close(); } } } DataSetServiceClient(String baseUrl); DataSetServiceClient(String baseUrl, final String authorization); DataSetServiceClient(String baseUrl, final String username, final String password); DataSetServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); ResultSlice<DataSet> getDataSetsForProviderChunk(String providerId, String startFrom); List<DataSet> getDataSetsForProvider(String providerId); DataSetIterator getDataSetIteratorForProvider(String providerId); URI createDataSet(String providerId, String dataSetId, String description); ResultSlice<Representation> getDataSetRepresentationsChunk(
String providerId, String dataSetId, String startFrom); List<Representation> getDataSetRepresentations(String providerId, String dataSetId); RepresentationIterator getRepresentationIterator(String providerId, String dataSetId); void updateDescriptionOfDataSet(String providerId, String dataSetId, String description); void deleteDataSet(String providerId, String dataSetId); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName,
String version, String key, String value); void unassignRepresentationFromDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); ResultSlice<CloudTagsResponse> getDataSetRevisionsChunk(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp,
String startFrom, Integer limit); List<CloudTagsResponse> getDataSetRevisions(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp); ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationChunk(String dataSetId, String providerId, String representationName, String dateFrom, String tag, String startFrom); List<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentation(String dataSetId, String providerId,
String representationName, String dateFrom, String tag); ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevisionChunk(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted, String startFrom); List<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted); String getLatelyTaggedRecords(
String dataSetId, String providerId, String cloudId, String representationName,
String revisionName, String revisionProviderId); void useAuthorizationHeader(final String headerValue); void close(); } | @Betamax(tape = "dataSets_shouldThrowDataSetNotExistsForUpdateDescription") @Test(expected = DataSetNotExistsException.class) public void shouldThrowDataSetNotExistsForUpdateDescription() throws MCSException { String providerId = "Provider002"; String dataSetId = "noSuchDataset"; String description = "TEST4"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); instance.updateDescriptionOfDataSet(providerId, dataSetId, description); }
@Betamax(tape = "dataSets_shouldThrowDriverExceptionForUpdateDescription") @Test(expected = DriverException.class) public void shouldThrowDriverExceptionForUpdateDescription() throws MCSException { String providerId = "Provider002"; String dataSetId = "dataset000001"; String description = "TEST3"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); instance.updateDescriptionOfDataSet(providerId, dataSetId, description); } |
Elasticsearch implements Indexer { @Override public SearchResult search(String text, String[] fields) throws ConnectionException, IndexerException { return search(text, fields, PAGE_SIZE, 0); } Elasticsearch(IndexerInformations ii); Elasticsearch(String clasterAddresses, String index, String type); protected Elasticsearch(Client client, String index, String type); @Override Object getIndexer(); @Override SupportedIndexers getIndexerName(); @Override IndexerInformations getIndexerInformations(); @Override IndexedDocument getDocument(String documentId); @Override SearchResult getMoreLikeThis(String documentId); @Override SearchResult getMoreLikeThis(String documentId, int size, int timeout); @Override SearchResult getMoreLikeThis(String documentId, String[] fields); @Override SearchResult getMoreLikeThis(String documentId, String[] fields, int size, int timeout); @Override SearchResult getMoreLikeThis(String documentId, String[] fields, int maxQueryTerms, int minTermFreq,
int minDocFreq, int maxDocFreq, int minWordLength, int maxWordLength, int size, int timeout, Boolean includeItself); @Override SearchResult search(String text, String[] fields); @Override SearchResult search(String text, String[] fields, int size, int timeout); @Override SearchResult searchFullText(String text); @Override SearchResult searchFullText(String text, int size, int timeout); @Override SearchResult searchPhraseInFullText(String text, int slop); @Override SearchResult searchPhrase(String text, String field, int slop); @Override SearchResult searchPhrase(String text, String field, int slop, int size, int timeout); @Override SearchResult advancedSearch(String query); @Override SearchResult advancedSearch(String query, int size, int timeout); @Override SearchResult advancedSearch(String query, Map<String, Object> parameters); @Override SearchResult advancedSearch(String query, Map<String, Object> parameters, int size, int timeout); @Override void insert(String data); @Override void insert(Map<String, Object> data); @Override void insert(String documentId, String data); @Override void insert(String documentId, Map<String, Object> data); @Override void update(String documentId, String data); @Override void update(String documentId, Map<String, Object> data); @Override void delete(String documentId); @Override SearchResult getNextPage(String scrollId, Object context); } | @Test public void searchTest() throws IndexerException { boolean ok = false; int i = 0; do { try { createIndex("test"); client().prepareIndex("test", "type", "1").setSource("field1", "value1").execute().actionGet(); client().prepareIndex("test", "type", "2").setSource("field1", "value2").execute().actionGet(); client().prepareIndex("test", "type", "3").setSource(IndexFields.RAW_TEXT, "some full text with lot of informations").execute().actionGet(); client().prepareIndex("test", "type", "4").setSource(IndexFields.RAW_TEXT, "dog is an animal").execute().actionGet(); client().prepareIndex("test", "type", "5").setSource("field1", "value3", "field2", "value1 and value2").execute().actionGet(); client().prepareIndex("test", "type", "6").setSource("field1", "value4", "field2", "value5").execute().actionGet(); client().prepareIndex("test", "type", "7").setSource("field3", "my phrase").execute().actionGet(); client().prepareIndex("test", "type", "8").setSource("field3", "my dog and phrase").execute().actionGet(); client().prepareIndex("test", "type", "9").setSource("field3", "my dog and cat").execute().actionGet(); client().prepareIndex("test", "type", "10").setSource("field3", "my dog and your cat").execute().actionGet(); client().prepareIndex("test", "type", "11").setSource("field3", "my cat and dog").execute().actionGet(); refresh(); Elasticsearch es = new Elasticsearch(client(), "test", "type"); SearchResult result; String[] fields1 = {"field1"}; result = es.search("value2", fields1); assertTrue(result.getTotalHits() == 1); String[] fields2 = {"field1", "field2"}; result = es.search("value2", fields2); assertTrue(result.getTotalHits() == 2); result = es.search("xxxxx", fields2); assertTrue(result.getTotalHits() == 0); result = es.search("value2", fields2, 1, Indexer.TIMEOUT); assertTrue(result.getTotalHits() == 2); assertTrue(result.getHits().size() == 1); result = es.search("value2", fields2, -2, Indexer.TIMEOUT); assertTrue(result.getTotalHits() == 0); result = es.search("value2", null); assertTrue(result.getTotalHits() == 0); result = es.search(null, fields1); assertTrue(result.getTotalHits() == 0); result = es.searchFullText("cat is an animal"); assertTrue(result.getTotalHits() == 1); result = es.searchFullText("superman and batman"); assertTrue(result.getTotalHits() == 0); result = es.searchFullText(null); assertTrue(result.getTotalHits() == 0); result = es.searchPhrase("dog and cat", "field3", 0); assertTrue(result.getTotalHits() == 1); result = es.searchPhrase("dog and cat", "field3", 1); assertTrue(result.getTotalHits() == 2); result = es.searchPhrase("dog and cat", "field3", 4); assertTrue(result.getTotalHits() == 3); result = es.searchPhrase("xxx ccc", "field3", 1); assertTrue(result.getTotalHits() == 0); result = es.searchPhrase("dog and cat", "field3", -1); assertTrue(result.getTotalHits() == 0); result = es.searchPhrase("dog and cat", "field3", 1, -2, Indexer.TIMEOUT); assertTrue(result.getTotalHits() == 0); result = es.searchPhrase("dog and cat", null, 1); assertTrue(result.getTotalHits() == 0); result = es.searchPhrase(null, "field3", 1); assertTrue(result.getTotalHits() == 0); result = es.advancedSearch("field3:(+dog -your phrase^4)"); assertTrue(result.getTotalHits() == 3); assertEquals("8", result.getHits().get(0).getId()); Map<String, Object> p1 = new HashMap<>(); p1.put("default_operator", Indexer.Operator.AND); result = es.advancedSearch("field3:(+dog -your phrase^4)", p1); assertTrue(result.getTotalHits() == 1); Map<String, Object> p2 = new HashMap<>(); p2.put("default_field", "field3"); result = es.advancedSearch("+dog -your phrase^4", p2); assertTrue(result.getTotalHits() == 3); result = es.advancedSearch("field3:(+dog -your phrase^4)", null); assertTrue(result.getTotalHits() == 3); result = es.advancedSearch("field3:(+dog -your phrase^4)", null, -2, Indexer.TIMEOUT); assertTrue(result.getTotalHits() == 0); result = es.advancedSearch(""); assertTrue(result.getTotalHits() == 0); result = es.advancedSearch(null); assertTrue(result.getTotalHits() == 0); ok = true; break; } catch(Exception ex) { i++; } }while(i<4); if(!ok) { fail(); } } |
DataSetServiceClient extends MCSClient { public void deleteDataSet(String providerId, String dataSetId) throws MCSException { WebTarget target = client .target(this.baseUrl) .path(DATA_SET_RESOURCE) .resolveTemplate(PROVIDER_ID, providerId) .resolveTemplate(DATA_SET_ID, dataSetId); Response response = null; try { response = target.request().delete(); if (response.getStatus() != Status.NO_CONTENT.getStatusCode()) { ErrorInfo errorInfo = response.readEntity(ErrorInfo.class); throw MCSExceptionProvider.generateException(errorInfo); } } finally { if (response != null) { response.close(); } } } DataSetServiceClient(String baseUrl); DataSetServiceClient(String baseUrl, final String authorization); DataSetServiceClient(String baseUrl, final String username, final String password); DataSetServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); ResultSlice<DataSet> getDataSetsForProviderChunk(String providerId, String startFrom); List<DataSet> getDataSetsForProvider(String providerId); DataSetIterator getDataSetIteratorForProvider(String providerId); URI createDataSet(String providerId, String dataSetId, String description); ResultSlice<Representation> getDataSetRepresentationsChunk(
String providerId, String dataSetId, String startFrom); List<Representation> getDataSetRepresentations(String providerId, String dataSetId); RepresentationIterator getRepresentationIterator(String providerId, String dataSetId); void updateDescriptionOfDataSet(String providerId, String dataSetId, String description); void deleteDataSet(String providerId, String dataSetId); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName,
String version, String key, String value); void unassignRepresentationFromDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); ResultSlice<CloudTagsResponse> getDataSetRevisionsChunk(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp,
String startFrom, Integer limit); List<CloudTagsResponse> getDataSetRevisions(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp); ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationChunk(String dataSetId, String providerId, String representationName, String dateFrom, String tag, String startFrom); List<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentation(String dataSetId, String providerId,
String representationName, String dateFrom, String tag); ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevisionChunk(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted, String startFrom); List<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted); String getLatelyTaggedRecords(
String dataSetId, String providerId, String cloudId, String representationName,
String revisionName, String revisionProviderId); void useAuthorizationHeader(final String headerValue); void close(); } | @Betamax(tape = "dataSets_shouldThrowDataSetNotExistsForDeleteDataSet") @Test(expected = DataSetNotExistsException.class) public void shouldThrowDataSetNotExistsForDeleteDataSet() throws MCSException { String providerId = "Provider002"; String dataSetId = "dataset000033"; DataSet dataSet = new DataSet(); dataSet.setProviderId(providerId); dataSet.setId(dataSetId); dataSet.setDescription(null); DataSetServiceClient instance = new DataSetServiceClient(baseUrl); instance.deleteDataSet(providerId, dataSetId); }
@Betamax(tape = "dataSets_shouldThrowDriverExceptionForDeleteDataSet") @Test(expected = DriverException.class) public void shouldThrowDriverExceptionForDeleteDataSet() throws MCSException { String providerId = "Provider002"; String dataSetId = "dataset000033"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); instance.deleteDataSet(providerId, dataSetId); } |
DataSetServiceClient extends MCSClient { public void assignRepresentationToDataSet( String providerId, String dataSetId, String cloudId, String representationName, String version) throws MCSException { WebTarget target = client .target(this.baseUrl) .path(DATA_SET_ASSIGNMENTS) .resolveTemplate(PROVIDER_ID, providerId) .resolveTemplate(DATA_SET_ID, dataSetId); Form form = getForm(cloudId, representationName, version); Response response = null; try { response = target.request().post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE)); if (response.getStatus() != Status.NO_CONTENT.getStatusCode()) { ErrorInfo errorInfo = response.readEntity(ErrorInfo.class); throw MCSExceptionProvider.generateException(errorInfo); } } finally { if (response != null) { response.close(); } } } DataSetServiceClient(String baseUrl); DataSetServiceClient(String baseUrl, final String authorization); DataSetServiceClient(String baseUrl, final String username, final String password); DataSetServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); ResultSlice<DataSet> getDataSetsForProviderChunk(String providerId, String startFrom); List<DataSet> getDataSetsForProvider(String providerId); DataSetIterator getDataSetIteratorForProvider(String providerId); URI createDataSet(String providerId, String dataSetId, String description); ResultSlice<Representation> getDataSetRepresentationsChunk(
String providerId, String dataSetId, String startFrom); List<Representation> getDataSetRepresentations(String providerId, String dataSetId); RepresentationIterator getRepresentationIterator(String providerId, String dataSetId); void updateDescriptionOfDataSet(String providerId, String dataSetId, String description); void deleteDataSet(String providerId, String dataSetId); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName,
String version, String key, String value); void unassignRepresentationFromDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); ResultSlice<CloudTagsResponse> getDataSetRevisionsChunk(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp,
String startFrom, Integer limit); List<CloudTagsResponse> getDataSetRevisions(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp); ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationChunk(String dataSetId, String providerId, String representationName, String dateFrom, String tag, String startFrom); List<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentation(String dataSetId, String providerId,
String representationName, String dateFrom, String tag); ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevisionChunk(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted, String startFrom); List<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted); String getLatelyTaggedRecords(
String dataSetId, String providerId, String cloudId, String representationName,
String revisionName, String revisionProviderId); void useAuthorizationHeader(final String headerValue); void close(); } | @Betamax(tape = "dataSets_shouldAssignRepresentation") @Test public void shouldAssignRepresentation() throws MCSException { String providerId = "Provider002"; String dataSetId = "dataset000008"; String cloudId = "1DZ6HTS415W"; String representationName = "schema66"; String versionId = "b95fcda0-994a-11e3-bfe1-1c6f653f6012"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); instance.assignRepresentationToDataSet(providerId, dataSetId, cloudId, representationName, null); assertEquals(TestUtils.howManyThisRepresentationVersion(instance, providerId, dataSetId, representationName, versionId), 1); }
@Betamax(tape = "dataSets_shouldAssignRepresentationVersion") @Test public void shouldAssignRepresentationVersion() throws MCSException { String providerId = "Provider001"; String dataSetId = "dataset000066"; String cloudId = "1DZ6HTS415W"; String representationName = "schema77"; String versionId1 = "49398390-9a3f-11e3-9690-1c6f653f6012"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); instance.assignRepresentationToDataSet(providerId, dataSetId, cloudId, representationName, versionId1); assertEquals(TestUtils.howManyThisRepresentationVersion(instance, providerId, dataSetId, representationName, versionId1), 1); }
@Betamax(tape = "dataSets_shouldOverrideAssignedRepresentationVersion") @Test public void shouldOverrideAssignedRepresentationVersion() throws MCSException { String providerId = "Provider001"; String dataSetId = "dataset000066"; String cloudId = "1DZ6HTS415W"; String representationName = "schema77"; String versionId2 = "97dd0b70-9a3f-11e3-9690-1c6f653f6012"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); instance.assignRepresentationToDataSet(providerId, dataSetId, cloudId, representationName, versionId2); assertEquals(TestUtils.howManyThisRepresentationVersion(instance, providerId, dataSetId, representationName, versionId2), 1); }
@Betamax(tape = "dataSets_shouldThrowDriverExceptionForAssingRepresentation") @Test(expected = DriverException.class) public void shouldThrowDriverExceptionForAssingRepresentation() throws MCSException { String providerId = "Provider001"; String dataSetId = "dataset000015"; String cloudId = "1DZ6HTS415W"; String representationName = "schema66"; String versionId = "b929f090-994a-11e3-bfe1-1c6f653f6012"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); instance.assignRepresentationToDataSet(providerId, dataSetId, cloudId, representationName, versionId); }
@Betamax(tape = "dataSets_shouldThrowRepresentationNotExistsForAssingRepresentation") @Test(expected = RepresentationNotExistsException.class) public void shouldThrowRepresentationNotExistsForAssingRepresentation() throws MCSException { String providerId = "Provider001"; String dataSetId = "dataset000016"; String cloudId = "1DZ6HTS415W"; String representationName = "noSuchSchema"; String versionId = null; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); instance.assignRepresentationToDataSet(providerId, dataSetId, cloudId, representationName, versionId); }
@Betamax(tape = "dataSets_shouldThrowDataSetNotExistsForAssingRepresentation") @Test(expected = DataSetNotExistsException.class) public void shouldThrowDataSetNotExistsForAssingRepresentation() throws MCSException { String providerId = "Provider001"; String dataSetId = "noSuchDataSet"; String cloudId = "1DZ6HTS415W"; String representationName = "schema66"; String versionId = null; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); instance.assignRepresentationToDataSet(providerId, dataSetId, cloudId, representationName, versionId); } |
DataSetServiceClient extends MCSClient { public void unassignRepresentationFromDataSet( String providerId, String dataSetId, String cloudId, String representationName, String version) throws MCSException { WebTarget target = client .target(this.baseUrl) .path(DATA_SET_ASSIGNMENTS) .resolveTemplate(PROVIDER_ID, providerId) .resolveTemplate(DATA_SET_ID, dataSetId) .queryParam(CLOUD_ID, cloudId) .queryParam(REPRESENTATION_NAME, representationName) .queryParam(VERSION, version); Response response = null; try { response = target.request().delete(); if (response.getStatus() != Status.NO_CONTENT.getStatusCode()) { ErrorInfo errorInfo = response.readEntity(ErrorInfo.class); throw MCSExceptionProvider.generateException(errorInfo); } } finally { closeResponse(response); } } DataSetServiceClient(String baseUrl); DataSetServiceClient(String baseUrl, final String authorization); DataSetServiceClient(String baseUrl, final String username, final String password); DataSetServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); ResultSlice<DataSet> getDataSetsForProviderChunk(String providerId, String startFrom); List<DataSet> getDataSetsForProvider(String providerId); DataSetIterator getDataSetIteratorForProvider(String providerId); URI createDataSet(String providerId, String dataSetId, String description); ResultSlice<Representation> getDataSetRepresentationsChunk(
String providerId, String dataSetId, String startFrom); List<Representation> getDataSetRepresentations(String providerId, String dataSetId); RepresentationIterator getRepresentationIterator(String providerId, String dataSetId); void updateDescriptionOfDataSet(String providerId, String dataSetId, String description); void deleteDataSet(String providerId, String dataSetId); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName,
String version, String key, String value); void unassignRepresentationFromDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); ResultSlice<CloudTagsResponse> getDataSetRevisionsChunk(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp,
String startFrom, Integer limit); List<CloudTagsResponse> getDataSetRevisions(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp); ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationChunk(String dataSetId, String providerId, String representationName, String dateFrom, String tag, String startFrom); List<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentation(String dataSetId, String providerId,
String representationName, String dateFrom, String tag); ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevisionChunk(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted, String startFrom); List<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted); String getLatelyTaggedRecords(
String dataSetId, String providerId, String cloudId, String representationName,
String revisionName, String revisionProviderId); void useAuthorizationHeader(final String headerValue); void close(); } | @Betamax(tape = "dataSets_shouldUnassignRepresentation") @Test public void shouldUnassignRepresentation() throws MCSException { String providerId = "Provider002"; String dataSetId = "dataset000002"; String cloudId = "1DZ6HTS415W"; String representationName = "schema66"; String representationVersion = "66404040-0307-11e6-a5cb-0050568c62b8"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); instance.unassignRepresentationFromDataSet(providerId, dataSetId, cloudId, representationName, representationVersion); assertEquals(TestUtils.howManyThisRepresentationVersion(instance, providerId, dataSetId, representationName, null), 0); }
@Betamax(tape = "dataSets_shouldUnassignNotAssignedRepresentation") @Test public void shouldUnassignNotAssignedRepresentation() throws MCSException { String providerId = "Provider002"; String dataSetId = "dataset000002"; String cloudId = "1DZ6HTS415W"; String representationName = "schema66"; String representationVersion = "66404040-0307-11e6-a5cb-0050568c62b8"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); assertEquals(TestUtils.howManyThisRepresentationVersion(instance, providerId, dataSetId, representationName, null), 0); instance.unassignRepresentationFromDataSet(providerId, dataSetId, cloudId, representationName, representationVersion); }
@Betamax(tape = "dataSets_shouldUnassignRepresentationWithVersion") @Test public void shouldUnassignRepresentationWithVersion() throws MCSException { String providerId = "Provider001"; String dataSetId = "dataset000023"; String cloudId = "1DZ6HTS415W"; String representationName = "schema66"; String representationVersion = "66404040-0307-11e6-a5cb-0050568c62b8"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); instance.unassignRepresentationFromDataSet(providerId, dataSetId, cloudId, representationName, representationVersion); assertEquals(TestUtils.howManyThisRepresentationVersion(instance, providerId, dataSetId, representationName, null), 0); }
@Betamax(tape = "dataSets_shouldUnassignNonExistingRepresentation") @Test public void shouldUnassignNonExistingRepresentation() throws MCSException { String providerId = "Provider002"; String dataSetId = "dataset000007"; String cloudId = "1DZ6HTS415W"; String representationName = "noSuchSchema"; String representationVersion = "66404040-0307-11e6-a5cb-0050568c62b8"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); instance.unassignRepresentationFromDataSet(providerId, dataSetId, cloudId, representationName, representationVersion); }
@Betamax(tape = "dataSets_shouldThrowDriverExceptionForUnassingRepresentation") @Test(expected = DriverException.class) public void shouldThrowDriverExceptionForUnassingRepresentation() throws MCSException { String providerId = "Provider001"; String dataSetId = "dataset000058"; String cloudId = "1DZ6HTS415W"; String representationName = "schema77"; String representationVersion = "66404040-0307-11e6-a5cb-0050568c62b8"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); instance.unassignRepresentationFromDataSet(providerId, dataSetId, cloudId, representationName, representationVersion); }
@Betamax(tape = "dataSets_shouldThrowDataSetNotExistsForUnassingRepresentation") @Test(expected = DataSetNotExistsException.class) public void shouldThrowDataSetNotExistsForUnassingRepresentation() throws MCSException { String providerId = "Provider002"; String dataSetId = "noSuchDataSet"; String cloudId = "1DZ6HTS415W"; String representationName = "schema77"; String representationVersion = "66404040-0307-11e6-a5cb-0050568c62b8"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); instance.unassignRepresentationFromDataSet(providerId, dataSetId, cloudId, representationName, representationVersion); } |
Elasticsearch implements Indexer { @Override public SearchResult getMoreLikeThis(String documentId) throws ConnectionException, IndexerException { return getMoreLikeThis(documentId, null, MAX_QUERY_TERMS, MIN_TERM_FREQ, MIN_DOC_FREQ, MAX_DOC_FREQ, MIN_WORD_LENGTH, MAX_WORD_LENGTH, PAGE_SIZE, 0, false); } Elasticsearch(IndexerInformations ii); Elasticsearch(String clasterAddresses, String index, String type); protected Elasticsearch(Client client, String index, String type); @Override Object getIndexer(); @Override SupportedIndexers getIndexerName(); @Override IndexerInformations getIndexerInformations(); @Override IndexedDocument getDocument(String documentId); @Override SearchResult getMoreLikeThis(String documentId); @Override SearchResult getMoreLikeThis(String documentId, int size, int timeout); @Override SearchResult getMoreLikeThis(String documentId, String[] fields); @Override SearchResult getMoreLikeThis(String documentId, String[] fields, int size, int timeout); @Override SearchResult getMoreLikeThis(String documentId, String[] fields, int maxQueryTerms, int minTermFreq,
int minDocFreq, int maxDocFreq, int minWordLength, int maxWordLength, int size, int timeout, Boolean includeItself); @Override SearchResult search(String text, String[] fields); @Override SearchResult search(String text, String[] fields, int size, int timeout); @Override SearchResult searchFullText(String text); @Override SearchResult searchFullText(String text, int size, int timeout); @Override SearchResult searchPhraseInFullText(String text, int slop); @Override SearchResult searchPhrase(String text, String field, int slop); @Override SearchResult searchPhrase(String text, String field, int slop, int size, int timeout); @Override SearchResult advancedSearch(String query); @Override SearchResult advancedSearch(String query, int size, int timeout); @Override SearchResult advancedSearch(String query, Map<String, Object> parameters); @Override SearchResult advancedSearch(String query, Map<String, Object> parameters, int size, int timeout); @Override void insert(String data); @Override void insert(Map<String, Object> data); @Override void insert(String documentId, String data); @Override void insert(String documentId, Map<String, Object> data); @Override void update(String documentId, String data); @Override void update(String documentId, Map<String, Object> data); @Override void delete(String documentId); @Override SearchResult getNextPage(String scrollId, Object context); } | @Test public void moreLikeThisTest() throws IndexerException, IOException { boolean ok = false; int i = 0; do { try { XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("type1").startObject("properties") .startObject("field3").field("type", "string").field("term_vector", "yes") .endObject().endObject().endObject().endObject(); ElasticsearchAssertions.assertAcked(prepareCreate("test").addMapping("type1", mapping)); client().prepareIndex("test", "type1", "7").setSource("field3", "my phrase").execute().actionGet(); client().prepareIndex("test", "type1", "8").setSource("field3", "my dog and phrase").execute().actionGet(); client().prepareIndex("test", "type1", "9").setSource("field3", "my dog and cat").execute().actionGet(); client().prepareIndex("test", "type1", "10").setSource("field3", "my dog and your cat").execute().actionGet(); client().prepareIndex("test", "type1", "11").setSource("field3", "my cat and dog").execute().actionGet(); client().prepareIndex("test", "type1", "12").setSource("field3", "another text").execute().actionGet(); refresh(); Elasticsearch es = new Elasticsearch(client(), "test", "type1"); SearchResult result; String[] fields3 = {"field3", IndexFields.RAW_TEXT.toString()}; result = es.getMoreLikeThis("9",fields3, 20, 1, 1, 20, 1, 20, 10, 0, true); assertTrue(result.getTotalHits() == 5); result = es.getMoreLikeThis("9",fields3, 20, 1, 1, 20, 1, 20, 10, 0, false); assertTrue(result.getTotalHits() == 4); result = es.getMoreLikeThis("9", null, 20, 1, 1, 20, 1, 20, 10, 0, false); assertTrue(result.getTotalHits() == 4); result = es.getMoreLikeThis("9", null, 20, 1, 1, 20, 1, 20, -2, 0, false); assertTrue(result.getTotalHits() == 0); result = es.getMoreLikeThis("", null, 20, 1, 1, 20, 1, 20, 10, 0, false); assertTrue(result.getTotalHits() == 0); result = es.getMoreLikeThis(null, null, 20, 1, 1, 20, 1, 20, 10, 0, false); assertTrue(result.getTotalHits() == 0); ok=true; break; } catch(Exception ex) { i++; } }while(i<4); if(!ok) { fail(); } } |
DataSetServiceClient extends MCSClient { public DataSetIterator getDataSetIteratorForProvider(String providerId) { return new DataSetIterator(this, providerId); } DataSetServiceClient(String baseUrl); DataSetServiceClient(String baseUrl, final String authorization); DataSetServiceClient(String baseUrl, final String username, final String password); DataSetServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); ResultSlice<DataSet> getDataSetsForProviderChunk(String providerId, String startFrom); List<DataSet> getDataSetsForProvider(String providerId); DataSetIterator getDataSetIteratorForProvider(String providerId); URI createDataSet(String providerId, String dataSetId, String description); ResultSlice<Representation> getDataSetRepresentationsChunk(
String providerId, String dataSetId, String startFrom); List<Representation> getDataSetRepresentations(String providerId, String dataSetId); RepresentationIterator getRepresentationIterator(String providerId, String dataSetId); void updateDescriptionOfDataSet(String providerId, String dataSetId, String description); void deleteDataSet(String providerId, String dataSetId); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName,
String version, String key, String value); void unassignRepresentationFromDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); ResultSlice<CloudTagsResponse> getDataSetRevisionsChunk(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp,
String startFrom, Integer limit); List<CloudTagsResponse> getDataSetRevisions(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp); ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationChunk(String dataSetId, String providerId, String representationName, String dateFrom, String tag, String startFrom); List<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentation(String dataSetId, String providerId,
String representationName, String dateFrom, String tag); ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevisionChunk(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted, String startFrom); List<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted); String getLatelyTaggedRecords(
String dataSetId, String providerId, String cloudId, String representationName,
String revisionName, String revisionProviderId); void useAuthorizationHeader(final String headerValue); void close(); } | @Betamax(tape = "dataSets_shouldProvideDataSetIterator") @Test public void shouldProvideDataSetIterator() throws MCSException { String providerId = "Provider001"; int numberOfDataSets = 200; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); DataSetIterator iterator = instance.getDataSetIteratorForProvider(providerId); assertNotNull(iterator); int counter = 0; while (iterator.hasNext()) { counter++; assertNotNull(iterator.next()); } assertEquals(counter, numberOfDataSets); }
@Betamax(tape = "dataSets_shouldProvideEmptyDataSetIteratorWhenNoSuchProvider") @Test public void shouldProvideEmptyDataSetIteratorWhenNoSuchProvider() throws MCSException { String providerId = "noSuchProvider"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); DataSetIterator iterator = instance.getDataSetIteratorForProvider(providerId); assertNotNull(iterator); assertEquals(iterator.hasNext(), false); }
@Betamax(tape = "dataSets_shouldProvideDataSetIteratorThatThrowsNoSuchElementException") @Test(expected = NoSuchElementException.class) public void shouldProvideDataSetIteratorThatThrowsNoSuchElementException() throws MCSException { String providerId = "Provider001"; int numberOfDataSets = 200; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); DataSetIterator iterator = instance.getDataSetIteratorForProvider(providerId); assertNotNull(iterator); for (int i = 0; i < numberOfDataSets; i++) { try { assertNotNull(iterator.next()); } catch (NoSuchElementException ex) { assert false : "NoSuchElementException thrown in unexpected place."; } } iterator.next(); }
@Betamax(tape = "dataSets_shouldProvideDataSetIteratorThatThrowsDriverException") @Test(expected = DriverException.class) public void shouldProvideDataSetIteratorThatThrowsDriverException() throws MCSException { String providerId = "Provider001"; int numberOfDataSets = 200; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); DataSetIterator iterator = instance.getDataSetIteratorForProvider(providerId); iterator.next(); } |
DataSetServiceClient extends MCSClient { public RepresentationIterator getRepresentationIterator(String providerId, String dataSetId) { return new RepresentationIterator(this, providerId, dataSetId); } DataSetServiceClient(String baseUrl); DataSetServiceClient(String baseUrl, final String authorization); DataSetServiceClient(String baseUrl, final String username, final String password); DataSetServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); ResultSlice<DataSet> getDataSetsForProviderChunk(String providerId, String startFrom); List<DataSet> getDataSetsForProvider(String providerId); DataSetIterator getDataSetIteratorForProvider(String providerId); URI createDataSet(String providerId, String dataSetId, String description); ResultSlice<Representation> getDataSetRepresentationsChunk(
String providerId, String dataSetId, String startFrom); List<Representation> getDataSetRepresentations(String providerId, String dataSetId); RepresentationIterator getRepresentationIterator(String providerId, String dataSetId); void updateDescriptionOfDataSet(String providerId, String dataSetId, String description); void deleteDataSet(String providerId, String dataSetId); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName,
String version, String key, String value); void unassignRepresentationFromDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); ResultSlice<CloudTagsResponse> getDataSetRevisionsChunk(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp,
String startFrom, Integer limit); List<CloudTagsResponse> getDataSetRevisions(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp); ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationChunk(String dataSetId, String providerId, String representationName, String dateFrom, String tag, String startFrom); List<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentation(String dataSetId, String providerId,
String representationName, String dateFrom, String tag); ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevisionChunk(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted, String startFrom); List<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted); String getLatelyTaggedRecords(
String dataSetId, String providerId, String cloudId, String representationName,
String revisionName, String revisionProviderId); void useAuthorizationHeader(final String headerValue); void close(); } | @Betamax(tape = "dataSets_shouldProvideRepresentationIterator") @Test public void shouldProvideRepresentationIterator() throws MCSException { String providerId = "Provider001"; String dataSetId = "dataset3"; int numberOfRepresentations = 200; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); RepresentationIterator iterator = instance.getRepresentationIterator(providerId, dataSetId); assertNotNull(iterator); int counter = 0; while (iterator.hasNext()) { counter++; assertNotNull(iterator.next()); } assertEquals(counter, numberOfRepresentations); }
@Betamax(tape = "dataSets_shouldProvideRepresentationIteratorThatThrowsDataSetNotExistsExceptionWhenNoDataSet") @Test(expected = DataSetNotExistsException.class) public void shouldProvideRepresentationIteratorThatThrowsExceptionWhenNoDataSet() throws Exception, Throwable { String providerId = "Provider001"; String dataSetId = "noSuchDataSet"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); RepresentationIterator iterator = instance.getRepresentationIterator(providerId, dataSetId); assertNotNull(iterator); try { iterator.hasNext(); } catch (DriverException e) { throw e.getCause(); } }
@Betamax(tape = "dataSets_shouldProvideRepresentationIteratorThatThrowsDataSetNotExistsExceptionWhenNoProvider") @Test(expected = DataSetNotExistsException.class) public void shouldProvideRepresentationIteratorThatThrowsExceptionWhenNoProvider() throws MCSException, Throwable { String providerId = "noSuchProvider"; String dataSetId = "dataset3"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); RepresentationIterator iterator = instance.getRepresentationIterator(providerId, dataSetId); assertNotNull(iterator); try { iterator.hasNext(); } catch (DriverException e) { throw e.getCause(); } }
@Betamax(tape = "dataSets_shouldProvideRepresentationIteratorThatThrowsNoSuchElementException") @Test(expected = NoSuchElementException.class) public void shouldProvideRepresentationIteratorThatThrowsNoSuchElementException() throws MCSException { String providerId = "Provider001"; String dataSetId = "dataset3"; int numberOfRepresentations = 200; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); RepresentationIterator iterator = instance.getRepresentationIterator(providerId, dataSetId); assertNotNull(iterator); for (int i = 0; i < numberOfRepresentations; i++) { try { assertNotNull(iterator.next()); } catch (NoSuchElementException ex) { assert false : "NoSuchElementException thrown in unexpected place."; } } iterator.next(); }
@Betamax(tape = "dataSets_shouldProvideRepresentationIteratorThatThrowsDriverException") @Test(expected = DriverException.class) public void shouldProvideRepresentationIteratorThatThrowsDriverException() throws MCSException { String providerId = "Provider001"; String dataSetId = "dataset3"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); RepresentationIterator iterator = instance.getRepresentationIterator(providerId, dataSetId); iterator.next(); } |
AuthenticationResource { @PostMapping(value = "/create-user", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) @PreAuthorize("hasRole('ROLE_ADMIN')") public ResponseEntity<String> createCloudUser( @RequestParam(AASParamConstants.P_USER_NAME) String username, @RequestParam(AASParamConstants.P_PASS_TOKEN) String password) throws DatabaseConnectionException, UserExistsException, InvalidUsernameException, InvalidPasswordException { authenticationService.createUser(new User(username, password)); return ResponseEntity.ok("Cloud user was created!"); } @PostMapping(value = "/create-user", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) @PreAuthorize("hasRole('ROLE_ADMIN')") ResponseEntity<String> createCloudUser(
@RequestParam(AASParamConstants.P_USER_NAME) String username,
@RequestParam(AASParamConstants.P_PASS_TOKEN) String password); @PostMapping(value = "/delete-user", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) @PreAuthorize("hasRole('ROLE_ADMIN')") ResponseEntity<String> deleteCloudUser(
@RequestParam(AASParamConstants.P_USER_NAME) String username); @PostMapping(value = "/update-user", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) @PreAuthorize("hasRole('ROLE_ADMIN')") ResponseEntity<String> updateCloudUser(
@RequestParam(AASParamConstants.P_USER_NAME) String username,
@RequestParam(AASParamConstants.P_PASS_TOKEN) String password); } | @Test public void testCreateCloudUser() throws Exception { Mockito.doReturn(new User(username, password)).when(authenticationService).getUser(username); mockMvc.perform(post("/create-user") .param(AASParamConstants.P_USER_NAME, username) .param(AASParamConstants.P_PASS_TOKEN, password)) .andExpect(status().isOk()); } |
DataSetServiceClient extends MCSClient { public ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationChunk(String dataSetId, String providerId, String representationName, String dateFrom, String tag, String startFrom) throws MCSException { WebTarget target = client .target(this.baseUrl) .path(DATA_SET_BY_REPRESENTATION) .resolveTemplate(PROVIDER_ID, providerId) .resolveTemplate(DATA_SET_ID, dataSetId) .resolveTemplate(REPRESENTATION_NAME, representationName) .queryParam(ParamConstants.F_DATE_FROM, dateFrom) .queryParam(ParamConstants.F_TAG, tag); if (startFrom != null) { target = target.queryParam(ParamConstants.F_START_FROM, startFrom); } return prepareResultSliceResponse(target); } DataSetServiceClient(String baseUrl); DataSetServiceClient(String baseUrl, final String authorization); DataSetServiceClient(String baseUrl, final String username, final String password); DataSetServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); ResultSlice<DataSet> getDataSetsForProviderChunk(String providerId, String startFrom); List<DataSet> getDataSetsForProvider(String providerId); DataSetIterator getDataSetIteratorForProvider(String providerId); URI createDataSet(String providerId, String dataSetId, String description); ResultSlice<Representation> getDataSetRepresentationsChunk(
String providerId, String dataSetId, String startFrom); List<Representation> getDataSetRepresentations(String providerId, String dataSetId); RepresentationIterator getRepresentationIterator(String providerId, String dataSetId); void updateDescriptionOfDataSet(String providerId, String dataSetId, String description); void deleteDataSet(String providerId, String dataSetId); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName,
String version, String key, String value); void unassignRepresentationFromDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); ResultSlice<CloudTagsResponse> getDataSetRevisionsChunk(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp,
String startFrom, Integer limit); List<CloudTagsResponse> getDataSetRevisions(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp); ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationChunk(String dataSetId, String providerId, String representationName, String dateFrom, String tag, String startFrom); List<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentation(String dataSetId, String providerId,
String representationName, String dateFrom, String tag); ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevisionChunk(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted, String startFrom); List<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted); String getLatelyTaggedRecords(
String dataSetId, String providerId, String cloudId, String representationName,
String revisionName, String revisionProviderId); void useAuthorizationHeader(final String headerValue); void close(); } | @Betamax(tape = "dataSets_shouldRetrieveDataSetCloudIdsByRepresentationFirstChunk") @Test public void shouldRetrieveDataSetCloudIdsByRepresentationFirstChunk() throws MCSException { String providerId = "provider"; String dataSet = "dataset"; String representationName = "representation"; String dateFrom = "2016-08-21T11:08:28.059"; int resultSize = 5; String startFrom = "005a00100015000870726f76696465720000076461746173657400003d000e726570726573656e746174696f6e00000800000156b1580d280000087265766973696f6e000007636c6f75645f350000097075626c6973686564007ffffffa76a6db9eb099834f7db2bad6a99690e10003"; DataSetServiceClient instance = new DataSetServiceClient("http: ResultSlice<CloudVersionRevisionResponse> result = instance.getDataSetCloudIdsByRepresentationChunk(dataSet, providerId, representationName, dateFrom, "published", null); assertNotNull(result.getResults()); assertEquals(result.getResults().size(), resultSize); assertEquals(result.getNextSlice(), startFrom); }
@Betamax(tape = "dataSets_shouldRetrieveDataSetCloudIdsByRepresentationAllChunks") @Test public void shouldRetrieveDataSetCloudIdsByRepresentationAllChunks() throws MCSException { String providerId = "provider"; String dataSet = "dataset"; String representationName = "representation"; String dateFrom = "2016-08-21T11:08:28.059"; int resultSize = 5; String startFrom = null; DataSetServiceClient instance = new DataSetServiceClient("http: ResultSlice<CloudVersionRevisionResponse> result = instance.getDataSetCloudIdsByRepresentationChunk(dataSet, providerId, representationName, dateFrom, "published", startFrom); while (result.getNextSlice() != null) { assertNotNull(result.getResults()); assertEquals(result.getResults().size(), resultSize); startFrom = result.getNextSlice(); result = instance.getDataSetCloudIdsByRepresentationChunk(dataSet, providerId, representationName, dateFrom, "published", startFrom); } assertNotNull(result.getResults()); assertTrue(result.getResults().size() <= resultSize); } |
DataSetServiceClient extends MCSClient { public List<CloudTagsResponse> getDataSetRevisions( String providerId, String dataSetId, String representationName, String revisionName, String revisionProviderId, String revisionTimestamp) throws MCSException { List<CloudTagsResponse> resultList = new ArrayList<>(); ResultSlice<CloudTagsResponse> resultSlice; String startFrom = null; do { resultSlice = getDataSetRevisionsChunk(providerId, dataSetId, representationName, revisionName, revisionProviderId, revisionTimestamp, startFrom, null); if (resultSlice == null || resultSlice.getResults() == null) { throw new DriverException("Getting cloud ids and revision tags: result chunk obtained but is empty."); } resultList.addAll(resultSlice.getResults()); startFrom = resultSlice.getNextSlice(); } while (resultSlice.getNextSlice() != null); return resultList; } DataSetServiceClient(String baseUrl); DataSetServiceClient(String baseUrl, final String authorization); DataSetServiceClient(String baseUrl, final String username, final String password); DataSetServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); ResultSlice<DataSet> getDataSetsForProviderChunk(String providerId, String startFrom); List<DataSet> getDataSetsForProvider(String providerId); DataSetIterator getDataSetIteratorForProvider(String providerId); URI createDataSet(String providerId, String dataSetId, String description); ResultSlice<Representation> getDataSetRepresentationsChunk(
String providerId, String dataSetId, String startFrom); List<Representation> getDataSetRepresentations(String providerId, String dataSetId); RepresentationIterator getRepresentationIterator(String providerId, String dataSetId); void updateDescriptionOfDataSet(String providerId, String dataSetId, String description); void deleteDataSet(String providerId, String dataSetId); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName,
String version, String key, String value); void unassignRepresentationFromDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); ResultSlice<CloudTagsResponse> getDataSetRevisionsChunk(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp,
String startFrom, Integer limit); List<CloudTagsResponse> getDataSetRevisions(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp); ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationChunk(String dataSetId, String providerId, String representationName, String dateFrom, String tag, String startFrom); List<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentation(String dataSetId, String providerId,
String representationName, String dateFrom, String tag); ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevisionChunk(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted, String startFrom); List<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted); String getLatelyTaggedRecords(
String dataSetId, String providerId, String cloudId, String representationName,
String revisionName, String revisionProviderId); void useAuthorizationHeader(final String headerValue); void close(); } | @Betamax(tape = "dataSets_shouldRetrieveCloudIdsForSpecificRevision") @Test public void shouldRetrieveCloudIdsForSpecificRevision() throws MCSException { String providerId = "LFT"; String dataSetId = "set1"; String representationName = "t1"; String revisionName = "IMPORT"; String revisionProviderId = "EU"; String revisionTimestamp = "2017-01-09T08:16:47.824"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); List<CloudTagsResponse> cloudIds = instance.getDataSetRevisions(providerId, dataSetId, representationName, revisionName, revisionProviderId, revisionTimestamp); assertThat(cloudIds.size(), is(2)); CloudTagsResponse cid = cloudIds.get(0); assertThat(cid.getCloudId(), is("A2YCHGEFD4UV4UIEAWDUJHWJNZWXNOURWCQORIG7MCQASTB62OSQ")); assertTrue(cid.isAcceptance()); assertFalse(cid.isDeleted()); assertFalse(cid.isPublished()); cid = cloudIds.get(1); assertThat(cid.getCloudId(), is("V7UYW5HK2YVQH7HN67W4ZRXBKLXLEY2HRIICIWAFTDVHEFZE5SPQ")); assertFalse(cid.isAcceptance()); assertFalse(cid.isDeleted()); assertTrue(cid.isPublished()); } |
DataSetServiceClient extends MCSClient { public ResultSlice<CloudTagsResponse> getDataSetRevisionsChunk( String providerId, String dataSetId, String representationName, String revisionName, String revisionProviderId, String revisionTimestamp, String startFrom, Integer limit) throws MCSException { WebTarget target = client.target(baseUrl) .path(DATA_SET_REVISIONS_RESOURCE) .resolveTemplate(PROVIDER_ID, providerId) .resolveTemplate(DATA_SET_ID, dataSetId) .resolveTemplate(REPRESENTATION_NAME, representationName) .resolveTemplate(REVISION_NAME, revisionName) .resolveTemplate(REVISION_PROVIDER_ID, revisionProviderId) .queryParam(F_REVISION_TIMESTAMP, revisionTimestamp) .queryParam(F_START_FROM, startFrom); target = target.queryParam(F_LIMIT, limit != null ? limit : 0); Response response = null; try { response = target.request().get(); if (response.getStatus() == Status.OK.getStatusCode()) { return response.readEntity(ResultSlice.class); } ErrorInfo errorInfo = response.readEntity(ErrorInfo.class); throw MCSExceptionProvider.generateException(errorInfo); } finally { closeResponse(response); } } DataSetServiceClient(String baseUrl); DataSetServiceClient(String baseUrl, final String authorization); DataSetServiceClient(String baseUrl, final String username, final String password); DataSetServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); ResultSlice<DataSet> getDataSetsForProviderChunk(String providerId, String startFrom); List<DataSet> getDataSetsForProvider(String providerId); DataSetIterator getDataSetIteratorForProvider(String providerId); URI createDataSet(String providerId, String dataSetId, String description); ResultSlice<Representation> getDataSetRepresentationsChunk(
String providerId, String dataSetId, String startFrom); List<Representation> getDataSetRepresentations(String providerId, String dataSetId); RepresentationIterator getRepresentationIterator(String providerId, String dataSetId); void updateDescriptionOfDataSet(String providerId, String dataSetId, String description); void deleteDataSet(String providerId, String dataSetId); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName,
String version, String key, String value); void unassignRepresentationFromDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); ResultSlice<CloudTagsResponse> getDataSetRevisionsChunk(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp,
String startFrom, Integer limit); List<CloudTagsResponse> getDataSetRevisions(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp); ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationChunk(String dataSetId, String providerId, String representationName, String dateFrom, String tag, String startFrom); List<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentation(String dataSetId, String providerId,
String representationName, String dateFrom, String tag); ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevisionChunk(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted, String startFrom); List<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted); String getLatelyTaggedRecords(
String dataSetId, String providerId, String cloudId, String representationName,
String revisionName, String revisionProviderId); void useAuthorizationHeader(final String headerValue); void close(); } | @Betamax(tape = "dataSets_shouldRetrievCloudIdsChunkForSpecificRevision") @Test public void shouldRetrievCloudIdsChunkForSpecificRevision() throws MCSException { String providerId = "LFT"; String dataSetId = "set1"; String representationName = "t1"; String revisionName = "IMPORT"; String revisionProviderId = "EU"; String revisionTimestamp = "2017-01-09T08:16:47.824"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); ResultSlice<CloudTagsResponse> cloudIds = instance.getDataSetRevisionsChunk(providerId, dataSetId, representationName, revisionName, revisionProviderId, revisionTimestamp, null, null); assertThat(cloudIds.getNextSlice(), nullValue()); assertThat(cloudIds.getResults().size(), is(2)); CloudTagsResponse cid = cloudIds.getResults().get(0); assertThat(cid.getCloudId(), is("A2YCHGEFD4UV4UIEAWDUJHWJNZWXNOURWCQORIG7MCQASTB62OSQ")); assertTrue(cid.isAcceptance()); assertFalse(cid.isDeleted()); assertFalse(cid.isPublished()); cid = cloudIds.getResults().get(1); assertThat(cid.getCloudId(), is("V7UYW5HK2YVQH7HN67W4ZRXBKLXLEY2HRIICIWAFTDVHEFZE5SPQ")); assertFalse(cid.isAcceptance()); assertFalse(cid.isDeleted()); assertTrue(cid.isPublished()); } |
DataSetServiceClient extends MCSClient { public String getLatelyTaggedRecords( String dataSetId, String providerId, String cloudId, String representationName, String revisionName, String revisionProviderId) throws MCSException { WebTarget target = client .target(this.baseUrl) .path(DATA_SET_LATELY_REVISIONED_VERSION) .resolveTemplate(PROVIDER_ID, providerId) .resolveTemplate(DATA_SET_ID, dataSetId) .queryParam(CLOUD_ID, cloudId) .queryParam(REPRESENTATION_NAME, representationName) .queryParam(REVISION_NAME, revisionName) .queryParam(REVISION_PROVIDER_ID, revisionProviderId); Response response = null; try { response = target.request().get(); if (response.getStatus() == Status.OK.getStatusCode()) { return response.readEntity(String.class); } else if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) { return null; } else { ErrorInfo errorInfo = response.readEntity(ErrorInfo.class); throw MCSExceptionProvider.generateException(errorInfo); } } finally { if (response != null) { response.close(); } } } DataSetServiceClient(String baseUrl); DataSetServiceClient(String baseUrl, final String authorization); DataSetServiceClient(String baseUrl, final String username, final String password); DataSetServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); ResultSlice<DataSet> getDataSetsForProviderChunk(String providerId, String startFrom); List<DataSet> getDataSetsForProvider(String providerId); DataSetIterator getDataSetIteratorForProvider(String providerId); URI createDataSet(String providerId, String dataSetId, String description); ResultSlice<Representation> getDataSetRepresentationsChunk(
String providerId, String dataSetId, String startFrom); List<Representation> getDataSetRepresentations(String providerId, String dataSetId); RepresentationIterator getRepresentationIterator(String providerId, String dataSetId); void updateDescriptionOfDataSet(String providerId, String dataSetId, String description); void deleteDataSet(String providerId, String dataSetId); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); void assignRepresentationToDataSet(
String providerId, String dataSetId, String cloudId, String representationName,
String version, String key, String value); void unassignRepresentationFromDataSet(
String providerId, String dataSetId, String cloudId, String representationName, String version); ResultSlice<CloudTagsResponse> getDataSetRevisionsChunk(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp,
String startFrom, Integer limit); List<CloudTagsResponse> getDataSetRevisions(
String providerId, String dataSetId, String representationName,
String revisionName, String revisionProviderId, String revisionTimestamp); ResultSlice<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentationChunk(String dataSetId, String providerId, String representationName, String dateFrom, String tag, String startFrom); List<CloudVersionRevisionResponse> getDataSetCloudIdsByRepresentation(String dataSetId, String providerId,
String representationName, String dateFrom, String tag); ResultSlice<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevisionChunk(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted, String startFrom); List<CloudIdAndTimestampResponse> getLatestDataSetCloudIdByRepresentationAndRevision(
String dataSetId, String providerId, String revisionProvider, String revisionName,
String representationName, Boolean isDeleted); String getLatelyTaggedRecords(
String dataSetId, String providerId, String cloudId, String representationName,
String revisionName, String revisionProviderId); void useAuthorizationHeader(final String headerValue); void close(); } | @Betamax(tape = "dataSets_shouldRetrieveLatelyTaggedRecordsVersion") @Test public void shouldReturnSpecificVersion() throws MCSException { String providerId = "provider"; String dataSetId = "dataset"; String cloudId = "cloudId"; String representationName = "representation"; String revisionName = "revision"; String revisionProviderId = "revisionProvider"; DataSetServiceClient instance = new DataSetServiceClient(baseUrl); String version = instance.getLatelyTaggedRecords(dataSetId, providerId, cloudId, representationName, revisionName, revisionProviderId); assertNotNull(version); assertEquals(version, "ef240330-f783-11e6-a0f6-1c6f653f9042"); } |
MCSExceptionProvider { public static MCSException generateException(ErrorInfo errorInfo) { if (errorInfo == null) { throw new DriverException("Null errorInfo passed to generating exception."); } McsErrorCode errorCode; try { errorCode = McsErrorCode.valueOf(errorInfo.getErrorCode()); } catch (IllegalArgumentException e) { throw new DriverException("Unknown errorCode returned from service.", e); } String details = errorInfo.getDetails(); switch (errorCode) { case ACCESS_DENIED_OR_OBJECT_DOES_NOT_EXIST_EXCEPTION: return new AccessDeniedOrObjectDoesNotExistException(details); case CANNOT_MODIFY_PERSISTENT_REPRESENTATION: return new CannotModifyPersistentRepresentationException(details); case DATASET_ALREADY_EXISTS: return new DataSetAlreadyExistsException(details); case DATASET_NOT_EXISTS: return new DataSetNotExistsException(details); case FILE_ALREADY_EXISTS: return new FileAlreadyExistsException(details); case FILE_NOT_EXISTS: return new FileNotExistsException(details); case PROVIDER_NOT_EXISTS: return new ProviderNotExistsException(details); case RECORD_NOT_EXISTS: return new RecordNotExistsException(details); case REPRESENTATION_NOT_EXISTS: return new RepresentationNotExistsException(details); case VERSION_NOT_EXISTS: return new VersionNotExistsException(details); case FILE_CONTENT_HASH_MISMATCH: return new FileContentHashMismatchException(details); case REPRESENTATION_ALREADY_IN_SET: return new RepresentationAlreadyInSet(details); case CANNOT_PERSIST_EMPTY_REPRESENTATION: return new CannotPersistEmptyRepresentationException(details); case WRONG_CONTENT_RANGE: return new WrongContentRangeException(details); case OTHER: throw new DriverException(details); default: return new MCSException(details); } } private MCSExceptionProvider(); static MCSException generateException(ErrorInfo errorInfo); } | @Test(expected = DriverException.class) public void shouldThrowDriverExceptionWhenNullErrorInfoPassed() { ErrorInfo errorInfo = null; MCSExceptionProvider.generateException(errorInfo); }
@Test(expected = DriverException.class) public void shouldThrowDriverExceptionWhenUnknownErrorInfoCodePassed() { ErrorInfo errorInfo = new ErrorInfo("THIS_IS_REALLY_WRONG_CODE", null); MCSExceptionProvider.generateException(errorInfo); }
@Test @Parameters(method = "statusCodes") public void shouldReturnCorrectException(Throwable ex, String errorCode) { ErrorInfo errorInfo = new ErrorInfo(errorCode, "details"); MCSException exception = MCSExceptionProvider.generateException(errorInfo); Assert.assertEquals(ex.getClass(), exception.getClass()); assertThat(exception.getMessage(), is(errorInfo.getDetails())); }
@Test public void shouldReturnRecordNotExistsException() { ErrorInfo errorInfo = new ErrorInfo(McsErrorCode.RECORD_NOT_EXISTS.toString(), "details"); MCSException exception = MCSExceptionProvider.generateException(errorInfo); assertTrue(exception instanceof RecordNotExistsException); assertThat(exception.getMessage(), is("There is no record with provided global id: " + errorInfo.getDetails())); }
@Test(expected = DriverException.class) public void shouldThrowDriverException() { ErrorInfo errorInfo = new ErrorInfo(McsErrorCode.OTHER.toString(), "details"); MCSExceptionProvider.generateException(errorInfo); } |
CassandraAuthenticationService implements UserDetailsService, AuthenticationService { @Override public User getUser(String userName) throws DatabaseConnectionException, UserDoesNotExistException { return userDao.getUser(userName); } CassandraAuthenticationService(); CassandraAuthenticationService(CassandraUserDAO userDao); @Override UserDetails loadUserByUsername(final String userName); @Override User getUser(String userName); @Override void createUser(final User user); @Override void updateUser(final User user); @Override void deleteUser(final String userName); } | @Test(expected = UserDoesNotExistException.class) public void testUserDoesNotExist() throws Exception { service.getUser("test2"); } |
FileServiceClient extends MCSClient { public InputStream getFile(String cloudId, String representationName, String version, String fileName) throws MCSException, IOException { WebTarget target = client .target(baseUrl) .path(FILE_RESOURCE) .resolveTemplate(CLOUD_ID, cloudId) .resolveTemplate(REPRESENTATION_NAME, representationName) .resolveTemplate(VERSION, version) .resolveTemplate(FILE_NAME, fileName); Builder requset = target.request(); Response response = null; try { response = requset.get(); return handleReadFileResponse(response); } finally { closeResponse(response); } } FileServiceClient(String baseUrl); FileServiceClient(String baseUrl, final String username, final String password); FileServiceClient(String baseUrl, final String authorizationHeader); FileServiceClient(String baseUrl, final String authorizationHeader,
final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); InputStream getFile(String cloudId, String representationName,
String version, String fileName); InputStream getFile(String cloudId, String representationName, String version,
String fileName, String range); InputStream getFile(String fileUrl); InputStream getFile(String fileUrl,String key,String value); URI uploadFile(String cloudId, String representationName, String version,
InputStream data, String mediaType, String expectedMd5); URI uploadFile(String cloudId, String representationName, String version,
InputStream data, String mediaType); URI uploadFile(String cloudId, String representationName, String version, String fileName,
InputStream data, String mediaType); @Deprecated URI uploadFile(String versionUrl, InputStream data, String mediaType); URI modyfiyFile(String cloudId, String representationName, String version,
InputStream data, String mediaType, String fileName, String expectedMd5); URI modifyFile(String fileUrl, InputStream data, String mediaType); void deleteFile(String cloudId, String representationName, String version, String fileName); URI getFileUri(String cloudId, String representationName, String version, String fileName); static Map<String, String> parseFileUri(String uri); void useAuthorizationHeader(final String authorizationHeader); void close(); } | @Betamax(tape = "files/shouldGetFileWithoutRange") @Test public void shouldGetFileWithoutRange() throws UnsupportedEncodingException, MCSException, IOException { byte[] contentBytes = MODIFIED_FILE_CONTENTS.getBytes("UTF-8"); String contentChecksum = Hashing.md5().hashBytes(contentBytes).toString(); FileServiceClient instance = new FileServiceClient(baseUrl, username, password); InputStream responseStream = instance.getFile(TEST_CLOUD_ID, TEST_REPRESENTATION_NAME, TEST_VERSION, UPLOADED_FILE_NAME); assertNotNull(responseStream); byte[] responseBytes = ByteStreams.toByteArray(responseStream); assertArrayEquals("Content is incorrect", contentBytes, responseBytes); String responseChecksum = Hashing.md5().hashBytes(responseBytes).toString(); assertEquals("Checksum is incorrect", contentChecksum, responseChecksum); }
@Betamax(tape = "files/shouldThrowWrongContentRangeExceptionForGetFileWithRangeWhenIncorrectFormat") @Test(expected = WrongContentRangeException.class) public void shouldThrowWrongContentRangeExceptionForGetFileWithRangeWhenIncorrectFormat() throws UnsupportedEncodingException, MCSException, IOException { int rangeStart = 1; int rangeEnd = 4; FileServiceClient instance = new FileServiceClient(baseUrl, username, password); String range = String.format("bytese=%d-%d", rangeStart, rangeEnd); instance.getFile(TEST_CLOUD_ID, TEST_REPRESENTATION_NAME, TEST_VERSION, unmovableFileName, range); }
@Betamax(tape = "files/shouldThrowWrongContentRangeExceptionForGetFileWithRangeWhenIncorrectRangeValues") @Test(expected = WrongContentRangeException.class) public void shouldThrowWrongContentRangeExceptionForGetFileWithRangeWhenIncorrectRangeValues() throws UnsupportedEncodingException, MCSException, IOException { int rangeStart = 1; int rangeEnd = 50; FileServiceClient instance = new FileServiceClient(baseUrl, username, password); String range = String.format("bytese=%d-%d", rangeStart, rangeEnd); instance.getFile(TEST_CLOUD_ID, TEST_REPRESENTATION_NAME, TEST_VERSION, unmovableFileName, range); }
@Betamax(tape = "files/shouldThrowAccessDeniedOrObjectDoesNotExistExceptionForGetFileWithoutRange") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowAccessDeniedOrObjectDoesNotExistExceptionForGetFileWithoutRange() throws UnsupportedEncodingException, MCSException, IOException { String incorrectFileName = "edefc11e-1c5f-4a71-adb6-28efdd7b3b00"; FileServiceClient instance = new FileServiceClient(baseUrl, username, password); instance.getFile(cloudId, representationName, version, incorrectFileName); }
@Betamax(tape = "files/shouldThrowRepresentationNotExistsForGetFileWithoutRangeWhenIncorrectCloudId") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowRepresentationNotExistsForGetFileWithoutRangeWhenIncorrectCloudId() throws UnsupportedEncodingException, MCSException, IOException { String incorrectCloudId = "7MZWQJF8P99"; FileServiceClient instance = new FileServiceClient(baseUrl, username, password); instance.getFile(incorrectCloudId, representationName, version, unmovableFileName); }
@Betamax(tape = "files/shouldThrowAccessDeniedOrObjectDoesNotExistExceptionForGetFileWithoutRangeWhenIncorrectRepresentationName") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowAccessDeniedOrObjectDoesNotExistExceptionForGetFileWithoutRangeWhenIncorrectRepresentationName() throws UnsupportedEncodingException, MCSException, IOException { String incorrectRepresentationName = "schema_000101"; FileServiceClient instance = new FileServiceClient(baseUrl, username, password); instance.getFile(cloudId, incorrectRepresentationName, version, unmovableFileName); }
@Betamax(tape = "files/shouldThrowAccessDeniedOrObjectDoesNotExistExceptionForGetFileWithoutRangeWhenIncorrectVersion") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowAccessDeniedOrObjectDoesNotExistExceptionForGetFileWithoutRangeWhenIncorrectVersion() throws UnsupportedEncodingException, MCSException, IOException { String incorrectVersion = "8a64f9b0-98b6-11e3-b072-50e549e85200"; FileServiceClient instance = new FileServiceClient(baseUrl, username, password); instance.getFile(cloudId, representationName, incorrectVersion, unmovableFileName); } |
CassandraAuthenticationService implements UserDetailsService, AuthenticationService { @Override public void deleteUser(final String userName) throws DatabaseConnectionException, UserDoesNotExistException { userDao.deleteUser(userName); } CassandraAuthenticationService(); CassandraAuthenticationService(CassandraUserDAO userDao); @Override UserDetails loadUserByUsername(final String userName); @Override User getUser(String userName); @Override void createUser(final User user); @Override void updateUser(final User user); @Override void deleteUser(final String userName); } | @Test(expected = UserDoesNotExistException.class) public void testDeleteUser() throws Exception { dao.createUser(new SpringUser("test3", "test3")); service.deleteUser("test3"); service.getUser("test3"); }
@Test(expected = UserDoesNotExistException.class) public void testDeleteUserException() throws Exception { service.deleteUser("test4"); } |
RemoverImpl implements Remover { @Override public void removeNotifications(long taskId) { int retries = DEFAULT_RETRIES; while (true) { try { subTaskInfoDAO.removeNotifications(taskId); break; } catch (Exception e) { if (retries-- > 0) { LOGGER.warn("Error while removing the logs. Retries left: " + retries); waitForTheNextCall(); } else { LOGGER.error("Error while removing the logs."); throw e; } } } } RemoverImpl(String hosts, int port, String keyspaceName, String userName, String password); RemoverImpl(CassandraSubTaskInfoDAO subTaskInfoDAO, CassandraTaskErrorsDAO taskErrorDAO, CassandraNodeStatisticsDAO cassandraNodeStatisticsDAO); @Override void removeNotifications(long taskId); @Override void removeErrorReports(long taskId); @Override void removeStatistics(long taskId); } | @Test public void shouldSuccessfullyRemoveNotifications() { doNothing().when(subTaskInfoDAO).removeNotifications(eq(TASK_ID)); removerImpl.removeNotifications(TASK_ID); verify(subTaskInfoDAO, times(1)).removeNotifications((eq(TASK_ID))); }
@Test(expected = Exception.class) public void shouldRetry5TimesBeforeFailing() { doThrow(Exception.class).when(subTaskInfoDAO).removeNotifications(eq(TASK_ID)); removerImpl.removeNotifications(TASK_ID); verify(subTaskInfoDAO, times(6)).removeNotifications((eq(TASK_ID))); } |
FileServiceClient extends MCSClient { public URI uploadFile(String cloudId, String representationName, String version, InputStream data, String mediaType, String expectedMd5) throws IOException, MCSException { Response response = null; FormDataMultiPart multipart = new FormDataMultiPart(); try { WebTarget target = client .target(baseUrl) .path(FILES_RESOURCE) .resolveTemplate(CLOUD_ID, cloudId) .resolveTemplate(REPRESENTATION_NAME, representationName) .resolveTemplate(VERSION, version); multipart .field(ParamConstants.F_FILE_MIME, mediaType) .bodyPart(new StreamDataBodyPart(ParamConstants.F_FILE_DATA, data, MediaType.APPLICATION_OCTET_STREAM)); Builder request = target.request(); response = request.post(Entity.entity(multipart, multipart.getMediaType())); return handleResponse(expectedMd5, response, Status.CREATED.getStatusCode()); } finally { closeOpenResources(data, multipart, response); } } FileServiceClient(String baseUrl); FileServiceClient(String baseUrl, final String username, final String password); FileServiceClient(String baseUrl, final String authorizationHeader); FileServiceClient(String baseUrl, final String authorizationHeader,
final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); InputStream getFile(String cloudId, String representationName,
String version, String fileName); InputStream getFile(String cloudId, String representationName, String version,
String fileName, String range); InputStream getFile(String fileUrl); InputStream getFile(String fileUrl,String key,String value); URI uploadFile(String cloudId, String representationName, String version,
InputStream data, String mediaType, String expectedMd5); URI uploadFile(String cloudId, String representationName, String version,
InputStream data, String mediaType); URI uploadFile(String cloudId, String representationName, String version, String fileName,
InputStream data, String mediaType); @Deprecated URI uploadFile(String versionUrl, InputStream data, String mediaType); URI modyfiyFile(String cloudId, String representationName, String version,
InputStream data, String mediaType, String fileName, String expectedMd5); URI modifyFile(String fileUrl, InputStream data, String mediaType); void deleteFile(String cloudId, String representationName, String version, String fileName); URI getFileUri(String cloudId, String representationName, String version, String fileName); static Map<String, String> parseFileUri(String uri); void useAuthorizationHeader(final String authorizationHeader); void close(); } | @Betamax(tape = "files/shouldUploadFile") @Test public void shouldUploadFile() throws UnsupportedEncodingException, MCSException, IOException { String contentString = UPLOADED_FILE_CONTENTS; byte[] contentBytes = contentString.getBytes("UTF-8"); InputStream contentStream = new ByteArrayInputStream(contentBytes); String contentChecksum = Hashing.md5().hashBytes(contentBytes).toString(); FileServiceClient instance = new FileServiceClient(baseUrl, username, password); URI uri = instance.uploadFile(TEST_CLOUD_ID, TEST_REPRESENTATION_NAME, TEST_VERSION, contentStream, mediaType); System.out.println(uri); assertNotNull(uri); }
@Betamax(tape = "files/shouldThrowRepresentationNotExistsExceptionForUploadFileWhenIncorrectCloudId") @Test(expected = RepresentationNotExistsException.class) public void shouldThrowRepresentationNotExistsExceptionForUploadFileWhenIncorrectCloudId() throws MCSException, IOException { String contentString = "Test_123456789_"; String incorrectCloudId = "7MZWQJS8P84"; byte[] contentBytes = contentString.getBytes("UTF-8"); InputStream contentStream = new ByteArrayInputStream(contentBytes); FileServiceClient instance = new FileServiceClient(baseUrl, username, password); instance.uploadFile(incorrectCloudId, representationName, version, contentStream, mediaType); }
@Betamax(tape = "files/shouldThrowRepresentationNotExistsExceptionForUploadFileWhenIncorrectRepresentationName") @Test(expected = RepresentationNotExistsException.class) public void shouldThrowRepresentationNotExistsExceptionForUploadFileWhenIncorrectRepresentationName() throws MCSException, IOException { String contentString = "Test_123456789_"; String incorrectRepresentationName = "schema_000101"; byte[] contentBytes = contentString.getBytes("UTF-8"); InputStream contentStream = new ByteArrayInputStream(contentBytes); FileServiceClient instance = new FileServiceClient(baseUrl, username, password); instance.uploadFile(cloudId, incorrectRepresentationName, version, contentStream, mediaType); }
@Betamax(tape = "files/shouldThrowRepresentationNotExistsExceptionForUploadFileWhenIncorrectVersion") @Test(expected = RepresentationNotExistsException.class) public void shouldThrowRepresentationNotExistsExceptionForUploadFileWhenIncorrectVersion() throws MCSException, IOException { String contentString = "Test_123456789_"; String incorrectVersion = "8a64f9b0-98b6-11e3-b072-50e549e85200"; byte[] contentBytes = contentString.getBytes("UTF-8"); InputStream contentStream = new ByteArrayInputStream(contentBytes); FileServiceClient instance = new FileServiceClient(baseUrl, username, password); instance.uploadFile(cloudId, representationName, incorrectVersion, contentStream, mediaType); }
@Betamax(tape = "files/shouldThrowCannotModifyPersistentRepresentationExceptionForUploadFile") @Test(expected = CannotModifyPersistentRepresentationException.class) public void shouldThrowCannotModifyPersistentRepresentationExceptionForUploadFile() throws MCSException, IOException { String contentString = "Test_123456789_"; String persistedVersion = "80441ab0-a38d-11e3-8614-50e549e85271"; byte[] contentBytes = contentString.getBytes("UTF-8"); InputStream contentStream = new ByteArrayInputStream(contentBytes); FileServiceClient instance = new FileServiceClient(baseUrl, username, password); instance.uploadFile(TEST_CLOUD_ID, TEST_REPRESENTATION_NAME, PERSISTED_VERSION, contentStream, mediaType); }
@Betamax(tape = "files/shouldUploadFileWithChecksum") @Test public void shouldUploadFileWithChecksum() throws UnsupportedEncodingException, MCSException, IOException { String contentString = "Test_123456789_1"; byte[] contentBytes = contentString.getBytes("UTF-8"); InputStream contentStream = new ByteArrayInputStream(contentBytes); String contentChecksum = Hashing.md5().hashBytes(contentBytes).toString(); FileServiceClient instance = new FileServiceClient(baseUrl, username, password); URI uri = instance.uploadFile(TEST_CLOUD_ID, TEST_REPRESENTATION_NAME, TEST_VERSION, contentStream, mediaType, contentChecksum); assertNotNull(uri); }
@Betamax(tape = "files/shouldThrowRepresentationNotExistsExceptionForUploadFileWithChecksumWhenIncorrectCloudId") @Test(expected = RepresentationNotExistsException.class) public void shouldThrowRepresentationNotExistsExceptionForUploadFileWithChecksumWhenIncorrectCloudId() throws UnsupportedEncodingException, MCSException, IOException { String incorrectCloudId = "7MZWQJF8P00"; String contentString = "Test_123456789_1"; byte[] contentBytes = contentString.getBytes("UTF-8"); InputStream contentStream = new ByteArrayInputStream(contentBytes); String contentChecksum = Hashing.md5().hashBytes(contentBytes).toString(); FileServiceClient instance = new FileServiceClient(baseUrl, username, password); instance.uploadFile(incorrectCloudId, representationName, version, contentStream, mediaType, contentChecksum); }
@Betamax(tape = "files/shouldThrowRepresentationNotExistsExceptionForUploadFileWithChecksumWhenIncorrectRepresentationName") @Test(expected = RepresentationNotExistsException.class) public void shouldThrowRepresentationNotExistsExceptionForUploadFileWithChecksumWhenIncorrectRepresentationName() throws UnsupportedEncodingException, MCSException, IOException { String incorrectRepresentationName = "schema_000101"; String contentString = "Test_123456789_1"; byte[] contentBytes = contentString.getBytes("UTF-8"); InputStream contentStream = new ByteArrayInputStream(contentBytes); String contentChecksum = Hashing.md5().hashBytes(contentBytes).toString(); FileServiceClient instance = new FileServiceClient(baseUrl, username, password); instance.uploadFile(cloudId, incorrectRepresentationName, version, contentStream, mediaType, contentChecksum); }
@Betamax(tape = "files/shouldThrowRepresentationNotExistsExceptionForUploadFileWithChecksumWhenIncorrectVersion") @Test(expected = RepresentationNotExistsException.class) public void shouldThrowRepresentationNotExistsExceptionForUploadFileWithChecksumWhenIncorrectVersion() throws UnsupportedEncodingException, MCSException, IOException { String incorrectVersion = "8a64f9b0-98b6-11e3-b072-50e549e85200"; String contentString = "Test_123456789_1"; byte[] contentBytes = contentString.getBytes("UTF-8"); InputStream contentStream = new ByteArrayInputStream(contentBytes); String contentChecksum = Hashing.md5().hashBytes(contentBytes).toString(); FileServiceClient instance = new FileServiceClient(baseUrl, username, password); instance.uploadFile(cloudId, representationName, incorrectVersion, contentStream, mediaType, contentChecksum); }
@Betamax(tape = "files/shouldThrowCannotModifyPersistentRepresentationExceptionForUploadFileWithChecksum") @Test(expected = CannotModifyPersistentRepresentationException.class) public void shouldThrowCannotModifyPersistentRepresentationExceptionForUploadFileWithChecksum() throws UnsupportedEncodingException, MCSException, IOException { String persistedVersion = "80441ab0-a38d-11e3-8614-50e549e85271"; String contentString = "Test_123456789_1"; byte[] contentBytes = contentString.getBytes("UTF-8"); InputStream contentStream = new ByteArrayInputStream(contentBytes); String contentChecksum = Hashing.md5().hashBytes(contentBytes).toString(); FileServiceClient instance = new FileServiceClient(baseUrl, username, password); instance.uploadFile(TEST_CLOUD_ID, TEST_REPRESENTATION_NAME, PERSISTED_VERSION, contentStream, mediaType, contentChecksum); }
@Betamax(tape = "files/shouldThrowIOExceptionForUploadFile") @Test(expected = IOException.class) public void shouldThrowIOExceptionForUploadFile() throws UnsupportedEncodingException, MCSException, IOException { String contentString = "Test_123456789_1"; byte[] contentBytes = contentString.getBytes("UTF-8"); InputStream contentStream = new ByteArrayInputStream(contentBytes); String contentChecksum = Hashing.md5().hashBytes(contentBytes).toString(); String incorrectContentChecksum = contentChecksum.substring(1) + "0"; FileServiceClient instance = new FileServiceClient(baseUrl, username, password); instance.uploadFile(TEST_CLOUD_ID, TEST_REPRESENTATION_NAME, TEST_VERSION, contentStream, mediaType, incorrectContentChecksum); } |
FileServiceClient extends MCSClient { public URI modyfiyFile(String cloudId, String representationName, String version, InputStream data, String mediaType, String fileName, String expectedMd5) throws IOException, MCSException { Response response = null; FormDataMultiPart multipart = new FormDataMultiPart(); try { WebTarget target = client .target(baseUrl) .path(FILE_RESOURCE) .resolveTemplate(CLOUD_ID, cloudId) .resolveTemplate(REPRESENTATION_NAME, representationName) .resolveTemplate(VERSION, version) .resolveTemplate(FILE_NAME, fileName); response = target.request().put(Entity.entity(data, mediaType)); return handleResponse(expectedMd5, response, Status.NO_CONTENT.getStatusCode()); } finally { closeOpenResources(data, multipart, response); } } FileServiceClient(String baseUrl); FileServiceClient(String baseUrl, final String username, final String password); FileServiceClient(String baseUrl, final String authorizationHeader); FileServiceClient(String baseUrl, final String authorizationHeader,
final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); InputStream getFile(String cloudId, String representationName,
String version, String fileName); InputStream getFile(String cloudId, String representationName, String version,
String fileName, String range); InputStream getFile(String fileUrl); InputStream getFile(String fileUrl,String key,String value); URI uploadFile(String cloudId, String representationName, String version,
InputStream data, String mediaType, String expectedMd5); URI uploadFile(String cloudId, String representationName, String version,
InputStream data, String mediaType); URI uploadFile(String cloudId, String representationName, String version, String fileName,
InputStream data, String mediaType); @Deprecated URI uploadFile(String versionUrl, InputStream data, String mediaType); URI modyfiyFile(String cloudId, String representationName, String version,
InputStream data, String mediaType, String fileName, String expectedMd5); URI modifyFile(String fileUrl, InputStream data, String mediaType); void deleteFile(String cloudId, String representationName, String version, String fileName); URI getFileUri(String cloudId, String representationName, String version, String fileName); static Map<String, String> parseFileUri(String uri); void useAuthorizationHeader(final String authorizationHeader); void close(); } | @Betamax(tape = "files/shouldModifyFile") @Test public void shouldModifyFile() throws UnsupportedEncodingException, IOException, MCSException { String contentString = MODIFIED_FILE_CONTENTS; byte[] contentBytes = contentString.getBytes("UTF-8"); InputStream contentStream = new ByteArrayInputStream(contentBytes); String contentChecksum = Hashing.md5().hashBytes(contentBytes).toString(); FileServiceClient instance = new FileServiceClient(baseUrl, username, password); URI uri = instance.modyfiyFile(TEST_CLOUD_ID, TEST_REPRESENTATION_NAME, TEST_VERSION, contentStream, mediaType, MODIFIED_FILE_NAME, contentChecksum); assertNotNull(uri); }
@Betamax(tape = "files/shouldThrowAccessDeniedOrObjectDoesNotExistExceptionForModifyFileWhenIncorrectCloudId") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowAccessDeniedOrObjectDoesNotExistExceptionForModifyFileWhenIncorrectCloudId() throws UnsupportedEncodingException, IOException, MCSException { String incorrectCloudId = "12c068c9-461d-484e-878f-099c5fca4400"; String contentString = "Test_123456789_123456"; byte[] contentBytes = contentString.getBytes("UTF-8"); InputStream contentStream = new ByteArrayInputStream(contentBytes); String contentChecksum = Hashing.md5().hashBytes(contentBytes).toString(); FileServiceClient instance = new FileServiceClient(baseUrl, username, password); instance.modyfiyFile(incorrectCloudId, representationName, version, contentStream, mediaType, modyfiedFileName, contentChecksum); }
@Betamax(tape = "files/shouldThrowAccessDeniedOrObjectDoesNotExistExceptionForModifyFileWhenIncorrectRepresentationName") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowAccessDeniedOrObjectDoesNotExistExceptionForModifyFileWhenIncorrectRepresentationName() throws UnsupportedEncodingException, IOException, MCSException { String incorrectRepresentationName = "schema_000101"; String contentString = "Test_123456789_123456"; byte[] contentBytes = contentString.getBytes("UTF-8"); InputStream contentStream = new ByteArrayInputStream(contentBytes); String contentChecksum = Hashing.md5().hashBytes(contentBytes).toString(); FileServiceClient instance = new FileServiceClient(baseUrl, username, password); instance.modyfiyFile(cloudId, incorrectRepresentationName, version, contentStream, mediaType, modyfiedFileName, contentChecksum); }
@Betamax(tape = "files/shouldThrowAccessDeniedOrObjectDoesNotExistExceptionForModifyFileWhenIncorrectVersion") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowAccessDeniedOrObjectDoesNotExistExceptionForModifyFileWhenIncorrectVersion() throws UnsupportedEncodingException, IOException, MCSException { String incorrectVersion = "8a64f9b0-98b6-11e3-b072-50e549e85200"; String contentString = "Test_123456789_123456"; byte[] contentBytes = contentString.getBytes("UTF-8"); InputStream contentStream = new ByteArrayInputStream(contentBytes); String contentChecksum = Hashing.md5().hashBytes(contentBytes).toString(); FileServiceClient instance = new FileServiceClient(baseUrl, username, password); instance.modyfiyFile(cloudId, representationName, incorrectVersion, contentStream, mediaType, modyfiedFileName, contentChecksum); }
@Betamax(tape = "files/shouldThrowIOExceptionForModifyFile") @Test(expected = IOException.class) public void shouldThrowIOExceptionForModifyFile() throws UnsupportedEncodingException, IOException, MCSException { String contentString = "Test_123456789_123456"; byte[] contentBytes = contentString.getBytes("UTF-8"); InputStream contentStream = new ByteArrayInputStream(contentBytes); String contentChecksum = Hashing.md5().hashBytes(contentBytes).toString(); String incorrectContentChecksum = contentChecksum.substring(1) + "0"; FileServiceClient instance = new FileServiceClient(baseUrl, username, password); instance.modyfiyFile(TEST_CLOUD_ID, TEST_REPRESENTATION_NAME, TEST_VERSION, contentStream, mediaType, MODIFIED_FILE_NAME, incorrectContentChecksum); } |
FileServiceClient extends MCSClient { public void deleteFile(String cloudId, String representationName, String version, String fileName) throws MCSException { WebTarget target = client .target(baseUrl) .path(FILE_RESOURCE) .resolveTemplate(CLOUD_ID, cloudId) .resolveTemplate(REPRESENTATION_NAME, representationName) .resolveTemplate(VERSION, version) .resolveTemplate(FILE_NAME, fileName); Response response = null; try { response = target.request().delete(); if (response.getStatus() != Response.Status.NO_CONTENT.getStatusCode()) { ErrorInfo errorInfo = response.readEntity(ErrorInfo.class); throw MCSExceptionProvider.generateException(errorInfo); } } finally { closeResponse(response); } } FileServiceClient(String baseUrl); FileServiceClient(String baseUrl, final String username, final String password); FileServiceClient(String baseUrl, final String authorizationHeader); FileServiceClient(String baseUrl, final String authorizationHeader,
final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); InputStream getFile(String cloudId, String representationName,
String version, String fileName); InputStream getFile(String cloudId, String representationName, String version,
String fileName, String range); InputStream getFile(String fileUrl); InputStream getFile(String fileUrl,String key,String value); URI uploadFile(String cloudId, String representationName, String version,
InputStream data, String mediaType, String expectedMd5); URI uploadFile(String cloudId, String representationName, String version,
InputStream data, String mediaType); URI uploadFile(String cloudId, String representationName, String version, String fileName,
InputStream data, String mediaType); @Deprecated URI uploadFile(String versionUrl, InputStream data, String mediaType); URI modyfiyFile(String cloudId, String representationName, String version,
InputStream data, String mediaType, String fileName, String expectedMd5); URI modifyFile(String fileUrl, InputStream data, String mediaType); void deleteFile(String cloudId, String representationName, String version, String fileName); URI getFileUri(String cloudId, String representationName, String version, String fileName); static Map<String, String> parseFileUri(String uri); void useAuthorizationHeader(final String authorizationHeader); void close(); } | @Betamax(tape = "files/shouldDeleteFile") public void shouldDeleteFile() throws MCSException { FileServiceClient instance = new FileServiceClient(baseUrl, username, password); instance.deleteFile(TEST_CLOUD_ID, TEST_REPRESENTATION_NAME, TEST_VERSION, UPLOADED_FILE_CONTENTS); Response response = BuildWebTarget(cloudId, representationName, version, deletedFileName).request().get(); assertEquals("", Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); }
@Betamax(tape = "files/shouldThrowAccessDeniedOrObjectDoesNotExistExceptionForDeleteFileWhenIncorrectCloudId") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowAccessDeniedOrObjectDoesNotExistExceptionForDeleteFileWhenIncorrectCloudId() throws MCSException { String incorrectCloudId = "7MZWQJF8P99"; FileServiceClient instance = new FileServiceClient(baseUrl, username, password); instance.deleteFile(incorrectCloudId, representationName, version, deletedFileName); }
@Betamax(tape = "files/shouldThrowAccessDeniedOrObjectDoesNotExistExceptionForDeleteFileWhenIncorrectRepresentationName") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowAccessDeniedOrObjectDoesNotExistExceptionForDeleteFileWhenIncorrectRepresentationName() throws MCSException { String incorrectRepresentationName = "schema_000101"; FileServiceClient instance = new FileServiceClient(baseUrl, username, password); instance.deleteFile(cloudId, incorrectRepresentationName, version, deletedFileName); }
@Betamax(tape = "files/shouldThrowAccessDeniedOrObjectDoesNotExistExceptionForDeleteFileWhenIncorrectVersion") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowAccessDeniedOrObjectDoesNotExistExceptionForDeleteFileWhenIncorrectVersion() throws MCSException { String incorrectVersion = "8a64f9b0-98b6-11e3-b072-50e549e85200"; FileServiceClient instance = new FileServiceClient(baseUrl, username, password); instance.deleteFile(cloudId, representationName, incorrectVersion, deletedFileName); }
@Betamax(tape = "files/shouldThrowAccessDeniedOrObjectDoesNotExistExceptionForDeleteFile") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowAccessDeniedOrObjectDoesNotExistExceptionForDeleteFile() throws MCSException { String notExistDeletedFileName = "d64b423b-1018-4526-ab4b-3539261ff000"; FileServiceClient instance = new FileServiceClient(baseUrl, username, password); instance.deleteFile(cloudId, representationName, version, notExistDeletedFileName); }
@Betamax(tape = "files/shouldThrowCannotModifyPersistentRepresentationExceptionForDeleteFile") @Test(expected = CannotModifyPersistentRepresentationException.class) public void shouldThrowCannotModifyPersistentRepresentationExceptionForDeleteFile() throws MCSException, UnsupportedEncodingException { FileServiceClient instance = new FileServiceClient(baseUrl, username, password); instance.deleteFile(TEST_CLOUD_ID, TEST_REPRESENTATION_NAME, "eb5c0a60-4306-11e4-8576-00163eefc9c8", DELETED_FILE_NAME); } |
CassandraAclService implements AclService { @Override public Acl readAclById(ObjectIdentity object) throws NotFoundException { return readAclById(object, null); } CassandraAclService(AclRepository aclRepository, AclCache aclCache, PermissionGrantingStrategy grantingStrategy,
AclAuthorizationStrategy aclAuthorizationStrategy, PermissionFactory permissionFactory); @Override List<ObjectIdentity> findChildren(ObjectIdentity parentIdentity); @Override Acl readAclById(ObjectIdentity object); @Override Acl readAclById(ObjectIdentity object, List<Sid> sids); @Override Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects); @Override Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects, List<Sid> sids); } | @Test(expected = NotFoundException.class) public void testCreateAndRetrieve() throws Exception { TestingAuthenticationToken auth = new TestingAuthenticationToken(creator, creator); auth.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(auth); ObjectIdentity obj = new ObjectIdentityImpl(testKey, testValue); MutableAcl acl = mutableAclService.createAcl(obj); acl.insertAce(0, BasePermission.READ, new PrincipalSid(creator), true); acl.insertAce(1, BasePermission.WRITE, new PrincipalSid(creator), true); acl.insertAce(2, BasePermission.DELETE, new PrincipalSid(creator), true); acl.insertAce(3, BasePermission.ADMINISTRATION, new PrincipalSid(creator), true); mutableAclService.updateAcl(acl); Acl readAcl = mutableAclService.readAclById(obj); Assert.assertTrue(acl.getEntries().size() == readAcl.getEntries().size()); mutableAclService.readAclById(new ObjectIdentityImpl(testKey, creator)); } |
RecordServiceClient extends MCSClient { public Record getRecord(String cloudId) throws MCSException { WebTarget target = client .target(baseUrl) .path(RECORDS_RESOURCE) .resolveTemplate(CLOUD_ID, cloudId); Builder request = target.request(); Response response = null; try { response = request.get(); if (response.getStatus() == Response.Status.OK.getStatusCode()) { return response.readEntity(Record.class); } ErrorInfo errorInfo = response.readEntity(ErrorInfo.class); throw MCSExceptionProvider.generateException(errorInfo); } finally { closeResponse(response); } } RecordServiceClient(String baseUrl); RecordServiceClient(String baseUrl, final int connectTimeoutInMillis, final int readTimeoutInMillis); RecordServiceClient(String baseUrl, final String username, final String password); RecordServiceClient(String baseUrl, final String authorizationHeader); RecordServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); void useAuthorizationHeader(final String authorizationHeader); Record getRecord(String cloudId); void deleteRecord(String cloudId); List<Representation> getRepresentations(String cloudId); Representation getRepresentation(String cloudId, String representationName); URI createRepresentation(String cloudId, String representationName, String providerId); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String fileName,
String mediaType); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String fileName,
String mediaType,
String key, String value); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String mediaType); void deleteRepresentation(String cloudId, String representationName); List<Representation> getRepresentations(String cloudId, String representationName); Representation getRepresentation(String cloudId, String representationName, String version); Representation getRepresentation(String cloudId, String representationName,
String version, String key, String value); void deleteRepresentation(String cloudId, String representationName, String version); void deleteRepresentation(String cloudId, String representationName, String version,
String key, String value); URI copyRepresentation(String cloudId, String representationName, String version); URI persistRepresentation(String cloudId, String representationName, String version); void grantPermissionsToVersion(String cloudId, String representationName, String version,
String userName, Permission permission); void revokePermissionsToVersion(String cloudId, String representationName, String version,
String userName, Permission permission); void permitVersion(String cloudId, String representationName, String version); List<Representation> getRepresentationsByRevision(
String cloudId, String representationName, String revisionName,
String revisionProviderId, String revisionTimestamp); List<Representation> getRepresentationsByRevision(
String cloudId,
String representationName,
String revisionName,
String revisionProviderId,
String revisionTimestamp,
String key,
String value); void close(); } | @Betamax(tape = "records_shouldRetrieveRecord") @Test public void shouldRetrieveRecord() throws MCSException { RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); Record record = instance.getRecord(CLOUD_ID); assertNotNull(record); assertEquals(CLOUD_ID, record.getCloudId()); }
@Betamax(tape = "records_shouldThrowRecordNotExistsForGetRecord") @Test(expected = RecordNotExistsException.class) public void shouldThrowRecordNotExistsForGetRecord() throws MCSException { String cloudId = "noSuchRecord"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.getRecord(cloudId); } |
RecordServiceClient extends MCSClient { public void deleteRecord(String cloudId) throws MCSException { WebTarget target = client .target(baseUrl) .path(RECORDS_RESOURCE) .resolveTemplate(CLOUD_ID, cloudId); Builder request = target.request(); handleDeleteRequest(request); } RecordServiceClient(String baseUrl); RecordServiceClient(String baseUrl, final int connectTimeoutInMillis, final int readTimeoutInMillis); RecordServiceClient(String baseUrl, final String username, final String password); RecordServiceClient(String baseUrl, final String authorizationHeader); RecordServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); void useAuthorizationHeader(final String authorizationHeader); Record getRecord(String cloudId); void deleteRecord(String cloudId); List<Representation> getRepresentations(String cloudId); Representation getRepresentation(String cloudId, String representationName); URI createRepresentation(String cloudId, String representationName, String providerId); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String fileName,
String mediaType); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String fileName,
String mediaType,
String key, String value); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String mediaType); void deleteRepresentation(String cloudId, String representationName); List<Representation> getRepresentations(String cloudId, String representationName); Representation getRepresentation(String cloudId, String representationName, String version); Representation getRepresentation(String cloudId, String representationName,
String version, String key, String value); void deleteRepresentation(String cloudId, String representationName, String version); void deleteRepresentation(String cloudId, String representationName, String version,
String key, String value); URI copyRepresentation(String cloudId, String representationName, String version); URI persistRepresentation(String cloudId, String representationName, String version); void grantPermissionsToVersion(String cloudId, String representationName, String version,
String userName, Permission permission); void revokePermissionsToVersion(String cloudId, String representationName, String version,
String userName, Permission permission); void permitVersion(String cloudId, String representationName, String version); List<Representation> getRepresentationsByRevision(
String cloudId, String representationName, String revisionName,
String revisionProviderId, String revisionTimestamp); List<Representation> getRepresentationsByRevision(
String cloudId,
String representationName,
String revisionName,
String revisionProviderId,
String revisionTimestamp,
String key,
String value); void close(); } | @Betamax(tape = "records_shouldThrowRecordNotExistsForDeleteRecord") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowRecordNotExistsForDeleteRecord() throws MCSException { String cloudId = "noSuchRecord"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.deleteRecord(cloudId); } |
RecordServiceClient extends MCSClient { public List<Representation> getRepresentations(String cloudId) throws MCSException { WebTarget target = client .target(baseUrl) .path(REPRESENTATIONS_RESOURCE) .resolveTemplate(CLOUD_ID, cloudId); Response response = null; try { response = target.request().get(); if (response.getStatus() == Response.Status.OK.getStatusCode()) { return response.readEntity(new GenericType<List<Representation>>() { }); } ErrorInfo errorInfo = response.readEntity(ErrorInfo.class); throw MCSExceptionProvider.generateException(errorInfo); } finally { closeResponse(response); } } RecordServiceClient(String baseUrl); RecordServiceClient(String baseUrl, final int connectTimeoutInMillis, final int readTimeoutInMillis); RecordServiceClient(String baseUrl, final String username, final String password); RecordServiceClient(String baseUrl, final String authorizationHeader); RecordServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); void useAuthorizationHeader(final String authorizationHeader); Record getRecord(String cloudId); void deleteRecord(String cloudId); List<Representation> getRepresentations(String cloudId); Representation getRepresentation(String cloudId, String representationName); URI createRepresentation(String cloudId, String representationName, String providerId); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String fileName,
String mediaType); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String fileName,
String mediaType,
String key, String value); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String mediaType); void deleteRepresentation(String cloudId, String representationName); List<Representation> getRepresentations(String cloudId, String representationName); Representation getRepresentation(String cloudId, String representationName, String version); Representation getRepresentation(String cloudId, String representationName,
String version, String key, String value); void deleteRepresentation(String cloudId, String representationName, String version); void deleteRepresentation(String cloudId, String representationName, String version,
String key, String value); URI copyRepresentation(String cloudId, String representationName, String version); URI persistRepresentation(String cloudId, String representationName, String version); void grantPermissionsToVersion(String cloudId, String representationName, String version,
String userName, Permission permission); void revokePermissionsToVersion(String cloudId, String representationName, String version,
String userName, Permission permission); void permitVersion(String cloudId, String representationName, String version); List<Representation> getRepresentationsByRevision(
String cloudId, String representationName, String revisionName,
String revisionProviderId, String revisionTimestamp); List<Representation> getRepresentationsByRevision(
String cloudId,
String representationName,
String revisionName,
String revisionProviderId,
String revisionTimestamp,
String key,
String value); void close(); } | @Betamax(tape = "records_shouldRetrieveRepresentations") @Test public void shouldRetrieveRepresentations() throws MCSException { RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); List<Representation> representationList = instance .getRepresentations(CLOUD_ID); assertNotNull(representationList); assertEquals(representationList.size(), 2); for (Representation representation : representationList) { assertEquals(CLOUD_ID, representation.getCloudId()); assertTrue(representation.isPersistent()); } }
@Betamax(tape = "records_shouldThrowRecordNotExistsForGetRepresentations") @Test(expected = RecordNotExistsException.class) public void shouldThrowRecordNotExistsForGetRepresentations() throws MCSException { String cloudId = "noSuchRecord"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.getRepresentations(cloudId); }
@Betamax(tape = "records_shouldRetrieveSchemaVersions") @Test public void shouldRetrieveSchemaVersions() throws RepresentationNotExistsException, MCSException { RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); List<Representation> result = instance.getRepresentations(CLOUD_ID, REPRESENTATION_NAME); assertNotNull(result); assertThat(result.size(), greaterThan(1)); for (Representation representation : result) { assertEquals(CLOUD_ID, representation.getCloudId()); assertEquals(REPRESENTATION_NAME, representation.getRepresentationName()); } }
@Betamax(tape = "records_shouldThrowRepresentationNotExistsForGetRepresentationNameVersionsWhenNoRepresentationName") @Test(expected = RepresentationNotExistsException.class) public void shouldThrowRepresentationNotExistsForGetRepresentationNameVersionsWhenNoRepresentationName() throws MCSException { String cloudId = "J93T5R6615H"; String representationName = "noSuchSchema"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.getRepresentations(cloudId, representationName); }
@Betamax(tape = "records_shouldThrowRepresentationNotExistsForGetRepresentationNameVersionsWhenNoRecord") @Test(expected = RepresentationNotExistsException.class) public void shouldThrowRepresentationNotExistsForGetRepresentationNameVersionsWhenNoRecord() throws MCSException { String cloudId = "noSuchRecord"; String representationName = "schema1"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.getRepresentations(cloudId, representationName); } |
RecordServiceClient extends MCSClient { public Representation getRepresentation(String cloudId, String representationName) throws MCSException { WebTarget target = client .target(baseUrl) .path(REPRESENTATION_RESOURCE) .resolveTemplate(CLOUD_ID, cloudId) .resolveTemplate(REPRESENTATION_NAME, representationName); Builder request = target.request(); Response response = null; try { response = request.get(); if (response.getStatus() == Response.Status.OK.getStatusCode() || response.getStatus() == Response.Status.TEMPORARY_REDIRECT.getStatusCode()) { return response.readEntity(Representation.class); } else { ErrorInfo errorInfo = response.readEntity(ErrorInfo.class); throw MCSExceptionProvider.generateException(errorInfo); } } finally { closeResponse(response); } } RecordServiceClient(String baseUrl); RecordServiceClient(String baseUrl, final int connectTimeoutInMillis, final int readTimeoutInMillis); RecordServiceClient(String baseUrl, final String username, final String password); RecordServiceClient(String baseUrl, final String authorizationHeader); RecordServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); void useAuthorizationHeader(final String authorizationHeader); Record getRecord(String cloudId); void deleteRecord(String cloudId); List<Representation> getRepresentations(String cloudId); Representation getRepresentation(String cloudId, String representationName); URI createRepresentation(String cloudId, String representationName, String providerId); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String fileName,
String mediaType); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String fileName,
String mediaType,
String key, String value); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String mediaType); void deleteRepresentation(String cloudId, String representationName); List<Representation> getRepresentations(String cloudId, String representationName); Representation getRepresentation(String cloudId, String representationName, String version); Representation getRepresentation(String cloudId, String representationName,
String version, String key, String value); void deleteRepresentation(String cloudId, String representationName, String version); void deleteRepresentation(String cloudId, String representationName, String version,
String key, String value); URI copyRepresentation(String cloudId, String representationName, String version); URI persistRepresentation(String cloudId, String representationName, String version); void grantPermissionsToVersion(String cloudId, String representationName, String version,
String userName, Permission permission); void revokePermissionsToVersion(String cloudId, String representationName, String version,
String userName, Permission permission); void permitVersion(String cloudId, String representationName, String version); List<Representation> getRepresentationsByRevision(
String cloudId, String representationName, String revisionName,
String revisionProviderId, String revisionTimestamp); List<Representation> getRepresentationsByRevision(
String cloudId,
String representationName,
String revisionName,
String revisionProviderId,
String revisionTimestamp,
String key,
String value); void close(); } | @Betamax(tape = "records_shouldRetrieveLastPersistentRepresentationForRepresentationName") @Test public void shouldRetrieveLastPersistentRepresentationForRepresentationName() throws MCSException { RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); Representation representation = instance.getRepresentation(CLOUD_ID, REPRESENTATION_NAME); assertNotNull(representation); assertTrue(representation.isPersistent()); }
@Betamax(tape = "records_shouldThrowRepresentationNotExistsForGetRepresentationForRepresentationNameWhenNoRepresentationName") @Test(expected = RepresentationNotExistsException.class) public void shouldThrowRepresentationNotExistsForGetRepresentationForRepresentationNameWhenNoRepresentationName() throws MCSException { String cloudId = "7MZWQJF8P84"; String representationName = "noSuchSchema"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.getRepresentation(cloudId, representationName); }
@Betamax(tape = "records_shouldThrowRepresentationNotExistsForGetRepresentationForRepresentationNameWhenNoPersistent") @Test(expected = RepresentationNotExistsException.class) public void shouldThrowRepresentationNotExistsForGetRepresentationForRepresentationNameWhenNoPersistent() throws MCSException { String cloudId = "GWV0RHNSSGJ"; String representationName = "schema1"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.getRepresentation(cloudId, representationName); }
@Betamax(tape = "records_shouldRetrieveRepresentationVersion") @Test public void shouldRetrieveRepresentationVersion() throws MCSException { RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); Representation representation = instance.getRepresentation(CLOUD_ID, REPRESENTATION_NAME, VERSION); assertNotNull(representation); assertEquals(CLOUD_ID, representation.getCloudId()); assertEquals(REPRESENTATION_NAME, representation.getRepresentationName()); assertEquals(VERSION, representation.getVersion()); }
@Ignore @Test public void shouldRetrieveLatestRepresentationVersion() throws MCSException { String cloudId = "J93T5R6615H"; String representationName = "schema22"; String version = "LATEST"; String versionCode = "88edb4d0-a2ef-11e3-89f5-1c6f653f6012"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); Representation representationLatest = instance.getRepresentation( cloudId, representationName, version); assertNotNull(representationLatest); assertEquals(cloudId, representationLatest.getCloudId()); assertEquals(representationName, representationLatest.getRepresentationName()); assertEquals(versionCode, representationLatest.getVersion()); Representation representation = instance.getRepresentation(cloudId, representationName); }
@Betamax(tape = "records_shouldThrowRepresentationNotExistsForGetRepresentationVersionWhenNoRecord") @Test(expected = RepresentationNotExistsException.class) public void shouldThrowRepresentationNotExistsForGetRepresentationVersionWhenNoRecord() throws MCSException { String cloudId = "noSuchRecord"; String representationName = "schema22"; String version = "74cc8410-a2d9-11e3-8a55-1c6f653f6012"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.getRepresentation(cloudId, representationName, version); }
@Betamax(tape = "records_shouldThrowRepresentationNotExistsForGetRepresentationVersionWhenNoRepresentationName") @Test(expected = RepresentationNotExistsException.class) public void shouldThrowRepresentationNotExistsForGetRepresentationVersionWhenNoRepresentationName() throws MCSException { String cloudId = "J93T5R6615H"; String representationName = "noSuchSchema"; String version = "74cc8410-a2d9-11e3-8a55-1c6f653f6012"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.getRepresentation(cloudId, representationName, version); }
@Betamax(tape = "records_shouldThrowRepresentationNotExistsForGetRepresentationVersionWhenNoSuchVersion") @Test(expected = RepresentationNotExistsException.class) public void shouldThrowRepresentationNotExistsForGetRepresentationVersionWhenNoSuchVersion() throws MCSException { String cloudId = "J93T5R6615H"; String representationName = "schema22"; String version = "74cc8410-a2d9-11e3-8a55-1c6f653f6013"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.getRepresentation(cloudId, representationName, version); } |
CassandraAclRepository implements AclRepository { @Override public Map<AclObjectIdentity, Set<AclEntry>> findAcls(List<AclObjectIdentity> objectIdsToLookup) { assertAclObjectIdentityList(objectIdsToLookup); if (LOG.isDebugEnabled()) { LOG.debug("BEGIN findAcls: objectIdentities: " + objectIdsToLookup); } List<String> ids = new ArrayList<>(objectIdsToLookup.size()); for (AclObjectIdentity entry : objectIdsToLookup) { ids.add(entry.getRowId()); } ResultSet resultSet = session.execute(QueryBuilder.select().all().from(keyspace, AOI_TABLE) .where(QueryBuilder.in("id", ids.toArray())).setConsistencyLevel(ConsistencyLevel.QUORUM)); Map<AclObjectIdentity, Set<AclEntry>> resultMap = new HashMap<>(); for (Row row : resultSet.all()) { resultMap.put(convertToAclObjectIdentity(row, true), new TreeSet<>(new Comparator<AclEntry>() { @Override public int compare(AclEntry o1, AclEntry o2) { return Integer.compare(o1.getOrder(), o2.getOrder()); } })); } resultSet = session.execute(QueryBuilder.select().all().from(keyspace, ACL_TABLE) .where(QueryBuilder.in("id", ids.toArray())).setConsistencyLevel(ConsistencyLevel.QUORUM)); for (Row row : resultSet.all()) { String aoiId = row.getString("id"); AclEntry aclEntry = new AclEntry(); aclEntry.setAuditFailure(row.getBool("isAuditFailure")); aclEntry.setAuditSuccess(row.getBool("isAuditSuccess")); aclEntry.setGranting(row.getBool("isGranting")); aclEntry.setMask(row.getInt("mask")); aclEntry.setOrder(row.getInt("aclOrder")); aclEntry.setSid(row.getString("sid")); aclEntry.setSidPrincipal(row.getBool("isSidPrincipal")); aclEntry.setId(aoiId + ":" + aclEntry.getSid() + ":" + aclEntry.getOrder()); for (Entry<AclObjectIdentity, Set<AclEntry>> entry : resultMap.entrySet()) { if (entry.getKey().getRowId().equals(aoiId)) { entry.getValue().add(aclEntry); break; } } } if (LOG.isDebugEnabled()) { LOG.debug("END findAcls: objectIdentities: " + resultMap.keySet() + ", aclEntries: " + resultMap.values()); } return resultMap; } CassandraAclRepository(CassandraConnectionProvider provider, boolean initSchema); CassandraAclRepository(Session session, String keyspace); CassandraAclRepository(Session session, String keyspace, boolean initSchema); @Override Map<AclObjectIdentity, Set<AclEntry>> findAcls(List<AclObjectIdentity> objectIdsToLookup); @Override AclObjectIdentity findAclObjectIdentity(AclObjectIdentity objectId); @Override List<AclObjectIdentity> findAclObjectIdentityChildren(AclObjectIdentity objectId); @Override void deleteAcls(List<AclObjectIdentity> objectIdsToDelete); @Override void saveAcl(AclObjectIdentity aoi); @Override void updateAcl(AclObjectIdentity aoi, List<AclEntry> entries); void createAoisTable(); void createChilrenTable(); void createAclsTable(); } | @Test(expected = IllegalArgumentException.class) public void testFindAclListEmpty() { service.findAcls(new ArrayList<AclObjectIdentity>()); }
@Test(expected = IllegalArgumentException.class) public void testFindNullAclList() { service.findAcls(null); } |
RecordServiceClient extends MCSClient { public URI createRepresentation(String cloudId, String representationName, String providerId) throws MCSException { WebTarget target = client .target(baseUrl) .path(REPRESENTATION_RESOURCE) .resolveTemplate(CLOUD_ID, cloudId) .resolveTemplate(REPRESENTATION_NAME, representationName); Builder request = target.request(); Form form = new Form(); form.param(PROVIDER_ID, providerId); Response response = null; return handleRepresentationResponse(form, request, response); } RecordServiceClient(String baseUrl); RecordServiceClient(String baseUrl, final int connectTimeoutInMillis, final int readTimeoutInMillis); RecordServiceClient(String baseUrl, final String username, final String password); RecordServiceClient(String baseUrl, final String authorizationHeader); RecordServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); void useAuthorizationHeader(final String authorizationHeader); Record getRecord(String cloudId); void deleteRecord(String cloudId); List<Representation> getRepresentations(String cloudId); Representation getRepresentation(String cloudId, String representationName); URI createRepresentation(String cloudId, String representationName, String providerId); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String fileName,
String mediaType); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String fileName,
String mediaType,
String key, String value); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String mediaType); void deleteRepresentation(String cloudId, String representationName); List<Representation> getRepresentations(String cloudId, String representationName); Representation getRepresentation(String cloudId, String representationName, String version); Representation getRepresentation(String cloudId, String representationName,
String version, String key, String value); void deleteRepresentation(String cloudId, String representationName, String version); void deleteRepresentation(String cloudId, String representationName, String version,
String key, String value); URI copyRepresentation(String cloudId, String representationName, String version); URI persistRepresentation(String cloudId, String representationName, String version); void grantPermissionsToVersion(String cloudId, String representationName, String version,
String userName, Permission permission); void revokePermissionsToVersion(String cloudId, String representationName, String version,
String userName, Permission permission); void permitVersion(String cloudId, String representationName, String version); List<Representation> getRepresentationsByRevision(
String cloudId, String representationName, String revisionName,
String revisionProviderId, String revisionTimestamp); List<Representation> getRepresentationsByRevision(
String cloudId,
String representationName,
String revisionName,
String revisionProviderId,
String revisionTimestamp,
String key,
String value); void close(); } | @Betamax(tape = "records_shouldThrowRecordNotExistsForCreateRepresentation") @Test(expected = RecordNotExistsException.class) public void shouldThrowRecordNotExistsForCreateRepresentation() throws MCSException { String cloudId = "noSuchRecord"; String representationName = "schema_000001"; String providerId = "Provider001"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.createRepresentation(cloudId, representationName, providerId); }
@Betamax(tape = "records_shouldThrowProviderNotExistsForCreateRepresentation") @Test(expected = ProviderNotExistsException.class) public void shouldThrowProviderNotExistsForCreateRepresentation() throws MCSException { String cloudId = "7MZWQJF8P84"; String representationName = "schema_000001"; String providerId = "noSuchProvider"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.createRepresentation(cloudId, representationName, providerId); }
@Test @Betamax(tape = "records_shouldCreateNewRepresentationAndUploadFile") public void shouldCreateNewRepresentationAndUploadAFile() throws IOException, FileNotFoundException, MCSException { RecordServiceClient client = new RecordServiceClient("http: InputStream stream = new ByteArrayInputStream("example File Content".getBytes(StandardCharsets.UTF_8)); client.createRepresentation("FGDNTHPJQAUTEIGAHOALM2PMFSDRD726U5LNGMPYZZ34ZNVT5YGA", "sampleRepresentationName9", "sampleProvider", stream, "fileName", "mediaType"); }
@Test @Betamax(tape = "records_shouldCreateNewRepresentationAndUploadFile") public void shouldCreateNewRepresentationAndUploadAFile_1() throws IOException, FileNotFoundException, MCSException { RecordServiceClient client = new RecordServiceClient("http: InputStream stream = new ByteArrayInputStream("example File Content".getBytes(StandardCharsets.UTF_8)); client.createRepresentation("FGDNTHPJQAUTEIGAHOALM2PMFSDRD726U5LNGMPYZZ34ZNVT5YGA", "sampleRepresentationName9", "sampleProvider", stream, "mediaType"); } |
RecordServiceClient extends MCSClient { public void deleteRepresentation(String cloudId, String representationName) throws MCSException { WebTarget target = client .target(baseUrl) .path(REPRESENTATION_RESOURCE) .resolveTemplate(CLOUD_ID, cloudId) .resolveTemplate(REPRESENTATION_NAME, representationName); Builder request = target.request(); handleDeleteRequest(request); } RecordServiceClient(String baseUrl); RecordServiceClient(String baseUrl, final int connectTimeoutInMillis, final int readTimeoutInMillis); RecordServiceClient(String baseUrl, final String username, final String password); RecordServiceClient(String baseUrl, final String authorizationHeader); RecordServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); void useAuthorizationHeader(final String authorizationHeader); Record getRecord(String cloudId); void deleteRecord(String cloudId); List<Representation> getRepresentations(String cloudId); Representation getRepresentation(String cloudId, String representationName); URI createRepresentation(String cloudId, String representationName, String providerId); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String fileName,
String mediaType); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String fileName,
String mediaType,
String key, String value); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String mediaType); void deleteRepresentation(String cloudId, String representationName); List<Representation> getRepresentations(String cloudId, String representationName); Representation getRepresentation(String cloudId, String representationName, String version); Representation getRepresentation(String cloudId, String representationName,
String version, String key, String value); void deleteRepresentation(String cloudId, String representationName, String version); void deleteRepresentation(String cloudId, String representationName, String version,
String key, String value); URI copyRepresentation(String cloudId, String representationName, String version); URI persistRepresentation(String cloudId, String representationName, String version); void grantPermissionsToVersion(String cloudId, String representationName, String version,
String userName, Permission permission); void revokePermissionsToVersion(String cloudId, String representationName, String version,
String userName, Permission permission); void permitVersion(String cloudId, String representationName, String version); List<Representation> getRepresentationsByRevision(
String cloudId, String representationName, String revisionName,
String revisionProviderId, String revisionTimestamp); List<Representation> getRepresentationsByRevision(
String cloudId,
String representationName,
String revisionName,
String revisionProviderId,
String revisionTimestamp,
String key,
String value); void close(); } | @Betamax(tape = "records_shouldThrowRepresentationNotExistsForDeleteRepresentationNameWhenNoRepresentationName") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowRepresentationNotExistsForDeleteRepresentationNameWhenNoRepresentationName() throws MCSException { String cloudId = "J93T5R6615H"; String representationName = "noSuchSchema"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.deleteRepresentation(cloudId, representationName); }
@Betamax(tape = "records_shouldThrowRepresentationNotExistsForDeleteRepresentationNameWhenNoRecord") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowRepresentationNotExistsForDeleteRepresentationNameWhenNoRecord() throws MCSException { String cloudId = "noSuchRecord"; String representationName = "schema1"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.deleteRepresentation(cloudId, representationName); }
@Betamax(tape = "records_shouldThrowRepresentationNotExistsForDeleteRepresentationVersionWhenNoRecord") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowRepresentationNotExistsForDeleteRepresentationVersionWhenNoRecord() throws MCSException { String cloudId = "noSuchRecord"; String representationName = "schema22"; String version = "74cc8410-a2d9-11e3-8a55-1c6f653f6012"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.deleteRepresentation(cloudId, representationName, version); }
@Betamax(tape = "records_shouldThrowRepresentationNotExistsForDeleteRepresentationVersionWhenNoRepresentationName") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowRepresentationNotExistsForDeleteRepresentationVersionWhenNoRepresentationName() throws MCSException { String cloudId = "J93T5R6615H"; String representationName = "noSuchSchema"; String version = "74cc8410-a2d9-11e3-8a55-1c6f653f6012"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.deleteRepresentation(cloudId, representationName, version); }
@Betamax(tape = "records_shouldThrowRepresentationNotExistsForDeleteRepresentationVersionWhenNoSuchVersion") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowRepresentationNotExistsForDeleteRepresentationVersionWhenNoSuchVersion() throws MCSException { String cloudId = "J93T5R6615H"; String representationName = "schema22"; String version = "74cc8410-a2d9-11e3-8a55-1c6f653f6013"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.deleteRepresentation(cloudId, representationName, version); }
@Betamax(tape = "records_shouldThrowAccessDeniedOrObjectDoesNotExistExceptionForDeleteRepresentationVersionWhenInvalidVersion") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowAccessDeniedOrObjectDoesNotExistExceptionForDeleteRepresentationVersionWhenInvalidVersion() throws MCSException { String cloudId = "J93T5R6615H"; String representationName = "schema22"; String version = "noSuchVersion"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.deleteRepresentation(cloudId, representationName, version); } |
RecordServiceClient extends MCSClient { public URI copyRepresentation(String cloudId, String representationName, String version) throws MCSException { WebTarget target = client .target(baseUrl) .path(REPRESENTATION_VERSION_COPY) .resolveTemplate(CLOUD_ID, cloudId) .resolveTemplate(REPRESENTATION_NAME, representationName) .resolveTemplate(VERSION, version); Builder request = target.request(); Response response = null; try { response = request.post(Entity.entity(new Form(), MediaType.APPLICATION_FORM_URLENCODED_TYPE)); if (response.getStatus() == Response.Status.CREATED.getStatusCode()) { return response.getLocation(); } else { ErrorInfo errorInfo = response.readEntity(ErrorInfo.class); throw MCSExceptionProvider.generateException(errorInfo); } } finally { closeResponse(response); } } RecordServiceClient(String baseUrl); RecordServiceClient(String baseUrl, final int connectTimeoutInMillis, final int readTimeoutInMillis); RecordServiceClient(String baseUrl, final String username, final String password); RecordServiceClient(String baseUrl, final String authorizationHeader); RecordServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); void useAuthorizationHeader(final String authorizationHeader); Record getRecord(String cloudId); void deleteRecord(String cloudId); List<Representation> getRepresentations(String cloudId); Representation getRepresentation(String cloudId, String representationName); URI createRepresentation(String cloudId, String representationName, String providerId); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String fileName,
String mediaType); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String fileName,
String mediaType,
String key, String value); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String mediaType); void deleteRepresentation(String cloudId, String representationName); List<Representation> getRepresentations(String cloudId, String representationName); Representation getRepresentation(String cloudId, String representationName, String version); Representation getRepresentation(String cloudId, String representationName,
String version, String key, String value); void deleteRepresentation(String cloudId, String representationName, String version); void deleteRepresentation(String cloudId, String representationName, String version,
String key, String value); URI copyRepresentation(String cloudId, String representationName, String version); URI persistRepresentation(String cloudId, String representationName, String version); void grantPermissionsToVersion(String cloudId, String representationName, String version,
String userName, Permission permission); void revokePermissionsToVersion(String cloudId, String representationName, String version,
String userName, Permission permission); void permitVersion(String cloudId, String representationName, String version); List<Representation> getRepresentationsByRevision(
String cloudId, String representationName, String revisionName,
String revisionProviderId, String revisionTimestamp); List<Representation> getRepresentationsByRevision(
String cloudId,
String representationName,
String revisionName,
String revisionProviderId,
String revisionTimestamp,
String key,
String value); void close(); } | @Betamax(tape = "records_shouldThrowRepresentationNotExistsForCopyRepresentationWhenNoRecord") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowRepresentationNotExistsForCopyRepresentationWhenNoRecord() throws MCSException { String cloudId = "noSuchRecord"; String representationName = "schema22"; String version = "88edb4d0-a2ef-11e3-89f5-1c6f653f6012"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.copyRepresentation(cloudId, representationName, version); }
@Betamax(tape = "records_shouldThrowRepresentationNotExistsForCopyRepresentationWhenNoRepresentationName") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowRepresentationNotExistsForCopyRepresentationWhenNoRepresentationName() throws MCSException { String cloudId = "J93T5R6615H"; String representationName = "noSuchSchema"; String version = "88edb4d0-a2ef-11e3-89f5-1c6f653f6012"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.copyRepresentation(cloudId, representationName, version); }
@Betamax(tape = "records_shouldThrowRepresentationNotExistsForCopyRepresentationVersionWhenNoSuchVersion") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowRepresentationNotExistsForCopyRepresentationVersionWhenNoSuchVersion() throws MCSException { String cloudId = "J93T5R6615H"; String representationName = "schema22"; String version = "88edb4d0-a2ef-11e3-89f5-1c6f653f6013"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.copyRepresentation(cloudId, representationName, version); }
@Betamax(tape = "records_shouldThrowAccessDeniedForCopyRepresentationVersionWhenInvalidVersion") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowAccessDeniedForCopyRepresentationVersionWhenInvalidVersion() throws MCSException { String cloudId = "J93T5R6615H"; String representationName = "schema22"; String version = "noSuchVersion"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.copyRepresentation(cloudId, representationName, version); } |
CassandraAclRepository implements AclRepository { @Override public AclObjectIdentity findAclObjectIdentity(AclObjectIdentity objectId) { assertAclObjectIdentity(objectId); if (LOG.isDebugEnabled()) { LOG.debug("BEGIN findAclObjectIdentity: objectIdentity: " + objectId); } Row row = session .execute(QueryBuilder.select().all().from(keyspace, AOI_TABLE) .where(QueryBuilder.eq("id", objectId.getRowId())).setConsistencyLevel(ConsistencyLevel.QUORUM)) .one(); AclObjectIdentity objectIdentity = convertToAclObjectIdentity(row, true); if (LOG.isDebugEnabled()) { LOG.debug("END findAclObjectIdentity: objectIdentity: " + objectIdentity); } return objectIdentity; } CassandraAclRepository(CassandraConnectionProvider provider, boolean initSchema); CassandraAclRepository(Session session, String keyspace); CassandraAclRepository(Session session, String keyspace, boolean initSchema); @Override Map<AclObjectIdentity, Set<AclEntry>> findAcls(List<AclObjectIdentity> objectIdsToLookup); @Override AclObjectIdentity findAclObjectIdentity(AclObjectIdentity objectId); @Override List<AclObjectIdentity> findAclObjectIdentityChildren(AclObjectIdentity objectId); @Override void deleteAcls(List<AclObjectIdentity> objectIdsToDelete); @Override void saveAcl(AclObjectIdentity aoi); @Override void updateAcl(AclObjectIdentity aoi, List<AclEntry> entries); void createAoisTable(); void createChilrenTable(); void createAclsTable(); } | @Test(expected = IllegalArgumentException.class) public void testFindNullAcl() { service.findAclObjectIdentity(null); }
@Test public void testFindAclNotExisting() { AclObjectIdentity newAoi = new AclObjectIdentity(); newAoi.setId("invalid"); newAoi.setObjectClass(aoi_class); newAoi.setOwnerId(sid1); service.findAclObjectIdentity(newAoi); }
@Test(expected = IllegalArgumentException.class) public void testFindAclWithNullValues() { AclObjectIdentity newAoi = new AclObjectIdentity(); service.findAclObjectIdentity(newAoi); } |
RecordServiceClient extends MCSClient { public URI persistRepresentation(String cloudId, String representationName, String version) throws MCSException { WebTarget target = client .target(baseUrl) .path(REPRESENTATION_VERSION_PERSIST) .resolveTemplate(CLOUD_ID, cloudId) .resolveTemplate(REPRESENTATION_NAME, representationName) .resolveTemplate(VERSION, version); Form form = new Form(); Builder request = target.request(); Response response = null; return handleRepresentationResponse(form, request, response); } RecordServiceClient(String baseUrl); RecordServiceClient(String baseUrl, final int connectTimeoutInMillis, final int readTimeoutInMillis); RecordServiceClient(String baseUrl, final String username, final String password); RecordServiceClient(String baseUrl, final String authorizationHeader); RecordServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); void useAuthorizationHeader(final String authorizationHeader); Record getRecord(String cloudId); void deleteRecord(String cloudId); List<Representation> getRepresentations(String cloudId); Representation getRepresentation(String cloudId, String representationName); URI createRepresentation(String cloudId, String representationName, String providerId); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String fileName,
String mediaType); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String fileName,
String mediaType,
String key, String value); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String mediaType); void deleteRepresentation(String cloudId, String representationName); List<Representation> getRepresentations(String cloudId, String representationName); Representation getRepresentation(String cloudId, String representationName, String version); Representation getRepresentation(String cloudId, String representationName,
String version, String key, String value); void deleteRepresentation(String cloudId, String representationName, String version); void deleteRepresentation(String cloudId, String representationName, String version,
String key, String value); URI copyRepresentation(String cloudId, String representationName, String version); URI persistRepresentation(String cloudId, String representationName, String version); void grantPermissionsToVersion(String cloudId, String representationName, String version,
String userName, Permission permission); void revokePermissionsToVersion(String cloudId, String representationName, String version,
String userName, Permission permission); void permitVersion(String cloudId, String representationName, String version); List<Representation> getRepresentationsByRevision(
String cloudId, String representationName, String revisionName,
String revisionProviderId, String revisionTimestamp); List<Representation> getRepresentationsByRevision(
String cloudId,
String representationName,
String revisionName,
String revisionProviderId,
String revisionTimestamp,
String key,
String value); void close(); } | @Betamax(tape = "records_shouldThrowRepresentationNotExistsExceptionForPersistRepresentationWhenNoRecord") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowRepresentationNotExistsExceptionForPersistRepresentationWhenNoRecord() throws MCSException, IOException { String cloudId = "noSuchRecord"; String representationName = "schema33"; String version = "fece3cb0-a5fb-11e3-b4a7-50e549e85271"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.persistRepresentation(cloudId, representationName, version); }
@Betamax(tape = "records_shouldThrowRepresentationNotExistsExceptionForPersistRepresentationWhenNoRepresentationName") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowRepresentationNotExistsExceptionForPersistRepresentationWhenNoRepresentationName() throws MCSException, IOException { String cloudId = "J93T5R6615H"; String representationName = "noSuchSchema"; String version = "fece3cb0-a5fb-11e3-b4a7-50e549e85271"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.persistRepresentation(cloudId, representationName, version); }
@Betamax(tape = "records_shouldThrowRepresentationNotExistsExceptionForPersistRepresentationWhenNoSuchVersion") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowRepresentationNotExistsExceptionForPersistRepresentationWhenNoSuchVersion() throws MCSException, IOException { String cloudId = "J93T5R6615H"; String representationName = "schema33"; String version = "fece3cb0-a5fb-11e3-b4a7-50e549e85204"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.persistRepresentation(cloudId, representationName, version); }
@Betamax(tape = "records_shouldThrowAccessDeniedOrObjectDoesNotExistExceptionForPersistRepresentationVersionWhenInvalidVersion") @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) public void shouldThrowAccessDeniedOrObjectDoesNotExistExceptionForPersistRepresentationVersionWhenInvalidVersion() throws MCSException, IOException { String cloudId = "J93T5R6615H"; String representationName = "schema33"; String version = "noSuchVersion"; RecordServiceClient instance = new RecordServiceClient(baseUrl, username, password); instance.persistRepresentation(cloudId, representationName, version); } |
RecordServiceClient extends MCSClient { public void grantPermissionsToVersion(String cloudId, String representationName, String version, String userName, Permission permission) throws MCSException { WebTarget target = client .target(baseUrl) .path(REPRESENTATION_PERMISSION) .resolveTemplate(CLOUD_ID, cloudId) .resolveTemplate(REPRESENTATION_NAME, representationName) .resolveTemplate(VERSION, version) .resolveTemplate(PERMISSION, permission.getValue()) .resolveTemplate(USER_NAME, userName); Builder request = target.request(); Response response = null; try { response = request.post(null); if(response.getStatus() == Response.Status.NOT_MODIFIED.getStatusCode()) { throw new MCSException("Permissions not modified"); } else if (response.getStatus() != Response.Status.OK.getStatusCode()) { throwException(response); } } finally { closeResponse(response); } } RecordServiceClient(String baseUrl); RecordServiceClient(String baseUrl, final int connectTimeoutInMillis, final int readTimeoutInMillis); RecordServiceClient(String baseUrl, final String username, final String password); RecordServiceClient(String baseUrl, final String authorizationHeader); RecordServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); void useAuthorizationHeader(final String authorizationHeader); Record getRecord(String cloudId); void deleteRecord(String cloudId); List<Representation> getRepresentations(String cloudId); Representation getRepresentation(String cloudId, String representationName); URI createRepresentation(String cloudId, String representationName, String providerId); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String fileName,
String mediaType); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String fileName,
String mediaType,
String key, String value); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String mediaType); void deleteRepresentation(String cloudId, String representationName); List<Representation> getRepresentations(String cloudId, String representationName); Representation getRepresentation(String cloudId, String representationName, String version); Representation getRepresentation(String cloudId, String representationName,
String version, String key, String value); void deleteRepresentation(String cloudId, String representationName, String version); void deleteRepresentation(String cloudId, String representationName, String version,
String key, String value); URI copyRepresentation(String cloudId, String representationName, String version); URI persistRepresentation(String cloudId, String representationName, String version); void grantPermissionsToVersion(String cloudId, String representationName, String version,
String userName, Permission permission); void revokePermissionsToVersion(String cloudId, String representationName, String version,
String userName, Permission permission); void permitVersion(String cloudId, String representationName, String version); List<Representation> getRepresentationsByRevision(
String cloudId, String representationName, String revisionName,
String revisionProviderId, String revisionTimestamp); List<Representation> getRepresentationsByRevision(
String cloudId,
String representationName,
String revisionName,
String revisionProviderId,
String revisionTimestamp,
String key,
String value); void close(); } | @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) @Betamax(tape = "records_shouldThrowAccessDeniedOrObjectDoesNotExistExceptionWhileTryingToUpdatePermissions") public void shouldThrowAccessDeniedOrObjectDoesNotExistExceptionWhileTryingToUpdatePermissions() throws MCSException, IOException { RecordServiceClient client = new RecordServiceClient("http: client.grantPermissionsToVersion(CLOUD_ID, REPRESENTATION_NAME, VERSION, "user", Permission.READ); }
@Test(expected = DriverException.class) @Betamax(tape = "records_shouldThrowDriverExceptionWhileMcsIsNotAvailable") public void shouldThrowMcsExceptionWhileMcsIsNotAvailable() throws MCSException { RecordServiceClient client = new RecordServiceClient("http: client.grantPermissionsToVersion(CLOUD_ID, REPRESENTATION_NAME, VERSION, "user", Permission.READ); } |
RecordServiceClient extends MCSClient { public void revokePermissionsToVersion(String cloudId, String representationName, String version, String userName, Permission permission) throws MCSException { WebTarget target = client .target(baseUrl) .path(REPRESENTATION_PERMISSION) .resolveTemplate(CLOUD_ID, cloudId) .resolveTemplate(REPRESENTATION_NAME, representationName) .resolveTemplate(VERSION, version) .resolveTemplate(PERMISSION, permission.getValue()) .resolveTemplate(USER_NAME, userName); Builder request = target.request(); handleDeleteRequest(request); } RecordServiceClient(String baseUrl); RecordServiceClient(String baseUrl, final int connectTimeoutInMillis, final int readTimeoutInMillis); RecordServiceClient(String baseUrl, final String username, final String password); RecordServiceClient(String baseUrl, final String authorizationHeader); RecordServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); void useAuthorizationHeader(final String authorizationHeader); Record getRecord(String cloudId); void deleteRecord(String cloudId); List<Representation> getRepresentations(String cloudId); Representation getRepresentation(String cloudId, String representationName); URI createRepresentation(String cloudId, String representationName, String providerId); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String fileName,
String mediaType); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String fileName,
String mediaType,
String key, String value); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String mediaType); void deleteRepresentation(String cloudId, String representationName); List<Representation> getRepresentations(String cloudId, String representationName); Representation getRepresentation(String cloudId, String representationName, String version); Representation getRepresentation(String cloudId, String representationName,
String version, String key, String value); void deleteRepresentation(String cloudId, String representationName, String version); void deleteRepresentation(String cloudId, String representationName, String version,
String key, String value); URI copyRepresentation(String cloudId, String representationName, String version); URI persistRepresentation(String cloudId, String representationName, String version); void grantPermissionsToVersion(String cloudId, String representationName, String version,
String userName, Permission permission); void revokePermissionsToVersion(String cloudId, String representationName, String version,
String userName, Permission permission); void permitVersion(String cloudId, String representationName, String version); List<Representation> getRepresentationsByRevision(
String cloudId, String representationName, String revisionName,
String revisionProviderId, String revisionTimestamp); List<Representation> getRepresentationsByRevision(
String cloudId,
String representationName,
String revisionName,
String revisionProviderId,
String revisionTimestamp,
String key,
String value); void close(); } | @Test(expected = AccessDeniedOrObjectDoesNotExistException.class) @Betamax(tape = "records_shouldThrowAccessDeniedOrObjectDoesNotExistExceptionWhileTryingToRevokePermissions") public void shouldThrowAccessDeniedOrObjectDoesNotExistExceptionWhileTryingToRevokePermissions() throws MCSException, IOException { RecordServiceClient client = new RecordServiceClient("http: client.revokePermissionsToVersion(CLOUD_ID, REPRESENTATION_NAME, VERSION, "user", Permission.READ); } |
RecordServiceClient extends MCSClient { public List<Representation> getRepresentationsByRevision( String cloudId, String representationName, String revisionName, String revisionProviderId, String revisionTimestamp) throws MCSException { WebTarget webtarget = client .target(baseUrl) .path(REPRESENTATION_REVISIONS_RESOURCE) .resolveTemplate(CLOUD_ID, cloudId) .resolveTemplate(REPRESENTATION_NAME, representationName) .resolveTemplate(REVISION_NAME, revisionName); if (revisionProviderId != null) { webtarget = webtarget.queryParam(F_REVISION_PROVIDER_ID, revisionProviderId); } else { throw new MCSException("RevisionProviderId is required"); } if (revisionTimestamp != null) { webtarget = webtarget.queryParam(F_REVISION_TIMESTAMP, revisionTimestamp); } Builder request = webtarget.request(); Response response = null; try { response = request.get(); if (response.getStatus() == Response.Status.OK.getStatusCode()) { return response.readEntity(new GenericType<List<Representation>>() {}); } else { ErrorInfo errorInfo = response.readEntity(ErrorInfo.class); throw MCSExceptionProvider.generateException(errorInfo); } } catch (MessageBodyProviderNotFoundException e) { String out = webtarget.getUri().toString(); throw new MCSException(out, e); } finally { closeResponse(response); } } RecordServiceClient(String baseUrl); RecordServiceClient(String baseUrl, final int connectTimeoutInMillis, final int readTimeoutInMillis); RecordServiceClient(String baseUrl, final String username, final String password); RecordServiceClient(String baseUrl, final String authorizationHeader); RecordServiceClient(String baseUrl, final String authorizationHeader, final String username, final String password,
final int connectTimeoutInMillis, final int readTimeoutInMillis); void useAuthorizationHeader(final String authorizationHeader); Record getRecord(String cloudId); void deleteRecord(String cloudId); List<Representation> getRepresentations(String cloudId); Representation getRepresentation(String cloudId, String representationName); URI createRepresentation(String cloudId, String representationName, String providerId); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String fileName,
String mediaType); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String fileName,
String mediaType,
String key, String value); URI createRepresentation(String cloudId,
String representationName,
String providerId,
InputStream data,
String mediaType); void deleteRepresentation(String cloudId, String representationName); List<Representation> getRepresentations(String cloudId, String representationName); Representation getRepresentation(String cloudId, String representationName, String version); Representation getRepresentation(String cloudId, String representationName,
String version, String key, String value); void deleteRepresentation(String cloudId, String representationName, String version); void deleteRepresentation(String cloudId, String representationName, String version,
String key, String value); URI copyRepresentation(String cloudId, String representationName, String version); URI persistRepresentation(String cloudId, String representationName, String version); void grantPermissionsToVersion(String cloudId, String representationName, String version,
String userName, Permission permission); void revokePermissionsToVersion(String cloudId, String representationName, String version,
String userName, Permission permission); void permitVersion(String cloudId, String representationName, String version); List<Representation> getRepresentationsByRevision(
String cloudId, String representationName, String revisionName,
String revisionProviderId, String revisionTimestamp); List<Representation> getRepresentationsByRevision(
String cloudId,
String representationName,
String revisionName,
String revisionProviderId,
String revisionTimestamp,
String key,
String value); void close(); } | @Betamax(tape = "records_shouldRetrieveRepresentationByRevision") @Test public void shouldRetrieveRepresentationRevision() throws MCSException { RecordServiceClient instance = new RecordServiceClient("http: List<Representation> representations = instance.getRepresentationsByRevision("Z6DX3RWCEFUUSGRUWP6QZWRIZKY7HI5Y7H4UD3OQVB3SRPAUVZHA", "REPRESENTATION1", "Revision_2", "Revision_Provider", "2018-08-28T07:13:34.658"); assertNotNull(representations); assertTrue(representations.size() == 1); assertEquals("REPRESENTATION1", representations.get(0).getRepresentationName()); assertEquals("68b4cc30-aa8d-11e8-8289-1c6f653f9042", representations.get(0).getVersion()); }
@Betamax(tape = "records_shouldThrowRepresentationNotExist") @Test(expected = RepresentationNotExistsException.class) public void shouldThrowRepresentationNotExists() throws MCSException { RecordServiceClient instance = new RecordServiceClient("http: instance.getRepresentationsByRevision("Z6DX3RWCEFUUSGRUWP6QZWRIZKY7HI5Y7H4UD3OQVB3SRPAUVZHA", "REPRESENTATION2", "Revision_2", "Revision_Provider", "2018-08-28T07:13:34.658"); } |
CassandraDataProviderService implements DataProviderService { @Override public DataProvider getProvider(String providerId) throws ProviderDoesNotExistException { LOGGER.info("getProvider() providerId='{}'", providerId); DataProvider dp = dataProviderDao.getProvider(providerId); if (dp == null) { LOGGER.warn("ProviderDoesNotExistException providerId='{}''", providerId); throw new ProviderDoesNotExistException(new IdentifierErrorInfo( IdentifierErrorTemplate.PROVIDER_DOES_NOT_EXIST.getHttpCode(), IdentifierErrorTemplate.PROVIDER_DOES_NOT_EXIST.getErrorInfo(providerId))); } else { return dp; } } CassandraDataProviderService(CassandraDataProviderDAO dataProviderDao); @Override ResultSlice<DataProvider> getProviders(String thresholdProviderId, int limit); @Override DataProvider getProvider(String providerId); @Override DataProvider createProvider(String providerId, DataProviderProperties properties); @Override DataProvider updateProvider(String providerId, DataProviderProperties properties); @Override DataProvider updateProvider(DataProvider dataProvider); @Override void deleteProvider(String providerId); } | @Test(expected = ProviderDoesNotExistException.class) public void shouldFailWhenFetchingNonExistingProvider() throws ProviderDoesNotExistException { cassandraDataProviderService.getProvider("provident"); } |
CassandraDataProviderService implements DataProviderService { @Override public ResultSlice<DataProvider> getProviders(String thresholdProviderId, int limit) { LOGGER.info("getProviders() thresholdProviderId='{}', limit='{}'", thresholdProviderId, limit); String nextProvider = null; List<DataProvider> providers = dataProviderDao.getProviders(thresholdProviderId, limit + 1); final int providerSize = providers.size(); if (providerSize == limit + 1) { nextProvider = providers.get(limit).getId(); providers.remove(limit); } LOGGER.info("getProviders() returning providers={} and nextProvider={} for thresholdProviderId='{}', limit='{}'", providerSize, nextProvider, thresholdProviderId, limit); return new ResultSlice<DataProvider>(nextProvider, providers); } CassandraDataProviderService(CassandraDataProviderDAO dataProviderDao); @Override ResultSlice<DataProvider> getProviders(String thresholdProviderId, int limit); @Override DataProvider getProvider(String providerId); @Override DataProvider createProvider(String providerId, DataProviderProperties properties); @Override DataProvider updateProvider(String providerId, DataProviderProperties properties); @Override DataProvider updateProvider(DataProvider dataProvider); @Override void deleteProvider(String providerId); } | @Test public void shouldReturnEmptyArrayWhenNoProviderAdded() { assertTrue("Expecting no providers", cassandraDataProviderService.getProviders(null, 1).getResults().isEmpty()); } |
CassandraDataProviderService implements DataProviderService { @Override public void deleteProvider(String providerId) throws ProviderDoesNotExistException { LOGGER.info("Deleting provider {}", providerId); DataProvider dp = dataProviderDao.getProvider(providerId); if (dp == null) { LOGGER.warn("ProviderDoesNotExistException providerId='{}'", providerId); throw new ProviderDoesNotExistException(new IdentifierErrorInfo( IdentifierErrorTemplate.PROVIDER_DOES_NOT_EXIST.getHttpCode(), IdentifierErrorTemplate.PROVIDER_DOES_NOT_EXIST.getErrorInfo(providerId))); } dataProviderDao.deleteProvider(providerId); } CassandraDataProviderService(CassandraDataProviderDAO dataProviderDao); @Override ResultSlice<DataProvider> getProviders(String thresholdProviderId, int limit); @Override DataProvider getProvider(String providerId); @Override DataProvider createProvider(String providerId, DataProviderProperties properties); @Override DataProvider updateProvider(String providerId, DataProviderProperties properties); @Override DataProvider updateProvider(DataProvider dataProvider); @Override void deleteProvider(String providerId); } | @Test(expected = ProviderDoesNotExistException.class) public void shouldThrowExceptionWhenDeletingNonExistingProvider() throws ProviderDoesNotExistException { cassandraDataProviderService.deleteProvider("not existing provident"); } |
CassandraUniqueIdentifierService implements UniqueIdentifierService { @Override public CloudId getCloudId(String providerId, String recordId) throws DatabaseConnectionException, RecordDoesNotExistException { LOGGER.info("getCloudId() providerId='{}', recordId='{}'", providerId, recordId); List<CloudId> cloudIds = localIdDao.searchById(providerId, recordId); if (cloudIds.isEmpty()) { throw new RecordDoesNotExistException(new IdentifierErrorInfo( IdentifierErrorTemplate.RECORD_DOES_NOT_EXIST.getHttpCode(), IdentifierErrorTemplate.RECORD_DOES_NOT_EXIST.getErrorInfo(providerId, recordId))); } final CloudId cloudId = cloudIds.get(0); LOGGER.info("getCloudId() returning cloudId='{}'", cloudId); return cloudId; } CassandraUniqueIdentifierService(CassandraCloudIdDAO cloudIdDao, CassandraLocalIdDAO localIdDao,
CassandraDataProviderDAO dataProviderDao); @Override CloudId createCloudId(String... recordInfo); @Override CloudId getCloudId(String providerId, String recordId); @Override List<CloudId> getLocalIdsByCloudId(String cloudId); @Override List<CloudId> getLocalIdsByProvider(String providerId, String start, int end); @Override List<CloudId> getCloudIdsByProvider(String providerId, String startRecordId, int limit); @Override CloudId createIdMapping(String cloudId, String providerId, String recordId); @Override void removeIdMapping(String providerId, String recordId); @Override List<CloudId> deleteCloudId(String cloudId); @Override String getHostList(); @Override String getKeyspace(); @Override String getPort(); @Override CloudId createIdMapping(String cloudId, String providerId); } | @Test(expected = RecordDoesNotExistException.class) public void testRecordDoesNotExist() throws Exception { service.getCloudId("test2", "test2"); } |
CassandraUniqueIdentifierService implements UniqueIdentifierService { @Override public List<CloudId> getLocalIdsByCloudId(String cloudId) throws DatabaseConnectionException, CloudIdDoesNotExistException { LOGGER.info("getLocalIdsByCloudId() cloudId='{}'", cloudId); List<CloudId> cloudIds = cloudIdDao.searchById(cloudId); if (cloudIds.isEmpty()) { LOGGER.warn("CloudIdDoesNotExistException for cloudId={}", cloudId); throw new CloudIdDoesNotExistException(new IdentifierErrorInfo( IdentifierErrorTemplate.CLOUDID_DOES_NOT_EXIST.getHttpCode(), IdentifierErrorTemplate.CLOUDID_DOES_NOT_EXIST.getErrorInfo(cloudId))); } List<CloudId> localIds = new ArrayList<>(); for (CloudId cId : cloudIds) { if (localIdDao.searchById(cId.getLocalId().getProviderId(), cId.getLocalId().getRecordId()).size() > 0) { localIds.add(cId); } } return localIds; } CassandraUniqueIdentifierService(CassandraCloudIdDAO cloudIdDao, CassandraLocalIdDAO localIdDao,
CassandraDataProviderDAO dataProviderDao); @Override CloudId createCloudId(String... recordInfo); @Override CloudId getCloudId(String providerId, String recordId); @Override List<CloudId> getLocalIdsByCloudId(String cloudId); @Override List<CloudId> getLocalIdsByProvider(String providerId, String start, int end); @Override List<CloudId> getCloudIdsByProvider(String providerId, String startRecordId, int limit); @Override CloudId createIdMapping(String cloudId, String providerId, String recordId); @Override void removeIdMapping(String providerId, String recordId); @Override List<CloudId> deleteCloudId(String cloudId); @Override String getHostList(); @Override String getKeyspace(); @Override String getPort(); @Override CloudId createIdMapping(String cloudId, String providerId); } | @Test(expected = CloudIdDoesNotExistException.class) public void testGetLocalIdsByCloudId() throws Exception { List<CloudId> gid = service.getLocalIdsByCloudId(IdGenerator .encodeWithSha256AndBase32("/test11/test11")); CloudId gId = service.createCloudId("test11", "test11"); gid = service.getLocalIdsByCloudId(gId.getId()); assertEquals(gid.size(), 1); } |
CassandraUniqueIdentifierService implements UniqueIdentifierService { @Override public List<CloudId> getCloudIdsByProvider(String providerId, String startRecordId, int limit) throws DatabaseConnectionException, ProviderDoesNotExistException { LOGGER.info("getCloudIdsByProvider() providerId='{}', startRecordId='{}', end='{}'", providerId, startRecordId, limit); if (dataProviderDao.getProvider(providerId) == null) { LOGGER.warn("ProviderDoesNotExistException for providerId='{}', startRecordId='{}', end='{}'", providerId, startRecordId, limit); throw new ProviderDoesNotExistException(new IdentifierErrorInfo( IdentifierErrorTemplate.PROVIDER_DOES_NOT_EXIST.getHttpCode(), IdentifierErrorTemplate.PROVIDER_DOES_NOT_EXIST.getErrorInfo(providerId))); } if (startRecordId == null) { return localIdDao.searchById(providerId); } else { return localIdDao.searchByIdWithPagination(startRecordId, limit, providerId); } } CassandraUniqueIdentifierService(CassandraCloudIdDAO cloudIdDao, CassandraLocalIdDAO localIdDao,
CassandraDataProviderDAO dataProviderDao); @Override CloudId createCloudId(String... recordInfo); @Override CloudId getCloudId(String providerId, String recordId); @Override List<CloudId> getLocalIdsByCloudId(String cloudId); @Override List<CloudId> getLocalIdsByProvider(String providerId, String start, int end); @Override List<CloudId> getCloudIdsByProvider(String providerId, String startRecordId, int limit); @Override CloudId createIdMapping(String cloudId, String providerId, String recordId); @Override void removeIdMapping(String providerId, String recordId); @Override List<CloudId> deleteCloudId(String cloudId); @Override String getHostList(); @Override String getKeyspace(); @Override String getPort(); @Override CloudId createIdMapping(String cloudId, String providerId); } | @Test public void testGetCloudIdsByProvider() throws Exception { String providerId = "providerId"; dataProviderDao.createDataProvider(providerId, new DataProviderProperties()); service.createCloudId(providerId, "test3"); service.createCloudId(providerId, "test2"); List<CloudId> cIds = service .getCloudIdsByProvider(providerId, null, 10000); assertThat(cIds.size(), is(2)); } |
CassandraUniqueIdentifierService implements UniqueIdentifierService { @Override public CloudId createIdMapping(String cloudId, String providerId, String recordId) throws DatabaseConnectionException, CloudIdDoesNotExistException, IdHasBeenMappedException, ProviderDoesNotExistException, CloudIdAlreadyExistException { LOGGER.info("createIdMapping() creating mapping for cloudId='{}', providerId='{}', recordId='{}'", cloudId, providerId, recordId); if (dataProviderDao.getProvider(providerId) == null) { LOGGER.warn("ProviderDoesNotExistException for cloudId='{}', providerId='{}', recordId='{}'", cloudId, providerId, recordId); throw new ProviderDoesNotExistException(new IdentifierErrorInfo( IdentifierErrorTemplate.PROVIDER_DOES_NOT_EXIST.getHttpCode(), IdentifierErrorTemplate.PROVIDER_DOES_NOT_EXIST.getErrorInfo(providerId))); } List<CloudId> cloudIds = cloudIdDao.searchById(cloudId); if (cloudIds.isEmpty()) { LOGGER.warn("CloudIdDoesNotExistException for cloudId='{}', providerId='{}', recordId='{}'", cloudId, providerId, recordId); throw new CloudIdDoesNotExistException(new IdentifierErrorInfo( IdentifierErrorTemplate.CLOUDID_DOES_NOT_EXIST.getHttpCode(), IdentifierErrorTemplate.CLOUDID_DOES_NOT_EXIST.getErrorInfo(cloudId))); } List<CloudId> localIds = localIdDao.searchById(providerId, recordId); if (!localIds.isEmpty()) { LOGGER.warn("IdHasBeenMappedException for cloudId='{}', providerId='{}', recordId='{}'", cloudId, providerId, recordId); throw new IdHasBeenMappedException(new IdentifierErrorInfo( IdentifierErrorTemplate.ID_HAS_BEEN_MAPPED.getHttpCode(), IdentifierErrorTemplate.ID_HAS_BEEN_MAPPED.getErrorInfo(providerId, recordId, cloudId))); } localIdDao.insert(providerId, recordId, cloudId); cloudIdDao.insert(false, cloudId, providerId, recordId); CloudId newCloudId = new CloudId(); newCloudId.setId(cloudId); LocalId lid = new LocalId(); lid.setProviderId(providerId); lid.setRecordId(recordId); newCloudId.setLocalId(lid); LOGGER.info("createIdMapping() new mapping created! new cloudId='{}' for already " + "existing cloudId='{}', providerId='{}', recordId='{}'", newCloudId, cloudId, providerId, recordId); return newCloudId; } CassandraUniqueIdentifierService(CassandraCloudIdDAO cloudIdDao, CassandraLocalIdDAO localIdDao,
CassandraDataProviderDAO dataProviderDao); @Override CloudId createCloudId(String... recordInfo); @Override CloudId getCloudId(String providerId, String recordId); @Override List<CloudId> getLocalIdsByCloudId(String cloudId); @Override List<CloudId> getLocalIdsByProvider(String providerId, String start, int end); @Override List<CloudId> getCloudIdsByProvider(String providerId, String startRecordId, int limit); @Override CloudId createIdMapping(String cloudId, String providerId, String recordId); @Override void removeIdMapping(String providerId, String recordId); @Override List<CloudId> deleteCloudId(String cloudId); @Override String getHostList(); @Override String getKeyspace(); @Override String getPort(); @Override CloudId createIdMapping(String cloudId, String providerId); } | @Test(expected = IdHasBeenMappedException.class) public void testCreateIdMapping() throws Exception { dataProviderDao.createDataProvider("test12", new DataProviderProperties()); CloudId gid = service.createCloudId("test12", "test12"); service.createIdMapping(gid.getId(), "test12", "test13"); service.createIdMapping(gid.getId(), "test12", "test13"); } |
CassandraUniqueIdentifierService implements UniqueIdentifierService { @Override public void removeIdMapping(String providerId, String recordId) throws DatabaseConnectionException, ProviderDoesNotExistException { LOGGER.info("removeIdMapping() removing Id mapping for providerId='{}', recordId='{}' ...", providerId, recordId); if (dataProviderDao.getProvider(providerId) == null) { LOGGER.warn("ProviderDoesNotExistException for providerId='{}', recordId='{}'", providerId, recordId); throw new ProviderDoesNotExistException(new IdentifierErrorInfo( IdentifierErrorTemplate.PROVIDER_DOES_NOT_EXIST.getHttpCode(), IdentifierErrorTemplate.PROVIDER_DOES_NOT_EXIST.getErrorInfo(providerId))); } localIdDao.delete(providerId, recordId); LOGGER.info("Id mapping removed for providerId='{}', recordId='{}'", providerId, recordId); } CassandraUniqueIdentifierService(CassandraCloudIdDAO cloudIdDao, CassandraLocalIdDAO localIdDao,
CassandraDataProviderDAO dataProviderDao); @Override CloudId createCloudId(String... recordInfo); @Override CloudId getCloudId(String providerId, String recordId); @Override List<CloudId> getLocalIdsByCloudId(String cloudId); @Override List<CloudId> getLocalIdsByProvider(String providerId, String start, int end); @Override List<CloudId> getCloudIdsByProvider(String providerId, String startRecordId, int limit); @Override CloudId createIdMapping(String cloudId, String providerId, String recordId); @Override void removeIdMapping(String providerId, String recordId); @Override List<CloudId> deleteCloudId(String cloudId); @Override String getHostList(); @Override String getKeyspace(); @Override String getPort(); @Override CloudId createIdMapping(String cloudId, String providerId); } | @Test(expected = RecordDoesNotExistException.class) public void testRemoveIdMapping() throws Exception { dataProviderDao.createDataProvider("test16", new DataProviderProperties()); service.createCloudId("test16", "test16"); service.removeIdMapping("test16", "test16"); service.getCloudId("test16", "test16"); } |
CassandraUniqueIdentifierService implements UniqueIdentifierService { @Override public List<CloudId> deleteCloudId(String cloudId) throws DatabaseConnectionException, CloudIdDoesNotExistException { LOGGER.info("deleteCloudId() deleting cloudId='{}' ...", cloudId); if (cloudIdDao.searchById(cloudId).isEmpty()) { LOGGER.warn("CloudIdDoesNotExistException for cloudId='{}'", cloudId); throw new CloudIdDoesNotExistException(new IdentifierErrorInfo( IdentifierErrorTemplate.CLOUDID_DOES_NOT_EXIST.getHttpCode(), IdentifierErrorTemplate.CLOUDID_DOES_NOT_EXIST.getErrorInfo(cloudId))); } List<CloudId> localIds = cloudIdDao.searchAll(cloudId); for (CloudId cId : localIds) { localIdDao.delete(cId.getLocalId().getProviderId(), cId.getLocalId().getRecordId()); cloudIdDao.delete(cloudId, cId.getLocalId().getProviderId(), cId.getLocalId().getRecordId()); } LOGGER.info("CloudId deleted for cloudId='{}'", cloudId); return localIds; } CassandraUniqueIdentifierService(CassandraCloudIdDAO cloudIdDao, CassandraLocalIdDAO localIdDao,
CassandraDataProviderDAO dataProviderDao); @Override CloudId createCloudId(String... recordInfo); @Override CloudId getCloudId(String providerId, String recordId); @Override List<CloudId> getLocalIdsByCloudId(String cloudId); @Override List<CloudId> getLocalIdsByProvider(String providerId, String start, int end); @Override List<CloudId> getCloudIdsByProvider(String providerId, String startRecordId, int limit); @Override CloudId createIdMapping(String cloudId, String providerId, String recordId); @Override void removeIdMapping(String providerId, String recordId); @Override List<CloudId> deleteCloudId(String cloudId); @Override String getHostList(); @Override String getKeyspace(); @Override String getPort(); @Override CloudId createIdMapping(String cloudId, String providerId); } | @Test(expected = RecordDoesNotExistException.class) public void testDeleteCloudId() throws Exception { dataProviderDao.createDataProvider("test21", new DataProviderProperties()); CloudId cId = service.createCloudId("test21", "test21"); service.deleteCloudId(cId.getId()); service.getCloudId(cId.getLocalId().getProviderId(), cId.getLocalId() .getRecordId()); }
@Test(expected = CloudIdDoesNotExistException.class) public void testDeleteCloudIdException() throws Exception { service.deleteCloudId("test"); } |
CassandraUniqueIdentifierService implements UniqueIdentifierService { @Override public CloudId createCloudId(String... recordInfo) throws DatabaseConnectionException, RecordExistsException, ProviderDoesNotExistException, CloudIdAlreadyExistException { LOGGER.info("createCloudId() creating cloudId"); String providerId = recordInfo[0]; LOGGER.info("createCloudId() creating cloudId providerId={}", providerId); if (dataProviderDao.getProvider(providerId) == null) { LOGGER.warn("ProviderDoesNotExistException for providerId={}", providerId); throw new ProviderDoesNotExistException(new IdentifierErrorInfo( IdentifierErrorTemplate.PROVIDER_DOES_NOT_EXIST.getHttpCode(), IdentifierErrorTemplate.PROVIDER_DOES_NOT_EXIST.getErrorInfo(providerId))); } String recordId = recordInfo.length > 1 ? recordInfo[1] : IdGenerator.timeEncode(providerId); LOGGER.info("createCloudId() creating cloudId providerId='{}', recordId='{}'", providerId, recordId); if (!localIdDao.searchById(providerId, recordId).isEmpty()) { LOGGER.warn("RecordExistsException for providerId={}, recordId={}", providerId, recordId); throw new RecordExistsException(new IdentifierErrorInfo( IdentifierErrorTemplate.RECORD_EXISTS.getHttpCode(), IdentifierErrorTemplate.RECORD_EXISTS.getErrorInfo(providerId, recordId))); } String id = IdGenerator.encodeWithSha256AndBase32("/" + providerId + "/" + recordId); List<CloudId> cloudIds = cloudIdDao.insert(false, id, providerId, recordId); localIdDao.insert(providerId, recordId, id); CloudId cloudId = new CloudId(); cloudId.setId(cloudIds.get(0).getId()); LocalId lId = new LocalId(); lId.setProviderId(providerId); lId.setRecordId(recordId); cloudId.setLocalId(lId); return cloudId; } CassandraUniqueIdentifierService(CassandraCloudIdDAO cloudIdDao, CassandraLocalIdDAO localIdDao,
CassandraDataProviderDAO dataProviderDao); @Override CloudId createCloudId(String... recordInfo); @Override CloudId getCloudId(String providerId, String recordId); @Override List<CloudId> getLocalIdsByCloudId(String cloudId); @Override List<CloudId> getLocalIdsByProvider(String providerId, String start, int end); @Override List<CloudId> getCloudIdsByProvider(String providerId, String startRecordId, int limit); @Override CloudId createIdMapping(String cloudId, String providerId, String recordId); @Override void removeIdMapping(String providerId, String recordId); @Override List<CloudId> deleteCloudId(String cloudId); @Override String getHostList(); @Override String getKeyspace(); @Override String getPort(); @Override CloudId createIdMapping(String cloudId, String providerId); } | @Test @Ignore public void createCloudIdCollisonTest() throws DatabaseConnectionException, RecordExistsException, ProviderDoesNotExistException, RecordDatasetEmptyException, CloudIdDoesNotExistException, CloudIdAlreadyExistException { final Map<String, String> map = new HashMap<String, String>(); dataProviderDao.createDataProvider("testprovider", new DataProviderProperties()); for (BigInteger bigCounter = BigInteger.ONE; bigCounter .compareTo(new BigInteger("5000000")) < 0; bigCounter = bigCounter .add(BigInteger.ONE)) { final String counterString = bigCounter.toString(32); final String encodedId = service.createCloudId("testprovider") .getId(); if (map.containsKey(encodedId)) { throw new RuntimeException("bigCounter: " + bigCounter + " | counterString: " + counterString + " | encodedId:" + encodedId + " == collision with ==> " + map.get(encodedId)); } else { map.put(encodedId, "bigCounter: " + bigCounter + " | counterString: " + counterString + " | encodedId:" + encodedId); } } } |
CassandraCloudIdDAO { public List<CloudId> insert(boolean insertOnlyIfNoExist, String... args) throws DatabaseConnectionException, CloudIdAlreadyExistException { ResultSet rs = null; try { if (insertOnlyIfNoExist) { rs = dbService.getSession().execute(insertIfNoExistsStatement.bind(args[0], args[1], args[2])); Row row = rs.one(); if (!row.getBool("[applied]")) { throw new CloudIdAlreadyExistException(new IdentifierErrorInfo( IdentifierErrorTemplate.CLOUDID_ALREADY_EXIST.getHttpCode(), IdentifierErrorTemplate.CLOUDID_ALREADY_EXIST.getErrorInfo(args[0]))); } } else { dbService.getSession().execute(insertStatement.bind(args[0], args[1], args[2])); } } catch (NoHostAvailableException e) { throw new DatabaseConnectionException(new IdentifierErrorInfo( IdentifierErrorTemplate.DATABASE_CONNECTION_ERROR.getHttpCode(), IdentifierErrorTemplate.DATABASE_CONNECTION_ERROR.getErrorInfo(hostList, port, e.getMessage()))); } CloudId cId = new CloudId(); LocalId lId = new LocalId(); lId.setProviderId(args[1]); lId.setRecordId(args[2]); cId.setLocalId(lId); cId.setId(args[0]); List<CloudId> cIds = new ArrayList<>(); cIds.add(cId); return cIds; } CassandraCloudIdDAO(CassandraConnectionProvider dbService); List<CloudId> searchById(String... args); List<CloudId> searchAll(String args); List<CloudId> insert(boolean insertOnlyIfNoExist, String... args); void delete(String... args); String getHostList(); String getKeyspace(); String getPort(); } | @Test(expected = CloudIdAlreadyExistException.class) public void insert_tryInsertTheSameContentTwice_ThrowsCloudIdAlreadyExistException() throws Exception { final String providerId = "providerId"; final String recordId = "recordId"; final String id = "id"; service.insert(true, id, providerId, recordId); service.insert(true, id, providerId, recordId); } |
StaticUrlProvider implements UrlProvider { public String getBaseUrl() { return baseUrl; } StaticUrlProvider(final String serviceUrl); String getBaseUrl(); } | @Test @Parameters({"uis/,uis","uis,uis","uis public void shouldGetUrlWithoutSlashAtTheEnd(String inputSuffix, String expectedSuffix) { StaticUrlProvider provider = new StaticUrlProvider(URL_PREFIX + inputSuffix); String result = provider.getBaseUrl(); assertThat(result,is(URL_PREFIX + expectedSuffix)); } |
DateAdapter extends XmlAdapter<String, Date> { @Override public Date unmarshal(String stringDate) throws ParseException { if (stringDate == null || stringDate.isEmpty()) { return null; } try { Date date = GregorianCalendar.getInstance().getTime(); if(date == null){ throw new ParseException("Cannot parse the date. The accepted date format is "+FORMAT, 0); } return date; } catch (ParseException e) { throw new ParseException(e.getMessage() + ". The accepted date format is "+FORMAT, e.getErrorOffset()); } } @Override String marshal(Date date); @Override Date unmarshal(String stringDate); } | @Test public void shouldSerializeTheDateSuccessfully() throws ParseException { Date date = dateAdapter.unmarshal(DATE_STRING); assertEquals(cal.getTime(), date); }
@Test(expected = ParseException.class) public void shouldThrowParsingException() throws ParseException { String unParsedDateString = "2017-11-23"; dateAdapter.unmarshal(unParsedDateString); }
@Test public void shouldCreateNullDateInCaseEmptyOrNull() throws ParseException { assertNull(dateAdapter.unmarshal(null)); assertNull(dateAdapter.unmarshal("")); } |
DateAdapter extends XmlAdapter<String, Date> { @Override public String marshal(Date date) { if (date == null) { throw new RuntimeException("The revision creation Date shouldn't be null"); } return FORMATTER.format(date); } @Override String marshal(Date date); @Override Date unmarshal(String stringDate); } | @Test public void shouldDeSerializeTheDateSuccessfully() { assertEquals(dateAdapter.marshal(cal.getTime()), DATE_STRING); }
@Test(expected = RuntimeException.class) public void shouldThrowRunTimeException() { dateAdapter.marshal(null); } |
CassandraAclRepository implements AclRepository { @Override public List<AclObjectIdentity> findAclObjectIdentityChildren(AclObjectIdentity objectId) { assertAclObjectIdentity(objectId); if (LOG.isDebugEnabled()) { LOG.debug("BEGIN findAclObjectIdentityChildren: objectIdentity: " + objectId); } ResultSet resultSet = session.execute(QueryBuilder.select().all().from(keyspace, CHILDREN_TABLE) .where(QueryBuilder.eq("id", objectId.getRowId())).setConsistencyLevel(ConsistencyLevel.QUORUM)); List<AclObjectIdentity> result = new ArrayList<>(); for (Row row : resultSet.all()) { result.add(convertToAclObjectIdentity(row, false)); } if (LOG.isDebugEnabled()) { LOG.debug("END findAclObjectIdentityChildren: children: " + result); } return result; } CassandraAclRepository(CassandraConnectionProvider provider, boolean initSchema); CassandraAclRepository(Session session, String keyspace); CassandraAclRepository(Session session, String keyspace, boolean initSchema); @Override Map<AclObjectIdentity, Set<AclEntry>> findAcls(List<AclObjectIdentity> objectIdsToLookup); @Override AclObjectIdentity findAclObjectIdentity(AclObjectIdentity objectId); @Override List<AclObjectIdentity> findAclObjectIdentityChildren(AclObjectIdentity objectId); @Override void deleteAcls(List<AclObjectIdentity> objectIdsToDelete); @Override void saveAcl(AclObjectIdentity aoi); @Override void updateAcl(AclObjectIdentity aoi, List<AclEntry> entries); void createAoisTable(); void createChilrenTable(); void createAclsTable(); } | @Test public void testFindAclChildrenForNotExistingAcl() { AclObjectIdentity newAoi = new AclObjectIdentity(); newAoi.setId("invalid"); newAoi.setObjectClass(aoi_class); newAoi.setOwnerId(sid1); List<AclObjectIdentity> children = service .findAclObjectIdentityChildren(newAoi); assertTrue(children.isEmpty()); }
@Test(expected = IllegalArgumentException.class) public void testFindNullAclChildren() { service.findAclObjectIdentityChildren(null); }
@Test(expected = IllegalArgumentException.class) public void testFindAclChildrenWithNullValues() { AclObjectIdentity newAoi = new AclObjectIdentity(); service.findAclObjectIdentityChildren(newAoi); } |
CassandraAclRepository implements AclRepository { @Override public void updateAcl(AclObjectIdentity aoi, List<AclEntry> entries) throws AclNotFoundException { assertAclObjectIdentity(aoi); if (LOG.isDebugEnabled()) { LOG.debug("BEGIN updateAcl: aclObjectIdentity: " + aoi + ", entries: " + entries); } AclObjectIdentity persistedAoi = findAclObjectIdentity(aoi); if (persistedAoi == null) { throw new AclNotFoundException("Object identity '" + aoi + "' does not exist"); } Batch batch = QueryBuilder.batch(); batch.add(QueryBuilder.insertInto(keyspace, AOI_TABLE).values(AOI_KEYS, new Object[] { aoi.getRowId(), aoi.getId(), aoi.getObjectClass(), aoi.isEntriesInheriting(), aoi.getOwnerId(), aoi.isOwnerPrincipal(), aoi.getParentObjectId(), aoi.getParentObjectClass() })); batch.add(QueryBuilder.delete().all().from(keyspace, ACL_TABLE).where(QueryBuilder.eq("id", aoi.getRowId()))); boolean parentChanged = false; if (!(persistedAoi.getParentRowId() == null ? aoi.getParentRowId() == null : persistedAoi.getParentRowId().equals(aoi.getParentRowId()))) { parentChanged = true; if (persistedAoi.getParentRowId() != null) { batch.add(QueryBuilder.delete().all().from(keyspace, CHILDREN_TABLE) .where(QueryBuilder.eq("id", persistedAoi.getParentRowId())) .and(QueryBuilder.eq("childId", aoi.getRowId()))).setConsistencyLevel(ConsistencyLevel.QUORUM); } } session.execute(batch); batch = QueryBuilder.batch(); boolean executeBatch = false; if (entries != null && !entries.isEmpty()) { for (AclEntry entry : entries) { batch.add(QueryBuilder.insertInto(keyspace, ACL_TABLE).values(ACL_KEYS, new Object[] { aoi.getRowId(), entry.getOrder(), entry.getSid(), entry.getMask(), entry.isSidPrincipal(), entry.isGranting(), entry.isAuditSuccess(), entry.isAuditFailure() })); } executeBatch = true; } if (parentChanged) { if (aoi.getParentRowId() != null) { batch.add(QueryBuilder.insertInto(keyspace, CHILDREN_TABLE).values(CHILD_KEYS, new Object[] { aoi.getParentRowId(), aoi.getRowId(), aoi.getId(), aoi.getObjectClass() })) .setConsistencyLevel(ConsistencyLevel.QUORUM); } executeBatch = true; } if (executeBatch) { session.execute(batch); } if (LOG.isDebugEnabled()) { LOG.debug("END updateAcl"); } } CassandraAclRepository(CassandraConnectionProvider provider, boolean initSchema); CassandraAclRepository(Session session, String keyspace); CassandraAclRepository(Session session, String keyspace, boolean initSchema); @Override Map<AclObjectIdentity, Set<AclEntry>> findAcls(List<AclObjectIdentity> objectIdsToLookup); @Override AclObjectIdentity findAclObjectIdentity(AclObjectIdentity objectId); @Override List<AclObjectIdentity> findAclObjectIdentityChildren(AclObjectIdentity objectId); @Override void deleteAcls(List<AclObjectIdentity> objectIdsToDelete); @Override void saveAcl(AclObjectIdentity aoi); @Override void updateAcl(AclObjectIdentity aoi, List<AclEntry> entries); void createAoisTable(); void createChilrenTable(); void createAclsTable(); } | @Test(expected = IllegalArgumentException.class) public void testUpdateNullAcl() { service.updateAcl(null, null); }
@Test(expected = AclNotFoundException.class) public void testUpdateAclNotExisting() { AclObjectIdentity newAoi = new AclObjectIdentity(); newAoi.setId("invalid"); newAoi.setObjectClass(aoi_class); newAoi.setOwnerId(sid1); service.updateAcl(newAoi, new ArrayList<AclEntry>()); } |
CassandraAclRepository implements AclRepository { @Override public void saveAcl(AclObjectIdentity aoi) throws AclAlreadyExistsException { assertAclObjectIdentity(aoi); if (LOG.isDebugEnabled()) { LOG.debug("BEGIN saveAcl: aclObjectIdentity: " + aoi); } if (findAclObjectIdentity(aoi) != null) { throw new AclAlreadyExistsException("Object identity '" + aoi + "' already exists"); } Batch batch = QueryBuilder.batch(); batch.add(QueryBuilder.insertInto(keyspace, AOI_TABLE).values(AOI_KEYS, new Object[] { aoi.getRowId(), aoi.getId(), aoi.getObjectClass(), aoi.isEntriesInheriting(), aoi.getOwnerId(), aoi.isOwnerPrincipal(), aoi.getParentObjectId(), aoi.getParentObjectClass() })) .setConsistencyLevel(ConsistencyLevel.QUORUM); if (aoi.getParentRowId() != null) { batch.add(QueryBuilder.insertInto(keyspace, CHILDREN_TABLE).values(CHILD_KEYS, new Object[] { aoi.getParentRowId(), aoi.getRowId(), aoi.getId(), aoi.getObjectClass() })) .setConsistencyLevel(ConsistencyLevel.QUORUM); } session.execute(batch); if (LOG.isDebugEnabled()) { LOG.debug("END saveAcl"); } } CassandraAclRepository(CassandraConnectionProvider provider, boolean initSchema); CassandraAclRepository(Session session, String keyspace); CassandraAclRepository(Session session, String keyspace, boolean initSchema); @Override Map<AclObjectIdentity, Set<AclEntry>> findAcls(List<AclObjectIdentity> objectIdsToLookup); @Override AclObjectIdentity findAclObjectIdentity(AclObjectIdentity objectId); @Override List<AclObjectIdentity> findAclObjectIdentityChildren(AclObjectIdentity objectId); @Override void deleteAcls(List<AclObjectIdentity> objectIdsToDelete); @Override void saveAcl(AclObjectIdentity aoi); @Override void updateAcl(AclObjectIdentity aoi, List<AclEntry> entries); void createAoisTable(); void createChilrenTable(); void createAclsTable(); } | @Test(expected = IllegalArgumentException.class) public void testSaveNullAcl() { service.saveAcl(null); }
@Test(expected = AclAlreadyExistsException.class) public void testSaveAclAlreadyExisting() { AclObjectIdentity newAoi = createDefaultTestAOI(); service.saveAcl(newAoi); service.saveAcl(newAoi); }
@Test(expected = IllegalArgumentException.class) public void testSaveAclWithNullValues() { AclObjectIdentity newAoi = new AclObjectIdentity(); service.saveAcl(newAoi); } |
CassandraAclRepository implements AclRepository { @Override public void deleteAcls(List<AclObjectIdentity> objectIdsToDelete) { assertAclObjectIdentityList(objectIdsToDelete); if (LOG.isDebugEnabled()) { LOG.debug("BEGIN deleteAcls: objectIdsToDelete: " + objectIdsToDelete); } List<String> ids = new ArrayList<>(objectIdsToDelete.size()); for (AclObjectIdentity entry : objectIdsToDelete) { ids.add(entry.getRowId()); } Batch batch = QueryBuilder.batch(); batch.add(QueryBuilder.delete().all().from(keyspace, AOI_TABLE).where(QueryBuilder.in("id", ids.toArray()))); batch.add(QueryBuilder.delete().all().from(keyspace, CHILDREN_TABLE) .where(QueryBuilder.in("id", ids.toArray()))).setConsistencyLevel(ConsistencyLevel.QUORUM); session.execute(batch); if (LOG.isDebugEnabled()) { LOG.debug("END deleteAcls"); } } CassandraAclRepository(CassandraConnectionProvider provider, boolean initSchema); CassandraAclRepository(Session session, String keyspace); CassandraAclRepository(Session session, String keyspace, boolean initSchema); @Override Map<AclObjectIdentity, Set<AclEntry>> findAcls(List<AclObjectIdentity> objectIdsToLookup); @Override AclObjectIdentity findAclObjectIdentity(AclObjectIdentity objectId); @Override List<AclObjectIdentity> findAclObjectIdentityChildren(AclObjectIdentity objectId); @Override void deleteAcls(List<AclObjectIdentity> objectIdsToDelete); @Override void saveAcl(AclObjectIdentity aoi); @Override void updateAcl(AclObjectIdentity aoi, List<AclEntry> entries); void createAoisTable(); void createChilrenTable(); void createAclsTable(); } | @Test(expected = IllegalArgumentException.class) public void testDeleteNullAcl() { service.deleteAcls(null); }
@Test public void testDeleteAclNotExisting() { AclObjectIdentity newAoi = new AclObjectIdentity(); newAoi.setId("invalid"); newAoi.setObjectClass(aoi_class); newAoi.setOwnerId(sid1); service.deleteAcls(Arrays.asList(new AclObjectIdentity[] { newAoi })); }
@Test(expected = IllegalArgumentException.class) public void testDeleteEmptyAclList() { service.deleteAcls(new ArrayList<AclObjectIdentity>()); }
@Test(expected = IllegalArgumentException.class) public void testDeleteAclWithNullValues() { AclObjectIdentity newAoi = new AclObjectIdentity(); service.deleteAcls(Arrays.asList(new AclObjectIdentity[] { newAoi })); } |
BucketsHandler { public Bucket getCurrentBucket(String bucketsTableName, String objectId) { String query = "SELECT object_id, bucket_id, rows_count FROM " + bucketsTableName + " WHERE object_id = '" + objectId + "';"; ResultSet rs = session.execute(query); List<Row> rows = rs.all(); Row row = rows.isEmpty() ? null : rows.get(rows.size() - 1); if (row != null) { return new Bucket( row.getString(OBJECT_ID_COLUMN_NAME), row.getUUID(BUCKET_ID_COLUMN_NAME).toString(), row.getLong(ROWS_COUNT_COLUMN_NAME)); } return null; } BucketsHandler(Session session); Bucket getCurrentBucket(String bucketsTableName, String objectId); void increaseBucketCount(String bucketsTableName, Bucket bucket); void decreaseBucketCount(String bucketsTableName, Bucket bucket); List<Bucket> getAllBuckets(String bucketsTableName, String objectId); Bucket getBucket(String bucketsTableName, Bucket bucket); Bucket getNextBucket(String bucketsTableName, String objectId); Bucket getNextBucket(String bucketsTableName, String objectId, Bucket bucket); void removeBucket(String bucketsTableName, Bucket bucket); static final String OBJECT_ID_COLUMN_NAME; static final String BUCKET_ID_COLUMN_NAME; static final String ROWS_COUNT_COLUMN_NAME; } | @Test public void currentBucketShouldBeNull() { Bucket bucket = bucketsHandler.getCurrentBucket(BUCKETS_TABLE_NAME, "sampleObject"); Assert.assertNull(bucket); } |
RemoverImpl implements Remover { @Override public void removeErrorReports(long taskId) { int retries = DEFAULT_RETRIES; while (true) { try { taskErrorDAO.removeErrors(taskId); break; } catch (Exception e) { if (retries-- > 0) { LOGGER.warn("Error while removing the error reports. Retries left: " + retries); waitForTheNextCall(); } else { LOGGER.error("Error while removing the error reports."); throw e; } } } } RemoverImpl(String hosts, int port, String keyspaceName, String userName, String password); RemoverImpl(CassandraSubTaskInfoDAO subTaskInfoDAO, CassandraTaskErrorsDAO taskErrorDAO, CassandraNodeStatisticsDAO cassandraNodeStatisticsDAO); @Override void removeNotifications(long taskId); @Override void removeErrorReports(long taskId); @Override void removeStatistics(long taskId); } | @Test public void shouldSuccessfullyRemoveErrors() { doNothing().when(taskErrorDAO).removeErrors(eq(TASK_ID)); removerImpl.removeErrorReports(TASK_ID); verify(taskErrorDAO, times(1)).removeErrors((eq(TASK_ID))); }
@Test(expected = Exception.class) public void shouldRetry5TimesBeforeFailingWhileRemovingErrorReports() { doThrow(Exception.class).when(taskErrorDAO).removeErrors(eq(TASK_ID)); removerImpl.removeErrorReports(TASK_ID); verify(taskErrorDAO, times(6)).removeErrors((eq(TASK_ID))); } |
BucketsHandler { public void increaseBucketCount(String bucketsTableName, Bucket bucket) { String query = "UPDATE " + bucketsTableName + " SET rows_count = rows_count + 1 WHERE object_id = '" + bucket.getObjectId() + "' AND bucket_id = " + UUID.fromString(bucket.getBucketId()) + ";"; session.execute(query); } BucketsHandler(Session session); Bucket getCurrentBucket(String bucketsTableName, String objectId); void increaseBucketCount(String bucketsTableName, Bucket bucket); void decreaseBucketCount(String bucketsTableName, Bucket bucket); List<Bucket> getAllBuckets(String bucketsTableName, String objectId); Bucket getBucket(String bucketsTableName, Bucket bucket); Bucket getNextBucket(String bucketsTableName, String objectId); Bucket getNextBucket(String bucketsTableName, String objectId, Bucket bucket); void removeBucket(String bucketsTableName, Bucket bucket); static final String OBJECT_ID_COLUMN_NAME; static final String BUCKET_ID_COLUMN_NAME; static final String ROWS_COUNT_COLUMN_NAME; } | @Test public void shouldCreateNewBucket() { Bucket bucket = new Bucket("sampleObjectId", new com.eaio.uuid.UUID().toString(), 0); bucketsHandler.increaseBucketCount(BUCKETS_TABLE_NAME, bucket); assertResults(bucket, 1); }
@Test public void shouldUpdateCounterForExistingBucket() { Bucket bucket = new Bucket("sampleObjectId", new com.eaio.uuid.UUID().toString(), 0); bucketsHandler.increaseBucketCount(BUCKETS_TABLE_NAME, bucket); bucketsHandler.increaseBucketCount(BUCKETS_TABLE_NAME, bucket); assertResults(bucket, 2); } |
StatisticsBolt extends AbstractDpsBolt { @Override public void execute(Tuple anchorTuple, StormTaskTuple stormTaskTuple) { try { if (!statsAlreadyCalculated(stormTaskTuple)) { LOGGER.info("Calculating file statistics for {}", stormTaskTuple); countStatistics(stormTaskTuple); markRecordStatsAsCalculated(stormTaskTuple); } else { LOGGER.info("File stats will NOT be calculated because if was already done in the previous attempt"); } stormTaskTuple.setFileData((byte[]) null); outputCollector.emit(anchorTuple, stormTaskTuple.toStormTuple()); } catch (Exception e) { emitErrorNotification(anchorTuple, stormTaskTuple.getTaskId(), stormTaskTuple.getFileUrl(), e.getMessage(), "Statistics for the given file could not be prepared.", StormTaskTupleHelper.getRecordProcessingStartTime(stormTaskTuple)); } outputCollector.ack(anchorTuple); } StatisticsBolt(String hosts, int port, String keyspaceName,
String userName, String password); @Override void prepare(); @Override void execute(Tuple anchorTuple, StormTaskTuple stormTaskTuple); static final Logger LOGGER; } | @Test public void testCountStatisticsSuccessfully() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); byte[] fileData = Files.readAllBytes(Paths.get("src/test/resources/example1.xml")); StormTaskTuple tuple = new StormTaskTuple(TASK_ID, TASK_NAME, SOURCE_VERSION_URL, fileData, new HashMap<String, String>(), new Revision()); List<NodeStatistics> generated = new RecordStatisticsGenerator(new String(fileData)).getStatistics(); statisticsBolt.execute(anchorTuple, tuple); assertSuccess(1); assertDataStoring(generated); }
@Test public void testAggregatedCountStatisticsSuccessfully() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); Tuple anchorTuple2 = mock(TupleImpl.class); byte[] fileData = Files.readAllBytes(Paths.get("src/test/resources/example1.xml")); StormTaskTuple tuple = new StormTaskTuple(TASK_ID, TASK_NAME, SOURCE_VERSION_URL, fileData, new HashMap<String, String>(), new Revision()); List<NodeStatistics> generated = new RecordStatisticsGenerator(new String(fileData)).getStatistics(); byte[] fileData2 = Files.readAllBytes(Paths.get("src/test/resources/example2.xml")); StormTaskTuple tuple2 = new StormTaskTuple(TASK_ID, TASK_NAME, SOURCE_VERSION_URL, fileData2, new HashMap<String, String>(), new Revision()); List<NodeStatistics> generated2 = new RecordStatisticsGenerator(new String(fileData2)).getStatistics(); statisticsBolt.execute(anchorTuple, tuple); statisticsBolt.execute(anchorTuple2, tuple2); assertSuccess(2); assertDataStoring(generated, generated2); }
@Test public void testCountStatisticsFailed() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); byte[] fileData = Files.readAllBytes(Paths.get("src/test/resources/example1.xml")); fileData[0] = 'X'; StormTaskTuple tuple = new StormTaskTuple(TASK_ID, TASK_NAME, SOURCE_VERSION_URL, fileData, new HashMap<String, String>(), new Revision()); statisticsBolt.execute(anchorTuple, tuple); assertFailure(); } |
ValidationBolt extends AbstractDpsBolt { @Override public void execute(Tuple anchorTuple, StormTaskTuple stormTaskTuple) { try { reorderFileContent(stormTaskTuple); validateFileAndEmit(anchorTuple, stormTaskTuple); } catch (Exception e) { LOGGER.error("Validation Bolt error: {}", e.getMessage()); emitErrorNotification(anchorTuple, stormTaskTuple.getTaskId(), stormTaskTuple.getFileUrl(), e.getMessage(), "Error while validation. The full error :" + ExceptionUtils.getStackTrace(e), StormTaskTupleHelper.getRecordProcessingStartTime(stormTaskTuple)); } outputCollector.ack(anchorTuple); } ValidationBolt(Properties properties); @Override void execute(Tuple anchorTuple, StormTaskTuple stormTaskTuple); @Override void prepare(); static final Logger LOGGER; } | @Test public void validateEdmInternalFile() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); byte[] FILE_DATA = Files.readAllBytes(Paths.get("src/test/resources/Item_35834473_test.xml")); StormTaskTuple tuple = new StormTaskTuple(TASK_ID, TASK_NAME, SOURCE_VERSION_URL, FILE_DATA, prepareStormTaskTupleParameters("edm-internal", null), new Revision()); validationBolt.execute(anchorTuple, tuple); assertSuccessfulValidation(); }
@Test public void validateEdmInternalFileWithProvidedRootLocation() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); byte[] FILE_DATA = Files.readAllBytes(Paths.get("src/test/resources/Item_35834473_test.xml")); StormTaskTuple tuple = new StormTaskTuple(TASK_ID, TASK_NAME, SOURCE_VERSION_URL, FILE_DATA, prepareStormTaskTupleParameters("edm-internal", "EDM-INTERNAL.xsd"), new Revision()); validationBolt.execute(anchorTuple, tuple); assertSuccessfulValidation(); }
@Test public void validateEdmExternalFile() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); byte[] FILE_DATA = Files.readAllBytes(Paths.get("src/test/resources/Item_35834473.xml")); StormTaskTuple tuple = new StormTaskTuple(TASK_ID, TASK_NAME, SOURCE_VERSION_URL, FILE_DATA, prepareStormTaskTupleParameters("edm-external", null), new Revision()); validationBolt.execute(anchorTuple, tuple); assertSuccessfulValidation(); }
@Test public void validateEdmExternalOutOfOrderFile() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); byte[] FILE_DATA = Files.readAllBytes(Paths.get("src/test/resources/edmExternalWithOutOfOrderElements.xml")); StormTaskTuple tuple = new StormTaskTuple(TASK_ID, TASK_NAME, SOURCE_VERSION_URL, FILE_DATA, prepareStormTaskTupleParameters("edm-external", null), new Revision()); validationBolt.execute(anchorTuple, tuple); assertSuccessfulValidation(); }
@Test public void sendErrorNotificationWhenTheValidationFails() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); byte[] FILE_DATA = Files.readAllBytes(Paths.get("src/test/resources/Item_35834473_test.xml")); StormTaskTuple tuple = new StormTaskTuple(TASK_ID, TASK_NAME, SOURCE_VERSION_URL, FILE_DATA, prepareStormTaskTupleParameters("edm-external", null), new Revision()); validationBolt.execute(anchorTuple, tuple); assertFailedValidation(); } |
RecordStatisticsGenerator { public List<NodeStatistics> getStatistics() throws SAXException, IOException, ParserConfigurationException { Document doc = getParsedDocument(); doc.getDocumentElement().normalize(); Node root = doc.getDocumentElement(); addRootToNodeList(root); prepareNodeStatistics(root); return new ArrayList<>(nodeStatistics.values()); } RecordStatisticsGenerator(String fileContent); List<NodeStatistics> getStatistics(); } | @Test public void nodeContentsSizeShouldBeSmallerThanMaximumSize() throws Exception { String fileContent = readFile("src/test/resources/BigContent.xml"); RecordStatisticsGenerator xmlParser = new RecordStatisticsGenerator(fileContent); List<NodeStatistics> nodeModelList = xmlParser.getStatistics(); for (NodeStatistics nodeModel : nodeModelList) { assertTrue(nodeModel.getValue().length() <= MAX_SIZE); } } |
EDMEnrichmentBolt extends ReadFileBolt { @Override public void execute(Tuple anchorTuple, StormTaskTuple stormTaskTuple) { if (stormTaskTuple.getParameter(PluginParameterKeys.RESOURCE_LINKS_COUNT) == null) { LOGGER.warn(NO_RESOURCES_DETAILED_MESSAGE); try (InputStream stream = getFileStreamByStormTuple(stormTaskTuple)) { EnrichedRdf enrichedRdf = deserializer.getRdfForResourceEnriching(IOUtils.toByteArray(stream)); prepareStormTaskTuple(stormTaskTuple, enrichedRdf, NO_RESOURCES_DETAILED_MESSAGE); outputCollector.emit(anchorTuple, stormTaskTuple.toStormTuple()); } catch (IOException | RdfDeserializationException | RdfSerializationException | MCSException ex) { LOGGER.error("Error while serializing the enriched file: ", ex); emitErrorNotification(anchorTuple, stormTaskTuple.getTaskId(), stormTaskTuple.getFileUrl(), ex.getMessage(), "Error while serializing the enriched file: " + ExceptionUtils.getStackTrace(ex), StormTaskTupleHelper.getRecordProcessingStartTime(stormTaskTuple)); } outputCollector.ack(anchorTuple); } else { final String file = stormTaskTuple.getFileUrl(); TempEnrichedFile tempEnrichedFile = cache.get(file); try { if ((tempEnrichedFile == null) || (tempEnrichedFile.getTaskId() != stormTaskTuple.getTaskId())) { try (InputStream stream = getFileStreamByStormTuple(stormTaskTuple)) { tempEnrichedFile = new TempEnrichedFile(); tempEnrichedFile.setTaskId(stormTaskTuple.getTaskId()); tempEnrichedFile.setEnrichedRdf(deserializer.getRdfForResourceEnriching(IOUtils.toByteArray(stream))); } } tempEnrichedFile.addSourceTuple(anchorTuple); if (stormTaskTuple.getParameter(PluginParameterKeys.RESOURCE_METADATA) != null) { EnrichedRdf enrichedRdf = enrichRdf(tempEnrichedFile.getEnrichedRdf(), stormTaskTuple.getParameter(PluginParameterKeys.RESOURCE_METADATA)); tempEnrichedFile.setEnrichedRdf(enrichedRdf); } String cachedErrorMessage = tempEnrichedFile.getExceptions(); cachedErrorMessage = buildErrorMessage(stormTaskTuple.getParameter(PluginParameterKeys.EXCEPTION_ERROR_MESSAGE), cachedErrorMessage); tempEnrichedFile.setExceptions(cachedErrorMessage); } catch (Exception e) { LOGGER.error("problem while enrichment ", e); String currentException = tempEnrichedFile.getExceptions(); String exceptionMessage = "Exception while enriching the original edm file with resource: " + stormTaskTuple.getParameter(PluginParameterKeys.RESOURCE_URL) + " because of: " + ExceptionUtils.getStackTrace(e); if (currentException.isEmpty()) tempEnrichedFile.setExceptions(exceptionMessage); else tempEnrichedFile.setExceptions(currentException + "," + exceptionMessage); } finally { tempEnrichedFile.increaseCount(); if (tempEnrichedFile.isTheLastResource(Integer.parseInt(stormTaskTuple.getParameter(PluginParameterKeys.RESOURCE_LINKS_COUNT)))) { try { LOGGER.info("The file {} was fully enriched and will be send to the next bolt", file); prepareStormTaskTuple(stormTaskTuple, tempEnrichedFile); cache.remove(file); outputCollector.emit(anchorTuple, stormTaskTuple.toStormTuple()); } catch (Exception ex) { LOGGER.error("Error while serializing the enriched file: ", ex); emitErrorNotification(anchorTuple, stormTaskTuple.getTaskId(), stormTaskTuple.getFileUrl(), ex.getMessage(), "Error while serializing the enriched file: " + ExceptionUtils.getStackTrace(ex), StormTaskTupleHelper.getRecordProcessingStartTime(stormTaskTuple)); } ackAllSourceTuplesForFile(tempEnrichedFile); } else { cache.put(file, tempEnrichedFile); } } } } EDMEnrichmentBolt(String mcsURL); @Override void execute(Tuple anchorTuple, StormTaskTuple stormTaskTuple); @Override void prepare(); static final String NO_RESOURCES_DETAILED_MESSAGE; } | @Test public void shouldEnrichTheFileSuccessfullyAndSendItToTheNextBolt() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); try (InputStream stream = this.getClass().getResourceAsStream("/files/Item_35834473.xml")) { when(fileClient.getFile(eq(FILE_URL), eq(AUTHORIZATION), eq(AUTHORIZATION))).thenReturn(stream); stormTaskTuple.addParameter(PluginParameterKeys.RESOURCE_METADATA, "{\"textResourceMetadata\":{\"containsText\":false,\"resolution\":10,\"mimeType\":\"text/xml\",\"resourceUrl\":\"http: stormTaskTuple.addParameter(PluginParameterKeys.RESOURCE_LINKS_COUNT, String.valueOf(1)); assertEquals(4, stormTaskTuple.getParameters().size()); edmEnrichmentBolt.execute(anchorTuple, stormTaskTuple); verify(outputCollector, times(1)).emit(eq(anchorTuple), captor.capture()); Values values = captor.getValue(); Map<String, String> parameters = (Map) values.get(4); assertNotNull(parameters); assertEquals(6, parameters.size()); assertNull(parameters.get(PluginParameterKeys.RESOURCE_METADATA)); assertEquals("sourceCloudId", parameters.get(PluginParameterKeys.CLOUD_ID)); assertEquals("sourceRepresentationName", parameters.get(PluginParameterKeys.REPRESENTATION_NAME)); assertEquals("sourceVersion", parameters.get(PluginParameterKeys.REPRESENTATION_VERSION)); } }
@Test public void shouldEnrichTheFileSuccessfullyOnMultipleBatchesAndSendItToTheNextBolt() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); try (InputStream stream = this.getClass().getResourceAsStream("/files/Item_35834473.xml")) { when(fileClient.getFile(eq(FILE_URL), eq(AUTHORIZATION), eq(AUTHORIZATION))).thenReturn(stream); stormTaskTuple.addParameter(PluginParameterKeys.RESOURCE_METADATA, "{\"textResourceMetadata\":{\"containsText\":false,\"resolution\":10,\"mimeType\":\"text/xml\",\"resourceUrl\":\"http: int resourceLinksCount = 10; stormTaskTuple.addParameter(PluginParameterKeys.RESOURCE_LINKS_COUNT, String.valueOf(resourceLinksCount)); assertEquals(4, stormTaskTuple.getParameters().size()); for (int i = 1; i <= resourceLinksCount; i++) { edmEnrichmentBolt.execute(anchorTuple, stormTaskTuple); if (i < resourceLinksCount) assertEquals(i, edmEnrichmentBolt.cache.get(FILE_URL).getCount()); } verify(outputCollector, times(1)).emit(eq(anchorTuple), captor.capture()); Values values = captor.getValue(); Map<String, String> parameters = (Map) values.get(4); assertNotNull(parameters); assertEquals(6, parameters.size()); assertNull(parameters.get(PluginParameterKeys.RESOURCE_METADATA)); assertEquals("sourceCloudId", parameters.get(PluginParameterKeys.CLOUD_ID)); assertEquals("sourceRepresentationName", parameters.get(PluginParameterKeys.REPRESENTATION_NAME)); assertEquals("sourceVersion", parameters.get(PluginParameterKeys.REPRESENTATION_VERSION)); } }
@Test public void shouldForwardTheTupleWhenNoResourceLinkFound() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); edmEnrichmentBolt.execute(anchorTuple, stormTaskTuple); int expectedParametersSize = 2; Map<String, String> initialTupleParameters = stormTaskTuple.getParameters(); assertEquals(expectedParametersSize, initialTupleParameters.size()); verify(outputCollector, Mockito.times(1)).emit(eq(anchorTuple), captor.capture()); Values value = captor.getValue(); Map<String, String> parametersAfterExecution = (Map) value.get(4); assertNotNull(parametersAfterExecution); assertEquals(expectedParametersSize, parametersAfterExecution.size()); for (String key : parametersAfterExecution.keySet()) { assertTrue(initialTupleParameters.keySet().contains(key)); assertEquals(initialTupleParameters.get(key), parametersAfterExecution.get(key)); } }
@Test public void shouldLogTheExceptionAndSendItAsParameterToTheNextBolt() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); try (InputStream stream = this.getClass().getResourceAsStream("/files/Item_35834473.xml")) { when(fileClient.getFile(eq(FILE_URL), eq(AUTHORIZATION), eq(AUTHORIZATION))).thenReturn(stream); String brokenMetaData = "{\"textResourceMetadata\":{\"containsTe/xml\",\"resourceUrl\":\"RESOURCE_URL\",\"contentSize\":100,\"thumbnailTargetNames\":[\"TargetName1\",\"TargetName0\",\"TargetName2\"]}}"; stormTaskTuple.addParameter(PluginParameterKeys.RESOURCE_METADATA, brokenMetaData); stormTaskTuple.addParameter(PluginParameterKeys.RESOURCE_LINKS_COUNT, String.valueOf(1)); assertEquals(4, stormTaskTuple.getParameters().size()); edmEnrichmentBolt.execute(anchorTuple, stormTaskTuple); verify(outputCollector, times(1)).emit(eq(anchorTuple), captor.capture()); Values values = captor.getValue(); Map<String, String> parameters = (Map) values.get(4); assertNotNull(parameters); assertEquals(8, parameters.size()); assertNotNull(parameters.get(PluginParameterKeys.EXCEPTION_ERROR_MESSAGE)); assertNotNull(parameters.get(PluginParameterKeys.UNIFIED_ERROR_MESSAGE)); assertNull(parameters.get(PluginParameterKeys.RESOURCE_METADATA)); assertEquals("sourceCloudId", parameters.get(PluginParameterKeys.CLOUD_ID)); assertEquals("sourceRepresentationName", parameters.get(PluginParameterKeys.REPRESENTATION_NAME)); assertEquals("sourceVersion", parameters.get(PluginParameterKeys.REPRESENTATION_VERSION)); assertNotNull(parameters.get(PluginParameterKeys.UNIFIED_ERROR_MESSAGE)); assertNotNull(MEDIA_RESOURCE_EXCEPTION, parameters.get(PluginParameterKeys.UNIFIED_ERROR_MESSAGE)); } } |
ResourceProcessingBolt extends AbstractDpsBolt { @Override public void execute(Tuple anchorTuple, StormTaskTuple stormTaskTuple) { LOGGER.info("Starting resource processing"); long processingStartTime = new Date().getTime(); StringBuilder exception = new StringBuilder(); if (stormTaskTuple.getParameter(PluginParameterKeys.RESOURCE_LINKS_COUNT) == null) { outputCollector.emit(anchorTuple, stormTaskTuple.toStormTuple()); outputCollector.ack(anchorTuple); } else { try { RdfResourceEntry rdfResourceEntry = gson.fromJson(stormTaskTuple.getParameter(PluginParameterKeys.RESOURCE_LINK_KEY), RdfResourceEntry.class); ResourceExtractionResult resourceExtractionResult = mediaExtractor.performMediaExtraction(rdfResourceEntry, Boolean.parseBoolean(stormTaskTuple.getParameter(PluginParameterKeys.MAIN_THUMBNAIL_AVAILABLE))); if (resourceExtractionResult != null) { if (resourceExtractionResult.getMetadata() != null) stormTaskTuple.addParameter(PluginParameterKeys.RESOURCE_METADATA, gson.toJson(resourceExtractionResult.getMetadata())); storeThumbnails(stormTaskTuple, exception, resourceExtractionResult); } LOGGER.info("Resource processing finished in: {}ms", String.valueOf(Calendar.getInstance().getTimeInMillis() - processingStartTime)); } catch (Exception e) { LOGGER.error("Exception while processing the resource {}. The full error is:{} ", stormTaskTuple.getParameter(PluginParameterKeys.RESOURCE_URL), ExceptionUtils.getStackTrace(e)); buildErrorMessage(exception, "Exception while processing the resource: " + stormTaskTuple.getParameter(PluginParameterKeys.RESOURCE_URL) + ". The full error is: " + e.getMessage() + " because of: " + e.getCause()); } finally { stormTaskTuple.getParameters().remove(PluginParameterKeys.RESOURCE_LINK_KEY); if (exception.length() > 0) { stormTaskTuple.addParameter(PluginParameterKeys.EXCEPTION_ERROR_MESSAGE, exception.toString()); stormTaskTuple.addParameter(PluginParameterKeys.UNIFIED_ERROR_MESSAGE, MEDIA_RESOURCE_EXCEPTION); } outputCollector.emit(anchorTuple, stormTaskTuple.toStormTuple()); outputCollector.ack(anchorTuple); } } LOGGER.info("Resource processing finished in: {}ms", Calendar.getInstance().getTimeInMillis() - processingStartTime); } ResourceProcessingBolt(AmazonClient amazonClient); @Override void execute(Tuple anchorTuple, StormTaskTuple stormTaskTuple); @Override void prepare(); } | @Test public void shouldSuccessfullyProcessTheResource() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); stormTaskTuple.addParameter(PluginParameterKeys.RESOURCE_LINKS_COUNT, Integer.toString(5)); stormTaskTuple.addParameter(PluginParameterKeys.RESOURCE_LINK_KEY, "{\"resourceUrl\":\"http: String resourceName = "RESOURCE_URL"; int thumbnailCount = 3; List<Thumbnail> thumbnailList = getThumbnails(thumbnailCount); AbstractResourceMetadata resourceMetadata = new TextResourceMetadata("text/xml", resourceName, 100L, false, 10, thumbnailList); ResourceExtractionResult resourceExtractionResult = new ResourceExtractionResultImpl(resourceMetadata, thumbnailList); when(mediaExtractor.performMediaExtraction(any(RdfResourceEntry.class), anyBoolean())).thenReturn(resourceExtractionResult); when(amazonClient.putObject(anyString(), any(InputStream.class), nullable(ObjectMetadata.class))).thenReturn(new PutObjectResult()); when(taskStatusChecker.hasKillFlag(eq(TASK_ID))).thenReturn(false); resourceProcessingBolt.execute(anchorTuple, stormTaskTuple); verify(amazonClient, Mockito.times(thumbnailCount)).putObject(anyString(), any(InputStream.class), any(ObjectMetadata.class)); verify(outputCollector, Mockito.times(1)).emit(eq(anchorTuple), captor.capture()); Values value = captor.getValue(); Map<String, String> parameters = (Map) value.get(4); assertNotNull(parameters); assertEquals(4, parameters.size()); assertNull(parameters.get(PluginParameterKeys.EXCEPTION_ERROR_MESSAGE)); }
@Test public void shouldDropTheTaskAndStopProcessing() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); stormTaskTuple.addParameter(PluginParameterKeys.RESOURCE_LINKS_COUNT, Integer.toString(5)); stormTaskTuple.addParameter(PluginParameterKeys.RESOURCE_LINK_KEY, "{\"resourceUrl\":\"http: String resourceName = "RESOURCE_URL"; int thumbnailCount = 3; List<Thumbnail> thumbnailList = getThumbnails(thumbnailCount); AbstractResourceMetadata resourceMetadata = new TextResourceMetadata("text/xml", resourceName, 100L, false, 10, thumbnailList); ResourceExtractionResult resourceExtractionResult = new ResourceExtractionResultImpl(resourceMetadata, thumbnailList); when(mediaExtractor.performMediaExtraction(any(RdfResourceEntry.class), anyBoolean())).thenReturn(resourceExtractionResult); when(amazonClient.putObject(anyString(), any(InputStream.class), isNull(ObjectMetadata.class))).thenReturn(new PutObjectResult()); when(taskStatusChecker.hasKillFlag(eq(TASK_ID))).thenReturn(false).thenReturn(true); resourceProcessingBolt.execute(anchorTuple, stormTaskTuple); verify(amazonClient, Mockito.times(1)).putObject(anyString(), any(InputStream.class), any(ObjectMetadata.class)); }
@Test public void shouldFormulateTheAggregateExceptionsWhenSavingToAmazonFails() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); stormTaskTuple.addParameter(PluginParameterKeys.RESOURCE_LINKS_COUNT, Integer.toString(5)); stormTaskTuple.addParameter(PluginParameterKeys.RESOURCE_LINK_KEY, "{\"resourceUrl\":\"http: String resourceName = "RESOURCE_URL"; int thumbNailCount = 3; List<Thumbnail> thumbnailList = getThumbnails(thumbNailCount); AbstractResourceMetadata resourceMetadata = new TextResourceMetadata("text/xml", resourceName, 100L, false, 10, thumbnailList); ResourceExtractionResult resourceExtractionResult = new ResourceExtractionResultImpl(resourceMetadata, thumbnailList); String errorMessage = "The error was thrown because of something"; when(mediaExtractor.performMediaExtraction(any(RdfResourceEntry.class), anyBoolean())).thenReturn(resourceExtractionResult); doThrow(new AmazonServiceException(errorMessage)).when(amazonClient).putObject( anyString(), any(InputStream.class), any(ObjectMetadata.class)); resourceProcessingBolt.execute(anchorTuple, stormTaskTuple); verify(amazonClient, Mockito.times(3)).putObject(anyString(), any(InputStream.class), any(ObjectMetadata.class)); verify(outputCollector, Mockito.times(1)).emit(eq(anchorTuple), captor.capture()); Values value = captor.getValue(); Map<String, String> parameters = (Map) value.get(4); assertNotNull(parameters); assertEquals(6, parameters.size()); assertNotNull(parameters.get(PluginParameterKeys.EXCEPTION_ERROR_MESSAGE)); assertNotNull(parameters.get(PluginParameterKeys.UNIFIED_ERROR_MESSAGE)); assertEquals(thumbNailCount, StringUtils.countMatches(parameters.get(PluginParameterKeys.EXCEPTION_ERROR_MESSAGE), errorMessage)); assertNull(parameters.get(PluginParameterKeys.RESOURCE_LINK_KEY)); assertNotNull(MEDIA_RESOURCE_EXCEPTION, parameters.get(PluginParameterKeys.UNIFIED_ERROR_MESSAGE)); }
@Test public void shouldSendExceptionsWhenProcessingFails() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); stormTaskTuple.addParameter(PluginParameterKeys.RESOURCE_LINKS_COUNT, Integer.toString(5)); stormTaskTuple.addParameter(PluginParameterKeys.RESOURCE_LINK_KEY, "{\"resourceUrl\":\"http: doThrow(MediaExtractionException.class).when(mediaExtractor).performMediaExtraction(any(RdfResourceEntry.class), anyBoolean()); resourceProcessingBolt.execute(anchorTuple, stormTaskTuple); verify(outputCollector, Mockito.times(1)).emit(eq(anchorTuple), captor.capture()); verify(amazonClient, Mockito.times(0)).putObject(anyString(), any(InputStream.class), isNull(ObjectMetadata.class)); Values value = captor.getValue(); Map<String, String> parameters = (Map) value.get(4); assertNotNull(parameters); assertEquals(5, parameters.size()); assertNotNull(parameters.get(PluginParameterKeys.EXCEPTION_ERROR_MESSAGE)); assertNotNull(parameters.get(PluginParameterKeys.UNIFIED_ERROR_MESSAGE)); assertNull(parameters.get(PluginParameterKeys.RESOURCE_METADATA)); assertNull(parameters.get(PluginParameterKeys.RESOURCE_LINK_KEY)); assertNotNull(MEDIA_RESOURCE_EXCEPTION, parameters.get(PluginParameterKeys.UNIFIED_ERROR_MESSAGE)); }
@Test public void shouldForwardTheTupleWhenNoResourceLinkFound() throws Exception { Tuple anchorTuple = mock(TupleImpl.class); resourceProcessingBolt.execute(anchorTuple, stormTaskTuple); int expectedParametersSize = 2; assertEquals(expectedParametersSize, stormTaskTuple.getParameters().size()); verify(outputCollector, Mockito.times(1)).emit(eq(anchorTuple), captor.capture()); Values value = captor.getValue(); Map<String, String> parameters = (Map) value.get(4); assertNotNull(parameters); assertEquals(expectedParametersSize, parameters.size()); assertNull(parameters.get(PluginParameterKeys.EXCEPTION_ERROR_MESSAGE)); assertNull(parameters.get(PluginParameterKeys.RESOURCE_METADATA)); } |
RemoverImpl implements Remover { @Override public void removeStatistics(long taskId) { int retries = DEFAULT_RETRIES; while (true) { try { cassandraNodeStatisticsDAO.removeStatistics(taskId); break; } catch (Exception e) { if (retries-- > 0) { LOGGER.warn("Error while removing the validation statistics. Retries left: " + retries); waitForTheNextCall(); } else { LOGGER.error("rror while removing the validation statistics."); throw e; } } } } RemoverImpl(String hosts, int port, String keyspaceName, String userName, String password); RemoverImpl(CassandraSubTaskInfoDAO subTaskInfoDAO, CassandraTaskErrorsDAO taskErrorDAO, CassandraNodeStatisticsDAO cassandraNodeStatisticsDAO); @Override void removeNotifications(long taskId); @Override void removeErrorReports(long taskId); @Override void removeStatistics(long taskId); } | @Test public void shouldSuccessfullyRemoveStatistics() { doNothing().when(cassandraNodeStatisticsDAO).removeStatistics(eq(TASK_ID)); removerImpl.removeStatistics(TASK_ID); verify(cassandraNodeStatisticsDAO, times(1)).removeStatistics((eq(TASK_ID))); }
@Test(expected = Exception.class) public void shouldRetry5TimesBeforeFailingWhileRemovingStatistics() { doThrow(Exception.class).when(cassandraNodeStatisticsDAO).removeStatistics(eq(TASK_ID)); removerImpl.removeStatistics(TASK_ID); verify(cassandraNodeStatisticsDAO, times(6)).removeStatistics((eq(TASK_ID))); } |
HttpKafkaSpout extends CustomKafkaSpout { @Override public void deactivate() { LOGGER.info("Deactivate method was executed"); deactivateWaitingTasks(); deactivateCurrentTask(); LOGGER.info("Deactivate method was finished"); } HttpKafkaSpout(KafkaSpoutConfig spoutConf); HttpKafkaSpout(KafkaSpoutConfig spoutConf, String hosts, int port, String keyspaceName,
String userName, String password); @Override void open(Map conf, TopologyContext context,
SpoutOutputCollector collector); @Override void nextTuple(); @Override void declareOutputFields(OutputFieldsDeclarer declarer); @Override void deactivate(); } | @Test public void deactivateShouldClearTheTaskQueue() throws Exception { final int taskCount = 10; for (int i = 0; i < taskCount; i++) { httpKafkaSpout.taskDownloader.taskQueue.put(new DpsTask()); } assertTrue(!httpKafkaSpout.taskDownloader.taskQueue.isEmpty()); httpKafkaSpout.deactivate(); assertTrue(httpKafkaSpout.taskDownloader.taskQueue.isEmpty()); verify(cassandraTaskInfoDAO, atLeast(taskCount)).setTaskDropped(anyLong(), anyString()); } |
ZipUnpackingService implements FileUnpackingService { public void unpackFile(final String compressedFilePath, final String destinationFolder) throws CompressionExtensionNotRecognizedException, IOException { final List<String> zipFiles = new ArrayList<>(); ZipUtil.unpack(new File(compressedFilePath), new File(destinationFolder), new NameMapper() { public String map(String name) { if (CompressionFileExtension.contains(FilenameUtils.getExtension(name))) { String compressedFilePath = destinationFolder + name; zipFiles.add(compressedFilePath); } return name; } }); for (String nestedCompressedFile : zipFiles) { String extension = FilenameUtils.getExtension(nestedCompressedFile); UnpackingServiceFactory.createUnpackingService(extension).unpackFile(nestedCompressedFile, FilenameUtils.removeExtension(nestedCompressedFile) + File.separator); } } void unpackFile(final String compressedFilePath, final String destinationFolder); } | @Test public void shouldUnpackTheZipFilesRecursively() throws CompressionExtensionNotRecognizedException, IOException { zipUnpackingService.unpackFile(DESTINATION_DIR + FILE_NAME + ZIP_EXTENSION, DESTINATION_DIR); Collection files = getXMLFiles(DESTINATION_DIR + DEFAULT_DESTINATION_NAME); assertNotNull(files); assertEquals(XML_FILES_COUNT,files.size()); }
@Test public void shouldUnpackTheZipFilesWithNestedFoldersRecursively() throws CompressionExtensionNotRecognizedException, IOException { zipUnpackingService.unpackFile(DESTINATION_DIR + FILE_NAME2 + ZIP_EXTENSION, DESTINATION_DIR); Collection files = getXMLFiles(DESTINATION_DIR + DEFAULT_DESTINATION_NAME); assertNotNull(files); assertEquals(XML_FILES_COUNT,files.size()); }
@Test public void shouldUnpackTheZipFilesWithNestedMixedCompressedFiles() throws CompressionExtensionNotRecognizedException, IOException { zipUnpackingService.unpackFile(DESTINATION_DIR + FILE_NAME3 + ZIP_EXTENSION, DESTINATION_DIR); Collection files = getXMLFiles(DESTINATION_DIR + DEFAULT_DESTINATION_NAME); assertNotNull(files); assertEquals(XML_FILES_COUNT,files.size()); } |
Subsets and Splits