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 testWebserviceProtocol() throws Exception { DemoService service = new DemoServiceImpl(); protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("webservice: service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("webservice: assertEquals(service.create(1, "kk").getName(), "kk"); assertEquals(service.getSize(null), -1); assertEquals(service.getSize(new String[]{"", "", ""}), 3); Object object = service.invoke("webservice: System.out.println(object); assertEquals("webservice: StringBuffer buf = new StringBuffer(); for (int i = 0; i < 1024 * 32 + 32; i++) buf.append('A'); assertEquals(32800, service.stringLength(buf.toString())); }
public WebServiceProtocol() { super(Fault.class); bus.setExtension(new ServletDestinationFactory(), HttpDestinationFactory.class); }
WebServiceProtocol extends AbstractProxyProtocol { public WebServiceProtocol() { super(Fault.class); bus.setExtension(new ServletDestinationFactory(), HttpDestinationFactory.class); } }
WebServiceProtocol extends AbstractProxyProtocol { public WebServiceProtocol() { super(Fault.class); bus.setExtension(new ServletDestinationFactory(), HttpDestinationFactory.class); } WebServiceProtocol(); }
WebServiceProtocol extends AbstractProxyProtocol { public WebServiceProtocol() { super(Fault.class); bus.setExtension(new ServletDestinationFactory(), HttpDestinationFactory.class); } WebServiceProtocol(); void setHttpBinder(HttpBinder httpBinder); @Override int getDefaultPort(); }
WebServiceProtocol extends AbstractProxyProtocol { public WebServiceProtocol() { super(Fault.class); bus.setExtension(new ServletDestinationFactory(), HttpDestinationFactory.class); } WebServiceProtocol(); void setHttpBinder(HttpBinder httpBinder); @Override int getDefaultPort(); static final int DEFAULT_PORT; }
@Test public void onRetainCustomNonConfigurationInstance_THEN_return_dagger_component() throws Exception { assertThat(tested.onRetainCustomNonConfigurationInstance()).isEqualTo(tested.daggerComponent); }
public Object onRetainCustomNonConfigurationInstance() { return daggerComponent; }
DaggerLifecycleDelegate { public Object onRetainCustomNonConfigurationInstance() { return daggerComponent; } }
DaggerLifecycleDelegate { public Object onRetainCustomNonConfigurationInstance() { return daggerComponent; } DaggerLifecycleDelegate(@NonNull DaggerComponentFactory<T> daggerComponentFactory); }
DaggerLifecycleDelegate { public Object onRetainCustomNonConfigurationInstance() { return daggerComponent; } DaggerLifecycleDelegate(@NonNull DaggerComponentFactory<T> daggerComponentFactory); @SuppressWarnings("unchecked") void onCreate(AppCompatActivity activity); Object onRetainCustomNonConfigurationInstance(); T daggerComponent(); }
DaggerLifecycleDelegate { public Object onRetainCustomNonConfigurationInstance() { return daggerComponent; } DaggerLifecycleDelegate(@NonNull DaggerComponentFactory<T> daggerComponentFactory); @SuppressWarnings("unchecked") void onCreate(AppCompatActivity activity); Object onRetainCustomNonConfigurationInstance(); T daggerComponent(); }
@Test public void daggerComponent_THEN_return_dagger_component() throws Exception { assertThat(tested.daggerComponent()).isEqualTo(tested.daggerComponent); }
public T daggerComponent() { return daggerComponent; }
DaggerLifecycleDelegate { public T daggerComponent() { return daggerComponent; } }
DaggerLifecycleDelegate { public T daggerComponent() { return daggerComponent; } DaggerLifecycleDelegate(@NonNull DaggerComponentFactory<T> daggerComponentFactory); }
DaggerLifecycleDelegate { public T daggerComponent() { return daggerComponent; } DaggerLifecycleDelegate(@NonNull DaggerComponentFactory<T> daggerComponentFactory); @SuppressWarnings("unchecked") void onCreate(AppCompatActivity activity); Object onRetainCustomNonConfigurationInstance(); T daggerComponent(); }
DaggerLifecycleDelegate { public T daggerComponent() { return daggerComponent; } DaggerLifecycleDelegate(@NonNull DaggerComponentFactory<T> daggerComponentFactory); @SuppressWarnings("unchecked") void onCreate(AppCompatActivity activity); Object onRetainCustomNonConfigurationInstance(); T daggerComponent(); }
@Test public void should_return_concatenated_list() throws Exception { assertThat(CollectionsX.concat(Arrays.asList(1, 2, 3), Arrays.asList(4, 5, 6))) .isEqualTo(Arrays.asList(1, 2, 3, 4, 5, 6)); }
public static <T> List<T> concat(@NonNull List<T> list1, @NonNull List<T> list2) { final ArrayList<T> list = new ArrayList<>(list1.size() + list2.size()); if (!list1.isEmpty()) { list.addAll(list1); } if (!list2.isEmpty()) { list.addAll(list2); } return list; }
CollectionsX { public static <T> List<T> concat(@NonNull List<T> list1, @NonNull List<T> list2) { final ArrayList<T> list = new ArrayList<>(list1.size() + list2.size()); if (!list1.isEmpty()) { list.addAll(list1); } if (!list2.isEmpty()) { list.addAll(list2); } return list; } }
CollectionsX { public static <T> List<T> concat(@NonNull List<T> list1, @NonNull List<T> list2) { final ArrayList<T> list = new ArrayList<>(list1.size() + list2.size()); if (!list1.isEmpty()) { list.addAll(list1); } if (!list2.isEmpty()) { list.addAll(list2); } return list; } private CollectionsX(); }
CollectionsX { public static <T> List<T> concat(@NonNull List<T> list1, @NonNull List<T> list2) { final ArrayList<T> list = new ArrayList<>(list1.size() + list2.size()); if (!list1.isEmpty()) { list.addAll(list1); } if (!list2.isEmpty()) { list.addAll(list2); } return list; } private CollectionsX(); static List<T> concat(@NonNull List<T> list1, @NonNull List<T> list2); }
CollectionsX { public static <T> List<T> concat(@NonNull List<T> list1, @NonNull List<T> list2) { final ArrayList<T> list = new ArrayList<>(list1.size() + list2.size()); if (!list1.isEmpty()) { list.addAll(list1); } if (!list2.isEmpty()) { list.addAll(list2); } return list; } private CollectionsX(); static List<T> concat(@NonNull List<T> list1, @NonNull List<T> list2); }
@Test public void should_return_loginIntent() throws Exception { tested.loginIntent(mockedContext); verify(mockedIntentFactory).create(mockedContext, LoginActivity.class); }
public Intent loginIntent(Context context) { return intentFactory.create(context, LoginActivity.class); }
AppRouter { public Intent loginIntent(Context context) { return intentFactory.create(context, LoginActivity.class); } }
AppRouter { public Intent loginIntent(Context context) { return intentFactory.create(context, LoginActivity.class); } AppRouter(); @VisibleForTesting AppRouter(IntentFactory intentFactory); }
AppRouter { public Intent loginIntent(Context context) { return intentFactory.create(context, LoginActivity.class); } AppRouter(); @VisibleForTesting AppRouter(IntentFactory intentFactory); Intent loginIntent(Context context); }
AppRouter { public Intent loginIntent(Context context) { return intentFactory.create(context, LoginActivity.class); } AppRouter(); @VisibleForTesting AppRouter(IntentFactory intentFactory); Intent loginIntent(Context context); }
@Test public void should_return_false_when_email_is_null() throws Exception { assertThat(tested.isValid(null)).isFalse(); }
public boolean isValid(CharSequence email) { return email != null && EMAIL_ADDRESS.matcher(email).matches(); }
EmailValidator { public boolean isValid(CharSequence email) { return email != null && EMAIL_ADDRESS.matcher(email).matches(); } }
EmailValidator { public boolean isValid(CharSequence email) { return email != null && EMAIL_ADDRESS.matcher(email).matches(); } }
EmailValidator { public boolean isValid(CharSequence email) { return email != null && EMAIL_ADDRESS.matcher(email).matches(); } boolean isValid(CharSequence email); Observable<Boolean> checkEmail(CharSequence email); }
EmailValidator { public boolean isValid(CharSequence email) { return email != null && EMAIL_ADDRESS.matcher(email).matches(); } boolean isValid(CharSequence email); Observable<Boolean> checkEmail(CharSequence email); }
@Test public void should_return_false_when_email_is_invalid() throws Exception { assertThat(tested.isValid("abc")).isFalse(); }
public boolean isValid(CharSequence email) { return email != null && EMAIL_ADDRESS.matcher(email).matches(); }
EmailValidator { public boolean isValid(CharSequence email) { return email != null && EMAIL_ADDRESS.matcher(email).matches(); } }
EmailValidator { public boolean isValid(CharSequence email) { return email != null && EMAIL_ADDRESS.matcher(email).matches(); } }
EmailValidator { public boolean isValid(CharSequence email) { return email != null && EMAIL_ADDRESS.matcher(email).matches(); } boolean isValid(CharSequence email); Observable<Boolean> checkEmail(CharSequence email); }
EmailValidator { public boolean isValid(CharSequence email) { return email != null && EMAIL_ADDRESS.matcher(email).matches(); } boolean isValid(CharSequence email); Observable<Boolean> checkEmail(CharSequence email); }
@Test public void should_return_true_when_email_is_valid() throws Exception { assertThat(tested.isValid("[email protected]")).isTrue(); }
public boolean isValid(CharSequence email) { return email != null && EMAIL_ADDRESS.matcher(email).matches(); }
EmailValidator { public boolean isValid(CharSequence email) { return email != null && EMAIL_ADDRESS.matcher(email).matches(); } }
EmailValidator { public boolean isValid(CharSequence email) { return email != null && EMAIL_ADDRESS.matcher(email).matches(); } }
EmailValidator { public boolean isValid(CharSequence email) { return email != null && EMAIL_ADDRESS.matcher(email).matches(); } boolean isValid(CharSequence email); Observable<Boolean> checkEmail(CharSequence email); }
EmailValidator { public boolean isValid(CharSequence email) { return email != null && EMAIL_ADDRESS.matcher(email).matches(); } boolean isValid(CharSequence email); Observable<Boolean> checkEmail(CharSequence email); }
@Test public void testPolicyConditionCacheConfigDisabled() { assertThat(this.policyConditionCacheConfig.conditionCache(true), instanceOf(NonCachingGroovyConditionCache.class)); }
@Bean public GroovyConditionCache conditionCache( @Value("${ENABLE_DECISION_CACHING:true}") final boolean decisionCachingEnabled) { if (decisionCachingEnabled) { LOGGER.info( "In-memory condition caching disabled for policy evaluation (superseded by decision caching)."); return new NonCachingGroovyConditionCache(); } LOGGER.info("In-memory condition caching enabled for policy evaluation."); return new InMemoryGroovyConditionCache(); }
PolicyConditionCacheConfig { @Bean public GroovyConditionCache conditionCache( @Value("${ENABLE_DECISION_CACHING:true}") final boolean decisionCachingEnabled) { if (decisionCachingEnabled) { LOGGER.info( "In-memory condition caching disabled for policy evaluation (superseded by decision caching)."); return new NonCachingGroovyConditionCache(); } LOGGER.info("In-memory condition caching enabled for policy evaluation."); return new InMemoryGroovyConditionCache(); } }
PolicyConditionCacheConfig { @Bean public GroovyConditionCache conditionCache( @Value("${ENABLE_DECISION_CACHING:true}") final boolean decisionCachingEnabled) { if (decisionCachingEnabled) { LOGGER.info( "In-memory condition caching disabled for policy evaluation (superseded by decision caching)."); return new NonCachingGroovyConditionCache(); } LOGGER.info("In-memory condition caching enabled for policy evaluation."); return new InMemoryGroovyConditionCache(); } }
PolicyConditionCacheConfig { @Bean public GroovyConditionCache conditionCache( @Value("${ENABLE_DECISION_CACHING:true}") final boolean decisionCachingEnabled) { if (decisionCachingEnabled) { LOGGER.info( "In-memory condition caching disabled for policy evaluation (superseded by decision caching)."); return new NonCachingGroovyConditionCache(); } LOGGER.info("In-memory condition caching enabled for policy evaluation."); return new InMemoryGroovyConditionCache(); } @Bean GroovyConditionCache conditionCache( @Value("${ENABLE_DECISION_CACHING:true}") final boolean decisionCachingEnabled); }
PolicyConditionCacheConfig { @Bean public GroovyConditionCache conditionCache( @Value("${ENABLE_DECISION_CACHING:true}") final boolean decisionCachingEnabled) { if (decisionCachingEnabled) { LOGGER.info( "In-memory condition caching disabled for policy evaluation (superseded by decision caching)."); return new NonCachingGroovyConditionCache(); } LOGGER.info("In-memory condition caching enabled for policy evaluation."); return new InMemoryGroovyConditionCache(); } @Bean GroovyConditionCache conditionCache( @Value("${ENABLE_DECISION_CACHING:true}") final boolean decisionCachingEnabled); }
@Test public void testPolicyConditionCacheConfigEnabled() { assertThat(this.policyConditionCacheConfig.conditionCache(false), instanceOf(InMemoryGroovyConditionCache.class)); }
@Bean public GroovyConditionCache conditionCache( @Value("${ENABLE_DECISION_CACHING:true}") final boolean decisionCachingEnabled) { if (decisionCachingEnabled) { LOGGER.info( "In-memory condition caching disabled for policy evaluation (superseded by decision caching)."); return new NonCachingGroovyConditionCache(); } LOGGER.info("In-memory condition caching enabled for policy evaluation."); return new InMemoryGroovyConditionCache(); }
PolicyConditionCacheConfig { @Bean public GroovyConditionCache conditionCache( @Value("${ENABLE_DECISION_CACHING:true}") final boolean decisionCachingEnabled) { if (decisionCachingEnabled) { LOGGER.info( "In-memory condition caching disabled for policy evaluation (superseded by decision caching)."); return new NonCachingGroovyConditionCache(); } LOGGER.info("In-memory condition caching enabled for policy evaluation."); return new InMemoryGroovyConditionCache(); } }
PolicyConditionCacheConfig { @Bean public GroovyConditionCache conditionCache( @Value("${ENABLE_DECISION_CACHING:true}") final boolean decisionCachingEnabled) { if (decisionCachingEnabled) { LOGGER.info( "In-memory condition caching disabled for policy evaluation (superseded by decision caching)."); return new NonCachingGroovyConditionCache(); } LOGGER.info("In-memory condition caching enabled for policy evaluation."); return new InMemoryGroovyConditionCache(); } }
PolicyConditionCacheConfig { @Bean public GroovyConditionCache conditionCache( @Value("${ENABLE_DECISION_CACHING:true}") final boolean decisionCachingEnabled) { if (decisionCachingEnabled) { LOGGER.info( "In-memory condition caching disabled for policy evaluation (superseded by decision caching)."); return new NonCachingGroovyConditionCache(); } LOGGER.info("In-memory condition caching enabled for policy evaluation."); return new InMemoryGroovyConditionCache(); } @Bean GroovyConditionCache conditionCache( @Value("${ENABLE_DECISION_CACHING:true}") final boolean decisionCachingEnabled); }
PolicyConditionCacheConfig { @Bean public GroovyConditionCache conditionCache( @Value("${ENABLE_DECISION_CACHING:true}") final boolean decisionCachingEnabled) { if (decisionCachingEnabled) { LOGGER.info( "In-memory condition caching disabled for policy evaluation (superseded by decision caching)."); return new NonCachingGroovyConditionCache(); } LOGGER.info("In-memory condition caching enabled for policy evaluation."); return new InMemoryGroovyConditionCache(); } @Bean GroovyConditionCache conditionCache( @Value("${ENABLE_DECISION_CACHING:true}") final boolean decisionCachingEnabled); }
@Test public void testGetWithCacheMissForPolicyEvaluation() { PolicyEvaluationRequestV1 request = new PolicyEvaluationRequestV1(); request.setAction(ACTION_GET); request.setSubjectIdentifier(AGENT_MULDER); request.setResourceIdentifier(XFILES_ID); PolicyEvaluationRequestCacheKey key = new PolicyEvaluationRequestCacheKey(request, ZONE_NAME); assertNull(this.cache.get(key)); }
@Override public PolicyEvaluationResult get(final PolicyEvaluationRequestCacheKey evalRequestkey) { DecisionCacheEntries cachedEntries = new DecisionCacheEntries(evalRequestkey); String cachedEvalResultString = cachedEntries.getDecisionString(); if (null == cachedEvalResultString) { return null; } PolicyEvaluationResult cachedEvalResult = toPolicyEvaluationResult(cachedEvalResultString); List<String> attributeInvalidationTimeStamps = new ArrayList<>(); List<String> policyInvalidationTimeStamps = new ArrayList<>(); attributeInvalidationTimeStamps.add(cachedEntries.getSubjectLastModified()); policyInvalidationTimeStamps.addAll(cachedEntries.getPolicySetsLastModified()); Set<String> cachedResolvedResourceUris = cachedEvalResult.getResolvedResourceUris(); if (cachedResolvedResourceUris.size() == 1 && cachedResolvedResourceUris.iterator().next() .equals(evalRequestkey.getResourceId())) { attributeInvalidationTimeStamps.add(cachedEntries.getRequestedResourceLastModified()); } else { List<String> cacheResolvedResourceKeys = cachedResolvedResourceUris.stream() .map(resolvedResourceUri -> resourceKey(evalRequestkey.getZoneId(), resolvedResourceUri)) .collect(Collectors.toList()); attributeInvalidationTimeStamps.addAll(multiGet(cacheResolvedResourceKeys)); } if (isCachedRequestInvalid(attributeInvalidationTimeStamps, policyInvalidationTimeStamps, timestampToDateUTC(cachedEvalResult.getTimestamp()))) { delete(cachedEntries.getDecisionKey()); LOGGER.debug("Cached decision for key '{}' is not valid.", cachedEntries.getDecisionKey()); return null; } return cachedEvalResult; }
AbstractPolicyEvaluationCache implements PolicyEvaluationCache { @Override public PolicyEvaluationResult get(final PolicyEvaluationRequestCacheKey evalRequestkey) { DecisionCacheEntries cachedEntries = new DecisionCacheEntries(evalRequestkey); String cachedEvalResultString = cachedEntries.getDecisionString(); if (null == cachedEvalResultString) { return null; } PolicyEvaluationResult cachedEvalResult = toPolicyEvaluationResult(cachedEvalResultString); List<String> attributeInvalidationTimeStamps = new ArrayList<>(); List<String> policyInvalidationTimeStamps = new ArrayList<>(); attributeInvalidationTimeStamps.add(cachedEntries.getSubjectLastModified()); policyInvalidationTimeStamps.addAll(cachedEntries.getPolicySetsLastModified()); Set<String> cachedResolvedResourceUris = cachedEvalResult.getResolvedResourceUris(); if (cachedResolvedResourceUris.size() == 1 && cachedResolvedResourceUris.iterator().next() .equals(evalRequestkey.getResourceId())) { attributeInvalidationTimeStamps.add(cachedEntries.getRequestedResourceLastModified()); } else { List<String> cacheResolvedResourceKeys = cachedResolvedResourceUris.stream() .map(resolvedResourceUri -> resourceKey(evalRequestkey.getZoneId(), resolvedResourceUri)) .collect(Collectors.toList()); attributeInvalidationTimeStamps.addAll(multiGet(cacheResolvedResourceKeys)); } if (isCachedRequestInvalid(attributeInvalidationTimeStamps, policyInvalidationTimeStamps, timestampToDateUTC(cachedEvalResult.getTimestamp()))) { delete(cachedEntries.getDecisionKey()); LOGGER.debug("Cached decision for key '{}' is not valid.", cachedEntries.getDecisionKey()); return null; } return cachedEvalResult; } }
AbstractPolicyEvaluationCache implements PolicyEvaluationCache { @Override public PolicyEvaluationResult get(final PolicyEvaluationRequestCacheKey evalRequestkey) { DecisionCacheEntries cachedEntries = new DecisionCacheEntries(evalRequestkey); String cachedEvalResultString = cachedEntries.getDecisionString(); if (null == cachedEvalResultString) { return null; } PolicyEvaluationResult cachedEvalResult = toPolicyEvaluationResult(cachedEvalResultString); List<String> attributeInvalidationTimeStamps = new ArrayList<>(); List<String> policyInvalidationTimeStamps = new ArrayList<>(); attributeInvalidationTimeStamps.add(cachedEntries.getSubjectLastModified()); policyInvalidationTimeStamps.addAll(cachedEntries.getPolicySetsLastModified()); Set<String> cachedResolvedResourceUris = cachedEvalResult.getResolvedResourceUris(); if (cachedResolvedResourceUris.size() == 1 && cachedResolvedResourceUris.iterator().next() .equals(evalRequestkey.getResourceId())) { attributeInvalidationTimeStamps.add(cachedEntries.getRequestedResourceLastModified()); } else { List<String> cacheResolvedResourceKeys = cachedResolvedResourceUris.stream() .map(resolvedResourceUri -> resourceKey(evalRequestkey.getZoneId(), resolvedResourceUri)) .collect(Collectors.toList()); attributeInvalidationTimeStamps.addAll(multiGet(cacheResolvedResourceKeys)); } if (isCachedRequestInvalid(attributeInvalidationTimeStamps, policyInvalidationTimeStamps, timestampToDateUTC(cachedEvalResult.getTimestamp()))) { delete(cachedEntries.getDecisionKey()); LOGGER.debug("Cached decision for key '{}' is not valid.", cachedEntries.getDecisionKey()); return null; } return cachedEvalResult; } }
AbstractPolicyEvaluationCache implements PolicyEvaluationCache { @Override public PolicyEvaluationResult get(final PolicyEvaluationRequestCacheKey evalRequestkey) { DecisionCacheEntries cachedEntries = new DecisionCacheEntries(evalRequestkey); String cachedEvalResultString = cachedEntries.getDecisionString(); if (null == cachedEvalResultString) { return null; } PolicyEvaluationResult cachedEvalResult = toPolicyEvaluationResult(cachedEvalResultString); List<String> attributeInvalidationTimeStamps = new ArrayList<>(); List<String> policyInvalidationTimeStamps = new ArrayList<>(); attributeInvalidationTimeStamps.add(cachedEntries.getSubjectLastModified()); policyInvalidationTimeStamps.addAll(cachedEntries.getPolicySetsLastModified()); Set<String> cachedResolvedResourceUris = cachedEvalResult.getResolvedResourceUris(); if (cachedResolvedResourceUris.size() == 1 && cachedResolvedResourceUris.iterator().next() .equals(evalRequestkey.getResourceId())) { attributeInvalidationTimeStamps.add(cachedEntries.getRequestedResourceLastModified()); } else { List<String> cacheResolvedResourceKeys = cachedResolvedResourceUris.stream() .map(resolvedResourceUri -> resourceKey(evalRequestkey.getZoneId(), resolvedResourceUri)) .collect(Collectors.toList()); attributeInvalidationTimeStamps.addAll(multiGet(cacheResolvedResourceKeys)); } if (isCachedRequestInvalid(attributeInvalidationTimeStamps, policyInvalidationTimeStamps, timestampToDateUTC(cachedEvalResult.getTimestamp()))) { delete(cachedEntries.getDecisionKey()); LOGGER.debug("Cached decision for key '{}' is not valid.", cachedEntries.getDecisionKey()); return null; } return cachedEvalResult; } @Override PolicyEvaluationResult get(final PolicyEvaluationRequestCacheKey evalRequestkey); @Override void set(final PolicyEvaluationRequestCacheKey key, final PolicyEvaluationResult result); @Override void reset(); @Override void reset(final PolicyEvaluationRequestCacheKey key); @Override void resetForPolicySet(final String zoneId, final String policySetId); @Override void resetForResource(final String zoneId, final String resourceId); @Override void resetForResourcesByIds(final String zoneId, final Set<String> resourceIds); @Override void resetForResources(final String zoneId, final List<ResourceEntity> resourceEntities); @Override void resetForSubject(final String zoneId, final String subjectId); @Override void resetForSubjectsByIds(final String zoneId, final Set<String> subjectIds); @Override void resetForSubjects(final String zoneId, final List<SubjectEntity> subjectEntities); }
AbstractPolicyEvaluationCache implements PolicyEvaluationCache { @Override public PolicyEvaluationResult get(final PolicyEvaluationRequestCacheKey evalRequestkey) { DecisionCacheEntries cachedEntries = new DecisionCacheEntries(evalRequestkey); String cachedEvalResultString = cachedEntries.getDecisionString(); if (null == cachedEvalResultString) { return null; } PolicyEvaluationResult cachedEvalResult = toPolicyEvaluationResult(cachedEvalResultString); List<String> attributeInvalidationTimeStamps = new ArrayList<>(); List<String> policyInvalidationTimeStamps = new ArrayList<>(); attributeInvalidationTimeStamps.add(cachedEntries.getSubjectLastModified()); policyInvalidationTimeStamps.addAll(cachedEntries.getPolicySetsLastModified()); Set<String> cachedResolvedResourceUris = cachedEvalResult.getResolvedResourceUris(); if (cachedResolvedResourceUris.size() == 1 && cachedResolvedResourceUris.iterator().next() .equals(evalRequestkey.getResourceId())) { attributeInvalidationTimeStamps.add(cachedEntries.getRequestedResourceLastModified()); } else { List<String> cacheResolvedResourceKeys = cachedResolvedResourceUris.stream() .map(resolvedResourceUri -> resourceKey(evalRequestkey.getZoneId(), resolvedResourceUri)) .collect(Collectors.toList()); attributeInvalidationTimeStamps.addAll(multiGet(cacheResolvedResourceKeys)); } if (isCachedRequestInvalid(attributeInvalidationTimeStamps, policyInvalidationTimeStamps, timestampToDateUTC(cachedEvalResult.getTimestamp()))) { delete(cachedEntries.getDecisionKey()); LOGGER.debug("Cached decision for key '{}' is not valid.", cachedEntries.getDecisionKey()); return null; } return cachedEvalResult; } @Override PolicyEvaluationResult get(final PolicyEvaluationRequestCacheKey evalRequestkey); @Override void set(final PolicyEvaluationRequestCacheKey key, final PolicyEvaluationResult result); @Override void reset(); @Override void reset(final PolicyEvaluationRequestCacheKey key); @Override void resetForPolicySet(final String zoneId, final String policySetId); @Override void resetForResource(final String zoneId, final String resourceId); @Override void resetForResourcesByIds(final String zoneId, final Set<String> resourceIds); @Override void resetForResources(final String zoneId, final List<ResourceEntity> resourceEntities); @Override void resetForSubject(final String zoneId, final String subjectId); @Override void resetForSubjectsByIds(final String zoneId, final Set<String> subjectIds); @Override void resetForSubjects(final String zoneId, final List<SubjectEntity> subjectEntities); }
@Test public void testKeyEqualsForSameRequests() { PolicyEvaluationRequestV1 request = new PolicyEvaluationRequestV1(); request.setAction(ACTION_GET); request.setSubjectIdentifier(AGENT_MULDER); request.setResourceIdentifier(XFILES_ID); request.setPolicySetsEvaluationOrder(EVALUATION_ORDER_POLICYONE); PolicyEvaluationRequestCacheKey key = new PolicyEvaluationRequestCacheKey(request, ZONE_NAME); PolicyEvaluationRequestV1 otherRequest = new PolicyEvaluationRequestV1(); otherRequest.setAction(ACTION_GET); otherRequest.setSubjectIdentifier(AGENT_MULDER); otherRequest.setResourceIdentifier(XFILES_ID); otherRequest.setPolicySetsEvaluationOrder(EVALUATION_ORDER_POLICYONE); PolicyEvaluationRequestCacheKey otherKey = new PolicyEvaluationRequestCacheKey(otherRequest, ZONE_NAME); assertTrue(key.equals(otherKey)); }
@Override public boolean equals(final Object obj) { if (obj instanceof PolicyEvaluationRequestCacheKey) { final PolicyEvaluationRequestCacheKey other = (PolicyEvaluationRequestCacheKey) obj; return new EqualsBuilder().append(this.request, other.request).append(this.zoneId, other.zoneId).isEquals(); } return false; }
PolicyEvaluationRequestCacheKey { @Override public boolean equals(final Object obj) { if (obj instanceof PolicyEvaluationRequestCacheKey) { final PolicyEvaluationRequestCacheKey other = (PolicyEvaluationRequestCacheKey) obj; return new EqualsBuilder().append(this.request, other.request).append(this.zoneId, other.zoneId).isEquals(); } return false; } }
PolicyEvaluationRequestCacheKey { @Override public boolean equals(final Object obj) { if (obj instanceof PolicyEvaluationRequestCacheKey) { final PolicyEvaluationRequestCacheKey other = (PolicyEvaluationRequestCacheKey) obj; return new EqualsBuilder().append(this.request, other.request).append(this.zoneId, other.zoneId).isEquals(); } return false; } PolicyEvaluationRequestCacheKey(final PolicyEvaluationRequestV1 request, final String zoneId); }
PolicyEvaluationRequestCacheKey { @Override public boolean equals(final Object obj) { if (obj instanceof PolicyEvaluationRequestCacheKey) { final PolicyEvaluationRequestCacheKey other = (PolicyEvaluationRequestCacheKey) obj; return new EqualsBuilder().append(this.request, other.request).append(this.zoneId, other.zoneId).isEquals(); } return false; } PolicyEvaluationRequestCacheKey(final PolicyEvaluationRequestV1 request, final String zoneId); String toDecisionKey(); @Override int hashCode(); @Override boolean equals(final Object obj); PolicyEvaluationRequestV1 getRequest(); LinkedHashSet<String> getPolicySetIds(); String getResourceId(); String getSubjectId(); String getZoneId(); }
PolicyEvaluationRequestCacheKey { @Override public boolean equals(final Object obj) { if (obj instanceof PolicyEvaluationRequestCacheKey) { final PolicyEvaluationRequestCacheKey other = (PolicyEvaluationRequestCacheKey) obj; return new EqualsBuilder().append(this.request, other.request).append(this.zoneId, other.zoneId).isEquals(); } return false; } PolicyEvaluationRequestCacheKey(final PolicyEvaluationRequestV1 request, final String zoneId); String toDecisionKey(); @Override int hashCode(); @Override boolean equals(final Object obj); PolicyEvaluationRequestV1 getRequest(); LinkedHashSet<String> getPolicySetIds(); String getResourceId(); String getSubjectId(); String getZoneId(); static final String ANY_POLICY_SET_KEY; static final LinkedHashSet<String> EVALUATION_ORDER_ANY_POLICY_SET_KEY; }
@Test public void testKeyEqualsForDifferentRequests() { PolicyEvaluationRequestV1 request = new PolicyEvaluationRequestV1(); request.setAction(ACTION_GET); request.setSubjectIdentifier(AGENT_MULDER); request.setResourceIdentifier(XFILES_ID); request.setPolicySetsEvaluationOrder(EVALUATION_ORDER_POLICYONE); PolicyEvaluationRequestCacheKey key = new PolicyEvaluationRequestCacheKey(request, ZONE_NAME); PolicyEvaluationRequestV1 otherRequest = new PolicyEvaluationRequestV1(); otherRequest.setAction(ACTION_GET); otherRequest.setSubjectIdentifier(AGENT_MULDER); otherRequest.setResourceIdentifier(XFILES_ID); PolicyEvaluationRequestCacheKey otherKey = new PolicyEvaluationRequestCacheKey(otherRequest, ZONE_NAME); assertFalse(key.equals(otherKey)); }
@Override public boolean equals(final Object obj) { if (obj instanceof PolicyEvaluationRequestCacheKey) { final PolicyEvaluationRequestCacheKey other = (PolicyEvaluationRequestCacheKey) obj; return new EqualsBuilder().append(this.request, other.request).append(this.zoneId, other.zoneId).isEquals(); } return false; }
PolicyEvaluationRequestCacheKey { @Override public boolean equals(final Object obj) { if (obj instanceof PolicyEvaluationRequestCacheKey) { final PolicyEvaluationRequestCacheKey other = (PolicyEvaluationRequestCacheKey) obj; return new EqualsBuilder().append(this.request, other.request).append(this.zoneId, other.zoneId).isEquals(); } return false; } }
PolicyEvaluationRequestCacheKey { @Override public boolean equals(final Object obj) { if (obj instanceof PolicyEvaluationRequestCacheKey) { final PolicyEvaluationRequestCacheKey other = (PolicyEvaluationRequestCacheKey) obj; return new EqualsBuilder().append(this.request, other.request).append(this.zoneId, other.zoneId).isEquals(); } return false; } PolicyEvaluationRequestCacheKey(final PolicyEvaluationRequestV1 request, final String zoneId); }
PolicyEvaluationRequestCacheKey { @Override public boolean equals(final Object obj) { if (obj instanceof PolicyEvaluationRequestCacheKey) { final PolicyEvaluationRequestCacheKey other = (PolicyEvaluationRequestCacheKey) obj; return new EqualsBuilder().append(this.request, other.request).append(this.zoneId, other.zoneId).isEquals(); } return false; } PolicyEvaluationRequestCacheKey(final PolicyEvaluationRequestV1 request, final String zoneId); String toDecisionKey(); @Override int hashCode(); @Override boolean equals(final Object obj); PolicyEvaluationRequestV1 getRequest(); LinkedHashSet<String> getPolicySetIds(); String getResourceId(); String getSubjectId(); String getZoneId(); }
PolicyEvaluationRequestCacheKey { @Override public boolean equals(final Object obj) { if (obj instanceof PolicyEvaluationRequestCacheKey) { final PolicyEvaluationRequestCacheKey other = (PolicyEvaluationRequestCacheKey) obj; return new EqualsBuilder().append(this.request, other.request).append(this.zoneId, other.zoneId).isEquals(); } return false; } PolicyEvaluationRequestCacheKey(final PolicyEvaluationRequestV1 request, final String zoneId); String toDecisionKey(); @Override int hashCode(); @Override boolean equals(final Object obj); PolicyEvaluationRequestV1 getRequest(); LinkedHashSet<String> getPolicySetIds(); String getResourceId(); String getSubjectId(); String getZoneId(); static final String ANY_POLICY_SET_KEY; static final LinkedHashSet<String> EVALUATION_ORDER_ANY_POLICY_SET_KEY; }
@SuppressWarnings("unchecked") @Test public void testSetPolicyEvalResult() throws Exception { PolicyEvaluationRequestV1 request = new PolicyEvaluationRequestV1(); request.setAction(ACTION_GET); request.setSubjectIdentifier(AGENT_MULDER); request.setResourceIdentifier(XFILES_ID); PolicyEvaluationRequestCacheKey key = new PolicyEvaluationRequestCacheKey(request, ZONE_NAME); PolicyEvaluationResult result = new PolicyEvaluationResult(Effect.PERMIT); String value = OBJECT_MAPPER.writeValueAsString(result); this.cache.set(key.toDecisionKey(), value); Map<String, String> evalCache = (Map<String, String>) getInternalState(this.cache, "evalCache"); assertEquals(evalCache.size(), 1); }
@Override void set(final String key, final String value) { if (isPolicySetChangedKey(key) || isResourceChangedKey(key) || isSubjectChangedKey(key) || isPolicyEvalResultKey(key)) { this.evalCache.put(key, value); } else { throw new IllegalArgumentException("Unsupported key format."); } }
InMemoryPolicyEvaluationCache extends AbstractPolicyEvaluationCache { @Override void set(final String key, final String value) { if (isPolicySetChangedKey(key) || isResourceChangedKey(key) || isSubjectChangedKey(key) || isPolicyEvalResultKey(key)) { this.evalCache.put(key, value); } else { throw new IllegalArgumentException("Unsupported key format."); } } }
InMemoryPolicyEvaluationCache extends AbstractPolicyEvaluationCache { @Override void set(final String key, final String value) { if (isPolicySetChangedKey(key) || isResourceChangedKey(key) || isSubjectChangedKey(key) || isPolicyEvalResultKey(key)) { this.evalCache.put(key, value); } else { throw new IllegalArgumentException("Unsupported key format."); } } }
InMemoryPolicyEvaluationCache extends AbstractPolicyEvaluationCache { @Override void set(final String key, final String value) { if (isPolicySetChangedKey(key) || isResourceChangedKey(key) || isSubjectChangedKey(key) || isPolicyEvalResultKey(key)) { this.evalCache.put(key, value); } else { throw new IllegalArgumentException("Unsupported key format."); } } }
InMemoryPolicyEvaluationCache extends AbstractPolicyEvaluationCache { @Override void set(final String key, final String value) { if (isPolicySetChangedKey(key) || isResourceChangedKey(key) || isSubjectChangedKey(key) || isPolicyEvalResultKey(key)) { this.evalCache.put(key, value); } else { throw new IllegalArgumentException("Unsupported key format."); } } }
@Test(dataProvider = "validScript") public void testParseValidScript(final String script, final Map<String, Object> boundVariables, final boolean expectedResult) throws ConditionParsingException { ConditionScript parsedScript = this.shell.parse(script); Assert.assertNotNull(parsedScript); }
public ConditionScript parse(final String script) throws ConditionParsingException { return parse(script, true); }
GroovyConditionShell { public ConditionScript parse(final String script) throws ConditionParsingException { return parse(script, true); } }
GroovyConditionShell { public ConditionScript parse(final String script) throws ConditionParsingException { return parse(script, true); } GroovyConditionShell(final GroovyConditionCache conditionCache); }
GroovyConditionShell { public ConditionScript parse(final String script) throws ConditionParsingException { return parse(script, true); } GroovyConditionShell(final GroovyConditionCache conditionCache); ConditionScript parse(final String script); boolean execute(final String script, final Map<String, Object> boundVariables); }
GroovyConditionShell { public ConditionScript parse(final String script) throws ConditionParsingException { return parse(script, true); } GroovyConditionShell(final GroovyConditionCache conditionCache); ConditionScript parse(final String script); boolean execute(final String script, final Map<String, Object> boundVariables); }
@Test(dataProvider = "validScript") public void testExecuteValidScript(final String script, final Map<String, Object> boundVariables, final boolean expectedResult) throws ConditionParsingException { Assert.assertEquals(this.shell.execute(script, boundVariables), expectedResult); }
public boolean execute(final String script, final Map<String, Object> boundVariables) throws ConditionParsingException { ConditionScript conditionScript = parse(script, false); try { return conditionScript.execute(boundVariables); } catch (ConditionAssertionFailedException e) { return false; } finally { removeLoadedClasses(); } }
GroovyConditionShell { public boolean execute(final String script, final Map<String, Object> boundVariables) throws ConditionParsingException { ConditionScript conditionScript = parse(script, false); try { return conditionScript.execute(boundVariables); } catch (ConditionAssertionFailedException e) { return false; } finally { removeLoadedClasses(); } } }
GroovyConditionShell { public boolean execute(final String script, final Map<String, Object> boundVariables) throws ConditionParsingException { ConditionScript conditionScript = parse(script, false); try { return conditionScript.execute(boundVariables); } catch (ConditionAssertionFailedException e) { return false; } finally { removeLoadedClasses(); } } GroovyConditionShell(final GroovyConditionCache conditionCache); }
GroovyConditionShell { public boolean execute(final String script, final Map<String, Object> boundVariables) throws ConditionParsingException { ConditionScript conditionScript = parse(script, false); try { return conditionScript.execute(boundVariables); } catch (ConditionAssertionFailedException e) { return false; } finally { removeLoadedClasses(); } } GroovyConditionShell(final GroovyConditionCache conditionCache); ConditionScript parse(final String script); boolean execute(final String script, final Map<String, Object> boundVariables); }
GroovyConditionShell { public boolean execute(final String script, final Map<String, Object> boundVariables) throws ConditionParsingException { ConditionScript conditionScript = parse(script, false); try { return conditionScript.execute(boundVariables); } catch (ConditionAssertionFailedException e) { return false; } finally { removeLoadedClasses(); } } GroovyConditionShell(final GroovyConditionCache conditionCache); ConditionScript parse(final String script); boolean execute(final String script, final Map<String, Object> boundVariables); }
@Test(dataProvider = "illegalScript", expectedExceptions = IllegalArgumentException.class) public void testParseBlankScript(final String script) throws ConditionParsingException { this.shell.parse(script); }
public ConditionScript parse(final String script) throws ConditionParsingException { return parse(script, true); }
GroovyConditionShell { public ConditionScript parse(final String script) throws ConditionParsingException { return parse(script, true); } }
GroovyConditionShell { public ConditionScript parse(final String script) throws ConditionParsingException { return parse(script, true); } GroovyConditionShell(final GroovyConditionCache conditionCache); }
GroovyConditionShell { public ConditionScript parse(final String script) throws ConditionParsingException { return parse(script, true); } GroovyConditionShell(final GroovyConditionCache conditionCache); ConditionScript parse(final String script); boolean execute(final String script, final Map<String, Object> boundVariables); }
GroovyConditionShell { public ConditionScript parse(final String script) throws ConditionParsingException { return parse(script, true); } GroovyConditionShell(final GroovyConditionCache conditionCache); ConditionScript parse(final String script); boolean execute(final String script, final Map<String, Object> boundVariables); }
@Test(dataProvider = "illegalScript", expectedExceptions = IllegalArgumentException.class) public void testExecuteBlankScript(final String script) throws ConditionParsingException { this.shell.execute(script, emptyBindingMap); }
public boolean execute(final String script, final Map<String, Object> boundVariables) throws ConditionParsingException { ConditionScript conditionScript = parse(script, false); try { return conditionScript.execute(boundVariables); } catch (ConditionAssertionFailedException e) { return false; } finally { removeLoadedClasses(); } }
GroovyConditionShell { public boolean execute(final String script, final Map<String, Object> boundVariables) throws ConditionParsingException { ConditionScript conditionScript = parse(script, false); try { return conditionScript.execute(boundVariables); } catch (ConditionAssertionFailedException e) { return false; } finally { removeLoadedClasses(); } } }
GroovyConditionShell { public boolean execute(final String script, final Map<String, Object> boundVariables) throws ConditionParsingException { ConditionScript conditionScript = parse(script, false); try { return conditionScript.execute(boundVariables); } catch (ConditionAssertionFailedException e) { return false; } finally { removeLoadedClasses(); } } GroovyConditionShell(final GroovyConditionCache conditionCache); }
GroovyConditionShell { public boolean execute(final String script, final Map<String, Object> boundVariables) throws ConditionParsingException { ConditionScript conditionScript = parse(script, false); try { return conditionScript.execute(boundVariables); } catch (ConditionAssertionFailedException e) { return false; } finally { removeLoadedClasses(); } } GroovyConditionShell(final GroovyConditionCache conditionCache); ConditionScript parse(final String script); boolean execute(final String script, final Map<String, Object> boundVariables); }
GroovyConditionShell { public boolean execute(final String script, final Map<String, Object> boundVariables) throws ConditionParsingException { ConditionScript conditionScript = parse(script, false); try { return conditionScript.execute(boundVariables); } catch (ConditionAssertionFailedException e) { return false; } finally { removeLoadedClasses(); } } GroovyConditionShell(final GroovyConditionCache conditionCache); ConditionScript parse(final String script); boolean execute(final String script, final Map<String, Object> boundVariables); }
@Test(dataProvider = "invalidScript", expectedExceptions = ClassCastException.class) public void testExecuteInvalidScript(final String script) throws ConditionParsingException { this.shell.execute(script, emptyBindingMap); }
public boolean execute(final String script, final Map<String, Object> boundVariables) throws ConditionParsingException { ConditionScript conditionScript = parse(script, false); try { return conditionScript.execute(boundVariables); } catch (ConditionAssertionFailedException e) { return false; } finally { removeLoadedClasses(); } }
GroovyConditionShell { public boolean execute(final String script, final Map<String, Object> boundVariables) throws ConditionParsingException { ConditionScript conditionScript = parse(script, false); try { return conditionScript.execute(boundVariables); } catch (ConditionAssertionFailedException e) { return false; } finally { removeLoadedClasses(); } } }
GroovyConditionShell { public boolean execute(final String script, final Map<String, Object> boundVariables) throws ConditionParsingException { ConditionScript conditionScript = parse(script, false); try { return conditionScript.execute(boundVariables); } catch (ConditionAssertionFailedException e) { return false; } finally { removeLoadedClasses(); } } GroovyConditionShell(final GroovyConditionCache conditionCache); }
GroovyConditionShell { public boolean execute(final String script, final Map<String, Object> boundVariables) throws ConditionParsingException { ConditionScript conditionScript = parse(script, false); try { return conditionScript.execute(boundVariables); } catch (ConditionAssertionFailedException e) { return false; } finally { removeLoadedClasses(); } } GroovyConditionShell(final GroovyConditionCache conditionCache); ConditionScript parse(final String script); boolean execute(final String script, final Map<String, Object> boundVariables); }
GroovyConditionShell { public boolean execute(final String script, final Map<String, Object> boundVariables) throws ConditionParsingException { ConditionScript conditionScript = parse(script, false); try { return conditionScript.execute(boundVariables); } catch (ConditionAssertionFailedException e) { return false; } finally { removeLoadedClasses(); } } GroovyConditionShell(final GroovyConditionCache conditionCache); ConditionScript parse(final String script); boolean execute(final String script, final Map<String, Object> boundVariables); }
@Test(dataProvider = "blackListedScript", expectedExceptions = ConditionParsingException.class) public void testParseBlackListedScript(final String script) throws ConditionParsingException { this.shell.parse(script); }
public ConditionScript parse(final String script) throws ConditionParsingException { return parse(script, true); }
GroovyConditionShell { public ConditionScript parse(final String script) throws ConditionParsingException { return parse(script, true); } }
GroovyConditionShell { public ConditionScript parse(final String script) throws ConditionParsingException { return parse(script, true); } GroovyConditionShell(final GroovyConditionCache conditionCache); }
GroovyConditionShell { public ConditionScript parse(final String script) throws ConditionParsingException { return parse(script, true); } GroovyConditionShell(final GroovyConditionCache conditionCache); ConditionScript parse(final String script); boolean execute(final String script, final Map<String, Object> boundVariables); }
GroovyConditionShell { public ConditionScript parse(final String script) throws ConditionParsingException { return parse(script, true); } GroovyConditionShell(final GroovyConditionCache conditionCache); ConditionScript parse(final String script); boolean execute(final String script, final Map<String, Object> boundVariables); }
@Test(dataProvider = "blackListedScript", expectedExceptions = ConditionParsingException.class) public void testExecuteBlackListedScript(final String script) throws ConditionParsingException { this.shell.execute(script, emptyBindingMap); }
public boolean execute(final String script, final Map<String, Object> boundVariables) throws ConditionParsingException { ConditionScript conditionScript = parse(script, false); try { return conditionScript.execute(boundVariables); } catch (ConditionAssertionFailedException e) { return false; } finally { removeLoadedClasses(); } }
GroovyConditionShell { public boolean execute(final String script, final Map<String, Object> boundVariables) throws ConditionParsingException { ConditionScript conditionScript = parse(script, false); try { return conditionScript.execute(boundVariables); } catch (ConditionAssertionFailedException e) { return false; } finally { removeLoadedClasses(); } } }
GroovyConditionShell { public boolean execute(final String script, final Map<String, Object> boundVariables) throws ConditionParsingException { ConditionScript conditionScript = parse(script, false); try { return conditionScript.execute(boundVariables); } catch (ConditionAssertionFailedException e) { return false; } finally { removeLoadedClasses(); } } GroovyConditionShell(final GroovyConditionCache conditionCache); }
GroovyConditionShell { public boolean execute(final String script, final Map<String, Object> boundVariables) throws ConditionParsingException { ConditionScript conditionScript = parse(script, false); try { return conditionScript.execute(boundVariables); } catch (ConditionAssertionFailedException e) { return false; } finally { removeLoadedClasses(); } } GroovyConditionShell(final GroovyConditionCache conditionCache); ConditionScript parse(final String script); boolean execute(final String script, final Map<String, Object> boundVariables); }
GroovyConditionShell { public boolean execute(final String script, final Map<String, Object> boundVariables) throws ConditionParsingException { ConditionScript conditionScript = parse(script, false); try { return conditionScript.execute(boundVariables); } catch (ConditionAssertionFailedException e) { return false; } finally { removeLoadedClasses(); } } GroovyConditionShell(final GroovyConditionCache conditionCache); ConditionScript parse(final String script); boolean execute(final String script, final Map<String, Object> boundVariables); }
@Test(dataProvider = "statuses") public void testHealth(final AcsMonitoringRepository acsMonitoringRepository, final Status status, final AcsMonitoringUtilities.HealthCode healthCode, final GraphStartupManager graphStartupManager) throws Exception { AcsDbHealthIndicator acsDbHealthIndicator = new AcsDbHealthIndicator(acsMonitoringRepository); acsDbHealthIndicator.setStartupManager(graphStartupManager); Assert.assertEquals(status, acsDbHealthIndicator.health().getStatus()); Assert.assertEquals(AcsDbHealthIndicator.DESCRIPTION, acsDbHealthIndicator.health().getDetails().get(AcsMonitoringUtilities.DESCRIPTION_KEY)); if (healthCode == AcsMonitoringUtilities.HealthCode.AVAILABLE) { Assert.assertFalse(acsDbHealthIndicator.health().getDetails().containsKey(AcsMonitoringUtilities.CODE_KEY)); } else { Assert.assertEquals(healthCode, acsDbHealthIndicator.health().getDetails().get(AcsMonitoringUtilities.CODE_KEY)); } }
@Override public Health health() { return AcsMonitoringUtilities.health(this::check, DESCRIPTION); }
AcsDbHealthIndicator implements HealthIndicator { @Override public Health health() { return AcsMonitoringUtilities.health(this::check, DESCRIPTION); } }
AcsDbHealthIndicator implements HealthIndicator { @Override public Health health() { return AcsMonitoringUtilities.health(this::check, DESCRIPTION); } @Autowired AcsDbHealthIndicator(final AcsMonitoringRepository acsMonitoringRepository); }
AcsDbHealthIndicator implements HealthIndicator { @Override public Health health() { return AcsMonitoringUtilities.health(this::check, DESCRIPTION); } @Autowired AcsDbHealthIndicator(final AcsMonitoringRepository acsMonitoringRepository); @Override Health health(); }
AcsDbHealthIndicator implements HealthIndicator { @Override public Health health() { return AcsMonitoringUtilities.health(this::check, DESCRIPTION); } @Autowired AcsDbHealthIndicator(final AcsMonitoringRepository acsMonitoringRepository); @Override Health health(); }
@Test public void testWithProtocol() { URL u = URL.parse("http: URL u2 = u.withProtocol(Protocols.WS); assertEquals(u.getPath(), u2.getPath()); assertNotEquals(u.getProtocol(), u2.getProtocol()); assertEquals(Protocols.HTTP, u.getProtocol()); assertEquals(Protocols.WS, u2.getProtocol()); }
public URL withProtocol(Protocol protocol) { if (protocol.equals(this.protocol)) { return this; } return new URL(userName, password, protocol, host, port, path, parameters, anchor); }
URL implements URLComponent, Validating, Comparable<URL> { public URL withProtocol(Protocol protocol) { if (protocol.equals(this.protocol)) { return this; } return new URL(userName, password, protocol, host, port, path, parameters, anchor); } }
URL implements URLComponent, Validating, Comparable<URL> { public URL withProtocol(Protocol protocol) { if (protocol.equals(this.protocol)) { return this; } return new URL(userName, password, protocol, host, port, path, parameters, anchor); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); }
URL implements URLComponent, Validating, Comparable<URL> { public URL withProtocol(Protocol protocol) { if (protocol.equals(this.protocol)) { return this; } return new URL(userName, password, protocol, host, port, path, parameters, anchor); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); }
URL implements URLComponent, Validating, Comparable<URL> { public URL withProtocol(Protocol protocol) { if (protocol.equals(this.protocol)) { return this; } return new URL(userName, password, protocol, host, port, path, parameters, anchor); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); }
@Test public void testLeadingAndTrailingSlashesDontAffectEquality() { Path a = Path.parse("foo/bar/baz"); Path b = Path.parse("/foo/bar/baz"); Path c = Path.parse("foo/bar/baz/"); Path d = Path.parse("/foo/bar/baz/"); Path e = Path.parse("foo/bar/baz/bean"); Path f = Path.parse("moo/bar/baz"); assertEquals(a, b); assertEquals(a, c); assertEquals(a, d); assertEquals(b, a); assertEquals(b, c); assertEquals(b, d); assertEquals(c, a); assertEquals(c, b); assertEquals(c, d); assertNotEquals(a, e); assertNotEquals(b, e); assertNotEquals(c, e); assertNotEquals(d, e); assertNotEquals(a, f); assertNotEquals(b, f); assertNotEquals(c, f); assertNotEquals(d, f); }
public static Path parse(String path) { return Path.parse(path, false); }
Path implements URLComponent, Iterable<PathElement> { public static Path parse(String path) { return Path.parse(path, false); } }
Path implements URLComponent, Iterable<PathElement> { public static Path parse(String path) { return Path.parse(path, false); } Path(PathElement... elements); Path(NormalizeResult n); }
Path implements URLComponent, Iterable<PathElement> { public static Path parse(String path) { return Path.parse(path, false); } Path(PathElement... elements); Path(NormalizeResult n); static Path parse(String path); static Path parse(String path, boolean decode); Path toURLDecodedPath(); Iterator<PathElement> iterator(); PathElement lastElement(); Path normalize(); Path replace(String old, String nue); final Path elideEmptyElements(); Path prepend(String part); Path append(String part); static Path merge(Path... paths); boolean isParentOf(Path path); boolean isChildOf(Path path); int size(); PathElement[] getElements(); Path getChildPath(); String toStringWithLeadingSlash(); Path getParentPath(); boolean lastElementMatches(CharSequence s); boolean lastElementMatches(CharSequence s, boolean ignoreCase); @Override String toString(); static AbstractBuilder<PathElement, Path> builder(); @Override boolean isValid(); @Override String getComponentName(); boolean isProbableFileReference(); void appendTo(StringBuilder sb); PathElement getElement(int ix); PathElement getLastElement(); @Override boolean equals(Object obj); @Override int hashCode(); URI toURI(); URI toURIWithLeadingSlash(); String[] toStringArray(); }
Path implements URLComponent, Iterable<PathElement> { public static Path parse(String path) { return Path.parse(path, false); } Path(PathElement... elements); Path(NormalizeResult n); static Path parse(String path); static Path parse(String path, boolean decode); Path toURLDecodedPath(); Iterator<PathElement> iterator(); PathElement lastElement(); Path normalize(); Path replace(String old, String nue); final Path elideEmptyElements(); Path prepend(String part); Path append(String part); static Path merge(Path... paths); boolean isParentOf(Path path); boolean isChildOf(Path path); int size(); PathElement[] getElements(); Path getChildPath(); String toStringWithLeadingSlash(); Path getParentPath(); boolean lastElementMatches(CharSequence s); boolean lastElementMatches(CharSequence s, boolean ignoreCase); @Override String toString(); static AbstractBuilder<PathElement, Path> builder(); @Override boolean isValid(); @Override String getComponentName(); boolean isProbableFileReference(); void appendTo(StringBuilder sb); PathElement getElement(int ix); PathElement getLastElement(); @Override boolean equals(Object obj); @Override int hashCode(); URI toURI(); URI toURIWithLeadingSlash(); String[] toStringArray(); }
@Test(timeout = 10000) public void testChainRunner() throws Exception, Throwable { AtomicBoolean cancelled = new AtomicBoolean(); ChainRunner cr = new ChainRunner(svc, scope); TestCallback chainWithDeferResults = new TestCallback(); TestCallback dontRespondChainResults = new TestCallback(); TestCallback plainChainResults = new TestCallback(); TestCallback errorChainResults = new TestCallback(); TestCallback rejectChainResults = new TestCallback(); TestCallback remnantChainResults = new TestCallback(); try (AutoCloseable cl = scope.enter()) { cr.submit(chain, chainWithDeferResults, cancelled); cr.submit(dontRespond, dontRespondChainResults, cancelled); cr.submit(plainChain, plainChainResults, cancelled); cr.submit(errorChain, errorChainResults, cancelled); cr.submit(rejectIt, rejectChainResults, cancelled); cr.submit(remnantChain, remnantChainResults, cancelled); cr.submit(remnantChain, remnantChainResults, cancelled); } chainWithDeferResults.assertGotResponse().assertActeurClass(AddedA.class).throwIfError().assertNotRejected(); dontRespondChainResults.assertNoResponse().throwIfError(); plainChainResults.throwIfError().assertGotResponse().assertActeurClass(AddedA.class).assertNotRejected(); errorChainResults.assertException(SpecialError.class); rejectChainResults.throwIfError().assertRejected(); remnantChainResults.throwIfError().assertRejected(); }
@Inject public ChainRunner(ExecutorService svc, ReentrantScope scope) { Checks.notNull("svc", svc); Checks.notNull("scope", scope); this.svc = svc; this.scope = scope; }
ChainRunner { @Inject public ChainRunner(ExecutorService svc, ReentrantScope scope) { Checks.notNull("svc", svc); Checks.notNull("scope", scope); this.svc = svc; this.scope = scope; } }
ChainRunner { @Inject public ChainRunner(ExecutorService svc, ReentrantScope scope) { Checks.notNull("svc", svc); Checks.notNull("scope", scope); this.svc = svc; this.scope = scope; } @Inject ChainRunner(ExecutorService svc, ReentrantScope scope); }
ChainRunner { @Inject public ChainRunner(ExecutorService svc, ReentrantScope scope) { Checks.notNull("svc", svc); Checks.notNull("scope", scope); this.svc = svc; this.scope = scope; } @Inject ChainRunner(ExecutorService svc, ReentrantScope scope); void submit(P chain, ChainCallback<A, S, P, T, R> onDone, AtomicBoolean cancelled); }
ChainRunner { @Inject public ChainRunner(ExecutorService svc, ReentrantScope scope) { Checks.notNull("svc", svc); Checks.notNull("scope", scope); this.svc = svc; this.scope = scope; } @Inject ChainRunner(ExecutorService svc, ReentrantScope scope); void submit(P chain, ChainCallback<A, S, P, T, R> onDone, AtomicBoolean cancelled); }
@Test(timeout = 20000) public void testMultiChainRunner() throws Exception, Throwable { AtomicBoolean cancelled = new AtomicBoolean(); List<ArrayChain<AbstractActeur<Response, ResponseImpl, ActeurState<Response, ResponseImpl>>, ?>> l = new LinkedList<>(); for (int i = 0; i < 5; i++) { ArrayChain<AbstractActeur<Response, ResponseImpl, ActeurState<Response, ResponseImpl>>, ?> ch = new NamedChain("Chain " + i, deps, AbstractActeur.class) .add(FirstA.class).add(Rejecter.class).add(SecondWithoutTimeoutA.class).add(EndA.class); l.add(ch); } l.add(plainChain); ChainsRunner cr = new ChainsRunner(svc, scope, new ChainRunner(svc, scope)); TestCallback callback = new TestCallback(); cr.submit(l, callback, cancelled); callback.throwIfError().assertNotRejected().assertGotResponse(); l.remove(l.size() - 1); callback = new TestCallback(); cr.submit(l, callback, cancelled); callback.throwIfError().assertNoResponse(); }
public <A extends AbstractActeur<T, R, S>, S extends ActeurState<T, R>, P extends Chain<? extends A, ?>, T, R extends T> void submit(P chain, ChainCallback<A, S, P, T, R> onDone, AtomicBoolean cancelled) { ActeurInvoker<A, S, P, T, R> cc = new ActeurInvoker<>(svc, scope, chain, onDone, cancelled); try (QuietAutoCloseable ac = scope.enter(chain, cc.deferral)) { if (firstSync) { try { cc.call(); } catch (Exception ex) { Exceptions.chuck(ex); } } else { svc.submit(scope.wrap(cc)); } } }
ChainRunner { public <A extends AbstractActeur<T, R, S>, S extends ActeurState<T, R>, P extends Chain<? extends A, ?>, T, R extends T> void submit(P chain, ChainCallback<A, S, P, T, R> onDone, AtomicBoolean cancelled) { ActeurInvoker<A, S, P, T, R> cc = new ActeurInvoker<>(svc, scope, chain, onDone, cancelled); try (QuietAutoCloseable ac = scope.enter(chain, cc.deferral)) { if (firstSync) { try { cc.call(); } catch (Exception ex) { Exceptions.chuck(ex); } } else { svc.submit(scope.wrap(cc)); } } } }
ChainRunner { public <A extends AbstractActeur<T, R, S>, S extends ActeurState<T, R>, P extends Chain<? extends A, ?>, T, R extends T> void submit(P chain, ChainCallback<A, S, P, T, R> onDone, AtomicBoolean cancelled) { ActeurInvoker<A, S, P, T, R> cc = new ActeurInvoker<>(svc, scope, chain, onDone, cancelled); try (QuietAutoCloseable ac = scope.enter(chain, cc.deferral)) { if (firstSync) { try { cc.call(); } catch (Exception ex) { Exceptions.chuck(ex); } } else { svc.submit(scope.wrap(cc)); } } } @Inject ChainRunner(ExecutorService svc, ReentrantScope scope); }
ChainRunner { public <A extends AbstractActeur<T, R, S>, S extends ActeurState<T, R>, P extends Chain<? extends A, ?>, T, R extends T> void submit(P chain, ChainCallback<A, S, P, T, R> onDone, AtomicBoolean cancelled) { ActeurInvoker<A, S, P, T, R> cc = new ActeurInvoker<>(svc, scope, chain, onDone, cancelled); try (QuietAutoCloseable ac = scope.enter(chain, cc.deferral)) { if (firstSync) { try { cc.call(); } catch (Exception ex) { Exceptions.chuck(ex); } } else { svc.submit(scope.wrap(cc)); } } } @Inject ChainRunner(ExecutorService svc, ReentrantScope scope); void submit(P chain, ChainCallback<A, S, P, T, R> onDone, AtomicBoolean cancelled); }
ChainRunner { public <A extends AbstractActeur<T, R, S>, S extends ActeurState<T, R>, P extends Chain<? extends A, ?>, T, R extends T> void submit(P chain, ChainCallback<A, S, P, T, R> onDone, AtomicBoolean cancelled) { ActeurInvoker<A, S, P, T, R> cc = new ActeurInvoker<>(svc, scope, chain, onDone, cancelled); try (QuietAutoCloseable ac = scope.enter(chain, cc.deferral)) { if (firstSync) { try { cc.call(); } catch (Exception ex) { Exceptions.chuck(ex); } } else { svc.submit(scope.wrap(cc)); } } } @Inject ChainRunner(ExecutorService svc, ReentrantScope scope); void submit(P chain, ChainCallback<A, S, P, T, R> onDone, AtomicBoolean cancelled); }
@Test public void testStrictTransportHeader() { HeaderValueType<StrictTransportSecurity> h = new StrictTransportSecurityHeader(); assertEquals(StrictTransportSecurity.FIVE_YEARS_INCLUDE_SUBDOMAINS_PRELOAD, h.toValue(StrictTransportSecurity.FIVE_YEARS_INCLUDE_SUBDOMAINS_PRELOAD.toString())); assertEquals(StrictTransportSecurity.ONE_YEAR, h.toValue(StrictTransportSecurity.ONE_YEAR.toString())); }
@Override public StrictTransportSecurity toValue(CharSequence value) { return StrictTransportSecurity.parse(value); }
StrictTransportSecurityHeader extends AbstractHeader<StrictTransportSecurity> { @Override public StrictTransportSecurity toValue(CharSequence value) { return StrictTransportSecurity.parse(value); } }
StrictTransportSecurityHeader extends AbstractHeader<StrictTransportSecurity> { @Override public StrictTransportSecurity toValue(CharSequence value) { return StrictTransportSecurity.parse(value); } StrictTransportSecurityHeader(); }
StrictTransportSecurityHeader extends AbstractHeader<StrictTransportSecurity> { @Override public StrictTransportSecurity toValue(CharSequence value) { return StrictTransportSecurity.parse(value); } StrictTransportSecurityHeader(); @Override StrictTransportSecurity toValue(CharSequence value); @Override CharSequence toCharSequence(StrictTransportSecurity value); }
StrictTransportSecurityHeader extends AbstractHeader<StrictTransportSecurity> { @Override public StrictTransportSecurity toValue(CharSequence value) { return StrictTransportSecurity.parse(value); } StrictTransportSecurityHeader(); @Override StrictTransportSecurity toValue(CharSequence value); @Override CharSequence toCharSequence(StrictTransportSecurity value); }
@Test @SuppressWarnings("deprecation") public void testLegacyCookies() { CookieHeader h = new CookieHeader(); io.netty.handler.codec.http.DefaultCookie a = new io.netty.handler.codec.http.DefaultCookie("a", "a"); io.netty.handler.codec.http.DefaultCookie b = new io.netty.handler.codec.http.DefaultCookie("b", "b"); io.netty.handler.codec.http.DefaultCookie c = new io.netty.handler.codec.http.DefaultCookie("c", "c"); String val = h.toString(new io.netty.handler.codec.http.Cookie[]{a, b, c}); io.netty.handler.codec.http.Cookie[] result = h.toValue(val); assertNotNull(result); assertNotNull(val); assertTrue("Should contain all cookies:" + val, val.contains("a") && val.contains("b") && val.contains("c")); assertEquals(3, result.length); }
@Override public Cookie[] toValue(CharSequence value) { ServerCookieDecoder decoder = strict ? ServerCookieDecoder.STRICT : ServerCookieDecoder.LAX; Set<Cookie> result = decoder.decode(notNull("value", value).toString()); return result == null ? EMPTY : result.toArray(new Cookie[result.size()]); }
CookieHeaderNetty428 extends AbstractHeader<Cookie[]> { @Override public Cookie[] toValue(CharSequence value) { ServerCookieDecoder decoder = strict ? ServerCookieDecoder.STRICT : ServerCookieDecoder.LAX; Set<Cookie> result = decoder.decode(notNull("value", value).toString()); return result == null ? EMPTY : result.toArray(new Cookie[result.size()]); } }
CookieHeaderNetty428 extends AbstractHeader<Cookie[]> { @Override public Cookie[] toValue(CharSequence value) { ServerCookieDecoder decoder = strict ? ServerCookieDecoder.STRICT : ServerCookieDecoder.LAX; Set<Cookie> result = decoder.decode(notNull("value", value).toString()); return result == null ? EMPTY : result.toArray(new Cookie[result.size()]); } CookieHeaderNetty428(boolean strict); }
CookieHeaderNetty428 extends AbstractHeader<Cookie[]> { @Override public Cookie[] toValue(CharSequence value) { ServerCookieDecoder decoder = strict ? ServerCookieDecoder.STRICT : ServerCookieDecoder.LAX; Set<Cookie> result = decoder.decode(notNull("value", value).toString()); return result == null ? EMPTY : result.toArray(new Cookie[result.size()]); } CookieHeaderNetty428(boolean strict); @Override CharSequence toCharSequence(Cookie[] value); @Override Cookie[] toValue(CharSequence value); }
CookieHeaderNetty428 extends AbstractHeader<Cookie[]> { @Override public Cookie[] toValue(CharSequence value) { ServerCookieDecoder decoder = strict ? ServerCookieDecoder.STRICT : ServerCookieDecoder.LAX; Set<Cookie> result = decoder.decode(notNull("value", value).toString()); return result == null ? EMPTY : result.toArray(new Cookie[result.size()]); } CookieHeaderNetty428(boolean strict); @Override CharSequence toCharSequence(Cookie[] value); @Override Cookie[] toValue(CharSequence value); }
@Test public void testAllowFrom() { FrameOptions fo = FrameOptions.allowFrom(URI.create("http: assertEquals(URI.create("http: assertSame(FrameOptionType.ALLOW_FROM, fo.type()); assertEquals("ALLOW-FROM http: FrameOptions fo2 = FrameOptions.parse(fo.toString()); assertEquals(fo, fo2); assertEquals(fo.hashCode(), fo2.hashCode()); FrameOptions fo3 = FrameOptions.parse(fo.toString().toLowerCase()); assertEquals(fo, fo3); assertEquals(fo.hashCode(), fo3.hashCode()); assertEquals(fo.toString(), fo3.toString()); }
public static FrameOptions allowFrom(URI uri) { return new FrameOptions(FrameOptionType.ALLOW_FROM, notNull("uri", uri)); }
FrameOptions { public static FrameOptions allowFrom(URI uri) { return new FrameOptions(FrameOptionType.ALLOW_FROM, notNull("uri", uri)); } }
FrameOptions { public static FrameOptions allowFrom(URI uri) { return new FrameOptions(FrameOptionType.ALLOW_FROM, notNull("uri", uri)); } FrameOptions(FrameOptionType type); FrameOptions(FrameOptionType type, URI value); }
FrameOptions { public static FrameOptions allowFrom(URI uri) { return new FrameOptions(FrameOptionType.ALLOW_FROM, notNull("uri", uri)); } FrameOptions(FrameOptionType type); FrameOptions(FrameOptionType type, URI value); FrameOptionType type(); URI uri(); String name(); String toString(); static FrameOptions allowFrom(URI uri); static FrameOptions parse(CharSequence seq); boolean equals(Object o); int hashCode(); }
FrameOptions { public static FrameOptions allowFrom(URI uri) { return new FrameOptions(FrameOptionType.ALLOW_FROM, notNull("uri", uri)); } FrameOptions(FrameOptionType type); FrameOptions(FrameOptionType type, URI value); FrameOptionType type(); URI uri(); String name(); String toString(); static FrameOptions allowFrom(URI uri); static FrameOptions parse(CharSequence seq); boolean equals(Object o); int hashCode(); static final FrameOptions DENY; static final FrameOptions SAMEORIGIN; }
@Test(expected=IllegalArgumentException.class) public void testMissingArgument() { FrameOptions.parse("DENY http: }
public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); }
FrameOptions { public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); } }
FrameOptions { public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); } FrameOptions(FrameOptionType type); FrameOptions(FrameOptionType type, URI value); }
FrameOptions { public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); } FrameOptions(FrameOptionType type); FrameOptions(FrameOptionType type, URI value); FrameOptionType type(); URI uri(); String name(); String toString(); static FrameOptions allowFrom(URI uri); static FrameOptions parse(CharSequence seq); boolean equals(Object o); int hashCode(); }
FrameOptions { public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); } FrameOptions(FrameOptionType type); FrameOptions(FrameOptionType type, URI value); FrameOptionType type(); URI uri(); String name(); String toString(); static FrameOptions allowFrom(URI uri); static FrameOptions parse(CharSequence seq); boolean equals(Object o); int hashCode(); static final FrameOptions DENY; static final FrameOptions SAMEORIGIN; }
@Test(expected=IllegalArgumentException.class) public void testMissingArgumen2t() { FrameOptions.parse("SAMEORIGIN http: }
public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); }
FrameOptions { public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); } }
FrameOptions { public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); } FrameOptions(FrameOptionType type); FrameOptions(FrameOptionType type, URI value); }
FrameOptions { public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); } FrameOptions(FrameOptionType type); FrameOptions(FrameOptionType type, URI value); FrameOptionType type(); URI uri(); String name(); String toString(); static FrameOptions allowFrom(URI uri); static FrameOptions parse(CharSequence seq); boolean equals(Object o); int hashCode(); }
FrameOptions { public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); } FrameOptions(FrameOptionType type); FrameOptions(FrameOptionType type, URI value); FrameOptionType type(); URI uri(); String name(); String toString(); static FrameOptions allowFrom(URI uri); static FrameOptions parse(CharSequence seq); boolean equals(Object o); int hashCode(); static final FrameOptions DENY; static final FrameOptions SAMEORIGIN; }
@Test(expected=IllegalArgumentException.class) public void testInvalidName() { FrameOptions.parse("PERCEIVE http: }
public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); }
FrameOptions { public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); } }
FrameOptions { public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); } FrameOptions(FrameOptionType type); FrameOptions(FrameOptionType type, URI value); }
FrameOptions { public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); } FrameOptions(FrameOptionType type); FrameOptions(FrameOptionType type, URI value); FrameOptionType type(); URI uri(); String name(); String toString(); static FrameOptions allowFrom(URI uri); static FrameOptions parse(CharSequence seq); boolean equals(Object o); int hashCode(); }
FrameOptions { public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); } FrameOptions(FrameOptionType type); FrameOptions(FrameOptionType type, URI value); FrameOptionType type(); URI uri(); String name(); String toString(); static FrameOptions allowFrom(URI uri); static FrameOptions parse(CharSequence seq); boolean equals(Object o); int hashCode(); static final FrameOptions DENY; static final FrameOptions SAMEORIGIN; }
@Test(expected=IllegalArgumentException.class) public void testInvalidName2() { FrameOptions.parse("DENI http: }
public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); }
FrameOptions { public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); } }
FrameOptions { public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); } FrameOptions(FrameOptionType type); FrameOptions(FrameOptionType type, URI value); }
FrameOptions { public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); } FrameOptions(FrameOptionType type); FrameOptions(FrameOptionType type, URI value); FrameOptionType type(); URI uri(); String name(); String toString(); static FrameOptions allowFrom(URI uri); static FrameOptions parse(CharSequence seq); boolean equals(Object o); int hashCode(); }
FrameOptions { public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); } FrameOptions(FrameOptionType type); FrameOptions(FrameOptionType type, URI value); FrameOptionType type(); URI uri(); String name(); String toString(); static FrameOptions allowFrom(URI uri); static FrameOptions parse(CharSequence seq); boolean equals(Object o); int hashCode(); static final FrameOptions DENY; static final FrameOptions SAMEORIGIN; }
@Test public void testHostEquality() { Label l1 = new Label("one"); Label l2 = new Label("one"); Label l3 = new Label("ONE"); Label l4 = new Label("oNe"); assertEquals(l1, l2); assertEquals(l2, l3); assertEquals(l3, l4); assertEquals(l1, l4); assertEquals(l2, l4); Host one = Host.parse("WWW.Test.CoM"); Host two = Host.parse("www.test.com"); assertEquals(one, two); }
public static URL parse (String url) { Checks.notNull("url", url); return new URLParser(url).getURL(); }
URL implements URLComponent, Validating, Comparable<URL> { public static URL parse (String url) { Checks.notNull("url", url); return new URLParser(url).getURL(); } }
URL implements URLComponent, Validating, Comparable<URL> { public static URL parse (String url) { Checks.notNull("url", url); return new URLParser(url).getURL(); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); }
URL implements URLComponent, Validating, Comparable<URL> { public static URL parse (String url) { Checks.notNull("url", url); return new URLParser(url).getURL(); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); }
URL implements URLComponent, Validating, Comparable<URL> { public static URL parse (String url) { Checks.notNull("url", url); return new URLParser(url).getURL(); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); }
@Test(expected=IllegalArgumentException.class) public void testInvalidUri() { FrameOptions.parse("ALLOW-FROM \\u0000 }
public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); }
FrameOptions { public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); } }
FrameOptions { public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); } FrameOptions(FrameOptionType type); FrameOptions(FrameOptionType type, URI value); }
FrameOptions { public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); } FrameOptions(FrameOptionType type); FrameOptions(FrameOptionType type, URI value); FrameOptionType type(); URI uri(); String name(); String toString(); static FrameOptions allowFrom(URI uri); static FrameOptions parse(CharSequence seq); boolean equals(Object o); int hashCode(); }
FrameOptions { public static FrameOptions parse(CharSequence seq) { Set<CharSequence> s = Strings.splitUniqueNoEmpty(' ', notNull("seq", seq)); if (s.size() > 2) { throw new IllegalArgumentException("FrameOptions should be " + "DENY, SAMEORIGIN or ALLOW-FROM $uri. Found " + s.size() + " elements in '" + seq + "'"); } Iterator<CharSequence> it = s.iterator(); if (!it.hasNext()) { return null; } CharSequence first = it.next(); outer: for (FrameOptionType ft : FrameOptionType.values()) { if (Strings.charSequencesEqual(ft.toString(), first, true)) { if (ft.takesValue != it.hasNext()) { if (it.hasNext()) { throw new IllegalArgumentException(ft + " does not take a value"); } else { throw new IllegalArgumentException(ft + " must be followed by a uri"); } } switch(ft) { case SAMEORIGIN : return SAMEORIGIN; case DENY : return DENY; case ALLOW_FROM : URI uri = URI.create(it.next().toString()); return new FrameOptions(ALLOW_FROM, uri); default : throw new AssertionError(ft); } } } throw new IllegalArgumentException("Could not parse '" + seq + "'"); } FrameOptions(FrameOptionType type); FrameOptions(FrameOptionType type, URI value); FrameOptionType type(); URI uri(); String name(); String toString(); static FrameOptions allowFrom(URI uri); static FrameOptions parse(CharSequence seq); boolean equals(Object o); int hashCode(); static final FrameOptions DENY; static final FrameOptions SAMEORIGIN; }
@Test(expected=IllegalArgumentException.class) public void testInvalidParse1() { StrictTransportSecurity.parse(""); }
public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); }
StrictTransportSecurity implements Comparable<StrictTransportSecurity> { public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); } }
StrictTransportSecurity implements Comparable<StrictTransportSecurity> { public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); } StrictTransportSecurity(Duration maxAge, SecurityElements... elements); StrictTransportSecurity(Duration maxAge, EnumSet<SecurityElements> elements); }
StrictTransportSecurity implements Comparable<StrictTransportSecurity> { public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); } StrictTransportSecurity(Duration maxAge, SecurityElements... elements); StrictTransportSecurity(Duration maxAge, EnumSet<SecurityElements> elements); Set<SecurityElements> elements(); boolean contains(SecurityElements element); Duration maxAge(); static StrictTransportSecurity parse(CharSequence val); int hashCode(); boolean equals(Object o); String toString(); @Override int compareTo(StrictTransportSecurity o); }
StrictTransportSecurity implements Comparable<StrictTransportSecurity> { public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); } StrictTransportSecurity(Duration maxAge, SecurityElements... elements); StrictTransportSecurity(Duration maxAge, EnumSet<SecurityElements> elements); Set<SecurityElements> elements(); boolean contains(SecurityElements element); Duration maxAge(); static StrictTransportSecurity parse(CharSequence val); int hashCode(); boolean equals(Object o); String toString(); @Override int compareTo(StrictTransportSecurity o); static final StrictTransportSecurity ONE_YEAR; static final StrictTransportSecurity ONE_YEAR_INCLUDE_SUBDOMAINS; static final StrictTransportSecurity ONE_YEAR_INCLUDE_SUBDOMAINS_PRELOAD; static final StrictTransportSecurity FIVE_YEARS; static final StrictTransportSecurity FIVE_YEARS_INCLUDE_SUBDOMAINS; static final StrictTransportSecurity FIVE_YEARS_INCLUDE_SUBDOMAINS_PRELOAD; }
@Test(expected=NullArgumentException.class) public void testInvalidConstruct() { StrictTransportSecurity.parse(null); }
public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); }
StrictTransportSecurity implements Comparable<StrictTransportSecurity> { public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); } }
StrictTransportSecurity implements Comparable<StrictTransportSecurity> { public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); } StrictTransportSecurity(Duration maxAge, SecurityElements... elements); StrictTransportSecurity(Duration maxAge, EnumSet<SecurityElements> elements); }
StrictTransportSecurity implements Comparable<StrictTransportSecurity> { public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); } StrictTransportSecurity(Duration maxAge, SecurityElements... elements); StrictTransportSecurity(Duration maxAge, EnumSet<SecurityElements> elements); Set<SecurityElements> elements(); boolean contains(SecurityElements element); Duration maxAge(); static StrictTransportSecurity parse(CharSequence val); int hashCode(); boolean equals(Object o); String toString(); @Override int compareTo(StrictTransportSecurity o); }
StrictTransportSecurity implements Comparable<StrictTransportSecurity> { public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); } StrictTransportSecurity(Duration maxAge, SecurityElements... elements); StrictTransportSecurity(Duration maxAge, EnumSet<SecurityElements> elements); Set<SecurityElements> elements(); boolean contains(SecurityElements element); Duration maxAge(); static StrictTransportSecurity parse(CharSequence val); int hashCode(); boolean equals(Object o); String toString(); @Override int compareTo(StrictTransportSecurity o); static final StrictTransportSecurity ONE_YEAR; static final StrictTransportSecurity ONE_YEAR_INCLUDE_SUBDOMAINS; static final StrictTransportSecurity ONE_YEAR_INCLUDE_SUBDOMAINS_PRELOAD; static final StrictTransportSecurity FIVE_YEARS; static final StrictTransportSecurity FIVE_YEARS_INCLUDE_SUBDOMAINS; static final StrictTransportSecurity FIVE_YEARS_INCLUDE_SUBDOMAINS_PRELOAD; }
@Test(expected=IllegalArgumentException.class) public void testInvalidParse2() { StrictTransportSecurity.parse("preload; includeSubDomains; max-age=61; foodbar"); }
public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); }
StrictTransportSecurity implements Comparable<StrictTransportSecurity> { public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); } }
StrictTransportSecurity implements Comparable<StrictTransportSecurity> { public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); } StrictTransportSecurity(Duration maxAge, SecurityElements... elements); StrictTransportSecurity(Duration maxAge, EnumSet<SecurityElements> elements); }
StrictTransportSecurity implements Comparable<StrictTransportSecurity> { public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); } StrictTransportSecurity(Duration maxAge, SecurityElements... elements); StrictTransportSecurity(Duration maxAge, EnumSet<SecurityElements> elements); Set<SecurityElements> elements(); boolean contains(SecurityElements element); Duration maxAge(); static StrictTransportSecurity parse(CharSequence val); int hashCode(); boolean equals(Object o); String toString(); @Override int compareTo(StrictTransportSecurity o); }
StrictTransportSecurity implements Comparable<StrictTransportSecurity> { public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); } StrictTransportSecurity(Duration maxAge, SecurityElements... elements); StrictTransportSecurity(Duration maxAge, EnumSet<SecurityElements> elements); Set<SecurityElements> elements(); boolean contains(SecurityElements element); Duration maxAge(); static StrictTransportSecurity parse(CharSequence val); int hashCode(); boolean equals(Object o); String toString(); @Override int compareTo(StrictTransportSecurity o); static final StrictTransportSecurity ONE_YEAR; static final StrictTransportSecurity ONE_YEAR_INCLUDE_SUBDOMAINS; static final StrictTransportSecurity ONE_YEAR_INCLUDE_SUBDOMAINS_PRELOAD; static final StrictTransportSecurity FIVE_YEARS; static final StrictTransportSecurity FIVE_YEARS_INCLUDE_SUBDOMAINS; static final StrictTransportSecurity FIVE_YEARS_INCLUDE_SUBDOMAINS_PRELOAD; }
@Test(expected=IllegalArgumentException.class) public void testInvalidParse3() { StrictTransportSecurity.parse("foodbar; preload; includeSubDomains; max-age=61;"); }
public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); }
StrictTransportSecurity implements Comparable<StrictTransportSecurity> { public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); } }
StrictTransportSecurity implements Comparable<StrictTransportSecurity> { public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); } StrictTransportSecurity(Duration maxAge, SecurityElements... elements); StrictTransportSecurity(Duration maxAge, EnumSet<SecurityElements> elements); }
StrictTransportSecurity implements Comparable<StrictTransportSecurity> { public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); } StrictTransportSecurity(Duration maxAge, SecurityElements... elements); StrictTransportSecurity(Duration maxAge, EnumSet<SecurityElements> elements); Set<SecurityElements> elements(); boolean contains(SecurityElements element); Duration maxAge(); static StrictTransportSecurity parse(CharSequence val); int hashCode(); boolean equals(Object o); String toString(); @Override int compareTo(StrictTransportSecurity o); }
StrictTransportSecurity implements Comparable<StrictTransportSecurity> { public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); } StrictTransportSecurity(Duration maxAge, SecurityElements... elements); StrictTransportSecurity(Duration maxAge, EnumSet<SecurityElements> elements); Set<SecurityElements> elements(); boolean contains(SecurityElements element); Duration maxAge(); static StrictTransportSecurity parse(CharSequence val); int hashCode(); boolean equals(Object o); String toString(); @Override int compareTo(StrictTransportSecurity o); static final StrictTransportSecurity ONE_YEAR; static final StrictTransportSecurity ONE_YEAR_INCLUDE_SUBDOMAINS; static final StrictTransportSecurity ONE_YEAR_INCLUDE_SUBDOMAINS_PRELOAD; static final StrictTransportSecurity FIVE_YEARS; static final StrictTransportSecurity FIVE_YEARS_INCLUDE_SUBDOMAINS; static final StrictTransportSecurity FIVE_YEARS_INCLUDE_SUBDOMAINS_PRELOAD; }
@Test(expected=NumberFormatException.class) public void testInvalidParse4() { StrictTransportSecurity.parse("preload; includeSubDomains; max-age=073r8b;"); }
public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); }
StrictTransportSecurity implements Comparable<StrictTransportSecurity> { public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); } }
StrictTransportSecurity implements Comparable<StrictTransportSecurity> { public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); } StrictTransportSecurity(Duration maxAge, SecurityElements... elements); StrictTransportSecurity(Duration maxAge, EnumSet<SecurityElements> elements); }
StrictTransportSecurity implements Comparable<StrictTransportSecurity> { public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); } StrictTransportSecurity(Duration maxAge, SecurityElements... elements); StrictTransportSecurity(Duration maxAge, EnumSet<SecurityElements> elements); Set<SecurityElements> elements(); boolean contains(SecurityElements element); Duration maxAge(); static StrictTransportSecurity parse(CharSequence val); int hashCode(); boolean equals(Object o); String toString(); @Override int compareTo(StrictTransportSecurity o); }
StrictTransportSecurity implements Comparable<StrictTransportSecurity> { public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); } StrictTransportSecurity(Duration maxAge, SecurityElements... elements); StrictTransportSecurity(Duration maxAge, EnumSet<SecurityElements> elements); Set<SecurityElements> elements(); boolean contains(SecurityElements element); Duration maxAge(); static StrictTransportSecurity parse(CharSequence val); int hashCode(); boolean equals(Object o); String toString(); @Override int compareTo(StrictTransportSecurity o); static final StrictTransportSecurity ONE_YEAR; static final StrictTransportSecurity ONE_YEAR_INCLUDE_SUBDOMAINS; static final StrictTransportSecurity ONE_YEAR_INCLUDE_SUBDOMAINS_PRELOAD; static final StrictTransportSecurity FIVE_YEARS; static final StrictTransportSecurity FIVE_YEARS_INCLUDE_SUBDOMAINS; static final StrictTransportSecurity FIVE_YEARS_INCLUDE_SUBDOMAINS_PRELOAD; }
@Test(expected=NumberFormatException.class) public void testInvalidParse5() { StrictTransportSecurity.parse("preload; includeSubDomains; max-age=infinity;"); }
public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); }
StrictTransportSecurity implements Comparable<StrictTransportSecurity> { public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); } }
StrictTransportSecurity implements Comparable<StrictTransportSecurity> { public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); } StrictTransportSecurity(Duration maxAge, SecurityElements... elements); StrictTransportSecurity(Duration maxAge, EnumSet<SecurityElements> elements); }
StrictTransportSecurity implements Comparable<StrictTransportSecurity> { public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); } StrictTransportSecurity(Duration maxAge, SecurityElements... elements); StrictTransportSecurity(Duration maxAge, EnumSet<SecurityElements> elements); Set<SecurityElements> elements(); boolean contains(SecurityElements element); Duration maxAge(); static StrictTransportSecurity parse(CharSequence val); int hashCode(); boolean equals(Object o); String toString(); @Override int compareTo(StrictTransportSecurity o); }
StrictTransportSecurity implements Comparable<StrictTransportSecurity> { public static StrictTransportSecurity parse(CharSequence val) { Set<CharSequence> seqs = Strings.splitUniqueNoEmpty(';', val); Duration maxAge = null; EnumSet<SecurityElements> els = EnumSet.noneOf(SecurityElements.class); for (CharSequence seq : seqs) { seq = Strings.trim(seq); if (seq.length() == 0) { continue; } if (Strings.startsWith(seq, "max-age")) { CharSequence[] maParts = Strings.split('=', seq); if (maParts.length != 2) { throw new IllegalArgumentException("Cannot parse " + seq + " as max-age"); } maParts[1] = Strings.trim(maParts[1]); long seconds = Strings.parseLong(maParts[1]); maxAge = Duration.ofSeconds(seconds); } else if (Strings.charSequencesEqual("includeSubDomains", seq)) { els.add(SecurityElements.INCLUDE_SUBDOMAINS); } else if (Strings.charSequencesEqual("preload", seq)) { els.add(SecurityElements.PRELOAD); } else { throw new IllegalArgumentException("Unrecognized element: '" + seq + "'"); } } if (maxAge == null) { throw new IllegalArgumentException("Required max-age= element missing in '" + val + "'"); } return new StrictTransportSecurity(maxAge, els); } StrictTransportSecurity(Duration maxAge, SecurityElements... elements); StrictTransportSecurity(Duration maxAge, EnumSet<SecurityElements> elements); Set<SecurityElements> elements(); boolean contains(SecurityElements element); Duration maxAge(); static StrictTransportSecurity parse(CharSequence val); int hashCode(); boolean equals(Object o); String toString(); @Override int compareTo(StrictTransportSecurity o); static final StrictTransportSecurity ONE_YEAR; static final StrictTransportSecurity ONE_YEAR_INCLUDE_SUBDOMAINS; static final StrictTransportSecurity ONE_YEAR_INCLUDE_SUBDOMAINS_PRELOAD; static final StrictTransportSecurity FIVE_YEARS; static final StrictTransportSecurity FIVE_YEARS_INCLUDE_SUBDOMAINS; static final StrictTransportSecurity FIVE_YEARS_INCLUDE_SUBDOMAINS_PRELOAD; }
@Test public void testCheckPassword() throws IOException, NoSuchAlgorithmException { assertTrue(true); PasswordHasher h = new PasswordHasher(new SettingsBuilder().build(), Charset.forName("UTF-8")); String pw = "password"; String enc = h.encryptPassword(pw); assertNotNull(enc); String pw2 = "somethingElse"; String enc2 = h.encryptPassword(pw2); assertNotNull(enc2); assertNotEquals(enc, enc2); boolean matches = h.checkPassword(pw2, enc2); assertTrue(matches); matches = h.checkPassword(pw, enc); assertTrue(matches); matches = h.checkPassword(pw2, enc); assertFalse(matches); matches = h.checkPassword(pw, enc2); assertFalse(matches); String old = "a:Du4EC8d82VujiPSlommA2XHrQLtUvytrowONoiG5q0yjG3Ed:4jhJV/hZ4Ab0liMsX0HDG/qJCIvgPCqyAeVB69n+ZdOWNWTXOCypD+WlzJELpKQ1/8tHL6jI709ogWTiJt0/9Q=="; assertTrue("Something has broken password compatibility", h.checkPassword("somethingElse", old)); old = "a:3wWOjtsJci7mL3wknhhtCsZnNmywjXI9w39Y2SiUVIfOaA2s:XZ6i/sDDGW0tEGYW3Bbcg1BitWugNm8DNQnx1p7CowRj9b0tkUQXRwqez60rSmRnBqOSRDw/4FUcg43fdliCZw=="; assertTrue("Something has broken password compatibility", h.checkPassword("password", old)); }
public boolean checkPassword(String unhashed, String hashed) { try { String[] saltAndPassAndAlgorithm = findSalt(hashed); if (saltAndPassAndAlgorithm.length == 1) { byte[] bytes = hash(unhashed, algorithm); byte[] check = Base64.getDecoder().decode(hashed); return Arrays.equals(bytes, check); } if (saltAndPassAndAlgorithm.length != 3) { encryptPassword("DaCuBYLAlxBbT6lTyatauRp2iXCsf9WGDi8a2SyWeFVsoxGBk3Y3l1l9IHie" + "+aVuOGQBD8mZlrhj8yGjl1ghjw==", "3J5pgcx0", algorithm); return false; } String enc = encryptPassword(unhashed, saltAndPassAndAlgorithm[1], decodeAlgorithm(saltAndPassAndAlgorithm[0])); return slowEquals(enc, hashed); } catch (NoSuchAlgorithmException ex) { return Exceptions.chuck(ex); } }
PasswordHasher { public boolean checkPassword(String unhashed, String hashed) { try { String[] saltAndPassAndAlgorithm = findSalt(hashed); if (saltAndPassAndAlgorithm.length == 1) { byte[] bytes = hash(unhashed, algorithm); byte[] check = Base64.getDecoder().decode(hashed); return Arrays.equals(bytes, check); } if (saltAndPassAndAlgorithm.length != 3) { encryptPassword("DaCuBYLAlxBbT6lTyatauRp2iXCsf9WGDi8a2SyWeFVsoxGBk3Y3l1l9IHie" + "+aVuOGQBD8mZlrhj8yGjl1ghjw==", "3J5pgcx0", algorithm); return false; } String enc = encryptPassword(unhashed, saltAndPassAndAlgorithm[1], decodeAlgorithm(saltAndPassAndAlgorithm[0])); return slowEquals(enc, hashed); } catch (NoSuchAlgorithmException ex) { return Exceptions.chuck(ex); } } }
PasswordHasher { public boolean checkPassword(String unhashed, String hashed) { try { String[] saltAndPassAndAlgorithm = findSalt(hashed); if (saltAndPassAndAlgorithm.length == 1) { byte[] bytes = hash(unhashed, algorithm); byte[] check = Base64.getDecoder().decode(hashed); return Arrays.equals(bytes, check); } if (saltAndPassAndAlgorithm.length != 3) { encryptPassword("DaCuBYLAlxBbT6lTyatauRp2iXCsf9WGDi8a2SyWeFVsoxGBk3Y3l1l9IHie" + "+aVuOGQBD8mZlrhj8yGjl1ghjw==", "3J5pgcx0", algorithm); return false; } String enc = encryptPassword(unhashed, saltAndPassAndAlgorithm[1], decodeAlgorithm(saltAndPassAndAlgorithm[0])); return slowEquals(enc, hashed); } catch (NoSuchAlgorithmException ex) { return Exceptions.chuck(ex); } } @Inject PasswordHasher(Settings settings, Charset charset); }
PasswordHasher { public boolean checkPassword(String unhashed, String hashed) { try { String[] saltAndPassAndAlgorithm = findSalt(hashed); if (saltAndPassAndAlgorithm.length == 1) { byte[] bytes = hash(unhashed, algorithm); byte[] check = Base64.getDecoder().decode(hashed); return Arrays.equals(bytes, check); } if (saltAndPassAndAlgorithm.length != 3) { encryptPassword("DaCuBYLAlxBbT6lTyatauRp2iXCsf9WGDi8a2SyWeFVsoxGBk3Y3l1l9IHie" + "+aVuOGQBD8mZlrhj8yGjl1ghjw==", "3J5pgcx0", algorithm); return false; } String enc = encryptPassword(unhashed, saltAndPassAndAlgorithm[1], decodeAlgorithm(saltAndPassAndAlgorithm[0])); return slowEquals(enc, hashed); } catch (NoSuchAlgorithmException ex) { return Exceptions.chuck(ex); } } @Inject PasswordHasher(Settings settings, Charset charset); boolean checkPassword(String unhashed, String hashed); String hash(String s); String encryptPassword(String password); }
PasswordHasher { public boolean checkPassword(String unhashed, String hashed) { try { String[] saltAndPassAndAlgorithm = findSalt(hashed); if (saltAndPassAndAlgorithm.length == 1) { byte[] bytes = hash(unhashed, algorithm); byte[] check = Base64.getDecoder().decode(hashed); return Arrays.equals(bytes, check); } if (saltAndPassAndAlgorithm.length != 3) { encryptPassword("DaCuBYLAlxBbT6lTyatauRp2iXCsf9WGDi8a2SyWeFVsoxGBk3Y3l1l9IHie" + "+aVuOGQBD8mZlrhj8yGjl1ghjw==", "3J5pgcx0", algorithm); return false; } String enc = encryptPassword(unhashed, saltAndPassAndAlgorithm[1], decodeAlgorithm(saltAndPassAndAlgorithm[0])); return slowEquals(enc, hashed); } catch (NoSuchAlgorithmException ex) { return Exceptions.chuck(ex); } } @Inject PasswordHasher(Settings settings, Charset charset); boolean checkPassword(String unhashed, String hashed); String hash(String s); String encryptPassword(String password); static final String SETTINGS_KEY_PASSWORD_SALT; static final String SETTINGS_KEY_HASHING_ALGORITHM; static final String DEFAULT_HASHING_ALGORITHM; static final String SETTINGS_KEY_RANDOM_SALT_LENGTH; static final int DEFAULT_RANDOM_SALT_LENGTH; }
@Test public void testDurationConversionWorks() { RotatingRealmProvider prov = new RotatingRealmProvider(Settings.EMPTY); Realm realm = prov.get(); assertEquals(realm, prov.get()); }
@Override public Realm get() { Duration since1970 = Duration.ofMillis(System.currentTimeMillis()); long minutesSince1970 = since1970.toMinutes(); long intervals = minutesSince1970 / interval.toMinutes(); return new Realm(Strings.interleave(Long.toString(intervals, 36), salt)); }
RotatingRealmProvider implements Provider<Realm> { @Override public Realm get() { Duration since1970 = Duration.ofMillis(System.currentTimeMillis()); long minutesSince1970 = since1970.toMinutes(); long intervals = minutesSince1970 / interval.toMinutes(); return new Realm(Strings.interleave(Long.toString(intervals, 36), salt)); } }
RotatingRealmProvider implements Provider<Realm> { @Override public Realm get() { Duration since1970 = Duration.ofMillis(System.currentTimeMillis()); long minutesSince1970 = since1970.toMinutes(); long intervals = minutesSince1970 / interval.toMinutes(); return new Realm(Strings.interleave(Long.toString(intervals, 36), salt)); } @Inject RotatingRealmProvider(Settings s); }
RotatingRealmProvider implements Provider<Realm> { @Override public Realm get() { Duration since1970 = Duration.ofMillis(System.currentTimeMillis()); long minutesSince1970 = since1970.toMinutes(); long intervals = minutesSince1970 / interval.toMinutes(); return new Realm(Strings.interleave(Long.toString(intervals, 36), salt)); } @Inject RotatingRealmProvider(Settings s); @Override Realm get(); }
RotatingRealmProvider implements Provider<Realm> { @Override public Realm get() { Duration since1970 = Duration.ofMillis(System.currentTimeMillis()); long minutesSince1970 = since1970.toMinutes(); long intervals = minutesSince1970 / interval.toMinutes(); return new Realm(Strings.interleave(Long.toString(intervals, 36), salt)); } @Inject RotatingRealmProvider(Settings s); @Override Realm get(); static final String SETTINGS_KEY_ROTATE_INTERVAL_MINUTES; static final int DEFAULT_ROTATE_INTERVAL; }
@Test @SuppressWarnings("unchecked") public void testTypeMatching() { for (Class<?> c : classes) { Class<? extends Page> pg = (Class<? extends Page>) c; ShouldMatch shoulds = pg.getAnnotation(ShouldMatch.class); if (shoulds != null) { Method mth = pg.getAnnotation(Methods.class).value()[0]; for (String uri : shoulds.value()) { HttpRequest req = req(mth, uri); assertTrue(mth + " " + uri + " should be matched but isn't", pgs.match(req)); } } ShouldNotMatch shouldntss = pg.getAnnotation(ShouldNotMatch.class); if (shouldntss != null) { Method mth = pg.getAnnotation(Methods.class).value()[0]; for (String uri : shouldntss.value()) { HttpRequest req = req(mth, uri); assertFalse(mth + " " + uri + " should be matched but isn't", pgs.match(req)); } } } }
public boolean match(HttpRequest req) { String path = this.basePathFilter.apply(req.uri()); if (path == null) { return false; } path = trimLeadingAndTrailingSlashes(trimQuery(path)); Method method = Method.get(req); MethodPath mp = new MethodPath(method, path); if (nonMatchesCache.contains(mp)) { return false; } if (matchesCache.contains(mp)) { return true; } ByMethod bm = all.get(mp.method); if (bm == null) { nonMatchesCache.add(mp); return false; } if (bm.match(mp.path)) { matchesCache.add(mp); return true; } else { nonMatchesCache.add(mp); return false; } }
PagePathAndMethodFilter { public boolean match(HttpRequest req) { String path = this.basePathFilter.apply(req.uri()); if (path == null) { return false; } path = trimLeadingAndTrailingSlashes(trimQuery(path)); Method method = Method.get(req); MethodPath mp = new MethodPath(method, path); if (nonMatchesCache.contains(mp)) { return false; } if (matchesCache.contains(mp)) { return true; } ByMethod bm = all.get(mp.method); if (bm == null) { nonMatchesCache.add(mp); return false; } if (bm.match(mp.path)) { matchesCache.add(mp); return true; } else { nonMatchesCache.add(mp); return false; } } }
PagePathAndMethodFilter { public boolean match(HttpRequest req) { String path = this.basePathFilter.apply(req.uri()); if (path == null) { return false; } path = trimLeadingAndTrailingSlashes(trimQuery(path)); Method method = Method.get(req); MethodPath mp = new MethodPath(method, path); if (nonMatchesCache.contains(mp)) { return false; } if (matchesCache.contains(mp)) { return true; } ByMethod bm = all.get(mp.method); if (bm == null) { nonMatchesCache.add(mp); return false; } if (bm.match(mp.path)) { matchesCache.add(mp); return true; } else { nonMatchesCache.add(mp); return false; } } PagePathAndMethodFilter(Function<String, String> basePathFilter); PagePathAndMethodFilter(); PagePathAndMethodFilter(String basePath); }
PagePathAndMethodFilter { public boolean match(HttpRequest req) { String path = this.basePathFilter.apply(req.uri()); if (path == null) { return false; } path = trimLeadingAndTrailingSlashes(trimQuery(path)); Method method = Method.get(req); MethodPath mp = new MethodPath(method, path); if (nonMatchesCache.contains(mp)) { return false; } if (matchesCache.contains(mp)) { return true; } ByMethod bm = all.get(mp.method); if (bm == null) { nonMatchesCache.add(mp); return false; } if (bm.match(mp.path)) { matchesCache.add(mp); return true; } else { nonMatchesCache.add(mp); return false; } } PagePathAndMethodFilter(Function<String, String> basePathFilter); PagePathAndMethodFilter(); PagePathAndMethodFilter(String basePath); @Override String toString(); boolean match(HttpRequest req); List<Object> listFor(HttpRequest req); }
PagePathAndMethodFilter { public boolean match(HttpRequest req) { String path = this.basePathFilter.apply(req.uri()); if (path == null) { return false; } path = trimLeadingAndTrailingSlashes(trimQuery(path)); Method method = Method.get(req); MethodPath mp = new MethodPath(method, path); if (nonMatchesCache.contains(mp)) { return false; } if (matchesCache.contains(mp)) { return true; } ByMethod bm = all.get(mp.method); if (bm == null) { nonMatchesCache.add(mp); return false; } if (bm.match(mp.path)) { matchesCache.add(mp); return true; } else { nonMatchesCache.add(mp); return false; } } PagePathAndMethodFilter(Function<String, String> basePathFilter); PagePathAndMethodFilter(); PagePathAndMethodFilter(String basePath); @Override String toString(); boolean match(HttpRequest req); List<Object> listFor(HttpRequest req); }
@Test public void testHighAsciiCharactersInPath() { PathElement el = new PathElement("foo"); assertTrue(el.isValid()); el = new PathElement(createHighAsciiString()); assertTrue(el.isValid()); }
@Override public boolean isValid() { URLComponent[] comps = components(); boolean result = comps.length > 0 && protocol != null && (!protocol.isNetworkProtocol() || host != null); if (result) { for (URLComponent c : comps) { if (c instanceof Host) { Host h = (Host) c; if (h != null && Protocols.FILE.match(getProtocol()) && "".equals(h.toString())) { continue; } } result = c.isValid(); if (!result) { break; } } } return result; }
URL implements URLComponent, Validating, Comparable<URL> { @Override public boolean isValid() { URLComponent[] comps = components(); boolean result = comps.length > 0 && protocol != null && (!protocol.isNetworkProtocol() || host != null); if (result) { for (URLComponent c : comps) { if (c instanceof Host) { Host h = (Host) c; if (h != null && Protocols.FILE.match(getProtocol()) && "".equals(h.toString())) { continue; } } result = c.isValid(); if (!result) { break; } } } return result; } }
URL implements URLComponent, Validating, Comparable<URL> { @Override public boolean isValid() { URLComponent[] comps = components(); boolean result = comps.length > 0 && protocol != null && (!protocol.isNetworkProtocol() || host != null); if (result) { for (URLComponent c : comps) { if (c instanceof Host) { Host h = (Host) c; if (h != null && Protocols.FILE.match(getProtocol()) && "".equals(h.toString())) { continue; } } result = c.isValid(); if (!result) { break; } } } return result; } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); }
URL implements URLComponent, Validating, Comparable<URL> { @Override public boolean isValid() { URLComponent[] comps = components(); boolean result = comps.length > 0 && protocol != null && (!protocol.isNetworkProtocol() || host != null); if (result) { for (URLComponent c : comps) { if (c instanceof Host) { Host h = (Host) c; if (h != null && Protocols.FILE.match(getProtocol()) && "".equals(h.toString())) { continue; } } result = c.isValid(); if (!result) { break; } } } return result; } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); }
URL implements URLComponent, Validating, Comparable<URL> { @Override public boolean isValid() { URLComponent[] comps = components(); boolean result = comps.length > 0 && protocol != null && (!protocol.isNetworkProtocol() || host != null); if (result) { for (URLComponent c : comps) { if (c instanceof Host) { Host h = (Host) c; if (h != null && Protocols.FILE.match(getProtocol()) && "".equals(h.toString())) { continue; } } result = c.isValid(); if (!result) { break; } } } return result; } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); }
@Test public void testNewerFeatures() throws Throwable { DefaultPathFactory f = new DefaultPathFactory(new SettingsBuilder() .add(ServerModule.SETTINGS_KEY_BASE_PATH, "/foo") .add(ServerModule.SETTINGS_KEY_GENERATE_SECURE_URLS, "true") .add(ServerModule.SETTINGS_KEY_URLS_HOST_NAME, "paths.example") .add(ServerModule.SETTINGS_KEY_URLS_EXTERNAL_PORT, 5720) .add(ServerModule.SETTINGS_KEY_URLS_EXTERNAL_SECURE_PORT, 5721) .build()); URL url = f.constructURL("/hey/you"); assertTrue(url.isValid()); String test1 = "https: String test2 = "https: assertEquals(test1 + "\tversus\n" + url, test1, url.toString()); assertEquals(url.toString(), f.constructURI("/hey/you").toString()); EventImpl fakeEvent = new EventImpl(new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/up/down", new DefaultHttpHeaders().add(HttpHeaderNames.HOST, "timboudreau.org:5223")), f); url = f.constructURL("/whee?this=that&you=me", fakeEvent); assertTrue(url.isValid()); assertEquals("timboudreau.org", url.getHost().toString()); assertEquals(5223, url.getPort().intValue()); assertEquals(test2 + "\tversus\n" + url, test2, url.toString()); url = f.constructURL("/whee?this=that&you=me#woohoo", fakeEvent); assertTrue(url.isValid()); assertEquals("woohoo", url.getAnchor().toString()); assertNotNull(url + " has no parameters", url.getParameters()); assertTrue(url.getParameters().isValid()); fakeEvent = new EventImpl(new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/up/down", new DefaultHttpHeaders() .add(Headers.X_FORWARDED_PROTO.name(), "http")), f); url = f.constructURL("/should/be/insecure", fakeEvent); assertEquals("/foo/should/be/insecure", url.getPath().toStringWithLeadingSlash()); assertEquals(HTTP, url.getProtocol()); assertEquals("paths.example", url.getHost().toString()); assertEquals(5720, url.getPort().intValue()); }
@Override public URL constructURL(Path path) { return constructURL(path, secure); }
DefaultPathFactory implements PathFactory { @Override public URL constructURL(Path path) { return constructURL(path, secure); } }
DefaultPathFactory implements PathFactory { @Override public URL constructURL(Path path) { return constructURL(path, secure); } @Inject DefaultPathFactory(Settings settings); }
DefaultPathFactory implements PathFactory { @Override public URL constructURL(Path path) { return constructURL(path, secure); } @Inject DefaultPathFactory(Settings settings); @Override int portForProtocol(Protocol protocol); @Override Path toExternalPath(String path); @Override Path toExternalPath(Path path); @Override URL constructURL(Path path); @Override Path toPath(String uri); @Override URL constructURL(Protocol protocol, Path path); URL constructURL(Protocol protocol, Path path, boolean secure); URL constructURL(Protocol protocol, Path path, int port); @Override URL constructURL(Path path, boolean secure); @Override URL constructURL(String path, HttpEvent evt); }
DefaultPathFactory implements PathFactory { @Override public URL constructURL(Path path) { return constructURL(path, secure); } @Inject DefaultPathFactory(Settings settings); @Override int portForProtocol(Protocol protocol); @Override Path toExternalPath(String path); @Override Path toExternalPath(Path path); @Override URL constructURL(Path path); @Override Path toPath(String uri); @Override URL constructURL(Protocol protocol, Path path); URL constructURL(Protocol protocol, Path path, boolean secure); URL constructURL(Protocol protocol, Path path, int port); @Override URL constructURL(Path path, boolean secure); @Override URL constructURL(String path, HttpEvent evt); }
@Test public void test(@Named("stuff") MongoCollection<Document> stuff) throws InterruptedException, IOException { byte[] bytes = new byte[120]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) (120 - i); } List<Object> list = new LinkedList<>(); list.add(1); list.add(2); list.add(2); list.add("hello"); list.add(new Document("in", "list")); Document document = new Document("hello", "world") .append("boolValue", true) .append("list", list) .append("intValue", 32) .append("dbl", 32.000235D) .append("subdoc", new Document("other", "stuff")) .append("longValue", Long.valueOf(Integer.MAX_VALUE + 1L)) .append("_id", new ObjectId()) .append("bytes", bytes); CB<Void> cb = new CB<Void>(); stuff.insertOne(document, cb); cb.get(); Thread.sleep(200); MongoCollection<ByteBuf> bbc = stuff.withDocumentClass(ByteBuf.class); CB<ByteBuf> bb = new CB<ByteBuf>(); bbc.find(new Document("_id", document.get("_id"))) .batchSize(1) .projection(new Document("hello", 1) .append("boolValue", 1) .append("intValue", 1) .append("longValue", 1) .append("dbl", 1) .append("list", 1) .append("subdoc", 1) .append("bytes", 1) .append("_id", 1)) .first(bb); ByteBuf buf = bb.get(); assertNotNull(buf); String content = Streams.readString(new ByteBufInputStream(buf)); buf.resetReaderIndex(); Map m = new ObjectMapper().readValue(content, Map.class); for (Map.Entry<String, Object> e : document.entrySet()) { Object other = m.get(e.getKey()); assertNotNull(e.getKey() + " is null", other); Object value = e.getValue(); assertNotNull(value); switch (e.getKey()) { case "_id": assertTrue(value instanceof ObjectId); assertTrue(other instanceof String); value = value.toString(); break; case "bytes": assertTrue(other.getClass().getName(), other instanceof String); other = Base64.getDecoder().decode((String)other); continue; } if (value instanceof byte[]) { assertTrue(other instanceof byte[]); assertTrue(value instanceof byte[]); assertArrayEquals((byte[]) value, (byte[]) other); } else { assertEquals(other, value); } } }
@Override public ByteBuf decode(BsonReader reader, DecoderContext dc) { ByteBuf buf = alloc.buffer(); JsonWriterSettings settings = JsonWriterSettings.builder() .indent(false).build(); PlainJsonWriter json = new PlainJsonWriter(buf, settings); json.pipe(reader); return buf; }
ByteBufCodec implements Codec<ByteBuf> { @Override public ByteBuf decode(BsonReader reader, DecoderContext dc) { ByteBuf buf = alloc.buffer(); JsonWriterSettings settings = JsonWriterSettings.builder() .indent(false).build(); PlainJsonWriter json = new PlainJsonWriter(buf, settings); json.pipe(reader); return buf; } }
ByteBufCodec implements Codec<ByteBuf> { @Override public ByteBuf decode(BsonReader reader, DecoderContext dc) { ByteBuf buf = alloc.buffer(); JsonWriterSettings settings = JsonWriterSettings.builder() .indent(false).build(); PlainJsonWriter json = new PlainJsonWriter(buf, settings); json.pipe(reader); return buf; } @Inject ByteBufCodec(ByteBufAllocator alloc); }
ByteBufCodec implements Codec<ByteBuf> { @Override public ByteBuf decode(BsonReader reader, DecoderContext dc) { ByteBuf buf = alloc.buffer(); JsonWriterSettings settings = JsonWriterSettings.builder() .indent(false).build(); PlainJsonWriter json = new PlainJsonWriter(buf, settings); json.pipe(reader); return buf; } @Inject ByteBufCodec(ByteBufAllocator alloc); void writeDateTime(BsonWriter writer, ZonedDateTime t, EncoderContext ec); @Override void encode(BsonWriter writer, ByteBuf t, EncoderContext ec); @Override Class<ByteBuf> getEncoderClass(); @Override ByteBuf decode(BsonReader reader, DecoderContext dc); }
ByteBufCodec implements Codec<ByteBuf> { @Override public ByteBuf decode(BsonReader reader, DecoderContext dc) { ByteBuf buf = alloc.buffer(); JsonWriterSettings settings = JsonWriterSettings.builder() .indent(false).build(); PlainJsonWriter json = new PlainJsonWriter(buf, settings); json.pipe(reader); return buf; } @Inject ByteBufCodec(ByteBufAllocator alloc); void writeDateTime(BsonWriter writer, ZonedDateTime t, EncoderContext ec); @Override void encode(BsonWriter writer, ByteBuf t, EncoderContext ec); @Override Class<ByteBuf> getEncoderClass(); @Override ByteBuf decode(BsonReader reader, DecoderContext dc); }
@Test public void testHighAsciiCharactersInLabel() { Label lbl = new Label("foo"); assertTrue(lbl.isValid()); lbl = new Label(createHighAsciiString()); assertFalse(lbl.isValid()); }
@Override public boolean isValid() { URLComponent[] comps = components(); boolean result = comps.length > 0 && protocol != null && (!protocol.isNetworkProtocol() || host != null); if (result) { for (URLComponent c : comps) { if (c instanceof Host) { Host h = (Host) c; if (h != null && Protocols.FILE.match(getProtocol()) && "".equals(h.toString())) { continue; } } result = c.isValid(); if (!result) { break; } } } return result; }
URL implements URLComponent, Validating, Comparable<URL> { @Override public boolean isValid() { URLComponent[] comps = components(); boolean result = comps.length > 0 && protocol != null && (!protocol.isNetworkProtocol() || host != null); if (result) { for (URLComponent c : comps) { if (c instanceof Host) { Host h = (Host) c; if (h != null && Protocols.FILE.match(getProtocol()) && "".equals(h.toString())) { continue; } } result = c.isValid(); if (!result) { break; } } } return result; } }
URL implements URLComponent, Validating, Comparable<URL> { @Override public boolean isValid() { URLComponent[] comps = components(); boolean result = comps.length > 0 && protocol != null && (!protocol.isNetworkProtocol() || host != null); if (result) { for (URLComponent c : comps) { if (c instanceof Host) { Host h = (Host) c; if (h != null && Protocols.FILE.match(getProtocol()) && "".equals(h.toString())) { continue; } } result = c.isValid(); if (!result) { break; } } } return result; } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); }
URL implements URLComponent, Validating, Comparable<URL> { @Override public boolean isValid() { URLComponent[] comps = components(); boolean result = comps.length > 0 && protocol != null && (!protocol.isNetworkProtocol() || host != null); if (result) { for (URLComponent c : comps) { if (c instanceof Host) { Host h = (Host) c; if (h != null && Protocols.FILE.match(getProtocol()) && "".equals(h.toString())) { continue; } } result = c.isValid(); if (!result) { break; } } } return result; } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); }
URL implements URLComponent, Validating, Comparable<URL> { @Override public boolean isValid() { URLComponent[] comps = components(); boolean result = comps.length > 0 && protocol != null && (!protocol.isNetworkProtocol() || host != null); if (result) { for (URLComponent c : comps) { if (c instanceof Host) { Host h = (Host) c; if (h != null && Protocols.FILE.match(getProtocol()) && "".equals(h.toString())) { continue; } } result = c.isValid(); if (!result) { break; } } } return result; } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); }
@Test public void testUnescape2() { StringBuilder sb = new StringBuilder(); for (char c = 1; c < 6; c++) { sb.append(c); } String unescaped = sb.toString(); String escaped = URLBuilder.escape(unescaped); String re_unescaped = URLBuilder.unescape(escaped); assertEquals(unescaped, re_unescaped); }
@Override public String toString() { StringBuilder sb = new StringBuilder(); appendTo (sb); if (sb.length() > 0 && isHostOnlyURL() && sb.charAt(sb.length() - 1) != '/') { sb.append ('/'); } return sb.toString(); }
URL implements URLComponent, Validating, Comparable<URL> { @Override public String toString() { StringBuilder sb = new StringBuilder(); appendTo (sb); if (sb.length() > 0 && isHostOnlyURL() && sb.charAt(sb.length() - 1) != '/') { sb.append ('/'); } return sb.toString(); } }
URL implements URLComponent, Validating, Comparable<URL> { @Override public String toString() { StringBuilder sb = new StringBuilder(); appendTo (sb); if (sb.length() > 0 && isHostOnlyURL() && sb.charAt(sb.length() - 1) != '/') { sb.append ('/'); } return sb.toString(); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); }
URL implements URLComponent, Validating, Comparable<URL> { @Override public String toString() { StringBuilder sb = new StringBuilder(); appendTo (sb); if (sb.length() > 0 && isHostOnlyURL() && sb.charAt(sb.length() - 1) != '/') { sb.append ('/'); } return sb.toString(); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); }
URL implements URLComponent, Validating, Comparable<URL> { @Override public String toString() { StringBuilder sb = new StringBuilder(); appendTo (sb); if (sb.length() > 0 && isHostOnlyURL() && sb.charAt(sb.length() - 1) != '/') { sb.append ('/'); } return sb.toString(); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); }
@Test public void testUnescape3() { StringBuilder sb = new StringBuilder(); for (char c = 5; c < 25; c++) { sb.append(c); } String unescaped = sb.toString(); String escaped = URLBuilder.escape(unescaped); String re_unescaped = URLBuilder.unescape(escaped); assertEquals(unescaped, re_unescaped); }
@Override public String toString() { StringBuilder sb = new StringBuilder(); appendTo (sb); if (sb.length() > 0 && isHostOnlyURL() && sb.charAt(sb.length() - 1) != '/') { sb.append ('/'); } return sb.toString(); }
URL implements URLComponent, Validating, Comparable<URL> { @Override public String toString() { StringBuilder sb = new StringBuilder(); appendTo (sb); if (sb.length() > 0 && isHostOnlyURL() && sb.charAt(sb.length() - 1) != '/') { sb.append ('/'); } return sb.toString(); } }
URL implements URLComponent, Validating, Comparable<URL> { @Override public String toString() { StringBuilder sb = new StringBuilder(); appendTo (sb); if (sb.length() > 0 && isHostOnlyURL() && sb.charAt(sb.length() - 1) != '/') { sb.append ('/'); } return sb.toString(); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); }
URL implements URLComponent, Validating, Comparable<URL> { @Override public String toString() { StringBuilder sb = new StringBuilder(); appendTo (sb); if (sb.length() > 0 && isHostOnlyURL() && sb.charAt(sb.length() - 1) != '/') { sb.append ('/'); } return sb.toString(); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); }
URL implements URLComponent, Validating, Comparable<URL> { @Override public String toString() { StringBuilder sb = new StringBuilder(); appendTo (sb); if (sb.length() > 0 && isHostOnlyURL() && sb.charAt(sb.length() - 1) != '/') { sb.append ('/'); } return sb.toString(); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); }
@Test public void testParse() throws Exception { test("http: test("http: test("http: test("http: test("http: test("http: test("http: test("http: test("http: test("http: }
public static URL parse (String url) { Checks.notNull("url", url); return new URLParser(url).getURL(); }
URL implements URLComponent, Validating, Comparable<URL> { public static URL parse (String url) { Checks.notNull("url", url); return new URLParser(url).getURL(); } }
URL implements URLComponent, Validating, Comparable<URL> { public static URL parse (String url) { Checks.notNull("url", url); return new URLParser(url).getURL(); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); }
URL implements URLComponent, Validating, Comparable<URL> { public static URL parse (String url) { Checks.notNull("url", url); return new URLParser(url).getURL(); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); }
URL implements URLComponent, Validating, Comparable<URL> { public static URL parse (String url) { Checks.notNull("url", url); return new URLParser(url).getURL(); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); }
@Test public void testHostParents() { Host h = Host.parse("www.timboudreau.com"); assertEquals(Host.parse("timboudreau.com"), h.getParentDomain()); Label[] l = h.getLabels(); assertEquals(new Label("com"), l[0]); assertEquals(new Label("timboudreau"), l[1]); assertEquals(new Label("www"), l[2]); assertEquals(new Label("com"), h.getTopLevelDomain()); assertEquals(new Label("timboudreau"), h.getDomain()); }
public static URL parse (String url) { Checks.notNull("url", url); return new URLParser(url).getURL(); }
URL implements URLComponent, Validating, Comparable<URL> { public static URL parse (String url) { Checks.notNull("url", url); return new URLParser(url).getURL(); } }
URL implements URLComponent, Validating, Comparable<URL> { public static URL parse (String url) { Checks.notNull("url", url); return new URLParser(url).getURL(); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); }
URL implements URLComponent, Validating, Comparable<URL> { public static URL parse (String url) { Checks.notNull("url", url); return new URLParser(url).getURL(); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); }
URL implements URLComponent, Validating, Comparable<URL> { public static URL parse (String url) { Checks.notNull("url", url); return new URLParser(url).getURL(); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); }
@Test public void testSameDomain() { Host h = Host.parse("weblogs.java.net"); assertTrue(h.isDomain("java.net")); assertTrue(h.isDomain("weblogs.java.net")); assertFalse(h.isDomain("bubble.java.net")); assertFalse(h.isDomain("java.com")); }
public static URL parse (String url) { Checks.notNull("url", url); return new URLParser(url).getURL(); }
URL implements URLComponent, Validating, Comparable<URL> { public static URL parse (String url) { Checks.notNull("url", url); return new URLParser(url).getURL(); } }
URL implements URLComponent, Validating, Comparable<URL> { public static URL parse (String url) { Checks.notNull("url", url); return new URLParser(url).getURL(); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); }
URL implements URLComponent, Validating, Comparable<URL> { public static URL parse (String url) { Checks.notNull("url", url); return new URLParser(url).getURL(); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); }
URL implements URLComponent, Validating, Comparable<URL> { public static URL parse (String url) { Checks.notNull("url", url); return new URLParser(url).getURL(); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); }
@Test public void testUnescape() { assertEquals("hello world", URLBuilder.unescape("hello%20world")); assertEquals(" ", URLBuilder.unescape("%20")); StringBuilder sb = new StringBuilder(); for (char c = 1; c < 255; c++) { if (c == 25) { continue; } sb.append(c); } String unescaped = sb.toString(); String escaped = URLBuilder.escape(unescaped); String re_unescaped = URLBuilder.unescape(escaped); assertEquals(examine(unescaped, re_unescaped), unescaped, re_unescaped); }
@Override public String toString() { StringBuilder sb = new StringBuilder(); appendTo (sb); if (sb.length() > 0 && isHostOnlyURL() && sb.charAt(sb.length() - 1) != '/') { sb.append ('/'); } return sb.toString(); }
URL implements URLComponent, Validating, Comparable<URL> { @Override public String toString() { StringBuilder sb = new StringBuilder(); appendTo (sb); if (sb.length() > 0 && isHostOnlyURL() && sb.charAt(sb.length() - 1) != '/') { sb.append ('/'); } return sb.toString(); } }
URL implements URLComponent, Validating, Comparable<URL> { @Override public String toString() { StringBuilder sb = new StringBuilder(); appendTo (sb); if (sb.length() > 0 && isHostOnlyURL() && sb.charAt(sb.length() - 1) != '/') { sb.append ('/'); } return sb.toString(); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); }
URL implements URLComponent, Validating, Comparable<URL> { @Override public String toString() { StringBuilder sb = new StringBuilder(); appendTo (sb); if (sb.length() > 0 && isHostOnlyURL() && sb.charAt(sb.length() - 1) != '/') { sb.append ('/'); } return sb.toString(); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); }
URL implements URLComponent, Validating, Comparable<URL> { @Override public String toString() { StringBuilder sb = new StringBuilder(); appendTo (sb); if (sb.length() > 0 && isHostOnlyURL() && sb.charAt(sb.length() - 1) != '/') { sb.append ('/'); } return sb.toString(); } URL(String userName, String password, Protocol protocol, Host host, Port port, Path path, Parameters query, Anchor anchor); URL withProtocol(Protocol protocol); static URLBuilder builder(); static URLBuilder builder(Protocol protocol); static URLBuilder builder(URL startWith); static URL parse(String url); URL getBaseURL(boolean retainPort); Anchor getAnchor(); Host getHost(); Path getPath(); Port getPort(); Protocol getProtocol(); Parameters getParameters(); URLComponent getUserName(); URLComponent getPassword(); boolean isKnownProtocol(); boolean isProbableFileReference(); boolean isSameDomain(String domain); HostAndPort getHostAndPort(); void appendTo(StringBuilder sb); String getPathAndQuery(); boolean isSecure(); URLComponent[] components(); URLComponent[] allComponents(); URLComponent getInvalidComponent(); @Override boolean isValid(); String getComponentName(); @Override String toString(); String toUnescapedForm(); URL stripAnchor(); URL stripQuery(); URL toSimpleURL(); URI toURI(); URL withParameter(String name, String value); boolean simpleEquals(URL other); URL getParentURL(); static URL fromFile(File file); static URL fromJavaUrl(java.net.URL url); @Override boolean equals(Object obj); @Override int hashCode(); static Charset getURLEncoding(); java.net.URL toJavaURL(); @Override @SuppressWarnings("EmptyIfStmt") Problems getProblems(); @Override int compareTo(URL o); }
@Test public void test_WHEN_valid_GIVEN_valid_model_THEN_ok_no_errors() { PersonModel person = new PersonModel( "Kim", "Kardashian", new GregorianCalendar(1980, Calendar.OCTOBER, 21)); ValidationByResponseHandler validator = new ValidationByResponseHandler(); Response response = validator.validate(person); assertThat(response.getStatus()).isEqualTo(200); }
<T> Response validate(T object) { Set<ConstraintViolation<T>> errs = jeeValidator.validate(object); if (errs.isEmpty()) { return Response.status(200).entity(object).build(); } else { String msg = "Invalid Bean, constraint error(s) : "; for (ConstraintViolation<T> err : errs) { msg += err.getPropertyPath() + " " + err.getMessage() + ". "; } return Response.status(400).entity(msg).build(); } }
ValidationByResponseHandler { <T> Response validate(T object) { Set<ConstraintViolation<T>> errs = jeeValidator.validate(object); if (errs.isEmpty()) { return Response.status(200).entity(object).build(); } else { String msg = "Invalid Bean, constraint error(s) : "; for (ConstraintViolation<T> err : errs) { msg += err.getPropertyPath() + " " + err.getMessage() + ". "; } return Response.status(400).entity(msg).build(); } } }
ValidationByResponseHandler { <T> Response validate(T object) { Set<ConstraintViolation<T>> errs = jeeValidator.validate(object); if (errs.isEmpty()) { return Response.status(200).entity(object).build(); } else { String msg = "Invalid Bean, constraint error(s) : "; for (ConstraintViolation<T> err : errs) { msg += err.getPropertyPath() + " " + err.getMessage() + ". "; } return Response.status(400).entity(msg).build(); } } }
ValidationByResponseHandler { <T> Response validate(T object) { Set<ConstraintViolation<T>> errs = jeeValidator.validate(object); if (errs.isEmpty()) { return Response.status(200).entity(object).build(); } else { String msg = "Invalid Bean, constraint error(s) : "; for (ConstraintViolation<T> err : errs) { msg += err.getPropertyPath() + " " + err.getMessage() + ". "; } return Response.status(400).entity(msg).build(); } } }
ValidationByResponseHandler { <T> Response validate(T object) { Set<ConstraintViolation<T>> errs = jeeValidator.validate(object); if (errs.isEmpty()) { return Response.status(200).entity(object).build(); } else { String msg = "Invalid Bean, constraint error(s) : "; for (ConstraintViolation<T> err : errs) { msg += err.getPropertyPath() + " " + err.getMessage() + ". "; } return Response.status(400).entity(msg).build(); } } }
@Test public void test_WHEN_valid_GIVEN_invalid_model_THEN_error() { PersonModel person = new PersonModel( null, "", null); ValidationByResponseHandler validator = new ValidationByResponseHandler(); Response response = validator.validate(person); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.getEntity().toString()) .contains("Invalid Bean, constraint error(s) : ") .contains("birthDate may not be null.") .contains("firstName may not be null.") .contains("lastName size must be between 1 and 16."); }
<T> Response validate(T object) { Set<ConstraintViolation<T>> errs = jeeValidator.validate(object); if (errs.isEmpty()) { return Response.status(200).entity(object).build(); } else { String msg = "Invalid Bean, constraint error(s) : "; for (ConstraintViolation<T> err : errs) { msg += err.getPropertyPath() + " " + err.getMessage() + ". "; } return Response.status(400).entity(msg).build(); } }
ValidationByResponseHandler { <T> Response validate(T object) { Set<ConstraintViolation<T>> errs = jeeValidator.validate(object); if (errs.isEmpty()) { return Response.status(200).entity(object).build(); } else { String msg = "Invalid Bean, constraint error(s) : "; for (ConstraintViolation<T> err : errs) { msg += err.getPropertyPath() + " " + err.getMessage() + ". "; } return Response.status(400).entity(msg).build(); } } }
ValidationByResponseHandler { <T> Response validate(T object) { Set<ConstraintViolation<T>> errs = jeeValidator.validate(object); if (errs.isEmpty()) { return Response.status(200).entity(object).build(); } else { String msg = "Invalid Bean, constraint error(s) : "; for (ConstraintViolation<T> err : errs) { msg += err.getPropertyPath() + " " + err.getMessage() + ". "; } return Response.status(400).entity(msg).build(); } } }
ValidationByResponseHandler { <T> Response validate(T object) { Set<ConstraintViolation<T>> errs = jeeValidator.validate(object); if (errs.isEmpty()) { return Response.status(200).entity(object).build(); } else { String msg = "Invalid Bean, constraint error(s) : "; for (ConstraintViolation<T> err : errs) { msg += err.getPropertyPath() + " " + err.getMessage() + ". "; } return Response.status(400).entity(msg).build(); } } }
ValidationByResponseHandler { <T> Response validate(T object) { Set<ConstraintViolation<T>> errs = jeeValidator.validate(object); if (errs.isEmpty()) { return Response.status(200).entity(object).build(); } else { String msg = "Invalid Bean, constraint error(s) : "; for (ConstraintViolation<T> err : errs) { msg += err.getPropertyPath() + " " + err.getMessage() + ". "; } return Response.status(400).entity(msg).build(); } } }
@Test public void test_WHEN_valid_GIVEN_valid_model_THEN_ok_no_errors() { PersonModel person = new PersonModel( "Kim", "Kardashian", new GregorianCalendar(1980, Calendar.OCTOBER, 21)); ValidationByExceptionHandler validator = new ValidationByExceptionHandler(); validator.validate(person); }
<T> void validate(T object) { Set<ConstraintViolation<T>> errs = jeeValidator.validate(object); if (errs.size() > 0) { String msg = "Invalid Bean, constraint error(s) : "; for (ConstraintViolation<T> err : errs) { msg += err.getPropertyPath() + " " + err.getMessage() + ". "; } throw new IllegalArgumentException(msg); } }
ValidationByExceptionHandler { <T> void validate(T object) { Set<ConstraintViolation<T>> errs = jeeValidator.validate(object); if (errs.size() > 0) { String msg = "Invalid Bean, constraint error(s) : "; for (ConstraintViolation<T> err : errs) { msg += err.getPropertyPath() + " " + err.getMessage() + ". "; } throw new IllegalArgumentException(msg); } } }
ValidationByExceptionHandler { <T> void validate(T object) { Set<ConstraintViolation<T>> errs = jeeValidator.validate(object); if (errs.size() > 0) { String msg = "Invalid Bean, constraint error(s) : "; for (ConstraintViolation<T> err : errs) { msg += err.getPropertyPath() + " " + err.getMessage() + ". "; } throw new IllegalArgumentException(msg); } } }
ValidationByExceptionHandler { <T> void validate(T object) { Set<ConstraintViolation<T>> errs = jeeValidator.validate(object); if (errs.size() > 0) { String msg = "Invalid Bean, constraint error(s) : "; for (ConstraintViolation<T> err : errs) { msg += err.getPropertyPath() + " " + err.getMessage() + ". "; } throw new IllegalArgumentException(msg); } } }
ValidationByExceptionHandler { <T> void validate(T object) { Set<ConstraintViolation<T>> errs = jeeValidator.validate(object); if (errs.size() > 0) { String msg = "Invalid Bean, constraint error(s) : "; for (ConstraintViolation<T> err : errs) { msg += err.getPropertyPath() + " " + err.getMessage() + ". "; } throw new IllegalArgumentException(msg); } } }
@Test public void test_WHEN_valid_GIVEN_invalid_model_THEN_error() { PersonModel person = new PersonModel( null, "", null); ValidationByExceptionHandler validator = new ValidationByExceptionHandler(); try { validator.validate(person); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage()) .contains("Invalid Bean, constraint error(s) : ") .contains("birthDate may not be null.") .contains("firstName may not be null.") .contains("lastName size must be between 1 and 16."); } }
<T> void validate(T object) { Set<ConstraintViolation<T>> errs = jeeValidator.validate(object); if (errs.size() > 0) { String msg = "Invalid Bean, constraint error(s) : "; for (ConstraintViolation<T> err : errs) { msg += err.getPropertyPath() + " " + err.getMessage() + ". "; } throw new IllegalArgumentException(msg); } }
ValidationByExceptionHandler { <T> void validate(T object) { Set<ConstraintViolation<T>> errs = jeeValidator.validate(object); if (errs.size() > 0) { String msg = "Invalid Bean, constraint error(s) : "; for (ConstraintViolation<T> err : errs) { msg += err.getPropertyPath() + " " + err.getMessage() + ". "; } throw new IllegalArgumentException(msg); } } }
ValidationByExceptionHandler { <T> void validate(T object) { Set<ConstraintViolation<T>> errs = jeeValidator.validate(object); if (errs.size() > 0) { String msg = "Invalid Bean, constraint error(s) : "; for (ConstraintViolation<T> err : errs) { msg += err.getPropertyPath() + " " + err.getMessage() + ". "; } throw new IllegalArgumentException(msg); } } }
ValidationByExceptionHandler { <T> void validate(T object) { Set<ConstraintViolation<T>> errs = jeeValidator.validate(object); if (errs.size() > 0) { String msg = "Invalid Bean, constraint error(s) : "; for (ConstraintViolation<T> err : errs) { msg += err.getPropertyPath() + " " + err.getMessage() + ". "; } throw new IllegalArgumentException(msg); } } }
ValidationByExceptionHandler { <T> void validate(T object) { Set<ConstraintViolation<T>> errs = jeeValidator.validate(object); if (errs.size() > 0) { String msg = "Invalid Bean, constraint error(s) : "; for (ConstraintViolation<T> err : errs) { msg += err.getPropertyPath() + " " + err.getMessage() + ". "; } throw new IllegalArgumentException(msg); } } }
@Test public void test_batch_execution() { String[] args = { "10" }; HelloWorldBatch.main(args); }
public static void main(String[] args) { System.out.println("Executing batch"); if (args != null && args.length == 1 && args[0] != null) { System.out.println("input args ok"); } else { System.out.println("Error with input args"); throw new IllegalArgumentException("Error with input args"); } try { System.out.println("Executing job"); for (int i = 0; i < Integer.valueOf(args[0]); i++) { System.out.println("Hello World!"); } System.out.println("Ending job (success)"); } catch (Exception e) { System.out.println("Error during job (failure)"); System.out.println(e.getMessage()); throw new RuntimeException("Error during task (failure)", e); } System.out.println("Ending batch"); }
HelloWorldBatch { public static void main(String[] args) { System.out.println("Executing batch"); if (args != null && args.length == 1 && args[0] != null) { System.out.println("input args ok"); } else { System.out.println("Error with input args"); throw new IllegalArgumentException("Error with input args"); } try { System.out.println("Executing job"); for (int i = 0; i < Integer.valueOf(args[0]); i++) { System.out.println("Hello World!"); } System.out.println("Ending job (success)"); } catch (Exception e) { System.out.println("Error during job (failure)"); System.out.println(e.getMessage()); throw new RuntimeException("Error during task (failure)", e); } System.out.println("Ending batch"); } }
HelloWorldBatch { public static void main(String[] args) { System.out.println("Executing batch"); if (args != null && args.length == 1 && args[0] != null) { System.out.println("input args ok"); } else { System.out.println("Error with input args"); throw new IllegalArgumentException("Error with input args"); } try { System.out.println("Executing job"); for (int i = 0; i < Integer.valueOf(args[0]); i++) { System.out.println("Hello World!"); } System.out.println("Ending job (success)"); } catch (Exception e) { System.out.println("Error during job (failure)"); System.out.println(e.getMessage()); throw new RuntimeException("Error during task (failure)", e); } System.out.println("Ending batch"); } }
HelloWorldBatch { public static void main(String[] args) { System.out.println("Executing batch"); if (args != null && args.length == 1 && args[0] != null) { System.out.println("input args ok"); } else { System.out.println("Error with input args"); throw new IllegalArgumentException("Error with input args"); } try { System.out.println("Executing job"); for (int i = 0; i < Integer.valueOf(args[0]); i++) { System.out.println("Hello World!"); } System.out.println("Ending job (success)"); } catch (Exception e) { System.out.println("Error during job (failure)"); System.out.println(e.getMessage()); throw new RuntimeException("Error during task (failure)", e); } System.out.println("Ending batch"); } static void main(String[] args); }
HelloWorldBatch { public static void main(String[] args) { System.out.println("Executing batch"); if (args != null && args.length == 1 && args[0] != null) { System.out.println("input args ok"); } else { System.out.println("Error with input args"); throw new IllegalArgumentException("Error with input args"); } try { System.out.println("Executing job"); for (int i = 0; i < Integer.valueOf(args[0]); i++) { System.out.println("Hello World!"); } System.out.println("Ending job (success)"); } catch (Exception e) { System.out.println("Error during job (failure)"); System.out.println(e.getMessage()); throw new RuntimeException("Error during task (failure)", e); } System.out.println("Ending batch"); } static void main(String[] args); }
@Test public void test_args_validation() { try { HelloWorldBatch.main(null); fail("error expected"); } catch (IllegalArgumentException e) { } try { HelloWorldBatch.main(new String[] {}); fail("error expected"); } catch (IllegalArgumentException e) { } try { HelloWorldBatch.main(new String[] { null }); fail("error expected"); } catch (IllegalArgumentException e) { } }
public static void main(String[] args) { System.out.println("Executing batch"); if (args != null && args.length == 1 && args[0] != null) { System.out.println("input args ok"); } else { System.out.println("Error with input args"); throw new IllegalArgumentException("Error with input args"); } try { System.out.println("Executing job"); for (int i = 0; i < Integer.valueOf(args[0]); i++) { System.out.println("Hello World!"); } System.out.println("Ending job (success)"); } catch (Exception e) { System.out.println("Error during job (failure)"); System.out.println(e.getMessage()); throw new RuntimeException("Error during task (failure)", e); } System.out.println("Ending batch"); }
HelloWorldBatch { public static void main(String[] args) { System.out.println("Executing batch"); if (args != null && args.length == 1 && args[0] != null) { System.out.println("input args ok"); } else { System.out.println("Error with input args"); throw new IllegalArgumentException("Error with input args"); } try { System.out.println("Executing job"); for (int i = 0; i < Integer.valueOf(args[0]); i++) { System.out.println("Hello World!"); } System.out.println("Ending job (success)"); } catch (Exception e) { System.out.println("Error during job (failure)"); System.out.println(e.getMessage()); throw new RuntimeException("Error during task (failure)", e); } System.out.println("Ending batch"); } }
HelloWorldBatch { public static void main(String[] args) { System.out.println("Executing batch"); if (args != null && args.length == 1 && args[0] != null) { System.out.println("input args ok"); } else { System.out.println("Error with input args"); throw new IllegalArgumentException("Error with input args"); } try { System.out.println("Executing job"); for (int i = 0; i < Integer.valueOf(args[0]); i++) { System.out.println("Hello World!"); } System.out.println("Ending job (success)"); } catch (Exception e) { System.out.println("Error during job (failure)"); System.out.println(e.getMessage()); throw new RuntimeException("Error during task (failure)", e); } System.out.println("Ending batch"); } }
HelloWorldBatch { public static void main(String[] args) { System.out.println("Executing batch"); if (args != null && args.length == 1 && args[0] != null) { System.out.println("input args ok"); } else { System.out.println("Error with input args"); throw new IllegalArgumentException("Error with input args"); } try { System.out.println("Executing job"); for (int i = 0; i < Integer.valueOf(args[0]); i++) { System.out.println("Hello World!"); } System.out.println("Ending job (success)"); } catch (Exception e) { System.out.println("Error during job (failure)"); System.out.println(e.getMessage()); throw new RuntimeException("Error during task (failure)", e); } System.out.println("Ending batch"); } static void main(String[] args); }
HelloWorldBatch { public static void main(String[] args) { System.out.println("Executing batch"); if (args != null && args.length == 1 && args[0] != null) { System.out.println("input args ok"); } else { System.out.println("Error with input args"); throw new IllegalArgumentException("Error with input args"); } try { System.out.println("Executing job"); for (int i = 0; i < Integer.valueOf(args[0]); i++) { System.out.println("Hello World!"); } System.out.println("Ending job (success)"); } catch (Exception e) { System.out.println("Error during job (failure)"); System.out.println(e.getMessage()); throw new RuntimeException("Error during task (failure)", e); } System.out.println("Ending batch"); } static void main(String[] args); }
@Test(expected = RuntimeException.class) public void test_batch_execution_error() { HelloWorldBatch.main(new String[] { "ERROR" }); }
public static void main(String[] args) { System.out.println("Executing batch"); if (args != null && args.length == 1 && args[0] != null) { System.out.println("input args ok"); } else { System.out.println("Error with input args"); throw new IllegalArgumentException("Error with input args"); } try { System.out.println("Executing job"); for (int i = 0; i < Integer.valueOf(args[0]); i++) { System.out.println("Hello World!"); } System.out.println("Ending job (success)"); } catch (Exception e) { System.out.println("Error during job (failure)"); System.out.println(e.getMessage()); throw new RuntimeException("Error during task (failure)", e); } System.out.println("Ending batch"); }
HelloWorldBatch { public static void main(String[] args) { System.out.println("Executing batch"); if (args != null && args.length == 1 && args[0] != null) { System.out.println("input args ok"); } else { System.out.println("Error with input args"); throw new IllegalArgumentException("Error with input args"); } try { System.out.println("Executing job"); for (int i = 0; i < Integer.valueOf(args[0]); i++) { System.out.println("Hello World!"); } System.out.println("Ending job (success)"); } catch (Exception e) { System.out.println("Error during job (failure)"); System.out.println(e.getMessage()); throw new RuntimeException("Error during task (failure)", e); } System.out.println("Ending batch"); } }
HelloWorldBatch { public static void main(String[] args) { System.out.println("Executing batch"); if (args != null && args.length == 1 && args[0] != null) { System.out.println("input args ok"); } else { System.out.println("Error with input args"); throw new IllegalArgumentException("Error with input args"); } try { System.out.println("Executing job"); for (int i = 0; i < Integer.valueOf(args[0]); i++) { System.out.println("Hello World!"); } System.out.println("Ending job (success)"); } catch (Exception e) { System.out.println("Error during job (failure)"); System.out.println(e.getMessage()); throw new RuntimeException("Error during task (failure)", e); } System.out.println("Ending batch"); } }
HelloWorldBatch { public static void main(String[] args) { System.out.println("Executing batch"); if (args != null && args.length == 1 && args[0] != null) { System.out.println("input args ok"); } else { System.out.println("Error with input args"); throw new IllegalArgumentException("Error with input args"); } try { System.out.println("Executing job"); for (int i = 0; i < Integer.valueOf(args[0]); i++) { System.out.println("Hello World!"); } System.out.println("Ending job (success)"); } catch (Exception e) { System.out.println("Error during job (failure)"); System.out.println(e.getMessage()); throw new RuntimeException("Error during task (failure)", e); } System.out.println("Ending batch"); } static void main(String[] args); }
HelloWorldBatch { public static void main(String[] args) { System.out.println("Executing batch"); if (args != null && args.length == 1 && args[0] != null) { System.out.println("input args ok"); } else { System.out.println("Error with input args"); throw new IllegalArgumentException("Error with input args"); } try { System.out.println("Executing job"); for (int i = 0; i < Integer.valueOf(args[0]); i++) { System.out.println("Hello World!"); } System.out.println("Ending job (success)"); } catch (Exception e) { System.out.println("Error during job (failure)"); System.out.println(e.getMessage()); throw new RuntimeException("Error during task (failure)", e); } System.out.println("Ending batch"); } static void main(String[] args); }
@Test public void invalidProgressValue() { try { button.setProgress(101); fail("Setting progress > max should throw"); } catch (IllegalArgumentException e) { } }
public void setProgress(int progress) { if (progress > mMax || progress < 0) { throw new IllegalArgumentException( String.format("Progress (%d) must be between %d and %d", progress, 0, mMax)); } mProgress = progress; invalidate(); }
ProgressButton extends CompoundButton { public void setProgress(int progress) { if (progress > mMax || progress < 0) { throw new IllegalArgumentException( String.format("Progress (%d) must be between %d and %d", progress, 0, mMax)); } mProgress = progress; invalidate(); } }
ProgressButton extends CompoundButton { public void setProgress(int progress) { if (progress > mMax || progress < 0) { throw new IllegalArgumentException( String.format("Progress (%d) must be between %d and %d", progress, 0, mMax)); } mProgress = progress; invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); }
ProgressButton extends CompoundButton { public void setProgress(int progress) { if (progress > mMax || progress < 0) { throw new IllegalArgumentException( String.format("Progress (%d) must be between %d and %d", progress, 0, mMax)); } mProgress = progress; invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); int getMax(); void setMax(int max); int getProgress(); void setProgress(int progress); void setProgressAndMax(int progress, int max); int getProgressColor(); void setProgressColor(int progressColor); int getCircleColor(); void setCircleColor(int circleColor); Drawable getPinnedDrawable(); void setPinnedDrawable(Drawable pinnedDrawable); Drawable getUnpinnedDrawable(); void setUnpinnedDrawable(Drawable unpinnedDrawable); Drawable getShadowDrawable(); void setShadowDrawable(Drawable shadowDrawable); int getInnerSize(); void setInnerSize(int innerSize); boolean isPinned(); void setPinned(boolean pinned); boolean isAnimating(); int getAnimationSpeed(); int getAnimationDelay(); int getAnimationStripWidth(); void setAnimationSpeed(int animationSpeed); void setAnimationDelay(int animationDelay); void setAnimationStripWidth(int animationStripWidth); void startAnimating(); void stopAnimating(); @Override Parcelable onSaveInstanceState(); @Override void onRestoreInstanceState(Parcelable state); }
ProgressButton extends CompoundButton { public void setProgress(int progress) { if (progress > mMax || progress < 0) { throw new IllegalArgumentException( String.format("Progress (%d) must be between %d and %d", progress, 0, mMax)); } mProgress = progress; invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); int getMax(); void setMax(int max); int getProgress(); void setProgress(int progress); void setProgressAndMax(int progress, int max); int getProgressColor(); void setProgressColor(int progressColor); int getCircleColor(); void setCircleColor(int circleColor); Drawable getPinnedDrawable(); void setPinnedDrawable(Drawable pinnedDrawable); Drawable getUnpinnedDrawable(); void setUnpinnedDrawable(Drawable unpinnedDrawable); Drawable getShadowDrawable(); void setShadowDrawable(Drawable shadowDrawable); int getInnerSize(); void setInnerSize(int innerSize); boolean isPinned(); void setPinned(boolean pinned); boolean isAnimating(); int getAnimationSpeed(); int getAnimationDelay(); int getAnimationStripWidth(); void setAnimationSpeed(int animationSpeed); void setAnimationDelay(int animationDelay); void setAnimationStripWidth(int animationStripWidth); void startAnimating(); void stopAnimating(); @Override Parcelable onSaveInstanceState(); @Override void onRestoreInstanceState(Parcelable state); }
@Test public void anotherInvalidProgressValue() { try { button.setProgress(-1); fail("Setting progress < 0 should throw"); } catch (IllegalArgumentException e) { } }
public void setProgress(int progress) { if (progress > mMax || progress < 0) { throw new IllegalArgumentException( String.format("Progress (%d) must be between %d and %d", progress, 0, mMax)); } mProgress = progress; invalidate(); }
ProgressButton extends CompoundButton { public void setProgress(int progress) { if (progress > mMax || progress < 0) { throw new IllegalArgumentException( String.format("Progress (%d) must be between %d and %d", progress, 0, mMax)); } mProgress = progress; invalidate(); } }
ProgressButton extends CompoundButton { public void setProgress(int progress) { if (progress > mMax || progress < 0) { throw new IllegalArgumentException( String.format("Progress (%d) must be between %d and %d", progress, 0, mMax)); } mProgress = progress; invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); }
ProgressButton extends CompoundButton { public void setProgress(int progress) { if (progress > mMax || progress < 0) { throw new IllegalArgumentException( String.format("Progress (%d) must be between %d and %d", progress, 0, mMax)); } mProgress = progress; invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); int getMax(); void setMax(int max); int getProgress(); void setProgress(int progress); void setProgressAndMax(int progress, int max); int getProgressColor(); void setProgressColor(int progressColor); int getCircleColor(); void setCircleColor(int circleColor); Drawable getPinnedDrawable(); void setPinnedDrawable(Drawable pinnedDrawable); Drawable getUnpinnedDrawable(); void setUnpinnedDrawable(Drawable unpinnedDrawable); Drawable getShadowDrawable(); void setShadowDrawable(Drawable shadowDrawable); int getInnerSize(); void setInnerSize(int innerSize); boolean isPinned(); void setPinned(boolean pinned); boolean isAnimating(); int getAnimationSpeed(); int getAnimationDelay(); int getAnimationStripWidth(); void setAnimationSpeed(int animationSpeed); void setAnimationDelay(int animationDelay); void setAnimationStripWidth(int animationStripWidth); void startAnimating(); void stopAnimating(); @Override Parcelable onSaveInstanceState(); @Override void onRestoreInstanceState(Parcelable state); }
ProgressButton extends CompoundButton { public void setProgress(int progress) { if (progress > mMax || progress < 0) { throw new IllegalArgumentException( String.format("Progress (%d) must be between %d and %d", progress, 0, mMax)); } mProgress = progress; invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); int getMax(); void setMax(int max); int getProgress(); void setProgress(int progress); void setProgressAndMax(int progress, int max); int getProgressColor(); void setProgressColor(int progressColor); int getCircleColor(); void setCircleColor(int circleColor); Drawable getPinnedDrawable(); void setPinnedDrawable(Drawable pinnedDrawable); Drawable getUnpinnedDrawable(); void setUnpinnedDrawable(Drawable unpinnedDrawable); Drawable getShadowDrawable(); void setShadowDrawable(Drawable shadowDrawable); int getInnerSize(); void setInnerSize(int innerSize); boolean isPinned(); void setPinned(boolean pinned); boolean isAnimating(); int getAnimationSpeed(); int getAnimationDelay(); int getAnimationStripWidth(); void setAnimationSpeed(int animationSpeed); void setAnimationDelay(int animationDelay); void setAnimationStripWidth(int animationStripWidth); void startAnimating(); void stopAnimating(); @Override Parcelable onSaveInstanceState(); @Override void onRestoreInstanceState(Parcelable state); }
@Test public void setMaxToUnderZero() { try { button.setMax(-1); fail("Setting max <= 0 should throw"); } catch (IllegalArgumentException e) { } }
public void setMax(int max) { if (max <= 0 || max < mProgress) { throw new IllegalArgumentException( String.format("Max (%d) must be > 0 and >= %d", max, mProgress)); } mMax = max; invalidate(); }
ProgressButton extends CompoundButton { public void setMax(int max) { if (max <= 0 || max < mProgress) { throw new IllegalArgumentException( String.format("Max (%d) must be > 0 and >= %d", max, mProgress)); } mMax = max; invalidate(); } }
ProgressButton extends CompoundButton { public void setMax(int max) { if (max <= 0 || max < mProgress) { throw new IllegalArgumentException( String.format("Max (%d) must be > 0 and >= %d", max, mProgress)); } mMax = max; invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); }
ProgressButton extends CompoundButton { public void setMax(int max) { if (max <= 0 || max < mProgress) { throw new IllegalArgumentException( String.format("Max (%d) must be > 0 and >= %d", max, mProgress)); } mMax = max; invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); int getMax(); void setMax(int max); int getProgress(); void setProgress(int progress); void setProgressAndMax(int progress, int max); int getProgressColor(); void setProgressColor(int progressColor); int getCircleColor(); void setCircleColor(int circleColor); Drawable getPinnedDrawable(); void setPinnedDrawable(Drawable pinnedDrawable); Drawable getUnpinnedDrawable(); void setUnpinnedDrawable(Drawable unpinnedDrawable); Drawable getShadowDrawable(); void setShadowDrawable(Drawable shadowDrawable); int getInnerSize(); void setInnerSize(int innerSize); boolean isPinned(); void setPinned(boolean pinned); boolean isAnimating(); int getAnimationSpeed(); int getAnimationDelay(); int getAnimationStripWidth(); void setAnimationSpeed(int animationSpeed); void setAnimationDelay(int animationDelay); void setAnimationStripWidth(int animationStripWidth); void startAnimating(); void stopAnimating(); @Override Parcelable onSaveInstanceState(); @Override void onRestoreInstanceState(Parcelable state); }
ProgressButton extends CompoundButton { public void setMax(int max) { if (max <= 0 || max < mProgress) { throw new IllegalArgumentException( String.format("Max (%d) must be > 0 and >= %d", max, mProgress)); } mMax = max; invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); int getMax(); void setMax(int max); int getProgress(); void setProgress(int progress); void setProgressAndMax(int progress, int max); int getProgressColor(); void setProgressColor(int progressColor); int getCircleColor(); void setCircleColor(int circleColor); Drawable getPinnedDrawable(); void setPinnedDrawable(Drawable pinnedDrawable); Drawable getUnpinnedDrawable(); void setUnpinnedDrawable(Drawable unpinnedDrawable); Drawable getShadowDrawable(); void setShadowDrawable(Drawable shadowDrawable); int getInnerSize(); void setInnerSize(int innerSize); boolean isPinned(); void setPinned(boolean pinned); boolean isAnimating(); int getAnimationSpeed(); int getAnimationDelay(); int getAnimationStripWidth(); void setAnimationSpeed(int animationSpeed); void setAnimationDelay(int animationDelay); void setAnimationStripWidth(int animationStripWidth); void startAnimating(); void stopAnimating(); @Override Parcelable onSaveInstanceState(); @Override void onRestoreInstanceState(Parcelable state); }
@Test public void setMaxToZero() { try { button.setMax(0); fail("Setting max <= 0 should throw"); } catch (IllegalArgumentException e) { } }
public void setMax(int max) { if (max <= 0 || max < mProgress) { throw new IllegalArgumentException( String.format("Max (%d) must be > 0 and >= %d", max, mProgress)); } mMax = max; invalidate(); }
ProgressButton extends CompoundButton { public void setMax(int max) { if (max <= 0 || max < mProgress) { throw new IllegalArgumentException( String.format("Max (%d) must be > 0 and >= %d", max, mProgress)); } mMax = max; invalidate(); } }
ProgressButton extends CompoundButton { public void setMax(int max) { if (max <= 0 || max < mProgress) { throw new IllegalArgumentException( String.format("Max (%d) must be > 0 and >= %d", max, mProgress)); } mMax = max; invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); }
ProgressButton extends CompoundButton { public void setMax(int max) { if (max <= 0 || max < mProgress) { throw new IllegalArgumentException( String.format("Max (%d) must be > 0 and >= %d", max, mProgress)); } mMax = max; invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); int getMax(); void setMax(int max); int getProgress(); void setProgress(int progress); void setProgressAndMax(int progress, int max); int getProgressColor(); void setProgressColor(int progressColor); int getCircleColor(); void setCircleColor(int circleColor); Drawable getPinnedDrawable(); void setPinnedDrawable(Drawable pinnedDrawable); Drawable getUnpinnedDrawable(); void setUnpinnedDrawable(Drawable unpinnedDrawable); Drawable getShadowDrawable(); void setShadowDrawable(Drawable shadowDrawable); int getInnerSize(); void setInnerSize(int innerSize); boolean isPinned(); void setPinned(boolean pinned); boolean isAnimating(); int getAnimationSpeed(); int getAnimationDelay(); int getAnimationStripWidth(); void setAnimationSpeed(int animationSpeed); void setAnimationDelay(int animationDelay); void setAnimationStripWidth(int animationStripWidth); void startAnimating(); void stopAnimating(); @Override Parcelable onSaveInstanceState(); @Override void onRestoreInstanceState(Parcelable state); }
ProgressButton extends CompoundButton { public void setMax(int max) { if (max <= 0 || max < mProgress) { throw new IllegalArgumentException( String.format("Max (%d) must be > 0 and >= %d", max, mProgress)); } mMax = max; invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); int getMax(); void setMax(int max); int getProgress(); void setProgress(int progress); void setProgressAndMax(int progress, int max); int getProgressColor(); void setProgressColor(int progressColor); int getCircleColor(); void setCircleColor(int circleColor); Drawable getPinnedDrawable(); void setPinnedDrawable(Drawable pinnedDrawable); Drawable getUnpinnedDrawable(); void setUnpinnedDrawable(Drawable unpinnedDrawable); Drawable getShadowDrawable(); void setShadowDrawable(Drawable shadowDrawable); int getInnerSize(); void setInnerSize(int innerSize); boolean isPinned(); void setPinned(boolean pinned); boolean isAnimating(); int getAnimationSpeed(); int getAnimationDelay(); int getAnimationStripWidth(); void setAnimationSpeed(int animationSpeed); void setAnimationDelay(int animationDelay); void setAnimationStripWidth(int animationStripWidth); void startAnimating(); void stopAnimating(); @Override Parcelable onSaveInstanceState(); @Override void onRestoreInstanceState(Parcelable state); }
@Test public void onCheckedChangeListenerIsNotified() { CompoundButton.OnCheckedChangeListener publisher = mock(CompoundButton.OnCheckedChangeListener.class); button.setOnCheckedChangeListener(publisher); button.setPinned(true); verify(publisher).onCheckedChanged(button, true); button.setPinned(false); verify(publisher).onCheckedChanged(button, false); }
public void setPinned(boolean pinned) { setChecked(pinned); invalidate(); }
ProgressButton extends CompoundButton { public void setPinned(boolean pinned) { setChecked(pinned); invalidate(); } }
ProgressButton extends CompoundButton { public void setPinned(boolean pinned) { setChecked(pinned); invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); }
ProgressButton extends CompoundButton { public void setPinned(boolean pinned) { setChecked(pinned); invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); int getMax(); void setMax(int max); int getProgress(); void setProgress(int progress); void setProgressAndMax(int progress, int max); int getProgressColor(); void setProgressColor(int progressColor); int getCircleColor(); void setCircleColor(int circleColor); Drawable getPinnedDrawable(); void setPinnedDrawable(Drawable pinnedDrawable); Drawable getUnpinnedDrawable(); void setUnpinnedDrawable(Drawable unpinnedDrawable); Drawable getShadowDrawable(); void setShadowDrawable(Drawable shadowDrawable); int getInnerSize(); void setInnerSize(int innerSize); boolean isPinned(); void setPinned(boolean pinned); boolean isAnimating(); int getAnimationSpeed(); int getAnimationDelay(); int getAnimationStripWidth(); void setAnimationSpeed(int animationSpeed); void setAnimationDelay(int animationDelay); void setAnimationStripWidth(int animationStripWidth); void startAnimating(); void stopAnimating(); @Override Parcelable onSaveInstanceState(); @Override void onRestoreInstanceState(Parcelable state); }
ProgressButton extends CompoundButton { public void setPinned(boolean pinned) { setChecked(pinned); invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); int getMax(); void setMax(int max); int getProgress(); void setProgress(int progress); void setProgressAndMax(int progress, int max); int getProgressColor(); void setProgressColor(int progressColor); int getCircleColor(); void setCircleColor(int circleColor); Drawable getPinnedDrawable(); void setPinnedDrawable(Drawable pinnedDrawable); Drawable getUnpinnedDrawable(); void setUnpinnedDrawable(Drawable unpinnedDrawable); Drawable getShadowDrawable(); void setShadowDrawable(Drawable shadowDrawable); int getInnerSize(); void setInnerSize(int innerSize); boolean isPinned(); void setPinned(boolean pinned); boolean isAnimating(); int getAnimationSpeed(); int getAnimationDelay(); int getAnimationStripWidth(); void setAnimationSpeed(int animationSpeed); void setAnimationDelay(int animationDelay); void setAnimationStripWidth(int animationStripWidth); void startAnimating(); void stopAnimating(); @Override Parcelable onSaveInstanceState(); @Override void onRestoreInstanceState(Parcelable state); }
@Test public void onCheckedChangeListenerIsNotifiedOnToggle() { button.setPinned(true); CompoundButton.OnCheckedChangeListener publisher = mock(CompoundButton.OnCheckedChangeListener.class); button.setOnCheckedChangeListener(publisher); button.toggle(); verify(publisher).onCheckedChanged(button, false); }
public void setPinned(boolean pinned) { setChecked(pinned); invalidate(); }
ProgressButton extends CompoundButton { public void setPinned(boolean pinned) { setChecked(pinned); invalidate(); } }
ProgressButton extends CompoundButton { public void setPinned(boolean pinned) { setChecked(pinned); invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); }
ProgressButton extends CompoundButton { public void setPinned(boolean pinned) { setChecked(pinned); invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); int getMax(); void setMax(int max); int getProgress(); void setProgress(int progress); void setProgressAndMax(int progress, int max); int getProgressColor(); void setProgressColor(int progressColor); int getCircleColor(); void setCircleColor(int circleColor); Drawable getPinnedDrawable(); void setPinnedDrawable(Drawable pinnedDrawable); Drawable getUnpinnedDrawable(); void setUnpinnedDrawable(Drawable unpinnedDrawable); Drawable getShadowDrawable(); void setShadowDrawable(Drawable shadowDrawable); int getInnerSize(); void setInnerSize(int innerSize); boolean isPinned(); void setPinned(boolean pinned); boolean isAnimating(); int getAnimationSpeed(); int getAnimationDelay(); int getAnimationStripWidth(); void setAnimationSpeed(int animationSpeed); void setAnimationDelay(int animationDelay); void setAnimationStripWidth(int animationStripWidth); void startAnimating(); void stopAnimating(); @Override Parcelable onSaveInstanceState(); @Override void onRestoreInstanceState(Parcelable state); }
ProgressButton extends CompoundButton { public void setPinned(boolean pinned) { setChecked(pinned); invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); int getMax(); void setMax(int max); int getProgress(); void setProgress(int progress); void setProgressAndMax(int progress, int max); int getProgressColor(); void setProgressColor(int progressColor); int getCircleColor(); void setCircleColor(int circleColor); Drawable getPinnedDrawable(); void setPinnedDrawable(Drawable pinnedDrawable); Drawable getUnpinnedDrawable(); void setUnpinnedDrawable(Drawable unpinnedDrawable); Drawable getShadowDrawable(); void setShadowDrawable(Drawable shadowDrawable); int getInnerSize(); void setInnerSize(int innerSize); boolean isPinned(); void setPinned(boolean pinned); boolean isAnimating(); int getAnimationSpeed(); int getAnimationDelay(); int getAnimationStripWidth(); void setAnimationSpeed(int animationSpeed); void setAnimationDelay(int animationDelay); void setAnimationStripWidth(int animationStripWidth); void startAnimating(); void stopAnimating(); @Override Parcelable onSaveInstanceState(); @Override void onRestoreInstanceState(Parcelable state); }
@Test public void onSaveInstanceState() { button.setProgress(72); button.setMax(842); final Parcelable parcelable = button.onSaveInstanceState(); button.setProgress(2); button.setMax(50); assertThat(button.getProgress()).isEqualTo(2); assertThat(button.getMax()).isEqualTo(50); button.onRestoreInstanceState(parcelable); assertThat(button.getProgress()).isEqualTo(72); assertThat(button.getMax()).isEqualTo(842); }
@Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); if (isSaveEnabled()) { SavedState ss = new SavedState(superState); ss.mMax = mMax; ss.mProgress = mProgress; return ss; } return superState; }
ProgressButton extends CompoundButton { @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); if (isSaveEnabled()) { SavedState ss = new SavedState(superState); ss.mMax = mMax; ss.mProgress = mProgress; return ss; } return superState; } }
ProgressButton extends CompoundButton { @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); if (isSaveEnabled()) { SavedState ss = new SavedState(superState); ss.mMax = mMax; ss.mProgress = mProgress; return ss; } return superState; } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); }
ProgressButton extends CompoundButton { @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); if (isSaveEnabled()) { SavedState ss = new SavedState(superState); ss.mMax = mMax; ss.mProgress = mProgress; return ss; } return superState; } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); int getMax(); void setMax(int max); int getProgress(); void setProgress(int progress); void setProgressAndMax(int progress, int max); int getProgressColor(); void setProgressColor(int progressColor); int getCircleColor(); void setCircleColor(int circleColor); Drawable getPinnedDrawable(); void setPinnedDrawable(Drawable pinnedDrawable); Drawable getUnpinnedDrawable(); void setUnpinnedDrawable(Drawable unpinnedDrawable); Drawable getShadowDrawable(); void setShadowDrawable(Drawable shadowDrawable); int getInnerSize(); void setInnerSize(int innerSize); boolean isPinned(); void setPinned(boolean pinned); boolean isAnimating(); int getAnimationSpeed(); int getAnimationDelay(); int getAnimationStripWidth(); void setAnimationSpeed(int animationSpeed); void setAnimationDelay(int animationDelay); void setAnimationStripWidth(int animationStripWidth); void startAnimating(); void stopAnimating(); @Override Parcelable onSaveInstanceState(); @Override void onRestoreInstanceState(Parcelable state); }
ProgressButton extends CompoundButton { @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); if (isSaveEnabled()) { SavedState ss = new SavedState(superState); ss.mMax = mMax; ss.mProgress = mProgress; return ss; } return superState; } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); int getMax(); void setMax(int max); int getProgress(); void setProgress(int progress); void setProgressAndMax(int progress, int max); int getProgressColor(); void setProgressColor(int progressColor); int getCircleColor(); void setCircleColor(int circleColor); Drawable getPinnedDrawable(); void setPinnedDrawable(Drawable pinnedDrawable); Drawable getUnpinnedDrawable(); void setUnpinnedDrawable(Drawable unpinnedDrawable); Drawable getShadowDrawable(); void setShadowDrawable(Drawable shadowDrawable); int getInnerSize(); void setInnerSize(int innerSize); boolean isPinned(); void setPinned(boolean pinned); boolean isAnimating(); int getAnimationSpeed(); int getAnimationDelay(); int getAnimationStripWidth(); void setAnimationSpeed(int animationSpeed); void setAnimationDelay(int animationDelay); void setAnimationStripWidth(int animationStripWidth); void startAnimating(); void stopAnimating(); @Override Parcelable onSaveInstanceState(); @Override void onRestoreInstanceState(Parcelable state); }
@Test public void settingInvalidProgressAndMax() { try { button.setProgressAndMax(10, 5); fail("Setting progress > max should throw"); } catch (IllegalArgumentException e) { } try { button.setProgressAndMax(0, 0); fail("Setting max = 0 should throw"); } catch (IllegalArgumentException e) { } try { button.setProgressAndMax(-1, 10); fail("Setting progress < 0 should throw"); } catch (IllegalArgumentException e) { } }
public void setProgressAndMax(int progress, int max) { if (progress > max || progress < 0) { throw new IllegalArgumentException( String.format("Progress (%d) must be between %d and %d", progress, 0, max)); } else if (max <= 0) { throw new IllegalArgumentException(String.format("Max (%d) must be > 0", max)); } mProgress = progress; mMax = max; invalidate(); }
ProgressButton extends CompoundButton { public void setProgressAndMax(int progress, int max) { if (progress > max || progress < 0) { throw new IllegalArgumentException( String.format("Progress (%d) must be between %d and %d", progress, 0, max)); } else if (max <= 0) { throw new IllegalArgumentException(String.format("Max (%d) must be > 0", max)); } mProgress = progress; mMax = max; invalidate(); } }
ProgressButton extends CompoundButton { public void setProgressAndMax(int progress, int max) { if (progress > max || progress < 0) { throw new IllegalArgumentException( String.format("Progress (%d) must be between %d and %d", progress, 0, max)); } else if (max <= 0) { throw new IllegalArgumentException(String.format("Max (%d) must be > 0", max)); } mProgress = progress; mMax = max; invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); }
ProgressButton extends CompoundButton { public void setProgressAndMax(int progress, int max) { if (progress > max || progress < 0) { throw new IllegalArgumentException( String.format("Progress (%d) must be between %d and %d", progress, 0, max)); } else if (max <= 0) { throw new IllegalArgumentException(String.format("Max (%d) must be > 0", max)); } mProgress = progress; mMax = max; invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); int getMax(); void setMax(int max); int getProgress(); void setProgress(int progress); void setProgressAndMax(int progress, int max); int getProgressColor(); void setProgressColor(int progressColor); int getCircleColor(); void setCircleColor(int circleColor); Drawable getPinnedDrawable(); void setPinnedDrawable(Drawable pinnedDrawable); Drawable getUnpinnedDrawable(); void setUnpinnedDrawable(Drawable unpinnedDrawable); Drawable getShadowDrawable(); void setShadowDrawable(Drawable shadowDrawable); int getInnerSize(); void setInnerSize(int innerSize); boolean isPinned(); void setPinned(boolean pinned); boolean isAnimating(); int getAnimationSpeed(); int getAnimationDelay(); int getAnimationStripWidth(); void setAnimationSpeed(int animationSpeed); void setAnimationDelay(int animationDelay); void setAnimationStripWidth(int animationStripWidth); void startAnimating(); void stopAnimating(); @Override Parcelable onSaveInstanceState(); @Override void onRestoreInstanceState(Parcelable state); }
ProgressButton extends CompoundButton { public void setProgressAndMax(int progress, int max) { if (progress > max || progress < 0) { throw new IllegalArgumentException( String.format("Progress (%d) must be between %d and %d", progress, 0, max)); } else if (max <= 0) { throw new IllegalArgumentException(String.format("Max (%d) must be > 0", max)); } mProgress = progress; mMax = max; invalidate(); } ProgressButton(Context context); ProgressButton(Context context, AttributeSet attrs); ProgressButton(Context context, AttributeSet attrs, int defStyle); int getMax(); void setMax(int max); int getProgress(); void setProgress(int progress); void setProgressAndMax(int progress, int max); int getProgressColor(); void setProgressColor(int progressColor); int getCircleColor(); void setCircleColor(int circleColor); Drawable getPinnedDrawable(); void setPinnedDrawable(Drawable pinnedDrawable); Drawable getUnpinnedDrawable(); void setUnpinnedDrawable(Drawable unpinnedDrawable); Drawable getShadowDrawable(); void setShadowDrawable(Drawable shadowDrawable); int getInnerSize(); void setInnerSize(int innerSize); boolean isPinned(); void setPinned(boolean pinned); boolean isAnimating(); int getAnimationSpeed(); int getAnimationDelay(); int getAnimationStripWidth(); void setAnimationSpeed(int animationSpeed); void setAnimationDelay(int animationDelay); void setAnimationStripWidth(int animationStripWidth); void startAnimating(); void stopAnimating(); @Override Parcelable onSaveInstanceState(); @Override void onRestoreInstanceState(Parcelable state); }
@Test public void testDelete() throws Exception { CommentModel model = new CommentModel(); model.setUsername("testuser"); model.setId("dqe345e456rf34rw"); model.setPageId("product0815"); model.setEmailAddress("[email protected]"); model.setComment("I am the comment"); String id = service.put(model); this.mvc.perform(delete("/" + id)).andExpect(status().isOk()); assertNull(service.get(model.getId())); }
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(value = HttpStatus.OK) public void delete(@PathVariable(value = "id") String id, HttpServletResponse response) throws IOException { service.delete(id); }
WriteController { @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(value = HttpStatus.OK) public void delete(@PathVariable(value = "id") String id, HttpServletResponse response) throws IOException { service.delete(id); } }
WriteController { @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(value = HttpStatus.OK) public void delete(@PathVariable(value = "id") String id, HttpServletResponse response) throws IOException { service.delete(id); } }
WriteController { @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(value = HttpStatus.OK) public void delete(@PathVariable(value = "id") String id, HttpServletResponse response) throws IOException { service.delete(id); } @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseStatus(value = HttpStatus.OK) @ResponseBody String create(@RequestParam("comment") final String comment, @RequestParam("pageId") final String pageId, @RequestParam("emailAddress") final String emailAddress, @RequestParam("username") final String username); @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(value = HttpStatus.OK) void delete(@PathVariable(value = "id") String id, HttpServletResponse response); @ExceptionHandler(EmptyResultDataAccessException.class) @ResponseStatus(value = HttpStatus.NOT_FOUND) void handle404(Exception ex, Locale locale); }
WriteController { @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(value = HttpStatus.OK) public void delete(@PathVariable(value = "id") String id, HttpServletResponse response) throws IOException { service.delete(id); } @RequestMapping(value = "/create", method = RequestMethod.POST) @ResponseStatus(value = HttpStatus.OK) @ResponseBody String create(@RequestParam("comment") final String comment, @RequestParam("pageId") final String pageId, @RequestParam("emailAddress") final String emailAddress, @RequestParam("username") final String username); @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) @ResponseStatus(value = HttpStatus.OK) void delete(@PathVariable(value = "id") String id, HttpServletResponse response); @ExceptionHandler(EmptyResultDataAccessException.class) @ResponseStatus(value = HttpStatus.NOT_FOUND) void handle404(Exception ex, Locale locale); }
@Test public void testGetComments() throws Exception { CommentModel model = setupDummyModel(); List<CommentModel> mockReturn = new ArrayList<CommentModel>(); mockReturn.add(model); when(this.commentService.list( anyString())).thenReturn(mockReturn); this.mvc.perform(get("/list/" + model.getPageId())) .andExpect(status().is(200)) .andExpect(jsonPath("$[0].id", is(model.getId()))) .andExpect( jsonPath("$[0].created", is(SDF.format(model .getCreationDate().getTime())))) .andExpect(jsonPath("$[0].username", is(model.getUsername()))) .andExpect(jsonPath("$[0].comment", is(model.getComment()))) .andExpect( jsonPath("$[0].email_address", is(model.getEmailAddress()))); verify(this.commentService, times(1)).list( anyString()); }
@RequestMapping(value = "/list/{id}") public List<CommentDTO> getComments(@PathVariable(value = "id") String pageId) throws IOException { LOGGER.info("get comments for pageId {}", pageId); counterService.increment("commentstore.list_comments"); List<CommentModel> r = service.list(pageId); if (r.isEmpty()) { LOGGER.info("get comments for pageId {} - not found", pageId); throw new FileNotFoundException("/list/" + pageId); } LOGGER.info("get comments for pageId {} - done", pageId); return transformToDTO(r); }
ReadController { @RequestMapping(value = "/list/{id}") public List<CommentDTO> getComments(@PathVariable(value = "id") String pageId) throws IOException { LOGGER.info("get comments for pageId {}", pageId); counterService.increment("commentstore.list_comments"); List<CommentModel> r = service.list(pageId); if (r.isEmpty()) { LOGGER.info("get comments for pageId {} - not found", pageId); throw new FileNotFoundException("/list/" + pageId); } LOGGER.info("get comments for pageId {} - done", pageId); return transformToDTO(r); } }
ReadController { @RequestMapping(value = "/list/{id}") public List<CommentDTO> getComments(@PathVariable(value = "id") String pageId) throws IOException { LOGGER.info("get comments for pageId {}", pageId); counterService.increment("commentstore.list_comments"); List<CommentModel> r = service.list(pageId); if (r.isEmpty()) { LOGGER.info("get comments for pageId {} - not found", pageId); throw new FileNotFoundException("/list/" + pageId); } LOGGER.info("get comments for pageId {} - done", pageId); return transformToDTO(r); } }
ReadController { @RequestMapping(value = "/list/{id}") public List<CommentDTO> getComments(@PathVariable(value = "id") String pageId) throws IOException { LOGGER.info("get comments for pageId {}", pageId); counterService.increment("commentstore.list_comments"); List<CommentModel> r = service.list(pageId); if (r.isEmpty()) { LOGGER.info("get comments for pageId {} - not found", pageId); throw new FileNotFoundException("/list/" + pageId); } LOGGER.info("get comments for pageId {} - done", pageId); return transformToDTO(r); } @RequestMapping(value = "/list/{id}") List<CommentDTO> getComments(@PathVariable(value = "id") String pageId); @RequestMapping(value = "/listspam/{id}") List<CommentDTO> getSpamComments(@PathVariable(value = "id") String pageId); @RequestMapping(value = "/{id}", method=RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE }) CommentDTO getComment(@PathVariable(value = "id") String commentId); @RequestMapping(value = "/comments") Page<CommentModel> listComments(@RequestParam(name="page", required=false) String pageIn, @RequestParam(name="size", required=false) String pageSizeIn); @ExceptionHandler(FileNotFoundException.class) @ResponseStatus(value = HttpStatus.NOT_FOUND) void handle404(Exception ex, Locale locale); }
ReadController { @RequestMapping(value = "/list/{id}") public List<CommentDTO> getComments(@PathVariable(value = "id") String pageId) throws IOException { LOGGER.info("get comments for pageId {}", pageId); counterService.increment("commentstore.list_comments"); List<CommentModel> r = service.list(pageId); if (r.isEmpty()) { LOGGER.info("get comments for pageId {} - not found", pageId); throw new FileNotFoundException("/list/" + pageId); } LOGGER.info("get comments for pageId {} - done", pageId); return transformToDTO(r); } @RequestMapping(value = "/list/{id}") List<CommentDTO> getComments(@PathVariable(value = "id") String pageId); @RequestMapping(value = "/listspam/{id}") List<CommentDTO> getSpamComments(@PathVariable(value = "id") String pageId); @RequestMapping(value = "/{id}", method=RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE }) CommentDTO getComment(@PathVariable(value = "id") String commentId); @RequestMapping(value = "/comments") Page<CommentModel> listComments(@RequestParam(name="page", required=false) String pageIn, @RequestParam(name="size", required=false) String pageSizeIn); @ExceptionHandler(FileNotFoundException.class) @ResponseStatus(value = HttpStatus.NOT_FOUND) void handle404(Exception ex, Locale locale); }
@Test public void testGetSpamComments() throws Exception { CommentModel model = setupDummyModel(); List<CommentModel> mockReturn = new ArrayList<CommentModel>(); mockReturn.add(model); when(this.commentService.list( anyString())).thenReturn(mockReturn); this.mvc.perform(get("/listspam/" + model.getPageId())) .andExpect(status().is(200)) .andExpect(jsonPath("$", hasSize(0))); ; }
@RequestMapping(value = "/listspam/{id}") public List<CommentDTO> getSpamComments(@PathVariable(value = "id") String pageId) throws IOException { LOGGER.info("get spam comments for pageId {}", pageId); counterService.increment("commentstore.list_spamcomments"); List<CommentModel> r = service.listSpamComments(pageId); LOGGER.info("get spam comments for pageId {} - done", pageId); return transformToDTO(r); }
ReadController { @RequestMapping(value = "/listspam/{id}") public List<CommentDTO> getSpamComments(@PathVariable(value = "id") String pageId) throws IOException { LOGGER.info("get spam comments for pageId {}", pageId); counterService.increment("commentstore.list_spamcomments"); List<CommentModel> r = service.listSpamComments(pageId); LOGGER.info("get spam comments for pageId {} - done", pageId); return transformToDTO(r); } }
ReadController { @RequestMapping(value = "/listspam/{id}") public List<CommentDTO> getSpamComments(@PathVariable(value = "id") String pageId) throws IOException { LOGGER.info("get spam comments for pageId {}", pageId); counterService.increment("commentstore.list_spamcomments"); List<CommentModel> r = service.listSpamComments(pageId); LOGGER.info("get spam comments for pageId {} - done", pageId); return transformToDTO(r); } }
ReadController { @RequestMapping(value = "/listspam/{id}") public List<CommentDTO> getSpamComments(@PathVariable(value = "id") String pageId) throws IOException { LOGGER.info("get spam comments for pageId {}", pageId); counterService.increment("commentstore.list_spamcomments"); List<CommentModel> r = service.listSpamComments(pageId); LOGGER.info("get spam comments for pageId {} - done", pageId); return transformToDTO(r); } @RequestMapping(value = "/list/{id}") List<CommentDTO> getComments(@PathVariable(value = "id") String pageId); @RequestMapping(value = "/listspam/{id}") List<CommentDTO> getSpamComments(@PathVariable(value = "id") String pageId); @RequestMapping(value = "/{id}", method=RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE }) CommentDTO getComment(@PathVariable(value = "id") String commentId); @RequestMapping(value = "/comments") Page<CommentModel> listComments(@RequestParam(name="page", required=false) String pageIn, @RequestParam(name="size", required=false) String pageSizeIn); @ExceptionHandler(FileNotFoundException.class) @ResponseStatus(value = HttpStatus.NOT_FOUND) void handle404(Exception ex, Locale locale); }
ReadController { @RequestMapping(value = "/listspam/{id}") public List<CommentDTO> getSpamComments(@PathVariable(value = "id") String pageId) throws IOException { LOGGER.info("get spam comments for pageId {}", pageId); counterService.increment("commentstore.list_spamcomments"); List<CommentModel> r = service.listSpamComments(pageId); LOGGER.info("get spam comments for pageId {} - done", pageId); return transformToDTO(r); } @RequestMapping(value = "/list/{id}") List<CommentDTO> getComments(@PathVariable(value = "id") String pageId); @RequestMapping(value = "/listspam/{id}") List<CommentDTO> getSpamComments(@PathVariable(value = "id") String pageId); @RequestMapping(value = "/{id}", method=RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE }) CommentDTO getComment(@PathVariable(value = "id") String commentId); @RequestMapping(value = "/comments") Page<CommentModel> listComments(@RequestParam(name="page", required=false) String pageIn, @RequestParam(name="size", required=false) String pageSizeIn); @ExceptionHandler(FileNotFoundException.class) @ResponseStatus(value = HttpStatus.NOT_FOUND) void handle404(Exception ex, Locale locale); }
@Test(expected = NullPointerException.class) public void nullAddLogPrinter() { Logger.addLogPrinter(null); }
public static void addLogPrinter(AbstractLogPrinter logPrinter) { if (logPrinter == null) throw new NullPointerException("logPrinter is null"); logAdapter.add(logPrinter); }
Logger { public static void addLogPrinter(AbstractLogPrinter logPrinter) { if (logPrinter == null) throw new NullPointerException("logPrinter is null"); logAdapter.add(logPrinter); } }
Logger { public static void addLogPrinter(AbstractLogPrinter logPrinter) { if (logPrinter == null) throw new NullPointerException("logPrinter is null"); logAdapter.add(logPrinter); } private Logger(); }
Logger { public static void addLogPrinter(AbstractLogPrinter logPrinter) { if (logPrinter == null) throw new NullPointerException("logPrinter is null"); logAdapter.add(logPrinter); } private Logger(); static void addLogPrinter(AbstractLogPrinter logPrinter); static void removeLogPrint(AbstractLogPrinter logPrinter); static void clearLogPrint(); static void v(String msg, Object...args); static void v(String msg, Throwable tr, Object...args); static void d(String msg, Object...args); static void d(String msg, Throwable tr, Object...args); static void i(String msg, Object...args); static void i(String msg, Throwable tr, Object...args); static void w(String msg, Object...args); static void w(String msg, Throwable tr, Object...args); static void w(Throwable tr, Object...args); static void e(String msg, Object...args); static void e(String msg, Throwable tr, Object...args); static void e(Throwable tr, Object...args); static void d(Object object); static void json(String json); static void json(String name, String json); }
Logger { public static void addLogPrinter(AbstractLogPrinter logPrinter) { if (logPrinter == null) throw new NullPointerException("logPrinter is null"); logAdapter.add(logPrinter); } private Logger(); static void addLogPrinter(AbstractLogPrinter logPrinter); static void removeLogPrint(AbstractLogPrinter logPrinter); static void clearLogPrint(); static void v(String msg, Object...args); static void v(String msg, Throwable tr, Object...args); static void d(String msg, Object...args); static void d(String msg, Throwable tr, Object...args); static void i(String msg, Object...args); static void i(String msg, Throwable tr, Object...args); static void w(String msg, Object...args); static void w(String msg, Throwable tr, Object...args); static void w(Throwable tr, Object...args); static void e(String msg, Object...args); static void e(String msg, Throwable tr, Object...args); static void e(Throwable tr, Object...args); static void d(Object object); static void json(String json); static void json(String name, String json); }
@Test(expected = NullPointerException.class) public void nullRemoveLogPrinter() { Logger.removeLogPrint(null); }
public static void removeLogPrint(AbstractLogPrinter logPrinter) { if (logPrinter == null) throw new NullPointerException("logPrinter is null"); logAdapter.remove(logPrinter); }
Logger { public static void removeLogPrint(AbstractLogPrinter logPrinter) { if (logPrinter == null) throw new NullPointerException("logPrinter is null"); logAdapter.remove(logPrinter); } }
Logger { public static void removeLogPrint(AbstractLogPrinter logPrinter) { if (logPrinter == null) throw new NullPointerException("logPrinter is null"); logAdapter.remove(logPrinter); } private Logger(); }
Logger { public static void removeLogPrint(AbstractLogPrinter logPrinter) { if (logPrinter == null) throw new NullPointerException("logPrinter is null"); logAdapter.remove(logPrinter); } private Logger(); static void addLogPrinter(AbstractLogPrinter logPrinter); static void removeLogPrint(AbstractLogPrinter logPrinter); static void clearLogPrint(); static void v(String msg, Object...args); static void v(String msg, Throwable tr, Object...args); static void d(String msg, Object...args); static void d(String msg, Throwable tr, Object...args); static void i(String msg, Object...args); static void i(String msg, Throwable tr, Object...args); static void w(String msg, Object...args); static void w(String msg, Throwable tr, Object...args); static void w(Throwable tr, Object...args); static void e(String msg, Object...args); static void e(String msg, Throwable tr, Object...args); static void e(Throwable tr, Object...args); static void d(Object object); static void json(String json); static void json(String name, String json); }
Logger { public static void removeLogPrint(AbstractLogPrinter logPrinter) { if (logPrinter == null) throw new NullPointerException("logPrinter is null"); logAdapter.remove(logPrinter); } private Logger(); static void addLogPrinter(AbstractLogPrinter logPrinter); static void removeLogPrint(AbstractLogPrinter logPrinter); static void clearLogPrint(); static void v(String msg, Object...args); static void v(String msg, Throwable tr, Object...args); static void d(String msg, Object...args); static void d(String msg, Throwable tr, Object...args); static void i(String msg, Object...args); static void i(String msg, Throwable tr, Object...args); static void w(String msg, Object...args); static void w(String msg, Throwable tr, Object...args); static void w(Throwable tr, Object...args); static void e(String msg, Object...args); static void e(String msg, Throwable tr, Object...args); static void e(Throwable tr, Object...args); static void d(Object object); static void json(String json); static void json(String name, String json); }
@Test public void dontAddLogPrinter() { String message = "Hello, world!"; Logger.d(message); assertLog() .hasNoMoreMessages(); }
public static void d(String msg, Object...args) { logAdapter.d(msg, args); }
Logger { public static void d(String msg, Object...args) { logAdapter.d(msg, args); } }
Logger { public static void d(String msg, Object...args) { logAdapter.d(msg, args); } private Logger(); }
Logger { public static void d(String msg, Object...args) { logAdapter.d(msg, args); } private Logger(); static void addLogPrinter(AbstractLogPrinter logPrinter); static void removeLogPrint(AbstractLogPrinter logPrinter); static void clearLogPrint(); static void v(String msg, Object...args); static void v(String msg, Throwable tr, Object...args); static void d(String msg, Object...args); static void d(String msg, Throwable tr, Object...args); static void i(String msg, Object...args); static void i(String msg, Throwable tr, Object...args); static void w(String msg, Object...args); static void w(String msg, Throwable tr, Object...args); static void w(Throwable tr, Object...args); static void e(String msg, Object...args); static void e(String msg, Throwable tr, Object...args); static void e(Throwable tr, Object...args); static void d(Object object); static void json(String json); static void json(String name, String json); }
Logger { public static void d(String msg, Object...args) { logAdapter.d(msg, args); } private Logger(); static void addLogPrinter(AbstractLogPrinter logPrinter); static void removeLogPrint(AbstractLogPrinter logPrinter); static void clearLogPrint(); static void v(String msg, Object...args); static void v(String msg, Throwable tr, Object...args); static void d(String msg, Object...args); static void d(String msg, Throwable tr, Object...args); static void i(String msg, Object...args); static void i(String msg, Throwable tr, Object...args); static void w(String msg, Object...args); static void w(String msg, Throwable tr, Object...args); static void w(Throwable tr, Object...args); static void e(String msg, Object...args); static void e(String msg, Throwable tr, Object...args); static void e(Throwable tr, Object...args); static void d(Object object); static void json(String json); static void json(String name, String json); }
@Test public void test() { String user = "zlikun" ; int seniority = 7 ; Component component = new ComponetImpl() ; Assert.assertEquals(0 ,component.calc(user ,seniority) ,0); Decorator d1 = new MonthDecorator(component) ; Assert.assertEquals(1000 ,d1.calc(user ,seniority) ,0); Decorator d2 = new YearDecorator(d1) ; Assert.assertEquals(3000 ,d2.calc(user ,seniority) ,0); }
@Override public double calc(String user ,int seniority) { return this.component.calc(user ,seniority); }
Decorator implements Component { @Override public double calc(String user ,int seniority) { return this.component.calc(user ,seniority); } }
Decorator implements Component { @Override public double calc(String user ,int seniority) { return this.component.calc(user ,seniority); } Decorator(Component component); }
Decorator implements Component { @Override public double calc(String user ,int seniority) { return this.component.calc(user ,seniority); } Decorator(Component component); @Override double calc(String user ,int seniority); }
Decorator implements Component { @Override public double calc(String user ,int seniority) { return this.component.calc(user ,seniority); } Decorator(Component component); @Override double calc(String user ,int seniority); }
@Test public void test_multi() { final ConcurrentMap<Singleton2 ,Boolean> map = new ConcurrentHashMap<>() ; ExecutorService exec = Executors.newFixedThreadPool(200) ; final long moment = System.currentTimeMillis() + 1000 ; for (int i = 0; i < 1000; i++) { exec.execute(new Runnable() { @Override public void run() { while (true) { if (moment < System.currentTimeMillis()) { map.put(Singleton2.getInstance() ,Boolean.TRUE) ; break; } } } }); } exec.shutdown(); while (!exec.isTerminated()) ; Assert.assertTrue(map.size() > 1); }
public static final Singleton2 getInstance() { if (INSTANCE == null) { INSTANCE = new Singleton2() ; } return INSTANCE ; }
Singleton2 { public static final Singleton2 getInstance() { if (INSTANCE == null) { INSTANCE = new Singleton2() ; } return INSTANCE ; } }
Singleton2 { public static final Singleton2 getInstance() { if (INSTANCE == null) { INSTANCE = new Singleton2() ; } return INSTANCE ; } Singleton2(); }
Singleton2 { public static final Singleton2 getInstance() { if (INSTANCE == null) { INSTANCE = new Singleton2() ; } return INSTANCE ; } Singleton2(); static final Singleton2 getInstance(); }
Singleton2 { public static final Singleton2 getInstance() { if (INSTANCE == null) { INSTANCE = new Singleton2() ; } return INSTANCE ; } Singleton2(); static final Singleton2 getInstance(); }
@Test public void test() { TrainFactory factory = new TrainFactory(new TrainBuilder()) ; String train = factory.process() ; Assert.assertEquals("火车头-火车身-火车尾" ,train); }
public String process() { StringBuilder sb = new StringBuilder() ; sb.append(builder.buildHeader()).append("-") ; sb.append(builder.buildBody()).append("-") ; sb.append(builder.buildFooter()) ; return sb.toString() ; }
TrainFactory { public String process() { StringBuilder sb = new StringBuilder() ; sb.append(builder.buildHeader()).append("-") ; sb.append(builder.buildBody()).append("-") ; sb.append(builder.buildFooter()) ; return sb.toString() ; } }
TrainFactory { public String process() { StringBuilder sb = new StringBuilder() ; sb.append(builder.buildHeader()).append("-") ; sb.append(builder.buildBody()).append("-") ; sb.append(builder.buildFooter()) ; return sb.toString() ; } TrainFactory(TrainBuilder builder); }
TrainFactory { public String process() { StringBuilder sb = new StringBuilder() ; sb.append(builder.buildHeader()).append("-") ; sb.append(builder.buildBody()).append("-") ; sb.append(builder.buildFooter()) ; return sb.toString() ; } TrainFactory(TrainBuilder builder); String process(); }
TrainFactory { public String process() { StringBuilder sb = new StringBuilder() ; sb.append(builder.buildHeader()).append("-") ; sb.append(builder.buildBody()).append("-") ; sb.append(builder.buildFooter()) ; return sb.toString() ; } TrainFactory(TrainBuilder builder); String process(); }
@Test public void test_single() { Assert.assertTrue(Singleton0.getInstance() == Singleton0.getInstance()); }
public static final Singleton0 getInstance() { return INSTANCE ; }
Singleton0 { public static final Singleton0 getInstance() { return INSTANCE ; } }
Singleton0 { public static final Singleton0 getInstance() { return INSTANCE ; } private Singleton0(); }
Singleton0 { public static final Singleton0 getInstance() { return INSTANCE ; } private Singleton0(); static final Singleton0 getInstance(); }
Singleton0 { public static final Singleton0 getInstance() { return INSTANCE ; } private Singleton0(); static final Singleton0 getInstance(); }
@Test public void test_multi() { final Set<Singleton0> set = new HashSet<>() ; ExecutorService exec = Executors.newFixedThreadPool(50) ; for (int i = 0; i < 1000; i++) { exec.execute(new Runnable() { @Override public void run() { set.add(Singleton0.getInstance()) ; } }); } exec.shutdown(); while (!exec.isTerminated()) ; Assert.assertEquals(1 ,set.size()); }
public static final Singleton0 getInstance() { return INSTANCE ; }
Singleton0 { public static final Singleton0 getInstance() { return INSTANCE ; } }
Singleton0 { public static final Singleton0 getInstance() { return INSTANCE ; } private Singleton0(); }
Singleton0 { public static final Singleton0 getInstance() { return INSTANCE ; } private Singleton0(); static final Singleton0 getInstance(); }
Singleton0 { public static final Singleton0 getInstance() { return INSTANCE ; } private Singleton0(); static final Singleton0 getInstance(); }
@Test public void test_single() { Assert.assertTrue(Singleton5.getInstance() == Singleton5.getInstance()); }
public static final Singleton5 getInstance() { if (INSTANCE == null) { try { if (LOCK.tryLock(100 , TimeUnit.MILLISECONDS)) { if (INSTANCE == null) { INSTANCE = new Singleton5(); } } } catch (InterruptedException e) { e.printStackTrace(); } finally { LOCK.unlock(); } } return INSTANCE ; }
Singleton5 { public static final Singleton5 getInstance() { if (INSTANCE == null) { try { if (LOCK.tryLock(100 , TimeUnit.MILLISECONDS)) { if (INSTANCE == null) { INSTANCE = new Singleton5(); } } } catch (InterruptedException e) { e.printStackTrace(); } finally { LOCK.unlock(); } } return INSTANCE ; } }
Singleton5 { public static final Singleton5 getInstance() { if (INSTANCE == null) { try { if (LOCK.tryLock(100 , TimeUnit.MILLISECONDS)) { if (INSTANCE == null) { INSTANCE = new Singleton5(); } } } catch (InterruptedException e) { e.printStackTrace(); } finally { LOCK.unlock(); } } return INSTANCE ; } private Singleton5(); }
Singleton5 { public static final Singleton5 getInstance() { if (INSTANCE == null) { try { if (LOCK.tryLock(100 , TimeUnit.MILLISECONDS)) { if (INSTANCE == null) { INSTANCE = new Singleton5(); } } } catch (InterruptedException e) { e.printStackTrace(); } finally { LOCK.unlock(); } } return INSTANCE ; } private Singleton5(); static final Singleton5 getInstance(); }
Singleton5 { public static final Singleton5 getInstance() { if (INSTANCE == null) { try { if (LOCK.tryLock(100 , TimeUnit.MILLISECONDS)) { if (INSTANCE == null) { INSTANCE = new Singleton5(); } } } catch (InterruptedException e) { e.printStackTrace(); } finally { LOCK.unlock(); } } return INSTANCE ; } private Singleton5(); static final Singleton5 getInstance(); }
@Test public void test_multi() { final ConcurrentMap<Singleton5 ,Boolean> map = new ConcurrentHashMap<>() ; ExecutorService exec = Executors.newFixedThreadPool(400) ; final long moment = System.currentTimeMillis() + 1000 ; for (int i = 0; i < 1000; i++) { exec.execute(new Runnable() { @Override public void run() { while (true) { if (moment < System.currentTimeMillis()) { map.put(Singleton5.getInstance() ,Boolean.TRUE) ; break; } } } }); } exec.shutdown(); while (!exec.isTerminated()) ; Assert.assertEquals(1 ,map.size()); }
public static final Singleton5 getInstance() { if (INSTANCE == null) { try { if (LOCK.tryLock(100 , TimeUnit.MILLISECONDS)) { if (INSTANCE == null) { INSTANCE = new Singleton5(); } } } catch (InterruptedException e) { e.printStackTrace(); } finally { LOCK.unlock(); } } return INSTANCE ; }
Singleton5 { public static final Singleton5 getInstance() { if (INSTANCE == null) { try { if (LOCK.tryLock(100 , TimeUnit.MILLISECONDS)) { if (INSTANCE == null) { INSTANCE = new Singleton5(); } } } catch (InterruptedException e) { e.printStackTrace(); } finally { LOCK.unlock(); } } return INSTANCE ; } }
Singleton5 { public static final Singleton5 getInstance() { if (INSTANCE == null) { try { if (LOCK.tryLock(100 , TimeUnit.MILLISECONDS)) { if (INSTANCE == null) { INSTANCE = new Singleton5(); } } } catch (InterruptedException e) { e.printStackTrace(); } finally { LOCK.unlock(); } } return INSTANCE ; } private Singleton5(); }
Singleton5 { public static final Singleton5 getInstance() { if (INSTANCE == null) { try { if (LOCK.tryLock(100 , TimeUnit.MILLISECONDS)) { if (INSTANCE == null) { INSTANCE = new Singleton5(); } } } catch (InterruptedException e) { e.printStackTrace(); } finally { LOCK.unlock(); } } return INSTANCE ; } private Singleton5(); static final Singleton5 getInstance(); }
Singleton5 { public static final Singleton5 getInstance() { if (INSTANCE == null) { try { if (LOCK.tryLock(100 , TimeUnit.MILLISECONDS)) { if (INSTANCE == null) { INSTANCE = new Singleton5(); } } } catch (InterruptedException e) { e.printStackTrace(); } finally { LOCK.unlock(); } } return INSTANCE ; } private Singleton5(); static final Singleton5 getInstance(); }
@Test public void test_single() { Assert.assertTrue(Singleton3.getInstance() == Singleton3.getInstance()); }
public static final Singleton3 getInstance() { if (INSTANCE == null) { synchronized (Singleton3.class) { if (INSTANCE == null) { INSTANCE = new Singleton3() ; } } } return INSTANCE ; }
Singleton3 { public static final Singleton3 getInstance() { if (INSTANCE == null) { synchronized (Singleton3.class) { if (INSTANCE == null) { INSTANCE = new Singleton3() ; } } } return INSTANCE ; } }
Singleton3 { public static final Singleton3 getInstance() { if (INSTANCE == null) { synchronized (Singleton3.class) { if (INSTANCE == null) { INSTANCE = new Singleton3() ; } } } return INSTANCE ; } private Singleton3(); }
Singleton3 { public static final Singleton3 getInstance() { if (INSTANCE == null) { synchronized (Singleton3.class) { if (INSTANCE == null) { INSTANCE = new Singleton3() ; } } } return INSTANCE ; } private Singleton3(); static final Singleton3 getInstance(); }
Singleton3 { public static final Singleton3 getInstance() { if (INSTANCE == null) { synchronized (Singleton3.class) { if (INSTANCE == null) { INSTANCE = new Singleton3() ; } } } return INSTANCE ; } private Singleton3(); static final Singleton3 getInstance(); }
@Test public void test_multi() { final ConcurrentMap<Singleton3 ,Boolean> map = new ConcurrentHashMap<>() ; ExecutorService exec = Executors.newFixedThreadPool(400) ; final long moment = System.currentTimeMillis() + 1000 ; for (int i = 0; i < 1000; i++) { exec.execute(new Runnable() { @Override public void run() { while (true) { if (moment < System.currentTimeMillis()) { map.put(Singleton3.getInstance() ,Boolean.TRUE) ; break; } } } }); } exec.shutdown(); while (!exec.isTerminated()) ; Assert.assertEquals(1 ,map.size()); }
public static final Singleton3 getInstance() { if (INSTANCE == null) { synchronized (Singleton3.class) { if (INSTANCE == null) { INSTANCE = new Singleton3() ; } } } return INSTANCE ; }
Singleton3 { public static final Singleton3 getInstance() { if (INSTANCE == null) { synchronized (Singleton3.class) { if (INSTANCE == null) { INSTANCE = new Singleton3() ; } } } return INSTANCE ; } }
Singleton3 { public static final Singleton3 getInstance() { if (INSTANCE == null) { synchronized (Singleton3.class) { if (INSTANCE == null) { INSTANCE = new Singleton3() ; } } } return INSTANCE ; } private Singleton3(); }
Singleton3 { public static final Singleton3 getInstance() { if (INSTANCE == null) { synchronized (Singleton3.class) { if (INSTANCE == null) { INSTANCE = new Singleton3() ; } } } return INSTANCE ; } private Singleton3(); static final Singleton3 getInstance(); }
Singleton3 { public static final Singleton3 getInstance() { if (INSTANCE == null) { synchronized (Singleton3.class) { if (INSTANCE == null) { INSTANCE = new Singleton3() ; } } } return INSTANCE ; } private Singleton3(); static final Singleton3 getInstance(); }
@Test public void test_single() { Assert.assertTrue(Singleton4.getInstance() == Singleton4.getInstance()); }
public static final Singleton4 getInstance() { if (INSTANCE == null) { INSTANCE = Singleton4Holder.obj ; } return INSTANCE ; }
Singleton4 { public static final Singleton4 getInstance() { if (INSTANCE == null) { INSTANCE = Singleton4Holder.obj ; } return INSTANCE ; } }
Singleton4 { public static final Singleton4 getInstance() { if (INSTANCE == null) { INSTANCE = Singleton4Holder.obj ; } return INSTANCE ; } private Singleton4(); }
Singleton4 { public static final Singleton4 getInstance() { if (INSTANCE == null) { INSTANCE = Singleton4Holder.obj ; } return INSTANCE ; } private Singleton4(); static final Singleton4 getInstance(); }
Singleton4 { public static final Singleton4 getInstance() { if (INSTANCE == null) { INSTANCE = Singleton4Holder.obj ; } return INSTANCE ; } private Singleton4(); static final Singleton4 getInstance(); }
@Test public void test_multi() { final ConcurrentMap<Singleton4 ,Boolean> map = new ConcurrentHashMap<>() ; ExecutorService exec = Executors.newFixedThreadPool(400) ; final long moment = System.currentTimeMillis() + 1000 ; for (int i = 0; i < 1000; i++) { exec.execute(new Runnable() { @Override public void run() { while (true) { if (moment < System.currentTimeMillis()) { map.put(Singleton4.getInstance() ,Boolean.TRUE) ; break; } } } }); } exec.shutdown(); while (!exec.isTerminated()) ; Assert.assertEquals(1 ,map.size()); }
public static final Singleton4 getInstance() { if (INSTANCE == null) { INSTANCE = Singleton4Holder.obj ; } return INSTANCE ; }
Singleton4 { public static final Singleton4 getInstance() { if (INSTANCE == null) { INSTANCE = Singleton4Holder.obj ; } return INSTANCE ; } }
Singleton4 { public static final Singleton4 getInstance() { if (INSTANCE == null) { INSTANCE = Singleton4Holder.obj ; } return INSTANCE ; } private Singleton4(); }
Singleton4 { public static final Singleton4 getInstance() { if (INSTANCE == null) { INSTANCE = Singleton4Holder.obj ; } return INSTANCE ; } private Singleton4(); static final Singleton4 getInstance(); }
Singleton4 { public static final Singleton4 getInstance() { if (INSTANCE == null) { INSTANCE = Singleton4Holder.obj ; } return INSTANCE ; } private Singleton4(); static final Singleton4 getInstance(); }
@Test public void test_single() { Assert.assertTrue(Singleton2.getInstance() == Singleton2.getInstance()); Assert.assertTrue(new Singleton2() != new Singleton2()); }
public static final Singleton2 getInstance() { if (INSTANCE == null) { INSTANCE = new Singleton2() ; } return INSTANCE ; }
Singleton2 { public static final Singleton2 getInstance() { if (INSTANCE == null) { INSTANCE = new Singleton2() ; } return INSTANCE ; } }
Singleton2 { public static final Singleton2 getInstance() { if (INSTANCE == null) { INSTANCE = new Singleton2() ; } return INSTANCE ; } Singleton2(); }
Singleton2 { public static final Singleton2 getInstance() { if (INSTANCE == null) { INSTANCE = new Singleton2() ; } return INSTANCE ; } Singleton2(); static final Singleton2 getInstance(); }
Singleton2 { public static final Singleton2 getInstance() { if (INSTANCE == null) { INSTANCE = new Singleton2() ; } return INSTANCE ; } Singleton2(); static final Singleton2 getInstance(); }
@Test public void havingRule_parseEmlFromBasicRule_noXmlErrors() throws Exception { String eml = builder.create_BR_5(rule).getEml(); assertThat(XMLBeansParser.validate(XmlObject.Factory.parse(eml)), is(empty())); }
public BasicRule create_BR_5(Rule rule) throws Exception { try { String finalEml; String title = rule.getTitle(); String incomingObservationsCountPatternId = title + "_incoming_observations_count_stream"; String incomingObservationsEventName = title + "_incoming_observations_count"; String noObservationsReceivedStreamPatternId = title + "_no_observation_received_stream"; String observationsReceivedStreamPatternId = title + "_observation_received_stream"; String noObservationsNotificationPatternId = title + "_no_observation_notification"; String observationsNotificationPatternId = title + "_observation_notification"; String noObservationsReceivedEventName = title + "_no_observation_received"; String observationsReceivedEventName = title + "_observation_received"; String noObservationsOutputName = title + "_no_observation_output"; String observationsOutputName = title + "_observation_output"; EMLDocument emlTemplateDoc = getEmlTemplate(); SimplePatterns simplePatterns = emlTemplateDoc.getEML().getSimplePatterns(); SimplePatternType incomingObservationCount = simplePatterns.getSimplePatternArray(0); processSimplePattern(incomingObservationCount, incomingObservationsCountPatternId, incomingObservationsEventName); processPropertyRestrictions(incomingObservationCount, rule.getTimeseriesMetadata()); processDurationValue(incomingObservationCount, rule); ComplexPatterns complexPatterns = emlTemplateDoc.getEML().getComplexPatterns(); ComplexPattern noObservationsReceived = complexPatterns.getComplexPatternArray(0); processComplexPattern(noObservationsReceived, noObservationsReceivedStreamPatternId, noObservationsReceivedEventName); setSelectEventName(noObservationsReceived, incomingObservationsEventName); noObservationsReceived.getFirstPattern().setPatternReference(incomingObservationsCountPatternId); noObservationsReceived.getSecondPattern().setPatternReference(incomingObservationsCountPatternId); processEqualToFilterGuard(noObservationsReceived, incomingObservationsEventName); ComplexPattern observationsReceived = complexPatterns.getComplexPatternArray(1); processComplexPattern(observationsReceived, observationsReceivedStreamPatternId, observationsReceivedEventName); setSelectEventName(observationsReceived, incomingObservationsEventName); observationsReceived.getFirstPattern().setPatternReference(incomingObservationsCountPatternId); observationsReceived.getSecondPattern().setPatternReference(incomingObservationsCountPatternId); processNotEqualToFilterGuard(observationsReceived, incomingObservationsEventName); ComplexPattern noObservationsReceivedNotification = complexPatterns.getComplexPatternArray(2); processComplexPattern(noObservationsReceivedNotification, noObservationsNotificationPatternId, noObservationsReceivedEventName); setOutputName(noObservationsReceivedNotification, noObservationsOutputName); noObservationsReceivedNotification.getFirstPattern().setPatternReference(observationsReceivedStreamPatternId); noObservationsReceivedNotification.getSecondPattern().setPatternReference(noObservationsReceivedStreamPatternId); ComplexPattern observationsReceivedNotification = complexPatterns.getComplexPatternArray(3); processComplexPattern(observationsReceivedNotification, observationsNotificationPatternId, observationsReceivedEventName); setOutputName(observationsReceivedNotification, observationsOutputName); observationsReceivedNotification.getFirstPattern().setPatternReference(noObservationsReceivedStreamPatternId); observationsReceivedNotification.getSecondPattern().setPatternReference(observationsReceivedStreamPatternId); finalEml = emlTemplateDoc.xmlText(); User user = getUserFrom(rule); BasicRule basicRule = new BasicRule(rule.getTitle(), "B", "BR5", rule.getDescription(), rule.isPublish(), user.getId(), finalEml, false); basicRule.setUuid(rule.getUuid()); return basicRule; } catch (Exception e) { LOGGER.error("Error creating rule", e); return null; } }
BasicRule_5_Builder extends BasicRuleBuilder { public BasicRule create_BR_5(Rule rule) throws Exception { try { String finalEml; String title = rule.getTitle(); String incomingObservationsCountPatternId = title + "_incoming_observations_count_stream"; String incomingObservationsEventName = title + "_incoming_observations_count"; String noObservationsReceivedStreamPatternId = title + "_no_observation_received_stream"; String observationsReceivedStreamPatternId = title + "_observation_received_stream"; String noObservationsNotificationPatternId = title + "_no_observation_notification"; String observationsNotificationPatternId = title + "_observation_notification"; String noObservationsReceivedEventName = title + "_no_observation_received"; String observationsReceivedEventName = title + "_observation_received"; String noObservationsOutputName = title + "_no_observation_output"; String observationsOutputName = title + "_observation_output"; EMLDocument emlTemplateDoc = getEmlTemplate(); SimplePatterns simplePatterns = emlTemplateDoc.getEML().getSimplePatterns(); SimplePatternType incomingObservationCount = simplePatterns.getSimplePatternArray(0); processSimplePattern(incomingObservationCount, incomingObservationsCountPatternId, incomingObservationsEventName); processPropertyRestrictions(incomingObservationCount, rule.getTimeseriesMetadata()); processDurationValue(incomingObservationCount, rule); ComplexPatterns complexPatterns = emlTemplateDoc.getEML().getComplexPatterns(); ComplexPattern noObservationsReceived = complexPatterns.getComplexPatternArray(0); processComplexPattern(noObservationsReceived, noObservationsReceivedStreamPatternId, noObservationsReceivedEventName); setSelectEventName(noObservationsReceived, incomingObservationsEventName); noObservationsReceived.getFirstPattern().setPatternReference(incomingObservationsCountPatternId); noObservationsReceived.getSecondPattern().setPatternReference(incomingObservationsCountPatternId); processEqualToFilterGuard(noObservationsReceived, incomingObservationsEventName); ComplexPattern observationsReceived = complexPatterns.getComplexPatternArray(1); processComplexPattern(observationsReceived, observationsReceivedStreamPatternId, observationsReceivedEventName); setSelectEventName(observationsReceived, incomingObservationsEventName); observationsReceived.getFirstPattern().setPatternReference(incomingObservationsCountPatternId); observationsReceived.getSecondPattern().setPatternReference(incomingObservationsCountPatternId); processNotEqualToFilterGuard(observationsReceived, incomingObservationsEventName); ComplexPattern noObservationsReceivedNotification = complexPatterns.getComplexPatternArray(2); processComplexPattern(noObservationsReceivedNotification, noObservationsNotificationPatternId, noObservationsReceivedEventName); setOutputName(noObservationsReceivedNotification, noObservationsOutputName); noObservationsReceivedNotification.getFirstPattern().setPatternReference(observationsReceivedStreamPatternId); noObservationsReceivedNotification.getSecondPattern().setPatternReference(noObservationsReceivedStreamPatternId); ComplexPattern observationsReceivedNotification = complexPatterns.getComplexPatternArray(3); processComplexPattern(observationsReceivedNotification, observationsNotificationPatternId, observationsReceivedEventName); setOutputName(observationsReceivedNotification, observationsOutputName); observationsReceivedNotification.getFirstPattern().setPatternReference(noObservationsReceivedStreamPatternId); observationsReceivedNotification.getSecondPattern().setPatternReference(observationsReceivedStreamPatternId); finalEml = emlTemplateDoc.xmlText(); User user = getUserFrom(rule); BasicRule basicRule = new BasicRule(rule.getTitle(), "B", "BR5", rule.getDescription(), rule.isPublish(), user.getId(), finalEml, false); basicRule.setUuid(rule.getUuid()); return basicRule; } catch (Exception e) { LOGGER.error("Error creating rule", e); return null; } } }
BasicRule_5_Builder extends BasicRuleBuilder { public BasicRule create_BR_5(Rule rule) throws Exception { try { String finalEml; String title = rule.getTitle(); String incomingObservationsCountPatternId = title + "_incoming_observations_count_stream"; String incomingObservationsEventName = title + "_incoming_observations_count"; String noObservationsReceivedStreamPatternId = title + "_no_observation_received_stream"; String observationsReceivedStreamPatternId = title + "_observation_received_stream"; String noObservationsNotificationPatternId = title + "_no_observation_notification"; String observationsNotificationPatternId = title + "_observation_notification"; String noObservationsReceivedEventName = title + "_no_observation_received"; String observationsReceivedEventName = title + "_observation_received"; String noObservationsOutputName = title + "_no_observation_output"; String observationsOutputName = title + "_observation_output"; EMLDocument emlTemplateDoc = getEmlTemplate(); SimplePatterns simplePatterns = emlTemplateDoc.getEML().getSimplePatterns(); SimplePatternType incomingObservationCount = simplePatterns.getSimplePatternArray(0); processSimplePattern(incomingObservationCount, incomingObservationsCountPatternId, incomingObservationsEventName); processPropertyRestrictions(incomingObservationCount, rule.getTimeseriesMetadata()); processDurationValue(incomingObservationCount, rule); ComplexPatterns complexPatterns = emlTemplateDoc.getEML().getComplexPatterns(); ComplexPattern noObservationsReceived = complexPatterns.getComplexPatternArray(0); processComplexPattern(noObservationsReceived, noObservationsReceivedStreamPatternId, noObservationsReceivedEventName); setSelectEventName(noObservationsReceived, incomingObservationsEventName); noObservationsReceived.getFirstPattern().setPatternReference(incomingObservationsCountPatternId); noObservationsReceived.getSecondPattern().setPatternReference(incomingObservationsCountPatternId); processEqualToFilterGuard(noObservationsReceived, incomingObservationsEventName); ComplexPattern observationsReceived = complexPatterns.getComplexPatternArray(1); processComplexPattern(observationsReceived, observationsReceivedStreamPatternId, observationsReceivedEventName); setSelectEventName(observationsReceived, incomingObservationsEventName); observationsReceived.getFirstPattern().setPatternReference(incomingObservationsCountPatternId); observationsReceived.getSecondPattern().setPatternReference(incomingObservationsCountPatternId); processNotEqualToFilterGuard(observationsReceived, incomingObservationsEventName); ComplexPattern noObservationsReceivedNotification = complexPatterns.getComplexPatternArray(2); processComplexPattern(noObservationsReceivedNotification, noObservationsNotificationPatternId, noObservationsReceivedEventName); setOutputName(noObservationsReceivedNotification, noObservationsOutputName); noObservationsReceivedNotification.getFirstPattern().setPatternReference(observationsReceivedStreamPatternId); noObservationsReceivedNotification.getSecondPattern().setPatternReference(noObservationsReceivedStreamPatternId); ComplexPattern observationsReceivedNotification = complexPatterns.getComplexPatternArray(3); processComplexPattern(observationsReceivedNotification, observationsNotificationPatternId, observationsReceivedEventName); setOutputName(observationsReceivedNotification, observationsOutputName); observationsReceivedNotification.getFirstPattern().setPatternReference(noObservationsReceivedStreamPatternId); observationsReceivedNotification.getSecondPattern().setPatternReference(observationsReceivedStreamPatternId); finalEml = emlTemplateDoc.xmlText(); User user = getUserFrom(rule); BasicRule basicRule = new BasicRule(rule.getTitle(), "B", "BR5", rule.getDescription(), rule.isPublish(), user.getId(), finalEml, false); basicRule.setUuid(rule.getUuid()); return basicRule; } catch (Exception e) { LOGGER.error("Error creating rule", e); return null; } } BasicRule_5_Builder(); }
BasicRule_5_Builder extends BasicRuleBuilder { public BasicRule create_BR_5(Rule rule) throws Exception { try { String finalEml; String title = rule.getTitle(); String incomingObservationsCountPatternId = title + "_incoming_observations_count_stream"; String incomingObservationsEventName = title + "_incoming_observations_count"; String noObservationsReceivedStreamPatternId = title + "_no_observation_received_stream"; String observationsReceivedStreamPatternId = title + "_observation_received_stream"; String noObservationsNotificationPatternId = title + "_no_observation_notification"; String observationsNotificationPatternId = title + "_observation_notification"; String noObservationsReceivedEventName = title + "_no_observation_received"; String observationsReceivedEventName = title + "_observation_received"; String noObservationsOutputName = title + "_no_observation_output"; String observationsOutputName = title + "_observation_output"; EMLDocument emlTemplateDoc = getEmlTemplate(); SimplePatterns simplePatterns = emlTemplateDoc.getEML().getSimplePatterns(); SimplePatternType incomingObservationCount = simplePatterns.getSimplePatternArray(0); processSimplePattern(incomingObservationCount, incomingObservationsCountPatternId, incomingObservationsEventName); processPropertyRestrictions(incomingObservationCount, rule.getTimeseriesMetadata()); processDurationValue(incomingObservationCount, rule); ComplexPatterns complexPatterns = emlTemplateDoc.getEML().getComplexPatterns(); ComplexPattern noObservationsReceived = complexPatterns.getComplexPatternArray(0); processComplexPattern(noObservationsReceived, noObservationsReceivedStreamPatternId, noObservationsReceivedEventName); setSelectEventName(noObservationsReceived, incomingObservationsEventName); noObservationsReceived.getFirstPattern().setPatternReference(incomingObservationsCountPatternId); noObservationsReceived.getSecondPattern().setPatternReference(incomingObservationsCountPatternId); processEqualToFilterGuard(noObservationsReceived, incomingObservationsEventName); ComplexPattern observationsReceived = complexPatterns.getComplexPatternArray(1); processComplexPattern(observationsReceived, observationsReceivedStreamPatternId, observationsReceivedEventName); setSelectEventName(observationsReceived, incomingObservationsEventName); observationsReceived.getFirstPattern().setPatternReference(incomingObservationsCountPatternId); observationsReceived.getSecondPattern().setPatternReference(incomingObservationsCountPatternId); processNotEqualToFilterGuard(observationsReceived, incomingObservationsEventName); ComplexPattern noObservationsReceivedNotification = complexPatterns.getComplexPatternArray(2); processComplexPattern(noObservationsReceivedNotification, noObservationsNotificationPatternId, noObservationsReceivedEventName); setOutputName(noObservationsReceivedNotification, noObservationsOutputName); noObservationsReceivedNotification.getFirstPattern().setPatternReference(observationsReceivedStreamPatternId); noObservationsReceivedNotification.getSecondPattern().setPatternReference(noObservationsReceivedStreamPatternId); ComplexPattern observationsReceivedNotification = complexPatterns.getComplexPatternArray(3); processComplexPattern(observationsReceivedNotification, observationsNotificationPatternId, observationsReceivedEventName); setOutputName(observationsReceivedNotification, observationsOutputName); observationsReceivedNotification.getFirstPattern().setPatternReference(noObservationsReceivedStreamPatternId); observationsReceivedNotification.getSecondPattern().setPatternReference(observationsReceivedStreamPatternId); finalEml = emlTemplateDoc.xmlText(); User user = getUserFrom(rule); BasicRule basicRule = new BasicRule(rule.getTitle(), "B", "BR5", rule.getDescription(), rule.isPublish(), user.getId(), finalEml, false); basicRule.setUuid(rule.getUuid()); return basicRule; } catch (Exception e) { LOGGER.error("Error creating rule", e); return null; } } BasicRule_5_Builder(); BasicRule create_BR_5(Rule rule); Rule getRuleByEML(BasicRule basicRule); }
BasicRule_5_Builder extends BasicRuleBuilder { public BasicRule create_BR_5(Rule rule) throws Exception { try { String finalEml; String title = rule.getTitle(); String incomingObservationsCountPatternId = title + "_incoming_observations_count_stream"; String incomingObservationsEventName = title + "_incoming_observations_count"; String noObservationsReceivedStreamPatternId = title + "_no_observation_received_stream"; String observationsReceivedStreamPatternId = title + "_observation_received_stream"; String noObservationsNotificationPatternId = title + "_no_observation_notification"; String observationsNotificationPatternId = title + "_observation_notification"; String noObservationsReceivedEventName = title + "_no_observation_received"; String observationsReceivedEventName = title + "_observation_received"; String noObservationsOutputName = title + "_no_observation_output"; String observationsOutputName = title + "_observation_output"; EMLDocument emlTemplateDoc = getEmlTemplate(); SimplePatterns simplePatterns = emlTemplateDoc.getEML().getSimplePatterns(); SimplePatternType incomingObservationCount = simplePatterns.getSimplePatternArray(0); processSimplePattern(incomingObservationCount, incomingObservationsCountPatternId, incomingObservationsEventName); processPropertyRestrictions(incomingObservationCount, rule.getTimeseriesMetadata()); processDurationValue(incomingObservationCount, rule); ComplexPatterns complexPatterns = emlTemplateDoc.getEML().getComplexPatterns(); ComplexPattern noObservationsReceived = complexPatterns.getComplexPatternArray(0); processComplexPattern(noObservationsReceived, noObservationsReceivedStreamPatternId, noObservationsReceivedEventName); setSelectEventName(noObservationsReceived, incomingObservationsEventName); noObservationsReceived.getFirstPattern().setPatternReference(incomingObservationsCountPatternId); noObservationsReceived.getSecondPattern().setPatternReference(incomingObservationsCountPatternId); processEqualToFilterGuard(noObservationsReceived, incomingObservationsEventName); ComplexPattern observationsReceived = complexPatterns.getComplexPatternArray(1); processComplexPattern(observationsReceived, observationsReceivedStreamPatternId, observationsReceivedEventName); setSelectEventName(observationsReceived, incomingObservationsEventName); observationsReceived.getFirstPattern().setPatternReference(incomingObservationsCountPatternId); observationsReceived.getSecondPattern().setPatternReference(incomingObservationsCountPatternId); processNotEqualToFilterGuard(observationsReceived, incomingObservationsEventName); ComplexPattern noObservationsReceivedNotification = complexPatterns.getComplexPatternArray(2); processComplexPattern(noObservationsReceivedNotification, noObservationsNotificationPatternId, noObservationsReceivedEventName); setOutputName(noObservationsReceivedNotification, noObservationsOutputName); noObservationsReceivedNotification.getFirstPattern().setPatternReference(observationsReceivedStreamPatternId); noObservationsReceivedNotification.getSecondPattern().setPatternReference(noObservationsReceivedStreamPatternId); ComplexPattern observationsReceivedNotification = complexPatterns.getComplexPatternArray(3); processComplexPattern(observationsReceivedNotification, observationsNotificationPatternId, observationsReceivedEventName); setOutputName(observationsReceivedNotification, observationsOutputName); observationsReceivedNotification.getFirstPattern().setPatternReference(noObservationsReceivedStreamPatternId); observationsReceivedNotification.getSecondPattern().setPatternReference(observationsReceivedStreamPatternId); finalEml = emlTemplateDoc.xmlText(); User user = getUserFrom(rule); BasicRule basicRule = new BasicRule(rule.getTitle(), "B", "BR5", rule.getDescription(), rule.isPublish(), user.getId(), finalEml, false); basicRule.setUuid(rule.getUuid()); return basicRule; } catch (Exception e) { LOGGER.error("Error creating rule", e); return null; } } BasicRule_5_Builder(); BasicRule create_BR_5(Rule rule); Rule getRuleByEML(BasicRule basicRule); }
@Test public void testParseStationKvp() { StringBuilder validQuery = new StringBuilder(); validQuery.append("features=").append("Heldra_41700105"); QueryParser parser = new QueryParser(validQuery.toString(), false); Collection<String> parsedStations = parser.parseFeatures(); assertTrue("Invalid size: " + parsedStations.size(), parsedStations.size() == 1); assertTrue("Stations could not be parsed.", parsedStations.contains("Heldra_41700105")); }
public Collection<String> parseFeatures() { String featureValues = kvps.get(FEATURES.name()); return parseCommaSeparatedValues(featureValues); }
QueryParser { public Collection<String> parseFeatures() { String featureValues = kvps.get(FEATURES.name()); return parseCommaSeparatedValues(featureValues); } }
QueryParser { public Collection<String> parseFeatures() { String featureValues = kvps.get(FEATURES.name()); return parseCommaSeparatedValues(featureValues); } QueryParser(String query, boolean compressed); }
QueryParser { public Collection<String> parseFeatures() { String featureValues = kvps.get(FEATURES.name()); return parseCommaSeparatedValues(featureValues); } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeatures(); Collection<String> parseOfferings(); Collection<String> parseProcedures(); Collection<String> parsePhenomenons(); TimeRange parseTimeRange(); }
QueryParser { public Collection<String> parseFeatures() { String featureValues = kvps.get(FEATURES.name()); return parseCommaSeparatedValues(featureValues); } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeatures(); Collection<String> parseOfferings(); Collection<String> parseProcedures(); Collection<String> parsePhenomenons(); TimeRange parseTimeRange(); }
@Test public void testParsePhenomenonsKvp() { StringBuilder validQuery = new StringBuilder(); validQuery.append("phenomenons=").append("Wasserstand"); QueryParser parser = new QueryParser(validQuery.toString(), false); Collection<String> parsedPhenomenons = parser.parsePhenomenons(); assertTrue("Invalid size: " + parsedPhenomenons.size(), parsedPhenomenons.size() == 1); assertTrue("Stations could not be parsed.", parsedPhenomenons.contains("Wasserstand")); }
public Collection<String> parsePhenomenons() { String phenomenonValues = kvps.get(PHENOMENONS.name()); return parseCommaSeparatedValues(phenomenonValues); }
QueryParser { public Collection<String> parsePhenomenons() { String phenomenonValues = kvps.get(PHENOMENONS.name()); return parseCommaSeparatedValues(phenomenonValues); } }
QueryParser { public Collection<String> parsePhenomenons() { String phenomenonValues = kvps.get(PHENOMENONS.name()); return parseCommaSeparatedValues(phenomenonValues); } QueryParser(String query, boolean compressed); }
QueryParser { public Collection<String> parsePhenomenons() { String phenomenonValues = kvps.get(PHENOMENONS.name()); return parseCommaSeparatedValues(phenomenonValues); } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeatures(); Collection<String> parseOfferings(); Collection<String> parseProcedures(); Collection<String> parsePhenomenons(); TimeRange parseTimeRange(); }
QueryParser { public Collection<String> parsePhenomenons() { String phenomenonValues = kvps.get(PHENOMENONS.name()); return parseCommaSeparatedValues(phenomenonValues); } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeatures(); Collection<String> parseOfferings(); Collection<String> parseProcedures(); Collection<String> parsePhenomenons(); TimeRange parseTimeRange(); }
@Test public void testParseProceduresKvp() { StringBuilder validQuery = new StringBuilder(); validQuery.append("procedures=").append("Wasserstand-Heldra_41700105"); QueryParser parser = new QueryParser(validQuery.toString(), false); Collection<String> parsedProcedures = parser.parseProcedures(); assertTrue("Invalid size: " + parsedProcedures.size(), parsedProcedures.size() == 1); assertTrue("Stations could not be parsed.", parsedProcedures.contains("Wasserstand-Heldra_41700105")); }
public Collection<String> parseProcedures() { String procedureValues = kvps.get(PROCEDURES.name()); return parseCommaSeparatedValues(procedureValues); }
QueryParser { public Collection<String> parseProcedures() { String procedureValues = kvps.get(PROCEDURES.name()); return parseCommaSeparatedValues(procedureValues); } }
QueryParser { public Collection<String> parseProcedures() { String procedureValues = kvps.get(PROCEDURES.name()); return parseCommaSeparatedValues(procedureValues); } QueryParser(String query, boolean compressed); }
QueryParser { public Collection<String> parseProcedures() { String procedureValues = kvps.get(PROCEDURES.name()); return parseCommaSeparatedValues(procedureValues); } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeatures(); Collection<String> parseOfferings(); Collection<String> parseProcedures(); Collection<String> parsePhenomenons(); TimeRange parseTimeRange(); }
QueryParser { public Collection<String> parseProcedures() { String procedureValues = kvps.get(PROCEDURES.name()); return parseCommaSeparatedValues(procedureValues); } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeatures(); Collection<String> parseOfferings(); Collection<String> parseProcedures(); Collection<String> parsePhenomenons(); TimeRange parseTimeRange(); }
@Test public void testParsingBeginAndEndKvps() { StringBuilder validQuery = new StringBuilder(); validQuery.append("begin"); validQuery.append("="); validQuery.append("2012-10-01T12:01:00"); validQuery.append("&"); validQuery.append("end"); validQuery.append("="); validQuery.append("2014-10-01T12:01:00"); QueryParser parser = new QueryParser(validQuery.toString(), false); TimeRange parsedTimeRange = parser.parseTimeRange(); assertEquals("2012-10-01T12:01:00", parsedTimeRange.getStart()); assertEquals("2014-10-01T12:01:00", parsedTimeRange.getEnd()); }
public TimeRange parseTimeRange() { String begin = kvps.get(BEGIN.name()); String end = kvps.get(END.name()); return TimeRange.createTimeRange(begin, end); }
QueryParser { public TimeRange parseTimeRange() { String begin = kvps.get(BEGIN.name()); String end = kvps.get(END.name()); return TimeRange.createTimeRange(begin, end); } }
QueryParser { public TimeRange parseTimeRange() { String begin = kvps.get(BEGIN.name()); String end = kvps.get(END.name()); return TimeRange.createTimeRange(begin, end); } QueryParser(String query, boolean compressed); }
QueryParser { public TimeRange parseTimeRange() { String begin = kvps.get(BEGIN.name()); String end = kvps.get(END.name()); return TimeRange.createTimeRange(begin, end); } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeatures(); Collection<String> parseOfferings(); Collection<String> parseProcedures(); Collection<String> parsePhenomenons(); TimeRange parseTimeRange(); }
QueryParser { public TimeRange parseTimeRange() { String begin = kvps.get(BEGIN.name()); String end = kvps.get(END.name()); return TimeRange.createTimeRange(begin, end); } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeatures(); Collection<String> parseOfferings(); Collection<String> parseProcedures(); Collection<String> parsePhenomenons(); TimeRange parseTimeRange(); }
@Test public void shouldParseSystemViaXPath() { SystemType systemType = xmlHelper.parseFirst(smlDoc, "$this assertNotNull(systemType); }
public <T> T parseFirst(XmlObject from, String xPath, Class<T> ofType) { T[] results = parseAll(from, xPath, ofType); return results.length > 0 ? results[0] : null; }
XmlHelper { public <T> T parseFirst(XmlObject from, String xPath, Class<T> ofType) { T[] results = parseAll(from, xPath, ofType); return results.length > 0 ? results[0] : null; } }
XmlHelper { public <T> T parseFirst(XmlObject from, String xPath, Class<T> ofType) { T[] results = parseAll(from, xPath, ofType); return results.length > 0 ? results[0] : null; } XmlHelper(Map<String, String> namespaceDecarations); }
XmlHelper { public <T> T parseFirst(XmlObject from, String xPath, Class<T> ofType) { T[] results = parseAll(from, xPath, ofType); return results.length > 0 ? results[0] : null; } XmlHelper(Map<String, String> namespaceDecarations); String getShortName(IdentifierList identifiers); String getUniqueId(IdentifierList identifiers); String[] getRelatedFeatures(Capabilities identifiers); PointDocument getPoint(FeaturePropertyType member, CRSUtils referenceHelper); String[] getRelatedPhenomena(Outputs outputs); T parseFirst(XmlObject from, String xPath, Class<T> ofType); @SuppressWarnings("unchecked") T[] parseAll(XmlObject from, String xPath, Class<T> ofType); }
XmlHelper { public <T> T parseFirst(XmlObject from, String xPath, Class<T> ofType) { T[] results = parseAll(from, xPath, ofType); return results.length > 0 ? results[0] : null; } XmlHelper(Map<String, String> namespaceDecarations); String getShortName(IdentifierList identifiers); String getUniqueId(IdentifierList identifiers); String[] getRelatedFeatures(Capabilities identifiers); PointDocument getPoint(FeaturePropertyType member, CRSUtils referenceHelper); String[] getRelatedPhenomena(Outputs outputs); T parseFirst(XmlObject from, String xPath, Class<T> ofType); @SuppressWarnings("unchecked") T[] parseAll(XmlObject from, String xPath, Class<T> ofType); }
@Test public void shouldNotAddValuesTwiceWhenCreatingTimeseriesDuringDaylightSavingSwitch() throws Exception { SosTimeseries timeseries = createSosTimeseries(); GetObservationResponseToOxfFeatureCollectionReader reader = createReader(); String[] foiIds = new String[]{timeseries.getFeatureId()}; String[] procedureIds = new String[]{timeseries.getProcedureId()}; String[] observedPropertyIds = new String[]{timeseries.getPhenomenonId()}; OXFFeatureCollection obsColl = reader.getFeatureCollection(); ObservationSeriesCollection seriesCollection = new ObservationSeriesCollection(obsColl, foiIds, observedPropertyIds, procedureIds, true); assertThat(seriesCollection.getAllTuples().size(), is(277)); TimeseriesFactory factory = new TimeseriesFactory(seriesCollection); TimeSeries chartTimeseries = factory.createTimeSeries(timeseries, "1"); assertThat(chartTimeseries.getItemCount(), is(277)); }
public TimeSeries createTimeSeries(SosTimeseries timeseries, String seriesType) { TimeSeries timeSeries = new TimeSeries(timeseries.getTimeseriesId()); ITimePosition timeArray[] = collection.getSortedTimeArray(); ObservedValueTuple prevObservation; ObservedValueTuple nextObservation = collection.getTuple(new OXFFeature(timeseries.getFeatureId(), null), timeArray[0]); ObservedValueTuple observation = nextObservation; int counter = 0; Double sum = 0.0; LOGGER.debug("Compressionlevel none"); for (int i = 0; i < timeArray.length; i++) { prevObservation = observation; observation = nextObservation; if (i + 1 < timeArray.length) { nextObservation = collection.getTuple(new OXFFeature(timeseries.getFeatureId(), null), timeArray[i + 1]); } counter++; Double resultVal = getValidData(observation.getValue(0).toString()); if (seriesType.equals("1")) { } else if (seriesType.equals("2")) { if (resultVal != null) { resultVal += sum; } else { resultVal = sum; } } else { } sum = resultVal; ITimePosition timePos = (ITimePosition) observation.getTime(); DateTime time = DateTime.parse(timePos.toISO8601Format()); timeSeries.add(new FixedMillisecond(time.getMillis()), resultVal); } LOGGER.debug("Compressed observations from " + timeArray.length + " to " + counter); return timeSeries; }
TimeseriesFactory { public TimeSeries createTimeSeries(SosTimeseries timeseries, String seriesType) { TimeSeries timeSeries = new TimeSeries(timeseries.getTimeseriesId()); ITimePosition timeArray[] = collection.getSortedTimeArray(); ObservedValueTuple prevObservation; ObservedValueTuple nextObservation = collection.getTuple(new OXFFeature(timeseries.getFeatureId(), null), timeArray[0]); ObservedValueTuple observation = nextObservation; int counter = 0; Double sum = 0.0; LOGGER.debug("Compressionlevel none"); for (int i = 0; i < timeArray.length; i++) { prevObservation = observation; observation = nextObservation; if (i + 1 < timeArray.length) { nextObservation = collection.getTuple(new OXFFeature(timeseries.getFeatureId(), null), timeArray[i + 1]); } counter++; Double resultVal = getValidData(observation.getValue(0).toString()); if (seriesType.equals("1")) { } else if (seriesType.equals("2")) { if (resultVal != null) { resultVal += sum; } else { resultVal = sum; } } else { } sum = resultVal; ITimePosition timePos = (ITimePosition) observation.getTime(); DateTime time = DateTime.parse(timePos.toISO8601Format()); timeSeries.add(new FixedMillisecond(time.getMillis()), resultVal); } LOGGER.debug("Compressed observations from " + timeArray.length + " to " + counter); return timeSeries; } }
TimeseriesFactory { public TimeSeries createTimeSeries(SosTimeseries timeseries, String seriesType) { TimeSeries timeSeries = new TimeSeries(timeseries.getTimeseriesId()); ITimePosition timeArray[] = collection.getSortedTimeArray(); ObservedValueTuple prevObservation; ObservedValueTuple nextObservation = collection.getTuple(new OXFFeature(timeseries.getFeatureId(), null), timeArray[0]); ObservedValueTuple observation = nextObservation; int counter = 0; Double sum = 0.0; LOGGER.debug("Compressionlevel none"); for (int i = 0; i < timeArray.length; i++) { prevObservation = observation; observation = nextObservation; if (i + 1 < timeArray.length) { nextObservation = collection.getTuple(new OXFFeature(timeseries.getFeatureId(), null), timeArray[i + 1]); } counter++; Double resultVal = getValidData(observation.getValue(0).toString()); if (seriesType.equals("1")) { } else if (seriesType.equals("2")) { if (resultVal != null) { resultVal += sum; } else { resultVal = sum; } } else { } sum = resultVal; ITimePosition timePos = (ITimePosition) observation.getTime(); DateTime time = DateTime.parse(timePos.toISO8601Format()); timeSeries.add(new FixedMillisecond(time.getMillis()), resultVal); } LOGGER.debug("Compressed observations from " + timeArray.length + " to " + counter); return timeSeries; } TimeseriesFactory(ObservationSeriesCollection collection); }
TimeseriesFactory { public TimeSeries createTimeSeries(SosTimeseries timeseries, String seriesType) { TimeSeries timeSeries = new TimeSeries(timeseries.getTimeseriesId()); ITimePosition timeArray[] = collection.getSortedTimeArray(); ObservedValueTuple prevObservation; ObservedValueTuple nextObservation = collection.getTuple(new OXFFeature(timeseries.getFeatureId(), null), timeArray[0]); ObservedValueTuple observation = nextObservation; int counter = 0; Double sum = 0.0; LOGGER.debug("Compressionlevel none"); for (int i = 0; i < timeArray.length; i++) { prevObservation = observation; observation = nextObservation; if (i + 1 < timeArray.length) { nextObservation = collection.getTuple(new OXFFeature(timeseries.getFeatureId(), null), timeArray[i + 1]); } counter++; Double resultVal = getValidData(observation.getValue(0).toString()); if (seriesType.equals("1")) { } else if (seriesType.equals("2")) { if (resultVal != null) { resultVal += sum; } else { resultVal = sum; } } else { } sum = resultVal; ITimePosition timePos = (ITimePosition) observation.getTime(); DateTime time = DateTime.parse(timePos.toISO8601Format()); timeSeries.add(new FixedMillisecond(time.getMillis()), resultVal); } LOGGER.debug("Compressed observations from " + timeArray.length + " to " + counter); return timeSeries; } TimeseriesFactory(ObservationSeriesCollection collection); TimeSeries createTimeSeries(SosTimeseries timeseries, String seriesType); TimeSeries compressToTimeSeries(SosTimeseries timeseries, boolean force, String seriesType); HashMap<Long, Double> compressToHashMap(String foiID, String phenID, String procID); }
TimeseriesFactory { public TimeSeries createTimeSeries(SosTimeseries timeseries, String seriesType) { TimeSeries timeSeries = new TimeSeries(timeseries.getTimeseriesId()); ITimePosition timeArray[] = collection.getSortedTimeArray(); ObservedValueTuple prevObservation; ObservedValueTuple nextObservation = collection.getTuple(new OXFFeature(timeseries.getFeatureId(), null), timeArray[0]); ObservedValueTuple observation = nextObservation; int counter = 0; Double sum = 0.0; LOGGER.debug("Compressionlevel none"); for (int i = 0; i < timeArray.length; i++) { prevObservation = observation; observation = nextObservation; if (i + 1 < timeArray.length) { nextObservation = collection.getTuple(new OXFFeature(timeseries.getFeatureId(), null), timeArray[i + 1]); } counter++; Double resultVal = getValidData(observation.getValue(0).toString()); if (seriesType.equals("1")) { } else if (seriesType.equals("2")) { if (resultVal != null) { resultVal += sum; } else { resultVal = sum; } } else { } sum = resultVal; ITimePosition timePos = (ITimePosition) observation.getTime(); DateTime time = DateTime.parse(timePos.toISO8601Format()); timeSeries.add(new FixedMillisecond(time.getMillis()), resultVal); } LOGGER.debug("Compressed observations from " + timeArray.length + " to " + counter); return timeSeries; } TimeseriesFactory(ObservationSeriesCollection collection); TimeSeries createTimeSeries(SosTimeseries timeseries, String seriesType); TimeSeries compressToTimeSeries(SosTimeseries timeseries, boolean force, String seriesType); HashMap<Long, Double> compressToHashMap(String foiID, String phenID, String procID); }
@Test public void shouldCreateTimeseries() throws Exception { long begin = DateTime.parse("2007-10-27T10:00:00.000+02:00").getMillis(); long end = DateTime.parse("2007-10-28T09:00:00.000+01:00").getMillis(); TimeseriesDataGenerator generator = new TimeseriesDataGeneratorSeam(); SosTimeseries timeseries = createSosTimeseries(); DesignOptions options = new DesignOptions(createTimeseriesProperties(timeseries), begin, end, true); TimeSeriesDataResponse response = (TimeSeriesDataResponse) generator.producePresentation(options); HashMap<String, HashMap<Long, Double>> data = response.getPayloadData(); HashMap<Long, Double> timeseriesData = data.get(timeseries.getTimeseriesId()); assertThat(timeseriesData.size(), is(277)); }
@Override public RepresentationResponse producePresentation(DesignOptions options) throws GeneratorException { LOGGER.debug("Starting producing representation with " + options); Map<String, OXFFeatureCollection> entireCollMap = new HashMap<String, OXFFeatureCollection>(); try { entireCollMap = getFeatureCollectionFor(options, false); } catch (AccessException e) { throw new GeneratorException("Error creating TimeSeriesDataResponse.", e); } Collection<OXFFeatureCollection> observationCollList = entireCollMap.values(); HashMap<String, HashMap<Long, Double>> allTimeSeries = new HashMap<String, HashMap<Long, Double>>(); for (OXFFeatureCollection coll : observationCollList) { List<String> foiList = new ArrayList<String>(); List<OXFPhenomenonPropertyType> phenomenonList = new ArrayList<OXFPhenomenonPropertyType>(); HashMap<String, List<String>> procMap = new HashMap<String, List<String>>(); for (OXFFeature observation : coll) { String foi = ((OXFFeature) observation.getAttribute(FEATURE_OF_INTEREST)).toString(); if (!foiList.contains(foi)) { foiList.add(foi); } String proc = (String) observation.getAttribute(PROCEDURE); if (procMap.containsKey(foi) == false) { procMap.put(foi, new ArrayList<String>()); } if (!procMap.get(foi).contains(proc)) { procMap.get(foi).add(proc); } OXFPhenomenonPropertyType obsProp = (OXFPhenomenonPropertyType) observation.getAttribute(OBSERVED_PROPERTY); if (!phenomenonList.contains(obsProp)) { phenomenonList.add(obsProp); } } for (String foi : foiList) { for (String procedure : procMap.get(foi)) { for (OXFPhenomenonPropertyType obsProp : phenomenonList) { ObservationSeriesCollection txCollection = new ObservationSeriesCollection(coll, new String[] { foi }, new String[] { obsProp.getURN() }, false); TimeseriesProperties selectedProperties = null; for (TimeseriesProperties property : options.getProperties()) { if (LOGGER.isDebugEnabled()) { LOGGER.debug(property.getOffFoiProcPhenCombination()); } if (property.getFeature().equals(foi) && property.getPhenomenon().equals(obsProp.getURN()) && property.getProcedure().equals(procedure)) { selectedProperties = property; String phenomenonId = selectedProperties.getPhenomenon(); try { TimeseriesFactory factory = new TimeseriesFactory(txCollection); HashMap<Long, Double> data = factory.compressToHashMap(foi, phenomenonId, procedure); allTimeSeries.put(selectedProperties.getTimeseriesId(), data); } catch (ParseException e) { throw new GeneratorException("Could not parse data.", e); } break; } else { if (LOGGER.isDebugEnabled()) { StringBuilder sb = new StringBuilder(); sb.append("Ignore unknown property constellation: ["); sb.append("foiId: ").append(foi); sb.append(", phenId: ").append(obsProp.getURN()); sb.append(", procId: ").append(procedure); sb.append(" ]. Expected timeseries properties: ["); sb.append("foiId: ").append(property.getFeature()); sb.append(", phenId: ").append(property.getPhenomenon()); sb.append(", procId: ").append(property.getProcedure()); sb.append(" ]"); LOGGER.debug(sb.toString()); } } } } } } } for (TimeseriesProperties prop : options.getProperties()) { if (!allTimeSeries.containsKey(prop.getTimeseriesId())) { allTimeSeries.put(prop.getTimeseriesId(), new HashMap<Long, Double>()); } } return new TimeSeriesDataResponse(allTimeSeries); }
TimeseriesDataGenerator extends Generator { @Override public RepresentationResponse producePresentation(DesignOptions options) throws GeneratorException { LOGGER.debug("Starting producing representation with " + options); Map<String, OXFFeatureCollection> entireCollMap = new HashMap<String, OXFFeatureCollection>(); try { entireCollMap = getFeatureCollectionFor(options, false); } catch (AccessException e) { throw new GeneratorException("Error creating TimeSeriesDataResponse.", e); } Collection<OXFFeatureCollection> observationCollList = entireCollMap.values(); HashMap<String, HashMap<Long, Double>> allTimeSeries = new HashMap<String, HashMap<Long, Double>>(); for (OXFFeatureCollection coll : observationCollList) { List<String> foiList = new ArrayList<String>(); List<OXFPhenomenonPropertyType> phenomenonList = new ArrayList<OXFPhenomenonPropertyType>(); HashMap<String, List<String>> procMap = new HashMap<String, List<String>>(); for (OXFFeature observation : coll) { String foi = ((OXFFeature) observation.getAttribute(FEATURE_OF_INTEREST)).toString(); if (!foiList.contains(foi)) { foiList.add(foi); } String proc = (String) observation.getAttribute(PROCEDURE); if (procMap.containsKey(foi) == false) { procMap.put(foi, new ArrayList<String>()); } if (!procMap.get(foi).contains(proc)) { procMap.get(foi).add(proc); } OXFPhenomenonPropertyType obsProp = (OXFPhenomenonPropertyType) observation.getAttribute(OBSERVED_PROPERTY); if (!phenomenonList.contains(obsProp)) { phenomenonList.add(obsProp); } } for (String foi : foiList) { for (String procedure : procMap.get(foi)) { for (OXFPhenomenonPropertyType obsProp : phenomenonList) { ObservationSeriesCollection txCollection = new ObservationSeriesCollection(coll, new String[] { foi }, new String[] { obsProp.getURN() }, false); TimeseriesProperties selectedProperties = null; for (TimeseriesProperties property : options.getProperties()) { if (LOGGER.isDebugEnabled()) { LOGGER.debug(property.getOffFoiProcPhenCombination()); } if (property.getFeature().equals(foi) && property.getPhenomenon().equals(obsProp.getURN()) && property.getProcedure().equals(procedure)) { selectedProperties = property; String phenomenonId = selectedProperties.getPhenomenon(); try { TimeseriesFactory factory = new TimeseriesFactory(txCollection); HashMap<Long, Double> data = factory.compressToHashMap(foi, phenomenonId, procedure); allTimeSeries.put(selectedProperties.getTimeseriesId(), data); } catch (ParseException e) { throw new GeneratorException("Could not parse data.", e); } break; } else { if (LOGGER.isDebugEnabled()) { StringBuilder sb = new StringBuilder(); sb.append("Ignore unknown property constellation: ["); sb.append("foiId: ").append(foi); sb.append(", phenId: ").append(obsProp.getURN()); sb.append(", procId: ").append(procedure); sb.append(" ]. Expected timeseries properties: ["); sb.append("foiId: ").append(property.getFeature()); sb.append(", phenId: ").append(property.getPhenomenon()); sb.append(", procId: ").append(property.getProcedure()); sb.append(" ]"); LOGGER.debug(sb.toString()); } } } } } } } for (TimeseriesProperties prop : options.getProperties()) { if (!allTimeSeries.containsKey(prop.getTimeseriesId())) { allTimeSeries.put(prop.getTimeseriesId(), new HashMap<Long, Double>()); } } return new TimeSeriesDataResponse(allTimeSeries); } }
TimeseriesDataGenerator extends Generator { @Override public RepresentationResponse producePresentation(DesignOptions options) throws GeneratorException { LOGGER.debug("Starting producing representation with " + options); Map<String, OXFFeatureCollection> entireCollMap = new HashMap<String, OXFFeatureCollection>(); try { entireCollMap = getFeatureCollectionFor(options, false); } catch (AccessException e) { throw new GeneratorException("Error creating TimeSeriesDataResponse.", e); } Collection<OXFFeatureCollection> observationCollList = entireCollMap.values(); HashMap<String, HashMap<Long, Double>> allTimeSeries = new HashMap<String, HashMap<Long, Double>>(); for (OXFFeatureCollection coll : observationCollList) { List<String> foiList = new ArrayList<String>(); List<OXFPhenomenonPropertyType> phenomenonList = new ArrayList<OXFPhenomenonPropertyType>(); HashMap<String, List<String>> procMap = new HashMap<String, List<String>>(); for (OXFFeature observation : coll) { String foi = ((OXFFeature) observation.getAttribute(FEATURE_OF_INTEREST)).toString(); if (!foiList.contains(foi)) { foiList.add(foi); } String proc = (String) observation.getAttribute(PROCEDURE); if (procMap.containsKey(foi) == false) { procMap.put(foi, new ArrayList<String>()); } if (!procMap.get(foi).contains(proc)) { procMap.get(foi).add(proc); } OXFPhenomenonPropertyType obsProp = (OXFPhenomenonPropertyType) observation.getAttribute(OBSERVED_PROPERTY); if (!phenomenonList.contains(obsProp)) { phenomenonList.add(obsProp); } } for (String foi : foiList) { for (String procedure : procMap.get(foi)) { for (OXFPhenomenonPropertyType obsProp : phenomenonList) { ObservationSeriesCollection txCollection = new ObservationSeriesCollection(coll, new String[] { foi }, new String[] { obsProp.getURN() }, false); TimeseriesProperties selectedProperties = null; for (TimeseriesProperties property : options.getProperties()) { if (LOGGER.isDebugEnabled()) { LOGGER.debug(property.getOffFoiProcPhenCombination()); } if (property.getFeature().equals(foi) && property.getPhenomenon().equals(obsProp.getURN()) && property.getProcedure().equals(procedure)) { selectedProperties = property; String phenomenonId = selectedProperties.getPhenomenon(); try { TimeseriesFactory factory = new TimeseriesFactory(txCollection); HashMap<Long, Double> data = factory.compressToHashMap(foi, phenomenonId, procedure); allTimeSeries.put(selectedProperties.getTimeseriesId(), data); } catch (ParseException e) { throw new GeneratorException("Could not parse data.", e); } break; } else { if (LOGGER.isDebugEnabled()) { StringBuilder sb = new StringBuilder(); sb.append("Ignore unknown property constellation: ["); sb.append("foiId: ").append(foi); sb.append(", phenId: ").append(obsProp.getURN()); sb.append(", procId: ").append(procedure); sb.append(" ]. Expected timeseries properties: ["); sb.append("foiId: ").append(property.getFeature()); sb.append(", phenId: ").append(property.getPhenomenon()); sb.append(", procId: ").append(property.getProcedure()); sb.append(" ]"); LOGGER.debug(sb.toString()); } } } } } } } for (TimeseriesProperties prop : options.getProperties()) { if (!allTimeSeries.containsKey(prop.getTimeseriesId())) { allTimeSeries.put(prop.getTimeseriesId(), new HashMap<Long, Double>()); } } return new TimeSeriesDataResponse(allTimeSeries); } }
TimeseriesDataGenerator extends Generator { @Override public RepresentationResponse producePresentation(DesignOptions options) throws GeneratorException { LOGGER.debug("Starting producing representation with " + options); Map<String, OXFFeatureCollection> entireCollMap = new HashMap<String, OXFFeatureCollection>(); try { entireCollMap = getFeatureCollectionFor(options, false); } catch (AccessException e) { throw new GeneratorException("Error creating TimeSeriesDataResponse.", e); } Collection<OXFFeatureCollection> observationCollList = entireCollMap.values(); HashMap<String, HashMap<Long, Double>> allTimeSeries = new HashMap<String, HashMap<Long, Double>>(); for (OXFFeatureCollection coll : observationCollList) { List<String> foiList = new ArrayList<String>(); List<OXFPhenomenonPropertyType> phenomenonList = new ArrayList<OXFPhenomenonPropertyType>(); HashMap<String, List<String>> procMap = new HashMap<String, List<String>>(); for (OXFFeature observation : coll) { String foi = ((OXFFeature) observation.getAttribute(FEATURE_OF_INTEREST)).toString(); if (!foiList.contains(foi)) { foiList.add(foi); } String proc = (String) observation.getAttribute(PROCEDURE); if (procMap.containsKey(foi) == false) { procMap.put(foi, new ArrayList<String>()); } if (!procMap.get(foi).contains(proc)) { procMap.get(foi).add(proc); } OXFPhenomenonPropertyType obsProp = (OXFPhenomenonPropertyType) observation.getAttribute(OBSERVED_PROPERTY); if (!phenomenonList.contains(obsProp)) { phenomenonList.add(obsProp); } } for (String foi : foiList) { for (String procedure : procMap.get(foi)) { for (OXFPhenomenonPropertyType obsProp : phenomenonList) { ObservationSeriesCollection txCollection = new ObservationSeriesCollection(coll, new String[] { foi }, new String[] { obsProp.getURN() }, false); TimeseriesProperties selectedProperties = null; for (TimeseriesProperties property : options.getProperties()) { if (LOGGER.isDebugEnabled()) { LOGGER.debug(property.getOffFoiProcPhenCombination()); } if (property.getFeature().equals(foi) && property.getPhenomenon().equals(obsProp.getURN()) && property.getProcedure().equals(procedure)) { selectedProperties = property; String phenomenonId = selectedProperties.getPhenomenon(); try { TimeseriesFactory factory = new TimeseriesFactory(txCollection); HashMap<Long, Double> data = factory.compressToHashMap(foi, phenomenonId, procedure); allTimeSeries.put(selectedProperties.getTimeseriesId(), data); } catch (ParseException e) { throw new GeneratorException("Could not parse data.", e); } break; } else { if (LOGGER.isDebugEnabled()) { StringBuilder sb = new StringBuilder(); sb.append("Ignore unknown property constellation: ["); sb.append("foiId: ").append(foi); sb.append(", phenId: ").append(obsProp.getURN()); sb.append(", procId: ").append(procedure); sb.append(" ]. Expected timeseries properties: ["); sb.append("foiId: ").append(property.getFeature()); sb.append(", phenId: ").append(property.getPhenomenon()); sb.append(", procId: ").append(property.getProcedure()); sb.append(" ]"); LOGGER.debug(sb.toString()); } } } } } } } for (TimeseriesProperties prop : options.getProperties()) { if (!allTimeSeries.containsKey(prop.getTimeseriesId())) { allTimeSeries.put(prop.getTimeseriesId(), new HashMap<Long, Double>()); } } return new TimeSeriesDataResponse(allTimeSeries); } @Override RepresentationResponse producePresentation(DesignOptions options); }
TimeseriesDataGenerator extends Generator { @Override public RepresentationResponse producePresentation(DesignOptions options) throws GeneratorException { LOGGER.debug("Starting producing representation with " + options); Map<String, OXFFeatureCollection> entireCollMap = new HashMap<String, OXFFeatureCollection>(); try { entireCollMap = getFeatureCollectionFor(options, false); } catch (AccessException e) { throw new GeneratorException("Error creating TimeSeriesDataResponse.", e); } Collection<OXFFeatureCollection> observationCollList = entireCollMap.values(); HashMap<String, HashMap<Long, Double>> allTimeSeries = new HashMap<String, HashMap<Long, Double>>(); for (OXFFeatureCollection coll : observationCollList) { List<String> foiList = new ArrayList<String>(); List<OXFPhenomenonPropertyType> phenomenonList = new ArrayList<OXFPhenomenonPropertyType>(); HashMap<String, List<String>> procMap = new HashMap<String, List<String>>(); for (OXFFeature observation : coll) { String foi = ((OXFFeature) observation.getAttribute(FEATURE_OF_INTEREST)).toString(); if (!foiList.contains(foi)) { foiList.add(foi); } String proc = (String) observation.getAttribute(PROCEDURE); if (procMap.containsKey(foi) == false) { procMap.put(foi, new ArrayList<String>()); } if (!procMap.get(foi).contains(proc)) { procMap.get(foi).add(proc); } OXFPhenomenonPropertyType obsProp = (OXFPhenomenonPropertyType) observation.getAttribute(OBSERVED_PROPERTY); if (!phenomenonList.contains(obsProp)) { phenomenonList.add(obsProp); } } for (String foi : foiList) { for (String procedure : procMap.get(foi)) { for (OXFPhenomenonPropertyType obsProp : phenomenonList) { ObservationSeriesCollection txCollection = new ObservationSeriesCollection(coll, new String[] { foi }, new String[] { obsProp.getURN() }, false); TimeseriesProperties selectedProperties = null; for (TimeseriesProperties property : options.getProperties()) { if (LOGGER.isDebugEnabled()) { LOGGER.debug(property.getOffFoiProcPhenCombination()); } if (property.getFeature().equals(foi) && property.getPhenomenon().equals(obsProp.getURN()) && property.getProcedure().equals(procedure)) { selectedProperties = property; String phenomenonId = selectedProperties.getPhenomenon(); try { TimeseriesFactory factory = new TimeseriesFactory(txCollection); HashMap<Long, Double> data = factory.compressToHashMap(foi, phenomenonId, procedure); allTimeSeries.put(selectedProperties.getTimeseriesId(), data); } catch (ParseException e) { throw new GeneratorException("Could not parse data.", e); } break; } else { if (LOGGER.isDebugEnabled()) { StringBuilder sb = new StringBuilder(); sb.append("Ignore unknown property constellation: ["); sb.append("foiId: ").append(foi); sb.append(", phenId: ").append(obsProp.getURN()); sb.append(", procId: ").append(procedure); sb.append(" ]. Expected timeseries properties: ["); sb.append("foiId: ").append(property.getFeature()); sb.append(", phenId: ").append(property.getPhenomenon()); sb.append(", procId: ").append(property.getProcedure()); sb.append(" ]"); LOGGER.debug(sb.toString()); } } } } } } } for (TimeseriesProperties prop : options.getProperties()) { if (!allTimeSeries.containsKey(prop.getTimeseriesId())) { allTimeSeries.put(prop.getTimeseriesId(), new HashMap<Long, Double>()); } } return new TimeSeriesDataResponse(allTimeSeries); } @Override RepresentationResponse producePresentation(DesignOptions options); }
@Test public void testCreatePostfix() { String postfix = SosMetadataUpdate.createPostfix(validServiceUrl); assertEquals("my.server.net_52n-SOS-Vx.x_sos", postfix); }
protected static String createPostfix(String url) { if (url.startsWith("http: url = url.substring("http: } return url.replaceAll("/", "_").replaceAll("\\?", "_").replaceAll(":", "_").replaceAll("@", "_"); }
SosMetadataUpdate { protected static String createPostfix(String url) { if (url.startsWith("http: url = url.substring("http: } return url.replaceAll("/", "_").replaceAll("\\?", "_").replaceAll(":", "_").replaceAll("@", "_"); } }
SosMetadataUpdate { protected static String createPostfix(String url) { if (url.startsWith("http: url = url.substring("http: } return url.replaceAll("/", "_").replaceAll("\\?", "_").replaceAll(":", "_").replaceAll("@", "_"); } }
SosMetadataUpdate { protected static String createPostfix(String url) { if (url.startsWith("http: url = url.substring("http: } return url.replaceAll("/", "_").replaceAll("\\?", "_").replaceAll(":", "_").replaceAll("@", "_"); } static void updateSosServices(Iterable<String> sosServices); static void updateService(String serviceUrl); static void invalidateCache(); }
SosMetadataUpdate { protected static String createPostfix(String url) { if (url.startsWith("http: url = url.substring("http: } return url.replaceAll("/", "_").replaceAll("\\?", "_").replaceAll(":", "_").replaceAll("@", "_"); } static void updateSosServices(Iterable<String> sosServices); static void updateService(String serviceUrl); static void invalidateCache(); }
@Test public void testGetCacheTarget() { File expected = new File(cacheTargetFile); File cacheTarget = SosMetadataUpdate.getCacheTarget(validServiceUrl); assertEquals(expected.getAbsoluteFile(), cacheTarget.getAbsoluteFile()); }
protected static File getCacheTarget(String serviceUrl) { String postfix = createPostfix(serviceUrl); return new File(generateCacheFilePath(postfix)); }
SosMetadataUpdate { protected static File getCacheTarget(String serviceUrl) { String postfix = createPostfix(serviceUrl); return new File(generateCacheFilePath(postfix)); } }
SosMetadataUpdate { protected static File getCacheTarget(String serviceUrl) { String postfix = createPostfix(serviceUrl); return new File(generateCacheFilePath(postfix)); } }
SosMetadataUpdate { protected static File getCacheTarget(String serviceUrl) { String postfix = createPostfix(serviceUrl); return new File(generateCacheFilePath(postfix)); } static void updateSosServices(Iterable<String> sosServices); static void updateService(String serviceUrl); static void invalidateCache(); }
SosMetadataUpdate { protected static File getCacheTarget(String serviceUrl) { String postfix = createPostfix(serviceUrl); return new File(generateCacheFilePath(postfix)); } static void updateSosServices(Iterable<String> sosServices); static void updateService(String serviceUrl); static void invalidateCache(); }
@Test public void testPrepareCacheTarget() throws IOException { SosMetadataUpdate.prepareCacheTargetDirectory(); assertTrue(temporalCacheDirectory.exists()); }
protected static void prepareCacheTargetDirectory() throws IOException { File cacheDirectory = getCacheDir(); if (!cacheDirectory.exists() && !cacheDirectory.mkdirs()) { throw new IOException("Unable to create cache directory."); } }
SosMetadataUpdate { protected static void prepareCacheTargetDirectory() throws IOException { File cacheDirectory = getCacheDir(); if (!cacheDirectory.exists() && !cacheDirectory.mkdirs()) { throw new IOException("Unable to create cache directory."); } } }
SosMetadataUpdate { protected static void prepareCacheTargetDirectory() throws IOException { File cacheDirectory = getCacheDir(); if (!cacheDirectory.exists() && !cacheDirectory.mkdirs()) { throw new IOException("Unable to create cache directory."); } } }
SosMetadataUpdate { protected static void prepareCacheTargetDirectory() throws IOException { File cacheDirectory = getCacheDir(); if (!cacheDirectory.exists() && !cacheDirectory.mkdirs()) { throw new IOException("Unable to create cache directory."); } } static void updateSosServices(Iterable<String> sosServices); static void updateService(String serviceUrl); static void invalidateCache(); }
SosMetadataUpdate { protected static void prepareCacheTargetDirectory() throws IOException { File cacheDirectory = getCacheDir(); if (!cacheDirectory.exists() && !cacheDirectory.mkdirs()) { throw new IOException("Unable to create cache directory."); } } static void updateSosServices(Iterable<String> sosServices); static void updateService(String serviceUrl); static void invalidateCache(); }
@Test public void havingRule_parseEmlFromBasicRule_noXmlErrors() throws Exception { String eml = builder.create(rule).getEml(); assertThat(XMLBeansParser.validate(XmlObject.Factory.parse(eml)), is(empty())); }
public BasicRule create(Rule rule) { String title = rule.getTitle(); this.overshootPatternId = title + this.overshootStream; this.undershootPatternId = title + this.undershootStream; this.entryNotificationPatternId = title + this.overshootNotificationStream; this.exitNotificationPatternId = title + this.undershootNotificationStream; this.overshootEventName = title + this.overshoot; this.undershootEventName = title + this.undershoot; this.entryEventName = title + this.overshootNotification; this.exitEventName = title + this.undershootNotification; this.output_enter = title + this.enter; this.output_exit = title + this.exit; try { EMLDocument emlTemplateDoc = getEmlTemplate(); SimplePatterns simplePatterns = emlTemplateDoc.getEML().getSimplePatterns(); ComplexPatterns complexPatterns = emlTemplateDoc.getEML().getComplexPatterns(); SimplePatternType staticInitPattern = simplePatterns.getSimplePatternArray(INDEX_SIMPLE_PATTERN_INTIAL_COUNT); processPropertyRestrictions(staticInitPattern, rule.getTimeseriesMetadata()); RuleFilter entryFilter = createEntryFilter(rule); SimplePatternType ruleUndershoot = simplePatterns.getSimplePatternArray(INDEX_ENTRY_CONDITION_PATTERN); processSimplePattern(ruleUndershoot, overshootPatternId, overshootEventName); processPropertyRestrictions(ruleUndershoot, rule.getTimeseriesMetadata()); processFilterGuard(ruleUndershoot.getGuard(), entryFilter, INPUT_STREAM_NAME); RuleFilter exitFilter = createExitFilter(rule); SimplePatternType ruleOvershoot = simplePatterns.getSimplePatternArray(INDEX_EXIT_CONDITION_PATTERN); processSimplePattern(ruleOvershoot, undershootPatternId, undershootEventName); processPropertyRestrictions(ruleOvershoot, rule.getTimeseriesMetadata()); processFilterGuard(ruleOvershoot.getGuard(), exitFilter, INPUT_STREAM_NAME); ComplexPattern entryClause = complexPatterns.getComplexPatternArray(INDEX_ENTRY_NOTIFICATION_PATTERN); processComplexPattern(entryClause, entryNotificationPatternId, entryEventName, output_enter); entryClause.getFirstPattern().setPatternReference(undershootPatternId); entryClause.getSecondPattern().setPatternReference(overshootPatternId); ComplexPattern exitClause = complexPatterns.getComplexPatternArray(INDEX_EXIT_NOTIFICATION_PATTERN); processComplexPattern(exitClause, exitNotificationPatternId, exitEventName, output_exit); exitClause.getFirstPattern().setPatternReference(overshootPatternId); exitClause.getSecondPattern().setPatternReference(undershootPatternId); ComplexPattern initialEntryClause = complexPatterns.getComplexPatternArray(INDEX_COMPLEX_PATTERN_INTIAL_ENTRY); processFilterGuard(initialEntryClause.getGuard(), entryFilter, INITIAL_STREAM_NAME); eml = emlTemplateDoc.xmlText(); finalEml = eml; } catch (Exception e) { LOGGER.error("Error creating rule", e); return null; } User user = getUserFrom(rule); BasicRule basicRule = new BasicRule(rule.getTitle(), "B", "BR4", rule.getDescription(), rule.isPublish(), user.getId(), finalEml, false); basicRule.setUuid(rule.getUuid()); return basicRule; }
BasicRule_4_Builder extends BasicRuleBuilder { public BasicRule create(Rule rule) { String title = rule.getTitle(); this.overshootPatternId = title + this.overshootStream; this.undershootPatternId = title + this.undershootStream; this.entryNotificationPatternId = title + this.overshootNotificationStream; this.exitNotificationPatternId = title + this.undershootNotificationStream; this.overshootEventName = title + this.overshoot; this.undershootEventName = title + this.undershoot; this.entryEventName = title + this.overshootNotification; this.exitEventName = title + this.undershootNotification; this.output_enter = title + this.enter; this.output_exit = title + this.exit; try { EMLDocument emlTemplateDoc = getEmlTemplate(); SimplePatterns simplePatterns = emlTemplateDoc.getEML().getSimplePatterns(); ComplexPatterns complexPatterns = emlTemplateDoc.getEML().getComplexPatterns(); SimplePatternType staticInitPattern = simplePatterns.getSimplePatternArray(INDEX_SIMPLE_PATTERN_INTIAL_COUNT); processPropertyRestrictions(staticInitPattern, rule.getTimeseriesMetadata()); RuleFilter entryFilter = createEntryFilter(rule); SimplePatternType ruleUndershoot = simplePatterns.getSimplePatternArray(INDEX_ENTRY_CONDITION_PATTERN); processSimplePattern(ruleUndershoot, overshootPatternId, overshootEventName); processPropertyRestrictions(ruleUndershoot, rule.getTimeseriesMetadata()); processFilterGuard(ruleUndershoot.getGuard(), entryFilter, INPUT_STREAM_NAME); RuleFilter exitFilter = createExitFilter(rule); SimplePatternType ruleOvershoot = simplePatterns.getSimplePatternArray(INDEX_EXIT_CONDITION_PATTERN); processSimplePattern(ruleOvershoot, undershootPatternId, undershootEventName); processPropertyRestrictions(ruleOvershoot, rule.getTimeseriesMetadata()); processFilterGuard(ruleOvershoot.getGuard(), exitFilter, INPUT_STREAM_NAME); ComplexPattern entryClause = complexPatterns.getComplexPatternArray(INDEX_ENTRY_NOTIFICATION_PATTERN); processComplexPattern(entryClause, entryNotificationPatternId, entryEventName, output_enter); entryClause.getFirstPattern().setPatternReference(undershootPatternId); entryClause.getSecondPattern().setPatternReference(overshootPatternId); ComplexPattern exitClause = complexPatterns.getComplexPatternArray(INDEX_EXIT_NOTIFICATION_PATTERN); processComplexPattern(exitClause, exitNotificationPatternId, exitEventName, output_exit); exitClause.getFirstPattern().setPatternReference(overshootPatternId); exitClause.getSecondPattern().setPatternReference(undershootPatternId); ComplexPattern initialEntryClause = complexPatterns.getComplexPatternArray(INDEX_COMPLEX_PATTERN_INTIAL_ENTRY); processFilterGuard(initialEntryClause.getGuard(), entryFilter, INITIAL_STREAM_NAME); eml = emlTemplateDoc.xmlText(); finalEml = eml; } catch (Exception e) { LOGGER.error("Error creating rule", e); return null; } User user = getUserFrom(rule); BasicRule basicRule = new BasicRule(rule.getTitle(), "B", "BR4", rule.getDescription(), rule.isPublish(), user.getId(), finalEml, false); basicRule.setUuid(rule.getUuid()); return basicRule; } }
BasicRule_4_Builder extends BasicRuleBuilder { public BasicRule create(Rule rule) { String title = rule.getTitle(); this.overshootPatternId = title + this.overshootStream; this.undershootPatternId = title + this.undershootStream; this.entryNotificationPatternId = title + this.overshootNotificationStream; this.exitNotificationPatternId = title + this.undershootNotificationStream; this.overshootEventName = title + this.overshoot; this.undershootEventName = title + this.undershoot; this.entryEventName = title + this.overshootNotification; this.exitEventName = title + this.undershootNotification; this.output_enter = title + this.enter; this.output_exit = title + this.exit; try { EMLDocument emlTemplateDoc = getEmlTemplate(); SimplePatterns simplePatterns = emlTemplateDoc.getEML().getSimplePatterns(); ComplexPatterns complexPatterns = emlTemplateDoc.getEML().getComplexPatterns(); SimplePatternType staticInitPattern = simplePatterns.getSimplePatternArray(INDEX_SIMPLE_PATTERN_INTIAL_COUNT); processPropertyRestrictions(staticInitPattern, rule.getTimeseriesMetadata()); RuleFilter entryFilter = createEntryFilter(rule); SimplePatternType ruleUndershoot = simplePatterns.getSimplePatternArray(INDEX_ENTRY_CONDITION_PATTERN); processSimplePattern(ruleUndershoot, overshootPatternId, overshootEventName); processPropertyRestrictions(ruleUndershoot, rule.getTimeseriesMetadata()); processFilterGuard(ruleUndershoot.getGuard(), entryFilter, INPUT_STREAM_NAME); RuleFilter exitFilter = createExitFilter(rule); SimplePatternType ruleOvershoot = simplePatterns.getSimplePatternArray(INDEX_EXIT_CONDITION_PATTERN); processSimplePattern(ruleOvershoot, undershootPatternId, undershootEventName); processPropertyRestrictions(ruleOvershoot, rule.getTimeseriesMetadata()); processFilterGuard(ruleOvershoot.getGuard(), exitFilter, INPUT_STREAM_NAME); ComplexPattern entryClause = complexPatterns.getComplexPatternArray(INDEX_ENTRY_NOTIFICATION_PATTERN); processComplexPattern(entryClause, entryNotificationPatternId, entryEventName, output_enter); entryClause.getFirstPattern().setPatternReference(undershootPatternId); entryClause.getSecondPattern().setPatternReference(overshootPatternId); ComplexPattern exitClause = complexPatterns.getComplexPatternArray(INDEX_EXIT_NOTIFICATION_PATTERN); processComplexPattern(exitClause, exitNotificationPatternId, exitEventName, output_exit); exitClause.getFirstPattern().setPatternReference(overshootPatternId); exitClause.getSecondPattern().setPatternReference(undershootPatternId); ComplexPattern initialEntryClause = complexPatterns.getComplexPatternArray(INDEX_COMPLEX_PATTERN_INTIAL_ENTRY); processFilterGuard(initialEntryClause.getGuard(), entryFilter, INITIAL_STREAM_NAME); eml = emlTemplateDoc.xmlText(); finalEml = eml; } catch (Exception e) { LOGGER.error("Error creating rule", e); return null; } User user = getUserFrom(rule); BasicRule basicRule = new BasicRule(rule.getTitle(), "B", "BR4", rule.getDescription(), rule.isPublish(), user.getId(), finalEml, false); basicRule.setUuid(rule.getUuid()); return basicRule; } BasicRule_4_Builder(); }
BasicRule_4_Builder extends BasicRuleBuilder { public BasicRule create(Rule rule) { String title = rule.getTitle(); this.overshootPatternId = title + this.overshootStream; this.undershootPatternId = title + this.undershootStream; this.entryNotificationPatternId = title + this.overshootNotificationStream; this.exitNotificationPatternId = title + this.undershootNotificationStream; this.overshootEventName = title + this.overshoot; this.undershootEventName = title + this.undershoot; this.entryEventName = title + this.overshootNotification; this.exitEventName = title + this.undershootNotification; this.output_enter = title + this.enter; this.output_exit = title + this.exit; try { EMLDocument emlTemplateDoc = getEmlTemplate(); SimplePatterns simplePatterns = emlTemplateDoc.getEML().getSimplePatterns(); ComplexPatterns complexPatterns = emlTemplateDoc.getEML().getComplexPatterns(); SimplePatternType staticInitPattern = simplePatterns.getSimplePatternArray(INDEX_SIMPLE_PATTERN_INTIAL_COUNT); processPropertyRestrictions(staticInitPattern, rule.getTimeseriesMetadata()); RuleFilter entryFilter = createEntryFilter(rule); SimplePatternType ruleUndershoot = simplePatterns.getSimplePatternArray(INDEX_ENTRY_CONDITION_PATTERN); processSimplePattern(ruleUndershoot, overshootPatternId, overshootEventName); processPropertyRestrictions(ruleUndershoot, rule.getTimeseriesMetadata()); processFilterGuard(ruleUndershoot.getGuard(), entryFilter, INPUT_STREAM_NAME); RuleFilter exitFilter = createExitFilter(rule); SimplePatternType ruleOvershoot = simplePatterns.getSimplePatternArray(INDEX_EXIT_CONDITION_PATTERN); processSimplePattern(ruleOvershoot, undershootPatternId, undershootEventName); processPropertyRestrictions(ruleOvershoot, rule.getTimeseriesMetadata()); processFilterGuard(ruleOvershoot.getGuard(), exitFilter, INPUT_STREAM_NAME); ComplexPattern entryClause = complexPatterns.getComplexPatternArray(INDEX_ENTRY_NOTIFICATION_PATTERN); processComplexPattern(entryClause, entryNotificationPatternId, entryEventName, output_enter); entryClause.getFirstPattern().setPatternReference(undershootPatternId); entryClause.getSecondPattern().setPatternReference(overshootPatternId); ComplexPattern exitClause = complexPatterns.getComplexPatternArray(INDEX_EXIT_NOTIFICATION_PATTERN); processComplexPattern(exitClause, exitNotificationPatternId, exitEventName, output_exit); exitClause.getFirstPattern().setPatternReference(overshootPatternId); exitClause.getSecondPattern().setPatternReference(undershootPatternId); ComplexPattern initialEntryClause = complexPatterns.getComplexPatternArray(INDEX_COMPLEX_PATTERN_INTIAL_ENTRY); processFilterGuard(initialEntryClause.getGuard(), entryFilter, INITIAL_STREAM_NAME); eml = emlTemplateDoc.xmlText(); finalEml = eml; } catch (Exception e) { LOGGER.error("Error creating rule", e); return null; } User user = getUserFrom(rule); BasicRule basicRule = new BasicRule(rule.getTitle(), "B", "BR4", rule.getDescription(), rule.isPublish(), user.getId(), finalEml, false); basicRule.setUuid(rule.getUuid()); return basicRule; } BasicRule_4_Builder(); BasicRule create(Rule rule); Rule getRuleByEML(BasicRule basicRule); }
BasicRule_4_Builder extends BasicRuleBuilder { public BasicRule create(Rule rule) { String title = rule.getTitle(); this.overshootPatternId = title + this.overshootStream; this.undershootPatternId = title + this.undershootStream; this.entryNotificationPatternId = title + this.overshootNotificationStream; this.exitNotificationPatternId = title + this.undershootNotificationStream; this.overshootEventName = title + this.overshoot; this.undershootEventName = title + this.undershoot; this.entryEventName = title + this.overshootNotification; this.exitEventName = title + this.undershootNotification; this.output_enter = title + this.enter; this.output_exit = title + this.exit; try { EMLDocument emlTemplateDoc = getEmlTemplate(); SimplePatterns simplePatterns = emlTemplateDoc.getEML().getSimplePatterns(); ComplexPatterns complexPatterns = emlTemplateDoc.getEML().getComplexPatterns(); SimplePatternType staticInitPattern = simplePatterns.getSimplePatternArray(INDEX_SIMPLE_PATTERN_INTIAL_COUNT); processPropertyRestrictions(staticInitPattern, rule.getTimeseriesMetadata()); RuleFilter entryFilter = createEntryFilter(rule); SimplePatternType ruleUndershoot = simplePatterns.getSimplePatternArray(INDEX_ENTRY_CONDITION_PATTERN); processSimplePattern(ruleUndershoot, overshootPatternId, overshootEventName); processPropertyRestrictions(ruleUndershoot, rule.getTimeseriesMetadata()); processFilterGuard(ruleUndershoot.getGuard(), entryFilter, INPUT_STREAM_NAME); RuleFilter exitFilter = createExitFilter(rule); SimplePatternType ruleOvershoot = simplePatterns.getSimplePatternArray(INDEX_EXIT_CONDITION_PATTERN); processSimplePattern(ruleOvershoot, undershootPatternId, undershootEventName); processPropertyRestrictions(ruleOvershoot, rule.getTimeseriesMetadata()); processFilterGuard(ruleOvershoot.getGuard(), exitFilter, INPUT_STREAM_NAME); ComplexPattern entryClause = complexPatterns.getComplexPatternArray(INDEX_ENTRY_NOTIFICATION_PATTERN); processComplexPattern(entryClause, entryNotificationPatternId, entryEventName, output_enter); entryClause.getFirstPattern().setPatternReference(undershootPatternId); entryClause.getSecondPattern().setPatternReference(overshootPatternId); ComplexPattern exitClause = complexPatterns.getComplexPatternArray(INDEX_EXIT_NOTIFICATION_PATTERN); processComplexPattern(exitClause, exitNotificationPatternId, exitEventName, output_exit); exitClause.getFirstPattern().setPatternReference(overshootPatternId); exitClause.getSecondPattern().setPatternReference(undershootPatternId); ComplexPattern initialEntryClause = complexPatterns.getComplexPatternArray(INDEX_COMPLEX_PATTERN_INTIAL_ENTRY); processFilterGuard(initialEntryClause.getGuard(), entryFilter, INITIAL_STREAM_NAME); eml = emlTemplateDoc.xmlText(); finalEml = eml; } catch (Exception e) { LOGGER.error("Error creating rule", e); return null; } User user = getUserFrom(rule); BasicRule basicRule = new BasicRule(rule.getTitle(), "B", "BR4", rule.getDescription(), rule.isPublish(), user.getId(), finalEml, false); basicRule.setUuid(rule.getUuid()); return basicRule; } BasicRule_4_Builder(); BasicRule create(Rule rule); Rule getRuleByEML(BasicRule basicRule); }
@Test public void shouldParseReferenceValuesFromCapabilitiesSection() { assertThat(parser.parseReferenceValues().size(), is(5)); }
public HashMap<String, ReferenceValue> parseReferenceValues() { final Capabilities[] capabilities = getSensorMLCapabilities(smlDoc.getSensorML()); final HashMap<String, ReferenceValue> map = new HashMap<String, ReferenceValue>(); if (capabilities == null || capabilities.length == 0) { return map; } for (final Capabilities capability : capabilities) { final AbstractDataRecordType abstractDataRecord = capability.getAbstractDataRecord(); if (abstractDataRecord instanceof SimpleDataRecordType) { final SimpleDataRecordType simpleDataRecord = (SimpleDataRecordType) abstractDataRecord; for (final AnyScalarPropertyType field : simpleDataRecord.getFieldArray()) { if (field.isSetText()) { final String fieldName = field.getName(); final Text textComponent = field.getText(); final String definition = textComponent.getDefinition(); if (isReferenceValue(definition)) { final ReferenceValue referenceValue = parseReferenceValue(textComponent, fieldName); if (referenceValue != null) { map.put(fieldName, referenceValue); } } } } } else if (abstractDataRecord instanceof DataRecordType) { final DataRecordType dataRecord = (DataRecordType) abstractDataRecord; for (final DataComponentPropertyType field : dataRecord.getFieldArray()) { if (field.isSetText()) { final String fieldName = field.getName(); final Text textComponent = field.getText(); final String definition = textComponent.getDefinition(); if (isReferenceValue(definition)) { final ReferenceValue referenceValue = parseReferenceValue(textComponent, fieldName); if (referenceValue != null) { map.put(fieldName, referenceValue); } } } } } } return map; }
DescribeSensorParser { public HashMap<String, ReferenceValue> parseReferenceValues() { final Capabilities[] capabilities = getSensorMLCapabilities(smlDoc.getSensorML()); final HashMap<String, ReferenceValue> map = new HashMap<String, ReferenceValue>(); if (capabilities == null || capabilities.length == 0) { return map; } for (final Capabilities capability : capabilities) { final AbstractDataRecordType abstractDataRecord = capability.getAbstractDataRecord(); if (abstractDataRecord instanceof SimpleDataRecordType) { final SimpleDataRecordType simpleDataRecord = (SimpleDataRecordType) abstractDataRecord; for (final AnyScalarPropertyType field : simpleDataRecord.getFieldArray()) { if (field.isSetText()) { final String fieldName = field.getName(); final Text textComponent = field.getText(); final String definition = textComponent.getDefinition(); if (isReferenceValue(definition)) { final ReferenceValue referenceValue = parseReferenceValue(textComponent, fieldName); if (referenceValue != null) { map.put(fieldName, referenceValue); } } } } } else if (abstractDataRecord instanceof DataRecordType) { final DataRecordType dataRecord = (DataRecordType) abstractDataRecord; for (final DataComponentPropertyType field : dataRecord.getFieldArray()) { if (field.isSetText()) { final String fieldName = field.getName(); final Text textComponent = field.getText(); final String definition = textComponent.getDefinition(); if (isReferenceValue(definition)) { final ReferenceValue referenceValue = parseReferenceValue(textComponent, fieldName); if (referenceValue != null) { map.put(fieldName, referenceValue); } } } } } } return map; } }
DescribeSensorParser { public HashMap<String, ReferenceValue> parseReferenceValues() { final Capabilities[] capabilities = getSensorMLCapabilities(smlDoc.getSensorML()); final HashMap<String, ReferenceValue> map = new HashMap<String, ReferenceValue>(); if (capabilities == null || capabilities.length == 0) { return map; } for (final Capabilities capability : capabilities) { final AbstractDataRecordType abstractDataRecord = capability.getAbstractDataRecord(); if (abstractDataRecord instanceof SimpleDataRecordType) { final SimpleDataRecordType simpleDataRecord = (SimpleDataRecordType) abstractDataRecord; for (final AnyScalarPropertyType field : simpleDataRecord.getFieldArray()) { if (field.isSetText()) { final String fieldName = field.getName(); final Text textComponent = field.getText(); final String definition = textComponent.getDefinition(); if (isReferenceValue(definition)) { final ReferenceValue referenceValue = parseReferenceValue(textComponent, fieldName); if (referenceValue != null) { map.put(fieldName, referenceValue); } } } } } else if (abstractDataRecord instanceof DataRecordType) { final DataRecordType dataRecord = (DataRecordType) abstractDataRecord; for (final DataComponentPropertyType field : dataRecord.getFieldArray()) { if (field.isSetText()) { final String fieldName = field.getName(); final Text textComponent = field.getText(); final String definition = textComponent.getDefinition(); if (isReferenceValue(definition)) { final ReferenceValue referenceValue = parseReferenceValue(textComponent, fieldName); if (referenceValue != null) { map.put(fieldName, referenceValue); } } } } } } return map; } DescribeSensorParser(final InputStream inputStream, final SOSMetadata metadata); }
DescribeSensorParser { public HashMap<String, ReferenceValue> parseReferenceValues() { final Capabilities[] capabilities = getSensorMLCapabilities(smlDoc.getSensorML()); final HashMap<String, ReferenceValue> map = new HashMap<String, ReferenceValue>(); if (capabilities == null || capabilities.length == 0) { return map; } for (final Capabilities capability : capabilities) { final AbstractDataRecordType abstractDataRecord = capability.getAbstractDataRecord(); if (abstractDataRecord instanceof SimpleDataRecordType) { final SimpleDataRecordType simpleDataRecord = (SimpleDataRecordType) abstractDataRecord; for (final AnyScalarPropertyType field : simpleDataRecord.getFieldArray()) { if (field.isSetText()) { final String fieldName = field.getName(); final Text textComponent = field.getText(); final String definition = textComponent.getDefinition(); if (isReferenceValue(definition)) { final ReferenceValue referenceValue = parseReferenceValue(textComponent, fieldName); if (referenceValue != null) { map.put(fieldName, referenceValue); } } } } } else if (abstractDataRecord instanceof DataRecordType) { final DataRecordType dataRecord = (DataRecordType) abstractDataRecord; for (final DataComponentPropertyType field : dataRecord.getFieldArray()) { if (field.isSetText()) { final String fieldName = field.getName(); final Text textComponent = field.getText(); final String definition = textComponent.getDefinition(); if (isReferenceValue(definition)) { final ReferenceValue referenceValue = parseReferenceValue(textComponent, fieldName); if (referenceValue != null) { map.put(fieldName, referenceValue); } } } } } } return map; } DescribeSensorParser(final InputStream inputStream, final SOSMetadata metadata); String buildUpSensorMetadataStationName(); String buildUpSensorMetadataUom(final String phenomenonID); String buildUpSensorMetadataHtmlUrl(final SosTimeseries timeseries); String createSensorDescriptionFileName(final SosTimeseries timeseries); Point buildUpSensorMetadataPosition(); HashMap<String, ReferenceValue> parseReferenceValues(); List<String> parseFOIReferences(); List<String> getPhenomenons(); static SensorMLDocument unwrapSensorMLFrom(XmlObject xmlObject); void setReferencingHelper(final CRSUtils refHelper); }
DescribeSensorParser { public HashMap<String, ReferenceValue> parseReferenceValues() { final Capabilities[] capabilities = getSensorMLCapabilities(smlDoc.getSensorML()); final HashMap<String, ReferenceValue> map = new HashMap<String, ReferenceValue>(); if (capabilities == null || capabilities.length == 0) { return map; } for (final Capabilities capability : capabilities) { final AbstractDataRecordType abstractDataRecord = capability.getAbstractDataRecord(); if (abstractDataRecord instanceof SimpleDataRecordType) { final SimpleDataRecordType simpleDataRecord = (SimpleDataRecordType) abstractDataRecord; for (final AnyScalarPropertyType field : simpleDataRecord.getFieldArray()) { if (field.isSetText()) { final String fieldName = field.getName(); final Text textComponent = field.getText(); final String definition = textComponent.getDefinition(); if (isReferenceValue(definition)) { final ReferenceValue referenceValue = parseReferenceValue(textComponent, fieldName); if (referenceValue != null) { map.put(fieldName, referenceValue); } } } } } else if (abstractDataRecord instanceof DataRecordType) { final DataRecordType dataRecord = (DataRecordType) abstractDataRecord; for (final DataComponentPropertyType field : dataRecord.getFieldArray()) { if (field.isSetText()) { final String fieldName = field.getName(); final Text textComponent = field.getText(); final String definition = textComponent.getDefinition(); if (isReferenceValue(definition)) { final ReferenceValue referenceValue = parseReferenceValue(textComponent, fieldName); if (referenceValue != null) { map.put(fieldName, referenceValue); } } } } } } return map; } DescribeSensorParser(final InputStream inputStream, final SOSMetadata metadata); String buildUpSensorMetadataStationName(); String buildUpSensorMetadataUom(final String phenomenonID); String buildUpSensorMetadataHtmlUrl(final SosTimeseries timeseries); String createSensorDescriptionFileName(final SosTimeseries timeseries); Point buildUpSensorMetadataPosition(); HashMap<String, ReferenceValue> parseReferenceValues(); List<String> parseFOIReferences(); List<String> getPhenomenons(); static SensorMLDocument unwrapSensorMLFrom(XmlObject xmlObject); void setReferencingHelper(final CRSUtils refHelper); }