index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/impl/FinishedSpan.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.impl;
import io.opentracing.Span;
public class FinishedSpan {
private final Span span;
public FinishedSpan(final Span span) {
this.span = span;
}
public Span getSpan() {
return span;
}
}
| 6,300 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/impl/ReferenceImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.impl;
public class ReferenceImpl {
private final String type;
private final SpanContextImpl value;
public ReferenceImpl(final String type, final SpanContextImpl value) {
this.type = type;
this.value = value;
}
public String getType() {
return type;
}
public SpanContextImpl getValue() {
return value;
}
@Override
public String toString() {
return "ReferenceImpl{" +
"type='" + type + '\'' +
", value=" + value +
'}';
}
}
| 6,301 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/impl/ScopeImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.impl;
import io.opentracing.Scope;
import io.opentracing.Span;
public class ScopeImpl implements Scope {
private final Span span;
private final boolean finishOnClose;
private final Runnable onClose;
public ScopeImpl(final Runnable onClose, final Span span, final boolean finishSpanOnClose) {
this.onClose = onClose;
this.span = span;
this.finishOnClose = finishSpanOnClose;
}
@Override
public void close() {
try {
if (finishOnClose) {
span.finish();
}
} finally {
if (onClose != null) {
onClose.run();
}
}
}
@Override
public Span span() {
return span;
}
}
| 6,302 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/impl/GeronimoTracer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.impl;
import static java.util.Collections.list;
import static java.util.Optional.ofNullable;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toMap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.MultivaluedMap;
import org.apache.geronimo.microprofile.opentracing.common.config.GeronimoOpenTracingConfig;
import org.apache.geronimo.microprofile.opentracing.common.spi.Bus;
import io.opentracing.Scope;
import io.opentracing.ScopeManager;
import io.opentracing.Span;
import io.opentracing.SpanContext;
import io.opentracing.Tracer;
import io.opentracing.propagation.Format;
import io.opentracing.propagation.TextMap;
public class GeronimoTracer implements Tracer {
private ScopeManager scopeManager;
private IdGenerator idGenerator;
private Bus<FinishedSpan> finishedSpanEvent;
private GeronimoOpenTracingConfig config;
private String parentSpanIdHeader;
private String spanIdHeader;
private String traceIdHeader;
private String baggageHeaderPrefix;
public void init() {
parentSpanIdHeader = config.read("propagation.headers.parentSpanId", "X-B3-ParentSpanId");
spanIdHeader = config.read("propagation.headers.spanId", "X-B3-SpanId");
traceIdHeader = config.read("propagation.headers.traceId", "X-B3-TraceId");
baggageHeaderPrefix = config.read("propagation.headers.baggagePrefix", "baggage-");
}
public void setScopeManager(final ScopeManager scopeManager) {
this.scopeManager = scopeManager;
}
public void setIdGenerator(final IdGenerator idGenerator) {
this.idGenerator = idGenerator;
}
public void setFinishedSpanEvent(final Bus<FinishedSpan> finishedSpanEvent) {
this.finishedSpanEvent = finishedSpanEvent;
}
public void setConfig(final GeronimoOpenTracingConfig config) {
this.config = config;
}
@Override
public ScopeManager scopeManager() {
return scopeManager;
}
@Override
public Span activeSpan() {
return ofNullable(scopeManager.active()).map(Scope::span).orElse(null);
}
@Override
public SpanBuilder buildSpan(final String operationName) {
return new SpanBuilderImpl(
this,
span -> finishedSpanEvent.fire(new FinishedSpan(processNewSpan(span))), operationName, idGenerator);
}
@Override
public <C> void inject(final SpanContext spanContext, final Format<C> format, final C carrier) {
if (!TextMap.class.isInstance(carrier)) {
throw new IllegalArgumentException("Only TextMap are supported");
}
final TextMap textMap = TextMap.class.cast(carrier);
final SpanContextImpl context = SpanContextImpl.class.cast(spanContext);
textMap.put(traceIdHeader, String.valueOf(context.getTraceId()));
textMap.put(spanIdHeader, String.valueOf(context.getSpanId()));
context.getBaggageItems().forEach((k, v) -> textMap.put(baggageHeaderPrefix + k, v));
}
@Override
public <C> SpanContext extract(final Format<C> format, final C carrier) {
if (JaxRsHeaderTextMap.class.isInstance(carrier)) {
final MultivaluedMap<String, ?> map = JaxRsHeaderTextMap.class.cast(carrier).getMap();
final String traceid = (String) map.getFirst(traceIdHeader);
final String spanid = (String) map.getFirst(spanIdHeader);
final String parentspanid = (String) map.getFirst(parentSpanIdHeader);
if (traceid != null && spanid != null) {
return newContext(traceid, parentspanid, spanid, map.keySet().stream().filter(it -> it.startsWith(baggageHeaderPrefix))
.collect(toMap(identity(), k -> String.valueOf(map.getFirst(k)))));
}
return null;
}
if (ServletHeaderTextMap.class.isInstance(carrier)) {
final HttpServletRequest req = ServletHeaderTextMap.class.cast(carrier).getRequest();
final String traceid = req.getHeader(traceIdHeader);
final String spanid = req.getHeader(spanIdHeader);
final String parentspanid = req.getHeader(parentSpanIdHeader);
if (traceid != null && spanid != null) {
return newContext(traceid, parentspanid, spanid, list(req.getHeaderNames()).stream()
.filter(it -> it.startsWith(baggageHeaderPrefix))
.collect(toMap(identity(), k -> String.valueOf(req.getHeader(k)))));
}
return null;
}
if (!TextMap.class.isInstance(carrier)) {
throw new IllegalArgumentException("Only TextMap are supported");
}
final Iterator<Map.Entry<String, String>> textMap = TextMap.class.cast(carrier).iterator();
String traceId = null;
String spanId = null;
String parentSpanId = null;
final Map<String, String> baggages = new HashMap<>();
while (textMap.hasNext()) {
final Map.Entry<String, String> next = textMap.next();
if (next.getKey().startsWith(baggageHeaderPrefix)) {
baggages.put(next.getKey(), next.getValue());
} else if (spanIdHeader.equals(next.getKey())) {
spanId = next.getValue();
} else if (traceIdHeader.equals(next.getKey())) {
traceId = next.getValue();
} else if (parentSpanIdHeader.equals(next.getKey())) {
parentSpanId = next.getValue();
}
}
if (traceId != null && spanId != null) {
return newContext(traceId, parentSpanId, spanId, baggages);
}
return null;
}
protected Span processNewSpan(final SpanImpl span) {
return span;
}
protected SpanContextImpl newContext(final Object traceId, final Object parentSpanId,
final Object spanId, final Map<String, String> baggages) {
return new SpanContextImpl(traceId, parentSpanId, spanId, baggages);
}
}
| 6,303 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/impl/SpanBuilderImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.impl;
import static java.util.stream.Collectors.toMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.stream.StreamSupport;
import io.opentracing.References;
import io.opentracing.Scope;
import io.opentracing.Span;
import io.opentracing.SpanContext;
import io.opentracing.Tracer;
public class SpanBuilderImpl implements Tracer.SpanBuilder {
private final GeronimoTracer tracer;
private final Consumer<SpanImpl> onFinish;
private final String operationName;
private final Collection<ReferenceImpl> references = new ArrayList<>();
private final Map<String, Object> tags = new HashMap<>();
private final IdGenerator idGenerator;
private boolean ignoreActiveSpan;
private long timestamp = -1;
public SpanBuilderImpl(final GeronimoTracer tracer,
final Consumer<SpanImpl> onFinish, final String operationName,
final IdGenerator idGenerator) {
this.tracer = tracer;
this.onFinish = onFinish;
this.operationName = operationName;
this.idGenerator = idGenerator;
}
@Override
public Tracer.SpanBuilder asChildOf(final SpanContext parent) {
return addReference(References.CHILD_OF, parent);
}
@Override
public Tracer.SpanBuilder asChildOf(final Span parent) {
if (parent == null) {
return this;
}
return asChildOf(parent.context());
}
@Override
public Tracer.SpanBuilder addReference(final String referenceType, final SpanContext referencedContext) {
references.add(new ReferenceImpl(referenceType, SpanContextImpl.class.cast(referencedContext)));
return this;
}
@Override
public Tracer.SpanBuilder ignoreActiveSpan() {
this.ignoreActiveSpan = true;
return this;
}
@Override
public Tracer.SpanBuilder withTag(final String key, final String value) {
tags.put(key, value);
return this;
}
@Override
public Tracer.SpanBuilder withTag(final String key, final boolean value) {
tags.put(key, value);
return this;
}
@Override
public Tracer.SpanBuilder withTag(final String key, final Number value) {
tags.put(key, value);
return this;
}
@Override
public Tracer.SpanBuilder withStartTimestamp(final long microseconds) {
this.timestamp = microseconds;
return this;
}
@Override
public Scope startActive(final boolean finishSpanOnClose) {
return tracer.scopeManager().activate(startManual(), finishSpanOnClose);
}
@Override
public Span startManual() {
if (timestamp < 0) {
timestamp = TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis());
}
if (!ignoreActiveSpan && references.stream().noneMatch(it -> it.getType().equalsIgnoreCase(References.CHILD_OF))) {
final Span span = tracer.activeSpan();
if (span != null) {
addReference(References.CHILD_OF, span.context());
}
}
final ReferenceImpl parent = references.stream().filter(it -> References.CHILD_OF.equals(it.getType())).findFirst()
.orElseGet(() -> references.isEmpty() ? null : references.iterator().next());
final Map<String, String> baggages = references.stream()
.flatMap(r -> StreamSupport.stream(
Spliterators.spliteratorUnknownSize(r.getValue().baggageItems().iterator(), Spliterator.IMMUTABLE),
false))
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
final SpanContextImpl context = parent == null ?
tracer.newContext(idGenerator.next(), null, idGenerator.next(), baggages) :
tracer.newContext(parent.getValue().getTraceId(), parent.getValue().getSpanId(), idGenerator.next(), baggages);
return new SpanImpl(operationName, timestamp, references, tags, onFinish, context);
}
@Override
public Span start() {
return startManual();
}
}
| 6,304 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/impl/ScopeManagerImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.impl;
import io.opentracing.Scope;
import io.opentracing.ScopeManager;
import io.opentracing.Span;
// @ApplicationScoped
public class ScopeManagerImpl implements ScopeManager {
private final ThreadLocal<Scope> current = new ThreadLocal<>();
@Override
public Scope activate(final Span span, final boolean finishSpanOnClose) {
final Thread thread = Thread.currentThread();
final Scope oldScope = current.get();
final ScopeImpl newScope = new ScopeImpl(() -> {
if (Thread.currentThread() == thread) {
current.set(oldScope);
} // else error?
}, span, finishSpanOnClose);
current.set(newScope);
return newScope;
}
@Override
public Scope active() {
final Scope scope = current.get();
if (scope == null) {
current.remove();
}
return scope;
}
public void clear() {
current.remove();
}
}
| 6,305 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/impl/JaxRsHeaderTextMap.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.impl;
import java.util.Iterator;
import java.util.Map;
import javax.ws.rs.core.MultivaluedMap;
import io.opentracing.propagation.TextMap;
public class JaxRsHeaderTextMap<T> implements TextMap {
private final MultivaluedMap<String, T> headers;
public JaxRsHeaderTextMap(final MultivaluedMap<String, T> headers) {
this.headers = headers;
}
public MultivaluedMap<String, ?> getMap() {
return headers;
}
@Override
public Iterator<Map.Entry<String, String>> iterator() {
final Iterator<String> iterator = headers.keySet().iterator();
return new Iterator<Map.Entry<String, String>>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public Map.Entry<String, String> next() {
final String next = iterator.next();
return new Map.Entry<String, String>() {
@Override
public String getKey() {
return next;
}
@Override
public String getValue() {
return String.valueOf(headers.getFirst(next));
}
@Override
public String setValue(final String value) {
throw new UnsupportedOperationException();
}
};
}
};
}
@Override
public void put(final String key, final String value) {
this.headers.putSingle(key, (T) value);
}
}
| 6,306 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/impl/SpanImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.impl;
import static java.util.Collections.singletonMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import io.opentracing.Span;
import io.opentracing.SpanContext;
import io.opentracing.tag.Tags;
public class SpanImpl implements Span {
private final Collection<ReferenceImpl> references;
private final Map<String, Object> tags;
private final Consumer<SpanImpl> onFinish;
private final SpanContextImpl context;
private final long startTimestamp;
private String operationName;
private long finishTimestamp;
private final Collection<Log> logs = new ArrayList<>();
public SpanImpl(final String operationName, final long startTimestamp, final Collection<ReferenceImpl> references,
final Map<String, Object> tags, final Consumer<SpanImpl> onFinish, final SpanContextImpl context) {
this.operationName = operationName;
this.startTimestamp = startTimestamp;
this.references = references;
this.tags = tags;
this.context = context;
this.onFinish = onFinish;
}
@Override
public Span log(final long timestampMicroseconds, final Map<String, ?> fields) {
final Log log = new Log(timestampMicroseconds, fields);
synchronized (logs) {
logs.add(log);
}
return this;
}
@Override
public SpanContext context() {
return context;
}
@Override
public Span log(final long timestampMicroseconds, final String event) {
return log(singletonMap("event", event));
}
@Override
public void finish() {
finish(TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis()));
}
@Override
public void finish(final long finishMicros) {
if (finishTimestamp != 0) {
return;
}
finishTimestamp = finishMicros;
onFinish.accept(this);
}
@Override
public Span setTag(final String key, final String value) {
tags.put(key, value);
return this;
}
@Override
public Span setTag(final String key, final boolean value) {
tags.put(key, value);
return this;
}
@Override
public Span setTag(final String key, final Number value) {
tags.put(key, value);
return this;
}
@Override
public Span log(final Map<String, ?> fields) {
return log(startTimestamp, fields);
}
@Override
public Span log(final String event) {
return log(startTimestamp, event);
}
@Override
public Span setBaggageItem(final String key, final String value) {
context.getBaggageItems().put(key, value);
return this;
}
@Override
public String getBaggageItem(final String key) {
return context.getBaggageItems().get(key);
}
@Override
public Span setOperationName(final String operationName) {
this.operationName = operationName;
return this;
}
@Override
public String toString() {
return "SpanImpl{" +
" id=" + context.getSpanId() +
", operationName='" + operationName + '\'' +
", references=" + references +
", tags=" + tags +
", startTimestamp=" + startTimestamp +
", finishTimestamp=" + finishTimestamp +
", logs=" + logs +
'}';
}
public Object getId() {
return context.getSpanId();
}
public Object getTraceId() {
return context.getTraceId();
}
public Object getParentId() {
return context.getParentSpanId();
}
public String getName() {
return operationName;
}
public long getTimestamp() {
return startTimestamp;
}
public long getDuration() {
return finishTimestamp - startTimestamp;
}
public String getKind() {
return tags.entrySet().stream().filter(it -> Tags.SPAN_KIND.getKey().equals(it.getKey()))
.findFirst().map(Map.Entry::getValue)
.map(String::valueOf).orElse(null);
}
public Map<String, Object> getTags() {
return tags;
}
public Collection<Log> getLogs() {
return logs;
}
public Collection<ReferenceImpl> getReferences() {
return references;
}
public static class Log {
private final long timestampMicros;
private final Map<String, ?> fields;
public Log(long timestampMicros, Map<String, ?> fields) {
this.timestampMicros = timestampMicros;
this.fields = fields;
}
public long getTimestampMicros() {
return timestampMicros;
}
public Map<String, ?> getFields() {
return fields;
}
}
}
| 6,307 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/impl/SpanContextImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.impl;
import java.util.Map;
import io.opentracing.SpanContext;
public class SpanContextImpl implements SpanContext {
private final Object traceId;
private final Object parentSpanId;
private final Object spanId;
private final Map<String, String> baggageItems;
public SpanContextImpl(final Object traceId, final Object parentSpanId, final Object spanId, final Map<String, String> baggageItems) {
this.traceId = traceId;
this.parentSpanId = parentSpanId;
this.spanId = spanId;
this.baggageItems = baggageItems;
}
public Map<String, String> getBaggageItems() {
return baggageItems;
}
public Object getTraceId() {
return traceId;
}
public Object getParentSpanId() {
return parentSpanId;
}
public Object getSpanId() {
return spanId;
}
@Override
public Iterable<Map.Entry<String, String>> baggageItems() {
return baggageItems.entrySet();
}
@Override
public String toString() {
return "SpanContextImpl{" +
"traceId=" + traceId +
", parentSpanId=" + parentSpanId +
", spanId=" + spanId +
", baggageItems=" + baggageItems +
'}';
}
}
| 6,308 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/config/GeronimoOpenTracingConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.config;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
class DefaultOpenTracingConfig implements GeronimoOpenTracingConfig {
private final Map<String, String> configuration = new HashMap<>();
DefaultOpenTracingConfig() {
System.getProperties().stringPropertyNames()
.forEach(k -> configuration.put(k, System.getProperty(k)));
try (final InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("META-INF/geronimo/microprofile/opentracing.properties")) {
if (stream != null) {
final Properties properties = new Properties();
properties.load(stream);
properties.stringPropertyNames().forEach(k -> configuration.put(k, properties.getProperty(k)));
}
} catch (final IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public String read(final String value, final String def) {
return configuration.getOrDefault(value, def);
}
}
@FunctionalInterface
public interface GeronimoOpenTracingConfig {
String read(String value, String def);
static GeronimoOpenTracingConfig create() {
try {
final Iterator<GeronimoOpenTracingConfig> iterator = ServiceLoader.load(GeronimoOpenTracingConfig.class).iterator();
if (iterator.hasNext()) {
return new PrefixedConfig(iterator.next());
}
} catch (final ServiceConfigurationError | ExceptionInInitializerError | NoClassDefFoundError | Exception e) {
// no-op
}
return new PrefixedConfig(new DefaultOpenTracingConfig());
}
}
| 6,309 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/config/PrefixedConfig.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.config;
class PrefixedConfig implements GeronimoOpenTracingConfig {
private final GeronimoOpenTracingConfig delegate;
PrefixedConfig(final GeronimoOpenTracingConfig geronimoOpenTracingConfig) {
this.delegate = geronimoOpenTracingConfig;
}
@Override
public String read(final String value, final String def) {
if (value.startsWith("mp.")) {
return delegate.read(value, delegate.read("geronimo.opentracing." + value, def));
}
return delegate.read("geronimo.opentracing." + value, def);
}
}
| 6,310 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/spi/Container.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.spi;
import java.util.Iterator;
import java.util.ServiceLoader;
public interface Container {
<T> T lookup(Class<T> type);
static Container get() {
final Iterator<Container> iterator = ServiceLoader.load(Container.class).iterator();
if (!iterator.hasNext()) {
throw new IllegalArgumentException("No implementation of Container found");
}
return iterator.next();
}
@FunctionalInterface
interface Unwrappable {
Object unwrap();
}
}
| 6,311 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/spi/Listener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.spi;
public interface Listener<T> {
void onEvent(T event);
}
| 6,312 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/spi/Bus.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.spi;
public interface Bus<T> {
void fire(T event);
}
| 6,313 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile/server/OpenTracingFilter.java | package org.apache.geronimo.microprofile.opentracing.common.microprofile.server;
import static java.util.Optional.ofNullable;
import static java.util.stream.Collectors.toList;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeoutException;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.geronimo.microprofile.opentracing.common.config.GeronimoOpenTracingConfig;
import org.apache.geronimo.microprofile.opentracing.common.impl.ScopeManagerImpl;
import org.apache.geronimo.microprofile.opentracing.common.impl.ServletHeaderTextMap;
import org.apache.geronimo.microprofile.opentracing.common.spi.Container;
import io.opentracing.Scope;
import io.opentracing.ScopeManager;
import io.opentracing.Span;
import io.opentracing.Tracer;
import io.opentracing.propagation.Format;
import io.opentracing.tag.Tags;
public class OpenTracingFilter implements Filter {
private Tracer tracer;
private GeronimoOpenTracingConfig config;
private ScopeManager manager;
private Container container;
private Collection<Predicate<String>> forcedUrls;
private List<Predicate<String>> skipUrls;
private boolean skipDefaultTags;
private boolean forceStackLog;
public void setTracer(final Tracer tracer) {
this.tracer = tracer;
}
public void setConfig(final GeronimoOpenTracingConfig config) {
this.config = config;
}
public void setManager(final ScopeManager manager) {
this.manager = manager;
}
public void setContainer(final Container container) {
this.container = container;
}
@Override
public void init(final FilterConfig filterConfig) {
if (container == null) {
container = Container.get();
}
if (tracer == null) {
tracer = container.lookup(Tracer.class);
}
if (manager == null) {
manager = container.lookup(ScopeManager.class);
}
if (config == null) {
config = container.lookup(GeronimoOpenTracingConfig.class);
}
skipDefaultTags = Boolean.parseBoolean(config.read("filter.forcedTracing.skipDefaultTags", "false"));
forceStackLog = Boolean.parseBoolean(config.read("filter.error.forceStackLog", "false"));
forcedUrls = ofNullable(config.read("filter.forcedTracing.urls", null))
.map(String::trim).filter(v -> !v.isEmpty())
.map(v -> toMatchingPredicates(v, "forcedTracing"))
.orElse(null);
skipUrls = ofNullable(config.read("filter.skippedTracing.urls", null))
.map(String::trim).filter(v -> !v.isEmpty())
.map(v -> toMatchingPredicates(v, "skippedTracing"))
.orElse(null);
}
private List<Predicate<String>> toMatchingPredicates(final String v, final String keyMarker) {
final String matchingType = config.read("filter." + keyMarker + ".matcherType", "prefix");
final Function<String, Predicate<String>> matcherFactory;
switch (matchingType) {
case "regex":
matcherFactory = from -> {
final Pattern compiled = Pattern.compile(from);
return url -> compiled.matcher(url).matches();
};
break;
case "prefix":
default:
matcherFactory = from -> url -> url.startsWith(from);
}
return Stream.of(v.split(",")).map(String::trim).filter(it -> !it.isEmpty()).map(matcherFactory)
.collect(toList());
}
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws IOException, ServletException {
if (!HttpServletRequest.class.isInstance(request)) {
chain.doFilter(request, response);
return;
}
if (forcedUrls != null && !forcedUrls.isEmpty()) {
final HttpServletRequest req = HttpServletRequest.class.cast(request);
final String matching = req.getRequestURI().substring(req.getContextPath().length());
if (forcedUrls.stream().anyMatch(p -> p.test(matching))) {
final Tracer.SpanBuilder builder = tracer.buildSpan(buildServletOperationName(req));
builder.withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER);
builder.withTag("component", "servlet");
ofNullable(ofNullable(tracer.activeSpan()).map(Span::context)
.orElseGet(() -> tracer.extract(Format.Builtin.HTTP_HEADERS,
new ServletHeaderTextMap(req, HttpServletResponse.class.cast(response)))))
.ifPresent(builder::asChildOf);
final Scope scope = builder.startActive(true);
final Span span = scope.span();
if (!skipDefaultTags) {
Tags.HTTP_METHOD.set(span, req.getMethod());
Tags.HTTP_URL.set(span, req.getRequestURL().toString());
}
request.setAttribute(OpenTracingFilter.class.getName(), scope);
}
}
if (skipUrls != null && !skipUrls.isEmpty()) {
final HttpServletRequest req = HttpServletRequest.class.cast(request);
final String matching = req.getRequestURI().substring(req.getContextPath().length());
if (skipUrls.stream().anyMatch(p -> p.test(matching))) {
chain.doFilter(request, response);
return;
}
}
try {
chain.doFilter(request, response);
} catch (final Exception ex) {
getCurrentScope(request).ifPresent(scope -> onError(response, ex, scope));
throw ex;
} finally {
getCurrentScope(request).ifPresent(scope -> {
if (request.isAsyncStarted()) {
request.getAsyncContext().addListener(new AsyncListener() {
@Override
public void onComplete(final AsyncEvent event) {
scope.close();
}
@Override
public void onTimeout(final AsyncEvent event) {
OpenTracingFilter.this.onError(
event.getSuppliedResponse(),
ofNullable(event.getThrowable()).orElseGet(TimeoutException::new),
scope);
}
@Override
public void onError(final AsyncEvent event) {
OpenTracingFilter.this.onError(event.getSuppliedResponse(), event.getThrowable(), scope);
}
@Override
public void onStartAsync(final AsyncEvent event) {
// no-op
}
});
ScopeManager managerImpl = manager;
if (!ScopeManagerImpl.class.isInstance(managerImpl) && Proxy.isProxyClass(manager.getClass())) {
final InvocationHandler handler = Proxy.getInvocationHandler(manager);
if (Container.Unwrappable.class.isInstance(handler)) {
managerImpl = ScopeManager.class.cast(Container.Unwrappable.class.cast(handler).unwrap());
}
}
if (ScopeManagerImpl.class.isInstance(managerImpl)) {
ScopeManagerImpl.class.cast(managerImpl).clear();
}
} else {
scope.close();
}
});
}
}
private void onError(final ServletResponse response, final Throwable ex, final Scope scope) {
final int status = HttpServletResponse.class.cast(response).getStatus();
final Span span = scope.span();
Tags.HTTP_STATUS.set(span,
status == HttpServletResponse.SC_OK ? HttpServletResponse.SC_INTERNAL_SERVER_ERROR : status);
if (forceStackLog) {
Tags.ERROR.set(span, true);
final Map<String, Object> logs = new LinkedHashMap<>();
logs.put("event", Tags.ERROR.getKey());
logs.put("error.object", ex);
span.log(logs);
}
}
private Optional<Scope> getCurrentScope(final ServletRequest request) {
return ofNullable(ofNullable(request.getAttribute(OpenTracingFilter.class.getName()))
.orElseGet(() -> tracer.scopeManager().active())).map(Scope.class::cast);
}
protected String buildServletOperationName(final HttpServletRequest req) {
return req.getMethod() + ":" + req.getRequestURL();
}
}
| 6,314 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile/server/ServletTracingSetup.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.microprofile.server;
import java.util.EnumSet;
import java.util.Set;
import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import org.apache.geronimo.microprofile.opentracing.common.config.GeronimoOpenTracingConfig;
public class ServletTracingSetup implements ServletContainerInitializer {
@Override
public void onStartup(final Set<Class<?>> c, final ServletContext ctx) {
final GeronimoOpenTracingConfig config = GeronimoOpenTracingConfig.create();
if (!"true".equalsIgnoreCase(config.read("filter.active", "true"))) {
return;
}
final FilterRegistration.Dynamic opentracing = ctx.addFilter("opentracing", OpenTracingFilter.class);
opentracing.setAsyncSupported(true);
opentracing.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*");
}
}
| 6,315 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile/server/GeronimoOpenTracingFeature.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.microprofile.server;
import static java.util.Optional.ofNullable;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import java.util.Collection;
import java.util.Collections;
import java.util.Optional;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.Path;
import javax.ws.rs.container.DynamicFeature;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.FeatureContext;
import javax.ws.rs.ext.Provider;
import org.apache.geronimo.microprofile.opentracing.common.config.GeronimoOpenTracingConfig;
import org.apache.geronimo.microprofile.opentracing.common.spi.Container;
import org.eclipse.microprofile.opentracing.Traced;
import io.opentracing.Tracer;
// @Provider - don't let it be scanned by EE containers like tomee, it is in CDI module anyway!
// @Dependent
public class GeronimoOpenTracingFeature implements DynamicFeature {
private Tracer tracer;
private GeronimoOpenTracingConfig config;
private Container container;
private Collection<Pattern> skipPatterns;
private String globalFilterRequestSkip;
private boolean globalIgnoreMetadataResources;
public void setTracer(final Tracer tracer) {
this.tracer = tracer;
}
public void setConfig(final GeronimoOpenTracingConfig config) {
this.config = config;
this.globalFilterRequestSkip = config.read("server.filter.request.skip", "false");
this.globalIgnoreMetadataResources = Boolean.parseBoolean(config.read("server.filter.request.ignoreMetadaResources", "true"));
}
public void setContainer(final Container container) {
this.container = container;
}
@Override
public void configure(final ResourceInfo resourceInfo, final FeatureContext context) {
if ((tracer == null || config == null) && container == null) {
container = Container.get();
}
if (tracer == null) { // configured instead of scanned
tracer = container.lookup(Tracer.class);
}
if (config == null) {
config = container.lookup(GeronimoOpenTracingConfig.class);
}
if (skipPatterns == null) {
skipPatterns = ofNullable(config.read("mp.opentracing.server.skip-pattern", null))
.map(it -> Stream.of(it.split("\\|")).map(String::trim).filter(p -> !p.isEmpty()).map(Pattern::compile).collect(toList()))
.orElseGet(Collections::emptyList);
}
final Optional<Traced> traced = ofNullable(ofNullable(resourceInfo.getResourceMethod().getAnnotation(Traced.class))
.orElseGet(() -> resourceInfo.getResourceClass().getAnnotation(Traced.class)));
if (!traced.map(Traced::value).orElse(true)) {
return;
}
final String path = Stream.of(
ofNullable(resourceInfo.getResourceClass().getAnnotation(Path.class)).map(Path::value).orElse(""),
ofNullable(resourceInfo.getResourceMethod().getAnnotation(Path.class)).map(Path::value).orElse(""))
.map(it -> it.equals("/") ? "" : it)
.map(it -> it.substring(it.startsWith("/") ? 1 : 0, it.endsWith("/") ? it.length() - 1 : it.length()))
.filter(it -> !it.isEmpty())
.collect(joining("/", "/", ""));
if (skipPatterns.stream().anyMatch(it -> it.matcher(path).matches())) {
return;
}
final String operationName = traced.map(Traced::operationName).filter(v -> !v.trim().isEmpty()).orElseGet(() -> {
if (Boolean.parseBoolean(config.read("server.filter.request.operationName.usePath", "false"))) {
return getHttpMethod(resourceInfo) + ':' + getMethodPath(resourceInfo);
} else if ("http-path".equals(config.read("mp.opentracing.server.operation-name-provider", null))) {
return getMethodPath(resourceInfo);
}
return buildDefaultName(resourceInfo);
});
context.register(new OpenTracingServerResponseFilter())
.register(new OpenTracingServerRequestFilter(operationName, tracer,
shouldSkip(resourceInfo),
Boolean.parseBoolean(config.read("server.filter.request.skipDefaultTags", "false"))));
}
private boolean shouldSkip(final ResourceInfo resourceInfo) {
if (Boolean.parseBoolean(config.read(
"server.filter.request.skip." + resourceInfo.getResourceClass().getName() + "_" + resourceInfo.getResourceMethod().getName(),
config.read("server.filter.request.skip." + resourceInfo.getResourceClass().getName(),
globalFilterRequestSkip)))) {
return true;
}
return globalIgnoreMetadataResources && isMetadataResource(resourceInfo.getResourceClass().getName());
}
private boolean isMetadataResource(final String name) {
return name.startsWith("org.apache.geronimo.microprofile.openapi.jaxrs.") ||
name.startsWith("org.apache.geronimo.microprofile.metrics.jaxrs.") ||
name.startsWith("org.apache.geronimo.microprofile.impl.health.jaxrs.") ||
name.startsWith("org.apache.geronimo.microprofile.reporter.storage.front.") ||
name.startsWith("org.microprofileext.openapi.swaggerui.");
}
private String getMethodPath(final ResourceInfo resourceInfo) {
final String classPath = ofNullable(resourceInfo.getResourceClass().getAnnotation(Path.class))
.map(Path::value).orElse("");
final String methodPath = ofNullable(resourceInfo.getResourceMethod().getAnnotation(Path.class))
.map(Path::value).orElse("");
return Stream.of(classPath, methodPath)
.map(it -> it.substring(it.startsWith("/") ? 1 : 0, it.length() - (it.endsWith("/") ? 1 : 0)))
.filter(it -> !it.isEmpty())
.collect(joining("/", "/", ""));
}
private String buildDefaultName(final ResourceInfo resourceInfo) {
return getHttpMethod(resourceInfo) + ':' + resourceInfo.getResourceClass().getName() + "."
+ resourceInfo.getResourceMethod().getName();
}
private String getHttpMethod(final ResourceInfo resourceInfo) {
return Stream.of(resourceInfo.getResourceMethod().getAnnotations())
.filter(a -> a.annotationType().isAnnotationPresent(HttpMethod.class)).findFirst()
.map(a -> a.annotationType().getAnnotation(HttpMethod.class).value()).orElse("");
}
}
| 6,316 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile/server/OpenTracingServerResponseFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.microprofile.server;
import static java.util.Optional.ofNullable;
import javax.annotation.Priority;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import io.opentracing.Scope;
import io.opentracing.tag.Tags;
@Priority(Priorities.HEADER_DECORATOR)
public class OpenTracingServerResponseFilter implements ContainerResponseFilter {
@Override
public void filter(final ContainerRequestContext req, final ContainerResponseContext resp) {
ofNullable(req.getProperty(OpenTracingFilter.class.getName())).map(Scope.class::cast)
.ifPresent(scope -> Tags.HTTP_STATUS.set(scope.span(), resp.getStatus()));
}
}
| 6,317 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile/server/OpenTracingServerRequestFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.microprofile.server;
import static java.util.Optional.ofNullable;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import org.apache.geronimo.microprofile.opentracing.common.impl.JaxRsHeaderTextMap;
import org.apache.geronimo.microprofile.opentracing.common.microprofile.client.OpenTracingClientRequestFilter;
import io.opentracing.Scope;
import io.opentracing.Span;
import io.opentracing.Tracer;
import io.opentracing.propagation.Format;
import io.opentracing.tag.Tags;
public class OpenTracingServerRequestFilter implements ContainerRequestFilter {
private final String operationName;
private final Tracer tracer;
private final boolean skip;
private final boolean skipDefaultTags;
public OpenTracingServerRequestFilter(final String operationName, final Tracer tracer,
final boolean skip, final boolean skipDefaultTags) {
this.operationName = operationName;
this.tracer = tracer;
this.skip = skip;
this.skipDefaultTags = skipDefaultTags;
}
@Override
public void filter(final ContainerRequestContext context) {
if (context.getProperty(OpenTracingFilter.class.getName()) != null || skip) {
return;
}
final Tracer.SpanBuilder builder = tracer.buildSpan(operationName);
builder.withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER);
builder.withTag("component", "jaxrs");
ofNullable(ofNullable(tracer.activeSpan()).map(Span::context)
.orElseGet(() -> tracer.extract(Format.Builtin.HTTP_HEADERS, new JaxRsHeaderTextMap<>(context.getHeaders()))))
.ifPresent(builder::asChildOf);
final Scope scope = builder.startActive(true);
final Span span = scope.span();
if (!skipDefaultTags) {
Tags.HTTP_METHOD.set(span, context.getMethod());
Tags.HTTP_URL.set(span, context.getUriInfo().getRequestUri().toASCIIString());
}
context.setProperty(OpenTracingFilter.class.getName(), scope);
}
}
| 6,318 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile/zipkin/ZipkinHttp.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.microprofile.zipkin;
import static java.util.Collections.singletonList;
import static java.util.Optional.ofNullable;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.MINUTES;
import static javax.ws.rs.client.Entity.entity;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.logging.Logger;
import java.util.stream.Stream;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
import org.apache.geronimo.microprofile.opentracing.common.config.GeronimoOpenTracingConfig;
import org.apache.geronimo.microprofile.opentracing.common.spi.Listener;
import org.eclipse.microprofile.opentracing.ClientTracingRegistrar;
// experimental
public class ZipkinHttp implements Listener<ZipkinSpan> {
private GeronimoOpenTracingConfig config;
private Jsonb jsonb;
private BlockingQueue<ZipkinSpan> spans;
private Client client;
private String collector;
private ScheduledExecutorService executor;
private ScheduledFuture<?> scheduledTask;
private int maxSpansPerBulk;
private int maxSpansIteration;
public void setConfig(final GeronimoOpenTracingConfig config) {
this.config = config;
}
public void setJsonb(final Jsonb jsonb) {
this.jsonb = jsonb;
}
public void init() {
if (jsonb == null) {
jsonb = JsonbBuilder.create();
}
final int capacity = Integer.parseInt(
config.read("span.converter.zipkin.http.bufferSize", "1000000"));
maxSpansPerBulk = Integer.parseInt(
config.read("span.converter.zipkin.http.maxSpansPerBulk", "250"));
maxSpansIteration = Integer.parseInt(
config.read("span.converter.zipkin.http.maxSpansIteration", "-1"));
collector = config.read("span.converter.zipkin.http.collector", null);
if (collector == null) {
return;
}
final long delay = Long.parseLong(
config.read("span.converter.zipkin.http.bulkSendInterval", "60000"));
if (delay < 0) {
logger().severe("No span.converter.zipkin.http.bulkSendInterval configured, skipping");
collector = null; // to skip anything
return;
}
if (delay > 0) {
executor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
final Thread thread = new Thread(r, getClass().getName() + "-executor");
thread.setPriority(Thread.NORM_PRIORITY);
thread.setDaemon(false);
return thread;
}
});
scheduledTask = executor.scheduleAtFixedRate(this::onEmit, delay, delay, MILLISECONDS);
spans = new ArrayBlockingQueue<>(capacity);
} else { // == 0 => immediate send
spans = null;
}
final ClientBuilder clientBuilder = ClientBuilder.newBuilder()
.connectTimeout(Long.parseLong(config.read("span.converter.zipkin.http.connectTimeout", "30000")), MILLISECONDS)
.readTimeout(Long.parseLong(config.read("span.converter.zipkin.http.readTimeout", "30000")), MILLISECONDS);
ofNullable(config.read("span.converter.zipkin.http.providers", null))
.ifPresent(providers -> Stream.of(providers.split(","))
.map(String::trim)
.map(it -> {
try {
return Thread.currentThread().getContextClassLoader().loadClass(it)
.getConstructor().newInstance();
} catch (final Exception e) {
throw new IllegalArgumentException(e);
}
})
.forEach(clientBuilder::register));
if (Boolean.parseBoolean(config.read("span.converter.zipkin.http.selfTrace", "false"))) {
ClientTracingRegistrar.configure(clientBuilder);
}
client = clientBuilder.build();
logger().info("Zipkin http sender configured");
}
private Logger logger() {
return Logger.getLogger("org.apache.geronimo.opentracing.zipkin.http");
}
public Jsonb getJsonb() {
return jsonb;
}
public void destroy() {
try {
jsonb.close();
} catch (final Exception e) {
// no-op
}
scheduledTask.cancel(true);
executor.shutdownNow();
try {
executor.awaitTermination(1, MINUTES);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
@Override
public void onEvent(final ZipkinSpan zipkinSpan) {
if (collector != null) {
if (spans == null) {
doSend(singletonList(zipkinSpan));
} else {
spans.add(zipkinSpan);
}
}
}
private void onEmit() {
final int size = this.spans.size();
final List<ZipkinSpan> copy = new ArrayList<>(size <= 0 ? maxSpansPerBulk : Math.min(size, maxSpansPerBulk));
int toSend = maxSpansIteration <= 0 ? size : Math.min(size, maxSpansIteration);
while (toSend > 0) {
this.spans.drainTo(copy, Math.min(toSend, maxSpansPerBulk));
if (copy.isEmpty()) {
break;
}
doSend(copy);
toSend -= copy.size();
copy.clear();
}
}
private void doSend(final List<ZipkinSpan> copy) {
final Response result = client.target(collector)
.request()
.post(entity(copy, APPLICATION_JSON_TYPE));
if (result.getStatus() >= 300) {
// todo: better handling but at least log them to not loose them completely or explode in memory
throw new IllegalStateException("Can't send to zipkin: " + copy);
}
}
}
| 6,319 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile/zipkin/ZipkinSpan.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.microprofile.zipkin;
import java.util.List;
import java.util.Map;
public class ZipkinSpan {
private Object traceId;
private Object parentId;
private Object id;
private String name;
private String kind;
private Long timestamp;
private Long duration;
private ZipkinEndpoint localEndpoint;
private ZipkinEndpoint remoteEndpoint;
private List<ZipkinAnnotation> annotations;
private Map<String, String> tags;
private Boolean debug;
private Boolean shared;
public Object getTraceId() {
return traceId;
}
public void setTraceId(final Object traceId) {
this.traceId = traceId;
}
public Object getParentId() {
return parentId;
}
public void setParentId(final Object parentId) {
this.parentId = parentId;
}
public Object getId() {
return id;
}
public void setId(final Object id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(final Long timestamp) {
this.timestamp = timestamp;
}
public Long getDuration() {
return duration;
}
public void setDuration(final Long duration) {
this.duration = duration;
}
public List<ZipkinAnnotation> getAnnotations() {
return annotations;
}
public void setAnnotations(final List<ZipkinAnnotation> annotations) {
this.annotations = annotations;
}
public Boolean getDebug() {
return debug;
}
public void setDebug(final Boolean debug) {
this.debug = debug;
}
public String getKind() {
return kind;
}
public void setKind(final String kind) {
this.kind = kind;
}
public ZipkinEndpoint getLocalEndpoint() {
return localEndpoint;
}
public void setLocalEndpoint(final ZipkinEndpoint localEndpoint) {
this.localEndpoint = localEndpoint;
}
public ZipkinEndpoint getRemoteEndpoint() {
return remoteEndpoint;
}
public void setRemoteEndpoint(final ZipkinEndpoint remoteEndpoint) {
this.remoteEndpoint = remoteEndpoint;
}
public Map<String, String> getTags() {
return tags;
}
public void setTags(final Map<String, String> tags) {
this.tags = tags;
}
public Boolean getShared() {
return shared;
}
public void setShared(final Boolean shared) {
this.shared = shared;
}
public static class ZipkinAnnotation {
private long timestamp;
private String value;
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(final long timestamp) {
this.timestamp = timestamp;
}
public String getValue() {
return value;
}
public void setValue(final String value) {
this.value = value;
}
}
public static class ZipkinBinaryAnnotation {
private String key;
private int type;
private Object value;
public String getKey() {
return key;
}
public void setKey(final String key) {
this.key = key;
}
public int getType() {
return type;
}
public void setType(final int type) {
this.type = type;
}
public Object getValue() {
return value;
}
public void setValue(final Object value) {
this.value = value;
}
}
public static class ZipkinEndpoint {
private String serviceName;
private String ipv4;
private String ipv6;
private int port;
public String getServiceName() {
return serviceName;
}
public void setServiceName(final String serviceName) {
this.serviceName = serviceName;
}
public String getIpv4() {
return ipv4;
}
public void setIpv4(final String ipv4) {
this.ipv4 = ipv4;
}
public String getIpv6() {
return ipv6;
}
public void setIpv6(final String ipv6) {
this.ipv6 = ipv6;
}
public int getPort() {
return port;
}
public void setPort(final int port) {
this.port = port;
}
}
}
| 6,320 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile/zipkin/ZipkinLogger.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.microprofile.zipkin;
import java.util.logging.Logger;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import org.apache.geronimo.microprofile.opentracing.common.config.GeronimoOpenTracingConfig;
import org.apache.geronimo.microprofile.opentracing.common.spi.Listener;
// this allows to integrate with any backend using appenders.
// @ApplicationScoped
public class ZipkinLogger implements Listener<ZipkinSpan> {
private final Logger spanLogger = Logger.getLogger("org.apache.geronimo.opentracing.zipkin");
private GeronimoOpenTracingConfig config;
private Jsonb jsonb;
private boolean wrapAsList;
public void setConfig(final GeronimoOpenTracingConfig config) {
this.config = config;
}
public void setJsonb(final Jsonb jsonb) {
this.jsonb = jsonb;
}
public void init() {
if (jsonb == null) {
jsonb = JsonbBuilder.create();
}
wrapAsList = Boolean.parseBoolean(config.read("span.converter.zipkin.logger.wrapAsList", "true"));
}
public Jsonb getJsonb() {
return jsonb;
}
public void destroy() {
try {
jsonb.close();
} catch (final Exception e) {
// no-op
}
}
@Override
public void onEvent(final ZipkinSpan zipkinSpan) {
final String json = jsonb.toJson(zipkinSpan);
spanLogger.info(wrapAsList ? '[' + json + ']' : json);
}
}
| 6,321 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile/zipkin/ZipkinConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.microprofile.zipkin;
import static java.util.Collections.emptyList;
import static java.util.Locale.ROOT;
import static java.util.Optional.ofNullable;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.geronimo.microprofile.opentracing.common.config.GeronimoOpenTracingConfig;
import org.apache.geronimo.microprofile.opentracing.common.impl.FinishedSpan;
import org.apache.geronimo.microprofile.opentracing.common.impl.IdGenerator;
import org.apache.geronimo.microprofile.opentracing.common.impl.SpanImpl;
import org.apache.geronimo.microprofile.opentracing.common.spi.Bus;
import org.apache.geronimo.microprofile.opentracing.common.spi.Listener;
import io.opentracing.Span;
import io.opentracing.tag.Tags;
// when writing this observer, opentracing has no standard propagation nor exchange format
// so falling back on zipkin
// @ApplicationScoped
public class ZipkinConverter implements Listener<FinishedSpan> {
private Bus<ZipkinSpan> zipkinSpanEvent;
private GeronimoOpenTracingConfig config;
private IdGenerator idGenerator;
private String serviceName;
private boolean useV2 = false;
public void setZipkinSpanEvent(final Bus<ZipkinSpan> zipkinSpanEvent) {
this.zipkinSpanEvent = zipkinSpanEvent;
}
public void setConfig(final GeronimoOpenTracingConfig config) {
this.config = config;
}
public void setIdGenerator(final IdGenerator idGenerator) {
this.idGenerator = idGenerator;
}
public void init() {
serviceName = config.read("zipkin.serviceName", getHostName() + "_" + getPid());
useV2 = Boolean.parseBoolean(config.read("span.converter.zipkin.http.useV2", "false").trim());
}
@Override
public void onEvent(final FinishedSpan finishedSpan) {
final Span from = finishedSpan.getSpan();
if (!SpanImpl.class.isInstance(from)) {
throw new IllegalStateException("Unsupported span type: " + from + ", maybe check your configuration");
}
zipkinSpanEvent.fire(toZipkin(SpanImpl.class.cast(from)));
}
private String getPid() {
return ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
}
private String getHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (final UnknownHostException e) {
return "server";
}
}
private ZipkinSpan toZipkin(final SpanImpl span) {
final ZipkinSpan.ZipkinEndpoint endpoint = toEndpoint(span);
final ZipkinSpan zipkin;
if (useV2) {
zipkin = new ZipkinSpan();
zipkin.setTags(span.getTags().entrySet().stream().filter(e -> !Tags.SPAN_KIND.getKey().equalsIgnoreCase(e.getKey()))
.collect(toMap(Map.Entry::getKey, e -> String.valueOf(e.getValue()))));
} else {
zipkin = new ZipkinV1Span();
((ZipkinV1Span) zipkin).setBinaryAnnotations(toBinaryAnnotations(span.getTags()));
zipkin.setAnnotations(toAnnotations(span));
}
if (idGenerator.isCounter()) {
zipkin.setParentId(asLong(span.getParentId()));
zipkin.setTraceId(asLong(span.getTraceId()));
zipkin.setId(asLong(span.getId()));
} else {
zipkin.setParentId(span.getParentId());
zipkin.setTraceId(span.getTraceId());
zipkin.setId(span.getId());
}
zipkin.setName(span.getName());
zipkin.setKind(ofNullable(span.getKind()).map(s -> s.toUpperCase(ROOT)).orElse(null));
zipkin.setTimestamp(span.getTimestamp());
zipkin.setDuration(span.getDuration());
if (Tags.SPAN_KIND_CLIENT.equals(String.valueOf(span.getTags().get(Tags.SPAN_KIND.getKey())))) {
zipkin.setRemoteEndpoint(endpoint);
}
zipkin.setLocalEndpoint(endpoint); // must alway exist
return zipkin;
}
private long asLong(final Object value) {
if (value == null) {
return 0;
}
if (Long.class.isInstance(value)) {
return Long.class.cast(value);
}
return Long.valueOf(String.valueOf(value));
}
private ZipkinSpan.ZipkinEndpoint toEndpoint(final SpanImpl span) {
final Map<String, Object> tags = span.getTags();
switch (String.valueOf(tags.get(Tags.SPAN_KIND.getKey()))) {
case Tags.SPAN_KIND_CLIENT: {
String ipv4 = (String) tags.get(Tags.PEER_HOST_IPV4.getKey());
String ipv6 = (String) tags.get(Tags.PEER_HOST_IPV6.getKey());
if (ipv4 == null && ipv6 == null && tags.containsKey(Tags.PEER_HOSTNAME.getKey())) {
try {
final String hostAddress = InetAddress.getByName(tags.get(Tags.PEER_HOSTNAME.getKey()).toString())
.getHostAddress();
if (hostAddress.contains("::")) {
ipv6 = hostAddress;
} else {
ipv4 = hostAddress;
}
} catch (final UnknownHostException e) {
// no-op
}
}
final Integer port = (Integer) tags.get(Tags.PEER_PORT.getKey());
final ZipkinSpan.ZipkinEndpoint endpoint = new ZipkinSpan.ZipkinEndpoint();
endpoint.setServiceName(serviceName);
endpoint.setIpv4(ipv4);
endpoint.setIpv6(ipv6);
endpoint.setPort(port == null ? 0 : port);
return endpoint;
}
case Tags.SPAN_KIND_SERVER: {
final String url = (String) tags.get(Tags.HTTP_URL.getKey());
String ipv4 = null;
String ipv6 = null;
Integer port = null;
if (url != null) {
try {
final URL asUrl = new URL(url);
port = asUrl.getPort();
final String host = asUrl.getHost();
final String hostAddress = host.contains(":") ? host : InetAddress.getByName(host).getHostAddress();
if (hostAddress.contains("::")) {
ipv6 = hostAddress;
} else {
ipv4 = hostAddress;
}
} catch (final UnknownHostException | MalformedURLException e) {
// no-op
}
}
final ZipkinSpan.ZipkinEndpoint endpoint = new ZipkinSpan.ZipkinEndpoint();
endpoint.setServiceName(serviceName);
endpoint.setIpv4(ipv4);
endpoint.setIpv6(ipv6);
endpoint.setPort(port == null ? 0 : port);
return endpoint;
}
default:
return null;
}
}
private List<ZipkinSpan.ZipkinAnnotation> toAnnotations(final SpanImpl span) {
final Map<String, Object> tags = span.getTags();
final List<ZipkinSpan.ZipkinAnnotation> annotations = new ArrayList<>(2);
switch (String.valueOf(tags.get(Tags.SPAN_KIND.getKey()))) {
case Tags.SPAN_KIND_CLIENT: {
{
final ZipkinSpan.ZipkinAnnotation clientSend = new ZipkinSpan.ZipkinAnnotation();
clientSend.setValue("cs");
clientSend.setTimestamp(span.getTimestamp());
annotations.add(clientSend);
}
{
final ZipkinSpan.ZipkinAnnotation clientReceived = new ZipkinSpan.ZipkinAnnotation();
clientReceived.setValue("cr");
clientReceived.setTimestamp(span.getTimestamp() + span.getDuration());
annotations.add(clientReceived);
}
return annotations;
}
case Tags.SPAN_KIND_SERVER: {
{
final ZipkinSpan.ZipkinAnnotation serverReceived = new ZipkinSpan.ZipkinAnnotation();
serverReceived.setValue("sr");
serverReceived.setTimestamp(span.getTimestamp());
annotations.add(serverReceived);
}
{
final ZipkinSpan.ZipkinAnnotation serverSend = new ZipkinSpan.ZipkinAnnotation();
serverSend.setValue("ss");
serverSend.setTimestamp(span.getTimestamp() + span.getDuration());
annotations.add(serverSend);
}
return annotations;
}
default:
return emptyList();
}
}
private List<ZipkinSpan.ZipkinBinaryAnnotation> toBinaryAnnotations(final Map<String, Object> tags) {
return tags.entrySet().stream().map(tag -> {
final ZipkinSpan.ZipkinBinaryAnnotation annotations = new ZipkinSpan.ZipkinBinaryAnnotation();
annotations.setType(findAnnotationType(tag.getValue()));
annotations.setKey(tag.getKey());
annotations.setValue(tag.getValue());
return annotations;
}).collect(toList());
}
private int findAnnotationType(final Object value) {
if (String.class.isInstance(value)) {
return 6;
}
if (Double.class.isInstance(value)) {
return 5;
}
if (Long.class.isInstance(value)) {
return 4;
}
if (Integer.class.isInstance(value)) {
return 3;
}
if (Short.class.isInstance(value)) {
return 2;
}
if (Byte.class.isInstance(value)) {
return 1;
}
return 6; // todo?
}
}
| 6,322 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile/zipkin/ZipkinV1Span.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.microprofile.zipkin;
import java.util.List;
public class ZipkinV1Span extends ZipkinSpan {
private List<ZipkinBinaryAnnotation> binaryAnnotations;
public List<ZipkinBinaryAnnotation> getBinaryAnnotations() {
return binaryAnnotations;
}
public void setBinaryAnnotations(final List<ZipkinBinaryAnnotation> binaryAnnotations) {
this.binaryAnnotations = binaryAnnotations;
}
}
| 6,323 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile/thread/OpenTracingExecutorService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.microprofile.thread;
import static java.util.stream.Collectors.toList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import io.opentracing.Tracer;
public class OpenTracingExecutorService implements ExecutorService {
private final ExecutorService delegate;
private final Tracer tracer;
public OpenTracingExecutorService(final ExecutorService executorService, final Tracer tracer) {
this.delegate = executorService;
this.tracer = tracer;
}
@Override
public void shutdown() {
delegate.shutdown();
}
@Override
public List<Runnable> shutdownNow() {
return delegate.shutdownNow();
}
@Override
public boolean isShutdown() {
return delegate.isShutdown();
}
@Override
public boolean isTerminated() {
return delegate.isTerminated();
}
@Override
public boolean awaitTermination(final long timeout, final TimeUnit unit) throws InterruptedException {
return delegate.awaitTermination(timeout, unit);
}
@Override
public <T> Future<T> submit(final Callable<T> task) {
return delegate.submit(wrap(task));
}
@Override
public <T> Future<T> submit(final Runnable task, final T result) {
return delegate.submit(wrap(task), result);
}
@Override
public Future<?> submit(final Runnable task) {
return delegate.submit(wrap(task));
}
@Override
public <T> List<Future<T>> invokeAll(final Collection<? extends Callable<T>> tasks) throws InterruptedException {
return delegate.invokeAll(tasks.stream().map(this::wrap).collect(toList()));
}
@Override
public <T> List<Future<T>> invokeAll(final Collection<? extends Callable<T>> tasks, final long timeout, final TimeUnit unit)
throws InterruptedException {
return delegate.invokeAll(tasks.stream().map(this::wrap).collect(toList()), timeout, unit);
}
@Override
public <T> T invokeAny(final Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException {
return delegate.invokeAny(tasks.stream().map(this::wrap).collect(toList()));
}
@Override
public <T> T invokeAny(final Collection<? extends Callable<T>> tasks, final long timeout, final TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return delegate.invokeAny(tasks.stream().map(this::wrap).collect(toList()), timeout, unit);
}
@Override
public void execute(final Runnable command) {
delegate.execute(wrap(command));
}
private Runnable wrap(final Runnable task) {
final ScopePropagatingCallable<Void> decorator = new ScopePropagatingCallable<>(() -> {
task.run();
return null;
}, tracer);
return () -> {
try {
decorator.call();
} catch (final RuntimeException | Error e) {
throw e;
} catch (final Exception e) { // unlikely since that's a Runnable
throw new IllegalStateException(e);
}
};
}
private <T> Callable<T> wrap(final Callable<T> task) {
return new ScopePropagatingCallable<>(task, tracer);
}
}
| 6,324 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile/thread/ScopePropagatingCallable.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.microprofile.thread;
import java.util.concurrent.Callable;
import io.opentracing.Span;
import io.opentracing.Tracer;
import io.opentracing.tag.Tags;
public class ScopePropagatingCallable<B> implements Callable<B> {
private final Callable<B> delegate;
private final Tracer tracer;
public ScopePropagatingCallable(final Callable<B> delegate, final Tracer tracer) {
this.delegate = delegate;
this.tracer = tracer;
}
private Span before() {
return tracer.activeSpan();
}
private void after(final Span span, final RuntimeException error) {
if (span != null && error != null) {
Tags.ERROR.set(span, true);
if (error.getMessage() != null) {
span.setTag("errorMessage", error.getMessage());
span.setTag("errorType", error.getClass().getName());
}
}
}
@Override
public B call() throws Exception {
RuntimeException error = null;
final Span span = before();
try {
return delegate.call();
} catch (final RuntimeException re) {
error = re;
throw re;
} finally {
after(span, error);
}
}
}
| 6,325 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile/client/GeronimoClientTracingRegistrarProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.microprofile.client;
import java.util.concurrent.ExecutorService;
import javax.ws.rs.client.ClientBuilder;
import org.apache.geronimo.microprofile.opentracing.common.microprofile.thread.OpenTracingExecutorService;
import org.apache.geronimo.microprofile.opentracing.common.spi.Container;
import org.eclipse.microprofile.opentracing.ClientTracingRegistrarProvider;
import io.opentracing.Tracer;
public class GeronimoClientTracingRegistrarProvider implements ClientTracingRegistrarProvider {
private final OpenTracingClientRequestFilter requestFilter;
private final OpenTracingClientResponseFilter responseFilter;
private final Tracer tracer;
public GeronimoClientTracingRegistrarProvider() {
final Container container = Container.get();
requestFilter = container.lookup(OpenTracingClientRequestFilter.class);
responseFilter = container.lookup(OpenTracingClientResponseFilter.class);
tracer = container.lookup(Tracer.class);
}
@Override
public ClientBuilder configure(final ClientBuilder builder) {
return configure(builder, new SyncExecutor());
}
@Override
public ClientBuilder configure(final ClientBuilder builder, final ExecutorService executorService) {
if (builder.getConfiguration().getInstances().stream().anyMatch(it -> requestFilter == it)) {
return builder;
}
return builder.register(requestFilter).register(responseFilter)
.executorService(wrapExecutor(executorService));
}
private ExecutorService wrapExecutor(final ExecutorService executorService) {
if (OpenTracingExecutorService.class.isInstance(executorService)) {
return executorService;
}
return new OpenTracingExecutorService(executorService, tracer);
}
}
| 6,326 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile/client/OpenTracingClientRequestFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.microprofile.client;
import static io.opentracing.References.CHILD_OF;
import static java.util.Optional.ofNullable;
import java.util.function.Consumer;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import org.apache.geronimo.microprofile.opentracing.common.config.GeronimoOpenTracingConfig;
import org.apache.geronimo.microprofile.opentracing.common.impl.JaxRsHeaderTextMap;
import io.opentracing.Scope;
import io.opentracing.Span;
import io.opentracing.SpanContext;
import io.opentracing.Tracer;
import io.opentracing.propagation.Format;
import io.opentracing.tag.Tags;
// @ApplicationScoped
public class OpenTracingClientRequestFilter implements ClientRequestFilter {
private Tracer tracer;
private GeronimoOpenTracingConfig config;
private boolean skip;
private boolean skipDefaultTags;
private boolean skipPeerTags;
public void init() {
skip = Boolean.parseBoolean(config.read("client.filter.request.skip", "false"));
skipDefaultTags = Boolean.parseBoolean(config.read("client.filter.request.skipDefaultTags", "false"));
skipPeerTags = Boolean.parseBoolean(config.read("client.filter.request.skipPeerTags", "false"));
}
public void setTracer(final Tracer tracer) {
this.tracer = tracer;
}
public void setConfig(final GeronimoOpenTracingConfig config) {
this.config = config;
}
@Override
public void filter(final ClientRequestContext context) {
if (context.getProperty(OpenTracingClientRequestFilter.class.getName()) != null || skip) {
return;
}
final Tracer.SpanBuilder builder = tracer.buildSpan(context.getMethod());
builder.withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT);
builder.withTag("component", "jaxrs");
ofNullable(SpanContext.class.cast(context.getProperty(CHILD_OF)))
.ifPresent(parent -> builder.ignoreActiveSpan().asChildOf(parent));
final Scope scope = builder.startActive(true);
final Span span = scope.span();
if (!skipDefaultTags) {
Tags.HTTP_METHOD.set(span, context.getMethod());
Tags.HTTP_URL.set(span, context.getUri().toASCIIString());
}
if (!skipPeerTags) {
final String host = context.getUri().getHost();
Tags.PEER_HOSTNAME.set(span, host);
Tags.PEER_PORT.set(span, context.getUri().getPort());
}
// customization point
ofNullable(context.getProperty("org.apache.geronimo.microprofile.opentracing.spanConsumer"))
.ifPresent(consumer -> Consumer.class.cast(consumer).accept(span));
tracer.inject(span.context(), Format.Builtin.HTTP_HEADERS, new JaxRsHeaderTextMap<>(context.getHeaders()));
context.setProperty(OpenTracingClientRequestFilter.class.getName(), scope);
}
}
| 6,327 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile/client/SyncExecutor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.microprofile.client;
import static java.util.Collections.emptyList;
import java.util.List;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class SyncExecutor extends AbstractExecutorService {
private volatile boolean shutdown;
private final CountDownLatch latch = new CountDownLatch(1);
@Override
public void shutdown() {
shutdown = true;
latch.countDown();
}
@Override
public List<Runnable> shutdownNow() {
return emptyList();
}
@Override
public boolean isShutdown() {
return shutdown;
}
@Override
public boolean isTerminated() {
return shutdown;
}
@Override
public boolean awaitTermination(final long timeout, final TimeUnit unit) {
try {
return latch.await(timeout, unit);
} catch (final InterruptedException e) {
return false;
}
}
@Override
public void execute(final Runnable command) {
command.run();
}
}
| 6,328 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing-common/src/main/java/org/apache/geronimo/microprofile/opentracing/common/microprofile/client/OpenTracingClientResponseFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.common.microprofile.client;
import static java.util.Optional.ofNullable;
import javax.annotation.Priority;
import javax.ws.rs.Priorities;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientResponseContext;
import javax.ws.rs.client.ClientResponseFilter;
import io.opentracing.Scope;
import io.opentracing.tag.Tags;
// @ApplicationScoped
@Priority(Priorities.HEADER_DECORATOR)
public class OpenTracingClientResponseFilter implements ClientResponseFilter {
@Override
public void filter(final ClientRequestContext req, final ClientResponseContext resp) {
ofNullable(req.getProperty(OpenTracingClientRequestFilter.class.getName())).map(Scope.class::cast)
.ifPresent(scope -> {
Tags.HTTP_STATUS.set(scope.span(), resp.getStatus());
scope.close();
});
}
}
| 6,329 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing/src/test/java/org/apache/geronimo/microprofile/opentracing/tck | Create_ds/geronimo-opentracing/geronimo-opentracing/src/test/java/org/apache/geronimo/microprofile/opentracing/tck/setup/TckTracer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.tck.setup;
import static java.util.stream.Collectors.toList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Map;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.Specializes;
import org.apache.geronimo.microprofile.opentracing.common.impl.FinishedSpan;
import org.apache.geronimo.microprofile.opentracing.common.impl.SpanContextImpl;
import org.apache.geronimo.microprofile.opentracing.common.impl.SpanImpl;
import org.apache.geronimo.microprofile.opentracing.impl.CdiGeronimoTracer;
import io.opentracing.Span;
import io.opentracing.SpanContext;
// compat for TCK which assume the MockTracer impl for validations
@Specializes
@ApplicationScoped
public class TckTracer extends CdiGeronimoTracer {
private final Collection<Span> spans = new LinkedHashSet<>();
synchronized void onSpan(@Observes final FinishedSpan span) {
spans.add(span.getSpan());
}
public synchronized Iterable<Span> finishedSpans() {
return new ArrayList<>(spans);
}
public synchronized void reset() {
spans.clear();
}
@Override
protected SpanContextImpl newContext(final Object traceId, final Object parentSpanId,
final Object spanId, final Map<String, String> baggages) {
return new TckSpanContext(traceId, parentSpanId, spanId, baggages);
}
@Override
protected Span processNewSpan(final SpanImpl span) {
return new TckSpan(span);
}
public static class TckSpan extends SpanImpl {
private final SpanImpl delegate;
public TckSpan(final SpanImpl delegate) {
super(delegate.getName(), delegate.getTimestamp(), delegate.getReferences(), delegate.getTags(), ignored -> {}, SpanContextImpl.class.cast(delegate.context()));
this.delegate = delegate;
}
@Override
public Span log(final long timestampMicroseconds, final Map<String, ?> fields) {
return delegate.log(timestampMicroseconds, fields);
}
@Override
public SpanContext context() {
return delegate.context();
}
@Override
public Span log(final long timestampMicroseconds, final String event) {
return delegate.log(timestampMicroseconds, event);
}
@Override
public void finish() {
delegate.finish();
}
@Override
public void finish(final long finishMicros) {
delegate.finish(finishMicros);
}
@Override
public Span setTag(final String key, final String value) {
return delegate.setTag(key, value);
}
@Override
public Span setTag(final String key, final boolean value) {
return delegate.setTag(key, value);
}
@Override
public Span setTag(final String key, final Number value) {
return delegate.setTag(key, value);
}
@Override
public Span log(final Map<String, ?> fields) {
return delegate.log(fields);
}
@Override
public Span log(final String event) {
return delegate.log(event);
}
@Override
public Span setBaggageItem(final String key, final String value) {
return delegate.setBaggageItem(key, value);
}
@Override
public String getBaggageItem(final String key) {
return delegate.getBaggageItem(key);
}
@Override
public Span setOperationName(final String operationName) {
return delegate.setOperationName(operationName);
}
public long startMicros() {
return delegate.getTimestamp();
}
public long finishMicros() {
return delegate.getTimestamp() + delegate.getDuration();
}
public String operationName() {
return delegate.getName();
}
public Object parentId() {
return delegate.getParentId() == null ? 0L : Long.parseLong(delegate.getParentId().toString());
}
public Map<String, Object> tags() {
return delegate.getTags();
}
public Collection<SpanImpl.Log> logEntries() {
return delegate.getLogs().stream()
.map(l -> new TckLog(l.getTimestampMicros(), l.getFields()))
.collect(toList());
}
}
public static class TckLog extends SpanImpl.Log {
public TckLog(final long timestampMicros, final Map<String, ?> fields) {
super(timestampMicros, fields);
}
public Map<String, ?> fields() {
return getFields();
}
}
public static class TckSpanContext extends SpanContextImpl {
private TckSpanContext(final Object traceId, final Object parentSpanId, final Object spanId, final Map<String, String> baggages) {
super(traceId, parentSpanId, spanId, baggages);
}
public Object traceId() {
final Object traceId = getTraceId();
return traceId == null ? 0L : Long.parseLong(traceId.toString());
}
public Object parentSpanId() {
final Object spanId = getParentSpanId();
return spanId == null ? 0L : Long.parseLong(spanId.toString());
}
public Object spanId() {
final Object spanId = getSpanId();
return spanId == null ? 0L : Long.parseLong(spanId.toString());
}
}
}
| 6,330 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing/src/test/java/org/apache/geronimo/microprofile/opentracing/tck | Create_ds/geronimo-opentracing/geronimo-opentracing/src/test/java/org/apache/geronimo/microprofile/opentracing/tck/setup/SkipOpentracingApiSetup.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.tck.setup;
import org.jboss.arquillian.container.spi.event.container.BeforeDeploy;
import org.jboss.arquillian.core.api.annotation.Observes;
import org.jboss.arquillian.core.spi.LoadableExtension;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.Filters;
import org.jboss.shrinkwrap.api.Node;
import java.util.Collection;
// the tck put the opentracing-api in the war but not our impl, let's fix it by using the apploader api jar!
public class SkipOpentracingApiSetup implements LoadableExtension {
@Override
public void register(final ExtensionBuilder builder) {
builder.observer(Impl.class);
}
public static class Impl {
public void clean(@Observes final BeforeDeploy beforeDeploy) {
final Archive<?> archive = beforeDeploy.getDeployment().getArchive();
final Collection<Node> opentracingApi = archive.getContent(Filters.include("\\/WEB-INF\\/lib\\/opentracing\\-api\\-.*\\.jar")).values();
if (opentracingApi != null && !opentracingApi.isEmpty()) {
archive.delete(opentracingApi.iterator().next().getPath());
}
}
}
}
| 6,331 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing/src/test/java/org/apache/geronimo/microprofile/opentracing/tck | Create_ds/geronimo-opentracing/geronimo-opentracing/src/test/java/org/apache/geronimo/microprofile/opentracing/tck/setup/ZipkinRule.java | /*
* Copyright 2015-2018 The OpenZipkin Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geronimo.microprofile.opentracing.tck.setup;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import okhttp3.HttpUrl;
import okhttp3.mockwebserver.Dispatcher;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import okio.Buffer;
import okio.GzipSource;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import zipkin2.Callback;
import zipkin2.DependencyLink;
import zipkin2.Span;
import zipkin2.codec.SpanBytesDecoder;
import zipkin2.collector.Collector;
import zipkin2.collector.CollectorMetrics;
import zipkin2.collector.InMemoryCollectorMetrics;
import zipkin2.internal.Nullable;
import zipkin2.internal.Platform;
import zipkin2.junit.HttpFailure;
import zipkin2.storage.InMemoryStorage;
import zipkin2.storage.StorageComponent;
import static okhttp3.mockwebserver.SocketPolicy.KEEP_OPEN;
/**
* Starts up a local Zipkin server, listening for http requests on {@link #httpUrl}.
*
* <p>This can be used to test instrumentation. For example, you can POST spans directly to this
* server.
*
* <p>See http://openzipkin.github.io/zipkin-api/#/
*/
public final class ZipkinRule implements TestRule {
private final InMemoryStorage storage = InMemoryStorage.newBuilder().build();
private final InMemoryCollectorMetrics metrics = new InMemoryCollectorMetrics();
private final MockWebServer server = new MockWebServer();
private final BlockingQueue<MockResponse> failureQueue = new LinkedBlockingQueue<>();
private final AtomicInteger receivedSpanBytes = new AtomicInteger();
public ZipkinRule() {
Dispatcher dispatcher =
new Dispatcher() {
final ZipkinDispatcher successDispatch = new ZipkinDispatcher(storage, metrics, server);
@Override
public MockResponse dispatch(RecordedRequest request) {
MockResponse maybeFailure = failureQueue.poll();
if (maybeFailure != null) return maybeFailure;
MockResponse result = successDispatch.dispatch(request);
if (request.getMethod().equals("POST")) {
receivedSpanBytes.addAndGet((int) request.getBodySize());
}
return result;
}
@Override
public MockResponse peek() {
MockResponse maybeFailure = failureQueue.peek();
if (maybeFailure != null) return maybeFailure.clone();
return new MockResponse().setSocketPolicy(KEEP_OPEN);
}
};
server.setDispatcher(dispatcher);
}
/** Use this to connect. The zipkin v1 interface will be under "/api/v1" */
public String httpUrl() {
return String.format("http://%s:%s", server.getHostName(), server.getPort());
}
/** Use this to see how many requests you've sent to any zipkin http endpoint. */
public int httpRequestCount() {
return server.getRequestCount();
}
/** Use this to see how many spans or serialized bytes were collected on the http endpoint. */
public InMemoryCollectorMetrics collectorMetrics() {
return metrics;
}
/** Retrieves all traces this zipkin server has received. */
public List<List<Span>> getTraces() {
return storage.spanStore().getTraces();
}
/** Retrieves a trace by ID which zipkin server has received, or null if not present. */
@Nullable
public List<Span> getTrace(String traceId) {
try {
return storage.spanStore().getTrace(traceId).execute();
} catch (IOException e) {
throw Platform.get().assertionError("I/O exception in in-memory storage", e);
}
}
/** Retrieves all service links between traces this zipkin server has received. */
public List<DependencyLink> getDependencies() {
return storage.spanStore().getDependencies();
}
/**
* Used to manually start the server.
*
* @param httpPort choose 0 to select an available port
*/
public void start(int httpPort) throws IOException {
server.start(httpPort);
}
/** Used to manually stop the server. */
public void shutdown() throws IOException {
server.shutdown();
}
@Override
public Statement apply(Statement base, Description description) {
return server.apply(base, description);
}
final class ZipkinDispatcher extends Dispatcher {
private final Collector consumer;
private final CollectorMetrics metrics;
private final MockWebServer server;
ZipkinDispatcher(StorageComponent storage, CollectorMetrics metrics, MockWebServer server) {
this.consumer = Collector.newBuilder(getClass()).storage(storage).metrics(metrics).build();
this.metrics = metrics;
this.server = server;
}
@Override
public MockResponse dispatch(RecordedRequest request) {
HttpUrl url = server.url(request.getPath());
if (request.getMethod().equals("POST")) {
String type = request.getHeader("Content-Type");
if (url.encodedPath().equals("/api/v1/spans")) {
SpanBytesDecoder decoder =
type != null && type.contains("/x-thrift")
? SpanBytesDecoder.THRIFT
: SpanBytesDecoder.JSON_V1;
return acceptSpans(request, decoder);
} else if (url.encodedPath().equals("/api/v2/spans")) {
SpanBytesDecoder decoder =
type != null && type.contains("/x-protobuf")
? SpanBytesDecoder.PROTO3
: SpanBytesDecoder.JSON_V2;
return acceptSpans(request, decoder);
}
} else { // unsupported method
return new MockResponse().setResponseCode(405);
}
return new MockResponse().setResponseCode(404);
}
MockResponse acceptSpans(RecordedRequest request, SpanBytesDecoder decoder) {
metrics.incrementMessages();
byte[] body = request.getBody().readByteArray();
// check for the presence of binaryAnnotations, which should not be present in V2.
// @see ZipkinHttpCollector.testForUnexpectedFormat
if (SpanBytesDecoder.JSON_V2.equals(decoder) &&
new String(body).contains("\"binaryAnnotations\"")) {
final MockResponse mockResponse = new MockResponse();
mockResponse.setResponseCode(400);
mockResponse.setBody("Expected a JSON_V2 encoded list, but received: JSON_V1\n");
return mockResponse;
}
String encoding = request.getHeader("Content-Encoding");
if (encoding != null && encoding.contains("gzip")) {
try {
Buffer result = new Buffer();
GzipSource source = new GzipSource(new Buffer().write(body));
while (source.read(result, Integer.MAX_VALUE) != -1) ;
body = result.readByteArray();
} catch (IOException e) {
metrics.incrementMessagesDropped();
return new MockResponse().setResponseCode(400).setBody("Cannot gunzip spans");
}
}
final MockResponse result = new MockResponse();
consumer.acceptSpans(
body,
decoder,
new Callback<Void>() {
@Override
public void onSuccess(Void value) {
result.setResponseCode(202);
}
@Override
public void onError(Throwable t) {
String message = t.getMessage();
result.setBody(message).setResponseCode(message.startsWith("Cannot store") ? 500 : 400);
}
});
return result;
}
}
}
| 6,332 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing/src/test/java/org/apache/geronimo/microprofile/opentracing/tck | Create_ds/geronimo-opentracing/geronimo-opentracing/src/test/java/org/apache/geronimo/microprofile/opentracing/tck/setup/UseGeronimoTracerExtension.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.tck.setup;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.Extension;
import javax.enterprise.inject.spi.ProcessAnnotatedType;
public class UseGeronimoTracerExtension implements Extension {
void vetoTckTracerIfScanned(@Observes final ProcessAnnotatedType<TckTracer> tckTracer) {
tckTracer.veto();
}
}
| 6,333 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing/src/test/java/org/apache/geronimo/microprofile/opentracing/tck | Create_ds/geronimo-opentracing/geronimo-opentracing/src/test/java/org/apache/geronimo/microprofile/opentracing/tck/setup/SimpleService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.tck.setup;
import org.eclipse.microprofile.opentracing.Traced;
import javax.enterprise.context.RequestScoped;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Traced
@RequestScoped
@Path("hello")
public class SimpleService {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String sayHello() throws Exception {
return "Hello, world!";
}
}
| 6,334 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing/src/test/java/org/apache/geronimo/microprofile/opentracing/tck | Create_ds/geronimo-opentracing/geronimo-opentracing/src/test/java/org/apache/geronimo/microprofile/opentracing/tck/setup/BasicZipkinTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.tck.setup;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.arquillian.testng.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.ClassLoaderAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import zipkin2.Span;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import java.net.URL;
import java.util.List;
public class BasicZipkinTest extends Arquillian {
@Deployment
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class)
.addClasses(SimpleService.class)
.addAsWebInfResource(new ClassLoaderAsset("test-beans.xml"), "beans.xml")
.addAsServiceProvider(javax.enterprise.inject.spi.Extension.class, UseGeronimoTracerExtension.class);
}
private ZipkinRule zipkin;
@ArquillianResource
private URL serviceUrl;
@BeforeMethod
public void configure() {
}
@BeforeSuite
public void setup() {
zipkin = new ZipkinRule();
System.setProperty("geronimo.opentracing.span.converter.zipkin.sender", "http");
System.setProperty("geronimo.opentracing.span.converter.zipkin.http.collector", zipkin.httpUrl() + "/api/v2/spans");
System.setProperty("geronimo.opentracing.span.converter.zipkin.http.bulkSendInterval", "6000");
System.setProperty("geronimo.opentracing.span.converter.zipkin.http.maxSpansPerBulk", "1");
System.setProperty("geronimo.opentracing.span.converter.zipkin.http.maxSpansIteration","1");
System.setProperty("geronimo.opentracing.span.converter.zipkin.http.bufferSize","1");
System.setProperty("geronimo.opentracing.span.converter.zipkin.http.useV2","true");
}
/**
* Test that server endpoint is adding standard tags
*/
@Test
@RunAsClient
public void testSimpleService() throws Exception {
Client client = ClientBuilder.newClient();
String url = serviceUrl.toExternalForm() + "hello";
WebTarget target = client.target(url);
Response response = target.request().get();
if (response.getStatus() != 200) {
String unexpectedResponse = response.readEntity(String.class);
Assert.fail("Expected HTTP response code 200 but received " + response.getStatus() + "; Response: " + unexpectedResponse);
}
Thread.sleep(10000);
final List<List<Span>> traces = zipkin.getTraces();
Assert.assertTrue(traces.size() > 0, "Expected some traces");
}
}
| 6,335 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing/package-info.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// give a handle to the package, no other usage
package org.apache.geronimo.microprofile.opentracing; | 6,336 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing/impl/CdiGeronimoTracer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.impl;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import org.apache.geronimo.microprofile.opentracing.common.config.GeronimoOpenTracingConfig;
import org.apache.geronimo.microprofile.opentracing.common.impl.FinishedSpan;
import org.apache.geronimo.microprofile.opentracing.common.impl.GeronimoTracer;
import org.apache.geronimo.microprofile.opentracing.common.impl.IdGenerator;
import io.opentracing.ScopeManager;
@ApplicationScoped
public class CdiGeronimoTracer extends GeronimoTracer {
@Inject
private ScopeManager scopeManager;
@Inject
private IdGenerator idGenerator;
@Inject
private Event<FinishedSpan> finishedSpanEvent;
@Inject
private GeronimoOpenTracingConfig config;
@PostConstruct
public void init() {
setConfig(config);
setIdGenerator(idGenerator);
setScopeManager(scopeManager);
setFinishedSpanEvent(finishedSpanEvent::fire);
super.init();
}
}
| 6,337 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing/impl/CdiIdGenerator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.impl;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import org.apache.geronimo.microprofile.opentracing.common.config.GeronimoOpenTracingConfig;
import org.apache.geronimo.microprofile.opentracing.common.impl.IdGenerator;
@ApplicationScoped
public class CdiIdGenerator extends IdGenerator {
@Inject
private GeronimoOpenTracingConfig config;
@Override
@PostConstruct
public void init() {
setConfig(config);
super.init();
}
}
| 6,338 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing/impl/CdiContainer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.impl;
import javax.enterprise.inject.spi.CDI;
import org.apache.geronimo.microprofile.opentracing.common.spi.Container;
public class CdiContainer implements Container {
private final CDI<Object> cdi;
public CdiContainer() {
cdi = CDI.current();
}
@Override
public <T> T lookup(final Class<T> type) {
return cdi.select(type).get();
}
}
| 6,339 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing/impl/CdiScopeManagerImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.impl;
import javax.enterprise.context.ApplicationScoped;
import org.apache.geronimo.microprofile.opentracing.common.impl.ScopeManagerImpl;
@ApplicationScoped
public class CdiScopeManagerImpl extends ScopeManagerImpl {
}
| 6,340 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing/config/OpenTracingConfigMpConfigImpl.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.config;
import javax.enterprise.inject.Vetoed;
import org.apache.geronimo.microprofile.opentracing.common.config.GeronimoOpenTracingConfig;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.ConfigProvider;
@Vetoed
public class OpenTracingConfigMpConfigImpl implements GeronimoOpenTracingConfig {
private final Config config;
public OpenTracingConfigMpConfigImpl() {
config = ConfigProvider.getConfig();
}
@Override
public String read(final String key, final String def) {
return config.getOptionalValue(key, String.class).orElse(def);
}
}
| 6,341 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing/microprofile/server/CdiGeronimoOpenTracingFeature.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.microprofile.server;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import javax.ws.rs.ext.Provider;
import org.apache.geronimo.microprofile.opentracing.common.config.GeronimoOpenTracingConfig;
import org.apache.geronimo.microprofile.opentracing.common.microprofile.server.GeronimoOpenTracingFeature;
import io.opentracing.Tracer;
@Provider
@Dependent
public class CdiGeronimoOpenTracingFeature extends GeronimoOpenTracingFeature {
@Inject
@Override
public void setTracer(final Tracer tracer) {
super.setTracer(tracer);
}
@Inject
@Override
public void setConfig(final GeronimoOpenTracingConfig config) {
super.setConfig(config);
}
}
| 6,342 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing/microprofile/cdi/TracedInterceptor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.microprofile.cdi;
import static java.util.Collections.singletonMap;
import static java.util.Objects.requireNonNull;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.annotation.Priority;
import javax.enterprise.inject.Intercepted;
import javax.enterprise.inject.spi.AnnotatedType;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import org.eclipse.microprofile.opentracing.Traced;
import io.opentracing.Scope;
import io.opentracing.Span;
import io.opentracing.Tracer;
import io.opentracing.tag.Tags;
@Traced
@Interceptor
@Priority(Interceptor.Priority.LIBRARY_BEFORE)
public class TracedInterceptor implements Serializable {
@Inject
private Tracer tracer;
@Inject
@Intercepted
private Bean<?> bean;
@Inject
private BeanManager beanManager;
private transient ConcurrentMap<Method, Meta> metas = new ConcurrentHashMap<>();
@AroundInvoke
public Object trace(final InvocationContext context) throws Exception {
final Method method = context.getMethod();
Meta meta = metas.get(method);
if (meta == null) {
final AnnotatedType<?> annotatedType = beanManager.createAnnotatedType(bean.getBeanClass());
final Traced traced = requireNonNull(annotatedType.getMethods().stream()
.filter(m -> m.getJavaMember().equals(method))
.findFirst().map(m -> m.getAnnotation(Traced.class))
.orElseGet(() -> annotatedType.getAnnotation(Traced.class)), "no @Traced found on " + method);
meta = new Meta(
traced.value(),
Optional.of(traced.operationName())
.filter(v -> !v.isEmpty())
.orElseGet(() -> method.getDeclaringClass().getName() + "." + method.getName()));
metas.putIfAbsent(method, meta); // no big deal to not use the same meta instance
}
if (!meta.traced) {
return context.proceed();
}
final Tracer.SpanBuilder spanBuilder = tracer.buildSpan(meta.operationName);
final Scope parent = tracer.scopeManager().active();
if (parent != null) {
spanBuilder.asChildOf(parent.span());
}
Scope scope = null;
try {
scope = spanBuilder.startActive(true);
return context.proceed();
} catch (final RuntimeException re) {
if (scope != null) {
final Span span = scope.span();
Tags.ERROR.set(span, true);
final Map<String, Object> logs = new LinkedHashMap<>();
logs.put("event", Tags.ERROR.getKey());
logs.put("error.object", re);
span.log(logs);
}
throw re;
} finally {
if (scope != null) {
scope.close();
}
}
}
private static class Meta {
private final boolean traced;
private final String operationName;
private Meta(final boolean traced, final String name) {
this.traced = traced;
this.operationName = name;
}
}
}
| 6,343 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing/microprofile/cdi/TracedExecutorServiceInterceptor.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.microprofile.cdi;
import java.io.Serializable;
import javax.annotation.Priority;
import javax.inject.Inject;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import org.apache.geronimo.microprofile.opentracing.common.microprofile.thread.ScopePropagatingCallable;
import io.opentracing.Tracer;
@Interceptor
@TracedExecutorService
@Priority(Interceptor.Priority.LIBRARY_AFTER)
public class TracedExecutorServiceInterceptor implements Serializable {
@Inject
private Tracer tracer;
public Object around(final InvocationContext context) throws Exception {
return new ScopePropagatingCallable<>(context::proceed, tracer).call();
}
}
| 6,344 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing/microprofile/cdi/OpenTracingExtension.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.microprofile.cdi;
import java.lang.reflect.Type;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.Default;
import javax.enterprise.inject.spi.AfterBeanDiscovery;
import javax.enterprise.inject.spi.AnnotatedMethod;
import javax.enterprise.inject.spi.AnnotatedType;
import javax.enterprise.inject.spi.BeforeBeanDiscovery;
import javax.enterprise.inject.spi.Extension;
import javax.enterprise.inject.spi.ProcessAnnotatedType;
import javax.enterprise.inject.spi.WithAnnotations;
import javax.enterprise.inject.spi.configurator.AnnotatedTypeConfigurator;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.Path;
import org.apache.geronimo.microprofile.opentracing.common.config.GeronimoOpenTracingConfig;
import org.apache.geronimo.microprofile.opentracing.common.impl.IdGenerator;
import org.apache.geronimo.microprofile.opentracing.common.microprofile.client.OpenTracingClientRequestFilter;
import org.apache.geronimo.microprofile.opentracing.common.microprofile.client.OpenTracingClientResponseFilter;
import org.apache.geronimo.microprofile.opentracing.common.microprofile.thread.OpenTracingExecutorService;
import org.apache.geronimo.microprofile.opentracing.microprofile.zipkin.CdiZipkinConverter;
import org.apache.geronimo.microprofile.opentracing.microprofile.zipkin.CdiZipkinHttp;
import org.apache.geronimo.microprofile.opentracing.microprofile.zipkin.CdiZipkinLogger;
import org.eclipse.microprofile.opentracing.Traced;
import io.opentracing.ScopeManager;
public class OpenTracingExtension implements Extension {
private GeronimoOpenTracingConfig config;
private boolean useZipkin;
private String zipkinSender;
void onStart(@Observes final BeforeBeanDiscovery beforeBeanDiscovery) {
config = GeronimoOpenTracingConfig.create();
useZipkin = Boolean.parseBoolean(config.read("span.converter.zipkin.active", "true"));
zipkinSender = config.read("span.converter.zipkin.sender", "logger");
}
void vetoDefaultConfigIfScanned(@Observes final ProcessAnnotatedType<GeronimoOpenTracingConfig> config) {
if (config.getAnnotatedType().getJavaClass().getName()
.equals("org.apache.geronimo.microprofile.opentracing.common.config.DefaultOpenTracingConfig")) {
config.veto();
}
}
void vetoDefaultScopeManagerIfScanned(@Observes final ProcessAnnotatedType<ScopeManager> manager) {
if (manager.getAnnotatedType().getJavaClass().getName()
.equals("org.apache.geronimo.microprofile.opentracing.common.impl.ScopeManagerImpl")) {
manager.veto();
}
}
void vetoDefaultIdGeneratorIfScanned(@Observes final ProcessAnnotatedType<IdGenerator> generator) {
if (generator.getAnnotatedType().getJavaClass().getName()
.equals("org.apache.geronimo.microprofile.opentracing.common.impl.IdGenerator")) {
generator.veto();
}
}
void vetoClientRequestTracingIfScanned(@Observes final ProcessAnnotatedType<OpenTracingClientRequestFilter> clientFilter) {
if (clientFilter.getAnnotatedType().getJavaClass().getName()
.equals("org.apache.geronimo.microprofile.opentracing.common.microprofile.client.OpenTracingClientRequestFilter")) {
clientFilter.veto();
}
}
void vetoClientResponseTracingIfScanned(@Observes final ProcessAnnotatedType<OpenTracingClientResponseFilter> clientFilter) {
if (clientFilter.getAnnotatedType().getJavaClass().getName()
.equals("org.apache.geronimo.microprofile.opentracing.common.microprofile.client.OpenTracingClientResponseFilter")) {
clientFilter.veto();
}
}
void zipkinConverterToggle(@Observes final ProcessAnnotatedType<CdiZipkinConverter> onZipkinConverter) {
if (!useZipkin) {
onZipkinConverter.veto();
}
}
void zipkinLoggerToggle(@Observes final ProcessAnnotatedType<CdiZipkinLogger> onZipkinLogger) {
if (!"logger".equalsIgnoreCase(zipkinSender) || !Boolean.parseBoolean(config.read("span.converter.zipkin.logger.active", "true"))) {
onZipkinLogger.veto();
}
}
void zipkinHttpToggle(@Observes final ProcessAnnotatedType<CdiZipkinHttp> onZipkinHttp) {
if (!"http".equalsIgnoreCase(zipkinSender) || !Boolean.parseBoolean(config.read("span.converter.zipkin.http.active", "true"))) {
onZipkinHttp.veto();
}
}
<T> void removeTracedFromJaxRsEndpoints(@Observes @WithAnnotations(Traced.class) final ProcessAnnotatedType<T> pat) {
if (isJaxRs(pat.getAnnotatedType())) { // we have filters with more accurate timing
final AnnotatedTypeConfigurator<T> configurator = pat.configureAnnotatedType();
configurator.remove(it -> it.annotationType() == Traced.class);
configurator.methods().stream().filter(m -> isJaxRs(m.getAnnotated()))
.forEach(m -> m.remove(it -> it.annotationType() == Traced.class));
}
}
<T> void instrumentExecutorServices(@Observes final ProcessAnnotatedType<T> pat) {
final Set<Type> typeClosure = pat.getAnnotatedType().getTypeClosure();
if (typeClosure.contains(ExecutorService.class) && !typeClosure.contains(OpenTracingExecutorService.class)) {
pat.configureAnnotatedType().add(TracedExecutorService.Literal.INSTANCE);
}
}
void addConfigAsBean(@Observes final AfterBeanDiscovery afterBeanDiscovery) {
afterBeanDiscovery.addBean().id(OpenTracingExtension.class.getName() + "#" + GeronimoOpenTracingConfig.class.getName())
.beanClass(GeronimoOpenTracingConfig.class).types(GeronimoOpenTracingConfig.class, Object.class)
.qualifiers(Default.Literal.INSTANCE, Any.Literal.INSTANCE).scope(ApplicationScoped.class)
.createWith(ctx -> config);
}
private <T> boolean isJaxRs(final AnnotatedType<T> annotatedType) {
return annotatedType.getAnnotations().stream().anyMatch(it -> it.annotationType() == Path.class)
|| annotatedType.getMethods().stream().anyMatch(this::isJaxRs);
}
private <T> boolean isJaxRs(final AnnotatedMethod<? super T> m) {
return m.getAnnotations().stream().anyMatch(it -> it.annotationType().isAnnotationPresent(HttpMethod.class));
}
}
| 6,345 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing/microprofile/cdi/TracedExecutorService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.microprofile.cdi;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.interceptor.InterceptorBinding;
@InterceptorBinding
@Retention(RUNTIME)
@Target({ TYPE, METHOD })
public @interface TracedExecutorService {
class Literal implements TracedExecutorService {
public static final TracedExecutorService INSTANCE = new Literal();
@Override
public Class<? extends Annotation> annotationType() {
return TracedExecutorService.class;
}
@Override
public boolean equals(final Object other) {
return TracedExecutorService.class.isInstance(other) || (Annotation.class.isInstance(other)
&& Annotation.class.cast(other).annotationType() == TracedExecutorService.class);
}
@Override
public int hashCode() {
return 0;
}
@Override
public String toString() {
return "@" + TracedExecutorService.class.getName();
}
}
}
| 6,346 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing/microprofile/zipkin/CdiZipkinLogger.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.microprofile.zipkin;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import org.apache.geronimo.microprofile.opentracing.common.config.GeronimoOpenTracingConfig;
import org.apache.geronimo.microprofile.opentracing.common.microprofile.zipkin.ZipkinLogger;
import org.apache.geronimo.microprofile.opentracing.common.microprofile.zipkin.ZipkinSpan;
// this allows to integrate with any backend using appenders.
@ApplicationScoped
public class CdiZipkinLogger extends ZipkinLogger {
@Inject
private GeronimoOpenTracingConfig config;
private Jsonb jsonb;
@PostConstruct
public void init() {
setConfig(config);
jsonb = JsonbBuilder.create();
super.init();
}
@PreDestroy
public void destroy() {
super.destroy();
}
public void onZipkinSpan(@Observes final ZipkinSpan zipkinSpan) {
super.onEvent(zipkinSpan);
}
}
| 6,347 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing/microprofile/zipkin/CdiZipkinHttp.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.microprofile.zipkin;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import org.apache.geronimo.microprofile.opentracing.common.config.GeronimoOpenTracingConfig;
import org.apache.geronimo.microprofile.opentracing.common.microprofile.zipkin.ZipkinHttp;
import org.apache.geronimo.microprofile.opentracing.common.microprofile.zipkin.ZipkinSpan;
@ApplicationScoped
public class CdiZipkinHttp extends ZipkinHttp {
@Inject
private GeronimoOpenTracingConfig config;
private Jsonb jsonb;
@PostConstruct
public void init() {
setConfig(config);
jsonb = JsonbBuilder.create();
super.init();
}
@PreDestroy
public void destroy() {
super.destroy();
}
public void onZipkinSpan(@Observes final ZipkinSpan zipkinSpan) {
super.onEvent(zipkinSpan);
}
}
| 6,348 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing/microprofile/zipkin/CdiZipkinConverter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.microprofile.zipkin;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Event;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import org.apache.geronimo.microprofile.opentracing.common.config.GeronimoOpenTracingConfig;
import org.apache.geronimo.microprofile.opentracing.common.impl.FinishedSpan;
import org.apache.geronimo.microprofile.opentracing.common.impl.IdGenerator;
import org.apache.geronimo.microprofile.opentracing.common.microprofile.zipkin.ZipkinConverter;
import org.apache.geronimo.microprofile.opentracing.common.microprofile.zipkin.ZipkinSpan;
@ApplicationScoped
public class CdiZipkinConverter extends ZipkinConverter {
@Inject
private Event<ZipkinSpan> zipkinSpanEvent;
@Inject
private GeronimoOpenTracingConfig config;
@Inject
private IdGenerator idGenerator;
@PostConstruct
public void init() {
setConfig(config);
setIdGenerator(idGenerator);
setZipkinSpanEvent(zipkinSpanEvent::fire);
super.init();
}
public void onSpan(@Observes final FinishedSpan finishedSpan) {
super.onEvent(finishedSpan);
}
}
| 6,349 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing/microprofile/client/CdiOpenTracingClientResponseFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.microprofile.client;
import javax.annotation.Priority;
import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.Priorities;
import org.apache.geronimo.microprofile.opentracing.common.microprofile.client.OpenTracingClientResponseFilter;
@ApplicationScoped
@Priority(Priorities.HEADER_DECORATOR)
public class CdiOpenTracingClientResponseFilter extends OpenTracingClientResponseFilter {
}
| 6,350 |
0 | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing/microprofile | Create_ds/geronimo-opentracing/geronimo-opentracing/src/main/java/org/apache/geronimo/microprofile/opentracing/microprofile/client/CdiOpenTracingClientRequestFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.microprofile.opentracing.microprofile.client;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import org.apache.geronimo.microprofile.opentracing.common.config.GeronimoOpenTracingConfig;
import org.apache.geronimo.microprofile.opentracing.common.microprofile.client.OpenTracingClientRequestFilter;
import io.opentracing.Tracer;
@ApplicationScoped
public class CdiOpenTracingClientRequestFilter extends OpenTracingClientRequestFilter {
@Inject
private Tracer tracer;
@Inject
private GeronimoOpenTracingConfig config;
@PostConstruct
public void init() {
setConfig(config);
setTracer(tracer);
super.init();
}
}
| 6,351 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/MockWorkManager.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector;
import jakarta.resource.spi.work.ExecutionContext;
import jakarta.resource.spi.work.Work;
import jakarta.resource.spi.work.WorkException;
import jakarta.resource.spi.work.WorkListener;
import jakarta.resource.spi.work.WorkManager;
/**
* Dummy implementation of WorkManager interface for use in
* {@link BootstrapContextTest}
* @version $Rev$ $Date$
*/
public class MockWorkManager
implements WorkManager {
private String id = null;
/** Creates a new instance of MockWorkManager */
public MockWorkManager(String id) {
this.id = id;
}
public void doWork(Work work) throws WorkException {
}
public void doWork(Work work,
long startTimeout,
ExecutionContext execContext,
WorkListener workListener)
throws WorkException {
}
public void scheduleWork(Work work) throws WorkException {
}
public void scheduleWork(Work work,
long startTimeout,
ExecutionContext execContext,
WorkListener workListener)
throws WorkException {
}
public long startWork(Work work) throws WorkException {
return -1;
}
public long startWork(Work work,
long startTimeout,
ExecutionContext execContext,
WorkListener workListener)
throws WorkException {
return -1;
}
public String getId() {
return id;
}
public boolean equals(WorkManager wm) {
if (!(wm instanceof MockWorkManager)) {
return false;
}
return ((MockWorkManager) wm).getId() != null &&
((MockWorkManager) wm).getId().equals(getId());
}
}
| 6,352 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/BootstrapContextTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector;
import java.util.Timer;
import java.util.Collections;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import jakarta.resource.spi.XATerminator;
import jakarta.resource.spi.work.WorkManager;
import junit.framework.TestCase;
import org.apache.geronimo.connector.work.GeronimoWorkManager;
import org.apache.geronimo.connector.work.TransactionContextHandler;
import org.apache.geronimo.connector.work.WorkContextHandler;
import org.apache.geronimo.transaction.manager.GeronimoTransactionManager;
import org.apache.geronimo.transaction.manager.XAWork;
/**
* Unit tests for {@link GeronimoBootstrapContext}
* @version $Rev$ $Date$
*/
public class BootstrapContextTest extends TestCase {
ThreadPoolExecutor pool;
protected void setUp() throws Exception {
super.setUp();
XAWork xaWork = new GeronimoTransactionManager();
int poolSize = 1;
int keepAliveTime = 30000;
ThreadPoolExecutor pool = new ThreadPoolExecutor(
poolSize, // core size
poolSize, // max size
keepAliveTime, TimeUnit.MILLISECONDS,
new SynchronousQueue());
pool.setRejectedExecutionHandler(new WaitWhenBlockedPolicy());
pool.setThreadFactory(new ThreadPoolThreadFactory("Connector Test", getClass().getClassLoader()));
}
private static class WaitWhenBlockedPolicy
implements RejectedExecutionHandler {
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) throws RejectedExecutionException {
try {
executor.getQueue().put(r);
}
catch (InterruptedException e) {
throw new RejectedExecutionException(e);
}
}
}
private static final class ThreadPoolThreadFactory implements ThreadFactory {
private final String poolName;
private final ClassLoader classLoader;
private int nextWorkerID = 0;
public ThreadPoolThreadFactory(String poolName, ClassLoader classLoader) {
this.poolName = poolName;
this.classLoader = classLoader;
}
public Thread newThread(Runnable arg0) {
Thread thread = new Thread(arg0, poolName + " " + getNextWorkerID());
thread.setContextClassLoader(classLoader);
return thread;
}
private synchronized int getNextWorkerID() {
return nextWorkerID++;
}
}
/**
* Tests get and set work manager
*/
public void testGetSetWorkManager() throws Exception {
GeronimoTransactionManager transactionManager = new GeronimoTransactionManager();
TransactionContextHandler txWorkContextHandler = new TransactionContextHandler(transactionManager);
GeronimoWorkManager manager = new GeronimoWorkManager(pool, pool, pool, Collections.<WorkContextHandler>singletonList(txWorkContextHandler));
GeronimoBootstrapContext context = new GeronimoBootstrapContext(manager, transactionManager, transactionManager);
WorkManager wm = context.getWorkManager();
assertSame("Make sure it is the same object", manager, wm);
}
/**
* Tests get and set XATerminator
*/
public void testGetSetXATerminator() throws Exception {
GeronimoTransactionManager transactionManager = new GeronimoTransactionManager();
TransactionContextHandler txWorkContextHandler = new TransactionContextHandler(transactionManager);
GeronimoWorkManager manager = new GeronimoWorkManager(pool, pool, pool, Collections.<WorkContextHandler>singletonList(txWorkContextHandler));
GeronimoBootstrapContext context = new GeronimoBootstrapContext(manager, transactionManager, transactionManager);
XATerminator xat = context.getXATerminator();
assertSame("Make sure it is the same object", transactionManager, xat);
}
/**
* Tests getTimer
*/
public void testGetTimer() throws Exception {
GeronimoBootstrapContext context = new GeronimoBootstrapContext(null, null, null);
Timer t = context.createTimer();
assertNotNull("Object is not null", t);
}
}
| 6,353 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/MockTransaction.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector;
import jakarta.transaction.HeuristicMixedException;
import jakarta.transaction.HeuristicRollbackException;
import jakarta.transaction.RollbackException;
import jakarta.transaction.Synchronization;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import javax.transaction.xa.XAResource;
/**
* Dummy implementation of Transaction interface for use in
* {@link TxUtilsTest}
* @version $Rev$ $Date$
*/
public class MockTransaction implements Transaction {
private int status = -1;
/** Creates a new instance of MockWorkManager */
public MockTransaction() {
}
public void commit() throws HeuristicMixedException,
HeuristicRollbackException,
RollbackException,
SecurityException,
SystemException {
}
public boolean delistResource(XAResource xaRes, int flag)
throws IllegalStateException, SystemException {
return false;
}
public boolean enlistResource(XAResource xaRes)
throws IllegalStateException,
RollbackException,
SystemException {
return false;
}
public int getStatus() throws SystemException {
return status;
}
public void registerSynchronization(Synchronization synch)
throws IllegalStateException,
RollbackException,
SystemException {
}
public void rollback() throws IllegalStateException, SystemException {
}
public void setRollbackOnly()
throws IllegalStateException,
SystemException {
}
public void setStatus(int status) {
this.status = status;
}
}
| 6,354 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/mock/MockConnectionRequestInfo.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.mock;
import jakarta.resource.cci.ConnectionSpec;
import jakarta.resource.spi.ConnectionRequestInfo;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class MockConnectionRequestInfo implements ConnectionRequestInfo, ConnectionSpec {
}
| 6,355 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/mock/MockResourceAdapter.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.mock;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ActivationSpec;
import jakarta.resource.spi.BootstrapContext;
import jakarta.resource.spi.ResourceAdapter;
import jakarta.resource.spi.ResourceAdapterInternalException;
import jakarta.resource.spi.endpoint.MessageEndpointFactory;
import javax.transaction.xa.XAResource;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class MockResourceAdapter implements ResourceAdapter {
private BootstrapContext bootstrapContext;
private String raStringProperty;
public void start(BootstrapContext bootstrapContext) throws ResourceAdapterInternalException {
assert this.bootstrapContext == null : "Attempting to restart adapter without stoppping";
assert bootstrapContext != null: "Null bootstrap context";
this.bootstrapContext = bootstrapContext;
}
public void stop() {
bootstrapContext = null;
}
public void endpointActivation(MessageEndpointFactory endpointFactory, ActivationSpec spec) throws ResourceException {
}
public void endpointDeactivation(MessageEndpointFactory endpointFactory, ActivationSpec spec) {
}
public XAResource[] getXAResources(ActivationSpec[] specs) throws ResourceException {
return new XAResource[0];
}
public String getRAStringProperty() {
return raStringProperty;
}
public void setRAStringProperty(String raStringProperty) {
this.raStringProperty = raStringProperty;
}
}
| 6,356 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/mock/MockManagedConnectionFactory.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.mock;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Collections;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ConnectionManager;
import jakarta.resource.spi.ConnectionRequestInfo;
import jakarta.resource.spi.ManagedConnection;
import jakarta.resource.spi.ManagedConnectionFactory;
import jakarta.resource.spi.ResourceAdapter;
import javax.security.auth.Subject;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class MockManagedConnectionFactory implements ManagedConnectionFactory {
private MockResourceAdapter resourceAdapter;
private PrintWriter logWriter;
private final Set managedConnections = Collections.synchronizedSet(new HashSet());
private boolean reauthentication;
public String getOutboundStringProperty1() {
return outboundStringProperty1;
}
public void setOutboundStringProperty1(String outboundStringProperty1) {
this.outboundStringProperty1 = outboundStringProperty1;
}
public String getOutboundStringProperty2() {
return outboundStringProperty2;
}
public void setOutboundStringProperty2(String outboundStringProperty2) {
this.outboundStringProperty2 = outboundStringProperty2;
}
public String getOutboundStringProperty3() {
return outboundStringProperty3;
}
public void setOutboundStringProperty3(String outboundStringProperty3) {
this.outboundStringProperty3 = outboundStringProperty3;
}
public String getOutboundStringProperty4() {
return outboundStringProperty4;
}
public void setOutboundStringProperty4(String outboundStringProperty4) {
this.outboundStringProperty4 = outboundStringProperty4;
}
private String outboundStringProperty1;
private String outboundStringProperty2;
private String outboundStringProperty3;
private String outboundStringProperty4;
public void setResourceAdapter(ResourceAdapter resourceAdapter) throws ResourceException {
assert this.resourceAdapter == null: "Setting ResourceAdapter twice";
assert resourceAdapter != null: "trying to set resourceAdapter to null";
this.resourceAdapter = (MockResourceAdapter) resourceAdapter;
}
public ResourceAdapter getResourceAdapter() {
return resourceAdapter;
}
public Object createConnectionFactory(ConnectionManager connectionManager) throws ResourceException {
return new MockConnectionFactory(this, connectionManager);
}
public Object createConnectionFactory() throws ResourceException {
return null;
}
public ManagedConnection createManagedConnection(Subject subject, ConnectionRequestInfo connectionRequestInfo) throws ResourceException {
MockManagedConnection managedConnection = new MockManagedConnection(this, subject, (MockConnectionRequestInfo) connectionRequestInfo);
managedConnections.add(managedConnection);
return managedConnection;
}
public ManagedConnection matchManagedConnections(Set connectionSet, Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException {
if (reauthentication) {
for (Iterator iterator = connectionSet.iterator(); iterator.hasNext();) {
ManagedConnection managedConnection = (ManagedConnection) iterator.next();
if (managedConnections.contains(managedConnection)) {
return managedConnection;
}
}
} else {
for (Iterator iterator = connectionSet.iterator(); iterator.hasNext();) {
ManagedConnection managedConnection = (ManagedConnection) iterator.next();
// return managedConnection;
if (managedConnections.contains(managedConnection)) {
MockManagedConnection mockManagedConnection = (MockManagedConnection) managedConnection;
if ((subject == null ? mockManagedConnection.getSubject() == null : subject.equals(mockManagedConnection.getSubject())
&& (cxRequestInfo == null ? mockManagedConnection.getConnectionRequestInfo() == null : cxRequestInfo.equals(mockManagedConnection.getConnectionRequestInfo())))) {
return mockManagedConnection;
}
}
}
}
return null;
}
public void setLogWriter(PrintWriter logWriter) throws ResourceException {
this.logWriter = logWriter;
}
public PrintWriter getLogWriter() throws ResourceException {
return logWriter;
}
public boolean isReauthentication() {
return reauthentication;
}
public void setReauthentication(boolean reauthentication) {
this.reauthentication = reauthentication;
}
public Set getManagedConnections() {
return managedConnections;
}
}
| 6,357 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/mock/MockSPILocalTransaction.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.mock;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.LocalTransaction;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class MockSPILocalTransaction implements LocalTransaction {
private boolean inTransaction;
private boolean begun;
private boolean committed;
private boolean rolledBack;
public MockSPILocalTransaction() {
}
public void begin() throws ResourceException {
assert !inTransaction;
inTransaction = true;
begun = true;
}
public void commit() throws ResourceException {
assert inTransaction;
inTransaction = false;
committed = true;
}
public void rollback() throws ResourceException {
assert inTransaction;
inTransaction = false;
rolledBack = true;
}
public void reset() {
inTransaction = false;
begun = false;
committed = false;
rolledBack = false;
}
public boolean isInTransaction() {
return inTransaction;
}
public boolean isBegun() {
return begun;
}
public boolean isCommitted() {
return committed;
}
public boolean isRolledBack() {
return rolledBack;
}
}
| 6,358 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/mock/MockManagedConnection.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.mock;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ConnectionEvent;
import jakarta.resource.spi.ConnectionEventListener;
import jakarta.resource.spi.ConnectionRequestInfo;
import jakarta.resource.spi.LocalTransaction;
import jakarta.resource.spi.ManagedConnection;
import jakarta.resource.spi.ManagedConnectionMetaData;
import javax.security.auth.Subject;
import javax.transaction.xa.XAResource;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class MockManagedConnection implements ManagedConnection {
private final MockManagedConnectionFactory managedConnectionFactory;
private final MockXAResource mockXAResource;
private Subject subject;
private MockConnectionRequestInfo connectionRequestInfo;
private final Set connections = new HashSet();
private final List connectionEventListeners = Collections.synchronizedList(new ArrayList());
private boolean destroyed;
private PrintWriter logWriter;
public MockManagedConnection(MockManagedConnectionFactory managedConnectionFactory, Subject subject, MockConnectionRequestInfo connectionRequestInfo) {
this.managedConnectionFactory = managedConnectionFactory;
mockXAResource = new MockXAResource(this);
this.subject = subject;
this.connectionRequestInfo = connectionRequestInfo;
}
public Object getConnection(Subject subject, ConnectionRequestInfo connectionRequestInfo) throws ResourceException {
checkSecurityConsistency(subject, connectionRequestInfo);
MockConnection mockConnection = new MockConnection(this, subject, (MockConnectionRequestInfo) connectionRequestInfo);
connections.add(mockConnection);
return mockConnection;
}
private void checkSecurityConsistency(Subject subject, ConnectionRequestInfo connectionRequestInfo) {
if (!managedConnectionFactory.isReauthentication()) {
assert subject == null ? this.subject == null : subject.equals(this.subject);
assert connectionRequestInfo == null ? this.connectionRequestInfo == null : connectionRequestInfo.equals(this.connectionRequestInfo);
}
}
public void destroy() throws ResourceException {
destroyed = true;
cleanup();
}
public void cleanup() throws ResourceException {
for (Iterator iterator = new HashSet(connections).iterator(); iterator.hasNext();) {
MockConnection mockConnection = (MockConnection) iterator.next();
mockConnection.close();
}
assert connections.isEmpty();
}
public void associateConnection(Object connection) throws ResourceException {
assert connection != null;
assert connection.getClass() == MockConnection.class;
MockConnection mockConnection = (MockConnection) connection;
checkSecurityConsistency(mockConnection.getSubject(), mockConnection.getConnectionRequestInfo());
mockConnection.reassociate(this);
connections.add(mockConnection);
}
public void addConnectionEventListener(ConnectionEventListener listener) {
connectionEventListeners.add(listener);
}
public void removeConnectionEventListener(ConnectionEventListener listener) {
connectionEventListeners.remove(listener);
}
public XAResource getXAResource() throws ResourceException {
return mockXAResource;
}
public LocalTransaction getLocalTransaction() throws ResourceException {
return new MockSPILocalTransaction();
}
public ManagedConnectionMetaData getMetaData() throws ResourceException {
return null;
}
public void setLogWriter(PrintWriter logWriter) throws ResourceException {
this.logWriter = logWriter;
}
public PrintWriter getLogWriter() throws ResourceException {
return logWriter;
}
public Subject getSubject() {
return subject;
}
public MockConnectionRequestInfo getConnectionRequestInfo() {
return connectionRequestInfo;
}
public void removeHandle(MockConnection mockConnection) {
connections.remove(mockConnection);
}
public MockManagedConnectionFactory getManagedConnectionFactory() {
return managedConnectionFactory;
}
public Set getConnections() {
return connections;
}
public List getConnectionEventListeners() {
return connectionEventListeners;
}
public boolean isDestroyed() {
return destroyed;
}
public void closedEvent(MockConnection mockConnection) {
ConnectionEvent connectionEvent = new ConnectionEvent(this, ConnectionEvent.CONNECTION_CLOSED);
connectionEvent.setConnectionHandle(mockConnection);
for (Iterator iterator = new ArrayList(connectionEventListeners).iterator(); iterator.hasNext();) {
ConnectionEventListener connectionEventListener = (ConnectionEventListener) iterator.next();
connectionEventListener.connectionClosed(connectionEvent);
}
}
public void errorEvent(MockConnection mockConnection) {
ConnectionEvent connectionEvent = new ConnectionEvent(this, ConnectionEvent.CONNECTION_ERROR_OCCURRED);
connectionEvent.setConnectionHandle(mockConnection);
for (Iterator iterator = new ArrayList(connectionEventListeners).iterator(); iterator.hasNext();) {
ConnectionEventListener connectionEventListener = (ConnectionEventListener) iterator.next();
connectionEventListener.connectionErrorOccurred(connectionEvent);
}
}
public void localTransactionStartedEvent(MockConnection mockConnection) {
ConnectionEvent connectionEvent = new ConnectionEvent(this, ConnectionEvent.LOCAL_TRANSACTION_STARTED);
connectionEvent.setConnectionHandle(mockConnection);
for (Iterator iterator = new ArrayList(connectionEventListeners).iterator(); iterator.hasNext();) {
ConnectionEventListener connectionEventListener = (ConnectionEventListener) iterator.next();
connectionEventListener.localTransactionStarted(connectionEvent);
}
}
public void localTransactionCommittedEvent(MockConnection mockConnection) {
ConnectionEvent connectionEvent = new ConnectionEvent(this, ConnectionEvent.LOCAL_TRANSACTION_COMMITTED);
connectionEvent.setConnectionHandle(mockConnection);
for (Iterator iterator = new ArrayList(connectionEventListeners).iterator(); iterator.hasNext();) {
ConnectionEventListener connectionEventListener = (ConnectionEventListener) iterator.next();
connectionEventListener.localTransactionCommitted(connectionEvent);
}
}
public void localTransactionRolledBackEvent(MockConnection mockConnection) {
ConnectionEvent connectionEvent = new ConnectionEvent(this, ConnectionEvent.LOCAL_TRANSACTION_ROLLEDBACK);
connectionEvent.setConnectionHandle(mockConnection);
for (Iterator iterator = new ArrayList(connectionEventListeners).iterator(); iterator.hasNext();) {
ConnectionEventListener connectionEventListener = (ConnectionEventListener) iterator.next();
connectionEventListener.localTransactionRolledback(connectionEvent);
}
}
}
| 6,359 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/mock/MockXAResource.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.mock;
import java.util.HashSet;
import java.util.Set;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class MockXAResource implements XAResource {
private final MockManagedConnection mockManagedConnection;
private int prepareResult = XAResource.XA_OK;
private Xid currentXid;
private int transactionTimeoutSeconds;
private final Set knownXids = new HashSet();
private final Set successfulXids = new HashSet();
private Xid prepared;
private Xid committed;
private Xid rolledback;
public MockXAResource(MockManagedConnection mockManagedConnection) {
this.mockManagedConnection = mockManagedConnection;
}
public void commit(Xid xid, boolean onePhase) throws XAException {
assert xid != null;
assert onePhase || prepared == xid;
committed = xid;
}
//TODO TMFAIL? TMENDRSCAN?
public void end(Xid xid, int flags) throws XAException {
assert xid != null;
assert knownXids.contains(xid);
assert flags == XAResource.TMSUSPEND || flags == XAResource.TMSUCCESS;
if (flags == XAResource.TMSUSPEND) {
assert currentXid == xid;
currentXid = null;
}
if (flags == XAResource.TMSUCCESS) {
successfulXids.add(xid);
if (xid.equals(currentXid)) {
currentXid = null;
}
}
}
public void forget(Xid xid) throws XAException {
//todo
}
public int getTransactionTimeout() throws XAException {
return transactionTimeoutSeconds;
}
public boolean isSameRM(XAResource xaResource) throws XAException {
if (!(xaResource instanceof MockXAResource)) {
return false;
}
MockXAResource other = (MockXAResource) xaResource;
return other.mockManagedConnection.getManagedConnectionFactory() == mockManagedConnection.getManagedConnectionFactory();
}
public int prepare(Xid xid) throws XAException {
assert xid != null;
prepared = xid;
return prepareResult;
}
public Xid[] recover(int flag) throws XAException {
//todo
return new Xid[0];
}
public void rollback(Xid xid) throws XAException {
assert xid != null;
rolledback = xid;
}
public boolean setTransactionTimeout(int seconds) throws XAException {
transactionTimeoutSeconds = seconds;
return true;
}
//TODO TMSTARTRSCAN?
public void start(Xid xid, int flags) throws XAException {
assert currentXid == null :"Expected no xid when start called";
assert xid != null: "Expected xid supplied to start";
assert flags == XAResource.TMNOFLAGS || flags == XAResource.TMJOIN || flags == XAResource.TMRESUME;
if (flags == XAResource.TMNOFLAGS || flags == XAResource.TMJOIN) {
assert !knownXids.contains(xid);
knownXids.add(xid);
}
if (flags == XAResource.TMRESUME) {
assert knownXids.contains(xid);
}
currentXid = xid;
}
public void setPrepareResult(int prepareResult) {
this.prepareResult = prepareResult;
}
public Xid getCurrentXid() {
return currentXid;
}
public Set getKnownXids() {
return knownXids;
}
public Set getSuccessfulXids() {
return successfulXids;
}
public Xid getPrepared() {
return prepared;
}
public Xid getCommitted() {
return committed;
}
public Xid getRolledback() {
return rolledback;
}
public void clear() {
currentXid = null;
prepared = null;
rolledback = null;
committed = null;
knownXids.clear();
successfulXids.clear();
prepareResult = XAResource.XA_OK;
}
}
| 6,360 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/mock/MockConnection.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.mock;
import jakarta.resource.ResourceException;
import jakarta.resource.cci.ConnectionMetaData;
import jakarta.resource.cci.Interaction;
import jakarta.resource.cci.LocalTransaction;
import jakarta.resource.cci.ResultSetInfo;
import javax.security.auth.Subject;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class MockConnection implements ConnectionExtension {
private MockManagedConnection managedConnection;
private Subject subject;
private MockConnectionRequestInfo connectionRequestInfo;
private boolean closed;
public MockConnection(MockManagedConnection managedConnection, Subject subject, MockConnectionRequestInfo connectionRequestInfo) {
this.managedConnection = managedConnection;
this.subject = subject;
this.connectionRequestInfo = connectionRequestInfo;
}
public Interaction createInteraction() throws ResourceException {
return null;
}
public LocalTransaction getLocalTransaction() throws ResourceException {
return new MockCCILocalTransaction(this);
}
public ConnectionMetaData getMetaData() throws ResourceException {
return null;
}
public ResultSetInfo getResultSetInfo() throws ResourceException {
return null;
}
public void close() throws ResourceException {
closed = true;
managedConnection.removeHandle(this);
managedConnection.closedEvent(this);
}
public void error() {
managedConnection.errorEvent(this);
}
public MockManagedConnection getManagedConnection() {
return managedConnection;
}
public Subject getSubject() {
return subject;
}
public MockConnectionRequestInfo getConnectionRequestInfo() {
return connectionRequestInfo;
}
public boolean isClosed() {
return closed;
}
public void reassociate(MockManagedConnection mockManagedConnection) {
assert managedConnection != null;
managedConnection.removeHandle(this);
managedConnection = mockManagedConnection;
subject = mockManagedConnection.getSubject();
connectionRequestInfo = mockManagedConnection.getConnectionRequestInfo();
}
}
| 6,361 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/mock/ConnectionExtension.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.mock;
import jakarta.resource.cci.Connection;
import javax.security.auth.Subject;
/**
* @version $Rev$ $Date$
*/
public interface ConnectionExtension extends Connection {
void error();
MockManagedConnection getManagedConnection();
Subject getSubject();
MockConnectionRequestInfo getConnectionRequestInfo();
boolean isClosed();
void reassociate(MockManagedConnection mockManagedConnection);
}
| 6,362 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/mock/MockAdminObjectImpl.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.mock;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class MockAdminObjectImpl implements MockAdminObject {
private String tweedle;
public String getTweedle() {
return tweedle;
}
public void setTweedle(String tweedle) {
this.tweedle = tweedle;
}
public MockAdminObject getSomething() {
return this;
}
}
| 6,363 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/mock/ConnectionFactoryExtension.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.mock;
import jakarta.resource.cci.ConnectionFactory;
/**
*
*
* @version $Rev$ $Date$
*
* */
public interface ConnectionFactoryExtension extends ConnectionFactory{
String doSomethingElse();
}
| 6,364 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/mock/MockConnectionFactory.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.mock;
import javax.naming.NamingException;
import javax.naming.Reference;
import jakarta.resource.ResourceException;
import jakarta.resource.cci.Connection;
import jakarta.resource.cci.ConnectionSpec;
import jakarta.resource.cci.RecordFactory;
import jakarta.resource.cci.ResourceAdapterMetaData;
import jakarta.resource.spi.ConnectionManager;
/**
* @version $Rev$ $Date$
*/
public class MockConnectionFactory implements ConnectionFactoryExtension {
private ConnectionManager connectionManager;
private MockManagedConnectionFactory managedConnectionFactory;
private Reference reference;
public MockConnectionFactory(MockManagedConnectionFactory managedConnectionFactory, ConnectionManager connectionManager) {
this.managedConnectionFactory = managedConnectionFactory;
this.connectionManager = connectionManager;
}
public Connection getConnection() throws ResourceException {
return getConnection(null);
}
public Connection getConnection(ConnectionSpec properties) throws ResourceException {
return (Connection) connectionManager.allocateConnection(managedConnectionFactory, (MockConnectionRequestInfo) properties);
}
public RecordFactory getRecordFactory() throws ResourceException {
return null;
}
public ResourceAdapterMetaData getMetaData() throws ResourceException {
return null;
}
public void setReference(Reference reference) {
this.reference = reference;
}
public Reference getReference() throws NamingException {
return reference;
}
public String doSomethingElse() {
return "SomethingElse";
}
}
| 6,365 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/mock/MockCCILocalTransaction.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.mock;
import jakarta.resource.ResourceException;
import jakarta.resource.cci.LocalTransaction;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class MockCCILocalTransaction extends MockSPILocalTransaction implements LocalTransaction {
private final MockConnection mockConnection;
public MockCCILocalTransaction(MockConnection mockConnection) {
this.mockConnection = mockConnection;
}
public void begin() throws ResourceException {
super.begin();
mockConnection.getManagedConnection().localTransactionStartedEvent(mockConnection);
}
public void commit() throws ResourceException {
super.commit();
mockConnection.getManagedConnection().localTransactionCommittedEvent(mockConnection);
}
public void rollback() throws ResourceException {
super.rollback();
mockConnection.getManagedConnection().localTransactionRolledBackEvent(mockConnection);
}
}
| 6,366 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/mock/MockActivationSpec.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.mock;
import jakarta.resource.spi.ActivationSpec;
import jakarta.resource.spi.InvalidPropertyException;
import jakarta.resource.spi.ResourceAdapter;
import jakarta.resource.ResourceException;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class MockActivationSpec implements ActivationSpec {
public void validate() throws InvalidPropertyException {
}
public ResourceAdapter getResourceAdapter() {
return null;
}
public void setResourceAdapter(ResourceAdapter ra) throws ResourceException {
}
}
| 6,367 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/mock/MockAdminObject.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.mock;
import java.io.Serializable;
/**
*
*
* @version $Rev$ $Date$
*
* */
public interface MockAdminObject extends Serializable {
String getTweedle();
void setTweedle(String tweedle);
MockAdminObject getSomething();
}
| 6,368 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/work/PooledWorkManagerTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.work;
import java.lang.reflect.Constructor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;
import jakarta.resource.spi.work.ExecutionContext;
import jakarta.resource.spi.work.Work;
import jakarta.resource.spi.work.WorkEvent;
import jakarta.resource.spi.work.WorkException;
import jakarta.resource.spi.work.WorkListener;
import junit.framework.TestCase;
import org.apache.geronimo.transaction.manager.GeronimoTransactionManager;
import org.apache.geronimo.transaction.manager.XAWork;
/**
* Timing is crucial for this test case, which focuses on the synchronization
* specificities of the doWork, startWork and scheduleWork.
*
* @version $Rev$ $Date$
*/
public class PooledWorkManagerTest extends TestCase {
private GeronimoWorkManager workManager;
protected void setUp() throws Exception {
super.setUp();
XAWork xaWork = new GeronimoTransactionManager();
TransactionContextHandler txWorkContextHandler = new TransactionContextHandler(xaWork);
int poolSize = 1;
int keepAliveTime = 30000;
ThreadPoolExecutor pool = new ThreadPoolExecutor(
poolSize, // core size
poolSize, // max size
keepAliveTime, TimeUnit.MILLISECONDS,
new SynchronousQueue());
pool.setRejectedExecutionHandler(new WaitWhenBlockedPolicy());
pool.setThreadFactory(new ThreadPoolThreadFactory("Connector Test", getClass().getClassLoader()));
workManager = new GeronimoWorkManager(pool, pool, pool, Collections.<WorkContextHandler>singletonList(txWorkContextHandler));
workManager.doStart();
}
private static class WaitWhenBlockedPolicy
implements RejectedExecutionHandler {
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) throws RejectedExecutionException {
try {
executor.getQueue().put(r);
}
catch (InterruptedException e) {
throw new RejectedExecutionException(e);
}
}
}
private static final class ThreadPoolThreadFactory implements ThreadFactory {
private final String poolName;
private final ClassLoader classLoader;
private int nextWorkerID = 0;
public ThreadPoolThreadFactory(String poolName, ClassLoader classLoader) {
this.poolName = poolName;
this.classLoader = classLoader;
}
public Thread newThread(Runnable arg0) {
Thread thread = new Thread(arg0, poolName + " " + getNextWorkerID());
thread.setContextClassLoader(classLoader);
return thread;
}
private synchronized int getNextWorkerID() {
return nextWorkerID++;
}
}
public void testDoWork() throws Exception {
int nbThreads = 2;
AbstractDummyWork threads[] = helperTest(DummyDoWork.class, nbThreads, 500, 600);
int nbStopped = 0;
int nbTimeout = 0;
for (int i = 0; i < threads.length; i++) {
if ( null != threads[i].listener.completedEvent ) {
nbStopped++;
} else if ( null != threads[i].listener.rejectedEvent ) {
assertTrue("Should be a time out exception.",
threads[i].listener.rejectedEvent.getException().
getErrorCode() == WorkException.START_TIMED_OUT);
nbTimeout++;
} else {
fail("WORK_COMPLETED or WORK_REJECTED expected");
}
}
assertEquals("Wrong number of works in the WORK_COMPLETED state", 1, nbStopped);
assertEquals("Wrong number of works in the START_TIMED_OUT state", 1, nbTimeout);
}
public void testStartWork() throws Exception {
AbstractDummyWork threads[] = helperTest(DummyStartWork.class, 2, 10000, 100);
int nbStopped = 0;
int nbStarted = 0;
for (int i = 0; i < threads.length; i++) {
if ( null != threads[i].listener.completedEvent ) {
nbStopped++;
} else if ( null != threads[i].listener.startedEvent ) {
nbStarted++;
} else {
fail("WORK_COMPLETED or WORK_STARTED expected");
}
}
assertEquals("At least one work should be in the WORK_COMPLETED state.", 1, nbStopped);
assertEquals("At least one work should be in the WORK_STARTED state.", 1, nbStarted);
}
public void testScheduleWork() throws Exception {
AbstractDummyWork threads[] =
helperTest(DummyScheduleWork.class, 3, 10000, 100);
int nbAccepted = 0;
int nbStarted = 0;
for (int i = 0; i < threads.length; i++) {
if ( null != threads[i].listener.acceptedEvent ) {
nbAccepted++;
} else if ( null != threads[i].listener.startedEvent ) {
nbStarted++;
} else {
fail("WORK_ACCEPTED or WORK_STARTED expected");
}
}
assertTrue("At least one work should be in the WORK_ACCEPTED state.", nbAccepted > 0);
}
public void testLifecycle() throws Exception {
testDoWork();
workManager.doStop();
workManager.doStart();
testDoWork();
}
private AbstractDummyWork[] helperTest(Class aWork, int nbThreads,
int aTimeOut, int aTempo)
throws Exception {
Constructor constructor = aWork.getConstructor(
new Class[]{PooledWorkManagerTest.class, String.class,
int.class, int.class});
AbstractDummyWork rarThreads[] = new AbstractDummyWork[nbThreads];
for (int i = 0; i < nbThreads; i++) {
rarThreads[i] = (AbstractDummyWork)
constructor.newInstance(
new Object[]{this, "Work" + i,
new Integer(aTimeOut), new Integer(aTempo)});
}
for (int i = 0; i < nbThreads; i++) {
rarThreads[i].start();
}
for (int i = 0; i < nbThreads; i++) {
rarThreads[i].join();
}
return rarThreads;
}
public abstract class AbstractDummyWork extends Thread {
public final DummyWorkListener listener;
protected final String name;
private final int timeout;
private final int tempo;
public AbstractDummyWork(String aName, int aTimeOut, int aTempo) {
listener = new DummyWorkListener();
timeout = aTimeOut;
tempo = aTempo;
name = aName;
}
public void run() {
try {
perform(new DummyWork(name, tempo), timeout, null, listener);
} catch (Exception e) {
// log.debug(e.getMessage(), e);
}
}
protected abstract void perform(Work work,
long startTimeout,
ExecutionContext execContext,
WorkListener workListener) throws Exception;
}
public class DummyDoWork extends AbstractDummyWork {
public DummyDoWork(String aName, int aTimeOut, int aTempo) {
super(aName, aTimeOut, aTempo);
}
protected void perform(Work work,
long startTimeout,
ExecutionContext execContext,
WorkListener workListener) throws Exception {
workManager.doWork(work, startTimeout, execContext, workListener);
}
}
public class DummyStartWork extends AbstractDummyWork {
public DummyStartWork(String aName, int aTimeOut, int aTempo) {
super(aName, aTimeOut, aTempo);
}
protected void perform(Work work,
long startTimeout,
ExecutionContext execContext,
WorkListener workListener) throws Exception {
workManager.startWork(work, startTimeout, execContext, workListener);
}
}
public class DummyScheduleWork extends AbstractDummyWork {
public DummyScheduleWork(String aName, int aTimeOut, int aTempo) {
super(aName, aTimeOut, aTempo);
}
protected void perform(Work work,
long startTimeout,
ExecutionContext execContext,
WorkListener workListener) throws Exception {
workManager.scheduleWork(work, startTimeout, execContext, workListener);
}
}
public static class DummyWork implements Work {
private Logger log = Logger.getLogger(getClass().getName());
private final String name;
private final int tempo;
public DummyWork(String aName, int aTempo) {
name = aName;
tempo = aTempo;
}
public void release() {
}
public void run() {
try {
Thread.sleep(tempo);
} catch (InterruptedException e) {
log.log(Level.FINE, e.getMessage(), e);
}
}
public String toString() {
return name;
}
}
public static class DummyWorkListener implements WorkListener {
private Logger log = Logger.getLogger(getClass().getName());
public WorkEvent acceptedEvent;
public WorkEvent rejectedEvent;
public WorkEvent startedEvent;
public WorkEvent completedEvent;
public void workAccepted(WorkEvent e) {
acceptedEvent = e;
log.log(Level.FINE, "accepted: " + e);
}
public void workRejected(WorkEvent e) {
rejectedEvent = e;
log.log(Level.FINE,"rejected: " + e);
}
public void workStarted(WorkEvent e) {
startedEvent = e;
log.log(Level.FINE,"started: " + e);
}
public void workCompleted(WorkEvent e) {
completedEvent = e;
log.log(Level.FINE,"completed: " + e);
}
}
}
| 6,369 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/outbound/ConnectionManagerTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.outbound;
import org.apache.geronimo.connector.mock.MockXAResource;
import org.apache.geronimo.connector.mock.ConnectionExtension;
import org.apache.geronimo.connector.outbound.connectiontracking.DefaultInterceptor;
import org.apache.geronimo.connector.outbound.connectiontracking.ConnectorInstanceContext;
import org.apache.geronimo.transaction.GeronimoUserTransaction;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class ConnectionManagerTest extends ConnectionManagerTestUtils {
public void testSingleTransactionCall() throws Throwable {
transactionManager.begin();
defaultComponentInterceptor.invoke(connectorInstanceContext);
MockXAResource mockXAResource = (MockXAResource) mockManagedConnection.getXAResource();
assertEquals("XAResource should know one xid", 1, mockXAResource.getKnownXids().size());
assertNull("Should not be committed", mockXAResource.getCommitted());
transactionManager.commit();
assertNotNull("Should be committed", mockXAResource.getCommitted());
}
public void testNoTransactionCall() throws Throwable {
defaultComponentInterceptor.invoke(connectorInstanceContext);
MockXAResource mockXAResource = (MockXAResource) mockManagedConnection.getXAResource();
assertEquals("XAResource should know 0 xid", 0, mockXAResource.getKnownXids().size());
assertNull("Should not be committed", mockXAResource.getCommitted());
}
public void testOneTransactionTwoCalls() throws Throwable {
transactionManager.begin();
defaultComponentInterceptor.invoke(connectorInstanceContext);
MockXAResource mockXAResource = (MockXAResource) mockManagedConnection.getXAResource();
assertEquals("XAResource should know one xid", 1, mockXAResource.getKnownXids().size());
assertNull("Should not be committed", mockXAResource.getCommitted());
defaultComponentInterceptor.invoke(connectorInstanceContext);
assertEquals("Expected same XAResource", mockXAResource, mockManagedConnection.getXAResource());
assertEquals("XAResource should know one xid", 1, mockXAResource.getKnownXids().size());
assertNull("Should not be committed", mockXAResource.getCommitted());
transactionManager.commit();
assertNotNull("Should be committed", mockXAResource.getCommitted());
}
public void testUserTransactionEnlistingExistingConnections() throws Throwable {
mockComponent = new DefaultInterceptor() {
public Object invoke(ConnectorInstanceContext newConnectorInstanceContext) throws Throwable {
ConnectionExtension mockConnection = (ConnectionExtension) connectionFactory.getConnection();
mockManagedConnection = mockConnection.getManagedConnection();
userTransaction.begin();
MockXAResource mockXAResource = (MockXAResource) mockManagedConnection.getXAResource();
assertEquals("XAResource should know one xid", 1, mockXAResource.getKnownXids().size());
assertNull("Should not be committed", mockXAResource.getCommitted());
userTransaction.commit();
assertNotNull("Should be committed", mockXAResource.getCommitted());
mockConnection.close();
return null;
}
};
userTransaction = new GeronimoUserTransaction(transactionManager);
defaultComponentInterceptor.invoke(connectorInstanceContext);
MockXAResource mockXAResource = (MockXAResource) mockManagedConnection.getXAResource();
assertEquals("XAResource should know 1 xid", 1, mockXAResource.getKnownXids().size());
assertNotNull("Should be committed", mockXAResource.getCommitted());
mockXAResource.clear();
}
public void testConnectionCloseReturnsCxAfterUserTransaction() throws Throwable {
for (int i = 0; i < maxSize + 1; i++) {
testUserTransactionEnlistingExistingConnections();
}
}
public void testUnshareableConnections() throws Throwable {
unshareableResources.add(name);
mockComponent = new DefaultInterceptor() {
public Object invoke(ConnectorInstanceContext newConnectorInstanceContext) throws Throwable {
ConnectionExtension mockConnection1 = (ConnectionExtension) connectionFactory.getConnection();
mockManagedConnection = mockConnection1.getManagedConnection();
ConnectionExtension mockConnection2 = (ConnectionExtension) connectionFactory.getConnection();
//the 2 cx are for the same RM, so tm will call commit only one one (the first)
//mockManagedConnection = mockConnection2.getManagedConnection();
assertNotNull("Expected non-null managedconnection 1", mockConnection1.getManagedConnection());
assertNotNull("Expected non-null managedconnection 2", mockConnection2.getManagedConnection());
assertTrue("Expected different managed connections for each unshared handle", mockConnection1.getManagedConnection() != mockConnection2.getManagedConnection());
mockConnection1.close();
mockConnection2.close();
return null;
}
};
transactionManager.begin();
defaultComponentInterceptor.invoke(connectorInstanceContext);
MockXAResource mockXAResource = (MockXAResource) mockManagedConnection.getXAResource();
assertEquals("XAResource should know one xid", 1, mockXAResource.getKnownXids().size());
assertNull("Should not be committed", mockXAResource.getCommitted());
transactionManager.commit();
assertNotNull("Should be committed", mockXAResource.getCommitted());
}
}
| 6,370 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/outbound/ConnectionManagerTestUtils.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.outbound;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;
import javax.security.auth.Subject;
import jakarta.transaction.UserTransaction;
import org.apache.geronimo.connector.mock.ConnectionExtension;
import org.apache.geronimo.connector.mock.MockConnectionFactory;
import org.apache.geronimo.connector.mock.MockManagedConnection;
import org.apache.geronimo.connector.mock.MockManagedConnectionFactory;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.PartitionedPool;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.PoolingSupport;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.TransactionSupport;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.XATransactions;
import org.apache.geronimo.connector.outbound.connectiontracking.ConnectionTrackingCoordinator;
import org.apache.geronimo.connector.outbound.connectiontracking.ConnectorInstanceContext;
import org.apache.geronimo.connector.outbound.connectiontracking.ConnectorInstanceContextImpl;
import org.apache.geronimo.connector.outbound.connectiontracking.DefaultComponentInterceptor;
import org.apache.geronimo.connector.outbound.connectiontracking.DefaultInterceptor;
import org.apache.geronimo.connector.outbound.connectiontracking.GeronimoTransactionListener;
import org.apache.geronimo.transaction.manager.RecoverableTransactionManager;
import org.apache.geronimo.transaction.manager.TransactionManagerImpl;
import junit.framework.TestCase;
/**
* ???
*
* @version $Rev$ $Date$
*/
public class ConnectionManagerTestUtils extends TestCase implements DefaultInterceptor {
protected static final Logger log = Logger.getLogger(ConnectionManagerTestUtils.class.getName());
protected boolean useTransactionCaching = true;
protected boolean useLocalTransactions = false;
protected boolean useThreadCaching = false;
protected boolean useTransactions = true;
protected int maxSize = 10;
protected int minSize = 0;
protected int blockingTimeout = 100;
protected int idleTimeoutMinutes = 15;
protected boolean useConnectionRequestInfo = false;
protected boolean useSubject = true;
private boolean matchOne = true;
private boolean matchAll = false;
private boolean selectOneNoMatch = false;
protected String name = "testCF";
//dependencies
protected ConnectionTrackingCoordinator connectionTrackingCoordinator;
protected RecoverableTransactionManager transactionManager;
protected AbstractConnectionManager connectionManagerDeployment;
protected MockConnectionFactory connectionFactory;
protected MockManagedConnectionFactory mockManagedConnectionFactory;
protected ConnectorInstanceContextImpl connectorInstanceContext;
protected DefaultComponentInterceptor defaultComponentInterceptor;
protected Set<String> unshareableResources = new HashSet<String>();
protected Set<String> applicationManagedSecurityResources = new HashSet<String>();
protected MockManagedConnection mockManagedConnection;
protected Subject subject;
protected UserTransaction userTransaction;
protected TransactionSupport transactionSupport = new XATransactions(useTransactionCaching, useThreadCaching);
protected PoolingSupport poolingSupport = new PartitionedPool(maxSize, minSize, blockingTimeout, idleTimeoutMinutes, matchOne, matchAll, selectOneNoMatch, useConnectionRequestInfo, useSubject);
protected boolean containerManagedSecurity = true;
protected DefaultInterceptor mockComponent = new DefaultInterceptor() {
public Object invoke(ConnectorInstanceContext newConnectorInstanceContext) throws Throwable {
ConnectionExtension mockConnection = (ConnectionExtension) connectionFactory.getConnection();
mockManagedConnection = mockConnection.getManagedConnection();
mockConnection.close();
return null;
}
};
private ClassLoader classLoader = this.getClass().getClassLoader();
protected void setUp() throws Exception {
super.setUp();
TransactionManagerImpl transactionManager = new TransactionManagerImpl();
this.transactionManager = transactionManager;
connectionTrackingCoordinator = new ConnectionTrackingCoordinator();
transactionManager.addTransactionAssociationListener(new GeronimoTransactionListener(connectionTrackingCoordinator));
mockManagedConnectionFactory = new MockManagedConnectionFactory();
subject = new Subject();
SubjectSource subjectSource = new SubjectSource() {
public Subject getSubject() throws SecurityException {
return subject;
}
};
connectionManagerDeployment = new GenericConnectionManager(
transactionSupport,
poolingSupport,
subjectSource, connectionTrackingCoordinator,
this.transactionManager,
mockManagedConnectionFactory,
name,
classLoader);
connectionFactory = (MockConnectionFactory) connectionManagerDeployment.createConnectionFactory();
connectorInstanceContext = new ConnectorInstanceContextImpl(unshareableResources, applicationManagedSecurityResources);
defaultComponentInterceptor = new DefaultComponentInterceptor(this, connectionTrackingCoordinator);
}
protected void tearDown() throws Exception {
connectionTrackingCoordinator = null;
transactionManager = null;
mockManagedConnectionFactory = null;
connectionManagerDeployment = null;
connectionFactory = null;
connectorInstanceContext = null;
super.tearDown();
}
public Object invoke(ConnectorInstanceContext newConnectorInstanceContext) throws Throwable {
return mockComponent.invoke(newConnectorInstanceContext);
}
}
| 6,371 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/outbound/MultiPoolMinSizeTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.connector.outbound;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ManagedConnectionFactory;
import junit.framework.TestCase;
import org.apache.geronimo.connector.mock.MockManagedConnectionFactory;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.PoolingSupport;
import org.apache.geronimo.connector.outbound.connectionmanagerconfig.SinglePool;
/**
* @version $Rev$ $Date$
*/
public class MultiPoolMinSizeTest extends TestCase {
private ManagedConnectionFactory mcf = new MockManagedConnectionFactory();
protected MultiPoolConnectionInterceptor interceptor;
protected int maxSize = 10;
protected int minSize = 2;
protected boolean matchOne = true;
protected boolean matchAll = true;
protected boolean selectOneAssumeMatch = false;
protected void setUp() throws Exception {
super.setUp();
PoolingSupport singlePool = new SinglePool(maxSize, minSize, 100, 1, matchOne, matchAll, selectOneAssumeMatch);
MCFConnectionInterceptor baseInterceptor = new MCFConnectionInterceptor();
interceptor = new MultiPoolConnectionInterceptor(baseInterceptor, singlePool, false, false);
}
/**
* Check that connection from the pre-filled pool can be returned ok.
* @throws Exception if test fails
*/
public void testInitialFill() throws Exception {
// get first connection, which then fills pool
ConnectionInfo ci1 = getConnection();
if (minSize > 0) {
Thread.sleep(500); // wait for FillTask Timer set at 10ms to run
assertEquals(minSize, interceptor.getConnectionCount());
}
// get second connection from filled pool
ConnectionInfo ci2 = getConnection();
// return second connection (which needs to have gotten a proper pool interceptor)
interceptor.returnConnection(ci2, ConnectionReturnAction.RETURN_HANDLE);
// return first connection
interceptor.returnConnection(ci1, ConnectionReturnAction.RETURN_HANDLE);
}
private ConnectionInfo getConnection() throws ResourceException {
ManagedConnectionInfo mci = new ManagedConnectionInfo(mcf, null);
ConnectionInfo ci = new ConnectionInfo(mci);
interceptor.getConnection(ci);
return ci;
}
}
| 6,372 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/outbound/ConnectionInterceptorTestUtils.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.outbound;
import java.io.PrintWriter;
import java.security.Principal;
import java.util.Set;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ConnectionEventListener;
import jakarta.resource.spi.ConnectionRequestInfo;
import jakarta.resource.spi.DissociatableManagedConnection;
import jakarta.resource.spi.LocalTransaction;
import jakarta.resource.spi.ManagedConnection;
import jakarta.resource.spi.ManagedConnectionMetaData;
import javax.security.auth.Subject;
import javax.transaction.xa.XAResource;
import junit.framework.TestCase;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class ConnectionInterceptorTestUtils extends TestCase implements ConnectionInterceptor {
protected Subject subject;
protected ConnectionInfo obtainedConnectionInfo;
protected ConnectionInfo returnedConnectionInfo;
protected ManagedConnection managedConnection;
protected void setUp() throws Exception {
}
protected void tearDown() throws Exception {
subject = null;
obtainedConnectionInfo = null;
returnedConnectionInfo = null;
managedConnection = null;
}
public void testNothing() throws Exception {
}
//ConnectorInterceptor implementation
public void getConnection(ConnectionInfo connectionInfo) throws ResourceException {
ManagedConnectionInfo managedConnectionInfo = connectionInfo.getManagedConnectionInfo();
if (managedConnectionInfo.getManagedConnection() == null) {
managedConnectionInfo.setManagedConnection(managedConnection);
}
obtainedConnectionInfo = connectionInfo;
}
public void returnConnection(ConnectionInfo connectionInfo, ConnectionReturnAction connectionReturnAction) {
returnedConnectionInfo = connectionInfo;
}
public void destroy() {
}
protected void makeSubject(String principalName) {
subject = new Subject();
Set principals = subject.getPrincipals();
principals.add(new TestPrincipal(principalName));
}
protected ConnectionInfo makeConnectionInfo() {
ManagedConnectionInfo managedConnectionInfo = new ManagedConnectionInfo(null, null);
return new ConnectionInfo(managedConnectionInfo);
}
private static class TestPrincipal implements Principal {
private final String name;
public TestPrincipal(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
protected static class TestPlainManagedConnection implements ManagedConnection {
public Object getConnection(Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException {
return null;
}
public void destroy() throws ResourceException {
}
public void cleanup() throws ResourceException {
}
public void associateConnection(Object connection) throws ResourceException {
}
public void addConnectionEventListener(ConnectionEventListener listener) {
}
public void removeConnectionEventListener(ConnectionEventListener listener) {
}
public XAResource getXAResource() throws ResourceException {
return null;
}
public LocalTransaction getLocalTransaction() throws ResourceException {
return null;
}
public ManagedConnectionMetaData getMetaData() throws ResourceException {
return null;
}
public void setLogWriter(PrintWriter out) throws ResourceException {
}
public PrintWriter getLogWriter() throws ResourceException {
return null;
}
}
protected static class TestDissociatableManagedConnection implements ManagedConnection, DissociatableManagedConnection {
public void dissociateConnections() throws ResourceException {
}
public Object getConnection(Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException {
return null;
}
public void destroy() throws ResourceException {
}
public void cleanup() throws ResourceException {
}
public void associateConnection(Object connection) throws ResourceException {
}
public void addConnectionEventListener(ConnectionEventListener listener) {
}
public void removeConnectionEventListener(ConnectionEventListener listener) {
}
public XAResource getXAResource() throws ResourceException {
return null;
}
public LocalTransaction getLocalTransaction() throws ResourceException {
return null;
}
public ManagedConnectionMetaData getMetaData() throws ResourceException {
return null;
}
public void setLogWriter(PrintWriter out) throws ResourceException {
}
public PrintWriter getLogWriter() throws ResourceException {
return null;
}
}
public void info(StringBuilder s) {
s.append(getClass().getName()).append("\n");
s.append("<end>");
}
}
| 6,373 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/outbound/SinglePoolMatchAllTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.connector.outbound;
/**
* @version $Rev:$ $Date:$
*/
public class SinglePoolMatchAllTest extends AbstractSinglePoolTest{
protected void setUp() throws Exception {
super.setUp();
// interceptor = new SinglePoolConnectionInterceptor(switchableInterceptor, maxSize, 0, 100, 1, true);
this.interceptor = new SinglePoolMatchAllConnectionInterceptor(switchableInterceptor, maxSize, 0, 100, 1);
}
} | 6,374 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/outbound/PoolResizeTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.outbound;
import junit.framework.TestCase;
/**
* @version $Rev$ $Date$
*/
public class PoolResizeTest extends TestCase {
private final int oldCheckedOut = 20;
private final int oldConnectionCount = 40;
private final int oldPermitsAvailable = oldConnectionCount - oldCheckedOut;
private final int oldMaxSize = 60;
public void testOne() throws Exception {
int oldMinSize = 5;
int newMaxSize = 10;
AbstractSinglePoolConnectionInterceptor.ResizeInfo resizeInfo = new AbstractSinglePoolConnectionInterceptor.ResizeInfo(oldMinSize, oldPermitsAvailable, oldConnectionCount, newMaxSize);
assertEquals("wrong shrinkLater", 10, resizeInfo.getShrinkLater());
assertEquals("wrong shrinkNow", 20, resizeInfo.getShrinkNow());
assertEquals("wrong newMinSize", 5, resizeInfo.getNewMinSize());
assertEquals("wrong transferCheckedOut", 10, resizeInfo.getTransferCheckedOut());
}
public void testTwo() throws Exception {
int oldMinSize = 5;
int newMaxSize = 30;
AbstractSinglePoolConnectionInterceptor.ResizeInfo resizeInfo = new AbstractSinglePoolConnectionInterceptor.ResizeInfo(oldMinSize, oldPermitsAvailable, oldConnectionCount, newMaxSize);
assertEquals("wrong shrinkLater", 0, resizeInfo.getShrinkLater());
assertEquals("wrong shrinkNow", 10, resizeInfo.getShrinkNow());
assertEquals("wrong newMinSize", 5, resizeInfo.getNewMinSize());
assertEquals("wrong transferCheckedOut", 20, resizeInfo.getTransferCheckedOut());
}
public void testThree() throws Exception {
int oldMinSize = 5;
int newMaxSize = 50;
AbstractSinglePoolConnectionInterceptor.ResizeInfo resizeInfo = new AbstractSinglePoolConnectionInterceptor.ResizeInfo(oldMinSize, oldPermitsAvailable, oldConnectionCount, newMaxSize);
assertEquals("wrong shrinkLater", 00, resizeInfo.getShrinkLater());
assertEquals("wrong shrinkNow", 0, resizeInfo.getShrinkNow());
assertEquals("wrong newMinSize", 5, resizeInfo.getNewMinSize());
assertEquals("wrong transferCheckedOut", 20, resizeInfo.getTransferCheckedOut());
}
public void testFour() throws Exception {
int oldMinSize = 5;
int newMaxSize = 70;
AbstractSinglePoolConnectionInterceptor.ResizeInfo resizeInfo = new AbstractSinglePoolConnectionInterceptor.ResizeInfo(oldMinSize, oldPermitsAvailable, oldConnectionCount, newMaxSize);
assertEquals("wrong shrinkLater", 0, resizeInfo.getShrinkLater());
assertEquals("wrong shrinkNow", 0, resizeInfo.getShrinkNow());
assertEquals("wrong newMinSize", 5, resizeInfo.getNewMinSize());
assertEquals("wrong transferCheckedOut", 20, resizeInfo.getTransferCheckedOut());
}
}
| 6,375 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/outbound/ConnectionManagerStressTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.outbound;
import java.util.HashSet;
import java.util.logging.Level;
import org.apache.geronimo.connector.outbound.connectiontracking.ConnectorInstanceContextImpl;
/**
* ???
*
* @version $Rev$ $Date$
*/
public class ConnectionManagerStressTest extends ConnectionManagerTestUtils {
protected int repeatCount = 200;
protected int threadCount = 10;
private Object startBarrier = new Object();
private Object stopBarrier = new Object();
private int startedThreads = 0;
private int stoppedThreads = 0;
private long totalDuration = 0;
private int slowCount = 0;
private Object mutex = new Object();
private Exception e = null;
public void testNoTransactionCallOneThread() throws Throwable {
for (int i = 0; i < repeatCount; i++) {
defaultComponentInterceptor.invoke(connectorInstanceContext);
}
}
public void testNoTransactionCallMultiThread() throws Throwable {
startedThreads = 0;
stoppedThreads = 0;
for (int t = 0; t < threadCount; t++) {
new Thread() {
public void run() {
long localStartTime = 0;
int localSlowCount = 0;
try {
synchronized (startBarrier) {
++startedThreads;
startBarrier.notifyAll();
while (startedThreads < (threadCount + 1)) {
startBarrier.wait();
}
}
localStartTime = System.currentTimeMillis();
for (int i = 0; i < repeatCount; i++) {
try {
long start = System.currentTimeMillis();
defaultComponentInterceptor.invoke(new ConnectorInstanceContextImpl(new HashSet<String>(), new HashSet<String>()));
long duration = System.currentTimeMillis() - start;
if (duration > 100) {
localSlowCount++;
log.log(Level.FINE, "got a cx: " + i + ", time: " + (duration));
}
} catch (Throwable throwable) {
log.log(Level.FINE, throwable.getMessage(), throwable);
}
}
} catch (Exception e) {
log.log(Level.INFO, e.getMessage(), e);
ConnectionManagerStressTest.this.e = e;
} finally {
synchronized (stopBarrier) {
++stoppedThreads;
stopBarrier.notifyAll();
}
long localDuration = System.currentTimeMillis() - localStartTime;
synchronized (mutex) {
totalDuration += localDuration;
slowCount += localSlowCount;
}
}
}
}.start();
}
// Wait for all the workers to be ready..
long startTime = 0;
synchronized (startBarrier) {
while (startedThreads < threadCount) startBarrier.wait();
++startedThreads;
startBarrier.notifyAll();
startTime = System.currentTimeMillis();
}
// Wait for all the workers to finish.
synchronized (stopBarrier) {
while (stoppedThreads < threadCount) stopBarrier.wait();
}
long duration = System.currentTimeMillis() - startTime;
log.log(Level.FINE, "no tx run, thread count: " + threadCount + ", connection count: " + repeatCount + ", duration: " + duration + ", total duration: " + totalDuration + ", ms per cx request: " + (totalDuration / (threadCount * repeatCount)) + ", slow cx request count: " + slowCount);
//return startTime;
if (e != null) {
throw e;
}
}
}
| 6,376 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/outbound/SinglePoolTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.connector.outbound;
/**
* @version $Rev:$ $Date:$
*/
public class SinglePoolTest extends AbstractSinglePoolTest{
protected void setUp() throws Exception {
super.setUp();
interceptor = new SinglePoolConnectionInterceptor(switchableInterceptor, maxSize, 0, 100, 1, true);
// this.interceptor = new SinglePoolMatchAllConnectionInterceptor(switchableInterceptor, maxSize, 0, 100, 1);
}
}
| 6,377 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/outbound/TransactionEnlistingInterceptorTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.outbound;
import jakarta.resource.ResourceException;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import jakarta.transaction.TransactionManager;
import org.apache.geronimo.transaction.manager.NamedXAResource;
import org.apache.geronimo.transaction.manager.TransactionManagerImpl;
import org.apache.geronimo.transaction.manager.XidFactoryImpl;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class TransactionEnlistingInterceptorTest extends ConnectionInterceptorTestUtils implements NamedXAResource {
private TransactionEnlistingInterceptor transactionEnlistingInterceptor;
private boolean started;
private boolean ended;
private boolean returned;
private boolean committed;
private TransactionManager transactionManager;
protected void setUp() throws Exception {
super.setUp();
transactionManager = new TransactionManagerImpl();
transactionEnlistingInterceptor = new TransactionEnlistingInterceptor(this, this.transactionManager);
}
protected void tearDown() throws Exception {
super.tearDown();
transactionEnlistingInterceptor = null;
started = false;
ended = false;
returned = false;
committed = false;
}
public void testNoTransaction() throws Exception {
ConnectionInfo connectionInfo = makeConnectionInfo();
transactionEnlistingInterceptor.getConnection(connectionInfo);
assertTrue("Expected not started", !started);
assertTrue("Expected not ended", !ended);
transactionEnlistingInterceptor.returnConnection(connectionInfo, ConnectionReturnAction.RETURN_HANDLE);
assertTrue("Expected returned", returned);
assertTrue("Expected not committed", !committed);
}
public void testTransactionShareableConnection() throws Exception {
transactionManager.begin();
ConnectionInfo connectionInfo = makeConnectionInfo();
transactionEnlistingInterceptor.getConnection(connectionInfo);
assertTrue("Expected started", started);
assertTrue("Expected not ended", !ended);
started = false;
transactionEnlistingInterceptor.returnConnection(connectionInfo, ConnectionReturnAction.RETURN_HANDLE);
assertTrue("Expected not started", !started);
assertTrue("Expected ended", ended);
assertTrue("Expected returned", returned);
transactionManager.commit();
assertTrue("Expected committed", committed);
}
public void testTransactionUnshareableConnection() throws Exception {
transactionManager.begin();
ConnectionInfo connectionInfo = makeConnectionInfo();
connectionInfo.setUnshareable(true);
transactionEnlistingInterceptor.getConnection(connectionInfo);
assertTrue("Expected started", started);
assertTrue("Expected not ended", !ended);
started = false;
transactionEnlistingInterceptor.returnConnection(connectionInfo, ConnectionReturnAction.RETURN_HANDLE);
assertTrue("Expected not started", !started);
assertTrue("Expected ended", ended);
assertTrue("Expected returned", returned);
transactionManager.commit();
assertTrue("Expected committed", committed);
}
//ConnectionInterceptor
public void getConnection(ConnectionInfo connectionInfo) throws ResourceException {
ManagedConnectionInfo managedConnectionInfo = connectionInfo.getManagedConnectionInfo();
managedConnectionInfo.setXAResource(this);
}
public void returnConnection(ConnectionInfo connectionInfo, ConnectionReturnAction connectionReturnAction) {
returned = true;
}
//XAResource
public void commit(Xid xid, boolean onePhase) throws XAException {
committed = true;
}
public void end(Xid xid, int flags) throws XAException {
ended = true;
}
public void forget(Xid xid) throws XAException {
}
public int getTransactionTimeout() throws XAException {
return 0;
}
public boolean isSameRM(XAResource xaResource) throws XAException {
return false;
}
public int prepare(Xid xid) throws XAException {
return 0;
}
public Xid[] recover(int flag) throws XAException {
return new Xid[0];
}
public void rollback(Xid xid) throws XAException {
}
public boolean setTransactionTimeout(int seconds) throws XAException {
return false;
}
public void start(Xid xid, int flags) throws XAException {
started = true;
}
}
| 6,378 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/outbound/SubjectInterceptorTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.outbound;
import javax.security.auth.Subject;
import jakarta.resource.ResourceException;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class SubjectInterceptorTest extends ConnectionInterceptorTestUtils {
private SubjectInterceptor subjectInterceptor;
protected void setUp() throws Exception {
super.setUp();
SubjectSource subjectSource = new SubjectSource() {
public Subject getSubject() throws SecurityException {
return subject;
}
};
subjectInterceptor = new SubjectInterceptor(this, subjectSource);
}
protected void tearDown() throws Exception {
super.tearDown();
subjectInterceptor = null;
}
public void testGetConnection() throws Exception {
subject = new Subject();
ConnectionInfo connectionInfo = makeConnectionInfo();
ManagedConnectionInfo managedConnectionInfo = connectionInfo.getManagedConnectionInfo();
subjectInterceptor.getConnection(connectionInfo);
assertTrue("Expected call to next with same connectionInfo", connectionInfo == obtainedConnectionInfo);
assertTrue("Expected the same managedConnectionInfo", managedConnectionInfo == connectionInfo.getManagedConnectionInfo());
assertTrue("Expected supplied subject to be inserted", subject == managedConnectionInfo.getSubject());
}
public void testReturnConnection() throws Exception {
ConnectionInfo connectionInfo = makeConnectionInfo();
subjectInterceptor.returnConnection(connectionInfo, ConnectionReturnAction.RETURN_HANDLE);
assertTrue("Expected call to next with same connectionInfo", connectionInfo == returnedConnectionInfo);
}
public void testEnterWithSameSubject() throws Exception {
makeSubject("foo");
ConnectionInfo connectionInfo = makeConnectionInfo();
managedConnection = new TestPlainManagedConnection();
subjectInterceptor.getConnection(connectionInfo);
//reset our test indicator
obtainedConnectionInfo = null;
subjectInterceptor.getConnection(connectionInfo);
assertTrue("Expected connection asked for", obtainedConnectionInfo == connectionInfo);
assertTrue("Expected no connection returned", returnedConnectionInfo == null);
}
public void testEnterWithChangedSubject() throws Exception {
makeSubject("foo");
ConnectionInfo connectionInfo = makeConnectionInfo();
managedConnection = new TestPlainManagedConnection();
subjectInterceptor.getConnection(connectionInfo);
//reset our test indicator
obtainedConnectionInfo = null;
makeSubject("bar");
subjectInterceptor.getConnection(connectionInfo);
//expect re-association
assertTrue("Expected connection asked for", obtainedConnectionInfo != null);
//connection is returned by SubjectInterceptor
assertTrue("Expected connection returned", returnedConnectionInfo != null);
}
public void testApplicationManagedSecurity() throws Exception {
makeSubject("foo");
ConnectionInfo connectionInfo = makeConnectionInfo();
connectionInfo.setApplicationManagedSecurity(true);
ManagedConnectionInfo managedConnectionInfo = connectionInfo.getManagedConnectionInfo();
managedConnection = new TestPlainManagedConnection();
subjectInterceptor.getConnection(connectionInfo);
//expect no subject set on mci
assertTrue("Expected call to next with same connectionInfo", connectionInfo == obtainedConnectionInfo);
assertTrue("Expected the same managedConnectionInfo", managedConnectionInfo == connectionInfo.getManagedConnectionInfo());
assertTrue("Expected no subject to be inserted", null == managedConnectionInfo.getSubject());
}
public void testUnshareablePreventsReAssociation() throws Exception {
makeSubject("foo");
ConnectionInfo connectionInfo = makeConnectionInfo();
connectionInfo.setUnshareable(true);
managedConnection = new TestPlainManagedConnection();
subjectInterceptor.getConnection(connectionInfo);
//reset our test indicator
obtainedConnectionInfo = null;
makeSubject("bar");
try {
subjectInterceptor.getConnection(connectionInfo);
fail("Reassociating should fail on an unshareable connection");
} catch (ResourceException e) {
}
}
}
| 6,379 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/outbound/ConnectionTrackingInterceptorTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.outbound;
import java.util.Collection;
import java.util.HashSet;
import jakarta.resource.ResourceException;
import org.apache.geronimo.connector.outbound.connectiontracking.ConnectionTracker;
/**
* TODO test unshareable resources.
* TODO test repeat calls with null/non-null Subject
*
* @version $Rev$ $Date$
*
* */
public class ConnectionTrackingInterceptorTest extends ConnectionInterceptorTestUtils
implements ConnectionTracker {
private final static String key = "test-name";
private ConnectionTrackingInterceptor connectionTrackingInterceptor;
private ConnectionTrackingInterceptor obtainedConnectionTrackingInterceptor;
private ConnectionInfo obtainedTrackedConnectionInfo;
private ConnectionTrackingInterceptor releasedConnectionTrackingInterceptor;
private ConnectionInfo releasedTrackedConnectionInfo;
private Collection connectionInfos;
protected void setUp() throws Exception {
super.setUp();
connectionTrackingInterceptor = new ConnectionTrackingInterceptor(this, key, this);
}
protected void tearDown() throws Exception {
super.tearDown();
connectionTrackingInterceptor = null;
managedConnection = null;
obtainedConnectionTrackingInterceptor = null;
obtainedTrackedConnectionInfo = null;
releasedConnectionTrackingInterceptor = null;
releasedTrackedConnectionInfo = null;
}
public void testConnectionRegistration() throws Exception {
ConnectionInfo connectionInfo = makeConnectionInfo();
connectionTrackingInterceptor.getConnection(connectionInfo);
assertTrue("Expected handleObtained call with our connectionTrackingInterceptor",
connectionTrackingInterceptor == obtainedConnectionTrackingInterceptor);
assertTrue("Expected handleObtained call with our connectionInfo",
connectionInfo == obtainedTrackedConnectionInfo);
//release connection handle
connectionTrackingInterceptor.returnConnection(connectionInfo, ConnectionReturnAction.RETURN_HANDLE);
assertTrue("Expected handleReleased call with our connectionTrackingInterceptor",
connectionTrackingInterceptor == releasedConnectionTrackingInterceptor);
assertTrue("Expected handleReleased call with our connectionInfo",
connectionInfo == releasedTrackedConnectionInfo);
}
private void getConnectionAndReenter() throws ResourceException {
ConnectionInfo connectionInfo = makeConnectionInfo();
connectionTrackingInterceptor.getConnection(connectionInfo);
//reset our test indicator
obtainedConnectionInfo = null;
connectionInfos = new HashSet();
connectionInfos.add(connectionInfo);
connectionTrackingInterceptor.enter(connectionInfos);
}
public void testEnterWithSameSubject() throws Exception {
makeSubject("foo");
getConnectionAndReenter();
//decision on re-association happens in subject interceptor
assertTrue("Expected connection asked for", obtainedConnectionInfo != null);
assertTrue("Expected no connection returned", returnedConnectionInfo == null);
}
public void testEnterWithChangedSubject() throws Exception {
testEnterWithSameSubject();
makeSubject("bar");
connectionTrackingInterceptor.enter(connectionInfos);
//expect re-association
assertTrue("Expected connection asked for", obtainedConnectionInfo != null);
//connection is returned by SubjectInterceptor
assertTrue("Expected no connection returned", returnedConnectionInfo == null);
}
public void testExitWithNonDissociatableConnection() throws Exception {
managedConnection = new TestPlainManagedConnection();
testEnterWithSameSubject();
connectionTrackingInterceptor.exit(connectionInfos);
assertTrue("Expected no connection returned", returnedConnectionInfo == null);
assertEquals("Expected one info in connectionInfos", connectionInfos.size(), 1);
}
public void testExitWithDissociatableConnection() throws Exception {
managedConnection = new TestDissociatableManagedConnection();
testEnterWithSameSubject();
assertEquals("Expected one info in connectionInfos", 1, connectionInfos.size());
connectionTrackingInterceptor.exit(connectionInfos);
assertTrue("Expected connection returned", returnedConnectionInfo != null);
assertEquals("Expected no infos in connectionInfos", 0, connectionInfos.size());
}
//ConnectionTracker interface
public void handleObtained(
ConnectionTrackingInterceptor connectionTrackingInterceptor,
ConnectionInfo connectionInfo,
boolean reassociate) {
obtainedConnectionTrackingInterceptor = connectionTrackingInterceptor;
obtainedTrackedConnectionInfo = connectionInfo;
}
public void handleReleased(
ConnectionTrackingInterceptor connectionTrackingInterceptor,
ConnectionInfo connectionInfo,
ConnectionReturnAction connectionReturnAction) {
releasedConnectionTrackingInterceptor = connectionTrackingInterceptor;
releasedTrackedConnectionInfo = connectionInfo;
}
public void setEnvironment(ConnectionInfo connectionInfo, String key) {
//unsharable = false, app security = false;
}
//ConnectionInterceptor interface
public void getConnection(ConnectionInfo connectionInfo) throws ResourceException {
super.getConnection(connectionInfo);
ManagedConnectionInfo managedConnectionInfo = connectionInfo.getManagedConnectionInfo();
managedConnectionInfo.setConnectionEventListener(new GeronimoConnectionEventListener(null, managedConnectionInfo));
managedConnectionInfo.setSubject(subject);
if (managedConnectionInfo.getManagedConnection() == null) {
managedConnectionInfo.setManagedConnection(managedConnection);
}
if (connectionInfo.getConnectionHandle() == null) {
connectionInfo.setConnectionHandle(new Object());
}
managedConnectionInfo.addConnectionHandle(connectionInfo);
}
}
| 6,380 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/outbound/LocalXAResourceInsertionInterceptorTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.outbound;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.LocalTransaction;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class LocalXAResourceInsertionInterceptorTest extends ConnectionInterceptorTestUtils {
private LocalXAResourceInsertionInterceptor localXAResourceInsertionInterceptor;
private LocalTransaction localTransaction;
private String name = "LocalXAResource";
protected void setUp() throws Exception {
super.setUp();
localXAResourceInsertionInterceptor = new LocalXAResourceInsertionInterceptor(this, name);
}
protected void tearDown() throws Exception {
super.tearDown();
localXAResourceInsertionInterceptor = null;
}
public void testInsertLocalXAResource() throws Exception {
ConnectionInfo connectionInfo = makeConnectionInfo();
localXAResourceInsertionInterceptor.getConnection(connectionInfo);
LocalXAResource returnedLocalXAResource = (LocalXAResource) connectionInfo.getManagedConnectionInfo().getXAResource();
assertTrue("Expected the same LocalTransaction", localTransaction == returnedLocalXAResource.localTransaction);
}
public void getConnection(ConnectionInfo connectionInfo) throws ResourceException {
super.getConnection(connectionInfo);
localTransaction = new TestLocalTransaction();
TestManagedConnection managedConnection = new TestManagedConnection(localTransaction);
ManagedConnectionInfo managedConnectionInfo = connectionInfo.getManagedConnectionInfo();
managedConnectionInfo.setManagedConnection(managedConnection);
}
private static class TestLocalTransaction implements LocalTransaction {
public void begin() throws ResourceException {
}
public void commit() throws ResourceException {
}
public void rollback() throws ResourceException {
}
}
private static class TestManagedConnection extends TestPlainManagedConnection {
private final LocalTransaction localTransaction;
public TestManagedConnection(LocalTransaction localTransaction) {
this.localTransaction = localTransaction;
}
public LocalTransaction getLocalTransaction() throws ResourceException {
return localTransaction;
}
}
}
| 6,381 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/outbound/XAResourceInsertionInterceptorTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.outbound;
import jakarta.resource.ResourceException;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class XAResourceInsertionInterceptorTest extends ConnectionInterceptorTestUtils {
private XAResourceInsertionInterceptor xaResourceInsertionInterceptor;
private XAResource xaResource;
private String name = "XAResource";
protected void setUp() throws Exception {
super.setUp();
xaResourceInsertionInterceptor = new XAResourceInsertionInterceptor(this, name);
}
protected void tearDown() throws Exception {
super.tearDown();
xaResourceInsertionInterceptor = null;
}
public void testInsertXAResource() throws Exception {
ConnectionInfo connectionInfo = makeConnectionInfo();
xaResource = new TestXAResource();
managedConnection = new TestManagedConnection(xaResource);
xaResourceInsertionInterceptor.getConnection(connectionInfo);
xaResource.setTransactionTimeout(200);
//xaresource is wrapped, so we do something to ours to make it distinguishable.
assertEquals("Expected the same XAResource", 200, connectionInfo.getManagedConnectionInfo().getXAResource().getTransactionTimeout());
}
private static class TestXAResource implements XAResource {
private int txTimeout;
public void commit(Xid xid, boolean onePhase) throws XAException {
}
public void end(Xid xid, int flags) throws XAException {
}
public void forget(Xid xid) throws XAException {
}
public int getTransactionTimeout() throws XAException {
return txTimeout;
}
public boolean isSameRM(XAResource xaResource) throws XAException {
return false;
}
public int prepare(Xid xid) throws XAException {
return 0;
}
public Xid[] recover(int flag) throws XAException {
return new Xid[0];
}
public void rollback(Xid xid) throws XAException {
}
public boolean setTransactionTimeout(int seconds) throws XAException {
this.txTimeout = seconds;
return false;
}
public void start(Xid xid, int flags) throws XAException {
}
}
private static class TestManagedConnection extends TestPlainManagedConnection {
private final XAResource xaResource;
public TestManagedConnection(XAResource xaResource) {
this.xaResource = xaResource;
}
public XAResource getXAResource() throws ResourceException {
return xaResource;
}
}
}
| 6,382 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/outbound/AbstractSinglePoolTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.connector.outbound;
import java.util.List;
import java.util.ArrayList;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ManagedConnectionFactory;
import junit.framework.TestCase;
import org.apache.geronimo.connector.mock.MockManagedConnectionFactory;
/**
* @version $Rev$ $Date$
*/
public abstract class AbstractSinglePoolTest extends TestCase {
private ManagedConnectionFactory mcf = new MockManagedConnectionFactory();
protected SwitchableInterceptor switchableInterceptor;
protected AbstractSinglePoolConnectionInterceptor interceptor;
protected int maxSize = 10;
protected void setUp() throws Exception {
ConnectionInterceptor interceptor = new MCFConnectionInterceptor();
switchableInterceptor = new SwitchableInterceptor(interceptor);
}
/**
* Check that you can only get maxSize connections out, whether you return or destroy them.
* Check the pool state after each round.
* @throws Exception if test fails
*/
public void testInitialMaxSize() throws Exception {
getConnections(ConnectionReturnAction.RETURN_HANDLE);
assertEquals(maxSize, interceptor.getConnectionCount());
assertEquals(maxSize, interceptor.getIdleConnectionCount());
getConnections(ConnectionReturnAction.DESTROY);
assertEquals(0, interceptor.getConnectionCount());
assertEquals(0, interceptor.getIdleConnectionCount());
getConnections(ConnectionReturnAction.RETURN_HANDLE);
}
/**
* Check that if connections cannot be created, no permits are expended.
* @throws Exception if test fails
*/
public void testConnectionsUnavailable() throws Exception {
switchableInterceptor.setOn(false);
for (int i = 0; i < maxSize; i++) {
try {
getConnection();
fail("Connections should be unavailable");
} catch (ResourceException e) {
//pass
}
}
switchableInterceptor.setOn(true);
getConnections(ConnectionReturnAction.DESTROY);
switchableInterceptor.setOn(false);
for (int i = 0; i < maxSize; i++) {
try {
getConnection();
fail("Connections should be unavailable");
} catch (ResourceException e) {
//pass
}
}
}
/**
* Test that increasing the size of the pool has the expected effects on the connection count
* and ability to get connections.
* @throws Exception if test fails
*/
public void testResizeUp() throws Exception {
getConnections(ConnectionReturnAction.RETURN_HANDLE);
int maxSize = this.maxSize;
assertEquals(maxSize, interceptor.getConnectionCount());
assertEquals(maxSize, interceptor.getIdleConnectionCount());
this.maxSize = 20;
interceptor.setPartitionMaxSize(this.maxSize);
assertEquals(maxSize, interceptor.getConnectionCount());
assertEquals(maxSize, interceptor.getIdleConnectionCount());
getConnections(ConnectionReturnAction.RETURN_HANDLE);
assertEquals(this.maxSize, interceptor.getConnectionCount());
assertEquals(this.maxSize, interceptor.getIdleConnectionCount());
}
/**
* Check that decreasing the pool size while the pool is full (no connections checked out)
* immediately destroys the expected number of excess connections and leaves the pool full with
* the new max size
* @throws Exception if test fails
*/
public void testResizeDown() throws Exception {
getConnections(ConnectionReturnAction.RETURN_HANDLE);
assertEquals(maxSize, interceptor.getConnectionCount());
assertEquals(maxSize, interceptor.getIdleConnectionCount());
this.maxSize = 5;
interceptor.setPartitionMaxSize(this.maxSize);
assertEquals(maxSize, interceptor.getConnectionCount());
assertEquals(maxSize, interceptor.getIdleConnectionCount());
getConnections(ConnectionReturnAction.RETURN_HANDLE);
assertEquals(this.maxSize, interceptor.getConnectionCount());
assertEquals(this.maxSize, interceptor.getIdleConnectionCount());
}
/**
* Check that, with all the connections checked out, shrinking the pool results in the
* expected number of connections being destroyed when they are returned.
* @throws Exception if test fails
*/
public void testShrinkLater() throws Exception {
List<ConnectionInfo> cis = new ArrayList<ConnectionInfo>();
for (int i = 0; i < maxSize; i++) {
cis.add(getConnection());
}
assertEquals(maxSize, interceptor.getConnectionCount());
assertEquals(0, interceptor.getIdleConnectionCount());
int oldMaxSize = maxSize;
maxSize = 5;
interceptor.setPartitionMaxSize(maxSize);
try {
getConnection();
fail("Pool should be exhausted");
} catch (ResourceException e) {
//pass
}
for (int i = 0; i< oldMaxSize - maxSize; i++) {
interceptor.returnConnection(cis.remove(0), ConnectionReturnAction.RETURN_HANDLE);
}
try {
getConnection();
fail("Pool should be exhausted");
} catch (ResourceException e) {
//pass
}
assertEquals(maxSize, interceptor.getConnectionCount());
assertEquals(0, interceptor.getIdleConnectionCount());
for (int i = 0; i< maxSize; i++) {
interceptor.returnConnection(cis.remove(0), ConnectionReturnAction.RETURN_HANDLE);
}
assertEquals(maxSize, interceptor.getConnectionCount());
assertEquals(maxSize, interceptor.getIdleConnectionCount());
getConnections(ConnectionReturnAction.RETURN_HANDLE);
assertEquals(maxSize, interceptor.getConnectionCount());
assertEquals(maxSize, interceptor.getIdleConnectionCount());
}
/**
* Check that the calculation of "shrinkLater" is correct when the pool is shrunk twice before
* all the "shrinkLater" connections are returned.
* @throws Exception if test fails
*/
public void testShrinkLaterTwice() throws Exception {
List<ConnectionInfo> cis = new ArrayList<ConnectionInfo>();
for (int i = 0; i < maxSize; i++) {
cis.add(getConnection());
}
assertEquals(maxSize, interceptor.getConnectionCount());
assertEquals(0, interceptor.getIdleConnectionCount());
int oldMaxSize = maxSize;
maxSize = 7;
interceptor.setPartitionMaxSize(maxSize);
try {
getConnection();
fail("Pool should be exhausted");
} catch (ResourceException e) {
//pass
}
interceptor.returnConnection(cis.remove(0), ConnectionReturnAction.RETURN_HANDLE);
oldMaxSize--;
maxSize = 5;
interceptor.setPartitionMaxSize(maxSize);
try {
getConnection();
fail("Pool should be exhausted");
} catch (ResourceException e) {
//pass
}
for (int i = 0; i< oldMaxSize - maxSize; i++) {
interceptor.returnConnection(cis.remove(0), ConnectionReturnAction.RETURN_HANDLE);
}
try {
getConnection();
fail("Pool should be exhausted");
} catch (ResourceException e) {
//pass
}
assertEquals(maxSize, interceptor.getConnectionCount());
assertEquals(0, interceptor.getIdleConnectionCount());
for (int i = 0; i< maxSize; i++) {
interceptor.returnConnection(cis.remove(0), ConnectionReturnAction.RETURN_HANDLE);
}
assertEquals(maxSize, interceptor.getConnectionCount());
assertEquals(maxSize, interceptor.getIdleConnectionCount());
getConnections(ConnectionReturnAction.RETURN_HANDLE);
assertEquals(maxSize, interceptor.getConnectionCount());
assertEquals(maxSize, interceptor.getIdleConnectionCount());
}
private void getConnections(ConnectionReturnAction connectionReturnAction) throws ResourceException {
List<ConnectionInfo> cis = new ArrayList<ConnectionInfo>();
for (int i = 0; i < maxSize; i++) {
cis.add(getConnection());
}
try {
getConnection();
fail("Pool should be exhausted");
} catch (ResourceException e) {
//pass
}
for (ConnectionInfo ci: cis) {
interceptor.returnConnection(ci, connectionReturnAction);
}
}
private ConnectionInfo getConnection() throws ResourceException {
ManagedConnectionInfo mci = new ManagedConnectionInfo(mcf, null);
ConnectionInfo ci = new ConnectionInfo(mci);
interceptor.getConnection(ci);
return ci;
}
private static class SwitchableInterceptor implements ConnectionInterceptor {
private final ConnectionInterceptor next;
private boolean on = true;
private SwitchableInterceptor(ConnectionInterceptor next) {
this.next = next;
}
public void setOn(boolean on) {
this.on = on;
}
public void getConnection(ConnectionInfo connectionInfo) throws ResourceException {
if (on) {
next.getConnection(connectionInfo);
} else {
throw new ResourceException();
}
}
public void returnConnection(ConnectionInfo connectionInfo, ConnectionReturnAction connectionReturnAction) {
next.returnConnection(connectionInfo, connectionReturnAction);
}
public void destroy() {
next.destroy();
}
public void info(StringBuilder s) {
s.append(getClass().getName()).append("\n");
next.info(s);
}
}
}
| 6,383 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/outbound/TransactionCachingInterceptorTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.outbound;
import jakarta.resource.ResourceException;
import jakarta.transaction.Transaction;
import jakarta.transaction.TransactionManager;
import jakarta.transaction.Status;
import org.apache.geronimo.connector.ConnectorTransactionContext;
import org.apache.geronimo.transaction.manager.TransactionManagerImpl;
/**
*
*
* @version $Rev$ $Date$
*
* */
public class TransactionCachingInterceptorTest extends ConnectionInterceptorTestUtils {
private TransactionManager transactionManager;
private TransactionCachingInterceptor transactionCachingInterceptor;
protected void setUp() throws Exception {
super.setUp();
transactionManager = new TransactionManagerImpl();
transactionCachingInterceptor = new TransactionCachingInterceptor(this, transactionManager);
}
protected void tearDown() throws Exception {
super.tearDown();
transactionManager = null;
transactionCachingInterceptor = null;
}
public void testGetConnectionInTransaction() throws Exception {
transactionManager.begin();
ConnectionInfo connectionInfo1 = makeConnectionInfo();
transactionCachingInterceptor.getConnection(connectionInfo1);
assertTrue("Expected to get an initial connection", obtainedConnectionInfo != null);
assertTrue("Expected nothing returned yet", returnedConnectionInfo == null);
assertTrue("Expected the same ManagedConnectionInfo in the TransactionContext as was returned",
connectionInfo1.getManagedConnectionInfo()
== getSharedManagedConnectionInfo(transactionManager.getTransaction()));
obtainedConnectionInfo = null;
ConnectionInfo connectionInfo2 = new ConnectionInfo();
transactionCachingInterceptor.getConnection(connectionInfo2);
assertTrue("Expected to not get a second connection", obtainedConnectionInfo == null);
assertTrue("Expected nothing returned yet", returnedConnectionInfo == null);
assertTrue("Expected the same ManagedConnectionInfo in both ConnectionInfos",
connectionInfo1.getManagedConnectionInfo() == connectionInfo2.getManagedConnectionInfo());
assertTrue("Expected the same ManagedConnectionInfo in the TransactionContext as was returned",
connectionInfo1.getManagedConnectionInfo() == getSharedManagedConnectionInfo(transactionManager.getTransaction()));
//commit, see if connection returned.
//we didn't create any handles, so the "ManagedConnection" should be returned.
assertTrue("Expected TransactionContext to report active", TxUtil.isTransactionActive(transactionManager));
transactionManager.commit();
assertTrue("Expected connection to be returned", returnedConnectionInfo != null);
assertTrue("Expected TransactionContext to report inactive", !TxUtil.isTransactionActive(transactionManager));
}
public void testGetUnshareableConnectionsInTransaction() throws Exception {
transactionManager.begin();
ConnectionInfo connectionInfo1 = makeConnectionInfo();
connectionInfo1.setUnshareable(true);
transactionCachingInterceptor.getConnection(connectionInfo1);
assertTrue("Expected to get an initial connection", obtainedConnectionInfo != null);
assertTrue("Expected nothing returned yet", returnedConnectionInfo == null);
//2nd is shared, modelling a call into another ejb
obtainedConnectionInfo = null;
ConnectionInfo connectionInfo2 = makeConnectionInfo();
transactionCachingInterceptor.getConnection(connectionInfo2);
assertTrue("Expected to get a second connection", obtainedConnectionInfo != null);
assertTrue("Expected nothing returned yet", returnedConnectionInfo == null);
assertTrue("Expected the same ManagedConnectionInfo in both ConnectionInfos",
connectionInfo1.getManagedConnectionInfo() != connectionInfo2.getManagedConnectionInfo());
//3rd is unshared, modelling a call into a third ejb
obtainedConnectionInfo = null;
ConnectionInfo connectionInfo3 = makeConnectionInfo();
connectionInfo3.setUnshareable(true);
transactionCachingInterceptor.getConnection(connectionInfo3);
assertTrue("Expected to get a third connection", obtainedConnectionInfo != null);
assertTrue("Expected nothing returned yet", returnedConnectionInfo == null);
assertTrue("Expected different ManagedConnectionInfo in both unshared ConnectionInfos",
connectionInfo1.getManagedConnectionInfo() != connectionInfo3.getManagedConnectionInfo());
//commit, see if connection returned.
//we didn't create any handles, so the "ManagedConnection" should be returned.
assertTrue("Expected TransactionContext to report active", transactionManager.getStatus() == Status.STATUS_ACTIVE);
transactionManager.commit();
assertTrue("Expected connection to be returned", returnedConnectionInfo != null);
}
private ManagedConnectionInfo getSharedManagedConnectionInfo(Transaction transaction) {
if (transaction == null) return null;
return ConnectorTransactionContext.get(transaction, transactionCachingInterceptor).getShared();
}
public void testGetConnectionOutsideTransaction() throws Exception {
ConnectionInfo connectionInfo1 = makeConnectionInfo();
transactionCachingInterceptor.getConnection(connectionInfo1);
assertTrue("Expected to get an initial connection", obtainedConnectionInfo != null);
assertTrue("Expected nothing returned yet", returnedConnectionInfo == null);
obtainedConnectionInfo = null;
ConnectionInfo connectionInfo2 = makeConnectionInfo();
transactionCachingInterceptor.getConnection(connectionInfo2);
assertTrue("Expected to get a second connection", obtainedConnectionInfo != null);
assertTrue("Expected nothing returned yet", returnedConnectionInfo == null);
assertTrue("Expected different ManagedConnectionInfo in both ConnectionInfos",
connectionInfo1.getManagedConnectionInfo() != connectionInfo2.getManagedConnectionInfo());
//we didn't create any handles, so the "ManagedConnection" should be returned.
transactionCachingInterceptor.returnConnection(connectionInfo1, ConnectionReturnAction.RETURN_HANDLE);
assertTrue("Expected connection to be returned", returnedConnectionInfo != null);
returnedConnectionInfo = null;
transactionCachingInterceptor.returnConnection(connectionInfo2, ConnectionReturnAction.RETURN_HANDLE);
assertTrue("Expected connection to be returned", returnedConnectionInfo != null);
}
public void testTransactionIndependence() throws Exception {
transactionManager.begin();
ConnectionInfo connectionInfo1 = makeConnectionInfo();
transactionCachingInterceptor.getConnection(connectionInfo1);
obtainedConnectionInfo = null;
//start a second transaction
Transaction suspendedTransaction = transactionManager.suspend();
transactionManager.begin();
ConnectionInfo connectionInfo2 = makeConnectionInfo();
transactionCachingInterceptor.getConnection(connectionInfo2);
assertTrue("Expected to get a second connection", obtainedConnectionInfo != null);
assertTrue("Expected nothing returned yet", returnedConnectionInfo == null);
assertTrue("Expected different ManagedConnectionInfo in each ConnectionInfos",
connectionInfo1.getManagedConnectionInfo() != connectionInfo2.getManagedConnectionInfo());
assertTrue("Expected the same ManagedConnectionInfo in the TransactionContext as was returned",
connectionInfo2.getManagedConnectionInfo() == getSharedManagedConnectionInfo(transactionManager.getTransaction()));
//commit 2nd transaction, see if connection returned.
//we didn't create any handles, so the "ManagedConnection" should be returned.
assertTrue("Expected TransactionContext to report active", transactionManager.getStatus() == Status.STATUS_ACTIVE);
transactionManager.commit();
assertTrue("Expected connection to be returned", returnedConnectionInfo != null);
assertTrue("Expected TransactionContext to report inactive", transactionManager.getStatus() == Status.STATUS_NO_TRANSACTION);
returnedConnectionInfo = null;
//resume first transaction
transactionManager.resume(suspendedTransaction);
transactionManager.commit();
assertTrue("Expected connection to be returned", returnedConnectionInfo != null);
assertTrue("Expected TransactionContext to report inactive", transactionManager.getStatus() == Status.STATUS_NO_TRANSACTION);
}
//interface implementations
public void getConnection(ConnectionInfo connectionInfo) throws ResourceException {
super.getConnection(connectionInfo);
ManagedConnectionInfo managedConnectionInfo = connectionInfo.getManagedConnectionInfo();
managedConnectionInfo.setConnectionEventListener(new GeronimoConnectionEventListener(null, managedConnectionInfo));
}
public void handleObtained(
ConnectionTrackingInterceptor connectionTrackingInterceptor,
ConnectionInfo connectionInfo) {
}
public void handleReleased(
ConnectionTrackingInterceptor connectionTrackingInterceptor,
ConnectionInfo connectionInfo) {
}
}
| 6,384 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/outbound | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/outbound/connectiontracking/ConnectionTrackingCoordinatorProxyTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.outbound.connectiontracking;
import junit.framework.TestCase;
import org.apache.geronimo.connector.outbound.ConnectionInterceptor;
import org.apache.geronimo.connector.outbound.ConnectionTrackingInterceptor;
import org.apache.geronimo.connector.outbound.ConnectionInfo;
import org.apache.geronimo.connector.outbound.ConnectionReturnAction;
import org.apache.geronimo.connector.outbound.ManagedConnectionInfo;
import org.apache.geronimo.connector.outbound.GeronimoConnectionEventListener;
import javax.security.auth.Subject;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ManagedConnection;
import jakarta.resource.spi.ConnectionRequestInfo;
import jakarta.resource.spi.ConnectionEventListener;
import jakarta.resource.spi.LocalTransaction;
import jakarta.resource.spi.ManagedConnectionMetaData;
import javax.transaction.xa.XAResource;
import java.util.Set;
import java.util.HashSet;
import java.util.Map;
import java.lang.reflect.Proxy;
import java.io.PrintWriter;
/**
* @version $Rev: 476049 $ $Date: 2006-11-16 20:35:17 -0800 (Thu, 16 Nov 2006) $
*/
public class ConnectionTrackingCoordinatorProxyTest extends TestCase implements ConnectionInterceptor {
private static final String name1 = "foo";
private ConnectionTrackingCoordinator connectionTrackingCoordinator;
private ConnectionTrackingInterceptor key1;
private Subject subject = null;
private Set<String> unshareableResources;
private Set<String> applicationManagedSecurityResources;
private ManagedConnectionInfo mci;
private ConnectionImpl connection;
protected void setUp() throws Exception {
super.setUp();
connectionTrackingCoordinator = new ConnectionTrackingCoordinator(true);
key1 = new ConnectionTrackingInterceptor(this, name1, connectionTrackingCoordinator);
unshareableResources = new HashSet<String>();
applicationManagedSecurityResources = new HashSet<String>();
mci = new ManagedConnectionInfo(null, null);
mci.setManagedConnection(new MockManagedConnection());
mci.setConnectionEventListener(new GeronimoConnectionEventListener(this, mci));
connection = new ConnectionImpl("ConnectionString");
}
protected void tearDown() throws Exception {
connectionTrackingCoordinator = null;
key1 = null;
super.tearDown();
}
public void testSimpleComponentContextLifecyle() throws Exception {
// enter component context
ConnectorInstanceContextImpl componentContext = new ConnectorInstanceContextImpl(unshareableResources, applicationManagedSecurityResources);
ConnectorInstanceContext oldConnectorInstanceContext = connectionTrackingCoordinator.enter(componentContext);
assertNull("Expected old instance context to be null", oldConnectorInstanceContext);
// simulate create connection
ConnectionInfo connectionInfo = createConnectionInfo();
connectionTrackingCoordinator.handleObtained(key1, connectionInfo, false);
// connection should be in component instance context
Map<ConnectionTrackingInterceptor, Set<ConnectionInfo>> connectionManagerMap = componentContext.getConnectionManagerMap();
Set<ConnectionInfo> infos = connectionManagerMap.get(key1);
assertNotNull("Expected one connections for key1", infos);
assertEquals("Expected one connection for key1", 1, infos.size());
assertTrue("Expected to get supplied ConnectionInfo from infos", connectionInfo == infos.iterator().next());
// verify handle
Object handle = connectionInfo.getConnectionHandle();
assertNotNull("Expected a handle from ConnectionInfo", handle);
assertTrue("Expected handle to be an instance of ConnectionImpl", handle instanceof ConnectionImpl);
ConnectionImpl connection = (ConnectionImpl) handle;
assertEquals("connection.getString()", "ConnectionString", connection.getString());
// verify proxy
Object proxy = connectionInfo.getConnectionProxy();
assertNotNull("Expected a proxy from ConnectionInfo", proxy);
assertTrue("Expected proxy to be an instance of Connection", proxy instanceof Connection);
Connection connectionProxy = (Connection) proxy;
assertEquals("connection.getString()", "ConnectionString", connectionProxy.getString());
assertSame("Expected connection.getUnmanaged() to be connectionImpl", connection, connectionProxy.getUnmanaged());
assertNotSame("Expected connection be proxied", connection, connectionProxy);
// exit component context
connectionTrackingCoordinator.exit(oldConnectorInstanceContext);
// connection should not be in context
connectionManagerMap = componentContext.getConnectionManagerMap();
infos = connectionManagerMap.get(key1);
assertEquals("Expected no connection set for key1", null, infos);
// enter again, and close the handle
oldConnectorInstanceContext = connectionTrackingCoordinator.enter(componentContext);
assertNull("Expected old instance context to be null", oldConnectorInstanceContext);
connectionTrackingCoordinator.handleReleased(key1, connectionInfo, ConnectionReturnAction.DESTROY);
connectionTrackingCoordinator.exit(oldConnectorInstanceContext);
// use connection which will cause it to get a new handle if it is not closed
ConnectionTrackingCoordinator.ConnectionInvocationHandler invocationHandler = (ConnectionTrackingCoordinator.ConnectionInvocationHandler) Proxy.getInvocationHandler(connectionProxy);
assertEquals("connection.getString()", "ConnectionString", connectionProxy.getString());
assertTrue("Proxy should be connected", invocationHandler.isReleased());
assertSame("Expected connection.getUnmanaged() to be original connection", connection, connection.getUnmanaged());
}
public void testReassociateConnection() throws Exception {
// enter component context
ConnectorInstanceContextImpl componentContext = new ConnectorInstanceContextImpl(unshareableResources, applicationManagedSecurityResources);
ConnectorInstanceContext oldConnectorInstanceContext1 = connectionTrackingCoordinator.enter(componentContext);
assertNull("Expected old component context to be null", oldConnectorInstanceContext1);
// simulate create connection
ConnectionInfo connectionInfo = createConnectionInfo();
connectionTrackingCoordinator.handleObtained(key1, connectionInfo, false);
// connection should be in component instance context
Map<ConnectionTrackingInterceptor, Set<ConnectionInfo>> connectionManagerMap = componentContext.getConnectionManagerMap();
Set<ConnectionInfo> infos = connectionManagerMap.get(key1);
assertNotNull("Expected one connections for key1", infos);
assertEquals("Expected one connection for key1", 1, infos.size());
assertTrue("Expected to get supplied ConnectionInfo from infos", connectionInfo == infos.iterator().next());
// verify handle
Object handle = connectionInfo.getConnectionHandle();
assertNotNull("Expected a handle from ConnectionInfo", handle);
assertTrue("Expected handle to be an instance of ConnectionImpl", handle instanceof ConnectionImpl);
ConnectionImpl connection = (ConnectionImpl) handle;
assertEquals("connection.getString()", "ConnectionString", connection.getString());
// verify proxy
Object proxy = connectionInfo.getConnectionProxy();
assertNotNull("Expected a proxy from ConnectionInfo", proxy);
assertTrue("Expected proxy to be an instance of Connection", proxy instanceof Connection);
Connection connectionProxy = (Connection) proxy;
assertEquals("connection.getString()", "ConnectionString", connectionProxy.getString());
assertSame("Expected connection.getUnmanaged() to be connectionImpl", connection, connectionProxy.getUnmanaged());
assertNotSame("Expected connection be proxied", connection, connectionProxy);
// exit outer component context
connectionTrackingCoordinator.exit(oldConnectorInstanceContext1);
// proxy should be disconnected
ConnectionTrackingCoordinator.ConnectionInvocationHandler invocationHandler = (ConnectionTrackingCoordinator.ConnectionInvocationHandler) Proxy.getInvocationHandler(connectionProxy);
assertTrue("Proxy should be disconnected", invocationHandler.isReleased());
// enter again
oldConnectorInstanceContext1 = connectionTrackingCoordinator.enter(componentContext);
assertNull("Expected old component context to be null", oldConnectorInstanceContext1);
// use connection to cause it to get a new handle
assertEquals("connection.getString()", "ConnectionString", connectionProxy.getString());
assertSame("Expected connection.getUnmanaged() to be original connection", connection, connection.getUnmanaged());
assertNotSame("Expected connection to not be original connection", connection, connectionProxy);
// destroy handle and exit context
connectionTrackingCoordinator.handleReleased(key1, connectionInfo, ConnectionReturnAction.DESTROY);
connectionTrackingCoordinator.exit(oldConnectorInstanceContext1);
// connection should not be in context
connectionManagerMap = componentContext.getConnectionManagerMap();
infos = connectionManagerMap.get(key1);
assertNull("Expected no connection set for key1", infos);
// use connection which will cause it to get a new handle if it is not closed
assertEquals("connection.getString()", "ConnectionString", connectionProxy.getString());
assertTrue("Proxy should be connected", invocationHandler.isReleased());
assertSame("Expected connection.getUnmanaged() to be original connection", connection, connection.getUnmanaged());
}
// some code calls the release method using a freshly constructed ContainerInfo without a proxy
// the ConnectionTrackingCoordinator must find the correct proxy and call releaseHandle or destroy
public void testReleaseNoProxy() throws Exception {
// enter component context
ConnectorInstanceContextImpl componentContext = new ConnectorInstanceContextImpl(unshareableResources, applicationManagedSecurityResources);
ConnectorInstanceContext oldConnectorInstanceContext1 = connectionTrackingCoordinator.enter(componentContext);
assertNull("Expected old component context to be null", oldConnectorInstanceContext1);
// simulate create connection
ConnectionInfo connectionInfo = createConnectionInfo();
connectionTrackingCoordinator.handleObtained(key1, connectionInfo, false);
// connection should be in component instance context
Map<ConnectionTrackingInterceptor, Set<ConnectionInfo>> connectionManagerMap = componentContext.getConnectionManagerMap();
Set<ConnectionInfo> infos = connectionManagerMap.get(key1);
assertNotNull("Expected one connections for key1", infos);
assertEquals("Expected one connection for key1", 1, infos.size());
assertTrue("Expected to get supplied ConnectionInfo from infos", connectionInfo == infos.iterator().next());
// verify handle
Object handle = connectionInfo.getConnectionHandle();
assertNotNull("Expected a handle from ConnectionInfo", handle);
assertTrue("Expected handle to be an instance of ConnectionImpl", handle instanceof ConnectionImpl);
ConnectionImpl connection = (ConnectionImpl) handle;
assertEquals("connection.getString()", "ConnectionString", connection.getString());
// verify proxy
Object proxy = connectionInfo.getConnectionProxy();
assertNotNull("Expected a proxy from ConnectionInfo", proxy);
assertTrue("Expected proxy to be an instance of Connection", proxy instanceof Connection);
Connection connectionProxy = (Connection) proxy;
assertEquals("connection.getString()", "ConnectionString", connectionProxy.getString());
assertSame("Expected connection.getUnmanaged() to be connectionImpl", connection, connectionProxy.getUnmanaged());
assertNotSame("Expected connection be proxied", connection, connectionProxy);
// simulate handle release due to a event listener, which won't hav the proxy
connectionTrackingCoordinator.handleReleased(key1, createConnectionInfo(), ConnectionReturnAction.RETURN_HANDLE);
// proxy should be disconnected
ConnectionTrackingCoordinator.ConnectionInvocationHandler invocationHandler = (ConnectionTrackingCoordinator.ConnectionInvocationHandler) Proxy.getInvocationHandler(connectionProxy);
assertTrue("Proxy should be disconnected", invocationHandler.isReleased());
// use connection which will cause it to get a new handle if it is not closed
assertEquals("connection.getString()", "ConnectionString", connectionProxy.getString());
assertTrue("Proxy should be connected", invocationHandler.isReleased());
assertSame("Expected connection.getUnmanaged() to be original connection", connection, connection.getUnmanaged());
// exit outer component context
connectionTrackingCoordinator.exit(oldConnectorInstanceContext1);
// proxy should be disconnected
assertTrue("Proxy should be disconnected", invocationHandler.isReleased());
// connection should not be in context
connectionManagerMap = componentContext.getConnectionManagerMap();
infos = connectionManagerMap.get(key1);
assertNull("Expected no connection set for key1", infos);
// enter again
oldConnectorInstanceContext1 = connectionTrackingCoordinator.enter(componentContext);
assertNull("Expected old component context to be null", oldConnectorInstanceContext1);
// exit context
connectionTrackingCoordinator.exit(oldConnectorInstanceContext1);
// use connection which will cause it to get a new handle if it is not closed
assertEquals("connection.getString()", "ConnectionString", connectionProxy.getString());
assertTrue("Proxy should be connected", invocationHandler.isReleased());
assertSame("Expected connection.getUnmanaged() to be original connection", connection, connection.getUnmanaged());
}
public Subject mapSubject(Subject sourceSubject) {
return subject;
}
public void getConnection(ConnectionInfo connectionInfo) throws ResourceException {
}
public void returnConnection(ConnectionInfo connectionInfo, ConnectionReturnAction connectionReturnAction) {
}
public void destroy() {
}
public void info(StringBuilder s) {
s.append(getClass().getName()).append("\n");
}
private ConnectionInfo createConnectionInfo() {
ConnectionInfo ci = new ConnectionInfo(mci);
ci.setConnectionHandle(connection);
mci.addConnectionHandle(ci);
return ci;
}
public static interface Connection {
String getString();
Connection getUnmanaged();
}
public static class ConnectionImpl implements Connection {
private final String string;
public ConnectionImpl(String string) {
this.string = string;
}
public String getString() {
return string;
}
public Connection getUnmanaged() {
return this;
}
}
public static class MockManagedConnection implements ManagedConnection {
public Object getConnection(Subject defaultSubject, ConnectionRequestInfo connectionRequestInfo) throws ResourceException {
return null;
}
public void destroy() throws ResourceException {
}
public void cleanup() throws ResourceException {
}
public void associateConnection(Object object) throws ResourceException {
}
public void addConnectionEventListener(ConnectionEventListener connectionEventListener) {
}
public void removeConnectionEventListener(ConnectionEventListener connectionEventListener) {
}
public XAResource getXAResource() throws ResourceException {
return null;
}
public LocalTransaction getLocalTransaction() throws ResourceException {
return null;
}
public ManagedConnectionMetaData getMetaData() throws ResourceException {
return null;
}
public void setLogWriter(PrintWriter printWriter) throws ResourceException {
}
public PrintWriter getLogWriter() throws ResourceException {
return null;
}
public void dissociateConnections() throws ResourceException {
}
}
}
| 6,385 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/outbound | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/outbound/connectiontracking/ConnectionTrackingCoordinatorTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.outbound.connectiontracking;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import jakarta.resource.ResourceException;
import javax.security.auth.Subject;
import junit.framework.TestCase;
import org.apache.geronimo.connector.outbound.ConnectionInfo;
import org.apache.geronimo.connector.outbound.ConnectionInterceptor;
import org.apache.geronimo.connector.outbound.ConnectionReturnAction;
import org.apache.geronimo.connector.outbound.ConnectionTrackingInterceptor;
import org.apache.geronimo.connector.outbound.ManagedConnectionInfo;
import org.apache.geronimo.connector.outbound.GeronimoConnectionEventListener;
/**
* @version $Rev$ $Date$
*/
public class ConnectionTrackingCoordinatorTest extends TestCase
implements ConnectionInterceptor {
private static final String name1 = "foo";
private static final String name2 = "bar";
private ConnectionTrackingCoordinator connectionTrackingCoordinator;
private ConnectionTrackingInterceptor key1;
private ConnectionTrackingInterceptor nestedKey;
private Subject subject = null;
private Set<String> unshareableResources;
private Set<String> applicationManagedSecurityResources;
protected void setUp() throws Exception {
super.setUp();
connectionTrackingCoordinator = new ConnectionTrackingCoordinator(false);
key1 = new ConnectionTrackingInterceptor(this, name1, connectionTrackingCoordinator);
nestedKey = new ConnectionTrackingInterceptor(this, name2, connectionTrackingCoordinator);
unshareableResources = new HashSet<String>();
applicationManagedSecurityResources = new HashSet<String>();
}
protected void tearDown() throws Exception {
connectionTrackingCoordinator = null;
key1 = null;
nestedKey = null;
super.tearDown();
}
public void testSimpleComponentContextLifecyle() throws Exception {
// enter component context
ConnectorInstanceContextImpl componentContext = new ConnectorInstanceContextImpl(unshareableResources, applicationManagedSecurityResources);
ConnectorInstanceContext oldConnectorInstanceContext = connectionTrackingCoordinator.enter(componentContext);
assertNull("Expected old instance context to be null", oldConnectorInstanceContext);
// simulate create connection
ConnectionInfo connectionInfo = newConnectionInfo();
connectionTrackingCoordinator.handleObtained(key1, connectionInfo, false);
// exit component context
connectionTrackingCoordinator.exit(oldConnectorInstanceContext);
// connection should be in component instance context
Map<ConnectionTrackingInterceptor, Set<ConnectionInfo>> connectionManagerMap = componentContext.getConnectionManagerMap();
Set<ConnectionInfo> infos = connectionManagerMap.get(key1);
assertNotNull("Expected one connections for key1", infos);
assertEquals("Expected one connection for key1", 1, infos.size());
assertTrue("Expected to get supplied ConnectionInfo from infos", connectionInfo == infos.iterator().next());
// enter again, and close the handle
oldConnectorInstanceContext = connectionTrackingCoordinator.enter(componentContext);
assertNull("Expected old instance context to be null", oldConnectorInstanceContext);
connectionTrackingCoordinator.handleReleased(key1, connectionInfo, ConnectionReturnAction.DESTROY);
connectionTrackingCoordinator.exit(oldConnectorInstanceContext);
// connection should not be in context
connectionManagerMap = componentContext.getConnectionManagerMap();
infos = connectionManagerMap.get(key1);
assertEquals("Expected no connection set for key1", null, infos);
}
private ConnectionInfo newConnectionInfo() {
ManagedConnectionInfo mci = new ManagedConnectionInfo(null, null);
mci.setConnectionEventListener(new GeronimoConnectionEventListener(this, mci));
ConnectionInfo ci = new ConnectionInfo(mci);
ci.setConnectionHandle(new Object());
mci.addConnectionHandle(ci);
return ci;
}
public void testNestedComponentContextLifecyle() throws Exception {
// enter component context
ConnectorInstanceContextImpl componentContext1 = new ConnectorInstanceContextImpl(unshareableResources, applicationManagedSecurityResources);
ConnectorInstanceContext oldConnectorInstanceContext1 = connectionTrackingCoordinator.enter(componentContext1);
assertNull("Expected old component context to be null", oldConnectorInstanceContext1);
// simulate create connection
ConnectionInfo connectionInfo1 = newConnectionInfo();
connectionTrackingCoordinator.handleObtained(key1, connectionInfo1, false);
// enter another (nested) component context
ConnectorInstanceContextImpl nextedComponentContext = new ConnectorInstanceContextImpl(unshareableResources, applicationManagedSecurityResources);
ConnectorInstanceContext oldConnectorInstanceContext2 = connectionTrackingCoordinator.enter(nextedComponentContext);
assertTrue("Expected returned component context to be componentContext1", oldConnectorInstanceContext2 == componentContext1);
// simulate create connection in nested context
ConnectionInfo nestedConnectionInfo = newConnectionInfo();
connectionTrackingCoordinator.handleObtained(nestedKey, nestedConnectionInfo, false);
// exit nested component context
connectionTrackingCoordinator.exit(oldConnectorInstanceContext2);
Map<ConnectionTrackingInterceptor, Set<ConnectionInfo>> nestedConnectionManagerMap = nextedComponentContext.getConnectionManagerMap();
Set<ConnectionInfo> nestedInfos = nestedConnectionManagerMap.get(nestedKey);
assertNotNull("Expected one connections for key2", nestedInfos);
assertEquals("Expected one connection for key2", 1, nestedInfos.size());
assertSame("Expected to get supplied ConnectionInfo from infos", nestedConnectionInfo, nestedInfos.iterator().next());
assertNull("Expected no connection for key1", nestedConnectionManagerMap.get(key1));
// exit outer component context
connectionTrackingCoordinator.exit(oldConnectorInstanceContext1);
Map<ConnectionTrackingInterceptor, Set<ConnectionInfo>> connectionManagerMap = componentContext1.getConnectionManagerMap();
Set<ConnectionInfo> infos1 = connectionManagerMap.get(key1);
assertNotNull("Expected one connections for key1", infos1);
assertEquals("Expected one connection for key1", 1, infos1.size());
assertSame("Expected to get supplied ConnectionInfo from infos", connectionInfo1, infos1.iterator().next());
assertNull("Expected no connection for key2", connectionManagerMap.get(nestedKey));
// enter again, and close the handle
oldConnectorInstanceContext1 = connectionTrackingCoordinator.enter(componentContext1);
assertNull("Expected old component context to be null", oldConnectorInstanceContext1);
connectionTrackingCoordinator.handleReleased(key1, connectionInfo1, ConnectionReturnAction.DESTROY);
connectionTrackingCoordinator.exit(oldConnectorInstanceContext1);
// connection should not be in context
connectionManagerMap = componentContext1.getConnectionManagerMap();
infos1 = connectionManagerMap.get(key1);
assertNull("Expected no connection set for key1", infos1);
}
public Subject mapSubject(Subject sourceSubject) {
return subject;
}
public void getConnection(ConnectionInfo connectionInfo) throws ResourceException {
}
public void returnConnection(ConnectionInfo connectionInfo, ConnectionReturnAction connectionReturnAction) {
}
public void destroy() {
}
public void info(StringBuilder s) {
s.append(getClass().getName()).append("\n");
s.append("<end>");
}
}
| 6,386 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/outbound | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/outbound/connectiontracking/DefaultComponentInterceptor.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.outbound.connectiontracking;
import org.apache.geronimo.connector.outbound.connectiontracking.ConnectorInstanceContext;
import org.apache.geronimo.connector.outbound.connectiontracking.TrackedConnectionAssociator;
/**
* Sample functionality for an interceptor that enables connection caching and obtaining
* connections outside a UserTransaction.
*
* @version $Rev$ $Date$
*/
public class DefaultComponentInterceptor implements DefaultInterceptor {
private final DefaultInterceptor next;
private final TrackedConnectionAssociator trackedConnectionAssociator;
public DefaultComponentInterceptor(DefaultInterceptor next, TrackedConnectionAssociator trackedConnectionAssociator) {
this.next = next;
this.trackedConnectionAssociator = trackedConnectionAssociator;
}
public Object invoke(ConnectorInstanceContext newConnectorInstanceContext) throws Throwable {
ConnectorInstanceContext oldConnectorInstanceContext = trackedConnectionAssociator.enter(newConnectorInstanceContext);
try {
return next.invoke(newConnectorInstanceContext);
} finally {
trackedConnectionAssociator.exit(oldConnectorInstanceContext);
}
}
}
| 6,387 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/outbound | Create_ds/geronimo-txmanager/geronimo-connector/src/test/java/org/apache/geronimo/connector/outbound/connectiontracking/DefaultInterceptor.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.outbound.connectiontracking;
import org.apache.geronimo.connector.outbound.connectiontracking.ConnectorInstanceContext;
/**
*
*
* @version $Rev$ $Date$
*
* */
public interface DefaultInterceptor {
Object invoke(ConnectorInstanceContext newConnectorInstanceContext) throws Throwable;
}
| 6,388 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/AdminObjectWrapper.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector;
import java.util.Set;
import jakarta.resource.spi.ResourceAdapterAssociation;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
/**
* Wrapper around AdminObject that manages the AdminObject lifecycle.
*
* @version $Rev$ $Date$
*/
public class AdminObjectWrapper {
private final String adminObjectInterface;
private final String adminObjectClass;
protected ResourceAdapterWrapper resourceAdapterWrapper;
protected Object adminObject;
private final ValidatorFactory validatorFactory;
/**
* Normal managed constructor.
*
* @param adminObjectInterface Interface the proxy will implement.
* @param adminObjectClass Class of admin object to be wrapped.
* @throws IllegalAccessException
* @throws InstantiationException
*/
public AdminObjectWrapper(final String adminObjectInterface,
final String adminObjectClass,
final ResourceAdapterWrapper resourceAdapterWrapper,
final ClassLoader cl,
final ValidatorFactory validatorFactory) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
this.adminObjectInterface = adminObjectInterface;
this.adminObjectClass = adminObjectClass;
this.resourceAdapterWrapper = resourceAdapterWrapper;
this.validatorFactory = validatorFactory;
Class clazz = cl.loadClass(adminObjectClass);
adminObject = clazz.newInstance();
}
public String getAdminObjectInterface() {
return adminObjectInterface;
}
/**
* Returns class of wrapped AdminObject.
* @return class of wrapped AdminObject
*/
public String getAdminObjectClass() {
return adminObjectClass;
}
/**
* Starts the AdminObject. This will validate the instance and register the object instance
* with its ResourceAdapter
*
* @throws Exception if the target failed to start; this will cause a transition to the failed state
*/
public void doStart() throws Exception {
// if we have a validator factory at this point, then validate
// the resource adaptor instance
if (validatorFactory != null) {
Validator validator = validatorFactory.getValidator();
Set generalSet = validator.validate(adminObject);
if (!generalSet.isEmpty()) {
throw new ConstraintViolationException("Constraint violation for AdminObject " + adminObjectClass, generalSet);
}
}
if (adminObject instanceof ResourceAdapterAssociation) {
if (resourceAdapterWrapper == null) {
throw new IllegalStateException("Admin object expects to be registered with a ResourceAdapter, but there is no ResourceAdapter");
}
resourceAdapterWrapper.registerResourceAdapterAssociation((ResourceAdapterAssociation) adminObject);
}
}
/**
* Stops the target. This is a NOP for AdminObjects
*
* @throws Exception if the target failed to stop; this will cause a transition to the failed state
*/
public void doStop() throws Exception {
}
/**
* Fails the target. This is a nop for an AdminObject.
*/
public void doFail() {
}
}
| 6,389 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/ResourceAdapterWrapper.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector;
import java.util.Map;
import java.util.Set;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ActivationSpec;
import jakarta.resource.spi.BootstrapContext;
import jakarta.resource.spi.ResourceAdapter;
import jakarta.resource.spi.ResourceAdapterAssociation;
import jakarta.resource.spi.ResourceAdapterInternalException;
import jakarta.resource.spi.endpoint.MessageEndpointFactory;
import jakarta.transaction.SystemException;
import javax.transaction.xa.XAResource;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.apache.geronimo.transaction.manager.NamedXAResource;
import org.apache.geronimo.transaction.manager.NamedXAResourceFactory;
import org.apache.geronimo.transaction.manager.RecoverableTransactionManager;
import org.apache.geronimo.transaction.manager.WrapperNamedXAResource;
/**
* Dynamic GBean wrapper around a ResourceAdapter object, exposing the config-properties as
* GBean attributes.
*
* @version $Rev$ $Date$
*/
public class ResourceAdapterWrapper implements ResourceAdapter {
private final String name;
private final String resourceAdapterClass;
private final BootstrapContext bootstrapContext;
protected final ResourceAdapter resourceAdapter;
private final Map<String,String> messageListenerToActivationSpecMap;
private final RecoverableTransactionManager transactionManager;
private final ValidatorFactory validatorFactory;
/**
* default constructor for enhancement proxy endpoint
*/
public ResourceAdapterWrapper() {
this.name = null;
this.resourceAdapterClass = null;
this.bootstrapContext = null;
this.resourceAdapter = null;
this.messageListenerToActivationSpecMap = null;
this.transactionManager = null;
this.validatorFactory = null;
}
public ResourceAdapterWrapper(String name,
String resourceAdapterClass,
Map<String, String> messageListenerToActivationSpecMap,
BootstrapContext bootstrapContext,
RecoverableTransactionManager transactionManager,
ClassLoader cl,
ValidatorFactory validatorFactory) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
this.name = name;
this.resourceAdapterClass = resourceAdapterClass;
this.bootstrapContext = bootstrapContext;
Class clazz = cl.loadClass(resourceAdapterClass);
resourceAdapter = (ResourceAdapter) clazz.newInstance();
this.messageListenerToActivationSpecMap = messageListenerToActivationSpecMap;
this.transactionManager = transactionManager;
this.validatorFactory = validatorFactory;
}
public ResourceAdapterWrapper(String name, ResourceAdapter resourceAdapter, Map<String, String> messageListenerToActivationSpecMap, BootstrapContext bootstrapContext, RecoverableTransactionManager transactionManager, ValidatorFactory validatorFactory) {
this.name = name;
this.resourceAdapterClass = resourceAdapter.getClass().getName();
this.bootstrapContext = bootstrapContext;
this.resourceAdapter = resourceAdapter;
this.messageListenerToActivationSpecMap = messageListenerToActivationSpecMap;
this.transactionManager = transactionManager;
this.validatorFactory = validatorFactory;
}
public String getName() {
return name;
}
public String getResourceAdapterClass() {
return resourceAdapterClass;
}
public Map<String,String> getMessageListenerToActivationSpecMap() {
return messageListenerToActivationSpecMap;
}
public ResourceAdapter getResourceAdapter() {
return resourceAdapter;
}
public void registerResourceAdapterAssociation(final ResourceAdapterAssociation resourceAdapterAssociation) throws ResourceException {
resourceAdapterAssociation.setResourceAdapter(resourceAdapter);
}
public void start(BootstrapContext ctx) throws ResourceAdapterInternalException {
throw new IllegalStateException("Don't call this");
}
public void stop() {
throw new IllegalStateException("Don't call this");
}
//endpoint handling
public void endpointActivation(final MessageEndpointFactory messageEndpointFactory, final ActivationSpec activationSpec) throws ResourceException {
resourceAdapter.endpointActivation(messageEndpointFactory, activationSpec);
}
public void doRecovery(ActivationSpec activationSpec, String containerId) {
transactionManager.registerNamedXAResourceFactory(new ActivationSpecNamedXAResourceFactory(containerId, activationSpec, resourceAdapter));
}
public void deregisterRecovery(String containerId) {
transactionManager.unregisterNamedXAResourceFactory(containerId);
}
public void endpointDeactivation(final MessageEndpointFactory messageEndpointFactory, final ActivationSpec activationSpec) {
resourceAdapter.endpointDeactivation(messageEndpointFactory, activationSpec);
}
public XAResource[] getXAResources(ActivationSpec[] specs) throws ResourceException {
return resourceAdapter.getXAResources(specs);
}
public void doStart() throws Exception {
// if we have a validator factory at this point, then validate
// the resource adaptor instance
if (validatorFactory != null) {
Validator validator = validatorFactory.getValidator();
Set generalSet = validator.validate(resourceAdapter);
if (!generalSet.isEmpty()) {
throw new ConstraintViolationException("Constraint violation for ResourceAdapter " + resourceAdapterClass, generalSet);
}
}
resourceAdapter.start(bootstrapContext);
}
public void doStop() {
resourceAdapter.stop();
}
public void doFail() {
resourceAdapter.stop();
}
}
| 6,390 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/ConnectionReleaser.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector;
/**
*
*
* @version $Rev$ $Date$
*
* */
public interface ConnectionReleaser {
void afterCompletion(Object managedConnectionInfo);
}
| 6,391 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/GeronimoBootstrapContext.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector;
import java.util.Timer;
import jakarta.resource.spi.UnavailableException;
import jakarta.resource.spi.XATerminator;
import jakarta.resource.spi.work.WorkManager;
import jakarta.resource.spi.work.WorkContext;
import jakarta.transaction.TransactionSynchronizationRegistry;
import org.apache.geronimo.connector.work.GeronimoWorkManager;
/**
* GBean BootstrapContext implementation that refers to externally configured WorkManager
* and XATerminator gbeans.
*
* @version $Rev$ $Date$
*/
public class GeronimoBootstrapContext implements jakarta.resource.spi.BootstrapContext {
private final GeronimoWorkManager workManager;
private final XATerminator xATerminator;
private final TransactionSynchronizationRegistry transactionSynchronizationRegistry;
/**
* Default constructor for use as a GBean Endpoint.
*/
public GeronimoBootstrapContext() {
workManager = null;
xATerminator = null;
transactionSynchronizationRegistry = null;
}
/**
* Normal constructor for use as a GBean.
* @param workManager
* @param xaTerminator
* @param transactionSynchronizationRegistry
*/
public GeronimoBootstrapContext(GeronimoWorkManager workManager, XATerminator xaTerminator, TransactionSynchronizationRegistry transactionSynchronizationRegistry) {
this.workManager = workManager;
this.xATerminator = xaTerminator;
this.transactionSynchronizationRegistry = transactionSynchronizationRegistry;
}
/**
* @see jakarta.resource.spi.BootstrapContext#getWorkManager()
*/
public WorkManager getWorkManager() {
return workManager;
}
/**
* @see jakarta.resource.spi.BootstrapContext#getXATerminator()
*/
public XATerminator getXATerminator() {
return xATerminator;
}
/**
* @see jakarta.resource.spi.BootstrapContext#createTimer()
*/
public Timer createTimer() throws UnavailableException {
return new Timer("BootStrapTimer", true);
}
public TransactionSynchronizationRegistry getTransactionSynchronizationRegistry() {
return transactionSynchronizationRegistry;
}
public boolean isContextSupported(Class<? extends WorkContext> aClass) {
return workManager.isContextSupported(aClass);
}
}
| 6,392 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/ConnectorTransactionContext.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import jakarta.transaction.Status;
import jakarta.transaction.Synchronization;
import jakarta.transaction.SystemException;
import jakarta.transaction.Transaction;
import org.apache.geronimo.connector.outbound.TransactionCachingInterceptor;
import org.apache.geronimo.transaction.manager.TransactionImpl;
/**
* @version $Rev$ $Date$
*/
public class ConnectorTransactionContext {
private static final ConcurrentHashMap<Transaction, ConnectorTransactionContext> DATA_INDEX = new ConcurrentHashMap<Transaction, ConnectorTransactionContext>();
public static ConnectorTransactionContext get(Transaction transaction) {
if (transaction == null) {
throw new NullPointerException("transaction is null");
}
ConnectorTransactionContext ctx = DATA_INDEX.get(transaction);
if (ctx == null) {
ctx = new ConnectorTransactionContext();
try {
int status = transaction.getStatus();
if (status != Status.STATUS_COMMITTED && status != Status.STATUS_ROLLEDBACK && status != Status.STATUS_UNKNOWN) {
((TransactionImpl)transaction).registerInterposedSynchronization(new ConnectorSynchronization(ctx, transaction));
// Note: no synchronization is necessary here. Since a transaction can only be associated with a single
// thread at a time, it should not be possible for someone else to have snuck in and created a
// ConnectorTransactionContext for this transaction. We still protect against that with the putIfAbsent
// call below, and we simply have an extra transaction synchronization registered that won't do anything
DATA_INDEX.putIfAbsent(transaction, ctx);
}
// } catch (RollbackException e) {
// throw (IllegalStateException) new IllegalStateException("Transaction is already rolled back").initCause(e);
} catch (SystemException e) {
throw new RuntimeException("Unable to register ejb transaction synchronization callback", e);
}
}
return ctx;
}
public static TransactionCachingInterceptor.ManagedConnectionInfos get(Transaction transaction, ConnectionReleaser key) {
ConnectorTransactionContext ctx = get(transaction);
TransactionCachingInterceptor.ManagedConnectionInfos infos = ctx.getManagedConnectionInfo(key);
if (infos == null) {
infos = new TransactionCachingInterceptor.ManagedConnectionInfos();
ctx.setManagedConnectionInfo(key, infos);
}
return infos;
}
private static void remove(Transaction transaction) {
DATA_INDEX.remove(transaction);
}
private Map<ConnectionReleaser, TransactionCachingInterceptor.ManagedConnectionInfos> managedConnections;
private synchronized TransactionCachingInterceptor.ManagedConnectionInfos getManagedConnectionInfo(ConnectionReleaser key) {
if (managedConnections == null) {
return null;
}
return managedConnections.get(key);
}
private synchronized void setManagedConnectionInfo(ConnectionReleaser key, TransactionCachingInterceptor.ManagedConnectionInfos info) {
if (managedConnections == null) {
managedConnections = new HashMap<ConnectionReleaser, TransactionCachingInterceptor.ManagedConnectionInfos>();
}
managedConnections.put(key, info);
}
private static class ConnectorSynchronization implements Synchronization {
private final ConnectorTransactionContext ctx;
private final Transaction transaction;
public ConnectorSynchronization(ConnectorTransactionContext ctx, Transaction transaction) {
this.ctx = ctx;
this.transaction = transaction;
}
public void beforeCompletion() {
}
public void afterCompletion(int status) {
try {
synchronized (ctx) {
if (ctx.managedConnections != null) {
for (Map.Entry<ConnectionReleaser, TransactionCachingInterceptor.ManagedConnectionInfos> entry : ctx.managedConnections.entrySet()) {
ConnectionReleaser key = entry.getKey();
key.afterCompletion(entry.getValue());
}
//If BeanTransactionContext never reuses the same instance for sequential BMT, this
//clearing is unnecessary.
ctx.managedConnections.clear();
}
}
} finally {
remove(transaction);
}
}
}
}
| 6,393 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/ActivationSpecNamedXAResourceFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.connector;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ActivationSpec;
import jakarta.resource.spi.ResourceAdapter;
import jakarta.transaction.SystemException;
import javax.transaction.xa.XAResource;
import org.apache.geronimo.transaction.manager.NamedXAResource;
import org.apache.geronimo.transaction.manager.NamedXAResourceFactory;
import org.apache.geronimo.transaction.manager.WrapperNamedXAResource;
/**
* @version $Rev$ $Date$
*/
public class ActivationSpecNamedXAResourceFactory implements NamedXAResourceFactory {
private final String name;
private final ActivationSpec activationSpec;
private final ResourceAdapter resourceAdapter;
public ActivationSpecNamedXAResourceFactory(String name, ActivationSpec activationSpec, ResourceAdapter resourceAdapter) {
this.name = name;
this.activationSpec = activationSpec;
this.resourceAdapter = resourceAdapter;
}
public String getName() {
return name;
}
public NamedXAResource getNamedXAResource() throws SystemException {
try {
XAResource[] xaResources = resourceAdapter.getXAResources(new ActivationSpec[]{activationSpec});
if (xaResources == null || xaResources.length == 0 || xaResources[0] == null) {
return null;
}
return new WrapperNamedXAResource(xaResources[0], name);
} catch (ResourceException e) {
throw (SystemException) new SystemException("Could not get XAResource for recovery for mdb: " + name).initCause(e);
}
}
public void returnNamedXAResource(NamedXAResource namedXAResource) {
// nothing to do AFAICT
}
}
| 6,394 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/ActivationSpecWrapper.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector;
import java.util.Set;
import jakarta.resource.ResourceException;
import jakarta.resource.spi.ActivationSpec;
import jakarta.resource.spi.ResourceAdapter;
import jakarta.resource.spi.InvalidPropertyException;
import jakarta.resource.spi.endpoint.MessageEndpointFactory;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
/**
* Wrapper for ActivationSpec instances.
* The framework assumes all RequiredConfigProperties are of type String, although it
* is unclear if this is required by the spec.
*
* @version $Rev$ $Date$
*/
public class ActivationSpecWrapper {
protected final ActivationSpec activationSpec;
private final ResourceAdapterWrapper resourceAdapterWrapper;
private final String containerId;
private final ValidatorFactory validatorFactory;
// indicates we've validated the spec on the first usage.
private boolean validated = false;
/**
* Default constructor required when a class is used as a GBean Endpoint.
*/
public ActivationSpecWrapper() {
activationSpec = null;
containerId = null;
resourceAdapterWrapper = null;
validatorFactory = null;
validated = false;
}
/**
* Normal managed constructor.
*
* @param activationSpecClass Class of admin object to be wrapped.
* @throws IllegalAccessException
* @throws InstantiationException
*/
public ActivationSpecWrapper(final String activationSpecClass,
final String containerId,
final ResourceAdapterWrapper resourceAdapterWrapper,
final ClassLoader cl,
final ValidatorFactory validatorFactory) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
Class clazz = cl.loadClass(activationSpecClass);
this.activationSpec = (ActivationSpec) clazz.newInstance();
this.containerId = containerId;
this.resourceAdapterWrapper = resourceAdapterWrapper;
this.validatorFactory = validatorFactory;
this.validated = false;
}
/**
*/
public ActivationSpecWrapper(ActivationSpec activationSpec, ResourceAdapterWrapper resourceAdapterWrapper, ValidatorFactory validatorFactory) {
this.activationSpec = activationSpec;
this.resourceAdapterWrapper = resourceAdapterWrapper;
this.containerId = null;
this.validatorFactory = validatorFactory;
this.validated = false;
}
/**
* Returns class of wrapped ActivationSpec.
*
* @return class of wrapped ActivationSpec
*/
// public String getActivationSpecClass() {
// return activationSpecClass;
// }
public String getContainerId() {
return containerId;
}
public ResourceAdapterWrapper getResourceAdapterWrapper() {
return resourceAdapterWrapper;
}
//GBeanLifecycle implementation
public void activate(final MessageEndpointFactory messageEndpointFactory) throws ResourceException {
checkConstraints(activationSpec);
ResourceAdapter resourceAdapter = activationSpec.getResourceAdapter();
if (resourceAdapter == null) {
resourceAdapterWrapper.registerResourceAdapterAssociation(activationSpec);
}
resourceAdapterWrapper.endpointActivation(messageEndpointFactory, activationSpec);
resourceAdapterWrapper.doRecovery(activationSpec, containerId);
}
public void deactivate(final MessageEndpointFactory messageEndpointFactory) {
ResourceAdapter resourceAdapter = activationSpec.getResourceAdapter();
if (resourceAdapter != null) {
resourceAdapterWrapper.deregisterRecovery(containerId);
resourceAdapterWrapper.endpointDeactivation(messageEndpointFactory, activationSpec);
} else {
//this should never happen, activation spec should have been registered with r.a.
throw new IllegalStateException("ActivationSpec was never registered with ResourceAdapter");
}
}
/**
* Validate an ActivationSpec instance on the first usage.
*
* @param spec The spec instance to validate.
*/
private void checkConstraints(ActivationSpec spec) throws InvalidPropertyException {
if (!validated) {
// There are two potential validations, self validation via the
// validate() method and container-driven validation using bean validation.
try {
spec.validate();
} catch (UnsupportedOperationException uoe) {
// ignore if not implemented.
}
// if we have a validator factory at this point, then validate
// the resource adaptor instance
if (validatorFactory != null) {
Validator validator = validatorFactory.getValidator();
Set generalSet = validator.validate(spec);
if (!generalSet.isEmpty()) {
throw new ConstraintViolationException("Constraint violation for ActitvationSpec", generalSet);
}
}
validated = true;
}
}
}
| 6,395 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/work/WorkContextHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.connector.work;
import jakarta.resource.spi.work.WorkContext;
import jakarta.resource.spi.work.WorkCompletedException;
/**
* @version $Rev$ $Date$
*/
public interface WorkContextHandler<E extends WorkContext> {
void before(E workContext) throws WorkCompletedException;
void after(E workContext) throws WorkCompletedException;
boolean supports(Class<? extends WorkContext> clazz);
boolean required();
}
| 6,396 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/work/TransactionContextHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.connector.work;
import jakarta.resource.spi.work.TransactionContext;
import jakarta.resource.spi.work.WorkCompletedException;
import jakarta.resource.spi.work.WorkContext;
import javax.transaction.xa.XAException;
import jakarta.transaction.InvalidTransactionException;
import jakarta.transaction.SystemException;
import org.apache.geronimo.transaction.manager.XAWork;
import org.apache.geronimo.transaction.manager.ImportedTransactionActiveException;
/**
* @version $Rev$ $Date$
*/
public class TransactionContextHandler implements WorkContextHandler<TransactionContext>{
private final XAWork xaWork;
public TransactionContextHandler(XAWork xaWork) {
this.xaWork = xaWork;
}
public void before(TransactionContext workContext) throws WorkCompletedException {
if (workContext.getXid() != null) {
try {
long transactionTimeout = workContext.getTransactionTimeout();
//translate -1 value to 0 to indicate default transaction timeout.
xaWork.begin(workContext.getXid(), transactionTimeout < 0 ? 0 : transactionTimeout);
} catch (XAException e) {
throw (WorkCompletedException)new WorkCompletedException("Transaction import failed for xid " + workContext.getXid(), WorkCompletedException.TX_RECREATE_FAILED).initCause(e);
} catch (InvalidTransactionException e) {
throw (WorkCompletedException)new WorkCompletedException("Transaction import failed for xid " + workContext.getXid(), WorkCompletedException.TX_RECREATE_FAILED).initCause(e);
} catch (SystemException e) {
throw (WorkCompletedException)new WorkCompletedException("Transaction import failed for xid " + workContext.getXid(), WorkCompletedException.TX_RECREATE_FAILED).initCause(e);
} catch (ImportedTransactionActiveException e) {
throw (WorkCompletedException)new WorkCompletedException("Transaction already active for xid " + workContext.getXid(), WorkCompletedException.TX_CONCURRENT_WORK_DISALLOWED).initCause(e);
}
}
}
public void after(TransactionContext workContext) throws WorkCompletedException {
if (workContext.getXid() != null) {
try {
xaWork.end(workContext.getXid());
} catch (XAException e) {
throw (WorkCompletedException)new WorkCompletedException("Transaction end failed for xid " + workContext.getXid(), WorkCompletedException.TX_RECREATE_FAILED).initCause(e);
} catch (SystemException e) {
throw (WorkCompletedException)new WorkCompletedException("Transaction end failed for xid " + workContext.getXid(), WorkCompletedException.TX_RECREATE_FAILED).initCause(e);
}
}
}
public boolean supports(Class<? extends WorkContext> clazz) {
return TransactionContext.class.isAssignableFrom(clazz);
}
public boolean required() {
return false;
}
}
| 6,397 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/work/HintsContextHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.geronimo.connector.work;
import jakarta.resource.spi.work.HintsContext;
import jakarta.resource.spi.work.WorkCompletedException;
import jakarta.resource.spi.work.WorkContext;
/**
* @version $Rev$ $Date$
*/
public class HintsContextHandler implements WorkContextHandler<HintsContext> {
public void before(HintsContext workContext) throws WorkCompletedException {
}
public void after(HintsContext workContext) throws WorkCompletedException {
}
public boolean supports(Class<? extends WorkContext> clazz) {
return HintsContext.class.isAssignableFrom(clazz);
}
public boolean required() {
return false;
}
}
| 6,398 |
0 | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector | Create_ds/geronimo-txmanager/geronimo-connector/src/main/java/org/apache/geronimo/connector/work/GeronimoWorkManager.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.connector.work;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.Executor;
import jakarta.resource.spi.work.ExecutionContext;
import jakarta.resource.spi.work.Work;
import jakarta.resource.spi.work.WorkCompletedException;
import jakarta.resource.spi.work.WorkContext;
import jakarta.resource.spi.work.WorkException;
import jakarta.resource.spi.work.WorkListener;
import jakarta.resource.spi.work.WorkManager;
import org.apache.geronimo.connector.work.pool.ScheduleWorkExecutor;
import org.apache.geronimo.connector.work.pool.StartWorkExecutor;
import org.apache.geronimo.connector.work.pool.SyncWorkExecutor;
import org.apache.geronimo.connector.work.pool.WorkExecutor;
/**
* WorkManager implementation which uses under the cover three WorkExecutorPool
* - one for each synchronization policy - in order to dispatch the submitted
* Work instances.
* <p/>
* A WorkManager is a component of the JCA specifications, which allows a
* Resource Adapter to submit tasks to an Application Server for execution.
*
* @version $Rev$ $Date$
*/
public class GeronimoWorkManager implements WorkManager {
// private final static int DEFAULT_POOL_SIZE = 10;
/**
* Pool of threads used by this WorkManager in order to process
* the Work instances submitted via the doWork methods.
*/
private Executor syncWorkExecutorPool;
/**
* Pool of threads used by this WorkManager in order to process
* the Work instances submitted via the startWork methods.
*/
private Executor startWorkExecutorPool;
/**
* Pool of threads used by this WorkManager in order to process
* the Work instances submitted via the scheduleWork methods.
*/
private Executor scheduledWorkExecutorPool;
private final Collection<WorkContextHandler> workContextHandlers;
private final WorkExecutor scheduleWorkExecutor = new ScheduleWorkExecutor();
private final WorkExecutor startWorkExecutor = new StartWorkExecutor();
private final WorkExecutor syncWorkExecutor = new SyncWorkExecutor();
/**
* Create a WorkManager.
*/
public GeronimoWorkManager() {
this(null, null, null, null);
}
public GeronimoWorkManager(Executor sync, Executor start, Executor sched, Collection<WorkContextHandler> workContextHandlers) {
syncWorkExecutorPool = sync;
startWorkExecutorPool = start;
scheduledWorkExecutorPool = sched;
this.workContextHandlers = workContextHandlers == null ? Collections.<WorkContextHandler>emptyList() : workContextHandlers;
}
public void doStart() throws Exception {
}
public void doStop() throws Exception {
}
public void doFail() {
try {
doStop();
} catch (Exception e) {
//TODO what to do?
}
}
public Executor getSyncWorkExecutorPool() {
return syncWorkExecutorPool;
}
public Executor getStartWorkExecutorPool() {
return startWorkExecutorPool;
}
public Executor getScheduledWorkExecutorPool() {
return scheduledWorkExecutorPool;
}
/* (non-Javadoc)
* @see jakarta.resource.spi.work.WorkManager#doWork(jakarta.resource.spi.work.Work)
*/
public void doWork(Work work) throws WorkException {
executeWork(new WorkerContext(work, workContextHandlers), syncWorkExecutor, syncWorkExecutorPool);
}
/* (non-Javadoc)
* @see jakarta.resource.spi.work.WorkManager#doWork(jakarta.resource.spi.work.Work, long, jakarta.resource.spi.work.ExecutionContext, jakarta.resource.spi.work.WorkListener)
*/
public void doWork(
Work work,
long startTimeout,
ExecutionContext execContext,
WorkListener workListener)
throws WorkException {
WorkerContext workWrapper =
new WorkerContext(work, startTimeout, execContext, workListener, workContextHandlers);
workWrapper.setThreadPriority(Thread.currentThread().getPriority());
executeWork(workWrapper, syncWorkExecutor, syncWorkExecutorPool);
}
/* (non-Javadoc)
* @see jakarta.resource.spi.work.WorkManager#startWork(jakarta.resource.spi.work.Work)
*/
public long startWork(Work work) throws WorkException {
WorkerContext workWrapper = new WorkerContext(work, workContextHandlers);
workWrapper.setThreadPriority(Thread.currentThread().getPriority());
executeWork(workWrapper, startWorkExecutor, startWorkExecutorPool);
return System.currentTimeMillis() - workWrapper.getAcceptedTime();
}
/* (non-Javadoc)
* @see jakarta.resource.spi.work.WorkManager#startWork(jakarta.resource.spi.work.Work, long, jakarta.resource.spi.work.ExecutionContext, jakarta.resource.spi.work.WorkListener)
*/
public long startWork(
Work work,
long startTimeout,
ExecutionContext execContext,
WorkListener workListener)
throws WorkException {
WorkerContext workWrapper =
new WorkerContext(work, startTimeout, execContext, workListener, workContextHandlers);
workWrapper.setThreadPriority(Thread.currentThread().getPriority());
executeWork(workWrapper, startWorkExecutor, startWorkExecutorPool);
return System.currentTimeMillis() - workWrapper.getAcceptedTime();
}
/* (non-Javadoc)
* @see jakarta.resource.spi.work.WorkManager#scheduleWork(jakarta.resource.spi.work.Work)
*/
public void scheduleWork(Work work) throws WorkException {
WorkerContext workWrapper = new WorkerContext(work, workContextHandlers);
workWrapper.setThreadPriority(Thread.currentThread().getPriority());
executeWork(workWrapper, scheduleWorkExecutor, scheduledWorkExecutorPool);
}
/* (non-Javadoc)
* @see jakarta.resource.spi.work.WorkManager#scheduleWork(jakarta.resource.spi.work.Work, long, jakarta.resource.spi.work.ExecutionContext, jakarta.resource.spi.work.WorkListener)
*/
public void scheduleWork(
Work work,
long startTimeout,
ExecutionContext execContext,
WorkListener workListener)
throws WorkException {
WorkerContext workWrapper =
new WorkerContext(work, startTimeout, execContext, workListener, workContextHandlers);
workWrapper.setThreadPriority(Thread.currentThread().getPriority());
executeWork(workWrapper, scheduleWorkExecutor, scheduledWorkExecutorPool);
}
/**
* Execute the specified Work.
*
* @param work Work to be executed.
* @throws WorkException Indicates that the Work execution has been
* unsuccessful.
*/
private void executeWork(WorkerContext work, WorkExecutor workExecutor, Executor pooledExecutor) throws WorkException {
work.workAccepted(this);
try {
workExecutor.doExecute(work, pooledExecutor);
WorkException exception = work.getWorkException();
if (null != exception) {
throw exception;
}
} catch (InterruptedException e) {
WorkCompletedException wcj = new WorkCompletedException(
"The execution has been interrupted.", e);
wcj.setErrorCode(WorkException.INTERNAL);
throw wcj;
}
}
public boolean isContextSupported(Class<? extends WorkContext> aClass) {
for (WorkContextHandler workContextHandler: workContextHandlers) {
if (workContextHandler.supports(aClass)) {
return true;
}
}
return false;
}
}
| 6,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.