target
stringlengths
20
113k
src_fm
stringlengths
11
86.3k
src_fm_fc
stringlengths
21
86.4k
src_fm_fc_co
stringlengths
30
86.4k
src_fm_fc_ms
stringlengths
42
86.8k
src_fm_fc_ms_ff
stringlengths
43
86.8k
@Test public void testTimeZoneDate() { RelatedItem product = new RelatedItem("1".toCharArray(),"1920-01-02T01:59:59+02:00",null,new RelatedItemAdditionalProperties()); String name = minBasedMapper.getLocationName(product); assertEquals(config.getStorageIndexNamePrefix() + "-1920-01-01_23:59",name); }
@Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHourAndMinute(); } else { date = currentDayFormatter.parseToDateAndHourAndMinute(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); }
MinuteBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHourAndMinute(); } else { date = currentDayFormatter.parseToDateAndHourAndMinute(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } }
MinuteBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHourAndMinute(); } else { date = currentDayFormatter.parseToDateAndHourAndMinute(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } MinuteBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateAndHourAndMinuteFormatter dateFormatter); }
MinuteBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHourAndMinute(); } else { date = currentDayFormatter.parseToDateAndHourAndMinute(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } MinuteBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateAndHourAndMinuteFormatter dateFormatter); @Override String getLocationName(RelatedItem product); }
MinuteBasedStorageLocationMapper implements RelatedItemStorageLocationMapper { @Override public String getLocationName(RelatedItem product) { String dateStr = product.getDate(); String date; if(dateStr==null) { date = currentDayFormatter.getCurrentDayAndHourAndMinute(); } else { date = currentDayFormatter.parseToDateAndHourAndMinute(dateStr); } StringBuilder indexName = new StringBuilder(indexNameSize); return indexName.append(this.indexPrefixName).append(date).toString(); } MinuteBasedStorageLocationMapper(Configuration configuration, UTCCurrentDateAndHourAndMinuteFormatter dateFormatter); @Override String getLocationName(RelatedItem product); }
@Test public void testSendingOneItem() { try { handler.onEvent(getMessage(),1,true); } catch(Exception e) { fail(); } assertEquals(1,repo.getNumberOfCalls()); assertEquals(1,repo.getNumberOfProductsSentForStoring()); }
@Override public void onEvent(RelatedItemReference request, long l, boolean endOfBatch) throws Exception { try { relatedItems.add(request.getReference()); if(endOfBatch || --this.count[COUNTER_POS] == 0) { try { log.debug("Sending {} indexing requests to the storage repository",relatedItems.size()); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", relatedItems,e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setReference(null); } }
BatchingRelatedItemReferenceEventHandler implements RelatedItemReferenceEventHandler { @Override public void onEvent(RelatedItemReference request, long l, boolean endOfBatch) throws Exception { try { relatedItems.add(request.getReference()); if(endOfBatch || --this.count[COUNTER_POS] == 0) { try { log.debug("Sending {} indexing requests to the storage repository",relatedItems.size()); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", relatedItems,e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setReference(null); } } }
BatchingRelatedItemReferenceEventHandler implements RelatedItemReferenceEventHandler { @Override public void onEvent(RelatedItemReference request, long l, boolean endOfBatch) throws Exception { try { relatedItems.add(request.getReference()); if(endOfBatch || --this.count[COUNTER_POS] == 0) { try { log.debug("Sending {} indexing requests to the storage repository",relatedItems.size()); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", relatedItems,e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setReference(null); } } BatchingRelatedItemReferenceEventHandler(int batchSize, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); }
BatchingRelatedItemReferenceEventHandler implements RelatedItemReferenceEventHandler { @Override public void onEvent(RelatedItemReference request, long l, boolean endOfBatch) throws Exception { try { relatedItems.add(request.getReference()); if(endOfBatch || --this.count[COUNTER_POS] == 0) { try { log.debug("Sending {} indexing requests to the storage repository",relatedItems.size()); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", relatedItems,e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setReference(null); } } BatchingRelatedItemReferenceEventHandler(int batchSize, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); @Override void onEvent(RelatedItemReference request, long l, boolean endOfBatch); void shutdown(); }
BatchingRelatedItemReferenceEventHandler implements RelatedItemReferenceEventHandler { @Override public void onEvent(RelatedItemReference request, long l, boolean endOfBatch) throws Exception { try { relatedItems.add(request.getReference()); if(endOfBatch || --this.count[COUNTER_POS] == 0) { try { log.debug("Sending {} indexing requests to the storage repository",relatedItems.size()); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", relatedItems,e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setReference(null); } } BatchingRelatedItemReferenceEventHandler(int batchSize, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); @Override void onEvent(RelatedItemReference request, long l, boolean endOfBatch); void shutdown(); }
@Test public void testSendingManyItemsButBelowBatchSize() { try { for(int i=0;i<7;i++) { handler.onEvent(getMessage(),i,false); } handler.onEvent(getMessage(),8,true); } catch(Exception e) { fail(); } assertEquals(1,repo.getNumberOfCalls()); assertEquals(8,repo.getNumberOfProductsSentForStoring()); }
@Override public void onEvent(RelatedItemReference request, long l, boolean endOfBatch) throws Exception { try { relatedItems.add(request.getReference()); if(endOfBatch || --this.count[COUNTER_POS] == 0) { try { log.debug("Sending {} indexing requests to the storage repository",relatedItems.size()); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", relatedItems,e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setReference(null); } }
BatchingRelatedItemReferenceEventHandler implements RelatedItemReferenceEventHandler { @Override public void onEvent(RelatedItemReference request, long l, boolean endOfBatch) throws Exception { try { relatedItems.add(request.getReference()); if(endOfBatch || --this.count[COUNTER_POS] == 0) { try { log.debug("Sending {} indexing requests to the storage repository",relatedItems.size()); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", relatedItems,e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setReference(null); } } }
BatchingRelatedItemReferenceEventHandler implements RelatedItemReferenceEventHandler { @Override public void onEvent(RelatedItemReference request, long l, boolean endOfBatch) throws Exception { try { relatedItems.add(request.getReference()); if(endOfBatch || --this.count[COUNTER_POS] == 0) { try { log.debug("Sending {} indexing requests to the storage repository",relatedItems.size()); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", relatedItems,e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setReference(null); } } BatchingRelatedItemReferenceEventHandler(int batchSize, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); }
BatchingRelatedItemReferenceEventHandler implements RelatedItemReferenceEventHandler { @Override public void onEvent(RelatedItemReference request, long l, boolean endOfBatch) throws Exception { try { relatedItems.add(request.getReference()); if(endOfBatch || --this.count[COUNTER_POS] == 0) { try { log.debug("Sending {} indexing requests to the storage repository",relatedItems.size()); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", relatedItems,e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setReference(null); } } BatchingRelatedItemReferenceEventHandler(int batchSize, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); @Override void onEvent(RelatedItemReference request, long l, boolean endOfBatch); void shutdown(); }
BatchingRelatedItemReferenceEventHandler implements RelatedItemReferenceEventHandler { @Override public void onEvent(RelatedItemReference request, long l, boolean endOfBatch) throws Exception { try { relatedItems.add(request.getReference()); if(endOfBatch || --this.count[COUNTER_POS] == 0) { try { log.debug("Sending {} indexing requests to the storage repository",relatedItems.size()); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", relatedItems,e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setReference(null); } } BatchingRelatedItemReferenceEventHandler(int batchSize, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); @Override void onEvent(RelatedItemReference request, long l, boolean endOfBatch); void shutdown(); }
@Test public void testSendingManyItemsExceedingBatchSize() { try { for(int i=0;i<25;i++) { handler.onEvent(getMessage(),i,false); } handler.onEvent(getMessage(),26,true); } catch(Exception e) { fail(); } assertEquals(2,repo.getNumberOfCalls()); assertEquals(26,repo.getNumberOfProductsSentForStoring()); }
@Override public void onEvent(RelatedItemReference request, long l, boolean endOfBatch) throws Exception { try { relatedItems.add(request.getReference()); if(endOfBatch || --this.count[COUNTER_POS] == 0) { try { log.debug("Sending {} indexing requests to the storage repository",relatedItems.size()); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", relatedItems,e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setReference(null); } }
BatchingRelatedItemReferenceEventHandler implements RelatedItemReferenceEventHandler { @Override public void onEvent(RelatedItemReference request, long l, boolean endOfBatch) throws Exception { try { relatedItems.add(request.getReference()); if(endOfBatch || --this.count[COUNTER_POS] == 0) { try { log.debug("Sending {} indexing requests to the storage repository",relatedItems.size()); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", relatedItems,e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setReference(null); } } }
BatchingRelatedItemReferenceEventHandler implements RelatedItemReferenceEventHandler { @Override public void onEvent(RelatedItemReference request, long l, boolean endOfBatch) throws Exception { try { relatedItems.add(request.getReference()); if(endOfBatch || --this.count[COUNTER_POS] == 0) { try { log.debug("Sending {} indexing requests to the storage repository",relatedItems.size()); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", relatedItems,e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setReference(null); } } BatchingRelatedItemReferenceEventHandler(int batchSize, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); }
BatchingRelatedItemReferenceEventHandler implements RelatedItemReferenceEventHandler { @Override public void onEvent(RelatedItemReference request, long l, boolean endOfBatch) throws Exception { try { relatedItems.add(request.getReference()); if(endOfBatch || --this.count[COUNTER_POS] == 0) { try { log.debug("Sending {} indexing requests to the storage repository",relatedItems.size()); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", relatedItems,e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setReference(null); } } BatchingRelatedItemReferenceEventHandler(int batchSize, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); @Override void onEvent(RelatedItemReference request, long l, boolean endOfBatch); void shutdown(); }
BatchingRelatedItemReferenceEventHandler implements RelatedItemReferenceEventHandler { @Override public void onEvent(RelatedItemReference request, long l, boolean endOfBatch) throws Exception { try { relatedItems.add(request.getReference()); if(endOfBatch || --this.count[COUNTER_POS] == 0) { try { log.debug("Sending {} indexing requests to the storage repository",relatedItems.size()); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", relatedItems,e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setReference(null); } } BatchingRelatedItemReferenceEventHandler(int batchSize, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); @Override void onEvent(RelatedItemReference request, long l, boolean endOfBatch); void shutdown(); }
@Test public void testShutdownIsCalledOnStorageRepo() { handler.shutdown(); assertTrue(repo.isShutdown()); }
public void shutdown() { try { storageRepository.shutdown(); } catch(Exception e) { log.error("Problem shutting down storage repository"); } }
BatchingRelatedItemReferenceEventHandler implements RelatedItemReferenceEventHandler { public void shutdown() { try { storageRepository.shutdown(); } catch(Exception e) { log.error("Problem shutting down storage repository"); } } }
BatchingRelatedItemReferenceEventHandler implements RelatedItemReferenceEventHandler { public void shutdown() { try { storageRepository.shutdown(); } catch(Exception e) { log.error("Problem shutting down storage repository"); } } BatchingRelatedItemReferenceEventHandler(int batchSize, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); }
BatchingRelatedItemReferenceEventHandler implements RelatedItemReferenceEventHandler { public void shutdown() { try { storageRepository.shutdown(); } catch(Exception e) { log.error("Problem shutting down storage repository"); } } BatchingRelatedItemReferenceEventHandler(int batchSize, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); @Override void onEvent(RelatedItemReference request, long l, boolean endOfBatch); void shutdown(); }
BatchingRelatedItemReferenceEventHandler implements RelatedItemReferenceEventHandler { public void shutdown() { try { storageRepository.shutdown(); } catch(Exception e) { log.error("Problem shutting down storage repository"); } } BatchingRelatedItemReferenceEventHandler(int batchSize, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); @Override void onEvent(RelatedItemReference request, long l, boolean endOfBatch); void shutdown(); }
@Test public void testFactoryCreatesNewBatchingRelatedItemReferenceEventHander() { BatchingRelatedItemReferenceEventHanderFactory factory = new BatchingRelatedItemReferenceEventHanderFactory(new SystemPropertiesConfiguration(),repo,null); assertNotSame(factory.getHandler(),factory.getHandler()); assertEquals(2,repo.getInvocationCount()); }
@Override public RelatedItemReferenceEventHandler getHandler() { return new BatchingRelatedItemReferenceEventHandler(configuration.getIndexBatchSize(),repository.getRepository(configuration),locationMapper); }
BatchingRelatedItemReferenceEventHanderFactory implements RelatedItemReferenceEventHandlerFactory { @Override public RelatedItemReferenceEventHandler getHandler() { return new BatchingRelatedItemReferenceEventHandler(configuration.getIndexBatchSize(),repository.getRepository(configuration),locationMapper); } }
BatchingRelatedItemReferenceEventHanderFactory implements RelatedItemReferenceEventHandlerFactory { @Override public RelatedItemReferenceEventHandler getHandler() { return new BatchingRelatedItemReferenceEventHandler(configuration.getIndexBatchSize(),repository.getRepository(configuration),locationMapper); } BatchingRelatedItemReferenceEventHanderFactory(Configuration config, RelatedItemStorageRepositoryFactory repository, RelatedItemStorageLocationMapper locationMapper); }
BatchingRelatedItemReferenceEventHanderFactory implements RelatedItemReferenceEventHandlerFactory { @Override public RelatedItemReferenceEventHandler getHandler() { return new BatchingRelatedItemReferenceEventHandler(configuration.getIndexBatchSize(),repository.getRepository(configuration),locationMapper); } BatchingRelatedItemReferenceEventHanderFactory(Configuration config, RelatedItemStorageRepositoryFactory repository, RelatedItemStorageLocationMapper locationMapper); @Override RelatedItemReferenceEventHandler getHandler(); }
BatchingRelatedItemReferenceEventHanderFactory implements RelatedItemReferenceEventHandlerFactory { @Override public RelatedItemReferenceEventHandler getHandler() { return new BatchingRelatedItemReferenceEventHandler(configuration.getIndexBatchSize(),repository.getRepository(configuration),locationMapper); } BatchingRelatedItemReferenceEventHanderFactory(Configuration config, RelatedItemStorageRepositoryFactory repository, RelatedItemStorageLocationMapper locationMapper); @Override RelatedItemReferenceEventHandler getHandler(); }
@Test public void testSendingOneItem() { CountDownLatch latch = new CountDownLatch(3); repo.handlers.get(0).setEndOfBatchCountDownLatch(latch); repo.handlers.get(1).setEndOfBatchCountDownLatch(latch); try { handler.onEvent(getMessage(),1,true); } catch(Exception e) { fail(); } try { boolean countedDown = latch.await(5000, TimeUnit.MILLISECONDS); assertTrue("Storage Repository not called in required time",countedDown); } catch (InterruptedException e) { fail("Timed out waiting for messages to be sent through the ring buffer"); e.printStackTrace(); } assertEquals(3,(repo.handlers.get(0).getNumberOfCalls()+repo.handlers.get(1).getNumberOfCalls())); assertEquals(1,(repo.handlers.get(0).getNumberOfEndOfBatchCalls()+repo.handlers.get(1).getNumberOfEndOfBatchCalls())); }
@Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { try { if(request.isValidMessage()) { if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.info("indexing message not valid. ignoring. No related products"); return; } for(RelatedItem p : converter.convertFrom(request)) batchMessages.add(p); if(endOfBatch || batchMessages.size()>=batchSize) { log.debug("handing off request to indexing processor"); try { disruptors[nextDisruptor[COUNTER_POS]++ & mask].publishEvents(BatchCopyingRelatedItemIndexMessageTranslator.INSTANCE,batchMessages.toArray(new RelatedItem[batchMessages.size()])); } finally { batchMessages.clear(); } } } else { log.info("indexing message not valid, and will be ignored. Potentially contained {} related products", request.getRelatedItems().getNumberOfRelatedItems()); } } finally { request.setValidMessage(false); } }
RoundRobinRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { try { if(request.isValidMessage()) { if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.info("indexing message not valid. ignoring. No related products"); return; } for(RelatedItem p : converter.convertFrom(request)) batchMessages.add(p); if(endOfBatch || batchMessages.size()>=batchSize) { log.debug("handing off request to indexing processor"); try { disruptors[nextDisruptor[COUNTER_POS]++ & mask].publishEvents(BatchCopyingRelatedItemIndexMessageTranslator.INSTANCE,batchMessages.toArray(new RelatedItem[batchMessages.size()])); } finally { batchMessages.clear(); } } } else { log.info("indexing message not valid, and will be ignored. Potentially contained {} related products", request.getRelatedItems().getNumberOfRelatedItems()); } } finally { request.setValidMessage(false); } } }
RoundRobinRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { try { if(request.isValidMessage()) { if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.info("indexing message not valid. ignoring. No related products"); return; } for(RelatedItem p : converter.convertFrom(request)) batchMessages.add(p); if(endOfBatch || batchMessages.size()>=batchSize) { log.debug("handing off request to indexing processor"); try { disruptors[nextDisruptor[COUNTER_POS]++ & mask].publishEvents(BatchCopyingRelatedItemIndexMessageTranslator.INSTANCE,batchMessages.toArray(new RelatedItem[batchMessages.size()])); } finally { batchMessages.clear(); } } } else { log.info("indexing message not valid, and will be ignored. Potentially contained {} related products", request.getRelatedItems().getNumberOfRelatedItems()); } } finally { request.setValidMessage(false); } } RoundRobinRelatedItemIndexingMessageEventHandler(final Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemReferenceMessageFactory messageFactory, RelatedItemReferenceEventHandlerFactory relatedItemIndexingEventHandlerFactory ); }
RoundRobinRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { try { if(request.isValidMessage()) { if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.info("indexing message not valid. ignoring. No related products"); return; } for(RelatedItem p : converter.convertFrom(request)) batchMessages.add(p); if(endOfBatch || batchMessages.size()>=batchSize) { log.debug("handing off request to indexing processor"); try { disruptors[nextDisruptor[COUNTER_POS]++ & mask].publishEvents(BatchCopyingRelatedItemIndexMessageTranslator.INSTANCE,batchMessages.toArray(new RelatedItem[batchMessages.size()])); } finally { batchMessages.clear(); } } } else { log.info("indexing message not valid, and will be ignored. Potentially contained {} related products", request.getRelatedItems().getNumberOfRelatedItems()); } } finally { request.setValidMessage(false); } } RoundRobinRelatedItemIndexingMessageEventHandler(final Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemReferenceMessageFactory messageFactory, RelatedItemReferenceEventHandlerFactory relatedItemIndexingEventHandlerFactory ); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); void shutdown(); }
RoundRobinRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { try { if(request.isValidMessage()) { if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.info("indexing message not valid. ignoring. No related products"); return; } for(RelatedItem p : converter.convertFrom(request)) batchMessages.add(p); if(endOfBatch || batchMessages.size()>=batchSize) { log.debug("handing off request to indexing processor"); try { disruptors[nextDisruptor[COUNTER_POS]++ & mask].publishEvents(BatchCopyingRelatedItemIndexMessageTranslator.INSTANCE,batchMessages.toArray(new RelatedItem[batchMessages.size()])); } finally { batchMessages.clear(); } } } else { log.info("indexing message not valid, and will be ignored. Potentially contained {} related products", request.getRelatedItems().getNumberOfRelatedItems()); } } finally { request.setValidMessage(false); } } RoundRobinRelatedItemIndexingMessageEventHandler(final Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemReferenceMessageFactory messageFactory, RelatedItemReferenceEventHandlerFactory relatedItemIndexingEventHandlerFactory ); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); void shutdown(); }
@Test public void testSendingManyItemsButBelowBatchSize() { CountDownLatch latch = new CountDownLatch(24); repo.handlers.get(0).setEndOfBatchCountDownLatch(latch); repo.handlers.get(1).setEndOfBatchCountDownLatch(latch); try { for(int i=0;i<7;i++) { handler.onEvent(getMessage(),i,false); } handler.onEvent(getMessage(),8,true); } catch(Exception e) { fail(); } try { boolean countedDown = latch.await(10000, TimeUnit.MILLISECONDS); assertTrue("Storage Repository not called in required time",countedDown); } catch (InterruptedException e) { fail("Timed out waiting for messages to be sent through the ring buffer"); e.printStackTrace(); } assertEquals(24,repo.handlers.get(0).getNumberOfCalls()); assertEquals(1,repo.handlers.get(0).getNumberOfEndOfBatchCalls()); }
@Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { try { if(request.isValidMessage()) { if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.info("indexing message not valid. ignoring. No related products"); return; } for(RelatedItem p : converter.convertFrom(request)) batchMessages.add(p); if(endOfBatch || batchMessages.size()>=batchSize) { log.debug("handing off request to indexing processor"); try { disruptors[nextDisruptor[COUNTER_POS]++ & mask].publishEvents(BatchCopyingRelatedItemIndexMessageTranslator.INSTANCE,batchMessages.toArray(new RelatedItem[batchMessages.size()])); } finally { batchMessages.clear(); } } } else { log.info("indexing message not valid, and will be ignored. Potentially contained {} related products", request.getRelatedItems().getNumberOfRelatedItems()); } } finally { request.setValidMessage(false); } }
RoundRobinRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { try { if(request.isValidMessage()) { if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.info("indexing message not valid. ignoring. No related products"); return; } for(RelatedItem p : converter.convertFrom(request)) batchMessages.add(p); if(endOfBatch || batchMessages.size()>=batchSize) { log.debug("handing off request to indexing processor"); try { disruptors[nextDisruptor[COUNTER_POS]++ & mask].publishEvents(BatchCopyingRelatedItemIndexMessageTranslator.INSTANCE,batchMessages.toArray(new RelatedItem[batchMessages.size()])); } finally { batchMessages.clear(); } } } else { log.info("indexing message not valid, and will be ignored. Potentially contained {} related products", request.getRelatedItems().getNumberOfRelatedItems()); } } finally { request.setValidMessage(false); } } }
RoundRobinRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { try { if(request.isValidMessage()) { if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.info("indexing message not valid. ignoring. No related products"); return; } for(RelatedItem p : converter.convertFrom(request)) batchMessages.add(p); if(endOfBatch || batchMessages.size()>=batchSize) { log.debug("handing off request to indexing processor"); try { disruptors[nextDisruptor[COUNTER_POS]++ & mask].publishEvents(BatchCopyingRelatedItemIndexMessageTranslator.INSTANCE,batchMessages.toArray(new RelatedItem[batchMessages.size()])); } finally { batchMessages.clear(); } } } else { log.info("indexing message not valid, and will be ignored. Potentially contained {} related products", request.getRelatedItems().getNumberOfRelatedItems()); } } finally { request.setValidMessage(false); } } RoundRobinRelatedItemIndexingMessageEventHandler(final Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemReferenceMessageFactory messageFactory, RelatedItemReferenceEventHandlerFactory relatedItemIndexingEventHandlerFactory ); }
RoundRobinRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { try { if(request.isValidMessage()) { if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.info("indexing message not valid. ignoring. No related products"); return; } for(RelatedItem p : converter.convertFrom(request)) batchMessages.add(p); if(endOfBatch || batchMessages.size()>=batchSize) { log.debug("handing off request to indexing processor"); try { disruptors[nextDisruptor[COUNTER_POS]++ & mask].publishEvents(BatchCopyingRelatedItemIndexMessageTranslator.INSTANCE,batchMessages.toArray(new RelatedItem[batchMessages.size()])); } finally { batchMessages.clear(); } } } else { log.info("indexing message not valid, and will be ignored. Potentially contained {} related products", request.getRelatedItems().getNumberOfRelatedItems()); } } finally { request.setValidMessage(false); } } RoundRobinRelatedItemIndexingMessageEventHandler(final Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemReferenceMessageFactory messageFactory, RelatedItemReferenceEventHandlerFactory relatedItemIndexingEventHandlerFactory ); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); void shutdown(); }
RoundRobinRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { try { if(request.isValidMessage()) { if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.info("indexing message not valid. ignoring. No related products"); return; } for(RelatedItem p : converter.convertFrom(request)) batchMessages.add(p); if(endOfBatch || batchMessages.size()>=batchSize) { log.debug("handing off request to indexing processor"); try { disruptors[nextDisruptor[COUNTER_POS]++ & mask].publishEvents(BatchCopyingRelatedItemIndexMessageTranslator.INSTANCE,batchMessages.toArray(new RelatedItem[batchMessages.size()])); } finally { batchMessages.clear(); } } } else { log.info("indexing message not valid, and will be ignored. Potentially contained {} related products", request.getRelatedItems().getNumberOfRelatedItems()); } } finally { request.setValidMessage(false); } } RoundRobinRelatedItemIndexingMessageEventHandler(final Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemReferenceMessageFactory messageFactory, RelatedItemReferenceEventHandlerFactory relatedItemIndexingEventHandlerFactory ); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); void shutdown(); }
@Test public void testSendingManyItemsExceedingBatchSize() { CountDownLatch latch = new CountDownLatch(78); repo.handlers.get(0).setEndOfBatchCountDownLatch(latch); repo.handlers.get(1).setEndOfBatchCountDownLatch(latch); try { for(int i=0;i<25;i++) { handler.onEvent(getMessage(),i,false); } handler.onEvent(getMessage(),26,true); } catch(Exception e) { fail(); } try { boolean countedDown = latch.await(10000, TimeUnit.MILLISECONDS); assertTrue("Storage Repository not called in required time",countedDown); } catch (InterruptedException e) { fail("Timed out waiting for messages to be sent through the ring buffer"); e.printStackTrace(); } assertEquals(51,repo.handlers.get(0).getNumberOfCalls()); assertTrue(repo.handlers.get(0).getNumberOfEndOfBatchCalls()>0); assertEquals(27,repo.handlers.get(1).getNumberOfCalls()); assertTrue(repo.handlers.get(1).getNumberOfEndOfBatchCalls()>0); }
@Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { try { if(request.isValidMessage()) { if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.info("indexing message not valid. ignoring. No related products"); return; } for(RelatedItem p : converter.convertFrom(request)) batchMessages.add(p); if(endOfBatch || batchMessages.size()>=batchSize) { log.debug("handing off request to indexing processor"); try { disruptors[nextDisruptor[COUNTER_POS]++ & mask].publishEvents(BatchCopyingRelatedItemIndexMessageTranslator.INSTANCE,batchMessages.toArray(new RelatedItem[batchMessages.size()])); } finally { batchMessages.clear(); } } } else { log.info("indexing message not valid, and will be ignored. Potentially contained {} related products", request.getRelatedItems().getNumberOfRelatedItems()); } } finally { request.setValidMessage(false); } }
RoundRobinRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { try { if(request.isValidMessage()) { if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.info("indexing message not valid. ignoring. No related products"); return; } for(RelatedItem p : converter.convertFrom(request)) batchMessages.add(p); if(endOfBatch || batchMessages.size()>=batchSize) { log.debug("handing off request to indexing processor"); try { disruptors[nextDisruptor[COUNTER_POS]++ & mask].publishEvents(BatchCopyingRelatedItemIndexMessageTranslator.INSTANCE,batchMessages.toArray(new RelatedItem[batchMessages.size()])); } finally { batchMessages.clear(); } } } else { log.info("indexing message not valid, and will be ignored. Potentially contained {} related products", request.getRelatedItems().getNumberOfRelatedItems()); } } finally { request.setValidMessage(false); } } }
RoundRobinRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { try { if(request.isValidMessage()) { if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.info("indexing message not valid. ignoring. No related products"); return; } for(RelatedItem p : converter.convertFrom(request)) batchMessages.add(p); if(endOfBatch || batchMessages.size()>=batchSize) { log.debug("handing off request to indexing processor"); try { disruptors[nextDisruptor[COUNTER_POS]++ & mask].publishEvents(BatchCopyingRelatedItemIndexMessageTranslator.INSTANCE,batchMessages.toArray(new RelatedItem[batchMessages.size()])); } finally { batchMessages.clear(); } } } else { log.info("indexing message not valid, and will be ignored. Potentially contained {} related products", request.getRelatedItems().getNumberOfRelatedItems()); } } finally { request.setValidMessage(false); } } RoundRobinRelatedItemIndexingMessageEventHandler(final Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemReferenceMessageFactory messageFactory, RelatedItemReferenceEventHandlerFactory relatedItemIndexingEventHandlerFactory ); }
RoundRobinRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { try { if(request.isValidMessage()) { if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.info("indexing message not valid. ignoring. No related products"); return; } for(RelatedItem p : converter.convertFrom(request)) batchMessages.add(p); if(endOfBatch || batchMessages.size()>=batchSize) { log.debug("handing off request to indexing processor"); try { disruptors[nextDisruptor[COUNTER_POS]++ & mask].publishEvents(BatchCopyingRelatedItemIndexMessageTranslator.INSTANCE,batchMessages.toArray(new RelatedItem[batchMessages.size()])); } finally { batchMessages.clear(); } } } else { log.info("indexing message not valid, and will be ignored. Potentially contained {} related products", request.getRelatedItems().getNumberOfRelatedItems()); } } finally { request.setValidMessage(false); } } RoundRobinRelatedItemIndexingMessageEventHandler(final Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemReferenceMessageFactory messageFactory, RelatedItemReferenceEventHandlerFactory relatedItemIndexingEventHandlerFactory ); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); void shutdown(); }
RoundRobinRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { try { if(request.isValidMessage()) { if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.info("indexing message not valid. ignoring. No related products"); return; } for(RelatedItem p : converter.convertFrom(request)) batchMessages.add(p); if(endOfBatch || batchMessages.size()>=batchSize) { log.debug("handing off request to indexing processor"); try { disruptors[nextDisruptor[COUNTER_POS]++ & mask].publishEvents(BatchCopyingRelatedItemIndexMessageTranslator.INSTANCE,batchMessages.toArray(new RelatedItem[batchMessages.size()])); } finally { batchMessages.clear(); } } } else { log.info("indexing message not valid, and will be ignored. Potentially contained {} related products", request.getRelatedItems().getNumberOfRelatedItems()); } } finally { request.setValidMessage(false); } } RoundRobinRelatedItemIndexingMessageEventHandler(final Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemReferenceMessageFactory messageFactory, RelatedItemReferenceEventHandlerFactory relatedItemIndexingEventHandlerFactory ); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); void shutdown(); }
@Test public void testHttpParseFoundTwoSources() { System.setProperty(ConfigurationConstants.PROPNAME_ELASTIC_SEARCH_HTTP_HOSTS, "http: Configuration configuration = new SystemPropertiesConfiguration(); HttpElasticSearchClientFactory factory = new AHCHttpElasticSearchClientFactory(configuration); repository = new ElasticSearchRelatedItemHttpGetRepository(configuration,factory); Map<String,String> map = repository.getRelatedItemDocument(new String[]{"1","2"}); assertEquals("Should have parsed to items",3,map.size()); assertTrue("Document id 1 contains correct hash values",map.get("1").contains("a8f346c5ddbbd8d438bc40f0049cc7f8")); assertTrue("Document id 2 contains correct hash values",map.get("2").contains("71a5120bdf4d998c2b043a681b1bd211")); }
@Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); @Override Map<String, String> getRelatedItemDocument(String[] ids); @Override void shutdown(); static Map<String,String> processResults(String responseBody); static Map<String,String> parseDocs(JSONArray array); }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { @Override public Map<String, String> getRelatedItemDocument(String[] ids) { Map<String,String> getResults = RelatedItemNoopGetRepository.getEmptyResults(ids); log.debug("MGET request to execute {} get request", ids.length); String arrayString = createArray(ids); String jsonStart = "{\"ids\":"; StringBuilder b = new StringBuilder(arrayString.length()+jsonStart.length()+1); b.append(jsonStart).append(arrayString).append('}'); String searchJson = b.toString(); log.debug("MGET request json is {}",searchJson); SearchResultEventWithSearchRequestKey[] results; HttpResult sr; long startNanos = System.nanoTime(); sr = elasticClient.executeSearch(HttpMethod.POST,url,searchJson); HttpSearchExecutionStatus searchRequestStatus = sr.getStatus(); if (searchRequestStatus == HttpSearchExecutionStatus.OK) { log.debug("MGET Processing results for get request(s)"); String responseBody = sr.getResult(); Map<String,String> mappedResults = processResults(responseBody); getResults.putAll(mappedResults); log.debug("MGET Completed, returning processed results."); } else if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_FAILURE) { log.warn("MGET Exception executing get request"); } else { if (searchRequestStatus == HttpSearchExecutionStatus.REQUEST_TIMEOUT) { log.warn("Request timeout executing search request"); } else { log.warn("Connection timeout executing search request"); } } long time = (System.nanoTime() - startNanos) / 1000000; getResults.put(keyForTiming,Long.toString(time)); return getResults; } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); @Override Map<String, String> getRelatedItemDocument(String[] ids); @Override void shutdown(); static Map<String,String> processResults(String responseBody); static Map<String,String> parseDocs(JSONArray array); }
@Test public void checkNoCallMadeForInvalidMessage() { RelatedItemIndexingMessage message = new RelatedItemIndexingMessage(configuration); message.setValidMessage(false); try { handler.onEvent(message,1,true); } catch (Exception e) { fail(); } assertEquals(0,repo.handlers.get(0).getNumberOfCalls()); }
@Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { try { if(request.isValidMessage()) { if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.info("indexing message not valid. ignoring. No related products"); return; } for(RelatedItem p : converter.convertFrom(request)) batchMessages.add(p); if(endOfBatch || batchMessages.size()>=batchSize) { log.debug("handing off request to indexing processor"); try { disruptors[nextDisruptor[COUNTER_POS]++ & mask].publishEvents(BatchCopyingRelatedItemIndexMessageTranslator.INSTANCE,batchMessages.toArray(new RelatedItem[batchMessages.size()])); } finally { batchMessages.clear(); } } } else { log.info("indexing message not valid, and will be ignored. Potentially contained {} related products", request.getRelatedItems().getNumberOfRelatedItems()); } } finally { request.setValidMessage(false); } }
RoundRobinRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { try { if(request.isValidMessage()) { if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.info("indexing message not valid. ignoring. No related products"); return; } for(RelatedItem p : converter.convertFrom(request)) batchMessages.add(p); if(endOfBatch || batchMessages.size()>=batchSize) { log.debug("handing off request to indexing processor"); try { disruptors[nextDisruptor[COUNTER_POS]++ & mask].publishEvents(BatchCopyingRelatedItemIndexMessageTranslator.INSTANCE,batchMessages.toArray(new RelatedItem[batchMessages.size()])); } finally { batchMessages.clear(); } } } else { log.info("indexing message not valid, and will be ignored. Potentially contained {} related products", request.getRelatedItems().getNumberOfRelatedItems()); } } finally { request.setValidMessage(false); } } }
RoundRobinRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { try { if(request.isValidMessage()) { if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.info("indexing message not valid. ignoring. No related products"); return; } for(RelatedItem p : converter.convertFrom(request)) batchMessages.add(p); if(endOfBatch || batchMessages.size()>=batchSize) { log.debug("handing off request to indexing processor"); try { disruptors[nextDisruptor[COUNTER_POS]++ & mask].publishEvents(BatchCopyingRelatedItemIndexMessageTranslator.INSTANCE,batchMessages.toArray(new RelatedItem[batchMessages.size()])); } finally { batchMessages.clear(); } } } else { log.info("indexing message not valid, and will be ignored. Potentially contained {} related products", request.getRelatedItems().getNumberOfRelatedItems()); } } finally { request.setValidMessage(false); } } RoundRobinRelatedItemIndexingMessageEventHandler(final Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemReferenceMessageFactory messageFactory, RelatedItemReferenceEventHandlerFactory relatedItemIndexingEventHandlerFactory ); }
RoundRobinRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { try { if(request.isValidMessage()) { if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.info("indexing message not valid. ignoring. No related products"); return; } for(RelatedItem p : converter.convertFrom(request)) batchMessages.add(p); if(endOfBatch || batchMessages.size()>=batchSize) { log.debug("handing off request to indexing processor"); try { disruptors[nextDisruptor[COUNTER_POS]++ & mask].publishEvents(BatchCopyingRelatedItemIndexMessageTranslator.INSTANCE,batchMessages.toArray(new RelatedItem[batchMessages.size()])); } finally { batchMessages.clear(); } } } else { log.info("indexing message not valid, and will be ignored. Potentially contained {} related products", request.getRelatedItems().getNumberOfRelatedItems()); } } finally { request.setValidMessage(false); } } RoundRobinRelatedItemIndexingMessageEventHandler(final Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemReferenceMessageFactory messageFactory, RelatedItemReferenceEventHandlerFactory relatedItemIndexingEventHandlerFactory ); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); void shutdown(); }
RoundRobinRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { try { if(request.isValidMessage()) { if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.info("indexing message not valid. ignoring. No related products"); return; } for(RelatedItem p : converter.convertFrom(request)) batchMessages.add(p); if(endOfBatch || batchMessages.size()>=batchSize) { log.debug("handing off request to indexing processor"); try { disruptors[nextDisruptor[COUNTER_POS]++ & mask].publishEvents(BatchCopyingRelatedItemIndexMessageTranslator.INSTANCE,batchMessages.toArray(new RelatedItem[batchMessages.size()])); } finally { batchMessages.clear(); } } } else { log.info("indexing message not valid, and will be ignored. Potentially contained {} related products", request.getRelatedItems().getNumberOfRelatedItems()); } } finally { request.setValidMessage(false); } } RoundRobinRelatedItemIndexingMessageEventHandler(final Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemReferenceMessageFactory messageFactory, RelatedItemReferenceEventHandlerFactory relatedItemIndexingEventHandlerFactory ); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); void shutdown(); }
@Test public void checkNoCallMadeForMessageWithNoProducts() { RelatedItemIndexingMessage message = new RelatedItemIndexingMessage(configuration); message.setValidMessage(true); message.getRelatedItems().setNumberOfRelatedItems(0); try { handler.onEvent(message,1,true); } catch (Exception e) { fail(); } assertEquals(0,repo.handlers.get(0).getNumberOfCalls()); }
@Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { try { if(request.isValidMessage()) { if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.info("indexing message not valid. ignoring. No related products"); return; } for(RelatedItem p : converter.convertFrom(request)) batchMessages.add(p); if(endOfBatch || batchMessages.size()>=batchSize) { log.debug("handing off request to indexing processor"); try { disruptors[nextDisruptor[COUNTER_POS]++ & mask].publishEvents(BatchCopyingRelatedItemIndexMessageTranslator.INSTANCE,batchMessages.toArray(new RelatedItem[batchMessages.size()])); } finally { batchMessages.clear(); } } } else { log.info("indexing message not valid, and will be ignored. Potentially contained {} related products", request.getRelatedItems().getNumberOfRelatedItems()); } } finally { request.setValidMessage(false); } }
RoundRobinRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { try { if(request.isValidMessage()) { if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.info("indexing message not valid. ignoring. No related products"); return; } for(RelatedItem p : converter.convertFrom(request)) batchMessages.add(p); if(endOfBatch || batchMessages.size()>=batchSize) { log.debug("handing off request to indexing processor"); try { disruptors[nextDisruptor[COUNTER_POS]++ & mask].publishEvents(BatchCopyingRelatedItemIndexMessageTranslator.INSTANCE,batchMessages.toArray(new RelatedItem[batchMessages.size()])); } finally { batchMessages.clear(); } } } else { log.info("indexing message not valid, and will be ignored. Potentially contained {} related products", request.getRelatedItems().getNumberOfRelatedItems()); } } finally { request.setValidMessage(false); } } }
RoundRobinRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { try { if(request.isValidMessage()) { if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.info("indexing message not valid. ignoring. No related products"); return; } for(RelatedItem p : converter.convertFrom(request)) batchMessages.add(p); if(endOfBatch || batchMessages.size()>=batchSize) { log.debug("handing off request to indexing processor"); try { disruptors[nextDisruptor[COUNTER_POS]++ & mask].publishEvents(BatchCopyingRelatedItemIndexMessageTranslator.INSTANCE,batchMessages.toArray(new RelatedItem[batchMessages.size()])); } finally { batchMessages.clear(); } } } else { log.info("indexing message not valid, and will be ignored. Potentially contained {} related products", request.getRelatedItems().getNumberOfRelatedItems()); } } finally { request.setValidMessage(false); } } RoundRobinRelatedItemIndexingMessageEventHandler(final Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemReferenceMessageFactory messageFactory, RelatedItemReferenceEventHandlerFactory relatedItemIndexingEventHandlerFactory ); }
RoundRobinRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { try { if(request.isValidMessage()) { if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.info("indexing message not valid. ignoring. No related products"); return; } for(RelatedItem p : converter.convertFrom(request)) batchMessages.add(p); if(endOfBatch || batchMessages.size()>=batchSize) { log.debug("handing off request to indexing processor"); try { disruptors[nextDisruptor[COUNTER_POS]++ & mask].publishEvents(BatchCopyingRelatedItemIndexMessageTranslator.INSTANCE,batchMessages.toArray(new RelatedItem[batchMessages.size()])); } finally { batchMessages.clear(); } } } else { log.info("indexing message not valid, and will be ignored. Potentially contained {} related products", request.getRelatedItems().getNumberOfRelatedItems()); } } finally { request.setValidMessage(false); } } RoundRobinRelatedItemIndexingMessageEventHandler(final Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemReferenceMessageFactory messageFactory, RelatedItemReferenceEventHandlerFactory relatedItemIndexingEventHandlerFactory ); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); void shutdown(); }
RoundRobinRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { try { if(request.isValidMessage()) { if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.info("indexing message not valid. ignoring. No related products"); return; } for(RelatedItem p : converter.convertFrom(request)) batchMessages.add(p); if(endOfBatch || batchMessages.size()>=batchSize) { log.debug("handing off request to indexing processor"); try { disruptors[nextDisruptor[COUNTER_POS]++ & mask].publishEvents(BatchCopyingRelatedItemIndexMessageTranslator.INSTANCE,batchMessages.toArray(new RelatedItem[batchMessages.size()])); } finally { batchMessages.clear(); } } } else { log.info("indexing message not valid, and will be ignored. Potentially contained {} related products", request.getRelatedItems().getNumberOfRelatedItems()); } } finally { request.setValidMessage(false); } } RoundRobinRelatedItemIndexingMessageEventHandler(final Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemReferenceMessageFactory messageFactory, RelatedItemReferenceEventHandlerFactory relatedItemIndexingEventHandlerFactory ); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); void shutdown(); }
@Test public void testShutdownIsCalledOnStorageRepo() { handler.shutdown(); assertTrue(repo.handlers.get(0).isShutdown()); assertTrue(repo.handlers.get(1).isShutdown()); }
public void shutdown() { if(!shutdown) { shutdown=true; for(RelatedItemReferenceEventHandler handler : handlers) { try { handler.shutdown(); } catch(Exception e) { log.error("Issue terminating handler",e); } } for(ExecutorService executorService : executors) { try { executorService.shutdownNow(); } catch(Exception e) { log.error("Problem during shutdown terminating the executorservice",e); } } for(Disruptor disruptor : disruptors) { try { disruptor.shutdown(); } catch(Exception e) { log.error("Problem during shutdown of the disruptor",e); } } } }
RoundRobinRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { public void shutdown() { if(!shutdown) { shutdown=true; for(RelatedItemReferenceEventHandler handler : handlers) { try { handler.shutdown(); } catch(Exception e) { log.error("Issue terminating handler",e); } } for(ExecutorService executorService : executors) { try { executorService.shutdownNow(); } catch(Exception e) { log.error("Problem during shutdown terminating the executorservice",e); } } for(Disruptor disruptor : disruptors) { try { disruptor.shutdown(); } catch(Exception e) { log.error("Problem during shutdown of the disruptor",e); } } } } }
RoundRobinRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { public void shutdown() { if(!shutdown) { shutdown=true; for(RelatedItemReferenceEventHandler handler : handlers) { try { handler.shutdown(); } catch(Exception e) { log.error("Issue terminating handler",e); } } for(ExecutorService executorService : executors) { try { executorService.shutdownNow(); } catch(Exception e) { log.error("Problem during shutdown terminating the executorservice",e); } } for(Disruptor disruptor : disruptors) { try { disruptor.shutdown(); } catch(Exception e) { log.error("Problem during shutdown of the disruptor",e); } } } } RoundRobinRelatedItemIndexingMessageEventHandler(final Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemReferenceMessageFactory messageFactory, RelatedItemReferenceEventHandlerFactory relatedItemIndexingEventHandlerFactory ); }
RoundRobinRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { public void shutdown() { if(!shutdown) { shutdown=true; for(RelatedItemReferenceEventHandler handler : handlers) { try { handler.shutdown(); } catch(Exception e) { log.error("Issue terminating handler",e); } } for(ExecutorService executorService : executors) { try { executorService.shutdownNow(); } catch(Exception e) { log.error("Problem during shutdown terminating the executorservice",e); } } for(Disruptor disruptor : disruptors) { try { disruptor.shutdown(); } catch(Exception e) { log.error("Problem during shutdown of the disruptor",e); } } } } RoundRobinRelatedItemIndexingMessageEventHandler(final Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemReferenceMessageFactory messageFactory, RelatedItemReferenceEventHandlerFactory relatedItemIndexingEventHandlerFactory ); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); void shutdown(); }
RoundRobinRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { public void shutdown() { if(!shutdown) { shutdown=true; for(RelatedItemReferenceEventHandler handler : handlers) { try { handler.shutdown(); } catch(Exception e) { log.error("Issue terminating handler",e); } } for(ExecutorService executorService : executors) { try { executorService.shutdownNow(); } catch(Exception e) { log.error("Problem during shutdown terminating the executorservice",e); } } for(Disruptor disruptor : disruptors) { try { disruptor.shutdown(); } catch(Exception e) { log.error("Problem during shutdown of the disruptor",e); } } } } RoundRobinRelatedItemIndexingMessageEventHandler(final Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemReferenceMessageFactory messageFactory, RelatedItemReferenceEventHandlerFactory relatedItemIndexingEventHandlerFactory ); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); void shutdown(); }
@Test public void testSendingOneItem() { try { handler.onEvent(getMessage(),1,true); } catch(Exception e) { fail(); } assertEquals(1,repo.getNumberOfCalls()); assertEquals(3,repo.getNumberOfProductsSentForStoring()); }
@Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } }
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } } }
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } } SingleRelatedItemIndexingMessageEventHandler(Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); }
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } } SingleRelatedItemIndexingMessageEventHandler(Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); @Override void shutdown(); }
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } } SingleRelatedItemIndexingMessageEventHandler(Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); @Override void shutdown(); }
@Test public void testSendingManyItemsButBelowBatchSize() { try { for(int i=0;i<7;i++) { handler.onEvent(getMessage(),i,false); } handler.onEvent(getMessage(),8,true); } catch(Exception e) { fail(); } assertEquals(1,repo.getNumberOfCalls()); assertEquals(24,repo.getNumberOfProductsSentForStoring()); }
@Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } }
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } } }
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } } SingleRelatedItemIndexingMessageEventHandler(Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); }
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } } SingleRelatedItemIndexingMessageEventHandler(Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); @Override void shutdown(); }
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } } SingleRelatedItemIndexingMessageEventHandler(Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); @Override void shutdown(); }
@Test public void testSendingManyItemsExceedingBatchSize() { try { for(int i=0;i<25;i++) { handler.onEvent(getMessage(),i,false); } handler.onEvent(getMessage(),26,true); } catch(Exception e) { fail(); } assertEquals(3,repo.getNumberOfCalls()); assertEquals(78,repo.getNumberOfProductsSentForStoring()); }
@Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } }
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } } }
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } } SingleRelatedItemIndexingMessageEventHandler(Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); }
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } } SingleRelatedItemIndexingMessageEventHandler(Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); @Override void shutdown(); }
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } } SingleRelatedItemIndexingMessageEventHandler(Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); @Override void shutdown(); }
@Test public void checkNoCallMadeForInvalidMessage() { RelatedItemIndexingMessage message = new RelatedItemIndexingMessage(configuration); message.setValidMessage(false); try { handler.onEvent(message,1,true); } catch (Exception e) { fail(); } assertEquals(0,repo.getNumberOfCalls()); assertEquals(0,repo.getNumberOfProductsSentForStoring()); }
@Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } }
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } } }
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } } SingleRelatedItemIndexingMessageEventHandler(Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); }
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } } SingleRelatedItemIndexingMessageEventHandler(Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); @Override void shutdown(); }
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } } SingleRelatedItemIndexingMessageEventHandler(Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); @Override void shutdown(); }
@Test public void checkNoCallMadeForMessageWithNoProducts() { RelatedItemIndexingMessage message = new RelatedItemIndexingMessage(configuration); message.setValidMessage(true); message.getRelatedItems().setNumberOfRelatedItems(0); try { handler.onEvent(message,1,true); } catch (Exception e) { fail(); } assertEquals(0,repo.getNumberOfCalls()); assertEquals(0,repo.getNumberOfProductsSentForStoring()); }
@Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } }
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } } }
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } } SingleRelatedItemIndexingMessageEventHandler(Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); }
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } } SingleRelatedItemIndexingMessageEventHandler(Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); @Override void shutdown(); }
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch) throws Exception { if(!request.isValidMessage()) { log.debug("Invalid indexing message. Ignoring message"); return; } if(request.getRelatedItems().getNumberOfRelatedItems()==0) { log.debug("Invalid indexing message, no related products. Ignoring message"); request.setValidMessage(false); return; } try { RelatedItem[] products = indexConverter.convertFrom(request); this.count[COUNTER_POS]-=products.length; for(RelatedItem p : products) { relatedItems.add(p); } if(endOfBatch || this.count[COUNTER_POS]<1) { try { log.debug("Sending indexing requests to the storage repository"); try { storageRepository.store(locationMapper, relatedItems); } catch(Exception e) { log.warn("Exception calling storage repository for related products:{}", products, e); } } finally { this.count[COUNTER_POS] = batchSize; relatedItems.clear(); } } } finally { request.setValidMessage(false); } } SingleRelatedItemIndexingMessageEventHandler(Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); @Override void shutdown(); }
@Test public void testShutdownIsCalledOnStorageRepo() { handler.shutdown(); assertTrue(repo.isShutdown()); }
@Override public void shutdown() { if(!shutdown) { shutdown = true; try { storageRepository.shutdown(); } catch(Exception e) { log.warn("Unable to shutdown respository client"); } } }
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void shutdown() { if(!shutdown) { shutdown = true; try { storageRepository.shutdown(); } catch(Exception e) { log.warn("Unable to shutdown respository client"); } } } }
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void shutdown() { if(!shutdown) { shutdown = true; try { storageRepository.shutdown(); } catch(Exception e) { log.warn("Unable to shutdown respository client"); } } } SingleRelatedItemIndexingMessageEventHandler(Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); }
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void shutdown() { if(!shutdown) { shutdown = true; try { storageRepository.shutdown(); } catch(Exception e) { log.warn("Unable to shutdown respository client"); } } } SingleRelatedItemIndexingMessageEventHandler(Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); @Override void shutdown(); }
SingleRelatedItemIndexingMessageEventHandler implements RelatedItemIndexingMessageEventHandler { @Override public void shutdown() { if(!shutdown) { shutdown = true; try { storageRepository.shutdown(); } catch(Exception e) { log.warn("Unable to shutdown respository client"); } } } SingleRelatedItemIndexingMessageEventHandler(Configuration configuration, RelatedItemIndexingMessageConverter converter, RelatedItemStorageRepository repository, RelatedItemStorageLocationMapper locationMapper); @Override void onEvent(RelatedItemIndexingMessage request, long l, boolean endOfBatch); @Override void shutdown(); }
@Test public void testHandlerIsNotExecutedWithEmptyRequestData() { processor.processRequest(configuation, ByteBuffer.wrap(new byte[0])); assertEquals(0,handler.getNumberOfCalls()); }
@Override public IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data) { if(canIndex) { try { boolean published = ringBuffer.tryPublishEvent(requestConverter.createConverter(config,data)); return published ? IndexRequestPublishingStatus.PUBLISHED : IndexRequestPublishingStatus.NO_SPACE_AVALIABLE; } catch(InvalidIndexingRequestException e) { log.warn("Invalid json content, unable to process request: {}", e.getMessage()); if(log.isDebugEnabled()) { if(canOutputRequestData && data.hasArray()) { log.debug("content requested to be indexed: {}", Arrays.toString(data.array())); } } return IndexRequestPublishingStatus.FAILED; } } else { log.error("The indexing processor has been shutdown, and cannot accept requests."); return IndexRequestPublishingStatus.PUBLISHER_SHUTDOWN; } }
DisruptorBasedRelatedItemIndexRequestProcessor implements RelatedItemIndexRequestProcessor { @Override public IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data) { if(canIndex) { try { boolean published = ringBuffer.tryPublishEvent(requestConverter.createConverter(config,data)); return published ? IndexRequestPublishingStatus.PUBLISHED : IndexRequestPublishingStatus.NO_SPACE_AVALIABLE; } catch(InvalidIndexingRequestException e) { log.warn("Invalid json content, unable to process request: {}", e.getMessage()); if(log.isDebugEnabled()) { if(canOutputRequestData && data.hasArray()) { log.debug("content requested to be indexed: {}", Arrays.toString(data.array())); } } return IndexRequestPublishingStatus.FAILED; } } else { log.error("The indexing processor has been shutdown, and cannot accept requests."); return IndexRequestPublishingStatus.PUBLISHER_SHUTDOWN; } } }
DisruptorBasedRelatedItemIndexRequestProcessor implements RelatedItemIndexRequestProcessor { @Override public IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data) { if(canIndex) { try { boolean published = ringBuffer.tryPublishEvent(requestConverter.createConverter(config,data)); return published ? IndexRequestPublishingStatus.PUBLISHED : IndexRequestPublishingStatus.NO_SPACE_AVALIABLE; } catch(InvalidIndexingRequestException e) { log.warn("Invalid json content, unable to process request: {}", e.getMessage()); if(log.isDebugEnabled()) { if(canOutputRequestData && data.hasArray()) { log.debug("content requested to be indexed: {}", Arrays.toString(data.array())); } } return IndexRequestPublishingStatus.FAILED; } } else { log.error("The indexing processor has been shutdown, and cannot accept requests."); return IndexRequestPublishingStatus.PUBLISHER_SHUTDOWN; } } DisruptorBasedRelatedItemIndexRequestProcessor(Configuration configuration, IndexingRequestConverterFactory requestConverter, EventFactory<RelatedItemIndexingMessage> indexingMessageFactory, RelatedItemIndexingMessageEventHandler eventHandler ); }
DisruptorBasedRelatedItemIndexRequestProcessor implements RelatedItemIndexRequestProcessor { @Override public IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data) { if(canIndex) { try { boolean published = ringBuffer.tryPublishEvent(requestConverter.createConverter(config,data)); return published ? IndexRequestPublishingStatus.PUBLISHED : IndexRequestPublishingStatus.NO_SPACE_AVALIABLE; } catch(InvalidIndexingRequestException e) { log.warn("Invalid json content, unable to process request: {}", e.getMessage()); if(log.isDebugEnabled()) { if(canOutputRequestData && data.hasArray()) { log.debug("content requested to be indexed: {}", Arrays.toString(data.array())); } } return IndexRequestPublishingStatus.FAILED; } } else { log.error("The indexing processor has been shutdown, and cannot accept requests."); return IndexRequestPublishingStatus.PUBLISHER_SHUTDOWN; } } DisruptorBasedRelatedItemIndexRequestProcessor(Configuration configuration, IndexingRequestConverterFactory requestConverter, EventFactory<RelatedItemIndexingMessage> indexingMessageFactory, RelatedItemIndexingMessageEventHandler eventHandler ); @Override IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data); @PreDestroy void shutdown(); }
DisruptorBasedRelatedItemIndexRequestProcessor implements RelatedItemIndexRequestProcessor { @Override public IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data) { if(canIndex) { try { boolean published = ringBuffer.tryPublishEvent(requestConverter.createConverter(config,data)); return published ? IndexRequestPublishingStatus.PUBLISHED : IndexRequestPublishingStatus.NO_SPACE_AVALIABLE; } catch(InvalidIndexingRequestException e) { log.warn("Invalid json content, unable to process request: {}", e.getMessage()); if(log.isDebugEnabled()) { if(canOutputRequestData && data.hasArray()) { log.debug("content requested to be indexed: {}", Arrays.toString(data.array())); } } return IndexRequestPublishingStatus.FAILED; } } else { log.error("The indexing processor has been shutdown, and cannot accept requests."); return IndexRequestPublishingStatus.PUBLISHER_SHUTDOWN; } } DisruptorBasedRelatedItemIndexRequestProcessor(Configuration configuration, IndexingRequestConverterFactory requestConverter, EventFactory<RelatedItemIndexingMessage> indexingMessageFactory, RelatedItemIndexingMessageEventHandler eventHandler ); @Override IndexRequestPublishingStatus processRequest(Configuration config, ByteBuffer data); @PreDestroy void shutdown(); }
@Test public void parseFoundOneAndOneWithError() { Map<String,String> parsedDoc = ElasticSearchRelatedItemHttpGetRepository.processResults(FOUND_ONE_ONE_WITH_ERROR); assertTrue(parsedDoc.size()==1); assertTrue(parsedDoc.containsKey("1")); assertTrue(parsedDoc.get("1").contains("a8f346c5ddbbd8d438bc40f0049cc7f8")); }
public static Map<String,String> processResults(String responseBody) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(responseBody); Object results = object.get("docs"); if(results!=null && results instanceof JSONArray) { return parseDocs((JSONArray)results); }else { return Collections.EMPTY_MAP; } } catch (Exception e){ return Collections.EMPTY_MAP; } }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { public static Map<String,String> processResults(String responseBody) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(responseBody); Object results = object.get("docs"); if(results!=null && results instanceof JSONArray) { return parseDocs((JSONArray)results); }else { return Collections.EMPTY_MAP; } } catch (Exception e){ return Collections.EMPTY_MAP; } } }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { public static Map<String,String> processResults(String responseBody) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(responseBody); Object results = object.get("docs"); if(results!=null && results instanceof JSONArray) { return parseDocs((JSONArray)results); }else { return Collections.EMPTY_MAP; } } catch (Exception e){ return Collections.EMPTY_MAP; } } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { public static Map<String,String> processResults(String responseBody) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(responseBody); Object results = object.get("docs"); if(results!=null && results instanceof JSONArray) { return parseDocs((JSONArray)results); }else { return Collections.EMPTY_MAP; } } catch (Exception e){ return Collections.EMPTY_MAP; } } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); @Override Map<String, String> getRelatedItemDocument(String[] ids); @Override void shutdown(); static Map<String,String> processResults(String responseBody); static Map<String,String> parseDocs(JSONArray array); }
ElasticSearchRelatedItemHttpGetRepository implements RelatedItemGetRepository { public static Map<String,String> processResults(String responseBody) { JSONParser parser = new JSONParser(JSONParser.MODE_RFC4627); try { JSONObject object = (JSONObject)parser.parse(responseBody); Object results = object.get("docs"); if(results!=null && results instanceof JSONArray) { return parseDocs((JSONArray)results); }else { return Collections.EMPTY_MAP; } } catch (Exception e){ return Collections.EMPTY_MAP; } } ElasticSearchRelatedItemHttpGetRepository(Configuration configuration, HttpElasticSearchClientFactory factory); @Override Map<String, String> getRelatedItemDocument(String[] ids); @Override void shutdown(); static Map<String,String> processResults(String responseBody); static Map<String,String> parseDocs(JSONArray array); }
@Test public void getList() throws Exception { assertEquals(totalResult.getList().size(), 0); }
@NonNull public List<CheckInfo> getList() { return mList; }
TotalResult { @NonNull public List<CheckInfo> getList() { return mList; } }
TotalResult { @NonNull public List<CheckInfo> getList() { return mList; } TotalResult(@NonNull List<CheckInfo> list, @CheckingState int checkState); }
TotalResult { @NonNull public List<CheckInfo> getList() { return mList; } TotalResult(@NonNull List<CheckInfo> list, @CheckingState int checkState); @NonNull List<CheckInfo> getList(); @CheckingState int getCheckState(); }
TotalResult { @NonNull public List<CheckInfo> getList() { return mList; } TotalResult(@NonNull List<CheckInfo> list, @CheckingState int checkState); @NonNull List<CheckInfo> getList(); @CheckingState int getCheckState(); }
@Test public void getCheckState() throws Exception { assertEquals(totalResult.getCheckState(), GeneralConst.CH_STATE_CHECKED_ROOT_NOT_DETECTED); assertNotEquals(totalResult.getCheckState(), GeneralConst.CH_STATE_CHECKED_ERROR); assertNotEquals(totalResult.getCheckState(), GeneralConst.CH_STATE_CHECKED_ROOT_DETECTED); assertNotEquals(totalResult.getCheckState(), GeneralConst.CH_STATE_STILL_GOING); assertNotEquals(totalResult.getCheckState(), GeneralConst.CH_STATE_UNCHECKED); }
@CheckingState public int getCheckState() { return mCheckState; }
TotalResult { @CheckingState public int getCheckState() { return mCheckState; } }
TotalResult { @CheckingState public int getCheckState() { return mCheckState; } TotalResult(@NonNull List<CheckInfo> list, @CheckingState int checkState); }
TotalResult { @CheckingState public int getCheckState() { return mCheckState; } TotalResult(@NonNull List<CheckInfo> list, @CheckingState int checkState); @NonNull List<CheckInfo> getList(); @CheckingState int getCheckState(); }
TotalResult { @CheckingState public int getCheckState() { return mCheckState; } TotalResult(@NonNull List<CheckInfo> list, @CheckingState int checkState); @NonNull List<CheckInfo> getList(); @CheckingState int getCheckState(); }
@Test public void getTypeCheck() throws Exception { checkInfo.setTypeCheck(CH_TYPE_HOOKS); assertEquals(checkInfo.getTypeCheck(), CH_TYPE_HOOKS); }
@CheckingMethodType public int getTypeCheck() { return mTypeCheck; }
CheckInfo { @CheckingMethodType public int getTypeCheck() { return mTypeCheck; } }
CheckInfo { @CheckingMethodType public int getTypeCheck() { return mTypeCheck; } CheckInfo(@Nullable Boolean state,@CheckingMethodType int typeCheck); }
CheckInfo { @CheckingMethodType public int getTypeCheck() { return mTypeCheck; } CheckInfo(@Nullable Boolean state,@CheckingMethodType int typeCheck); @Nullable Boolean getState(); void setState(@Nullable Boolean state); @CheckingMethodType int getTypeCheck(); void setTypeCheck(int typeCheck); @Override boolean equals(Object o); @Override int hashCode(); }
CheckInfo { @CheckingMethodType public int getTypeCheck() { return mTypeCheck; } CheckInfo(@Nullable Boolean state,@CheckingMethodType int typeCheck); @Nullable Boolean getState(); void setState(@Nullable Boolean state); @CheckingMethodType int getTypeCheck(); void setTypeCheck(int typeCheck); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void equalsTest() throws Exception { checkInfo.setState(null); assertThat(checkInfo.equals(checkInfo), is(true)); assertThat(checkInfo.equals(this), is(false)); assertThat(checkInfo.equals(null), is(false)); checkInfo.setTypeCheck(GeneralConst.CH_TYPE_UNKNOWN); assertThat(checkInfo.equals(new CheckInfo(null, GeneralConst.CH_TYPE_UNKNOWN)), is(true)); assertThat(checkInfo.equals(new CheckInfo(null, GeneralConst.CH_TYPE_NON_RELEASE_KEYS)), is(false)); assertThat(checkInfo.equals(new CheckInfo(true, GeneralConst.CH_TYPE_UNKNOWN)), is(false)); }
@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CheckInfo)) return false; CheckInfo checkInfo = (CheckInfo) o; if (mTypeCheck != checkInfo.mTypeCheck) return false; return mState != null ? mState.equals(checkInfo.mState) : checkInfo.mState == null; }
CheckInfo { @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CheckInfo)) return false; CheckInfo checkInfo = (CheckInfo) o; if (mTypeCheck != checkInfo.mTypeCheck) return false; return mState != null ? mState.equals(checkInfo.mState) : checkInfo.mState == null; } }
CheckInfo { @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CheckInfo)) return false; CheckInfo checkInfo = (CheckInfo) o; if (mTypeCheck != checkInfo.mTypeCheck) return false; return mState != null ? mState.equals(checkInfo.mState) : checkInfo.mState == null; } CheckInfo(@Nullable Boolean state,@CheckingMethodType int typeCheck); }
CheckInfo { @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CheckInfo)) return false; CheckInfo checkInfo = (CheckInfo) o; if (mTypeCheck != checkInfo.mTypeCheck) return false; return mState != null ? mState.equals(checkInfo.mState) : checkInfo.mState == null; } CheckInfo(@Nullable Boolean state,@CheckingMethodType int typeCheck); @Nullable Boolean getState(); void setState(@Nullable Boolean state); @CheckingMethodType int getTypeCheck(); void setTypeCheck(int typeCheck); @Override boolean equals(Object o); @Override int hashCode(); }
CheckInfo { @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CheckInfo)) return false; CheckInfo checkInfo = (CheckInfo) o; if (mTypeCheck != checkInfo.mTypeCheck) return false; return mState != null ? mState.equals(checkInfo.mState) : checkInfo.mState == null; } CheckInfo(@Nullable Boolean state,@CheckingMethodType int typeCheck); @Nullable Boolean getState(); void setState(@Nullable Boolean state); @CheckingMethodType int getTypeCheck(); void setTypeCheck(int typeCheck); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void hashCodeTest() throws Exception { checkInfo.setState(true); checkInfo.setTypeCheck(CH_TYPE_DEV_KEYS); CheckInfo chInfo = new CheckInfo(true,CH_TYPE_DEV_KEYS); assertEquals(checkInfo.hashCode(), chInfo.hashCode()); chInfo.setTypeCheck(CH_TYPE_HOOKS); assertNotEquals(checkInfo.hashCode(), chInfo.hashCode()); chInfo.setState(null); checkInfo.setState(null); checkInfo.setTypeCheck(CH_TYPE_HOOKS); assertEquals(checkInfo.hashCode(), chInfo.hashCode()); }
@Override public int hashCode() { int result = mState != null ? mState.hashCode() : 0; result = 31 * result + mTypeCheck; return result; }
CheckInfo { @Override public int hashCode() { int result = mState != null ? mState.hashCode() : 0; result = 31 * result + mTypeCheck; return result; } }
CheckInfo { @Override public int hashCode() { int result = mState != null ? mState.hashCode() : 0; result = 31 * result + mTypeCheck; return result; } CheckInfo(@Nullable Boolean state,@CheckingMethodType int typeCheck); }
CheckInfo { @Override public int hashCode() { int result = mState != null ? mState.hashCode() : 0; result = 31 * result + mTypeCheck; return result; } CheckInfo(@Nullable Boolean state,@CheckingMethodType int typeCheck); @Nullable Boolean getState(); void setState(@Nullable Boolean state); @CheckingMethodType int getTypeCheck(); void setTypeCheck(int typeCheck); @Override boolean equals(Object o); @Override int hashCode(); }
CheckInfo { @Override public int hashCode() { int result = mState != null ? mState.hashCode() : 0; result = 31 * result + mTypeCheck; return result; } CheckInfo(@Nullable Boolean state,@CheckingMethodType int typeCheck); @Nullable Boolean getState(); void setState(@Nullable Boolean state); @CheckingMethodType int getTypeCheck(); void setTypeCheck(int typeCheck); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void getCheckStringIdTest() throws Exception { assertThat(getCheckStringId(CH_TYPE_TEST_KEYS), is(R.string.checks_desc_1)); assertThat(getCheckStringId(CH_TYPE_DEV_KEYS), is(R.string.checks_desc_2)); assertThat(getCheckStringId(CH_TYPE_NON_RELEASE_KEYS), is(R.string.checks_desc_3)); assertThat(getCheckStringId(CH_TYPE_DANGEROUS_PROPS), is(R.string.checks_desc_4)); assertThat(getCheckStringId(CH_TYPE_PERMISSIVE_SELINUX), is(R.string.checks_desc_5)); assertThat(getCheckStringId(CH_TYPE_SU_EXISTS), is(R.string.checks_desc_6)); assertThat(getCheckStringId(CH_TYPE_SUPER_USER_APK), is(R.string.checks_desc_7)); assertThat(getCheckStringId(CH_TYPE_SU_BINARY), is(R.string.checks_desc_8)); assertThat(getCheckStringId(CH_TYPE_BUSYBOX_BINARY), is(R.string.checks_desc_9)); assertThat(getCheckStringId(CH_TYPE_XPOSED), is(R.string.checks_desc_10)); assertThat(getCheckStringId(CH_TYPE_RESETPROP), is(R.string.checks_desc_11)); assertThat(getCheckStringId(CH_TYPE_WRONG_PATH_PERMITION), is(R.string.checks_desc_12)); assertThat(getCheckStringId(CH_TYPE_HOOKS), is(R.string.checks_desc_13)); assertThat(getCheckStringId(CH_TYPE_UNKNOWN), is(R.string.empty)); assertEquals(getCheckStringId(CH_TYPE_UNKNOWN), R.string.empty); assertThat(getCheckStringId(Integer.MAX_VALUE), is(R.string.empty)); }
@StringRes public static int getCheckStringId(@CheckingMethodType int typeCheck) { @StringRes int result = 0; switch (typeCheck) { case CH_TYPE_TEST_KEYS: result = R.string.checks_desc_1; break; case CH_TYPE_DEV_KEYS: result = R.string.checks_desc_2; break; case CH_TYPE_NON_RELEASE_KEYS: result = R.string.checks_desc_3; break; case CH_TYPE_DANGEROUS_PROPS: result = R.string.checks_desc_4; break; case CH_TYPE_PERMISSIVE_SELINUX: result = R.string.checks_desc_5; break; case CH_TYPE_SU_EXISTS: result = R.string.checks_desc_6; break; case CH_TYPE_SUPER_USER_APK: result = R.string.checks_desc_7; break; case CH_TYPE_SU_BINARY: result = R.string.checks_desc_8; break; case CH_TYPE_BUSYBOX_BINARY: result = R.string.checks_desc_9; break; case CH_TYPE_XPOSED: result = R.string.checks_desc_10; break; case CH_TYPE_RESETPROP: result = R.string.checks_desc_11; break; case CH_TYPE_WRONG_PATH_PERMITION: result = R.string.checks_desc_12; break; case CH_TYPE_HOOKS: result = R.string.checks_desc_13; break; case CH_TYPE_UNKNOWN: default: result = R.string.empty; } return result; }
ChecksHelper { @StringRes public static int getCheckStringId(@CheckingMethodType int typeCheck) { @StringRes int result = 0; switch (typeCheck) { case CH_TYPE_TEST_KEYS: result = R.string.checks_desc_1; break; case CH_TYPE_DEV_KEYS: result = R.string.checks_desc_2; break; case CH_TYPE_NON_RELEASE_KEYS: result = R.string.checks_desc_3; break; case CH_TYPE_DANGEROUS_PROPS: result = R.string.checks_desc_4; break; case CH_TYPE_PERMISSIVE_SELINUX: result = R.string.checks_desc_5; break; case CH_TYPE_SU_EXISTS: result = R.string.checks_desc_6; break; case CH_TYPE_SUPER_USER_APK: result = R.string.checks_desc_7; break; case CH_TYPE_SU_BINARY: result = R.string.checks_desc_8; break; case CH_TYPE_BUSYBOX_BINARY: result = R.string.checks_desc_9; break; case CH_TYPE_XPOSED: result = R.string.checks_desc_10; break; case CH_TYPE_RESETPROP: result = R.string.checks_desc_11; break; case CH_TYPE_WRONG_PATH_PERMITION: result = R.string.checks_desc_12; break; case CH_TYPE_HOOKS: result = R.string.checks_desc_13; break; case CH_TYPE_UNKNOWN: default: result = R.string.empty; } return result; } }
ChecksHelper { @StringRes public static int getCheckStringId(@CheckingMethodType int typeCheck) { @StringRes int result = 0; switch (typeCheck) { case CH_TYPE_TEST_KEYS: result = R.string.checks_desc_1; break; case CH_TYPE_DEV_KEYS: result = R.string.checks_desc_2; break; case CH_TYPE_NON_RELEASE_KEYS: result = R.string.checks_desc_3; break; case CH_TYPE_DANGEROUS_PROPS: result = R.string.checks_desc_4; break; case CH_TYPE_PERMISSIVE_SELINUX: result = R.string.checks_desc_5; break; case CH_TYPE_SU_EXISTS: result = R.string.checks_desc_6; break; case CH_TYPE_SUPER_USER_APK: result = R.string.checks_desc_7; break; case CH_TYPE_SU_BINARY: result = R.string.checks_desc_8; break; case CH_TYPE_BUSYBOX_BINARY: result = R.string.checks_desc_9; break; case CH_TYPE_XPOSED: result = R.string.checks_desc_10; break; case CH_TYPE_RESETPROP: result = R.string.checks_desc_11; break; case CH_TYPE_WRONG_PATH_PERMITION: result = R.string.checks_desc_12; break; case CH_TYPE_HOOKS: result = R.string.checks_desc_13; break; case CH_TYPE_UNKNOWN: default: result = R.string.empty; } return result; } private ChecksHelper(); }
ChecksHelper { @StringRes public static int getCheckStringId(@CheckingMethodType int typeCheck) { @StringRes int result = 0; switch (typeCheck) { case CH_TYPE_TEST_KEYS: result = R.string.checks_desc_1; break; case CH_TYPE_DEV_KEYS: result = R.string.checks_desc_2; break; case CH_TYPE_NON_RELEASE_KEYS: result = R.string.checks_desc_3; break; case CH_TYPE_DANGEROUS_PROPS: result = R.string.checks_desc_4; break; case CH_TYPE_PERMISSIVE_SELINUX: result = R.string.checks_desc_5; break; case CH_TYPE_SU_EXISTS: result = R.string.checks_desc_6; break; case CH_TYPE_SUPER_USER_APK: result = R.string.checks_desc_7; break; case CH_TYPE_SU_BINARY: result = R.string.checks_desc_8; break; case CH_TYPE_BUSYBOX_BINARY: result = R.string.checks_desc_9; break; case CH_TYPE_XPOSED: result = R.string.checks_desc_10; break; case CH_TYPE_RESETPROP: result = R.string.checks_desc_11; break; case CH_TYPE_WRONG_PATH_PERMITION: result = R.string.checks_desc_12; break; case CH_TYPE_HOOKS: result = R.string.checks_desc_13; break; case CH_TYPE_UNKNOWN: default: result = R.string.empty; } return result; } private ChecksHelper(); @StringRes static int getCheckStringId(@CheckingMethodType int typeCheck); static Bitmap getNonCheck(@NonNull Context pContext); static Bitmap getFound(@NonNull Context pContext); static Bitmap getOk(@NonNull Context pContext); }
ChecksHelper { @StringRes public static int getCheckStringId(@CheckingMethodType int typeCheck) { @StringRes int result = 0; switch (typeCheck) { case CH_TYPE_TEST_KEYS: result = R.string.checks_desc_1; break; case CH_TYPE_DEV_KEYS: result = R.string.checks_desc_2; break; case CH_TYPE_NON_RELEASE_KEYS: result = R.string.checks_desc_3; break; case CH_TYPE_DANGEROUS_PROPS: result = R.string.checks_desc_4; break; case CH_TYPE_PERMISSIVE_SELINUX: result = R.string.checks_desc_5; break; case CH_TYPE_SU_EXISTS: result = R.string.checks_desc_6; break; case CH_TYPE_SUPER_USER_APK: result = R.string.checks_desc_7; break; case CH_TYPE_SU_BINARY: result = R.string.checks_desc_8; break; case CH_TYPE_BUSYBOX_BINARY: result = R.string.checks_desc_9; break; case CH_TYPE_XPOSED: result = R.string.checks_desc_10; break; case CH_TYPE_RESETPROP: result = R.string.checks_desc_11; break; case CH_TYPE_WRONG_PATH_PERMITION: result = R.string.checks_desc_12; break; case CH_TYPE_HOOKS: result = R.string.checks_desc_13; break; case CH_TYPE_UNKNOWN: default: result = R.string.empty; } return result; } private ChecksHelper(); @StringRes static int getCheckStringId(@CheckingMethodType int typeCheck); static Bitmap getNonCheck(@NonNull Context pContext); static Bitmap getFound(@NonNull Context pContext); static Bitmap getOk(@NonNull Context pContext); }
@Test public void getPath() { testPath = "/sample34"; GmsSecurityException e = new GmsSecurityException("somePath"); ReflectionTestUtils.setField(e, "path", testPath); assertEquals(testPath, e.getPath()); }
public String getPath() { return path; }
GmsSecurityException extends SecurityException { public String getPath() { return path; } }
GmsSecurityException extends SecurityException { public String getPath() { return path; } GmsSecurityException(final String path); GmsSecurityException(final String path, final String message); GmsSecurityException(final String path, final String message, final Throwable throwable); }
GmsSecurityException extends SecurityException { public String getPath() { return path; } GmsSecurityException(final String path); GmsSecurityException(final String path, final String message); GmsSecurityException(final String path, final String message, final Throwable throwable); String getPath(); }
GmsSecurityException extends SecurityException { public String getPath() { return path; } GmsSecurityException(final String path); GmsSecurityException(final String path, final String message); GmsSecurityException(final String path, final String message, final Throwable throwable); String getPath(); static final String DEFAULT_MESSAGE; }
@Test public void getBAuthorizationDAOThrowNullPointer() { daoProvider = new DAOProvider(queryService); ReflectionTestUtils.setField(daoProvider, URL, URL_VALUE_UNKNOWN); boolean threwException = false; try { Assert.assertNotNull(daoProvider.getBAuthorizationDAO()); } catch (NullPointerException e) { threwException = true; } if (!threwException) { Assert.fail(URL_VALUE_UNKNOWN_MESSAGE); } }
public BAuthorizationDAO getBAuthorizationDAO() { if (DatabaseDriver.fromJdbcUrl(url) == DatabaseDriver.POSTGRESQL) { return new PostgreSQLBAuthorizationDAO(queryService); } throw new NullPointerException(NOT_IMPLEMENTED_YET); }
DAOProvider { public BAuthorizationDAO getBAuthorizationDAO() { if (DatabaseDriver.fromJdbcUrl(url) == DatabaseDriver.POSTGRESQL) { return new PostgreSQLBAuthorizationDAO(queryService); } throw new NullPointerException(NOT_IMPLEMENTED_YET); } }
DAOProvider { public BAuthorizationDAO getBAuthorizationDAO() { if (DatabaseDriver.fromJdbcUrl(url) == DatabaseDriver.POSTGRESQL) { return new PostgreSQLBAuthorizationDAO(queryService); } throw new NullPointerException(NOT_IMPLEMENTED_YET); } @Autowired DAOProvider(final QueryService queryService); }
DAOProvider { public BAuthorizationDAO getBAuthorizationDAO() { if (DatabaseDriver.fromJdbcUrl(url) == DatabaseDriver.POSTGRESQL) { return new PostgreSQLBAuthorizationDAO(queryService); } throw new NullPointerException(NOT_IMPLEMENTED_YET); } @Autowired DAOProvider(final QueryService queryService); BAuthorizationDAO getBAuthorizationDAO(); BPermissionDAO getBPermissionDAO(); }
DAOProvider { public BAuthorizationDAO getBAuthorizationDAO() { if (DatabaseDriver.fromJdbcUrl(url) == DatabaseDriver.POSTGRESQL) { return new PostgreSQLBAuthorizationDAO(queryService); } throw new NullPointerException(NOT_IMPLEMENTED_YET); } @Autowired DAOProvider(final QueryService queryService); BAuthorizationDAO getBAuthorizationDAO(); BPermissionDAO getBPermissionDAO(); }
@Test public void getBPermissionDAOOKThrowNullPointer() { daoProvider = new DAOProvider(queryService); ReflectionTestUtils.setField(daoProvider, URL, URL_VALUE_UNKNOWN); boolean threwException = false; try { Assert.assertNotNull(daoProvider.getBPermissionDAO()); } catch (NullPointerException e) { threwException = true; } if (!threwException) { Assert.fail(URL_VALUE_UNKNOWN_MESSAGE); } }
public BPermissionDAO getBPermissionDAO() { if (DatabaseDriver.fromJdbcUrl(url) == DatabaseDriver.POSTGRESQL) { return new PostgreSQLBPermissionDAO(queryService); } throw new NullPointerException(NOT_IMPLEMENTED_YET); }
DAOProvider { public BPermissionDAO getBPermissionDAO() { if (DatabaseDriver.fromJdbcUrl(url) == DatabaseDriver.POSTGRESQL) { return new PostgreSQLBPermissionDAO(queryService); } throw new NullPointerException(NOT_IMPLEMENTED_YET); } }
DAOProvider { public BPermissionDAO getBPermissionDAO() { if (DatabaseDriver.fromJdbcUrl(url) == DatabaseDriver.POSTGRESQL) { return new PostgreSQLBPermissionDAO(queryService); } throw new NullPointerException(NOT_IMPLEMENTED_YET); } @Autowired DAOProvider(final QueryService queryService); }
DAOProvider { public BPermissionDAO getBPermissionDAO() { if (DatabaseDriver.fromJdbcUrl(url) == DatabaseDriver.POSTGRESQL) { return new PostgreSQLBPermissionDAO(queryService); } throw new NullPointerException(NOT_IMPLEMENTED_YET); } @Autowired DAOProvider(final QueryService queryService); BAuthorizationDAO getBAuthorizationDAO(); BPermissionDAO getBPermissionDAO(); }
DAOProvider { public BPermissionDAO getBPermissionDAO() { if (DatabaseDriver.fromJdbcUrl(url) == DatabaseDriver.POSTGRESQL) { return new PostgreSQLBPermissionDAO(queryService); } throw new NullPointerException(NOT_IMPLEMENTED_YET); } @Autowired DAOProvider(final QueryService queryService); BAuthorizationDAO getBAuthorizationDAO(); BPermissionDAO getBPermissionDAO(); }
@Test public void configurationExist() { assertTrue(configurationService.isApplicationConfigured() && configurationRepository.count() > 0); }
public boolean isApplicationConfigured() { return configurationRepository.count() > 0; }
ConfigurationService { public boolean isApplicationConfigured() { return configurationRepository.count() > 0; } }
ConfigurationService { public boolean isApplicationConfigured() { return configurationRepository.count() > 0; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); }
ConfigurationService { public boolean isApplicationConfigured() { return configurationRepository.count() > 0; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); }
ConfigurationService { public boolean isApplicationConfigured() { return configurationRepository.count() > 0; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }
@Test public void createDefaultConfig() { configurationRepository.deleteAll(); boolean ok = configurationService.isDefaultConfigurationCreated(); assertTrue("Create default config failed", ok); String msg = "Default configuration was not created"; BConfiguration c = configurationRepository.findFirstByKey(keyMultiEntityApp); assertNotNull(msg, c); c = configurationRepository.findFirstByKey(keyUserRegistrationAllowed); assertNotNull(msg, c); }
public boolean isDefaultConfigurationCreated() { BConfiguration isMultiEntity = new BConfiguration( ConfigKey.IS_MULTI_ENTITY_APP_IN_SERVER.toString(), String.valueOf(dc.getIsMultiEntity()) ); BConfiguration isUserRegistrationAllowed = new BConfiguration( String.valueOf(ConfigKey.IS_USER_REGISTRATION_ALLOWED_IN_SERVER), String.valueOf(dc.getIsUserRegistrationAllowed()) ); configurationRepository.save(isMultiEntity); configurationRepository.save(isUserRegistrationAllowed); multiEntity = Boolean.parseBoolean(isMultiEntity.getValue()); userRegistrationAllowed = Boolean.parseBoolean(isUserRegistrationAllowed.getValue()); return true; }
ConfigurationService { public boolean isDefaultConfigurationCreated() { BConfiguration isMultiEntity = new BConfiguration( ConfigKey.IS_MULTI_ENTITY_APP_IN_SERVER.toString(), String.valueOf(dc.getIsMultiEntity()) ); BConfiguration isUserRegistrationAllowed = new BConfiguration( String.valueOf(ConfigKey.IS_USER_REGISTRATION_ALLOWED_IN_SERVER), String.valueOf(dc.getIsUserRegistrationAllowed()) ); configurationRepository.save(isMultiEntity); configurationRepository.save(isUserRegistrationAllowed); multiEntity = Boolean.parseBoolean(isMultiEntity.getValue()); userRegistrationAllowed = Boolean.parseBoolean(isUserRegistrationAllowed.getValue()); return true; } }
ConfigurationService { public boolean isDefaultConfigurationCreated() { BConfiguration isMultiEntity = new BConfiguration( ConfigKey.IS_MULTI_ENTITY_APP_IN_SERVER.toString(), String.valueOf(dc.getIsMultiEntity()) ); BConfiguration isUserRegistrationAllowed = new BConfiguration( String.valueOf(ConfigKey.IS_USER_REGISTRATION_ALLOWED_IN_SERVER), String.valueOf(dc.getIsUserRegistrationAllowed()) ); configurationRepository.save(isMultiEntity); configurationRepository.save(isUserRegistrationAllowed); multiEntity = Boolean.parseBoolean(isMultiEntity.getValue()); userRegistrationAllowed = Boolean.parseBoolean(isUserRegistrationAllowed.getValue()); return true; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); }
ConfigurationService { public boolean isDefaultConfigurationCreated() { BConfiguration isMultiEntity = new BConfiguration( ConfigKey.IS_MULTI_ENTITY_APP_IN_SERVER.toString(), String.valueOf(dc.getIsMultiEntity()) ); BConfiguration isUserRegistrationAllowed = new BConfiguration( String.valueOf(ConfigKey.IS_USER_REGISTRATION_ALLOWED_IN_SERVER), String.valueOf(dc.getIsUserRegistrationAllowed()) ); configurationRepository.save(isMultiEntity); configurationRepository.save(isUserRegistrationAllowed); multiEntity = Boolean.parseBoolean(isMultiEntity.getValue()); userRegistrationAllowed = Boolean.parseBoolean(isUserRegistrationAllowed.getValue()); return true; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); }
ConfigurationService { public boolean isDefaultConfigurationCreated() { BConfiguration isMultiEntity = new BConfiguration( ConfigKey.IS_MULTI_ENTITY_APP_IN_SERVER.toString(), String.valueOf(dc.getIsMultiEntity()) ); BConfiguration isUserRegistrationAllowed = new BConfiguration( String.valueOf(ConfigKey.IS_USER_REGISTRATION_ALLOWED_IN_SERVER), String.valueOf(dc.getIsUserRegistrationAllowed()) ); configurationRepository.save(isMultiEntity); configurationRepository.save(isUserRegistrationAllowed); multiEntity = Boolean.parseBoolean(isMultiEntity.getValue()); userRegistrationAllowed = Boolean.parseBoolean(isUserRegistrationAllowed.getValue()); return true; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }
@Test public void assignDefaultUserToEntityWithRole() { final String msg = "Assign default user to entity with role failed"; final boolean ok = configurationService.isDefaultUserAssignedToEntityWithRole(); assertTrue(msg, ok); final EUser u = userRepository.findFirstByUsername(dc.getUserAdminDefaultUsername()); final EOwnedEntity e = entityRepository.findFirstByUsername(dc.getEntityDefaultUsername()); assertNotNull(u); assertNotNull(e); final List<BRole> roles = authRepository.getRolesForUserOverEntity(u.getId(), e.getId()); assertTrue(msg, roles != null && !roles.isEmpty()); }
public boolean isDefaultUserAssignedToEntityWithRole() { EUser u = userRepository.findFirstByUsernameOrEmail(dc.getUserAdminDefaultName(), dc.getUserAdminDefaultEmail()); if (u != null) { EOwnedEntity e = entityRepository.findFirstByUsername(dc.getEntityDefaultUsername()); if (e != null) { BRole role = roleRepository.findFirstByLabel(dc.getRoleAdminDefaultLabel()); if (role != null) { com.gms.domain.security.BAuthorization.BAuthorizationPk pk = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), role.getId()); authRepository.save(new BAuthorization(pk, u, e, role)); return true; } } } return false; }
ConfigurationService { public boolean isDefaultUserAssignedToEntityWithRole() { EUser u = userRepository.findFirstByUsernameOrEmail(dc.getUserAdminDefaultName(), dc.getUserAdminDefaultEmail()); if (u != null) { EOwnedEntity e = entityRepository.findFirstByUsername(dc.getEntityDefaultUsername()); if (e != null) { BRole role = roleRepository.findFirstByLabel(dc.getRoleAdminDefaultLabel()); if (role != null) { com.gms.domain.security.BAuthorization.BAuthorizationPk pk = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), role.getId()); authRepository.save(new BAuthorization(pk, u, e, role)); return true; } } } return false; } }
ConfigurationService { public boolean isDefaultUserAssignedToEntityWithRole() { EUser u = userRepository.findFirstByUsernameOrEmail(dc.getUserAdminDefaultName(), dc.getUserAdminDefaultEmail()); if (u != null) { EOwnedEntity e = entityRepository.findFirstByUsername(dc.getEntityDefaultUsername()); if (e != null) { BRole role = roleRepository.findFirstByLabel(dc.getRoleAdminDefaultLabel()); if (role != null) { com.gms.domain.security.BAuthorization.BAuthorizationPk pk = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), role.getId()); authRepository.save(new BAuthorization(pk, u, e, role)); return true; } } } return false; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); }
ConfigurationService { public boolean isDefaultUserAssignedToEntityWithRole() { EUser u = userRepository.findFirstByUsernameOrEmail(dc.getUserAdminDefaultName(), dc.getUserAdminDefaultEmail()); if (u != null) { EOwnedEntity e = entityRepository.findFirstByUsername(dc.getEntityDefaultUsername()); if (e != null) { BRole role = roleRepository.findFirstByLabel(dc.getRoleAdminDefaultLabel()); if (role != null) { com.gms.domain.security.BAuthorization.BAuthorizationPk pk = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), role.getId()); authRepository.save(new BAuthorization(pk, u, e, role)); return true; } } } return false; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); }
ConfigurationService { public boolean isDefaultUserAssignedToEntityWithRole() { EUser u = userRepository.findFirstByUsernameOrEmail(dc.getUserAdminDefaultName(), dc.getUserAdminDefaultEmail()); if (u != null) { EOwnedEntity e = entityRepository.findFirstByUsername(dc.getEntityDefaultUsername()); if (e != null) { BRole role = roleRepository.findFirstByLabel(dc.getRoleAdminDefaultLabel()); if (role != null) { com.gms.domain.security.BAuthorization.BAuthorizationPk pk = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), role.getId()); authRepository.save(new BAuthorization(pk, u, e, role)); return true; } } } return false; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }
@Test public void getConfig() { String key; String value; List<String> keys = new LinkedList<>(); List<String> values = new LinkedList<>(); final int top = 10; for (int i = 0; i < top; i++) { key = random.nextString() + "_IN_SERVER"; value = random.nextString(); keys.add(key); values.add(value); assertNotNull(configurationRepository.save(new BConfiguration(key, value))); } Map<String, String> configs = configurationService.getConfig(); Object config; for (int i = 0; i < keys.size(); i++) { config = configs.get(keys.get(i)); assertNotNull("Configuration found if null", config); value = values.get(i); assertEquals("Configuration value returned by server (" + config + ") does not match the expected", config, value); } }
public Map<String, String> getConfig() { List<BConfiguration> configs = configurationRepository.findAllByKeyEndingWith(IN_SERVER); Map<String, String> map = new HashMap<>(); for (BConfiguration c : configs) { map.put(c.getKey(), c.getValue()); } return map; }
ConfigurationService { public Map<String, String> getConfig() { List<BConfiguration> configs = configurationRepository.findAllByKeyEndingWith(IN_SERVER); Map<String, String> map = new HashMap<>(); for (BConfiguration c : configs) { map.put(c.getKey(), c.getValue()); } return map; } }
ConfigurationService { public Map<String, String> getConfig() { List<BConfiguration> configs = configurationRepository.findAllByKeyEndingWith(IN_SERVER); Map<String, String> map = new HashMap<>(); for (BConfiguration c : configs) { map.put(c.getKey(), c.getValue()); } return map; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); }
ConfigurationService { public Map<String, String> getConfig() { List<BConfiguration> configs = configurationRepository.findAllByKeyEndingWith(IN_SERVER); Map<String, String> map = new HashMap<>(); for (BConfiguration c : configs) { map.put(c.getKey(), c.getValue()); } return map; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); }
ConfigurationService { public Map<String, String> getConfig() { List<BConfiguration> configs = configurationRepository.findAllByKeyEndingWith(IN_SERVER); Map<String, String> map = new HashMap<>(); for (BConfiguration c : configs) { map.put(c.getKey(), c.getValue()); } return map; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }
@Test public void getConfigByUser() { EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(u); EOwnedEntity e = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(e); BConfiguration c = configurationRepository.save(new BConfiguration(keyLang, "es", u.getId())); assertNotNull(c); BConfiguration c2 = configurationRepository.save( new BConfiguration(keyLastAccessedEntity, String.valueOf(e.getId()), u.getId()) ); assertNotNull(c2); Map<String, Object> configs = configurationService.getConfigByUser(u.getId()); assertNotNull(configs.get(keyLang)); assertNotNull(configs.get(keyLastAccessedEntity)); assertEquals("Configuration values (language) do not match", "es", configs.get(keyLang)); assertEquals("Configuration values (last accessed entity) do not match", configs.get(keyLastAccessedEntity), String.valueOf(e.getId())); }
public Map<String, Object> getConfigByUser(final long userId) { final List<BConfiguration> configs = configurationRepository.findAllByUserId(userId); Map<String, Object> map = new HashMap<>(); for (BConfiguration c : configs) { map.put(c.getKey(), c.getValue()); } return map; }
ConfigurationService { public Map<String, Object> getConfigByUser(final long userId) { final List<BConfiguration> configs = configurationRepository.findAllByUserId(userId); Map<String, Object> map = new HashMap<>(); for (BConfiguration c : configs) { map.put(c.getKey(), c.getValue()); } return map; } }
ConfigurationService { public Map<String, Object> getConfigByUser(final long userId) { final List<BConfiguration> configs = configurationRepository.findAllByUserId(userId); Map<String, Object> map = new HashMap<>(); for (BConfiguration c : configs) { map.put(c.getKey(), c.getValue()); } return map; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); }
ConfigurationService { public Map<String, Object> getConfigByUser(final long userId) { final List<BConfiguration> configs = configurationRepository.findAllByUserId(userId); Map<String, Object> map = new HashMap<>(); for (BConfiguration c : configs) { map.put(c.getKey(), c.getValue()); } return map; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); }
ConfigurationService { public Map<String, Object> getConfigByUser(final long userId) { final List<BConfiguration> configs = configurationRepository.findAllByUserId(userId); Map<String, Object> map = new HashMap<>(); for (BConfiguration c : configs) { map.put(c.getKey(), c.getValue()); } return map; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }
@Test public void saveConfig() { List<Iterable<BConfiguration>> list = deleteAllServerConfig(); Map<String, Object> configs = new HashMap<>(); configs.put(keyUserRegistrationAllowed, false); configs.put(keyMultiEntityApp, true); try { configurationService.saveConfig(configs); BConfiguration cR = configurationRepository.findFirstByKey(keyUserRegistrationAllowed); assertNotNull(cR); assertEquals(Boolean.toString(false), cR.getValue()); cR = configurationRepository.findFirstByKey(keyMultiEntityApp); assertNotNull(cR); assertEquals(Boolean.toString(true), cR.getValue()); } catch (NotFoundEntityException e) { LOGGER.error(e.getLocalizedMessage()); fail("At least one of the keys was not found."); } catch (GmsGeneralException e) { LOGGER.error(e.getLocalizedMessage()); fail("The provided user key was not valid"); } assertTrue(hasRestoredAllServerConfig(list)); }
public void saveConfig(final Map<String, Object> configs) throws NotFoundEntityException, GmsGeneralException { if (configs.get("user") != null) { try { long id = Long.parseLong(configs.remove("user").toString()); saveConfig(configs, id); } catch (NumberFormatException e) { throw GmsGeneralException.builder() .messageI18N(CONFIG_USER_PARAM_NUMBER) .cause(e) .finishedOK(false) .httpStatus(HttpStatus.UNPROCESSABLE_ENTITY) .build(); } } String uppercaseKey; for (Map.Entry<String, Object> entry : configs.entrySet()) { uppercaseKey = entry.getKey().toUpperCase(Locale.ENGLISH); if (isValidKey(uppercaseKey) && uppercaseKey.endsWith(IN_SERVER)) { switch (ConfigKey.valueOf(uppercaseKey)) { case IS_MULTI_ENTITY_APP_IN_SERVER: setIsMultiEntity(Boolean.parseBoolean(entry.getValue().toString())); break; case IS_USER_REGISTRATION_ALLOWED_IN_SERVER: setUserRegistrationAllowed(Boolean.parseBoolean(entry.getValue().toString())); break; default: throw new NotFoundEntityException(CONFIG_NOT_FOUND); } } } }
ConfigurationService { public void saveConfig(final Map<String, Object> configs) throws NotFoundEntityException, GmsGeneralException { if (configs.get("user") != null) { try { long id = Long.parseLong(configs.remove("user").toString()); saveConfig(configs, id); } catch (NumberFormatException e) { throw GmsGeneralException.builder() .messageI18N(CONFIG_USER_PARAM_NUMBER) .cause(e) .finishedOK(false) .httpStatus(HttpStatus.UNPROCESSABLE_ENTITY) .build(); } } String uppercaseKey; for (Map.Entry<String, Object> entry : configs.entrySet()) { uppercaseKey = entry.getKey().toUpperCase(Locale.ENGLISH); if (isValidKey(uppercaseKey) && uppercaseKey.endsWith(IN_SERVER)) { switch (ConfigKey.valueOf(uppercaseKey)) { case IS_MULTI_ENTITY_APP_IN_SERVER: setIsMultiEntity(Boolean.parseBoolean(entry.getValue().toString())); break; case IS_USER_REGISTRATION_ALLOWED_IN_SERVER: setUserRegistrationAllowed(Boolean.parseBoolean(entry.getValue().toString())); break; default: throw new NotFoundEntityException(CONFIG_NOT_FOUND); } } } } }
ConfigurationService { public void saveConfig(final Map<String, Object> configs) throws NotFoundEntityException, GmsGeneralException { if (configs.get("user") != null) { try { long id = Long.parseLong(configs.remove("user").toString()); saveConfig(configs, id); } catch (NumberFormatException e) { throw GmsGeneralException.builder() .messageI18N(CONFIG_USER_PARAM_NUMBER) .cause(e) .finishedOK(false) .httpStatus(HttpStatus.UNPROCESSABLE_ENTITY) .build(); } } String uppercaseKey; for (Map.Entry<String, Object> entry : configs.entrySet()) { uppercaseKey = entry.getKey().toUpperCase(Locale.ENGLISH); if (isValidKey(uppercaseKey) && uppercaseKey.endsWith(IN_SERVER)) { switch (ConfigKey.valueOf(uppercaseKey)) { case IS_MULTI_ENTITY_APP_IN_SERVER: setIsMultiEntity(Boolean.parseBoolean(entry.getValue().toString())); break; case IS_USER_REGISTRATION_ALLOWED_IN_SERVER: setUserRegistrationAllowed(Boolean.parseBoolean(entry.getValue().toString())); break; default: throw new NotFoundEntityException(CONFIG_NOT_FOUND); } } } } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); }
ConfigurationService { public void saveConfig(final Map<String, Object> configs) throws NotFoundEntityException, GmsGeneralException { if (configs.get("user") != null) { try { long id = Long.parseLong(configs.remove("user").toString()); saveConfig(configs, id); } catch (NumberFormatException e) { throw GmsGeneralException.builder() .messageI18N(CONFIG_USER_PARAM_NUMBER) .cause(e) .finishedOK(false) .httpStatus(HttpStatus.UNPROCESSABLE_ENTITY) .build(); } } String uppercaseKey; for (Map.Entry<String, Object> entry : configs.entrySet()) { uppercaseKey = entry.getKey().toUpperCase(Locale.ENGLISH); if (isValidKey(uppercaseKey) && uppercaseKey.endsWith(IN_SERVER)) { switch (ConfigKey.valueOf(uppercaseKey)) { case IS_MULTI_ENTITY_APP_IN_SERVER: setIsMultiEntity(Boolean.parseBoolean(entry.getValue().toString())); break; case IS_USER_REGISTRATION_ALLOWED_IN_SERVER: setUserRegistrationAllowed(Boolean.parseBoolean(entry.getValue().toString())); break; default: throw new NotFoundEntityException(CONFIG_NOT_FOUND); } } } } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); }
ConfigurationService { public void saveConfig(final Map<String, Object> configs) throws NotFoundEntityException, GmsGeneralException { if (configs.get("user") != null) { try { long id = Long.parseLong(configs.remove("user").toString()); saveConfig(configs, id); } catch (NumberFormatException e) { throw GmsGeneralException.builder() .messageI18N(CONFIG_USER_PARAM_NUMBER) .cause(e) .finishedOK(false) .httpStatus(HttpStatus.UNPROCESSABLE_ENTITY) .build(); } } String uppercaseKey; for (Map.Entry<String, Object> entry : configs.entrySet()) { uppercaseKey = entry.getKey().toUpperCase(Locale.ENGLISH); if (isValidKey(uppercaseKey) && uppercaseKey.endsWith(IN_SERVER)) { switch (ConfigKey.valueOf(uppercaseKey)) { case IS_MULTI_ENTITY_APP_IN_SERVER: setIsMultiEntity(Boolean.parseBoolean(entry.getValue().toString())); break; case IS_USER_REGISTRATION_ALLOWED_IN_SERVER: setUserRegistrationAllowed(Boolean.parseBoolean(entry.getValue().toString())); break; default: throw new NotFoundEntityException(CONFIG_NOT_FOUND); } } } } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }
@Test public void saveConfigForUser() { EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); EOwnedEntity e = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(u); Map<String, Object> configs = new HashMap<>(); configs.put(keyLang, "fr"); configs.put(keyLastAccessedEntity, e.getId()); try { configurationService.saveConfig(configs, u.getId()); } catch (NotFoundEntityException e1) { LOGGER.error(e1.getLocalizedMessage()); fail("At least one of the keys was not found."); } }
public void saveConfig(final Map<String, Object> configs) throws NotFoundEntityException, GmsGeneralException { if (configs.get("user") != null) { try { long id = Long.parseLong(configs.remove("user").toString()); saveConfig(configs, id); } catch (NumberFormatException e) { throw GmsGeneralException.builder() .messageI18N(CONFIG_USER_PARAM_NUMBER) .cause(e) .finishedOK(false) .httpStatus(HttpStatus.UNPROCESSABLE_ENTITY) .build(); } } String uppercaseKey; for (Map.Entry<String, Object> entry : configs.entrySet()) { uppercaseKey = entry.getKey().toUpperCase(Locale.ENGLISH); if (isValidKey(uppercaseKey) && uppercaseKey.endsWith(IN_SERVER)) { switch (ConfigKey.valueOf(uppercaseKey)) { case IS_MULTI_ENTITY_APP_IN_SERVER: setIsMultiEntity(Boolean.parseBoolean(entry.getValue().toString())); break; case IS_USER_REGISTRATION_ALLOWED_IN_SERVER: setUserRegistrationAllowed(Boolean.parseBoolean(entry.getValue().toString())); break; default: throw new NotFoundEntityException(CONFIG_NOT_FOUND); } } } }
ConfigurationService { public void saveConfig(final Map<String, Object> configs) throws NotFoundEntityException, GmsGeneralException { if (configs.get("user") != null) { try { long id = Long.parseLong(configs.remove("user").toString()); saveConfig(configs, id); } catch (NumberFormatException e) { throw GmsGeneralException.builder() .messageI18N(CONFIG_USER_PARAM_NUMBER) .cause(e) .finishedOK(false) .httpStatus(HttpStatus.UNPROCESSABLE_ENTITY) .build(); } } String uppercaseKey; for (Map.Entry<String, Object> entry : configs.entrySet()) { uppercaseKey = entry.getKey().toUpperCase(Locale.ENGLISH); if (isValidKey(uppercaseKey) && uppercaseKey.endsWith(IN_SERVER)) { switch (ConfigKey.valueOf(uppercaseKey)) { case IS_MULTI_ENTITY_APP_IN_SERVER: setIsMultiEntity(Boolean.parseBoolean(entry.getValue().toString())); break; case IS_USER_REGISTRATION_ALLOWED_IN_SERVER: setUserRegistrationAllowed(Boolean.parseBoolean(entry.getValue().toString())); break; default: throw new NotFoundEntityException(CONFIG_NOT_FOUND); } } } } }
ConfigurationService { public void saveConfig(final Map<String, Object> configs) throws NotFoundEntityException, GmsGeneralException { if (configs.get("user") != null) { try { long id = Long.parseLong(configs.remove("user").toString()); saveConfig(configs, id); } catch (NumberFormatException e) { throw GmsGeneralException.builder() .messageI18N(CONFIG_USER_PARAM_NUMBER) .cause(e) .finishedOK(false) .httpStatus(HttpStatus.UNPROCESSABLE_ENTITY) .build(); } } String uppercaseKey; for (Map.Entry<String, Object> entry : configs.entrySet()) { uppercaseKey = entry.getKey().toUpperCase(Locale.ENGLISH); if (isValidKey(uppercaseKey) && uppercaseKey.endsWith(IN_SERVER)) { switch (ConfigKey.valueOf(uppercaseKey)) { case IS_MULTI_ENTITY_APP_IN_SERVER: setIsMultiEntity(Boolean.parseBoolean(entry.getValue().toString())); break; case IS_USER_REGISTRATION_ALLOWED_IN_SERVER: setUserRegistrationAllowed(Boolean.parseBoolean(entry.getValue().toString())); break; default: throw new NotFoundEntityException(CONFIG_NOT_FOUND); } } } } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); }
ConfigurationService { public void saveConfig(final Map<String, Object> configs) throws NotFoundEntityException, GmsGeneralException { if (configs.get("user") != null) { try { long id = Long.parseLong(configs.remove("user").toString()); saveConfig(configs, id); } catch (NumberFormatException e) { throw GmsGeneralException.builder() .messageI18N(CONFIG_USER_PARAM_NUMBER) .cause(e) .finishedOK(false) .httpStatus(HttpStatus.UNPROCESSABLE_ENTITY) .build(); } } String uppercaseKey; for (Map.Entry<String, Object> entry : configs.entrySet()) { uppercaseKey = entry.getKey().toUpperCase(Locale.ENGLISH); if (isValidKey(uppercaseKey) && uppercaseKey.endsWith(IN_SERVER)) { switch (ConfigKey.valueOf(uppercaseKey)) { case IS_MULTI_ENTITY_APP_IN_SERVER: setIsMultiEntity(Boolean.parseBoolean(entry.getValue().toString())); break; case IS_USER_REGISTRATION_ALLOWED_IN_SERVER: setUserRegistrationAllowed(Boolean.parseBoolean(entry.getValue().toString())); break; default: throw new NotFoundEntityException(CONFIG_NOT_FOUND); } } } } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); }
ConfigurationService { public void saveConfig(final Map<String, Object> configs) throws NotFoundEntityException, GmsGeneralException { if (configs.get("user") != null) { try { long id = Long.parseLong(configs.remove("user").toString()); saveConfig(configs, id); } catch (NumberFormatException e) { throw GmsGeneralException.builder() .messageI18N(CONFIG_USER_PARAM_NUMBER) .cause(e) .finishedOK(false) .httpStatus(HttpStatus.UNPROCESSABLE_ENTITY) .build(); } } String uppercaseKey; for (Map.Entry<String, Object> entry : configs.entrySet()) { uppercaseKey = entry.getKey().toUpperCase(Locale.ENGLISH); if (isValidKey(uppercaseKey) && uppercaseKey.endsWith(IN_SERVER)) { switch (ConfigKey.valueOf(uppercaseKey)) { case IS_MULTI_ENTITY_APP_IN_SERVER: setIsMultiEntity(Boolean.parseBoolean(entry.getValue().toString())); break; case IS_USER_REGISTRATION_ALLOWED_IN_SERVER: setUserRegistrationAllowed(Boolean.parseBoolean(entry.getValue().toString())); break; default: throw new NotFoundEntityException(CONFIG_NOT_FOUND); } } } } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }
@Test public void setUserRegistrationAllowed() { final List<Iterable<BConfiguration>> list = deleteAllServerConfig(); configurationService.setUserRegistrationAllowed(true); BConfiguration c = configurationRepository.findFirstByKey(keyUserRegistrationAllowed); assertNotNull(c); assertEquals(Boolean.toString(true), c.getValue()); final Object allowed = ReflectionTestUtils.getField(configurationService, "userRegistrationAllowed"); assertNotNull(allowed); assertEquals(Boolean.toString(true), allowed.toString()); hasRestoredAllServerConfig(list); }
public void setUserRegistrationAllowed(final boolean userRegistrationAllowed) { insertOrUpdateValue(ConfigKey.IS_USER_REGISTRATION_ALLOWED_IN_SERVER, userRegistrationAllowed); this.userRegistrationAllowed = userRegistrationAllowed; }
ConfigurationService { public void setUserRegistrationAllowed(final boolean userRegistrationAllowed) { insertOrUpdateValue(ConfigKey.IS_USER_REGISTRATION_ALLOWED_IN_SERVER, userRegistrationAllowed); this.userRegistrationAllowed = userRegistrationAllowed; } }
ConfigurationService { public void setUserRegistrationAllowed(final boolean userRegistrationAllowed) { insertOrUpdateValue(ConfigKey.IS_USER_REGISTRATION_ALLOWED_IN_SERVER, userRegistrationAllowed); this.userRegistrationAllowed = userRegistrationAllowed; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); }
ConfigurationService { public void setUserRegistrationAllowed(final boolean userRegistrationAllowed) { insertOrUpdateValue(ConfigKey.IS_USER_REGISTRATION_ALLOWED_IN_SERVER, userRegistrationAllowed); this.userRegistrationAllowed = userRegistrationAllowed; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); }
ConfigurationService { public void setUserRegistrationAllowed(final boolean userRegistrationAllowed) { insertOrUpdateValue(ConfigKey.IS_USER_REGISTRATION_ALLOWED_IN_SERVER, userRegistrationAllowed); this.userRegistrationAllowed = userRegistrationAllowed; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }
@SuppressWarnings("unchecked") @Test public void setErrors() { Map<String, List<String>> errors = new HashMap<>(); List<String> l = new LinkedList<>(); List<String> l2 = new LinkedList<>(); l.add("a"); l.add("b"); l2.add("c"); l2.add("d"); errors.put("k1", l); errors.put("k2", l2); GmsError e = new GmsError(); e.addError(MSG); e.addError(FIELD, MSG_2); Map<String, List<String>> currentErrors = (Map<String, List<String>>) ReflectionTestUtils.getField(e, ERRORS_HOLDER); assertNotNull(currentErrors); assertTrue(currentErrors.get(GmsError.OTHERS).contains(MSG)); assertTrue(currentErrors.get(FIELD).contains(MSG_2)); e.setErrors(errors); currentErrors = (Map<String, List<String>>) ReflectionTestUtils.getField(e, ERRORS_HOLDER); if (currentErrors == null) { currentErrors = new HashMap<>(); } assertEquals(currentErrors.get("k1"), l); assertEquals(currentErrors.get("k2"), l2); }
public void addError(final String field, final String message) { if (errors.get(field) == null) { LinkedList<String> l = new LinkedList<>(); l.add(message); errors.put(field, l); } else { errors.get(field).add(message); } }
GmsError { public void addError(final String field, final String message) { if (errors.get(field) == null) { LinkedList<String> l = new LinkedList<>(); l.add(message); errors.put(field, l); } else { errors.get(field).add(message); } } }
GmsError { public void addError(final String field, final String message) { if (errors.get(field) == null) { LinkedList<String> l = new LinkedList<>(); l.add(message); errors.put(field, l); } else { errors.get(field).add(message); } } GmsError(); }
GmsError { public void addError(final String field, final String message) { if (errors.get(field) == null) { LinkedList<String> l = new LinkedList<>(); l.add(message); errors.put(field, l); } else { errors.get(field).add(message); } } GmsError(); void addError(final String field, final String message); void addError(final String message); void removeErrors(final String field); void removeError(final String error); void removeError(final String field, final String message); }
GmsError { public void addError(final String field, final String message) { if (errors.get(field) == null) { LinkedList<String> l = new LinkedList<>(); l.add(message); errors.put(field, l); } else { errors.get(field).add(message); } } GmsError(); void addError(final String field, final String message); void addError(final String message); void removeErrors(final String field); void removeError(final String error); void removeError(final String field, final String message); static final String OTHERS; }
@Test public void setIsMultiEntity() { final List<Iterable<BConfiguration>> list = deleteAllServerConfig(); configurationService.setIsMultiEntity(true); BConfiguration c = configurationRepository.findFirstByKey(keyMultiEntityApp); assertNotNull(c); assertEquals(Boolean.toString(true), c.getValue()); final Object multiEntity = ReflectionTestUtils.getField(configurationService, "multiEntity"); assertNotNull(multiEntity); assertEquals(Boolean.toString(true), multiEntity.toString()); hasRestoredAllServerConfig(list); }
public void setIsMultiEntity(final boolean isMultiEntity) { insertOrUpdateValue(ConfigKey.IS_MULTI_ENTITY_APP_IN_SERVER, isMultiEntity); this.multiEntity = isMultiEntity; }
ConfigurationService { public void setIsMultiEntity(final boolean isMultiEntity) { insertOrUpdateValue(ConfigKey.IS_MULTI_ENTITY_APP_IN_SERVER, isMultiEntity); this.multiEntity = isMultiEntity; } }
ConfigurationService { public void setIsMultiEntity(final boolean isMultiEntity) { insertOrUpdateValue(ConfigKey.IS_MULTI_ENTITY_APP_IN_SERVER, isMultiEntity); this.multiEntity = isMultiEntity; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); }
ConfigurationService { public void setIsMultiEntity(final boolean isMultiEntity) { insertOrUpdateValue(ConfigKey.IS_MULTI_ENTITY_APP_IN_SERVER, isMultiEntity); this.multiEntity = isMultiEntity; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); }
ConfigurationService { public void setIsMultiEntity(final boolean isMultiEntity) { insertOrUpdateValue(ConfigKey.IS_MULTI_ENTITY_APP_IN_SERVER, isMultiEntity); this.multiEntity = isMultiEntity; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }
@Test public void getLastAccessedEntityIdByUser() { EUser user = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(user); EOwnedEntity entity = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(entity); BConfiguration c = configurationRepository.save(new BConfiguration( keyLastAccessedEntity, String.valueOf(entity.getId()), user.getId() )); assertNotNull(c); assertEquals(Long.valueOf(c.getValue()), configurationService.getLastAccessedEntityIdByUser(user.getId())); }
public Long getLastAccessedEntityIdByUser(final long userId) { String v = getValueByUser(ConfigKey.LAST_ACCESSED_ENTITY.toString(), userId); return v != null ? Long.parseLong(v) : null; }
ConfigurationService { public Long getLastAccessedEntityIdByUser(final long userId) { String v = getValueByUser(ConfigKey.LAST_ACCESSED_ENTITY.toString(), userId); return v != null ? Long.parseLong(v) : null; } }
ConfigurationService { public Long getLastAccessedEntityIdByUser(final long userId) { String v = getValueByUser(ConfigKey.LAST_ACCESSED_ENTITY.toString(), userId); return v != null ? Long.parseLong(v) : null; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); }
ConfigurationService { public Long getLastAccessedEntityIdByUser(final long userId) { String v = getValueByUser(ConfigKey.LAST_ACCESSED_ENTITY.toString(), userId); return v != null ? Long.parseLong(v) : null; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); }
ConfigurationService { public Long getLastAccessedEntityIdByUser(final long userId) { String v = getValueByUser(ConfigKey.LAST_ACCESSED_ENTITY.toString(), userId); return v != null ? Long.parseLong(v) : null; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }
@Test public void setLastAccessedEntityIdByUser() { EUser user = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(user); EOwnedEntity entity = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(entity); configurationService.setLastAccessedEntityIdByUser(user.getId(), entity.getId()); BConfiguration c = configurationRepository.findFirstByKeyAndUserId(keyLastAccessedEntity, user.getId()); assertNotNull(c); assertEquals(Long.valueOf(c.getValue()), entity.getId()); }
public void setLastAccessedEntityIdByUser(final long userId, final long entityId) { insertOrUpdateValue(ConfigKey.LAST_ACCESSED_ENTITY, entityId, userId); }
ConfigurationService { public void setLastAccessedEntityIdByUser(final long userId, final long entityId) { insertOrUpdateValue(ConfigKey.LAST_ACCESSED_ENTITY, entityId, userId); } }
ConfigurationService { public void setLastAccessedEntityIdByUser(final long userId, final long entityId) { insertOrUpdateValue(ConfigKey.LAST_ACCESSED_ENTITY, entityId, userId); } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); }
ConfigurationService { public void setLastAccessedEntityIdByUser(final long userId, final long entityId) { insertOrUpdateValue(ConfigKey.LAST_ACCESSED_ENTITY, entityId, userId); } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); }
ConfigurationService { public void setLastAccessedEntityIdByUser(final long userId, final long entityId) { insertOrUpdateValue(ConfigKey.LAST_ACCESSED_ENTITY, entityId, userId); } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }
@Test public void getConfigInServerNotFound() { boolean success = false; try { configurationService.getConfig(random.nextString() + ConfigurationService.IN_SERVER); } catch (NotFoundEntityException e) { assertEquals(ConfigurationService.CONFIG_NOT_FOUND, e.getMessage()); success = true; } assertTrue(success); }
public Map<String, String> getConfig() { List<BConfiguration> configs = configurationRepository.findAllByKeyEndingWith(IN_SERVER); Map<String, String> map = new HashMap<>(); for (BConfiguration c : configs) { map.put(c.getKey(), c.getValue()); } return map; }
ConfigurationService { public Map<String, String> getConfig() { List<BConfiguration> configs = configurationRepository.findAllByKeyEndingWith(IN_SERVER); Map<String, String> map = new HashMap<>(); for (BConfiguration c : configs) { map.put(c.getKey(), c.getValue()); } return map; } }
ConfigurationService { public Map<String, String> getConfig() { List<BConfiguration> configs = configurationRepository.findAllByKeyEndingWith(IN_SERVER); Map<String, String> map = new HashMap<>(); for (BConfiguration c : configs) { map.put(c.getKey(), c.getValue()); } return map; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); }
ConfigurationService { public Map<String, String> getConfig() { List<BConfiguration> configs = configurationRepository.findAllByKeyEndingWith(IN_SERVER); Map<String, String> map = new HashMap<>(); for (BConfiguration c : configs) { map.put(c.getKey(), c.getValue()); } return map; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); }
ConfigurationService { public Map<String, String> getConfig() { List<BConfiguration> configs = configurationRepository.findAllByKeyEndingWith(IN_SERVER); Map<String, String> map = new HashMap<>(); for (BConfiguration c : configs) { map.put(c.getKey(), c.getValue()); } return map; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }
@Test public void getConfigNotFound() { boolean success = false; try { configurationService.getConfig(random.nextString().replace(ConfigurationService.IN_SERVER, "")); } catch (NotFoundEntityException e) { assertEquals(ConfigurationService.CONFIG_NOT_FOUND, e.getMessage()); success = true; } assertTrue(success); }
public Map<String, String> getConfig() { List<BConfiguration> configs = configurationRepository.findAllByKeyEndingWith(IN_SERVER); Map<String, String> map = new HashMap<>(); for (BConfiguration c : configs) { map.put(c.getKey(), c.getValue()); } return map; }
ConfigurationService { public Map<String, String> getConfig() { List<BConfiguration> configs = configurationRepository.findAllByKeyEndingWith(IN_SERVER); Map<String, String> map = new HashMap<>(); for (BConfiguration c : configs) { map.put(c.getKey(), c.getValue()); } return map; } }
ConfigurationService { public Map<String, String> getConfig() { List<BConfiguration> configs = configurationRepository.findAllByKeyEndingWith(IN_SERVER); Map<String, String> map = new HashMap<>(); for (BConfiguration c : configs) { map.put(c.getKey(), c.getValue()); } return map; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); }
ConfigurationService { public Map<String, String> getConfig() { List<BConfiguration> configs = configurationRepository.findAllByKeyEndingWith(IN_SERVER); Map<String, String> map = new HashMap<>(); for (BConfiguration c : configs) { map.put(c.getKey(), c.getValue()); } return map; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); }
ConfigurationService { public Map<String, String> getConfig() { List<BConfiguration> configs = configurationRepository.findAllByKeyEndingWith(IN_SERVER); Map<String, String> map = new HashMap<>(); for (BConfiguration c : configs) { map.put(c.getKey(), c.getValue()); } return map; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }
@Test public void saveConfigKeyNotFound() { Map<String, Object> configs = new HashMap<>(); configs.put(random.nextString(), random.nextString()); boolean success = false; try { configurationService.saveConfig(configs); } catch (GmsGeneralException e) { LOGGER.error(e.getLocalizedMessage()); fail("There was not provided user and the test still failed because of it"); } catch (Exception e) { success = true; } assertTrue(success); }
public void saveConfig(final Map<String, Object> configs) throws NotFoundEntityException, GmsGeneralException { if (configs.get("user") != null) { try { long id = Long.parseLong(configs.remove("user").toString()); saveConfig(configs, id); } catch (NumberFormatException e) { throw GmsGeneralException.builder() .messageI18N(CONFIG_USER_PARAM_NUMBER) .cause(e) .finishedOK(false) .httpStatus(HttpStatus.UNPROCESSABLE_ENTITY) .build(); } } String uppercaseKey; for (Map.Entry<String, Object> entry : configs.entrySet()) { uppercaseKey = entry.getKey().toUpperCase(Locale.ENGLISH); if (isValidKey(uppercaseKey) && uppercaseKey.endsWith(IN_SERVER)) { switch (ConfigKey.valueOf(uppercaseKey)) { case IS_MULTI_ENTITY_APP_IN_SERVER: setIsMultiEntity(Boolean.parseBoolean(entry.getValue().toString())); break; case IS_USER_REGISTRATION_ALLOWED_IN_SERVER: setUserRegistrationAllowed(Boolean.parseBoolean(entry.getValue().toString())); break; default: throw new NotFoundEntityException(CONFIG_NOT_FOUND); } } } }
ConfigurationService { public void saveConfig(final Map<String, Object> configs) throws NotFoundEntityException, GmsGeneralException { if (configs.get("user") != null) { try { long id = Long.parseLong(configs.remove("user").toString()); saveConfig(configs, id); } catch (NumberFormatException e) { throw GmsGeneralException.builder() .messageI18N(CONFIG_USER_PARAM_NUMBER) .cause(e) .finishedOK(false) .httpStatus(HttpStatus.UNPROCESSABLE_ENTITY) .build(); } } String uppercaseKey; for (Map.Entry<String, Object> entry : configs.entrySet()) { uppercaseKey = entry.getKey().toUpperCase(Locale.ENGLISH); if (isValidKey(uppercaseKey) && uppercaseKey.endsWith(IN_SERVER)) { switch (ConfigKey.valueOf(uppercaseKey)) { case IS_MULTI_ENTITY_APP_IN_SERVER: setIsMultiEntity(Boolean.parseBoolean(entry.getValue().toString())); break; case IS_USER_REGISTRATION_ALLOWED_IN_SERVER: setUserRegistrationAllowed(Boolean.parseBoolean(entry.getValue().toString())); break; default: throw new NotFoundEntityException(CONFIG_NOT_FOUND); } } } } }
ConfigurationService { public void saveConfig(final Map<String, Object> configs) throws NotFoundEntityException, GmsGeneralException { if (configs.get("user") != null) { try { long id = Long.parseLong(configs.remove("user").toString()); saveConfig(configs, id); } catch (NumberFormatException e) { throw GmsGeneralException.builder() .messageI18N(CONFIG_USER_PARAM_NUMBER) .cause(e) .finishedOK(false) .httpStatus(HttpStatus.UNPROCESSABLE_ENTITY) .build(); } } String uppercaseKey; for (Map.Entry<String, Object> entry : configs.entrySet()) { uppercaseKey = entry.getKey().toUpperCase(Locale.ENGLISH); if (isValidKey(uppercaseKey) && uppercaseKey.endsWith(IN_SERVER)) { switch (ConfigKey.valueOf(uppercaseKey)) { case IS_MULTI_ENTITY_APP_IN_SERVER: setIsMultiEntity(Boolean.parseBoolean(entry.getValue().toString())); break; case IS_USER_REGISTRATION_ALLOWED_IN_SERVER: setUserRegistrationAllowed(Boolean.parseBoolean(entry.getValue().toString())); break; default: throw new NotFoundEntityException(CONFIG_NOT_FOUND); } } } } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); }
ConfigurationService { public void saveConfig(final Map<String, Object> configs) throws NotFoundEntityException, GmsGeneralException { if (configs.get("user") != null) { try { long id = Long.parseLong(configs.remove("user").toString()); saveConfig(configs, id); } catch (NumberFormatException e) { throw GmsGeneralException.builder() .messageI18N(CONFIG_USER_PARAM_NUMBER) .cause(e) .finishedOK(false) .httpStatus(HttpStatus.UNPROCESSABLE_ENTITY) .build(); } } String uppercaseKey; for (Map.Entry<String, Object> entry : configs.entrySet()) { uppercaseKey = entry.getKey().toUpperCase(Locale.ENGLISH); if (isValidKey(uppercaseKey) && uppercaseKey.endsWith(IN_SERVER)) { switch (ConfigKey.valueOf(uppercaseKey)) { case IS_MULTI_ENTITY_APP_IN_SERVER: setIsMultiEntity(Boolean.parseBoolean(entry.getValue().toString())); break; case IS_USER_REGISTRATION_ALLOWED_IN_SERVER: setUserRegistrationAllowed(Boolean.parseBoolean(entry.getValue().toString())); break; default: throw new NotFoundEntityException(CONFIG_NOT_FOUND); } } } } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); }
ConfigurationService { public void saveConfig(final Map<String, Object> configs) throws NotFoundEntityException, GmsGeneralException { if (configs.get("user") != null) { try { long id = Long.parseLong(configs.remove("user").toString()); saveConfig(configs, id); } catch (NumberFormatException e) { throw GmsGeneralException.builder() .messageI18N(CONFIG_USER_PARAM_NUMBER) .cause(e) .finishedOK(false) .httpStatus(HttpStatus.UNPROCESSABLE_ENTITY) .build(); } } String uppercaseKey; for (Map.Entry<String, Object> entry : configs.entrySet()) { uppercaseKey = entry.getKey().toUpperCase(Locale.ENGLISH); if (isValidKey(uppercaseKey) && uppercaseKey.endsWith(IN_SERVER)) { switch (ConfigKey.valueOf(uppercaseKey)) { case IS_MULTI_ENTITY_APP_IN_SERVER: setIsMultiEntity(Boolean.parseBoolean(entry.getValue().toString())); break; case IS_USER_REGISTRATION_ALLOWED_IN_SERVER: setUserRegistrationAllowed(Boolean.parseBoolean(entry.getValue().toString())); break; default: throw new NotFoundEntityException(CONFIG_NOT_FOUND); } } } } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }
@Transactional @Test public void assignDefaultUserToEntityWithRoleDefaultUserNotFound() { EUser defaultUser = userRepository.findFirstByUsernameOrEmail(dc.getUserAdminDefaultName(), dc.getUserAdminDefaultEmail()); authRepository.delete(authRepository.findFirstByUserAndEntityNotNullAndRoleEnabled(defaultUser, true)); userRepository.delete(defaultUser); assertFalse(configurationService.isDefaultUserAssignedToEntityWithRole()); }
public boolean isDefaultUserAssignedToEntityWithRole() { EUser u = userRepository.findFirstByUsernameOrEmail(dc.getUserAdminDefaultName(), dc.getUserAdminDefaultEmail()); if (u != null) { EOwnedEntity e = entityRepository.findFirstByUsername(dc.getEntityDefaultUsername()); if (e != null) { BRole role = roleRepository.findFirstByLabel(dc.getRoleAdminDefaultLabel()); if (role != null) { com.gms.domain.security.BAuthorization.BAuthorizationPk pk = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), role.getId()); authRepository.save(new BAuthorization(pk, u, e, role)); return true; } } } return false; }
ConfigurationService { public boolean isDefaultUserAssignedToEntityWithRole() { EUser u = userRepository.findFirstByUsernameOrEmail(dc.getUserAdminDefaultName(), dc.getUserAdminDefaultEmail()); if (u != null) { EOwnedEntity e = entityRepository.findFirstByUsername(dc.getEntityDefaultUsername()); if (e != null) { BRole role = roleRepository.findFirstByLabel(dc.getRoleAdminDefaultLabel()); if (role != null) { com.gms.domain.security.BAuthorization.BAuthorizationPk pk = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), role.getId()); authRepository.save(new BAuthorization(pk, u, e, role)); return true; } } } return false; } }
ConfigurationService { public boolean isDefaultUserAssignedToEntityWithRole() { EUser u = userRepository.findFirstByUsernameOrEmail(dc.getUserAdminDefaultName(), dc.getUserAdminDefaultEmail()); if (u != null) { EOwnedEntity e = entityRepository.findFirstByUsername(dc.getEntityDefaultUsername()); if (e != null) { BRole role = roleRepository.findFirstByLabel(dc.getRoleAdminDefaultLabel()); if (role != null) { com.gms.domain.security.BAuthorization.BAuthorizationPk pk = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), role.getId()); authRepository.save(new BAuthorization(pk, u, e, role)); return true; } } } return false; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); }
ConfigurationService { public boolean isDefaultUserAssignedToEntityWithRole() { EUser u = userRepository.findFirstByUsernameOrEmail(dc.getUserAdminDefaultName(), dc.getUserAdminDefaultEmail()); if (u != null) { EOwnedEntity e = entityRepository.findFirstByUsername(dc.getEntityDefaultUsername()); if (e != null) { BRole role = roleRepository.findFirstByLabel(dc.getRoleAdminDefaultLabel()); if (role != null) { com.gms.domain.security.BAuthorization.BAuthorizationPk pk = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), role.getId()); authRepository.save(new BAuthorization(pk, u, e, role)); return true; } } } return false; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); }
ConfigurationService { public boolean isDefaultUserAssignedToEntityWithRole() { EUser u = userRepository.findFirstByUsernameOrEmail(dc.getUserAdminDefaultName(), dc.getUserAdminDefaultEmail()); if (u != null) { EOwnedEntity e = entityRepository.findFirstByUsername(dc.getEntityDefaultUsername()); if (e != null) { BRole role = roleRepository.findFirstByLabel(dc.getRoleAdminDefaultLabel()); if (role != null) { com.gms.domain.security.BAuthorization.BAuthorizationPk pk = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), role.getId()); authRepository.save(new BAuthorization(pk, u, e, role)); return true; } } } return false; } @Autowired ConfigurationService(final BConfigurationRepository configurationRepository, final EUserRepository userRepository, final EOwnedEntityRepository entityRepository, final BRoleRepository roleRepository, final BAuthorizationRepository authRepository, final DefaultConst defaultConst); boolean isApplicationConfigured(); boolean isDefaultConfigurationCreated(); boolean isDefaultUserAssignedToEntityWithRole(); Map<String, String> getConfig(); Object getConfig(final String key); String getConfig(final String key, final long userId); Map<String, Object> getConfigByUser(final long userId); void saveConfig(final Map<String, Object> configs); void saveConfig(final Map<String, Object> configs, final long userId); void setUserRegistrationAllowed(final boolean userRegistrationAllowed); void setIsMultiEntity(final boolean isMultiEntity); Long getLastAccessedEntityIdByUser(final long userId); void setLastAccessedEntityIdByUser(final long userId, final long entityId); static final String IN_SERVER; static final String CONFIG_NOT_FOUND; }
@Test public void isInitialLoadOKTest() { authRepository.deleteAll(); userRepository.deleteAll(); entityRepository.deleteAll(); roleRepository.deleteAll(); permissionRepository.deleteAll(); configRepository.deleteAll(); ReflectionTestUtils.setField(appService, "initialLoadOK", null); Assert.assertTrue(appService.isInitialLoadOK()); }
public boolean isInitialLoadOK() { if (initialLoadOK == null) { boolean ok = true; if (!configurationService.isApplicationConfigured()) { ok = configurationService.isDefaultConfigurationCreated(); ok = ok && permissionService.areDefaultPermissionsCreatedSuccessfully(); ok = ok && roleService.createDefaultRole() != null; ok = ok && userService.createDefaultUser() != null; ok = ok && oeService.createDefaultEntity() != null; ok = ok && configurationService.isDefaultUserAssignedToEntityWithRole(); } initialLoadOK = ok; } return initialLoadOK; }
AppService { public boolean isInitialLoadOK() { if (initialLoadOK == null) { boolean ok = true; if (!configurationService.isApplicationConfigured()) { ok = configurationService.isDefaultConfigurationCreated(); ok = ok && permissionService.areDefaultPermissionsCreatedSuccessfully(); ok = ok && roleService.createDefaultRole() != null; ok = ok && userService.createDefaultUser() != null; ok = ok && oeService.createDefaultEntity() != null; ok = ok && configurationService.isDefaultUserAssignedToEntityWithRole(); } initialLoadOK = ok; } return initialLoadOK; } }
AppService { public boolean isInitialLoadOK() { if (initialLoadOK == null) { boolean ok = true; if (!configurationService.isApplicationConfigured()) { ok = configurationService.isDefaultConfigurationCreated(); ok = ok && permissionService.areDefaultPermissionsCreatedSuccessfully(); ok = ok && roleService.createDefaultRole() != null; ok = ok && userService.createDefaultUser() != null; ok = ok && oeService.createDefaultEntity() != null; ok = ok && configurationService.isDefaultUserAssignedToEntityWithRole(); } initialLoadOK = ok; } return initialLoadOK; } }
AppService { public boolean isInitialLoadOK() { if (initialLoadOK == null) { boolean ok = true; if (!configurationService.isApplicationConfigured()) { ok = configurationService.isDefaultConfigurationCreated(); ok = ok && permissionService.areDefaultPermissionsCreatedSuccessfully(); ok = ok && roleService.createDefaultRole() != null; ok = ok && userService.createDefaultUser() != null; ok = ok && oeService.createDefaultEntity() != null; ok = ok && configurationService.isDefaultUserAssignedToEntityWithRole(); } initialLoadOK = ok; } return initialLoadOK; } boolean isInitialLoadOK(); }
AppService { public boolean isInitialLoadOK() { if (initialLoadOK == null) { boolean ok = true; if (!configurationService.isApplicationConfigured()) { ok = configurationService.isDefaultConfigurationCreated(); ok = ok && permissionService.areDefaultPermissionsCreatedSuccessfully(); ok = ok && roleService.createDefaultRole() != null; ok = ok && userService.createDefaultUser() != null; ok = ok && oeService.createDefaultEntity() != null; ok = ok && configurationService.isDefaultUserAssignedToEntityWithRole(); } initialLoadOK = ok; } return initialLoadOK; } boolean isInitialLoadOK(); }
@Test public void createQuery() { assertNotNull(repository.save(EntityUtil.getSamplePermission())); final Query query = queryService.createQuery("select e from BPermission e"); assertNotNull(query); final List<?> resultList = query.getResultList(); assertNotNull(resultList); assertFalse(resultList.isEmpty()); }
public Query createQuery(final String qls) { return entityManager.createQuery(qls); }
QueryService { public Query createQuery(final String qls) { return entityManager.createQuery(qls); } }
QueryService { public Query createQuery(final String qls) { return entityManager.createQuery(qls); } }
QueryService { public Query createQuery(final String qls) { return entityManager.createQuery(qls); } Query createQuery(final String qls); Query createQuery(final String qls, final Class<?> clazz); Query createNativeQuery(final String sql); Query createNativeQuery(final String sql, final Class<?> clazz); }
QueryService { public Query createQuery(final String qls) { return entityManager.createQuery(qls); } Query createQuery(final String qls); Query createQuery(final String qls, final Class<?> clazz); Query createNativeQuery(final String sql); Query createNativeQuery(final String sql, final Class<?> clazz); }
@Test public void createQueryWithResultClass() { BPermission p = repository.save(EntityUtil.getSamplePermission()); assertNotNull(p); final Query query = queryService.createQuery("select e from BPermission e", BPermission.class); assertNotNull(query); final List<?> resultList = query.getResultList(); assertNotNull(resultList); assertFalse(resultList.isEmpty()); assertTrue(resultList.contains(p)); }
public Query createQuery(final String qls) { return entityManager.createQuery(qls); }
QueryService { public Query createQuery(final String qls) { return entityManager.createQuery(qls); } }
QueryService { public Query createQuery(final String qls) { return entityManager.createQuery(qls); } }
QueryService { public Query createQuery(final String qls) { return entityManager.createQuery(qls); } Query createQuery(final String qls); Query createQuery(final String qls, final Class<?> clazz); Query createNativeQuery(final String sql); Query createNativeQuery(final String sql, final Class<?> clazz); }
QueryService { public Query createQuery(final String qls) { return entityManager.createQuery(qls); } Query createQuery(final String qls); Query createQuery(final String qls, final Class<?> clazz); Query createNativeQuery(final String sql); Query createNativeQuery(final String sql, final Class<?> clazz); }
@Test public void getWhat() { Object field = ReflectionTestUtils.getField(LinkPath.class, "LINK"); String link = field != null ? field.toString() : ""; field = ReflectionTestUtils.getField(LinkPath.class, "HREF"); String href = field != null ? field.toString() : ""; Assert.assertEquals(LinkPath.get("test"), String.format("%s.%s.%s", link, "test", href)); }
public static String get(final String what) { return String.format("%s.%s.%s", LINK, what, HREF); }
LinkPath { public static String get(final String what) { return String.format("%s.%s.%s", LINK, what, HREF); } }
LinkPath { public static String get(final String what) { return String.format("%s.%s.%s", LINK, what, HREF); } private LinkPath(); }
LinkPath { public static String get(final String what) { return String.format("%s.%s.%s", LINK, what, HREF); } private LinkPath(); static String get(final String what); static String getSelf(final String what); static String get(); }
LinkPath { public static String get(final String what) { return String.format("%s.%s.%s", LINK, what, HREF); } private LinkPath(); static String get(final String what); static String getSelf(final String what); static String get(); static final String EMBEDDED; static final String PAGE_SIZE_PARAM_META; static final String PAGE_SORT_PARAM_META; static final String PAGE_PAGE_PARAM_META; }
@Test public void createNativeQuery() { assertNotNull(repository.save(EntityUtil.getSamplePermission())); final Query nativeQuery = queryService.createNativeQuery("SELECT * FROM bpermission"); assertNotNull(nativeQuery); final List<?> resultList = nativeQuery.getResultList(); assertNotNull(resultList); assertFalse(resultList.isEmpty()); }
public Query createNativeQuery(final String sql) { return entityManager.createNativeQuery(sql); }
QueryService { public Query createNativeQuery(final String sql) { return entityManager.createNativeQuery(sql); } }
QueryService { public Query createNativeQuery(final String sql) { return entityManager.createNativeQuery(sql); } }
QueryService { public Query createNativeQuery(final String sql) { return entityManager.createNativeQuery(sql); } Query createQuery(final String qls); Query createQuery(final String qls, final Class<?> clazz); Query createNativeQuery(final String sql); Query createNativeQuery(final String sql, final Class<?> clazz); }
QueryService { public Query createNativeQuery(final String sql) { return entityManager.createNativeQuery(sql); } Query createQuery(final String qls); Query createQuery(final String qls, final Class<?> clazz); Query createNativeQuery(final String sql); Query createNativeQuery(final String sql, final Class<?> clazz); }
@Test public void createNativeQueryWithResultClass() { BPermission p = repository.save(EntityUtil.getSamplePermission()); assertNotNull(p); final Query nativeQuery = queryService.createNativeQuery("SELECT * FROM bpermission", BPermission.class); assertNotNull(nativeQuery); final List<?> resultList = nativeQuery.getResultList(); assertNotNull(resultList); assertTrue(resultList.contains(p)); }
public Query createNativeQuery(final String sql) { return entityManager.createNativeQuery(sql); }
QueryService { public Query createNativeQuery(final String sql) { return entityManager.createNativeQuery(sql); } }
QueryService { public Query createNativeQuery(final String sql) { return entityManager.createNativeQuery(sql); } }
QueryService { public Query createNativeQuery(final String sql) { return entityManager.createNativeQuery(sql); } Query createQuery(final String qls); Query createQuery(final String qls, final Class<?> clazz); Query createNativeQuery(final String sql); Query createNativeQuery(final String sql, final Class<?> clazz); }
QueryService { public Query createNativeQuery(final String sql) { return entityManager.createNativeQuery(sql); } Query createQuery(final String qls); Query createQuery(final String qls, final Class<?> clazz); Query createNativeQuery(final String sql); Query createNativeQuery(final String sql, final Class<?> clazz); }
@Test public void createDefaultUser() { assertNotNull(userRepository.findFirstByUsername(dc.getUserAdminDefaultUsername())); }
public EUser createDefaultUser() { EUser u = new EUser( dc.getUserAdminDefaultUsername(), dc.getUserAdminDefaultEmail(), dc.getUserAdminDefaultName(), dc.getUserAdminDefaultLastName(), dc.getUserAdminDefaultPassword() ); u.setEnabled(true); return signUp(u, EmailStatus.VERIFIED); }
UserService implements UserDetailsService { public EUser createDefaultUser() { EUser u = new EUser( dc.getUserAdminDefaultUsername(), dc.getUserAdminDefaultEmail(), dc.getUserAdminDefaultName(), dc.getUserAdminDefaultLastName(), dc.getUserAdminDefaultPassword() ); u.setEnabled(true); return signUp(u, EmailStatus.VERIFIED); } }
UserService implements UserDetailsService { public EUser createDefaultUser() { EUser u = new EUser( dc.getUserAdminDefaultUsername(), dc.getUserAdminDefaultEmail(), dc.getUserAdminDefaultName(), dc.getUserAdminDefaultLastName(), dc.getUserAdminDefaultPassword() ); u.setEnabled(true); return signUp(u, EmailStatus.VERIFIED); } }
UserService implements UserDetailsService { public EUser createDefaultUser() { EUser u = new EUser( dc.getUserAdminDefaultUsername(), dc.getUserAdminDefaultEmail(), dc.getUserAdminDefaultName(), dc.getUserAdminDefaultLastName(), dc.getUserAdminDefaultPassword() ); u.setEnabled(true); return signUp(u, EmailStatus.VERIFIED); } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }
UserService implements UserDetailsService { public EUser createDefaultUser() { EUser u = new EUser( dc.getUserAdminDefaultUsername(), dc.getUserAdminDefaultEmail(), dc.getUserAdminDefaultName(), dc.getUserAdminDefaultLastName(), dc.getUserAdminDefaultPassword() ); u.setEnabled(true); return signUp(u, EmailStatus.VERIFIED); } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }
@Test public void addRolesToUser() { EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(u); BRole r1 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r1); BRole r2 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r2); EOwnedEntity e = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(e); List<Long> ids = new LinkedList<>(); ids.add(r1.getId()); ids.add(r2.getId()); assertEquals(2, ids.size()); List<Long> added = null; try { added = userService.addRolesToUser(u.getId(), e.getId(), ids); assertNotNull(added); assertEquals(added.size(), ids.size()); assertTrue(added.contains(ids.get(0))); assertTrue(added.contains(ids.get(1))); } catch (NotFoundEntityException e1) { LOGGER.error(e1.getLocalizedMessage()); fail("Roles could not be saved"); } final List<BRole> roles = authorizationRepository.getRolesForUserOverEntity(u.getId(), e.getId()); assertNotNull(roles); assertEquals(roles.size(), ids.size()); assertNotNull(added); assertEquals(added.size(), roles.size()); assertTrue(added.contains(roles.get(0).getId())); assertTrue(added.contains(roles.get(1).getId())); }
public List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId) throws NotFoundEntityException { return addRemoveRolesToFromUser(userId, entityId, rolesId, true); }
UserService implements UserDetailsService { public List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId) throws NotFoundEntityException { return addRemoveRolesToFromUser(userId, entityId, rolesId, true); } }
UserService implements UserDetailsService { public List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId) throws NotFoundEntityException { return addRemoveRolesToFromUser(userId, entityId, rolesId, true); } }
UserService implements UserDetailsService { public List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId) throws NotFoundEntityException { return addRemoveRolesToFromUser(userId, entityId, rolesId, true); } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }
UserService implements UserDetailsService { public List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId) throws NotFoundEntityException { return addRemoveRolesToFromUser(userId, entityId, rolesId, true); } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }
@Test public void removeRolesFromUser() { EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(u); BRole r1 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r1); BRole r2 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r2); EOwnedEntity e = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(e); BAuthorization.BAuthorizationPk pk1 = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), r1.getId()); assertNotNull(pk1); BAuthorization auth1 = authorizationRepository.save(new BAuthorization(pk1, u, e, r1)); assertNotNull(auth1); BAuthorization.BAuthorizationPk pk2 = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), r2.getId()); assertNotNull(pk1); BAuthorization auth2 = authorizationRepository.save(new BAuthorization(pk2, u, e, r2)); assertNotNull(auth2); Collection<Long> ids = new LinkedList<>(); ids.add(r1.getId()); ids.add(r2.getId()); List<BRole> roles = authorizationRepository.getRolesForUserOverEntity(u.getId(), e.getId()); assertNotNull(roles); assertEquals(roles.size(), ids.size()); assertTrue(ids.contains(roles.get(0).getId())); assertTrue(ids.contains(roles.get(1).getId())); List<Long> removed = null; try { removed = userService.removeRolesFromUser(u.getId(), e.getId(), ids); } catch (NotFoundEntityException e1) { LOGGER.error(e1.getLocalizedMessage()); fail("Roles could not be removed"); } assertNotNull(removed); assertEquals(removed.size(), roles.size()); assertTrue(removed.contains(roles.get(0).getId())); assertTrue(removed.contains(roles.get(1).getId())); roles = authorizationRepository.getRolesForUserOverEntity(u.getId(), e.getId()); assertNotNull(roles); assertTrue(roles.isEmpty()); }
public List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId) throws NotFoundEntityException { return addRemoveRolesToFromUser(userId, entityId, rolesId, false); }
UserService implements UserDetailsService { public List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId) throws NotFoundEntityException { return addRemoveRolesToFromUser(userId, entityId, rolesId, false); } }
UserService implements UserDetailsService { public List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId) throws NotFoundEntityException { return addRemoveRolesToFromUser(userId, entityId, rolesId, false); } }
UserService implements UserDetailsService { public List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId) throws NotFoundEntityException { return addRemoveRolesToFromUser(userId, entityId, rolesId, false); } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }
UserService implements UserDetailsService { public List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId) throws NotFoundEntityException { return addRemoveRolesToFromUser(userId, entityId, rolesId, false); } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }
@Test public void loadUserByUsername() { EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(u); UserDetails su = userService.loadUserByUsername(u.getUsername()); assertNotNull(su); assertEquals(su, u); }
@Override public UserDetails loadUserByUsername(final String usernameOrEmail) { EUser u = userRepository.findFirstByUsernameOrEmail(usernameOrEmail, usernameOrEmail); if (u != null) { return u; } throw new UsernameNotFoundException(msg.getMessage(USER_NOT_FOUND)); }
UserService implements UserDetailsService { @Override public UserDetails loadUserByUsername(final String usernameOrEmail) { EUser u = userRepository.findFirstByUsernameOrEmail(usernameOrEmail, usernameOrEmail); if (u != null) { return u; } throw new UsernameNotFoundException(msg.getMessage(USER_NOT_FOUND)); } }
UserService implements UserDetailsService { @Override public UserDetails loadUserByUsername(final String usernameOrEmail) { EUser u = userRepository.findFirstByUsernameOrEmail(usernameOrEmail, usernameOrEmail); if (u != null) { return u; } throw new UsernameNotFoundException(msg.getMessage(USER_NOT_FOUND)); } }
UserService implements UserDetailsService { @Override public UserDetails loadUserByUsername(final String usernameOrEmail) { EUser u = userRepository.findFirstByUsernameOrEmail(usernameOrEmail, usernameOrEmail); if (u != null) { return u; } throw new UsernameNotFoundException(msg.getMessage(USER_NOT_FOUND)); } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }
UserService implements UserDetailsService { @Override public UserDetails loadUserByUsername(final String usernameOrEmail) { EUser u = userRepository.findFirstByUsernameOrEmail(usernameOrEmail, usernameOrEmail); if (u != null) { return u; } throw new UsernameNotFoundException(msg.getMessage(USER_NOT_FOUND)); } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }
@Test public void getUserAuthoritiesForToken() { BPermission p1 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p1); BPermission p2 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p2); BRole r1 = EntityUtil.getSampleRole(random.nextString()); r1.addPermission(p1, p2); assertNotNull(roleRepository.save(r1)); BPermission p3 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p3); BPermission p4 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p4); BRole r2 = EntityUtil.getSampleRole(random.nextString()); r2.addPermission(p3, p4); assertNotNull(roleRepository.save(r2)); EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(u); EOwnedEntity e = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(e); BAuthorization.BAuthorizationPk pk1 = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), r1.getId()); BAuthorization auth1 = new BAuthorization(pk1, u, e, r1); assertNotNull(authorizationRepository.save(auth1)); BAuthorization.BAuthorizationPk pk2 = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), r2.getId()); BAuthorization auth2 = new BAuthorization(pk2, u, e, r2); assertNotNull(authorizationRepository.save(auth2)); String separator = "--<<" + random.nextString() + ">>--"; String authForToken = userService.getUserAuthoritiesForToken(u.getUsername(), separator); assertNotNull(authForToken); assertNotEquals("", authForToken); List<String> permissionNames = Arrays.asList(authForToken.split(separator)); assertTrue(permissionNames.contains(p1.getName())); assertTrue(permissionNames.contains(p2.getName())); assertTrue(permissionNames.contains(p3.getName())); assertTrue(permissionNames.contains(p4.getName())); }
public String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator) { StringBuilder authBuilder = new StringBuilder(); EUser u = (EUser) loadUserByUsername(usernameOrEmail); if (u != null) { Long entityId = getEntityIdByUser(u); if (entityId == null) { return ""; } List<BPermission> pFromDB = permissionService.findPermissionsByUserIdAndEntityId(u.getId(), entityId); for (BPermission p : pFromDB) { authBuilder.append(p.getName()).append(separator); } } return authBuilder.toString(); }
UserService implements UserDetailsService { public String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator) { StringBuilder authBuilder = new StringBuilder(); EUser u = (EUser) loadUserByUsername(usernameOrEmail); if (u != null) { Long entityId = getEntityIdByUser(u); if (entityId == null) { return ""; } List<BPermission> pFromDB = permissionService.findPermissionsByUserIdAndEntityId(u.getId(), entityId); for (BPermission p : pFromDB) { authBuilder.append(p.getName()).append(separator); } } return authBuilder.toString(); } }
UserService implements UserDetailsService { public String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator) { StringBuilder authBuilder = new StringBuilder(); EUser u = (EUser) loadUserByUsername(usernameOrEmail); if (u != null) { Long entityId = getEntityIdByUser(u); if (entityId == null) { return ""; } List<BPermission> pFromDB = permissionService.findPermissionsByUserIdAndEntityId(u.getId(), entityId); for (BPermission p : pFromDB) { authBuilder.append(p.getName()).append(separator); } } return authBuilder.toString(); } }
UserService implements UserDetailsService { public String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator) { StringBuilder authBuilder = new StringBuilder(); EUser u = (EUser) loadUserByUsername(usernameOrEmail); if (u != null) { Long entityId = getEntityIdByUser(u); if (entityId == null) { return ""; } List<BPermission> pFromDB = permissionService.findPermissionsByUserIdAndEntityId(u.getId(), entityId); for (BPermission p : pFromDB) { authBuilder.append(p.getName()).append(separator); } } return authBuilder.toString(); } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }
UserService implements UserDetailsService { public String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator) { StringBuilder authBuilder = new StringBuilder(); EUser u = (EUser) loadUserByUsername(usernameOrEmail); if (u != null) { Long entityId = getEntityIdByUser(u); if (entityId == null) { return ""; } List<BPermission> pFromDB = permissionService.findPermissionsByUserIdAndEntityId(u.getId(), entityId); for (BPermission p : pFromDB) { authBuilder.append(p.getName()).append(separator); } } return authBuilder.toString(); } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }
@Test public void getRolesForUser() { EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(u); EOwnedEntity e1 = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(e1); EOwnedEntity e2 = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(e2); BRole r1 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r1); BRole r2 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r2); BRole r3 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r3); BRole r4 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r4); BAuthorization.BAuthorizationPk pk1 = new BAuthorization.BAuthorizationPk(u.getId(), e1.getId(), r1.getId()); BAuthorization auth1 = authorizationRepository.save(new BAuthorization(pk1, u, e1, r1)); assertNotNull(auth1); BAuthorization.BAuthorizationPk pk2 = new BAuthorization.BAuthorizationPk(u.getId(), e1.getId(), r2.getId()); BAuthorization auth2 = authorizationRepository.save(new BAuthorization(pk2, u, e1, r2)); assertNotNull(auth2); BAuthorization.BAuthorizationPk pk3 = new BAuthorization.BAuthorizationPk(u.getId(), e2.getId(), r3.getId()); BAuthorization auth3 = authorizationRepository.save(new BAuthorization(pk3, u, e2, r3)); assertNotNull(auth3); BAuthorization.BAuthorizationPk pk4 = new BAuthorization.BAuthorizationPk(u.getId(), e2.getId(), r4.getId()); BAuthorization auth4 = authorizationRepository.save(new BAuthorization(pk4, u, e2, r4)); assertNotNull(auth4); try { final Map<String, List<BRole>> rolesForUser = userService.getRolesForUser(u.getId()); assertNotNull(rolesForUser); assertFalse(rolesForUser.isEmpty()); final Set<String> keySet = rolesForUser.keySet(); assertTrue(keySet.contains(e1.getUsername())); assertTrue(keySet.contains(e2.getUsername())); assertTrue(rolesForUser.get(e1.getUsername()).contains(r1)); assertTrue(rolesForUser.get(e1.getUsername()).contains(r2)); assertTrue(rolesForUser.get(e2.getUsername()).contains(r3)); assertTrue(rolesForUser.get(e2.getUsername()).contains(r4)); } catch (NotFoundEntityException e) { LOGGER.error(e.getLocalizedMessage()); fail("The username was not found"); } }
public Map<String, List<BRole>> getRolesForUser(final Long id) throws NotFoundEntityException { EUser u = getUser(id); return authorizationRepository.getRolesForUserOverAllEntities(u.getId()); }
UserService implements UserDetailsService { public Map<String, List<BRole>> getRolesForUser(final Long id) throws NotFoundEntityException { EUser u = getUser(id); return authorizationRepository.getRolesForUserOverAllEntities(u.getId()); } }
UserService implements UserDetailsService { public Map<String, List<BRole>> getRolesForUser(final Long id) throws NotFoundEntityException { EUser u = getUser(id); return authorizationRepository.getRolesForUserOverAllEntities(u.getId()); } }
UserService implements UserDetailsService { public Map<String, List<BRole>> getRolesForUser(final Long id) throws NotFoundEntityException { EUser u = getUser(id); return authorizationRepository.getRolesForUserOverAllEntities(u.getId()); } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }
UserService implements UserDetailsService { public Map<String, List<BRole>> getRolesForUser(final Long id) throws NotFoundEntityException { EUser u = getUser(id); return authorizationRepository.getRolesForUserOverAllEntities(u.getId()); } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }
@Test public void getRolesForUserOverEntity() { EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(u); EOwnedEntity e = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(e); BRole r1 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r1); BRole r2 = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r2); BAuthorization.BAuthorizationPk pk1 = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), r1.getId()); BAuthorization auth1 = authorizationRepository.save(new BAuthorization(pk1, u, e, r1)); assertNotNull(auth1); BAuthorization.BAuthorizationPk pk2 = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), r2.getId()); BAuthorization auth2 = authorizationRepository.save(new BAuthorization(pk2, u, e, r2)); assertNotNull(auth2); try { final List<BRole> roles = userService.getRolesForUserOverEntity(u.getId(), e.getId()); assertNotNull(roles); assertFalse(roles.isEmpty()); assertTrue(roles.contains(r1)); assertTrue(roles.contains(r2)); } catch (NotFoundEntityException ex) { LOGGER.error(ex.getLocalizedMessage()); fail("Either the username or the entity was not found"); } }
public List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId) throws NotFoundEntityException { return authorizationRepository.getRolesForUserOverEntity( getUser(userId).getId(), getOwnedEntity(entityId).getId() ); }
UserService implements UserDetailsService { public List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId) throws NotFoundEntityException { return authorizationRepository.getRolesForUserOverEntity( getUser(userId).getId(), getOwnedEntity(entityId).getId() ); } }
UserService implements UserDetailsService { public List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId) throws NotFoundEntityException { return authorizationRepository.getRolesForUserOverEntity( getUser(userId).getId(), getOwnedEntity(entityId).getId() ); } }
UserService implements UserDetailsService { public List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId) throws NotFoundEntityException { return authorizationRepository.getRolesForUserOverEntity( getUser(userId).getId(), getOwnedEntity(entityId).getId() ); } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }
UserService implements UserDetailsService { public List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId) throws NotFoundEntityException { return authorizationRepository.getRolesForUserOverEntity( getUser(userId).getId(), getOwnedEntity(entityId).getId() ); } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }
@Test public void getEntityIdByUserWithNoRoles() { EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(u); assertNull(userService.getEntityIdByUser(u)); }
public Long getEntityIdByUser(final EUser u) { Long entityId = configService.getLastAccessedEntityIdByUser(u.getId()); if (entityId == null) { BAuthorization anAuth = authorizationRepository.findFirstByUserAndEntityNotNullAndRoleEnabled(u, true); if (anAuth == null) { return null; } entityId = anAuth.getEntity().getId(); configService.setLastAccessedEntityIdByUser(u.getId(), entityId); } return entityId; }
UserService implements UserDetailsService { public Long getEntityIdByUser(final EUser u) { Long entityId = configService.getLastAccessedEntityIdByUser(u.getId()); if (entityId == null) { BAuthorization anAuth = authorizationRepository.findFirstByUserAndEntityNotNullAndRoleEnabled(u, true); if (anAuth == null) { return null; } entityId = anAuth.getEntity().getId(); configService.setLastAccessedEntityIdByUser(u.getId(), entityId); } return entityId; } }
UserService implements UserDetailsService { public Long getEntityIdByUser(final EUser u) { Long entityId = configService.getLastAccessedEntityIdByUser(u.getId()); if (entityId == null) { BAuthorization anAuth = authorizationRepository.findFirstByUserAndEntityNotNullAndRoleEnabled(u, true); if (anAuth == null) { return null; } entityId = anAuth.getEntity().getId(); configService.setLastAccessedEntityIdByUser(u.getId(), entityId); } return entityId; } }
UserService implements UserDetailsService { public Long getEntityIdByUser(final EUser u) { Long entityId = configService.getLastAccessedEntityIdByUser(u.getId()); if (entityId == null) { BAuthorization anAuth = authorizationRepository.findFirstByUserAndEntityNotNullAndRoleEnabled(u, true); if (anAuth == null) { return null; } entityId = anAuth.getEntity().getId(); configService.setLastAccessedEntityIdByUser(u.getId(), entityId); } return entityId; } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }
UserService implements UserDetailsService { public Long getEntityIdByUser(final EUser u) { Long entityId = configService.getLastAccessedEntityIdByUser(u.getId()); if (entityId == null) { BAuthorization anAuth = authorizationRepository.findFirstByUserAndEntityNotNullAndRoleEnabled(u, true); if (anAuth == null) { return null; } entityId = anAuth.getEntity().getId(); configService.setLastAccessedEntityIdByUser(u.getId(), entityId); } return entityId; } EUser createDefaultUser(); EUser signUp(final EUser u, final EmailStatus emailStatus); EUser signUp(final EUser u, final EmailStatus emailStatus, final RegistrationPrivilege registrationPrivilege); List<Long> addRolesToUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); List<Long> removeRolesFromUser(final Long userId, final Long entityId, final Iterable<Long> rolesId); @Override UserDetails loadUserByUsername(final String usernameOrEmail); String getUserAuthoritiesForToken(final String usernameOrEmail, final String separator); Map<String, List<BRole>> getRolesForUser(final Long id); List<BRole> getRolesForUserOverEntity(final Long userId, final Long entityId); Long getEntityIdByUser(final EUser u); }
@Test public void getSelf() { Object field = ReflectionTestUtils.getField(LinkPath.class, "LINK"); String link = field != null ? field.toString() : ""; field = ReflectionTestUtils.getField(LinkPath.class, "HREF"); String href = field != null ? field.toString() : ""; field = ReflectionTestUtils.getField(LinkPath.class, "SELF"); String self = field != null ? field.toString() : ""; Assert.assertEquals(LinkPath.get(self), String.format("%s.%s.%s", link, self, href)); }
public static String getSelf(final String what) { return String.format("%s.%s.%s", LINK, SELF, what); }
LinkPath { public static String getSelf(final String what) { return String.format("%s.%s.%s", LINK, SELF, what); } }
LinkPath { public static String getSelf(final String what) { return String.format("%s.%s.%s", LINK, SELF, what); } private LinkPath(); }
LinkPath { public static String getSelf(final String what) { return String.format("%s.%s.%s", LINK, SELF, what); } private LinkPath(); static String get(final String what); static String getSelf(final String what); static String get(); }
LinkPath { public static String getSelf(final String what) { return String.format("%s.%s.%s", LINK, SELF, what); } private LinkPath(); static String get(final String what); static String getSelf(final String what); static String get(); static final String EMBEDDED; static final String PAGE_SIZE_PARAM_META; static final String PAGE_SORT_PARAM_META; static final String PAGE_PAGE_PARAM_META; }
@Test public void createDefaultEntity() { assertNotNull(repository.findFirstByUsername(dc.getEntityDefaultUsername())); }
public EOwnedEntity createDefaultEntity() { return entityRepository.save(new EOwnedEntity( dc.getEntityDefaultName(), dc.getEntityDefaultUsername(), dc.getEntityDefaultDescription()) ); }
OwnedEntityService { public EOwnedEntity createDefaultEntity() { return entityRepository.save(new EOwnedEntity( dc.getEntityDefaultName(), dc.getEntityDefaultUsername(), dc.getEntityDefaultDescription()) ); } }
OwnedEntityService { public EOwnedEntity createDefaultEntity() { return entityRepository.save(new EOwnedEntity( dc.getEntityDefaultName(), dc.getEntityDefaultUsername(), dc.getEntityDefaultDescription()) ); } }
OwnedEntityService { public EOwnedEntity createDefaultEntity() { return entityRepository.save(new EOwnedEntity( dc.getEntityDefaultName(), dc.getEntityDefaultUsername(), dc.getEntityDefaultDescription()) ); } EOwnedEntity createDefaultEntity(); EOwnedEntity create(final EOwnedEntity e); }
OwnedEntityService { public EOwnedEntity createDefaultEntity() { return entityRepository.save(new EOwnedEntity( dc.getEntityDefaultName(), dc.getEntityDefaultUsername(), dc.getEntityDefaultDescription()) ); } EOwnedEntity createDefaultEntity(); EOwnedEntity create(final EOwnedEntity e); }
@Test public void create() { boolean initialIsM = configService.isMultiEntity(); if (!initialIsM) { configService.setIsMultiEntity(true); } try { final EOwnedEntity e = service.create(EntityUtil.getSampleEntity()); assertNotNull(e); Optional<EOwnedEntity> er = repository.findById(e.getId()); assertTrue(er.isPresent()); assertEquals(e, er.get()); } catch (GmsGeneralException e) { LOGGER.error(e.getLocalizedMessage()); fail("Entity could not be created"); } if (!initialIsM) { configService.setIsMultiEntity(false); } }
public EOwnedEntity create(final EOwnedEntity e) throws GmsGeneralException { if (configService.isMultiEntity()) { return entityRepository.save(e); } throw GmsGeneralException.builder() .messageI18N("entity.add.not_allowed") .finishedOK(true).httpStatus(HttpStatus.CONFLICT) .build(); }
OwnedEntityService { public EOwnedEntity create(final EOwnedEntity e) throws GmsGeneralException { if (configService.isMultiEntity()) { return entityRepository.save(e); } throw GmsGeneralException.builder() .messageI18N("entity.add.not_allowed") .finishedOK(true).httpStatus(HttpStatus.CONFLICT) .build(); } }
OwnedEntityService { public EOwnedEntity create(final EOwnedEntity e) throws GmsGeneralException { if (configService.isMultiEntity()) { return entityRepository.save(e); } throw GmsGeneralException.builder() .messageI18N("entity.add.not_allowed") .finishedOK(true).httpStatus(HttpStatus.CONFLICT) .build(); } }
OwnedEntityService { public EOwnedEntity create(final EOwnedEntity e) throws GmsGeneralException { if (configService.isMultiEntity()) { return entityRepository.save(e); } throw GmsGeneralException.builder() .messageI18N("entity.add.not_allowed") .finishedOK(true).httpStatus(HttpStatus.CONFLICT) .build(); } EOwnedEntity createDefaultEntity(); EOwnedEntity create(final EOwnedEntity e); }
OwnedEntityService { public EOwnedEntity create(final EOwnedEntity e) throws GmsGeneralException { if (configService.isMultiEntity()) { return entityRepository.save(e); } throw GmsGeneralException.builder() .messageI18N("entity.add.not_allowed") .finishedOK(true).httpStatus(HttpStatus.CONFLICT) .build(); } EOwnedEntity createDefaultEntity(); EOwnedEntity create(final EOwnedEntity e); }
@Test public void createDefaultRole() { BRole r = roleRepository.findFirstByLabel(dc.getRoleAdminDefaultLabel()); assertNotNull("Default role not created", r); }
public BRole createDefaultRole() { BRole role = new BRole(dc.getRoleAdminDefaultLabel()); role.setDescription(dc.getRoleAdminDefaultDescription()); role.setEnabled(dc.isRoleAdminDefaultEnabled()); final Iterable<BPermission> permissions = permissionRepository.findAll(); for (BPermission p : permissions) { role.addPermission(p); } return repository.save(role); }
RoleService { public BRole createDefaultRole() { BRole role = new BRole(dc.getRoleAdminDefaultLabel()); role.setDescription(dc.getRoleAdminDefaultDescription()); role.setEnabled(dc.isRoleAdminDefaultEnabled()); final Iterable<BPermission> permissions = permissionRepository.findAll(); for (BPermission p : permissions) { role.addPermission(p); } return repository.save(role); } }
RoleService { public BRole createDefaultRole() { BRole role = new BRole(dc.getRoleAdminDefaultLabel()); role.setDescription(dc.getRoleAdminDefaultDescription()); role.setEnabled(dc.isRoleAdminDefaultEnabled()); final Iterable<BPermission> permissions = permissionRepository.findAll(); for (BPermission p : permissions) { role.addPermission(p); } return repository.save(role); } }
RoleService { public BRole createDefaultRole() { BRole role = new BRole(dc.getRoleAdminDefaultLabel()); role.setDescription(dc.getRoleAdminDefaultDescription()); role.setEnabled(dc.isRoleAdminDefaultEnabled()); final Iterable<BPermission> permissions = permissionRepository.findAll(); for (BPermission p : permissions) { role.addPermission(p); } return repository.save(role); } BRole createDefaultRole(); List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId); List<Long> removePermissionsFromRole(final long roleId, final Iterable<Long> permissionsId); List<Long> updatePermissionsInRole(final long roleId, final Iterable<Long> permissionsId); BRole getRole(final long id); Page<BPermission> getAllPermissionsByRoleId(final long id, final Pageable pageable); }
RoleService { public BRole createDefaultRole() { BRole role = new BRole(dc.getRoleAdminDefaultLabel()); role.setDescription(dc.getRoleAdminDefaultDescription()); role.setEnabled(dc.isRoleAdminDefaultEnabled()); final Iterable<BPermission> permissions = permissionRepository.findAll(); for (BPermission p : permissions) { role.addPermission(p); } return repository.save(role); } BRole createDefaultRole(); List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId); List<Long> removePermissionsFromRole(final long roleId, final Iterable<Long> permissionsId); List<Long> updatePermissionsInRole(final long roleId, final Iterable<Long> permissionsId); BRole getRole(final long id); Page<BPermission> getAllPermissionsByRoleId(final long id, final Pageable pageable); static final String ROLE_NOT_FOUND; }
@Test public void addPermissionsToRole() { BRole r = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r); BPermission p1 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p1); BPermission p2 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p2); Collection<Long> pIDs = new LinkedList<>(); pIDs.add(p1.getId()); pIDs.add(p2.getId()); try { List<Long> added = roleService.addPermissionsToRole(r.getId(), pIDs); assertEquals(added.size(), pIDs.size()); assertTrue(added.contains(p1.getId())); assertTrue(added.contains(p2.getId())); } catch (NotFoundEntityException e) { LOGGER.error(e.getLocalizedMessage()); fail("Could not add permissions to role"); } }
public List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId) throws NotFoundEntityException { return addRemovePermissionToFromRole(roleId, permissionsId, ActionOverRolePermissions.ADD_PERMISSIONS); }
RoleService { public List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId) throws NotFoundEntityException { return addRemovePermissionToFromRole(roleId, permissionsId, ActionOverRolePermissions.ADD_PERMISSIONS); } }
RoleService { public List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId) throws NotFoundEntityException { return addRemovePermissionToFromRole(roleId, permissionsId, ActionOverRolePermissions.ADD_PERMISSIONS); } }
RoleService { public List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId) throws NotFoundEntityException { return addRemovePermissionToFromRole(roleId, permissionsId, ActionOverRolePermissions.ADD_PERMISSIONS); } BRole createDefaultRole(); List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId); List<Long> removePermissionsFromRole(final long roleId, final Iterable<Long> permissionsId); List<Long> updatePermissionsInRole(final long roleId, final Iterable<Long> permissionsId); BRole getRole(final long id); Page<BPermission> getAllPermissionsByRoleId(final long id, final Pageable pageable); }
RoleService { public List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId) throws NotFoundEntityException { return addRemovePermissionToFromRole(roleId, permissionsId, ActionOverRolePermissions.ADD_PERMISSIONS); } BRole createDefaultRole(); List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId); List<Long> removePermissionsFromRole(final long roleId, final Iterable<Long> permissionsId); List<Long> updatePermissionsInRole(final long roleId, final Iterable<Long> permissionsId); BRole getRole(final long id); Page<BPermission> getAllPermissionsByRoleId(final long id, final Pageable pageable); static final String ROLE_NOT_FOUND; }
@Test public void addPermissionsNotFoundToRole() { BRole r = roleRepository.save(EntityUtil.getSampleRole(random.nextString())); assertNotNull(r); Collection<Long> pIDs = new LinkedList<>(); pIDs.add(INVALID_ID); boolean success = false; try { roleService.addPermissionsToRole(r.getId(), pIDs); } catch (NotFoundEntityException e) { success = true; assertEquals("role.add.permissions.found.none", e.getMessage()); } assertTrue(success); }
public List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId) throws NotFoundEntityException { return addRemovePermissionToFromRole(roleId, permissionsId, ActionOverRolePermissions.ADD_PERMISSIONS); }
RoleService { public List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId) throws NotFoundEntityException { return addRemovePermissionToFromRole(roleId, permissionsId, ActionOverRolePermissions.ADD_PERMISSIONS); } }
RoleService { public List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId) throws NotFoundEntityException { return addRemovePermissionToFromRole(roleId, permissionsId, ActionOverRolePermissions.ADD_PERMISSIONS); } }
RoleService { public List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId) throws NotFoundEntityException { return addRemovePermissionToFromRole(roleId, permissionsId, ActionOverRolePermissions.ADD_PERMISSIONS); } BRole createDefaultRole(); List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId); List<Long> removePermissionsFromRole(final long roleId, final Iterable<Long> permissionsId); List<Long> updatePermissionsInRole(final long roleId, final Iterable<Long> permissionsId); BRole getRole(final long id); Page<BPermission> getAllPermissionsByRoleId(final long id, final Pageable pageable); }
RoleService { public List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId) throws NotFoundEntityException { return addRemovePermissionToFromRole(roleId, permissionsId, ActionOverRolePermissions.ADD_PERMISSIONS); } BRole createDefaultRole(); List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId); List<Long> removePermissionsFromRole(final long roleId, final Iterable<Long> permissionsId); List<Long> updatePermissionsInRole(final long roleId, final Iterable<Long> permissionsId); BRole getRole(final long id); Page<BPermission> getAllPermissionsByRoleId(final long id, final Pageable pageable); static final String ROLE_NOT_FOUND; }
@Test public void getRoleNotFound() { boolean success = false; try { roleService.getRole(INVALID_ID); } catch (NotFoundEntityException e) { success = true; assertEquals(RoleService.ROLE_NOT_FOUND, e.getMessage()); } assertTrue(success); }
public BRole getRole(final long id) throws NotFoundEntityException { Optional<BRole> r = repository.findById(id); if (!r.isPresent()) { throw new NotFoundEntityException(ROLE_NOT_FOUND); } return r.get(); }
RoleService { public BRole getRole(final long id) throws NotFoundEntityException { Optional<BRole> r = repository.findById(id); if (!r.isPresent()) { throw new NotFoundEntityException(ROLE_NOT_FOUND); } return r.get(); } }
RoleService { public BRole getRole(final long id) throws NotFoundEntityException { Optional<BRole> r = repository.findById(id); if (!r.isPresent()) { throw new NotFoundEntityException(ROLE_NOT_FOUND); } return r.get(); } }
RoleService { public BRole getRole(final long id) throws NotFoundEntityException { Optional<BRole> r = repository.findById(id); if (!r.isPresent()) { throw new NotFoundEntityException(ROLE_NOT_FOUND); } return r.get(); } BRole createDefaultRole(); List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId); List<Long> removePermissionsFromRole(final long roleId, final Iterable<Long> permissionsId); List<Long> updatePermissionsInRole(final long roleId, final Iterable<Long> permissionsId); BRole getRole(final long id); Page<BPermission> getAllPermissionsByRoleId(final long id, final Pageable pageable); }
RoleService { public BRole getRole(final long id) throws NotFoundEntityException { Optional<BRole> r = repository.findById(id); if (!r.isPresent()) { throw new NotFoundEntityException(ROLE_NOT_FOUND); } return r.get(); } BRole createDefaultRole(); List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId); List<Long> removePermissionsFromRole(final long roleId, final Iterable<Long> permissionsId); List<Long> updatePermissionsInRole(final long roleId, final Iterable<Long> permissionsId); BRole getRole(final long id); Page<BPermission> getAllPermissionsByRoleId(final long id, final Pageable pageable); static final String ROLE_NOT_FOUND; }
@Test public void removePermissionsFromRole() { BPermission p1 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p1); BPermission p2 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p2); BRole r = EntityUtil.getSampleRole(random.nextString()); r.addPermission(p1, p2); roleRepository.save(r); assertNotNull(r); Collection<Long> pIDs = new LinkedList<>(); pIDs.add(p1.getId()); pIDs.add(p2.getId()); try { List<Long> deleted = roleService.removePermissionsFromRole(r.getId(), pIDs); assertNotNull(deleted); assertEquals(deleted.size(), pIDs.size()); assertTrue(deleted.contains(p1.getId())); assertTrue(deleted.contains(p2.getId())); } catch (NotFoundEntityException e) { LOGGER.error(e.getLocalizedMessage()); fail("Could not remove element"); } }
public List<Long> removePermissionsFromRole(final long roleId, final Iterable<Long> permissionsId) throws NotFoundEntityException { return addRemovePermissionToFromRole(roleId, permissionsId, ActionOverRolePermissions.REMOVE_PERMISSIONS); }
RoleService { public List<Long> removePermissionsFromRole(final long roleId, final Iterable<Long> permissionsId) throws NotFoundEntityException { return addRemovePermissionToFromRole(roleId, permissionsId, ActionOverRolePermissions.REMOVE_PERMISSIONS); } }
RoleService { public List<Long> removePermissionsFromRole(final long roleId, final Iterable<Long> permissionsId) throws NotFoundEntityException { return addRemovePermissionToFromRole(roleId, permissionsId, ActionOverRolePermissions.REMOVE_PERMISSIONS); } }
RoleService { public List<Long> removePermissionsFromRole(final long roleId, final Iterable<Long> permissionsId) throws NotFoundEntityException { return addRemovePermissionToFromRole(roleId, permissionsId, ActionOverRolePermissions.REMOVE_PERMISSIONS); } BRole createDefaultRole(); List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId); List<Long> removePermissionsFromRole(final long roleId, final Iterable<Long> permissionsId); List<Long> updatePermissionsInRole(final long roleId, final Iterable<Long> permissionsId); BRole getRole(final long id); Page<BPermission> getAllPermissionsByRoleId(final long id, final Pageable pageable); }
RoleService { public List<Long> removePermissionsFromRole(final long roleId, final Iterable<Long> permissionsId) throws NotFoundEntityException { return addRemovePermissionToFromRole(roleId, permissionsId, ActionOverRolePermissions.REMOVE_PERMISSIONS); } BRole createDefaultRole(); List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId); List<Long> removePermissionsFromRole(final long roleId, final Iterable<Long> permissionsId); List<Long> updatePermissionsInRole(final long roleId, final Iterable<Long> permissionsId); BRole getRole(final long id); Page<BPermission> getAllPermissionsByRoleId(final long id, final Pageable pageable); static final String ROLE_NOT_FOUND; }
@Test @Transactional public void updatePermissionsInRole() { BPermission p1 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p1); BPermission p2 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p2); BRole r = EntityUtil.getSampleRole(random.nextString()); r.addPermission(p1, p2); assertNotNull(roleRepository.save(r)); assertTrue(r.getPermissions().contains(p1)); assertTrue(r.getPermissions().contains(p2)); BPermission p3 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p3); BPermission p4 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p4); Collection<Long> pIDs = new LinkedList<>(); pIDs.add(p3.getId()); pIDs.add(p4.getId()); try { final List<Long> updated = roleService.updatePermissionsInRole(r.getId(), pIDs); assertNotNull(updated); assertEquals(updated.size(), pIDs.size()); assertTrue(updated.contains(p3.getId())); assertTrue(updated.contains(p4.getId())); assertFalse(updated.contains(p1.getId())); assertFalse(updated.contains(p2.getId())); Optional<BRole> role = roleRepository.findById(r.getId()); assertTrue(role.isPresent()); final Set<BPermission> rPermissions = role.get().getPermissions(); assertFalse(rPermissions.contains(p1)); assertFalse(rPermissions.contains(p2)); assertTrue(rPermissions.contains(p3)); assertTrue(rPermissions.contains(p4)); } catch (NotFoundEntityException e) { LOGGER.error(e.getLocalizedMessage()); fail("Could not update the role permissions"); } }
public List<Long> updatePermissionsInRole(final long roleId, final Iterable<Long> permissionsId) throws NotFoundEntityException { return addRemovePermissionToFromRole(roleId, permissionsId, ActionOverRolePermissions.UPDATE_PERMISSIONS); }
RoleService { public List<Long> updatePermissionsInRole(final long roleId, final Iterable<Long> permissionsId) throws NotFoundEntityException { return addRemovePermissionToFromRole(roleId, permissionsId, ActionOverRolePermissions.UPDATE_PERMISSIONS); } }
RoleService { public List<Long> updatePermissionsInRole(final long roleId, final Iterable<Long> permissionsId) throws NotFoundEntityException { return addRemovePermissionToFromRole(roleId, permissionsId, ActionOverRolePermissions.UPDATE_PERMISSIONS); } }
RoleService { public List<Long> updatePermissionsInRole(final long roleId, final Iterable<Long> permissionsId) throws NotFoundEntityException { return addRemovePermissionToFromRole(roleId, permissionsId, ActionOverRolePermissions.UPDATE_PERMISSIONS); } BRole createDefaultRole(); List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId); List<Long> removePermissionsFromRole(final long roleId, final Iterable<Long> permissionsId); List<Long> updatePermissionsInRole(final long roleId, final Iterable<Long> permissionsId); BRole getRole(final long id); Page<BPermission> getAllPermissionsByRoleId(final long id, final Pageable pageable); }
RoleService { public List<Long> updatePermissionsInRole(final long roleId, final Iterable<Long> permissionsId) throws NotFoundEntityException { return addRemovePermissionToFromRole(roleId, permissionsId, ActionOverRolePermissions.UPDATE_PERMISSIONS); } BRole createDefaultRole(); List<Long> addPermissionsToRole(final long roleId, final Iterable<Long> permissionsId); List<Long> removePermissionsFromRole(final long roleId, final Iterable<Long> permissionsId); List<Long> updatePermissionsInRole(final long roleId, final Iterable<Long> permissionsId); BRole getRole(final long id); Page<BPermission> getAllPermissionsByRoleId(final long id, final Pageable pageable); static final String ROLE_NOT_FOUND; }
@Test public void findPermissionsByUserIdAndEntityId() { EUser u = userRepository.save(EntityUtil.getSampleUser(random.nextString())); assertNotNull(u); EOwnedEntity e = entityRepository.save(EntityUtil.getSampleEntity(random.nextString())); assertNotNull(e); BPermission p1 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p1); BPermission p2 = permissionRepository.save(EntityUtil.getSamplePermission(random.nextString())); assertNotNull(p2); BRole r = EntityUtil.getSampleRole(random.nextString()); r.addPermission(p1, p2); roleRepository.save(r); BAuthorization.BAuthorizationPk pk = new BAuthorization.BAuthorizationPk(u.getId(), e.getId(), r.getId()); assertNotNull(authRepository.save(new BAuthorization(pk, u, e, r))); final List<BPermission> permissions = permissionService.findPermissionsByUserIdAndEntityId(u.getId(), e.getId()); assertTrue(permissions.contains(p1)); assertTrue(permissions.contains(p2)); }
public List<BPermission> findPermissionsByUserIdAndEntityId(final long userId, final long entityId) { return repository.findPermissionsByUserIdAndEntityId(userId, entityId); }
PermissionService { public List<BPermission> findPermissionsByUserIdAndEntityId(final long userId, final long entityId) { return repository.findPermissionsByUserIdAndEntityId(userId, entityId); } }
PermissionService { public List<BPermission> findPermissionsByUserIdAndEntityId(final long userId, final long entityId) { return repository.findPermissionsByUserIdAndEntityId(userId, entityId); } }
PermissionService { public List<BPermission> findPermissionsByUserIdAndEntityId(final long userId, final long entityId) { return repository.findPermissionsByUserIdAndEntityId(userId, entityId); } boolean areDefaultPermissionsCreatedSuccessfully(); List<BPermission> findPermissionsByUserIdAndEntityId(final long userId, final long entityId); Page<BRole> getAllRolesByPermissionId(final long id, final Pageable pageable); }
PermissionService { public List<BPermission> findPermissionsByUserIdAndEntityId(final long userId, final long entityId) { return repository.findPermissionsByUserIdAndEntityId(userId, entityId); } boolean areDefaultPermissionsCreatedSuccessfully(); List<BPermission> findPermissionsByUserIdAndEntityId(final long userId, final long entityId); Page<BRole> getAllRolesByPermissionId(final long id, final Pageable pageable); }
@Test public void getAuthentication() { SecurityContextHolder.clearContext(); SecurityContextHolder.getContext().setAuthentication(auth); final Authentication realAuthInfo = SecurityContextHolder.getContext().getAuthentication(); final Authentication facadeAuthInfo = authFacade.getAuthentication(); assertEquals("(getAuthentication)The \"principal\" set in the authentication in the facade context " + "does not match the \"principal\" set in the authentication in the real context", realAuthInfo.getPrincipal(), facadeAuthInfo.getPrincipal()); assertEquals("(getAuthentication)The \"authorities\" set in the authentication in the facade context" + " does not match the \"authorities\" set in the authentication in the real context", realAuthInfo.getAuthorities(), facadeAuthInfo.getAuthorities()); assertEquals("(getAuthentication)The \"credentials\" set in the authentication in the facade context" + " does not match the \"credentials\" set in the authentication in the real context", realAuthInfo.getCredentials(), facadeAuthInfo.getCredentials()); }
@Override public Authentication getAuthentication() { return SecurityContextHolder.getContext().getAuthentication(); }
AuthenticationFacadeImpl implements AuthenticationFacade { @Override public Authentication getAuthentication() { return SecurityContextHolder.getContext().getAuthentication(); } }
AuthenticationFacadeImpl implements AuthenticationFacade { @Override public Authentication getAuthentication() { return SecurityContextHolder.getContext().getAuthentication(); } }
AuthenticationFacadeImpl implements AuthenticationFacade { @Override public Authentication getAuthentication() { return SecurityContextHolder.getContext().getAuthentication(); } @Override Authentication getAuthentication(); @Override void setAuthentication(final Authentication authentication); }
AuthenticationFacadeImpl implements AuthenticationFacade { @Override public Authentication getAuthentication() { return SecurityContextHolder.getContext().getAuthentication(); } @Override Authentication getAuthentication(); @Override void setAuthentication(final Authentication authentication); }
@Test public void get() { Object field = ReflectionTestUtils.getField(LinkPath.class, "LINK"); String link = field != null ? field.toString() : ""; field = ReflectionTestUtils.getField(LinkPath.class, "HREF"); String href = field != null ? field.toString() : ""; field = ReflectionTestUtils.getField(LinkPath.class, "SELF"); String self = field != null ? field.toString() : ""; Assert.assertEquals(LinkPath.get(self), String.format("%s.%s.%s", link, self, href)); }
public static String get(final String what) { return String.format("%s.%s.%s", LINK, what, HREF); }
LinkPath { public static String get(final String what) { return String.format("%s.%s.%s", LINK, what, HREF); } }
LinkPath { public static String get(final String what) { return String.format("%s.%s.%s", LINK, what, HREF); } private LinkPath(); }
LinkPath { public static String get(final String what) { return String.format("%s.%s.%s", LINK, what, HREF); } private LinkPath(); static String get(final String what); static String getSelf(final String what); static String get(); }
LinkPath { public static String get(final String what) { return String.format("%s.%s.%s", LINK, what, HREF); } private LinkPath(); static String get(final String what); static String getSelf(final String what); static String get(); static final String EMBEDDED; static final String PAGE_SIZE_PARAM_META; static final String PAGE_SORT_PARAM_META; static final String PAGE_PAGE_PARAM_META; }
@Test public void setAuthentication() { SecurityContextHolder.clearContext(); authFacade.setAuthentication(auth); final Authentication realAuthInfo = SecurityContextHolder.getContext().getAuthentication(); final Authentication facadeAuthInfo = authFacade.getAuthentication(); assertEquals("(setAuthentication)The \"principal\" set in the authentication in the facade context " + "does not match the \"principal\" set in the authentication in the real context", realAuthInfo.getPrincipal(), facadeAuthInfo.getPrincipal()); assertEquals("(setAuthentication)The \"authorities\" set in the authentication in the facade context " + "does not match the \"authorities\" set in the authentication in the real context", realAuthInfo.getAuthorities(), facadeAuthInfo.getAuthorities()); assertEquals("(setAuthentication)The \"credentials\" set in the authentication in the facade context " + "does not match the \"credentials\" set in the authentication in the real context", realAuthInfo.getCredentials(), facadeAuthInfo.getCredentials()); }
@Override public void setAuthentication(final Authentication authentication) { SecurityContextHolder.getContext().setAuthentication(authentication); }
AuthenticationFacadeImpl implements AuthenticationFacade { @Override public void setAuthentication(final Authentication authentication) { SecurityContextHolder.getContext().setAuthentication(authentication); } }
AuthenticationFacadeImpl implements AuthenticationFacade { @Override public void setAuthentication(final Authentication authentication) { SecurityContextHolder.getContext().setAuthentication(authentication); } }
AuthenticationFacadeImpl implements AuthenticationFacade { @Override public void setAuthentication(final Authentication authentication) { SecurityContextHolder.getContext().setAuthentication(authentication); } @Override Authentication getAuthentication(); @Override void setAuthentication(final Authentication authentication); }
AuthenticationFacadeImpl implements AuthenticationFacade { @Override public void setAuthentication(final Authentication authentication) { SecurityContextHolder.getContext().setAuthentication(authentication); } @Override Authentication getAuthentication(); @Override void setAuthentication(final Authentication authentication); }
@Test public void getATokenExpirationTime() { final Object aTokenExpirationTime = ReflectionTestUtils.getField(sc, "aTokenExpirationTime"); long prev = aTokenExpirationTime != null ? Long.parseLong(aTokenExpirationTime.toString()) : -1; final long expTime = -10; ReflectionTestUtils.setField(sc, "aTokenExpirationTime", expTime); assertTrue("Expiration time for access token must be greater than zero", jwtService.getATokenExpirationTime() > 0); ReflectionTestUtils.setField(sc, "aTokenExpirationTime", prev); }
public long getATokenExpirationTime() { return sc.getATokenExpirationTime() > 0 ? (sc.getATokenExpirationTime() * THOUSAND) : DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; }
JWTService { public long getATokenExpirationTime() { return sc.getATokenExpirationTime() > 0 ? (sc.getATokenExpirationTime() * THOUSAND) : DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; } }
JWTService { public long getATokenExpirationTime() { return sc.getATokenExpirationTime() > 0 ? (sc.getATokenExpirationTime() * THOUSAND) : DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; } }
JWTService { public long getATokenExpirationTime() { return sc.getATokenExpirationTime() > 0 ? (sc.getATokenExpirationTime() * THOUSAND) : DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt, final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); }
JWTService { public long getATokenExpirationTime() { return sc.getATokenExpirationTime() > 0 ? (sc.getATokenExpirationTime() * THOUSAND) : DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt, final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); static final String AUDIENCE; static final String EXPIRATION; static final String ID; static final String ISSUED_AT; static final String ISSUER; static final String NOT_BEFORE; static final String SUBJECT; static final long DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; static final long DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; }
@Test public void getRTokenExpirationTime() { long prev = Long.parseLong(String.valueOf(ReflectionTestUtils.getField(sc, "rTokenExpirationTime"))); final long expTime = -10; ReflectionTestUtils.setField(sc, "rTokenExpirationTime", expTime); assertTrue("Expiration time for refresh token must be greater than zero", jwtService.getRTokenExpirationTime() > 0); ReflectionTestUtils.setField(sc, "rTokenExpirationTime", prev); }
public long getRTokenExpirationTime() { return sc.getRTokenExpirationTime() > 0 ? (sc.getRTokenExpirationTime() * THOUSAND) : DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; }
JWTService { public long getRTokenExpirationTime() { return sc.getRTokenExpirationTime() > 0 ? (sc.getRTokenExpirationTime() * THOUSAND) : DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; } }
JWTService { public long getRTokenExpirationTime() { return sc.getRTokenExpirationTime() > 0 ? (sc.getRTokenExpirationTime() * THOUSAND) : DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; } }
JWTService { public long getRTokenExpirationTime() { return sc.getRTokenExpirationTime() > 0 ? (sc.getRTokenExpirationTime() * THOUSAND) : DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt, final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); }
JWTService { public long getRTokenExpirationTime() { return sc.getRTokenExpirationTime() > 0 ? (sc.getRTokenExpirationTime() * THOUSAND) : DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt, final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); static final String AUDIENCE; static final String EXPIRATION; static final String ID; static final String ISSUED_AT; static final String ISSUER; static final String NOT_BEFORE; static final String SUBJECT; static final long DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; static final long DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; }
@Test public void createTwoTokensWithSubjectAreNotEqual() { final String sub = "TestSubjectBN"; final String token1 = jwtService.createToken(sub); final String token2 = jwtService.createToken(sub); assertNotEquals("The JWTService#createToken(String subject) method never should create two tokens " + "which are equals", token1, token2); }
public String createToken(final String subject) { return getBuilder(subject).compact(); }
JWTService { public String createToken(final String subject) { return getBuilder(subject).compact(); } }
JWTService { public String createToken(final String subject) { return getBuilder(subject).compact(); } }
JWTService { public String createToken(final String subject) { return getBuilder(subject).compact(); } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt, final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); }
JWTService { public String createToken(final String subject) { return getBuilder(subject).compact(); } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt, final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); static final String AUDIENCE; static final String EXPIRATION; static final String ID; static final String ISSUED_AT; static final String ISSUER; static final String NOT_BEFORE; static final String SUBJECT; static final long DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; static final long DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; }
@Test public void createTwoTokensWithSubjectAndExpAreNotEqual() { final String sub = "TestSubjectCV"; final long exp = 123; final String token1 = jwtService.createToken(sub, exp); final String token2 = jwtService.createToken(sub, exp); assertNotEquals("The JWTService#createToken(String subject, long expiresIn) method never should " + "create two tokens which are equals", token1, token2); }
public String createToken(final String subject) { return getBuilder(subject).compact(); }
JWTService { public String createToken(final String subject) { return getBuilder(subject).compact(); } }
JWTService { public String createToken(final String subject) { return getBuilder(subject).compact(); } }
JWTService { public String createToken(final String subject) { return getBuilder(subject).compact(); } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt, final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); }
JWTService { public String createToken(final String subject) { return getBuilder(subject).compact(); } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt, final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); static final String AUDIENCE; static final String EXPIRATION; static final String ID; static final String ISSUED_AT; static final String ISSUER; static final String NOT_BEFORE; static final String SUBJECT; static final long DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; static final long DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; }
@Test public void createTwoTokensWithSubjectAndAuthAreNotEqual() { final String sub = "TestSubjectRF"; final String auth = "ROLE_WS;ROLE_RF"; final String token1 = jwtService.createToken(sub, auth); final String token2 = jwtService.createToken(sub, auth); assertNotEquals("The JWTService#createToken(String subject, String authorities) method never should " + "create two tokens which are equals", token1, token2); }
public String createToken(final String subject) { return getBuilder(subject).compact(); }
JWTService { public String createToken(final String subject) { return getBuilder(subject).compact(); } }
JWTService { public String createToken(final String subject) { return getBuilder(subject).compact(); } }
JWTService { public String createToken(final String subject) { return getBuilder(subject).compact(); } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt, final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); }
JWTService { public String createToken(final String subject) { return getBuilder(subject).compact(); } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt, final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); static final String AUDIENCE; static final String EXPIRATION; static final String ID; static final String ISSUED_AT; static final String ISSUER; static final String NOT_BEFORE; static final String SUBJECT; static final long DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; static final long DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; }
@Test public void createTwoTokensWithSubjectAuthAndExpAreNotEqual() { final String sub = "TestSubjectBN"; final String auth = "ROLE_GT;ROLE_DE"; final long exp = 123; final String token1 = jwtService.createToken(sub, auth, exp); final String token2 = jwtService.createToken(sub, auth, exp); assertNotEquals("The JWTService#createToken(String subject, String authorities, long expiresIn) " + "method never should create two tokens which are equals", token1, token2); }
public String createToken(final String subject) { return getBuilder(subject).compact(); }
JWTService { public String createToken(final String subject) { return getBuilder(subject).compact(); } }
JWTService { public String createToken(final String subject) { return getBuilder(subject).compact(); } }
JWTService { public String createToken(final String subject) { return getBuilder(subject).compact(); } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt, final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); }
JWTService { public String createToken(final String subject) { return getBuilder(subject).compact(); } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt, final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); static final String AUDIENCE; static final String EXPIRATION; static final String ID; static final String ISSUED_AT; static final String ISSUER; static final String NOT_BEFORE; static final String SUBJECT; static final long DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; static final long DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; }
@Test public void createTwoRefreshTokensWithSubjectAndAuthAreNotEqual() { final String sub = "TestSubjectG"; final String auth = "ROLE_N;ROLE_C"; final String token1 = jwtService.createRefreshToken(sub, auth); final String token2 = jwtService.createRefreshToken(sub, auth); assertNotEquals("The JWTService#createRefreshToken(String subject, String authorities) method never " + "should create two tokens which are equals", token1, token2); }
public String createRefreshToken(final String subject, final String authorities) { return getBuilder(subject, authorities, getRTokenExpirationTime()).compact(); }
JWTService { public String createRefreshToken(final String subject, final String authorities) { return getBuilder(subject, authorities, getRTokenExpirationTime()).compact(); } }
JWTService { public String createRefreshToken(final String subject, final String authorities) { return getBuilder(subject, authorities, getRTokenExpirationTime()).compact(); } }
JWTService { public String createRefreshToken(final String subject, final String authorities) { return getBuilder(subject, authorities, getRTokenExpirationTime()).compact(); } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt, final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); }
JWTService { public String createRefreshToken(final String subject, final String authorities) { return getBuilder(subject, authorities, getRTokenExpirationTime()).compact(); } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt, final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); static final String AUDIENCE; static final String EXPIRATION; static final String ID; static final String ISSUED_AT; static final String ISSUER; static final String NOT_BEFORE; static final String SUBJECT; static final long DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; static final long DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; }
@Test public void getClaims() { final String sub = "TestSubjectX"; final String auth = "ROLE_1;ROLE_2"; final String token = jwtService.createToken(sub, auth); final Map<String, Object> claims = jwtService.getClaims(token, JWTService.SUBJECT, sc.getAuthoritiesHolder(), JWTService.EXPIRATION); assertClaimsState(claims, sub, auth); }
public Map<String, Object> getClaims(final String claimsJwt, final String... key) { Map<String, Object> r = new HashMap<>(); processClaimsJWT(claimsJwt, r, key); return r; }
JWTService { public Map<String, Object> getClaims(final String claimsJwt, final String... key) { Map<String, Object> r = new HashMap<>(); processClaimsJWT(claimsJwt, r, key); return r; } }
JWTService { public Map<String, Object> getClaims(final String claimsJwt, final String... key) { Map<String, Object> r = new HashMap<>(); processClaimsJWT(claimsJwt, r, key); return r; } }
JWTService { public Map<String, Object> getClaims(final String claimsJwt, final String... key) { Map<String, Object> r = new HashMap<>(); processClaimsJWT(claimsJwt, r, key); return r; } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt, final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); }
JWTService { public Map<String, Object> getClaims(final String claimsJwt, final String... key) { Map<String, Object> r = new HashMap<>(); processClaimsJWT(claimsJwt, r, key); return r; } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt, final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); static final String AUDIENCE; static final String EXPIRATION; static final String ID; static final String ISSUED_AT; static final String ISSUER; static final String NOT_BEFORE; static final String SUBJECT; static final long DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; static final long DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; }
@Test public void getClaimsExtended() { final String sub = "TestSubjectY"; final String auth = "ROLE_X;ROLE_Y"; final long expiresIn = 99999999; final String token = jwtService.createToken(sub, auth, expiresIn); final String randomKey = "randomKey"; final Map<String, Object> claims = jwtService.getClaimsExtended(token, randomKey, sc.getAuthoritiesHolder()); assertClaimsState(claims, sub, auth); assertNull("Claims contains an incorrect pair key-value", claims.get(randomKey)); assertNotNull("Expiration time is null", claims.get(JWTService.EXPIRATION)); assertTrue("Expiration time is not an instance of Date", claims.get(JWTService.EXPIRATION) instanceof Date); if (claims.get(JWTService.EXPIRATION) != null && claims.get(JWTService.EXPIRATION) instanceof Date) { assertTrue("Expiration time is not greater than the creation time of the token", ((Date) claims.get(JWTService.EXPIRATION)).getTime() > expiresIn); } }
public Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key) { Map<String, Object> r = new HashMap<>(); Claims claims = processClaimsJWT(claimsJwt, r, key); r.put(AUDIENCE, claims.getAudience()); r.put(EXPIRATION, claims.getExpiration()); r.put(ID, claims.getId()); r.put(ISSUED_AT, claims.getIssuedAt()); r.put(ISSUER, claims.getIssuer()); r.put(NOT_BEFORE, claims.getNotBefore()); r.put(SUBJECT, claims.getSubject()); return r; }
JWTService { public Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key) { Map<String, Object> r = new HashMap<>(); Claims claims = processClaimsJWT(claimsJwt, r, key); r.put(AUDIENCE, claims.getAudience()); r.put(EXPIRATION, claims.getExpiration()); r.put(ID, claims.getId()); r.put(ISSUED_AT, claims.getIssuedAt()); r.put(ISSUER, claims.getIssuer()); r.put(NOT_BEFORE, claims.getNotBefore()); r.put(SUBJECT, claims.getSubject()); return r; } }
JWTService { public Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key) { Map<String, Object> r = new HashMap<>(); Claims claims = processClaimsJWT(claimsJwt, r, key); r.put(AUDIENCE, claims.getAudience()); r.put(EXPIRATION, claims.getExpiration()); r.put(ID, claims.getId()); r.put(ISSUED_AT, claims.getIssuedAt()); r.put(ISSUER, claims.getIssuer()); r.put(NOT_BEFORE, claims.getNotBefore()); r.put(SUBJECT, claims.getSubject()); return r; } }
JWTService { public Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key) { Map<String, Object> r = new HashMap<>(); Claims claims = processClaimsJWT(claimsJwt, r, key); r.put(AUDIENCE, claims.getAudience()); r.put(EXPIRATION, claims.getExpiration()); r.put(ID, claims.getId()); r.put(ISSUED_AT, claims.getIssuedAt()); r.put(ISSUER, claims.getIssuer()); r.put(NOT_BEFORE, claims.getNotBefore()); r.put(SUBJECT, claims.getSubject()); return r; } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt, final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); }
JWTService { public Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key) { Map<String, Object> r = new HashMap<>(); Claims claims = processClaimsJWT(claimsJwt, r, key); r.put(AUDIENCE, claims.getAudience()); r.put(EXPIRATION, claims.getExpiration()); r.put(ID, claims.getId()); r.put(ISSUED_AT, claims.getIssuedAt()); r.put(ISSUER, claims.getIssuer()); r.put(NOT_BEFORE, claims.getNotBefore()); r.put(SUBJECT, claims.getSubject()); return r; } long getATokenExpirationTime(); long getRTokenExpirationTime(); String createToken(final String subject); String createToken(final String subject, final long expiresIn); String createToken(final String subject, final String authorities); String createRefreshToken(final String subject, final String authorities); String createToken(final String subject, final String authorities, final long expiresIn); Map<String, Object> getClaims(final String claimsJwt, final String... key); Map<String, Object> createLoginData(final String subject, final String accessToken, final Date issuedAt, final String authoritiesString, final String refreshToken); Map<String, Object> getClaimsExtended(final String claimsJwt, final String... key); static final String AUDIENCE; static final String EXPIRATION; static final String ID; static final String ISSUED_AT; static final String ISSUER; static final String NOT_BEFORE; static final String SUBJECT; static final long DEFAULT_ACCESS_TOKEN_EXPIRATION_TIME; static final long DEFAULT_REFRESH_TOKEN_EXPIRATION_TIME; }
@Test public void getFreeURLsAnyRequest() { assertArrayEquals(autowiredSc.getFreeURLsAnyRequest(), freeURLsAnyRequestBind.split(SEPARATOR)); }
public String[] getFreeURLsAnyRequest() { return freeURLsAnyRequest.split(";"); }
SecurityConst { public String[] getFreeURLsAnyRequest() { return freeURLsAnyRequest.split(";"); } }
SecurityConst { public String[] getFreeURLsAnyRequest() { return freeURLsAnyRequest.split(";"); } }
SecurityConst { public String[] getFreeURLsAnyRequest() { return freeURLsAnyRequest.split(";"); } String[] getFreeURLsAnyRequest(); String[] getFreeURLsGetRequest(); String[] getFreeURLsPostRequest(); }
SecurityConst { public String[] getFreeURLsAnyRequest() { return freeURLsAnyRequest.split(";"); } String[] getFreeURLsAnyRequest(); String[] getFreeURLsGetRequest(); String[] getFreeURLsPostRequest(); static final String AUTHORITIES_SEPARATOR; static final String ACCESS_TOKEN_URL; static final String USERNAME_HOLDER; static final String USERNAME_REGEXP; }
@Test public void isUserRegistrationAllowed() throws Exception { mvc.perform( get(apiPrefix + "/" + REQ_STRING + "/sign-up") .header(authHeader, tokenType + " " + accessToken) .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) ).andExpect(status().isOk()); }
@GetMapping("sign-up") public boolean isUserRegistrationAllowed() { return configService.isUserRegistrationAllowed(); }
ConfigurationController { @GetMapping("sign-up") public boolean isUserRegistrationAllowed() { return configService.isUserRegistrationAllowed(); } }
ConfigurationController { @GetMapping("sign-up") public boolean isUserRegistrationAllowed() { return configService.isUserRegistrationAllowed(); } }
ConfigurationController { @GetMapping("sign-up") public boolean isUserRegistrationAllowed() { return configService.isUserRegistrationAllowed(); } @GetMapping("sign-up") boolean isUserRegistrationAllowed(); @GetMapping("multientity") boolean isMultiEntity(); @GetMapping Object getConfig(@RequestParam(value = "key", required = false) final String key, @RequestParam(value = "id", required = false) final Long id); @GetMapping("{id}") Map<String, Object> getConfigByUser(@PathVariable(value = "id") final Long id); @RequestMapping(method = {RequestMethod.POST, RequestMethod.PUT}) @ResponseStatus(HttpStatus.NO_CONTENT) void saveConfig(@RequestBody final Map<String, Object> configs); }
ConfigurationController { @GetMapping("sign-up") public boolean isUserRegistrationAllowed() { return configService.isUserRegistrationAllowed(); } @GetMapping("sign-up") boolean isUserRegistrationAllowed(); @GetMapping("multientity") boolean isMultiEntity(); @GetMapping Object getConfig(@RequestParam(value = "key", required = false) final String key, @RequestParam(value = "id", required = false) final Long id); @GetMapping("{id}") Map<String, Object> getConfigByUser(@PathVariable(value = "id") final Long id); @RequestMapping(method = {RequestMethod.POST, RequestMethod.PUT}) @ResponseStatus(HttpStatus.NO_CONTENT) void saveConfig(@RequestBody final Map<String, Object> configs); }
@Test public void isMultiEntity() throws Exception { mvc.perform( get(apiPrefix + "/" + REQ_STRING + "/multientity") .header(authHeader, tokenType + " " + accessToken) .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) ).andExpect(status().isOk()); }
@GetMapping("multientity") public boolean isMultiEntity() { return configService.isMultiEntity(); }
ConfigurationController { @GetMapping("multientity") public boolean isMultiEntity() { return configService.isMultiEntity(); } }
ConfigurationController { @GetMapping("multientity") public boolean isMultiEntity() { return configService.isMultiEntity(); } }
ConfigurationController { @GetMapping("multientity") public boolean isMultiEntity() { return configService.isMultiEntity(); } @GetMapping("sign-up") boolean isUserRegistrationAllowed(); @GetMapping("multientity") boolean isMultiEntity(); @GetMapping Object getConfig(@RequestParam(value = "key", required = false) final String key, @RequestParam(value = "id", required = false) final Long id); @GetMapping("{id}") Map<String, Object> getConfigByUser(@PathVariable(value = "id") final Long id); @RequestMapping(method = {RequestMethod.POST, RequestMethod.PUT}) @ResponseStatus(HttpStatus.NO_CONTENT) void saveConfig(@RequestBody final Map<String, Object> configs); }
ConfigurationController { @GetMapping("multientity") public boolean isMultiEntity() { return configService.isMultiEntity(); } @GetMapping("sign-up") boolean isUserRegistrationAllowed(); @GetMapping("multientity") boolean isMultiEntity(); @GetMapping Object getConfig(@RequestParam(value = "key", required = false) final String key, @RequestParam(value = "id", required = false) final Long id); @GetMapping("{id}") Map<String, Object> getConfigByUser(@PathVariable(value = "id") final Long id); @RequestMapping(method = {RequestMethod.POST, RequestMethod.PUT}) @ResponseStatus(HttpStatus.NO_CONTENT) void saveConfig(@RequestBody final Map<String, Object> configs); }
@Test public void create() throws Exception { final boolean multiEntity = configService.isMultiEntity(); if (!multiEntity) { configService.setIsMultiEntity(true); } EOwnedEntity e = EntityUtil.getSampleEntity(random.nextString()); ConstrainedFields fields = new ConstrainedFields(EOwnedEntity.class); mvc.perform(post(apiPrefix + "/" + REQ_STRING) .contentType(MediaType.APPLICATION_JSON) .header(authHeader, tokenType + " " + accessToken) .content(objectMapper.writeValueAsString(e))) .andExpect(status().isCreated()) .andDo(restDocResHandler.document( requestFields( fields.withPath("name") .description("Natural name which is used commonly for referring to the entity"), fields.withPath("username") .description("A unique string representation of the {@LINK #name}. Useful " + "when there are other entities with the same {@LINK #name}"), fields.withPath("description") .description("A brief description of the entity") ) )); if (!multiEntity) { configService.setIsMultiEntity(false); } }
@PostMapping(path = ResourcePath.OWNED_ENTITY, produces = "application/hal+json") @ResponseStatus(HttpStatus.CREATED) public ResponseEntity<EOwnedEntity> create(@Valid @RequestBody final Resource<EOwnedEntity> entity) throws GmsGeneralException { EOwnedEntity e = entityService.create(entity.getContent()); if (e != null) { return new ResponseEntity<>(HttpStatus.CREATED); } else { throw GmsGeneralException.builder().messageI18N("entity.add.error").finishedOK(false).build(); } }
RestOwnedEntityController { @PostMapping(path = ResourcePath.OWNED_ENTITY, produces = "application/hal+json") @ResponseStatus(HttpStatus.CREATED) public ResponseEntity<EOwnedEntity> create(@Valid @RequestBody final Resource<EOwnedEntity> entity) throws GmsGeneralException { EOwnedEntity e = entityService.create(entity.getContent()); if (e != null) { return new ResponseEntity<>(HttpStatus.CREATED); } else { throw GmsGeneralException.builder().messageI18N("entity.add.error").finishedOK(false).build(); } } }
RestOwnedEntityController { @PostMapping(path = ResourcePath.OWNED_ENTITY, produces = "application/hal+json") @ResponseStatus(HttpStatus.CREATED) public ResponseEntity<EOwnedEntity> create(@Valid @RequestBody final Resource<EOwnedEntity> entity) throws GmsGeneralException { EOwnedEntity e = entityService.create(entity.getContent()); if (e != null) { return new ResponseEntity<>(HttpStatus.CREATED); } else { throw GmsGeneralException.builder().messageI18N("entity.add.error").finishedOK(false).build(); } } }
RestOwnedEntityController { @PostMapping(path = ResourcePath.OWNED_ENTITY, produces = "application/hal+json") @ResponseStatus(HttpStatus.CREATED) public ResponseEntity<EOwnedEntity> create(@Valid @RequestBody final Resource<EOwnedEntity> entity) throws GmsGeneralException { EOwnedEntity e = entityService.create(entity.getContent()); if (e != null) { return new ResponseEntity<>(HttpStatus.CREATED); } else { throw GmsGeneralException.builder().messageI18N("entity.add.error").finishedOK(false).build(); } } @PostMapping(path = ResourcePath.OWNED_ENTITY, produces = "application/hal+json") @ResponseStatus(HttpStatus.CREATED) ResponseEntity<EOwnedEntity> create(@Valid @RequestBody final Resource<EOwnedEntity> entity); }
RestOwnedEntityController { @PostMapping(path = ResourcePath.OWNED_ENTITY, produces = "application/hal+json") @ResponseStatus(HttpStatus.CREATED) public ResponseEntity<EOwnedEntity> create(@Valid @RequestBody final Resource<EOwnedEntity> entity) throws GmsGeneralException { EOwnedEntity e = entityService.create(entity.getContent()); if (e != null) { return new ResponseEntity<>(HttpStatus.CREATED); } else { throw GmsGeneralException.builder().messageI18N("entity.add.error").finishedOK(false).build(); } } @PostMapping(path = ResourcePath.OWNED_ENTITY, produces = "application/hal+json") @ResponseStatus(HttpStatus.CREATED) ResponseEntity<EOwnedEntity> create(@Valid @RequestBody final Resource<EOwnedEntity> entity); }
@Test public void refreshToken() throws Exception { final RefreshTokenPayload payload = new RefreshTokenPayload(refreshToken); final ConstrainedFields fields = new ConstrainedFields(RefreshTokenPayload.class); mvc.perform( post(apiPrefix + "/" + SecurityConst.ACCESS_TOKEN_URL).contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(payload)) ).andExpect(status().isOk()) .andDo( restDocResHandler.document( requestFields( fields.withPath("refreshToken") .description("The refresh token provided when login was " + "previously performed") ) ) ); }
@PostMapping(SecurityConst.ACCESS_TOKEN_URL) public Map<String, Object> refreshToken(@Valid @RequestBody final RefreshTokenPayload payload) { String oldRefreshToken = payload.getRefreshToken(); if (oldRefreshToken != null) { try { String[] keys = {sc.getAuthoritiesHolder()}; Map<String, Object> claims = jwtService.getClaimsExtended(oldRefreshToken, keys); String sub = claims.get(JWTService.SUBJECT).toString(); String authorities = claims.get(keys[0]).toString(); Date iat = (Date) claims.get(JWTService.ISSUED_AT); String newAccessToken = jwtService.createToken(sub, authorities); String newRefreshToken = jwtService.createRefreshToken(sub, authorities); return jwtService.createLoginData(sub, newAccessToken, iat, authorities, newRefreshToken); } catch (JwtException e) { throw new GmsSecurityException(SecurityConst.ACCESS_TOKEN_URL, "security.token.refresh.invalid"); } } throw new GmsSecurityException(SecurityConst.ACCESS_TOKEN_URL, "security.token.refresh.required"); }
SecurityController { @PostMapping(SecurityConst.ACCESS_TOKEN_URL) public Map<String, Object> refreshToken(@Valid @RequestBody final RefreshTokenPayload payload) { String oldRefreshToken = payload.getRefreshToken(); if (oldRefreshToken != null) { try { String[] keys = {sc.getAuthoritiesHolder()}; Map<String, Object> claims = jwtService.getClaimsExtended(oldRefreshToken, keys); String sub = claims.get(JWTService.SUBJECT).toString(); String authorities = claims.get(keys[0]).toString(); Date iat = (Date) claims.get(JWTService.ISSUED_AT); String newAccessToken = jwtService.createToken(sub, authorities); String newRefreshToken = jwtService.createRefreshToken(sub, authorities); return jwtService.createLoginData(sub, newAccessToken, iat, authorities, newRefreshToken); } catch (JwtException e) { throw new GmsSecurityException(SecurityConst.ACCESS_TOKEN_URL, "security.token.refresh.invalid"); } } throw new GmsSecurityException(SecurityConst.ACCESS_TOKEN_URL, "security.token.refresh.required"); } }
SecurityController { @PostMapping(SecurityConst.ACCESS_TOKEN_URL) public Map<String, Object> refreshToken(@Valid @RequestBody final RefreshTokenPayload payload) { String oldRefreshToken = payload.getRefreshToken(); if (oldRefreshToken != null) { try { String[] keys = {sc.getAuthoritiesHolder()}; Map<String, Object> claims = jwtService.getClaimsExtended(oldRefreshToken, keys); String sub = claims.get(JWTService.SUBJECT).toString(); String authorities = claims.get(keys[0]).toString(); Date iat = (Date) claims.get(JWTService.ISSUED_AT); String newAccessToken = jwtService.createToken(sub, authorities); String newRefreshToken = jwtService.createRefreshToken(sub, authorities); return jwtService.createLoginData(sub, newAccessToken, iat, authorities, newRefreshToken); } catch (JwtException e) { throw new GmsSecurityException(SecurityConst.ACCESS_TOKEN_URL, "security.token.refresh.invalid"); } } throw new GmsSecurityException(SecurityConst.ACCESS_TOKEN_URL, "security.token.refresh.required"); } }
SecurityController { @PostMapping(SecurityConst.ACCESS_TOKEN_URL) public Map<String, Object> refreshToken(@Valid @RequestBody final RefreshTokenPayload payload) { String oldRefreshToken = payload.getRefreshToken(); if (oldRefreshToken != null) { try { String[] keys = {sc.getAuthoritiesHolder()}; Map<String, Object> claims = jwtService.getClaimsExtended(oldRefreshToken, keys); String sub = claims.get(JWTService.SUBJECT).toString(); String authorities = claims.get(keys[0]).toString(); Date iat = (Date) claims.get(JWTService.ISSUED_AT); String newAccessToken = jwtService.createToken(sub, authorities); String newRefreshToken = jwtService.createRefreshToken(sub, authorities); return jwtService.createLoginData(sub, newAccessToken, iat, authorities, newRefreshToken); } catch (JwtException e) { throw new GmsSecurityException(SecurityConst.ACCESS_TOKEN_URL, "security.token.refresh.invalid"); } } throw new GmsSecurityException(SecurityConst.ACCESS_TOKEN_URL, "security.token.refresh.required"); } @PostMapping("${gms.security.sign_up_url}") @ResponseStatus(HttpStatus.CREATED) @ResponseBody ResponseEntity<EUser> signUpUser(@RequestBody @Valid final Resource<? extends EUser> user); @PostMapping(SecurityConst.ACCESS_TOKEN_URL) Map<String, Object> refreshToken(@Valid @RequestBody final RefreshTokenPayload payload); }
SecurityController { @PostMapping(SecurityConst.ACCESS_TOKEN_URL) public Map<String, Object> refreshToken(@Valid @RequestBody final RefreshTokenPayload payload) { String oldRefreshToken = payload.getRefreshToken(); if (oldRefreshToken != null) { try { String[] keys = {sc.getAuthoritiesHolder()}; Map<String, Object> claims = jwtService.getClaimsExtended(oldRefreshToken, keys); String sub = claims.get(JWTService.SUBJECT).toString(); String authorities = claims.get(keys[0]).toString(); Date iat = (Date) claims.get(JWTService.ISSUED_AT); String newAccessToken = jwtService.createToken(sub, authorities); String newRefreshToken = jwtService.createRefreshToken(sub, authorities); return jwtService.createLoginData(sub, newAccessToken, iat, authorities, newRefreshToken); } catch (JwtException e) { throw new GmsSecurityException(SecurityConst.ACCESS_TOKEN_URL, "security.token.refresh.invalid"); } } throw new GmsSecurityException(SecurityConst.ACCESS_TOKEN_URL, "security.token.refresh.required"); } @PostMapping("${gms.security.sign_up_url}") @ResponseStatus(HttpStatus.CREATED) @ResponseBody ResponseEntity<EUser> signUpUser(@RequestBody @Valid final Resource<? extends EUser> user); @PostMapping(SecurityConst.ACCESS_TOKEN_URL) Map<String, Object> refreshToken(@Valid @RequestBody final RefreshTokenPayload payload); }
@Test public void getAuthorities() { cleanEntity0(); ReflectionTestUtils.setField(entity0, "authorities", authoritiesS); assertArrayEquals(entity0.getAuthorities().toArray(), authoritiesS.toArray()); }
@Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities != null ? Collections.unmodifiableCollection(authorities) : null; }
EUser extends GmsEntity implements UserDetails { @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities != null ? Collections.unmodifiableCollection(authorities) : null; } }
EUser extends GmsEntity implements UserDetails { @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities != null ? Collections.unmodifiableCollection(authorities) : null; } EUser(final String username, final String email, final String name, final String lastName, final String password); }
EUser extends GmsEntity implements UserDetails { @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities != null ? Collections.unmodifiableCollection(authorities) : null; } EUser(final String username, final String email, final String name, final String lastName, final String password); @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); boolean isEmailVerified(); }
EUser extends GmsEntity implements UserDetails { @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities != null ? Collections.unmodifiableCollection(authorities) : null; } EUser(final String username, final String email, final String name, final String lastName, final String password); @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); boolean isEmailVerified(); }
@Test public void isAccountNonExpired() { cleanEntity0(); ReflectionTestUtils.setField(entity0, "accountNonExpired", accountNonExpiredS); assertEquals(entity0.isAccountNonExpired(), accountNonExpiredS); }
@Override public boolean isAccountNonExpired() { return accountNonExpired == null || accountNonExpired; }
EUser extends GmsEntity implements UserDetails { @Override public boolean isAccountNonExpired() { return accountNonExpired == null || accountNonExpired; } }
EUser extends GmsEntity implements UserDetails { @Override public boolean isAccountNonExpired() { return accountNonExpired == null || accountNonExpired; } EUser(final String username, final String email, final String name, final String lastName, final String password); }
EUser extends GmsEntity implements UserDetails { @Override public boolean isAccountNonExpired() { return accountNonExpired == null || accountNonExpired; } EUser(final String username, final String email, final String name, final String lastName, final String password); @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); boolean isEmailVerified(); }
EUser extends GmsEntity implements UserDetails { @Override public boolean isAccountNonExpired() { return accountNonExpired == null || accountNonExpired; } EUser(final String username, final String email, final String name, final String lastName, final String password); @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); boolean isEmailVerified(); }
@Test public void isAccountNonLocked() { cleanEntity0(); ReflectionTestUtils.setField(entity0, "accountNonLocked", accountNonLockedS); assertEquals(entity0.isAccountNonLocked(), accountNonLockedS); }
@Override public boolean isAccountNonLocked() { return accountNonLocked == null || accountNonLocked; }
EUser extends GmsEntity implements UserDetails { @Override public boolean isAccountNonLocked() { return accountNonLocked == null || accountNonLocked; } }
EUser extends GmsEntity implements UserDetails { @Override public boolean isAccountNonLocked() { return accountNonLocked == null || accountNonLocked; } EUser(final String username, final String email, final String name, final String lastName, final String password); }
EUser extends GmsEntity implements UserDetails { @Override public boolean isAccountNonLocked() { return accountNonLocked == null || accountNonLocked; } EUser(final String username, final String email, final String name, final String lastName, final String password); @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); boolean isEmailVerified(); }
EUser extends GmsEntity implements UserDetails { @Override public boolean isAccountNonLocked() { return accountNonLocked == null || accountNonLocked; } EUser(final String username, final String email, final String name, final String lastName, final String password); @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); boolean isEmailVerified(); }
@Test public void isCredentialsNonExpired() { cleanEntity0(); ReflectionTestUtils.setField(entity0, "credentialsNonExpired", credentialsNonExpiredS); assertEquals(entity0.isCredentialsNonExpired(), credentialsNonExpiredS); }
@Override public boolean isCredentialsNonExpired() { return credentialsNonExpired == null || credentialsNonExpired; }
EUser extends GmsEntity implements UserDetails { @Override public boolean isCredentialsNonExpired() { return credentialsNonExpired == null || credentialsNonExpired; } }
EUser extends GmsEntity implements UserDetails { @Override public boolean isCredentialsNonExpired() { return credentialsNonExpired == null || credentialsNonExpired; } EUser(final String username, final String email, final String name, final String lastName, final String password); }
EUser extends GmsEntity implements UserDetails { @Override public boolean isCredentialsNonExpired() { return credentialsNonExpired == null || credentialsNonExpired; } EUser(final String username, final String email, final String name, final String lastName, final String password); @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); boolean isEmailVerified(); }
EUser extends GmsEntity implements UserDetails { @Override public boolean isCredentialsNonExpired() { return credentialsNonExpired == null || credentialsNonExpired; } EUser(final String username, final String email, final String name, final String lastName, final String password); @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); boolean isEmailVerified(); }
@Test public void isEnabled() { cleanEntity0(); ReflectionTestUtils.setField(entity0, "enabled", enabledS); assertEquals(entity0.isEnabled(), enabledS); }
@Override public boolean isEnabled() { return enabled != null && enabled; }
EUser extends GmsEntity implements UserDetails { @Override public boolean isEnabled() { return enabled != null && enabled; } }
EUser extends GmsEntity implements UserDetails { @Override public boolean isEnabled() { return enabled != null && enabled; } EUser(final String username, final String email, final String name, final String lastName, final String password); }
EUser extends GmsEntity implements UserDetails { @Override public boolean isEnabled() { return enabled != null && enabled; } EUser(final String username, final String email, final String name, final String lastName, final String password); @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); boolean isEmailVerified(); }
EUser extends GmsEntity implements UserDetails { @Override public boolean isEnabled() { return enabled != null && enabled; } EUser(final String username, final String email, final String name, final String lastName, final String password); @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); boolean isEmailVerified(); }
@Test public void isEmailVerified() { cleanEntity0(); ReflectionTestUtils.setField(entity0, "emailVerified", emailVerifiedS); assertEquals(entity0.isEmailVerified(), emailVerifiedS); }
public boolean isEmailVerified() { return emailVerified != null && emailVerified; }
EUser extends GmsEntity implements UserDetails { public boolean isEmailVerified() { return emailVerified != null && emailVerified; } }
EUser extends GmsEntity implements UserDetails { public boolean isEmailVerified() { return emailVerified != null && emailVerified; } EUser(final String username, final String email, final String name, final String lastName, final String password); }
EUser extends GmsEntity implements UserDetails { public boolean isEmailVerified() { return emailVerified != null && emailVerified; } EUser(final String username, final String email, final String name, final String lastName, final String password); @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); boolean isEmailVerified(); }
EUser extends GmsEntity implements UserDetails { public boolean isEmailVerified() { return emailVerified != null && emailVerified; } EUser(final String username, final String email, final String name, final String lastName, final String password); @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); boolean isEmailVerified(); }
@Test public void getFreeURLsGetRequest() { assertArrayEquals(autowiredSc.getFreeURLsGetRequest(), freeURLsGetRequestBind.split(SEPARATOR)); }
public String[] getFreeURLsGetRequest() { return freeURLsGetRequest.split(";"); }
SecurityConst { public String[] getFreeURLsGetRequest() { return freeURLsGetRequest.split(";"); } }
SecurityConst { public String[] getFreeURLsGetRequest() { return freeURLsGetRequest.split(";"); } }
SecurityConst { public String[] getFreeURLsGetRequest() { return freeURLsGetRequest.split(";"); } String[] getFreeURLsAnyRequest(); String[] getFreeURLsGetRequest(); String[] getFreeURLsPostRequest(); }
SecurityConst { public String[] getFreeURLsGetRequest() { return freeURLsGetRequest.split(";"); } String[] getFreeURLsAnyRequest(); String[] getFreeURLsGetRequest(); String[] getFreeURLsPostRequest(); static final String AUTHORITIES_SEPARATOR; static final String ACCESS_TOKEN_URL; static final String USERNAME_HOLDER; static final String USERNAME_REGEXP; }
@Test public void addPermission() { cleanEntity0(); entity0.addPermission(sampleP); final Collection<?> permissions = (HashSet<?>) ReflectionTestUtils.getField(entity0, "permissions"); assertTrue(permissions != null && permissions.contains(sampleP)); }
public void addPermission(final BPermission... p) { if (permissions == null) { permissions = new HashSet<>(); } permissions.addAll(Arrays.asList(p)); }
BRole extends GmsEntity { public void addPermission(final BPermission... p) { if (permissions == null) { permissions = new HashSet<>(); } permissions.addAll(Arrays.asList(p)); } }
BRole extends GmsEntity { public void addPermission(final BPermission... p) { if (permissions == null) { permissions = new HashSet<>(); } permissions.addAll(Arrays.asList(p)); } }
BRole extends GmsEntity { public void addPermission(final BPermission... p) { if (permissions == null) { permissions = new HashSet<>(); } permissions.addAll(Arrays.asList(p)); } void addPermission(final BPermission... p); void removePermission(final BPermission... p); void removeAllPermissions(); }
BRole extends GmsEntity { public void addPermission(final BPermission... p) { if (permissions == null) { permissions = new HashSet<>(); } permissions.addAll(Arrays.asList(p)); } void addPermission(final BPermission... p); void removePermission(final BPermission... p); void removeAllPermissions(); }
@Test public void removePermission() { Collection<BPermission> auxP = new HashSet<>(); auxP.add(sampleP); cleanEntity0(); ReflectionTestUtils.setField(entity0, "permissions", auxP); Collection<?> permissions = (HashSet<?>) ReflectionTestUtils.getField(entity0, "permissions"); assertTrue(permissions != null && permissions.contains(sampleP)); entity0.removePermission(sampleP); permissions = (HashSet<?>) ReflectionTestUtils.getField(entity0, "permissions"); assertTrue(permissions != null && !permissions.contains(sampleP)); }
public void removePermission(final BPermission... p) { if (permissions != null) { for (BPermission iP : p) { permissions.remove(iP); } } }
BRole extends GmsEntity { public void removePermission(final BPermission... p) { if (permissions != null) { for (BPermission iP : p) { permissions.remove(iP); } } } }
BRole extends GmsEntity { public void removePermission(final BPermission... p) { if (permissions != null) { for (BPermission iP : p) { permissions.remove(iP); } } } }
BRole extends GmsEntity { public void removePermission(final BPermission... p) { if (permissions != null) { for (BPermission iP : p) { permissions.remove(iP); } } } void addPermission(final BPermission... p); void removePermission(final BPermission... p); void removeAllPermissions(); }
BRole extends GmsEntity { public void removePermission(final BPermission... p) { if (permissions != null) { for (BPermission iP : p) { permissions.remove(iP); } } } void addPermission(final BPermission... p); void removePermission(final BPermission... p); void removeAllPermissions(); }
@Test public void mainTest() { Runnable runnable = () -> Application.main(noArgs); Thread thread = new Thread(runnable); thread.start(); }
public static void main(final String[] args) { SpringApplication.run(Application.class, args); GMS_LOGGER.info("Application is running..."); }
Application extends SpringBootServletInitializer { public static void main(final String[] args) { SpringApplication.run(Application.class, args); GMS_LOGGER.info("Application is running..."); } }
Application extends SpringBootServletInitializer { public static void main(final String[] args) { SpringApplication.run(Application.class, args); GMS_LOGGER.info("Application is running..."); } }
Application extends SpringBootServletInitializer { public static void main(final String[] args) { SpringApplication.run(Application.class, args); GMS_LOGGER.info("Application is running..."); } static void main(final String[] args); @Bean CommandLineRunner commandLineRunner(final AppService appService); @Bean BCryptPasswordEncoder bCryptPasswordEncoder(); @Bean ErrorPageRegistrar errorPageRegistrar(); }
Application extends SpringBootServletInitializer { public static void main(final String[] args) { SpringApplication.run(Application.class, args); GMS_LOGGER.info("Application is running..."); } static void main(final String[] args); @Bean CommandLineRunner commandLineRunner(final AppService appService); @Bean BCryptPasswordEncoder bCryptPasswordEncoder(); @Bean ErrorPageRegistrar errorPageRegistrar(); }
@Test public void configureTest() { Application app = new Application(); assertNotNull(app.configure(new SpringApplicationBuilder(Application.class))); }
@Override protected SpringApplicationBuilder configure(final SpringApplicationBuilder builder) { return builder.sources(Application.class); }
Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(final SpringApplicationBuilder builder) { return builder.sources(Application.class); } }
Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(final SpringApplicationBuilder builder) { return builder.sources(Application.class); } }
Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(final SpringApplicationBuilder builder) { return builder.sources(Application.class); } static void main(final String[] args); @Bean CommandLineRunner commandLineRunner(final AppService appService); @Bean BCryptPasswordEncoder bCryptPasswordEncoder(); @Bean ErrorPageRegistrar errorPageRegistrar(); }
Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(final SpringApplicationBuilder builder) { return builder.sources(Application.class); } static void main(final String[] args); @Bean CommandLineRunner commandLineRunner(final AppService appService); @Bean BCryptPasswordEncoder bCryptPasswordEncoder(); @Bean ErrorPageRegistrar errorPageRegistrar(); }
@Test public void commandLineRunnerBeanCreationIsOK() { Application app = new Application(); assertNotNull(app.commandLineRunner(appService)); }
@Bean public CommandLineRunner commandLineRunner(final AppService appService) { return strings -> { if (!appService.isInitialLoadOK()) { GMS_LOGGER.error("App did not start properly and probably will fail at some point. Restarting it is " + "highly advisable"); } }; }
Application extends SpringBootServletInitializer { @Bean public CommandLineRunner commandLineRunner(final AppService appService) { return strings -> { if (!appService.isInitialLoadOK()) { GMS_LOGGER.error("App did not start properly and probably will fail at some point. Restarting it is " + "highly advisable"); } }; } }
Application extends SpringBootServletInitializer { @Bean public CommandLineRunner commandLineRunner(final AppService appService) { return strings -> { if (!appService.isInitialLoadOK()) { GMS_LOGGER.error("App did not start properly and probably will fail at some point. Restarting it is " + "highly advisable"); } }; } }
Application extends SpringBootServletInitializer { @Bean public CommandLineRunner commandLineRunner(final AppService appService) { return strings -> { if (!appService.isInitialLoadOK()) { GMS_LOGGER.error("App did not start properly and probably will fail at some point. Restarting it is " + "highly advisable"); } }; } static void main(final String[] args); @Bean CommandLineRunner commandLineRunner(final AppService appService); @Bean BCryptPasswordEncoder bCryptPasswordEncoder(); @Bean ErrorPageRegistrar errorPageRegistrar(); }
Application extends SpringBootServletInitializer { @Bean public CommandLineRunner commandLineRunner(final AppService appService) { return strings -> { if (!appService.isInitialLoadOK()) { GMS_LOGGER.error("App did not start properly and probably will fail at some point. Restarting it is " + "highly advisable"); } }; } static void main(final String[] args); @Bean CommandLineRunner commandLineRunner(final AppService appService); @Bean BCryptPasswordEncoder bCryptPasswordEncoder(); @Bean ErrorPageRegistrar errorPageRegistrar(); }
@Test public void bCryptPasswordEncoderTest() { Application app = new Application(); assertNotNull(app.bCryptPasswordEncoder()); }
@Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); }
Application extends SpringBootServletInitializer { @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } }
Application extends SpringBootServletInitializer { @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } }
Application extends SpringBootServletInitializer { @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } static void main(final String[] args); @Bean CommandLineRunner commandLineRunner(final AppService appService); @Bean BCryptPasswordEncoder bCryptPasswordEncoder(); @Bean ErrorPageRegistrar errorPageRegistrar(); }
Application extends SpringBootServletInitializer { @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } static void main(final String[] args); @Bean CommandLineRunner commandLineRunner(final AppService appService); @Bean BCryptPasswordEncoder bCryptPasswordEncoder(); @Bean ErrorPageRegistrar errorPageRegistrar(); }