method2testcases
stringlengths
118
6.63k
### Question: AbstractRegistry implements Registry { @Override public void unsubscribe(URL url, NotifyListener listener) { if (url == null) { throw new IllegalArgumentException("unsubscribe url == null"); } if (listener == null) { throw new IllegalArgumentException("unsubscribe listener == null"); } if (logger.isInfoEn...
### Question: AbstractRegistry implements Registry { protected static List<URL> filterEmpty(URL url, List<URL> urls) { if (CollectionUtils.isEmpty(urls)) { List<URL> result = new ArrayList<>(1); result.add(url.setProtocol(Constants.EMPTY_PROTOCOL)); return result; } return urls; } AbstractRegistry(URL url); @Override U...
### Question: AbstractRegistry implements Registry { @Override public List<URL> lookup(URL url) { List<URL> result = new ArrayList<>(); Map<String, List<URL>> notifiedUrls = getNotified().get(url); if (notifiedUrls != null && notifiedUrls.size() > 0) { for (List<URL> urls : notifiedUrls.values()) { for (URL u : urls) {...
### Question: AbstractRegistry implements Registry { @Override public void destroy() { if (logger.isInfoEnabled()) { logger.info("Destroy registry:" + getUrl()); } Set<URL> destroyRegistered = new HashSet<>(getRegistered()); if (!destroyRegistered.isEmpty()) { for (URL url : new HashSet<>(getRegistered())) { if (url.ge...
### Question: AbstractRegistry implements Registry { public List<URL> getCacheUrls(URL url) { for (Map.Entry<Object, Object> entry : properties.entrySet()) { String key = (String) entry.getKey(); String value = (String) entry.getValue(); if (key != null && key.length() > 0 && key.equals(url.getServiceKey()) && (Charact...
### Question: FailbackRegistry extends AbstractRegistry { @Override public void register(URL url) { super.register(url); removeFailedRegistered(url); removeFailedUnregistered(url); try { doRegister(url); } catch (Exception e) { Throwable t = e; boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) && url.get...
### Question: FailbackRegistry extends AbstractRegistry { @Override protected void recover() throws Exception { Set<URL> recoverRegistered = new HashSet<URL>(getRegistered()); if (!recoverRegistered.isEmpty()) { if (logger.isInfoEnabled()) { logger.info("Recover register url " + recoverRegistered); } for (URL url : rec...
### Question: InternalThreadLocal { @SuppressWarnings("unchecked") public static void removeAll() { InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.getIfSet(); if (threadLocalMap == null) { return; } try { Object v = threadLocalMap.indexedVariable(VARIABLES_TO_REMOVE_INDEX); if (v != null && v != Interna...
### Question: InternalThreadLocal { public static int size() { InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.getIfSet(); if (threadLocalMap == null) { return 0; } else { return threadLocalMap.size(); } } InternalThreadLocal(); @SuppressWarnings("unchecked") static void removeAll(); static int size(); s...
### Question: InternalThreadLocal { @SuppressWarnings("unchecked") public final void remove() { remove(InternalThreadLocalMap.getIfSet()); } InternalThreadLocal(); @SuppressWarnings("unchecked") static void removeAll(); static int size(); static void destroy(); @SuppressWarnings("unchecked") final V get(); final void s...
### Question: NamedInternalThreadFactory extends NamedThreadFactory { @Override public Thread newThread(Runnable runnable) { String name = mPrefix + mThreadNum.getAndIncrement(); InternalThread ret = new InternalThread(mGroup, runnable, name, 0); ret.setDaemon(mDaemon); return ret; } NamedInternalThreadFactory(); Name...
### Question: AbortPolicyWithReport extends ThreadPoolExecutor.AbortPolicy { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { String msg = String.format("Thread pool is EXHAUSTED!" + " Thread Name: %s, Pool Size: %d (active: %d, core: %d, max: %d, largest: %d), Task: %d (completed: %d)," + " ...
### Question: LimitedThreadPool implements ThreadPool { @Override public Executor getExecutor(URL url) { String name = url.getParameter(Constants.THREAD_NAME_KEY, Constants.DEFAULT_THREAD_NAME); int cores = url.getParameter(Constants.CORE_THREADS_KEY, Constants.DEFAULT_CORE_THREADS); int threads = url.getParameter(Cons...
### Question: 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_...
### Question: DaggerLifecycleDelegate { public Object onRetainCustomNonConfigurationInstance() { return daggerComponent; } DaggerLifecycleDelegate(@NonNull DaggerComponentFactory<T> daggerComponentFactory); @SuppressWarnings("unchecked") void onCreate(AppCompatActivity activity); Object onRetainCustomNonConfigurationIn...
### Question: DaggerLifecycleDelegate { public T daggerComponent() { return daggerComponent; } DaggerLifecycleDelegate(@NonNull DaggerComponentFactory<T> daggerComponentFactory); @SuppressWarnings("unchecked") void onCreate(AppCompatActivity activity); Object onRetainCustomNonConfigurationInstance(); T daggerComponent(...
### Question: 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(); stat...
### Question: AppRouter { public Intent loginIntent(Context context) { return intentFactory.create(context, LoginActivity.class); } AppRouter(); @VisibleForTesting AppRouter(IntentFactory intentFactory); Intent loginIntent(Context context); }### Answer: @Test public void should_return_loginIntent() throws Exception {...
### Question: EmailValidator { public boolean isValid(CharSequence email) { return email != null && EMAIL_ADDRESS.matcher(email).matches(); } boolean isValid(CharSequence email); Observable<Boolean> checkEmail(CharSequence email); }### Answer: @Test public void should_return_false_when_email_is_null() throws Exceptio...
### Question: 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)."); retur...
### Question: 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...
### Question: 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, Obje...
### Question: 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) { retu...
### Question: 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 h...
### Question: 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<PathEl...
### Question: 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,...
### Question: 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, cance...
### Question: StrictTransportSecurityHeader extends AbstractHeader<StrictTransportSecurity> { @Override public StrictTransportSecurity toValue(CharSequence value) { return StrictTransportSecurity.parse(value); } StrictTransportSecurityHeader(); @Override StrictTransportSecurity toValue(CharSequence value); @Override Ch...
### Question: 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 ? EMPT...
### Question: 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 FrameO...
### Question: 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 '" + s...
### Question: 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(P...
### Question: 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 (CharS...
### Question: 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, che...
### Question: 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(i...
### Question: 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 (nonMatchesCach...
### Question: 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)...
### Question: 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 p...
### Question: 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); re...
### Question: 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 passw...
### Question: 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) ...
### Question: 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() + ". ";...
### Question: 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"...
### Question: 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); ...
### Question: 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, Att...
### Question: 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);...
### Question: 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(Con...
### Question: 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(St...
### Question: 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 = RequestMe...
### Question: 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);...
### Question: 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 = serv...
### Question: 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 ...
### Question: 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(AbstractLogPrin...
### Question: 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...
### Question: 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); }### Answer: @Test public void test() { String user = "zlikun" ; int seniority = 7 ...
### Question: Singleton2 { public static final Singleton2 getInstance() { if (INSTANCE == null) { INSTANCE = new Singleton2() ; } return INSTANCE ; } Singleton2(); static final Singleton2 getInstance(); }### Answer: @Test public void test_multi() { final ConcurrentMap<Singleton2 ,Boolean> map = new ConcurrentHashMap<>...
### Question: 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(); }### Answer: @Tes...
### Question: Singleton0 { public static final Singleton0 getInstance() { return INSTANCE ; } private Singleton0(); static final Singleton0 getInstance(); }### Answer: @Test public void test_single() { Assert.assertTrue(Singleton0.getInstance() == Singleton0.getInstance()); } @Test public void test_multi() { final Se...
### Question: 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 ; } pri...
### Question: 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(); }### Answer: @Test public void test_single() ...
### Question: Singleton4 { public static final Singleton4 getInstance() { if (INSTANCE == null) { INSTANCE = Singleton4Holder.obj ; } return INSTANCE ; } private Singleton4(); static final Singleton4 getInstance(); }### Answer: @Test public void test_single() { Assert.assertTrue(Singleton4.getInstance() == Singleton4...
### Question: 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 + "_incom...
### Question: 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> parseFeat...
### Question: 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<Strin...
### Question: 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> p...
### Question: 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<Stri...
### Question: 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(Identi...
### Question: TimeseriesFactory { public TimeSeries createTimeSeries(SosTimeseries timeseries, String seriesType) { TimeSeries timeSeries = new TimeSeries(timeseries.getTimeseriesId()); ITimePosition timeArray[] = collection.getSortedTimeArray(); ObservedValueTuple prevObservation; ObservedValueTuple nextObservation = ...
### Question: 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 updat...
### Question: 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 invalidateCac...
### Question: 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> sosS...
### Question: 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; ...
### Question: 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)...
### Question: DescribeSensorParser { public static SensorMLDocument unwrapSensorMLFrom(XmlObject xmlObject) throws XmlException, XMLHandlingException, IOException { if (SoapUtil.isSoapEnvelope(xmlObject)) { xmlObject = SoapUtil.stripSoapEnvelope(xmlObject); } if (xmlObject instanceof SensorMLDocument) { return (SensorM...
### Question: SOSRequestBuilderGET_200 implements ISOSRequestBuilder { String encodePlusInParameter(String parameter) { return parameter.replace("+", "%2B"); } @Override String buildGetCapabilitiesRequest(ParameterContainer parameters); @Override String buildGetObservationRequest(ParameterContainer parameters); @Overr...
### Question: SOSRequestBuilderGET_200 implements ISOSRequestBuilder { String fixTimeZone(String timeString) { StringBuilder sb = new StringBuilder(timeString); int insertionIndex = timeString.length() - 2; if (sb.charAt(insertionIndex - 1) != ':') { sb.insert(insertionIndex, ":"); } return sb.toString(); } @Override ...
### Question: SOSRequestBuilderGET_200 implements ISOSRequestBuilder { public String encode(String parameter) { try { return encodePlusInParameter(URLEncoder.encode(parameter, "utf-8")); } catch (UnsupportedEncodingException e) { LOGGER.warn("Could not encode parameter {}!", parameter); return parameter; } } @Override...
### Question: SOSRequestBuilderGET_200 implements ISOSRequestBuilder { String createIso8601Duration(String start, String end) { StringBuilder sb = new StringBuilder(); sb.append(fixTimeZone(start)).append("/"); return sb.append(fixTimeZone(end)).toString(); } @Override String buildGetCapabilitiesRequest(ParameterConta...
### Question: ClientUtils { public static String[] splitJsonObjects(String value) { int openCurlies = 0; List<String> objects = new ArrayList<String>(); StringBuilder object = new StringBuilder(); for (int i=0; i < value.length() ; i++) { char currentChar = value.charAt(i); object.append(currentChar); if (currentChar =...
### Question: QueryBuilder { String encodeValue(String value) { value = value.replace("%", "%25"); value = value.replace("+", "%2B"); value = value.replace(" ", "+"); value = value.replace("!", "%21"); value = value.replace("#", "%23"); value = value.replace("$", "%24"); value = value.replace("&", "%26"); value = value...
### Question: EventSubscriptionController { String replaceNonAlphaNumerics(String toReplace) { return toReplace.replaceAll("[^0-9a-zA-Z_]", "_"); } void setTimeseries(TimeseriesLegendData timeseries); TimeseriesLegendData getTimeSeries(); String getServiceUrl(); String getOffering(); String getPhenomenon(); String get...
### Question: EventSubscriptionController { String replaceAllUmlauts(String toReplace) { toReplace = toReplace.replaceAll("[ö]", "oe"); toReplace = toReplace.replaceAll("^Ö", "Oe"); toReplace = toReplace.replaceAll("[Ö]", "OE"); toReplace = toReplace.replaceAll("[ä]", "ae"); toReplace = toReplace.replaceAll("^Ä", "Ae")...
### Question: EventSubscriptionController { String normalize(String toNormalize) { return replaceNonAlphaNumerics(replaceAllUmlauts(toNormalize)); } void setTimeseries(TimeseriesLegendData timeseries); TimeseriesLegendData getTimeSeries(); String getServiceUrl(); String getOffering(); String getPhenomenon(); String ge...
### Question: SensorNetworkParser { public Map<String, ComponentType> parseSensorDescriptions(InputStream stream) { Map<String, ComponentType> sensorDescriptions = new HashMap<String, ComponentType>(); ComponentDocument[] components = parseNetworkComponentsFromDescribeSensorResponse(stream); for (ComponentDocument comp...
### Question: ArcGISSoeEReportingMetadataHandler extends MetadataHandler { protected String parseCategory(String phenomenonLabel) { Pattern pattern = Pattern.compile("\\((.*)\\)$"); Matcher matcher = pattern.matcher(parseLastBraceGroup(phenomenonLabel)); return matcher.find() ? matcher.group(1) : phenomenonLabel; } Arc...
### Question: QueryParser { Map<String, String> parseKvps(String query) { Map<String, String> parsedKvps = new HashMap<String, String>(); if (query == null || query.isEmpty()) { return parsedKvps; } else { String[] splittedKvps = query.split("&"); for (String kvp : splittedKvps) { addKvp(kvp, parsedKvps); } return pars...
### Question: FeatureParser { public Map<Feature, Point> parseFeatures(InputStream stream) { Map<Feature, Point> featureLocations = new HashMap<Feature, Point>(); try { GetFeatureOfInterestResponseDocument responseDoc = GetFeatureOfInterestResponseDocument.Factory.parse(stream); GetFeatureOfInterestResponseType respons...
### Question: ArcGISSoeDescribeSensorParser { public String getUomFor(String phenomenonId) { String xPath = "$this String query = String.format(xPath, phenomenonId); Quantity output = xmlHelper.parseFirst(sensorML, query, Quantity.class); return output == null ? null : output.getUom().getCode(); } ArcGISSoeDescribeSens...
### Question: ArcGISSoeDescribeSensorParser { public String getShortName() { String query = "$this Identifier identifier = xmlHelper.parseFirst(sensorML, query, Identifier.class); return identifier == null ? null : identifier.getTerm().getValue(); } ArcGISSoeDescribeSensorParser(XmlObject sml); String getUomFor(String ...
### Question: HydroMetadataHandler extends MetadataHandler { protected Collection<SosTimeseries> getAvailableTimeseries(XmlObject result_xb, SosTimeseries timeserie, SOSMetadata metadata) throws XmlException, IOException { ArrayList<SosTimeseries> timeseries = new ArrayList<SosTimeseries>(); StringBuilder sb = new Stri...
### Question: SoapSOSRequestBuilder_200 extends SOSRequestBuilder_200_OXFExtension { @Override public String buildGetObservationRequest(ParameterContainer parameters) throws OXFException { parameters.removeParameterShell(parameters.getParameterShellWithCommonName(GET_OBSERVATION_RESPONSE_FORMAT_PARAMETER)); parameters....
### Question: TimeseriesParameter implements Serializable { public String getLabel() { return label; } TimeseriesParameter(); TimeseriesParameter(String parameterId, String[] parametersToGenerateId); @JsonIgnore String getGlobalId(); void setLabel(String label); String getLabel(); }### Answer: @Test public void shou...
### Question: TimeseriesParameter implements Serializable { @JsonIgnore public String getGlobalId() { return globalId; } TimeseriesParameter(); TimeseriesParameter(String parameterId, String[] parametersToGenerateId); @JsonIgnore String getGlobalId(); void setLabel(String label); String getLabel(); }### Answer: @Tes...
### Question: ResultPage implements Serializable { public boolean isLastPage() { return offset + results.length >= total; } @SuppressWarnings("unused") private ResultPage(); ResultPage(T[] results, int offset, int total); int getOffset(); int getTotal(); T[] getResults(); boolean isLastPage(); }### Answer: @Test pub...
### Question: QueryParser { String decodeValue(String value) { value = value.replace("%21", "!"); value = value.replace("%23", "#"); value = value.replace("%24", "$"); value = value.replace("%26", "&"); value = value.replace("%27", "'"); value = value.replace("%28", "("); value = value.replace("%29", ")"); value = valu...
### Question: QueryParser { public Collection<String> parseServices() { String serviceValues = kvps.get(SERVICES.name()); return parseCommaSeparatedValues(serviceValues); } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeat...
### Question: QueryParser { public Collection<String> parseVersions() { String versionValues = kvps.get(VERSIONS.name()); return parseCommaSeparatedValues(versionValues); } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parseFeat...
### Question: QueryParser { public Collection<String> parseOfferings() { String offeringValues = kvps.get(OFFERINGS.name()); return parseCommaSeparatedValues(offeringValues); } QueryParser(String query, boolean compressed); Collection<String> parseServices(); Collection<String> parseVersions(); Collection<String> parse...
### Question: CheckList { public static List<Class> getChecks() { return ImmutableList.<Class> of( ParsingErrorCheck.class, XPathCheck.class ); } private CheckList(); static List<Class> getChecks(); static final String REPOSITORY_KEY; static final String REPOSITORY_NAME; static final String SONAR_WAY_PROFILE; }### Ans...
### Question: _1CTokenizer implements Tokenizer { public final void tokenize(SourceCode source, Tokens cpdTokens) { Lexer lexer = _1CLexer.create(new _1CConfiguration(charset)); String fileName = source.getFileName(); List<Token> tokens = lexer.lex(new File(fileName)); for (Token token : tokens) { TokenEntry cpdToken =...