_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q18100 | QuartzClient.close | train | public void close() {
refuseNewRequests.set(true);
channel.close().awaitUninterruptibly();
channel.eventLoop().shutdownGracefully().awaitUninterruptibly();
} | java | {
"resource": ""
} |
q18101 | FraggleManager.peek | train | protected FraggleFragment peek(String tag) {
if (fm != null) {
return (FraggleFragment) fm.findFragmentByTag(tag);
}
return new EmptyFragment();
} | java | {
"resource": ""
} |
q18102 | FraggleManager.processAnimations | train | protected void processAnimations(FragmentAnimation animation, FragmentTransaction ft) {
if (animation != null) {
if (animation.isCompletedAnimation()) {
ft.setCustomAnimations(animation.getEnterAnim(), animation.getExitAnim(),
animation.getPushInAnim(), animation.getPopOutAnim());
} else {
ft.setCustomAnimations(animation.getEnterAnim(), animation.getExitAnim());
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
for (LollipopAnim sharedElement : animation.getSharedViews()) {
ft.addSharedElement(sharedElement.view, sharedElement.name);
}
}
} | java | {
"resource": ""
} |
q18103 | FraggleManager.configureAdditionMode | train | protected void configureAdditionMode(Fragment frag, int flags, FragmentTransaction ft, int containerId) {
if ((flags & DO_NOT_REPLACE_FRAGMENT) != DO_NOT_REPLACE_FRAGMENT) {
ft.replace(containerId, frag, ((FraggleFragment) frag).getFragmentTag());
} else {
ft.add(containerId, frag, ((FraggleFragment) frag).getFragmentTag());
peek().onFragmentNotVisible();
}
} | java | {
"resource": ""
} |
q18104 | FraggleManager.performTransaction | train | protected void performTransaction(Fragment frag, int flags, FragmentTransaction ft, int containerId) {
configureAdditionMode(frag, flags, ft, containerId);
ft.commitAllowingStateLoss();
} | java | {
"resource": ""
} |
q18105 | FraggleManager.peek | train | protected FraggleFragment peek() {
if (fm.getBackStackEntryCount() > 0) {
return ((FraggleFragment) fm.findFragmentByTag(
fm.getBackStackEntryAt(fm.getBackStackEntryCount() - 1).getName()));
} else {
return new EmptyFragment();
}
} | java | {
"resource": ""
} |
q18106 | FraggleManager.clear | train | public void clear() {
if (fm != null) {
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
fm = null;
} | java | {
"resource": ""
} |
q18107 | FraggleManager.reattach | train | public void reattach(String tag) {
final Fragment currentFragment = (Fragment) peek(tag);
FragmentTransaction fragTransaction = fm.beginTransaction();
fragTransaction.detach(currentFragment);
fragTransaction.attach(currentFragment);
fragTransaction.commit();
} | java | {
"resource": ""
} |
q18108 | Parameters.keys | train | public Set<String> keys(String pattern) {
Set<String> result = new TreeSet<String>();
for (String key : keys()) {
if (key.matches(pattern)) result.add(key);
}
return result;
} | java | {
"resource": ""
} |
q18109 | Parameters.get | train | public String get(String key, String defaultValue) {
String value = parameters.get(key);
return StringUtils.isBlank(value) ? defaultValue : value;
} | java | {
"resource": ""
} |
q18110 | system_settings.get | train | public static system_settings get(nitro_service client) throws Exception
{
system_settings resource = new system_settings();
resource.validate("get");
return ((system_settings[]) resource.get_resources(client))[0];
} | java | {
"resource": ""
} |
q18111 | AbstractSorter.getOrderBy | train | @Override
@SuppressWarnings("unchecked")
public <E> Comparator<E> getOrderBy() {
return ObjectUtils.defaultIfNull(ComparatorHolder.get(), ObjectUtils.defaultIfNull(
orderBy, ComparableComparator.INSTANCE));
} | java | {
"resource": ""
} |
q18112 | AbstractSorter.sort | train | @Override
@SuppressWarnings("unchecked")
public <E> E[] sort(final E... elements) {
sort(new SortableArrayList(elements));
return elements;
} | java | {
"resource": ""
} |
q18113 | AbstractSorter.sort | train | @Override
public <E> Sortable<E> sort(final Sortable<E> sortable) {
try {
sort(configureComparator(sortable).asList());
return sortable;
}
finally {
ComparatorHolder.unset();
}
} | java | {
"resource": ""
} |
q18114 | Optionals.first | train | @SafeVarargs
public static <T> @NonNull Optional<T> first(final @NonNull Optional<T>... optionals) {
return Arrays.stream(optionals)
.filter(Optional::isPresent)
.findFirst()
.orElse(Optional.empty());
} | java | {
"resource": ""
} |
q18115 | SearcherFactory.createSearcher | train | @SuppressWarnings("unchecked")
public static <T extends Searcher> T createSearcher(final SearchType type) {
switch (ObjectUtils.defaultIfNull(type, SearchType.UNKNOWN_SEARCH)) {
case BINARY_SEARCH:
return (T) new BinarySearch();
case LINEAR_SEARCH:
return (T) new LinearSearch();
default:
throw new IllegalArgumentException(String.format("The SearchType (%1$s) is not supported by the %2$s!", type,
SearcherFactory.class.getSimpleName()));
}
} | java | {
"resource": ""
} |
q18116 | SearcherFactory.createSearcherElseDefault | train | public static <T extends Searcher> T createSearcherElseDefault(final SearchType type, final T defaultSearcher) {
try {
return createSearcher(type);
}
catch (IllegalArgumentException ignore) {
return defaultSearcher;
}
} | java | {
"resource": ""
} |
q18117 | BalancingThreadPoolExecutor.balance | train | private void balance() {
// only try to balance when we're not terminating
if(!isTerminated()) {
Set<Map.Entry<Thread, Tracking>> threads = liveThreads.entrySet();
long liveAvgTimeTotal = 0;
long liveAvgCpuTotal = 0;
long liveCount = 0;
for (Map.Entry<Thread, Tracking> e : threads) {
if (!e.getKey().isAlive()) {
// thread is dead or otherwise hosed
threads.remove(e);
} else {
liveAvgTimeTotal += e.getValue().avgTotalTime;
liveAvgCpuTotal += e.getValue().avgCpuTime;
liveCount++;
}
}
long waitTime = 1;
long cpuTime = 1;
if(liveCount > 0) {
waitTime = liveAvgTimeTotal / liveCount;
cpuTime = liveAvgCpuTotal / liveCount;
}
int size = 1;
if(cpuTime > 0) {
size = (int) ceil((CPUS * targetUtilization * (1 + (waitTime / cpuTime))));
}
size = Math.min(size, threadPoolExecutor.getMaximumPoolSize());
// TODO remove debugging
//System.out.println(waitTime / 1000000 + " ms");
//System.out.println(cpuTime / 1000000 + " ms");
//System.out.println(size);
threadPoolExecutor.setCorePoolSize(size);
}
} | java | {
"resource": ""
} |
q18118 | RadialMenu.setMenu | train | public void setMenu(Menu menu) {
this.menu = menu;
RadialMenuItem.setupMenuButton(this, radialMenuParams, (menu != null) ? menu.getGraphic() : null, (menu != null) ? menu.getText() : null, true);
} | java | {
"resource": ""
} |
q18119 | HeapSort.sort | train | @Override
public <E> List<E> sort(final List<E> elements) {
int size = elements.size();
// create the heap
for (int parentIndex = ((size - 2) / 2); parentIndex >= 0; parentIndex--) {
siftDown(elements, parentIndex, size - 1);
}
// swap the first and last elements in the heap of array since the first is the largest value in the heap,
// and then heapify the heap again
for (int count = (size - 1); count > 0; count--) {
swap(elements, 0, count);
siftDown(elements, 0, count - 1);
}
return elements;
} | java | {
"resource": ""
} |
q18120 | HeapSort.siftDown | train | protected <E> void siftDown(final List<E> elements, final int startIndex, final int endIndex) {
int rootIndex = startIndex;
while ((rootIndex * 2 + 1) <= endIndex) {
int swapIndex = rootIndex;
int leftChildIndex = (rootIndex * 2 + 1);
int rightChildIndex = (leftChildIndex + 1);
if (getOrderBy().compare(elements.get(swapIndex), elements.get(leftChildIndex)) < 0) {
swapIndex = leftChildIndex;
}
if (rightChildIndex <= endIndex && getOrderBy().compare(elements.get(swapIndex), elements.get(rightChildIndex)) < 0) {
swapIndex = rightChildIndex;
}
if (swapIndex != rootIndex) {
swap(elements, rootIndex, swapIndex);
rootIndex = swapIndex;
}
else {
return;
}
}
} | java | {
"resource": ""
} |
q18121 | ChangeSupport.fireChangeEvent | train | public void fireChangeEvent() {
ChangeEvent event = createChangeEvent(getSource());
for (ChangeListener listener : this) {
listener.stateChanged(event);
}
} | java | {
"resource": ""
} |
q18122 | QuickSort.sort | train | @Override
public <E> List<E> sort(final List<E> elements) {
int elementsSize = elements.size();
if (elementsSize <= getSizeThreshold()) {
return getSorter().sort(elements);
}
else {
int beginIndex = 1;
int endIndex = (elementsSize - 1);
E pivotElement = elements.get(0);
while (beginIndex < endIndex) {
while (beginIndex < endIndex && getOrderBy().compare(elements.get(beginIndex), pivotElement) <= 0) {
beginIndex++;
}
while (endIndex >= beginIndex && getOrderBy().compare(elements.get(endIndex), pivotElement) >= 0) {
endIndex--;
}
if (beginIndex < endIndex) {
swap(elements, beginIndex, endIndex);
}
}
swap(elements, 0, endIndex);
sort(elements.subList(0, endIndex));
sort(elements.subList(endIndex + 1, elementsSize));
return elements;
}
} | java | {
"resource": ""
} |
q18123 | HeapQueueingStrategy.onBeforeAdd | train | public void onBeforeAdd(E value) {
long freeHeapSpace = RUNTIME.freeMemory() + (RUNTIME.maxMemory() - RUNTIME.totalMemory());
// start flow control if we cross the threshold
if (freeHeapSpace < minimumHeapSpaceBeforeFlowControl) {
// x indicates how close we are to overflowing the heap
long x = minimumHeapSpaceBeforeFlowControl - freeHeapSpace;
long delay = Math.round(x * (x * c)); // delay = x^2 * c
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
} | java | {
"resource": ""
} |
q18124 | HeapQueueingStrategy.onAfterRemove | train | public void onAfterRemove(E value) {
if (value != null) {
dequeued++;
if (dequeued % dequeueHint == 0) {
RUNTIME.gc();
}
}
} | java | {
"resource": ""
} |
q18125 | ChangeTracker.propertyChange | train | public void propertyChange(final PropertyChangeEvent event) {
if (objectStateMap.containsKey(event.getPropertyName())) {
if (objectStateMap.get(event.getPropertyName()) == ObjectUtils.hashCode(event.getNewValue())) {
// NOTE the state of the property identified by the event has been reverted to it's original, persisted value.
objectStateMap.remove(event.getPropertyName());
}
}
else {
if (!ObjectUtils.equalsIgnoreNull(event.getOldValue(), event.getNewValue())) {
objectStateMap.put(event.getPropertyName(), ObjectUtils.hashCode(event.getOldValue()));
}
}
} | java | {
"resource": ""
} |
q18126 | JsonResponseFuture.setResponse | train | public void setResponse(JsonRpcResponse response) {
if (response.isError()) {
setException(response.error());
return;
}
try {
set((V) Messages.fromJson(method.outputBuilder(), response.result()));
} catch (Exception e) {
setException(e);
}
} | java | {
"resource": ""
} |
q18127 | AbstractObjectFactory.getArgumentTypes | train | @SuppressWarnings("unchecked")
protected Class[] getArgumentTypes(final Object... arguments) {
Class[] argumentTypes = new Class[arguments.length];
int index = 0;
for (Object argument : arguments) {
argumentTypes[index++] = ObjectUtils.defaultIfNull(ClassUtils.getClass(argument), Object.class);
}
return argumentTypes;
} | java | {
"resource": ""
} |
q18128 | AbstractObjectFactory.resolveConstructor | train | protected Constructor resolveConstructor(final Class<?> objectType, final Class... parameterTypes) {
try {
return objectType.getConstructor(parameterTypes);
}
catch (NoSuchMethodException e) {
if (!ArrayUtils.isEmpty(parameterTypes)) {
Constructor constructor = resolveCompatibleConstructor(objectType, parameterTypes);
// if the "compatible" constructor is null, resolve to finding the public, default no-arg constructor
return (constructor != null ? constructor : resolveConstructor(objectType));
}
throw new NoSuchConstructorException(String.format(
"Failed to find a constructor with signature (%1$s) in Class (%2$s)", from(parameterTypes).toString(),
objectType.getName()), e);
}
} | java | {
"resource": ""
} |
q18129 | AbstractObjectFactory.resolveCompatibleConstructor | train | @SuppressWarnings("unchecked")
protected Constructor resolveCompatibleConstructor(final Class<?> objectType, final Class<?>[] parameterTypes) {
for (Constructor constructor : objectType.getConstructors()) {
Class[] constructorParameterTypes = constructor.getParameterTypes();
if (parameterTypes.length == constructorParameterTypes.length) {
boolean match = true;
for (int index = 0; index < constructorParameterTypes.length; index++) {
match &= constructorParameterTypes[index].isAssignableFrom(parameterTypes[index]);
}
if (match) {
return constructor;
}
}
}
return null;
} | java | {
"resource": ""
} |
q18130 | AbstractObjectFactory.create | train | @Override
@SuppressWarnings("unchecked")
public <T> T create(final String objectTypeName, final Object... args) {
return (T) create(ClassUtils.loadClass(objectTypeName), getArgumentTypes(args), args);
} | java | {
"resource": ""
} |
q18131 | AbstractObjectFactory.create | train | @Override
public <T> T create(final Class<T> objectType, final Object... args) {
return create(objectType, getArgumentTypes(args), args);
} | java | {
"resource": ""
} |
q18132 | UrlRewriterImpl.copyPathFragment | train | private static int copyPathFragment(char[] input, int beginIndex, StringBuilder output)
{
int inputCharIndex = beginIndex;
while (inputCharIndex < input.length)
{
final char inputChar = input[inputCharIndex];
if (inputChar == '/')
{
break;
}
output.append(inputChar);
inputCharIndex += 1;
}
return inputCharIndex;
} | java | {
"resource": ""
} |
q18133 | JsonRpcRequestInvoker.invoke | train | public ListenableFuture<JsonRpcResponse> invoke(JsonRpcRequest request) {
Service service = services.lookupByName(request.service());
if (service == null) {
JsonRpcError error = new JsonRpcError(HttpResponseStatus.BAD_REQUEST,
"Unknown service: " + request.service());
JsonRpcResponse response = JsonRpcResponse.error(error);
return Futures.immediateFuture(response);
}
ServerMethod<? extends Message, ? extends Message> method = service.lookup(request.method());
serverLogger.logMethodCall(service, method);
if (method == null) {
JsonRpcError error = new JsonRpcError(HttpResponseStatus.BAD_REQUEST,
"Unknown method: " + request.service());
JsonRpcResponse response = JsonRpcResponse.error(error);
return Futures.immediateFuture(response);
}
return invoke(method, request.parameter(), request.id());
} | java | {
"resource": ""
} |
q18134 | JsonRpcRequestInvoker.invoke | train | private <I extends Message, O extends Message> ListenableFuture<JsonRpcResponse> invoke(
ServerMethod<I, O> method, JsonObject parameter, JsonElement id) {
I request;
try {
request = (I) Messages.fromJson(method.inputBuilder(), parameter);
} catch (Exception e) {
serverLogger.logServerFailure(method, e);
SettableFuture<JsonRpcResponse> future = SettableFuture.create();
future.setException(e);
return future;
}
ListenableFuture<O> response = method.invoke(request);
return Futures.transform(response, new JsonConverter(id), TRANSFORM_EXECUTOR);
} | java | {
"resource": ""
} |
q18135 | JarFile.addContent | train | protected synchronized void addContent(Artifact record, String filename) {
if (record != null) {
if (filename.endsWith(".jar")) {
// this is an embedded archive
embedded.add(record);
} else {
contents.add(record);
}
}
} | java | {
"resource": ""
} |
q18136 | JarFile.submitJob | train | protected void submitJob(ExecutorService executor, Content file) {
// lifted from http://stackoverflow.com/a/5853198/1874604
class OneShotTask implements Runnable {
Content file;
OneShotTask(Content file) {
this.file = file;
}
public void run() {
processContent(file);
}
}
// we do not care about Future
executor.submit(new OneShotTask(file));
} | java | {
"resource": ""
} |
q18137 | ValueHolder.withComparableValue | train | public static <T extends Comparable<T>> ComparableValueHolder<T> withComparableValue(final T value) {
return new ComparableValueHolder<>(value);
} | java | {
"resource": ""
} |
q18138 | ValueHolder.withImmutableValue | train | public static <T extends Cloneable> ValueHolder<T> withImmutableValue(final T value) {
return new ValueHolder<T>(ObjectUtils.clone(value)) {
@Override public T getValue() {
return ObjectUtils.clone(super.getValue());
}
@Override public void setValue(final T value) {
super.setValue(ObjectUtils.clone(value));
}
};
} | java | {
"resource": ""
} |
q18139 | ValueHolder.withNonNullValue | train | public static <T> ValueHolder<T> withNonNullValue(final T value) {
Assert.notNull(value, "The value must not be null!");
return new ValueHolder<T>(value) {
@Override
public void setValue(final T value) {
Assert.notNull(value, "The value must not be null!");
super.setValue(value);
}
};
} | java | {
"resource": ""
} |
q18140 | xen.reboot | train | public static xen reboot(nitro_service client, xen resource) throws Exception
{
return ((xen[]) resource.perform_operation(client, "reboot"))[0];
} | java | {
"resource": ""
} |
q18141 | xen.stop | train | public static xen stop(nitro_service client, xen resource) throws Exception
{
return ((xen[]) resource.perform_operation(client, "stop"))[0];
} | java | {
"resource": ""
} |
q18142 | xen.get_filtered | train | public static xen[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception
{
xen obj = new xen();
options option = new options();
option.set_filter(filter);
xen[] response = (xen[]) obj.getfiltered(service, option);
return response;
} | java | {
"resource": ""
} |
q18143 | sdx_license.get | train | public static sdx_license get(nitro_service client) throws Exception
{
sdx_license resource = new sdx_license();
resource.validate("get");
return ((sdx_license[]) resource.get_resources(client))[0];
} | java | {
"resource": ""
} |
q18144 | IsModifiedVisitor.visit | train | @Override
public void visit(final Visitable visitable) {
if (visitable instanceof Auditable) {
modified |= ((Auditable) visitable).isModified();
}
} | java | {
"resource": ""
} |
q18145 | FilterBuilder.addWithAnd | train | public FilterBuilder<T> addWithAnd(final Filter<T> filter) {
filterInstance = ComposableFilter.and(filterInstance, filter);
return this;
} | java | {
"resource": ""
} |
q18146 | FilterBuilder.addWithOr | train | public FilterBuilder<T> addWithOr(final Filter<T> filter) {
filterInstance = ComposableFilter.or(filterInstance, filter);
return this;
} | java | {
"resource": ""
} |
q18147 | ArrayUtils.filter | train | @SuppressWarnings("unchecked")
public static <T> T[] filter(T[] array, Filter<T> filter) {
Assert.notNull(array, "Array is required");
Assert.notNull(filter, "Filter is required");
List<T> arrayList = stream(array).filter(filter::accept).collect(Collectors.toList());
return arrayList.toArray((T[]) Array.newInstance(array.getClass().getComponentType(), arrayList.size()));
} | java | {
"resource": ""
} |
q18148 | ArrayUtils.filterAndTransform | train | @SuppressWarnings("unchecked")
public static <T> T[] filterAndTransform(T[] array, FilteringTransformer<T> filteringTransformer) {
return transform(filter(array, filteringTransformer), filteringTransformer);
} | java | {
"resource": ""
} |
q18149 | ArrayUtils.insert | train | @SuppressWarnings("unchecked")
public static <T> T[] insert(T element, T[] array, int index) {
Assert.notNull(array, "Array is required");
assertThat(index).throwing(new ArrayIndexOutOfBoundsException(
String.format("[%1$d] is not a valid index [0, %2$d] in the array", index, array.length)))
.isGreaterThanEqualToAndLessThanEqualTo(0, array.length);
Class<?> componentType = array.getClass().getComponentType();
componentType = defaultIfNull(componentType, ObjectUtils.getClass(element));
componentType = defaultIfNull(componentType, Object.class);
T[] newArray = (T[]) Array.newInstance(componentType, array.length + 1);
if (index > 0) {
System.arraycopy(array, 0, newArray, 0, index);
}
newArray[index] = element;
if (index < array.length) {
System.arraycopy(array, index, newArray, index + 1, array.length - index);
}
return newArray;
} | java | {
"resource": ""
} |
q18150 | ArrayUtils.remove | train | @SuppressWarnings("unchecked")
public static <T> T[] remove(T[] array, int index) {
Assert.notNull(array, "Array is required");
assertThat(index).throwing(new ArrayIndexOutOfBoundsException(
String.format("[%1$d] is not a valid index [0, %2$d] in the array", index, array.length)))
.isGreaterThanEqualToAndLessThan(0, array.length);
Class<?> componentType = defaultIfNull(array.getClass().getComponentType(), Object.class);
T[] newArray = (T[]) Array.newInstance(componentType, array.length - 1);
if (index > 0) {
System.arraycopy(array, 0, newArray, 0, index);
}
if (index + 1 < array.length) {
System.arraycopy(array, index + 1, newArray, index, (array.length - index - 1));
}
return newArray;
} | java | {
"resource": ""
} |
q18151 | ArrayUtils.sort | train | public static <T> T[] sort(T[] array, Comparator<T> comparator) {
Arrays.sort(array, comparator);
return array;
} | java | {
"resource": ""
} |
q18152 | ArrayUtils.subArray | train | @SuppressWarnings("unchecked")
public static <T> T[] subArray(T[] array, int... indices) {
List<T> subArrayList = new ArrayList<>(indices.length);
for (int index : indices) {
subArrayList.add(array[index]);
}
return subArrayList.toArray((T[]) Array.newInstance(array.getClass().getComponentType(), subArrayList.size()));
} | java | {
"resource": ""
} |
q18153 | ArrayUtils.swap | train | public static <T> T[] swap(T[] array, int indexOne, int indexTwo) {
T elementAtIndexOne = array[indexOne];
array[indexOne] = array[indexTwo];
array[indexTwo] = elementAtIndexOne;
return array;
} | java | {
"resource": ""
} |
q18154 | Log.warnFormatted | train | public static void warnFormatted(final Exception exception) {
logWriterInstance.warn(exception);
UaiWebSocketLogManager.addLogText("[WARN] An exception just happened: " + exception.getMessage());
} | java | {
"resource": ""
} |
q18155 | Messages.toJson | train | public static JsonObject toJson(Message output) {
JsonObject object = new JsonObject();
for (Map.Entry<Descriptors.FieldDescriptor, Object> field : output.getAllFields().entrySet()) {
String jsonName = CaseFormat.LOWER_UNDERSCORE.to(
CaseFormat.LOWER_CAMEL, field.getKey().getName());
if (field.getKey().isRepeated()) {
JsonArray array = new JsonArray();
List<?> items = (List<?>) field.getValue();
for (Object item : items) {
array.add(serializeField(field.getKey(), item));
}
object.add(jsonName, array);
} else {
object.add(jsonName, serializeField(field.getKey(), field.getValue()));
}
}
return object;
} | java | {
"resource": ""
} |
q18156 | Messages.fromJson | train | public static Message fromJson(Message.Builder builder, JsonObject input) throws Exception {
Descriptors.Descriptor descriptor = builder.getDescriptorForType();
for (Map.Entry<String, JsonElement> entry : input.entrySet()) {
String protoName = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, entry.getKey());
Descriptors.FieldDescriptor field = descriptor.findFieldByName(protoName);
if (field == null) {
throw new Exception("Can't find descriptor for field " + protoName);
}
if (field.isRepeated()) {
if (!entry.getValue().isJsonArray()) {
// fail
}
JsonArray array = entry.getValue().getAsJsonArray();
for (JsonElement item : array) {
builder.addRepeatedField(field, parseField(field, item, builder));
}
} else {
builder.setField(field, parseField(field, entry.getValue(), builder));
}
}
return builder.build();
} | java | {
"resource": ""
} |
q18157 | Util.bind | train | public static void bind(final Context _ctx,
final String _nameStr,
final Object _object)
throws NamingException
{
final Name names = _ctx.getNameParser("").parse(_nameStr);
if (names.size() > 0) {
Context subCtx = _ctx;
for (int idx = 0; idx < names.size() - 1; idx++) {
final String name = names.get(idx);
try {
subCtx = (Context) subCtx.lookup(name);
if (Util.LOG.isDebugEnabled()) {
Util.LOG.debug("Subcontext " + name + " already exists");
}
} catch (final NameNotFoundException e) {
subCtx = subCtx.createSubcontext(name);
if (Util.LOG.isDebugEnabled()) {
Util.LOG.debug("Subcontext " + name + " created");
}
}
}
subCtx.rebind(names.get(names.size() - 1), _object);
if (Util.LOG.isDebugEnabled()) {
Util.LOG.debug("Bound object to " + names.get(names.size() - 1));
}
}
} | java | {
"resource": ""
} |
q18158 | JCRStoreResource.getSession | train | protected Session getSession()
throws EFapsException
{
if (this.session == null) {
try {
String username = getProperties().get(JCRStoreResource.PROPERTY_USERNAME);
if (username == null) {
username = Context.getThreadContext().getPerson().getName();
}
String passwd = getProperties().get(JCRStoreResource.PROPERTY_PASSWORD);
if (passwd == null) {
passwd = "efaps";
}
this.session = this.repository.login(new SimpleCredentials(username, passwd.toCharArray()),
getProperties().get(JCRStoreResource.PROPERTY_WORKSPACENAME));
} catch (final LoginException e) {
throw new EFapsException(JCRStoreResource.class, "initialize.LoginException", e);
} catch (final NoSuchWorkspaceException e) {
throw new EFapsException(JCRStoreResource.class, "initialize.NoSuchWorkspaceException", e);
} catch (final RepositoryException e) {
throw new EFapsException(JCRStoreResource.class, "initialize.RepositoryException", e);
}
}
return this.session;
} | java | {
"resource": ""
} |
q18159 | JCRStoreResource.getFolderNode | train | protected Node getFolderNode()
throws EFapsException, RepositoryException
{
Node ret = getSession().getRootNode();
if (getProperties().containsKey(JCRStoreResource.PROPERTY_BASEFOLDER)) {
if (ret.hasNode(getProperties().get(JCRStoreResource.PROPERTY_BASEFOLDER))) {
ret = ret.getNode(getProperties().get(JCRStoreResource.PROPERTY_BASEFOLDER));
} else {
ret = ret.addNode(getProperties().get(JCRStoreResource.PROPERTY_BASEFOLDER), NodeType.NT_FOLDER);
}
}
final String subFolder = new DateTime().toString("yyyy-MM");
if (ret.hasNode(subFolder)) {
ret = ret.getNode(subFolder);
} else {
ret = ret.addNode(subFolder, NodeType.NT_FOLDER);
}
return ret;
} | java | {
"resource": ""
} |
q18160 | JCRStoreResource.getBinary | train | protected Binary getBinary(final InputStream _in)
throws EFapsException
{
Binary ret = null;
try {
ret = SerialValueFactory.getInstance().createBinary(_in);
} catch (final RepositoryException e) {
throw new EFapsException("RepositoryException", e);
}
return ret;
} | java | {
"resource": ""
} |
q18161 | JCRStoreResource.setIdentifer | train | protected void setIdentifer(final String _identifier)
throws EFapsException
{
if (!_identifier.equals(this.identifier)) {
ConnectionResource res = null;
try {
res = Context.getThreadContext().getConnectionResource();
final StringBuffer cmd = new StringBuffer().append("update ")
.append(JCRStoreResource.TABLENAME_STORE).append(" set ")
.append(JCRStoreResource.COLNAME_IDENTIFIER).append("=? ")
.append("where ID =").append(getGeneralID());
final PreparedStatement stmt = res.prepareStatement(cmd.toString());
try {
stmt.setString(1, _identifier);
stmt.execute();
} finally {
stmt.close();
}
this.identifier = _identifier;
} catch (final EFapsException e) {
throw e;
} catch (final SQLException e) {
throw new EFapsException(JDBCStoreResource.class, "write.SQLException", e);
}
}
} | java | {
"resource": ""
} |
q18162 | JCRStoreResource.rollback | train | @Override
public void rollback(final Xid _xid)
throws XAException
{
try {
getSession().logout();
} catch (final EFapsException e) {
throw new XAException("EFapsException");
}
} | java | {
"resource": ""
} |
q18163 | XMLUserLoginModule.initialize | train | @Override
public final void initialize(final Subject _subject,
final CallbackHandler _callbackHandler,
final Map < String, ? > _sharedState,
final Map < String, ? > _options)
{
XMLUserLoginModule.LOG.debug("Init");
this.subject = _subject;
this.callbackHandler = _callbackHandler;
readPersons((String) _options.get("xmlFileName"));
} | java | {
"resource": ""
} |
q18164 | XMLUserLoginModule.readPersons | train | @SuppressWarnings("unchecked")
private void readPersons(final String _fileName)
{
try {
final File file = new File(_fileName);
final Digester digester = new Digester();
digester.setValidating(false);
digester.addObjectCreate("persons", ArrayList.class);
digester.addObjectCreate("persons/person", XMLPersonPrincipal.class);
digester.addSetNext("persons/person", "add");
digester.addCallMethod("persons/person/name", "setName", 1);
digester.addCallParam("persons/person/name", 0);
digester.addCallMethod("persons/person/password", "setPassword", 1);
digester.addCallParam("persons/person/password", 0);
digester.addCallMethod("persons/person/firstName", "setFirstName", 1);
digester.addCallParam("persons/person/firstName", 0);
digester.addCallMethod("persons/person/lastName", "setLastName", 1);
digester.addCallParam("persons/person/lastName", 0);
digester.addCallMethod("persons/person/email", "setEmail", 1);
digester.addCallParam("persons/person/email", 0);
digester.addCallMethod("persons/person/organisation", "setOrganisation", 1);
digester.addCallParam("persons/person/organisation", 0);
digester.addCallMethod("persons/person/url", "setUrl", 1);
digester.addCallParam("persons/person/url", 0);
digester.addCallMethod("persons/person/phone", "setPhone", 1);
digester.addCallParam("persons/person/phone", 0);
digester.addCallMethod("persons/person/mobile", "setMobile", 1);
digester.addCallParam("persons/person/mobile", 0);
digester.addCallMethod("persons/person/fax", "setFax", 1);
digester.addCallParam("persons/person/fax", 0);
digester.addCallMethod("persons/person/role", "addRole", 1);
digester.addCallParam("persons/person/role", 0);
digester.addCallMethod("persons/person/group", "addGroup", 1);
digester.addCallParam("persons/person/group", 0);
final List<XMLPersonPrincipal> personList = (List<XMLPersonPrincipal>) digester.parse(file);
for (final XMLPersonPrincipal personTmp : personList) {
this.allPersons.put(personTmp.getName(), personTmp);
}
} catch (final IOException e) {
XMLUserLoginModule.LOG.error("could not open file '" + _fileName + "'", e);
} catch (final SAXException e) {
XMLUserLoginModule.LOG.error("could not read file '" + _fileName + "'", e);
}
} | java | {
"resource": ""
} |
q18165 | AccessSet.getAccessSetFromDB | train | private static boolean getAccessSetFromDB(final String _sql,
final Object _criteria)
throws CacheReloadException
{
boolean ret = false;
Connection con = null;
try {
AccessSet accessSet = null;
con = Context.getConnection();
PreparedStatement stmt = null;
try {
stmt = con.prepareStatement(_sql);
stmt.setObject(1, _criteria);
final ResultSet rs = stmt.executeQuery();
if (rs.next()) {
final long id = rs.getLong(1);
final String uuid = rs.getString(2);
final String name = rs.getString(3);
AccessSet.LOG.debug("read AccessSet '{}' (id = {}, uuid ={})", name, id, uuid);
accessSet = new AccessSet(id, uuid, name);
}
ret = true;
rs.close();
} finally {
if (stmt != null) {
stmt.close();
}
}
con.commit();
if (accessSet != null) {
accessSet.readLinks2AccessTypes();
accessSet.readLinks2DMTypes();
accessSet.readLinks2Status();
accessSet.readLinks2Person();
// needed due to cluster serialization that does not update automatically
AccessSet.cacheAccessSet(accessSet);
}
} catch (final SQLException e) {
throw new CacheReloadException("could not read roles", e);
} catch (final EFapsException e) {
throw new CacheReloadException("could not read roles", e);
} finally {
try {
if (con != null && !con.isClosed()) {
con.close();
}
} catch (final SQLException e) {
throw new CacheReloadException("could not read child type ids", e);
}
}
return ret;
} | java | {
"resource": ""
} |
q18166 | Table.cloneTable | train | public Table cloneTable()
{
Table ret = null;
try {
ret = (Table) super.clone();
} catch (final CloneNotSupportedException e) {
e.printStackTrace();
}
return ret;
} | java | {
"resource": ""
} |
q18167 | MethodExpressionHandler.setIndex | train | @Override
public void setIndex(boolean b)
{
if (b)
{
assert safe == null;
safe = type;
type = Typ.Int;
}
else
{
assert type.getKind() == TypeKind.INT;
assert safe != null;
type = safe;
safe = null;
}
} | java | {
"resource": ""
} |
q18168 | AbstractCache.hasEntries | train | public boolean hasEntries()
{
return (getCache4Id() != null && !getCache4Id().isEmpty())
|| (getCache4Name() != null && !getCache4Name().isEmpty())
|| (getCache4UUID() != null && !getCache4UUID().isEmpty());
} | java | {
"resource": ""
} |
q18169 | AbstractCache.initialize | train | public void initialize(final Class<?> _initializer)
{
this.initializer = _initializer.getName();
synchronized (this) {
try {
readCache();
} catch (final CacheReloadException e) {
AbstractCache.LOG.error("Unexpected error while initializing Cache for " + getClass(), e);
}
}
} | java | {
"resource": ""
} |
q18170 | AbstractCache.clear | train | public void clear()
{
if (getCache4Id() != null) {
getCache4Id().clear();
}
if (getCache4Name() != null) {
getCache4Name().clear();
}
if (getCache4UUID() != null) {
getCache4UUID().clear();
}
} | java | {
"resource": ""
} |
q18171 | AbstractCache.clearCaches | train | public static void clearCaches()
{
synchronized (AbstractCache.CACHES) {
for (final AbstractCache<?> cache : AbstractCache.CACHES) {
cache.getCache4Id().clear();
cache.getCache4Name().clear();
cache.getCache4UUID().clear();
}
}
} | java | {
"resource": ""
} |
q18172 | CompositePropertyMatcher.registerPropertyMatcher | train | @Override
public void registerPropertyMatcher(PropertyMatcher<?> propertyMatcher) {
if (propertyMatcher.getPathProvider() == null) {
propertyMatcher.setPathProvider(this);
}
propertyMatcherList.add(propertyMatcher);
} | java | {
"resource": ""
} |
q18173 | DeviceService.add | train | @Deprecated
public Add add(long projectId, String deviceId, String deviceName, String deviceType,
Date created) {
return add(projectId, new Device.Spec(deviceId, deviceName, deviceType), created);
} | java | {
"resource": ""
} |
q18174 | UserLoginModule.abort | train | public final boolean abort()
{
boolean ret = false;
if (UserLoginModule.LOG.isDebugEnabled()) {
UserLoginModule.LOG.debug("Abort of " + this.principal);
}
// If our authentication was successful, just return false
if (this.principal != null) {
// Clean up if overall authentication failed
if (this.committed) {
this.subject.getPrincipals().remove(this.principal);
}
this.committed = false;
this.principal = null;
ret = true;
}
return ret;
} | java | {
"resource": ""
} |
q18175 | AbstractUpdate.readXML | train | @Override
public void readXML(final List<String> _tags,
final Map<String, String> _attributes,
final String _text)
throws SAXException, EFapsException
{
if (_tags.size() == 1) {
final String value = _tags.get(0);
if ("uuid".equals(value)) {
this.uuid = _text;
} else if ("file-application".equals(value)) {
this.fileApplication = _text;
} else if ("definition".equals(value)) {
this.definitions.add(newDefinition());
}
} else if ("definition".equals(_tags.get(0))) {
final AbstractDefinition curDef = this.definitions.get(this.definitions.size() - 1);
curDef.readXML(_tags.subList(1, _tags.size()), _attributes, _text);
} else {
throw new SAXException("Unknown XML Tag: " + _tags + " for: " + this.installFile);
}
} | java | {
"resource": ""
} |
q18176 | AbstractUpdate.registerRevision | train | protected void registerRevision(final String _application,
final InstallFile _installFile,
final Instance _objInst)
throws InstallationException
{
try {
if (CIAdminCommon.Application.getType() != null
&& CIAdminCommon.Application.getType().getAttributes().size() > 4) {
final QueryBuilder appQueryBldr = new QueryBuilder(CIAdminCommon.Application);
appQueryBldr.addWhereAttrEqValue(CIAdminCommon.Application.Name, _application);
final CachedInstanceQuery appQuery = appQueryBldr.getCachedQuery4Request();
appQuery.execute();
if (appQuery.next()) {
final Instance appInst = appQuery.getCurrentValue();
final QueryBuilder queryBldr = new QueryBuilder(CIAdminCommon.ApplicationRevision);
queryBldr.addWhereAttrEqValue(CIAdminCommon.ApplicationRevision.ApplicationLink, appInst);
queryBldr.addWhereAttrEqValue(CIAdminCommon.ApplicationRevision.Revision,
_installFile.getRevision());
final MultiPrintQuery multi = queryBldr.getPrint();
multi.addAttribute(CIAdminCommon.ApplicationRevision.Date);
multi.execute();
final Instance appRevInst;
if (multi.next()) {
appRevInst = multi.getCurrentInstance();
if (_installFile.getDate().isAfter(multi.<DateTime>getAttribute(
CIAdminCommon.ApplicationRevision.Date))) {
AbstractUpdate.LOG.debug("Updated Revision {} - {} with Date {] ",
_installFile.getRevision(), _application, _installFile.getDate());
final Update update = new Update(appRevInst);
update.add(CIAdminCommon.ApplicationRevision.Date, _installFile.getDate());
update.executeWithoutTrigger();
}
} else {
final Insert insert = new Insert(CIAdminCommon.ApplicationRevision);
insert.add(CIAdminCommon.ApplicationRevision.ApplicationLink, appInst);
insert.add(CIAdminCommon.ApplicationRevision.Revision, _installFile.getRevision());
insert.add(CIAdminCommon.ApplicationRevision.Date, _installFile.getDate());
insert.execute();
appRevInst = insert.getInstance();
}
if (_objInst.getType().getAttribute(CIAdmin.Abstract.RevisionLink.name) != null) {
final Update update = new Update(_objInst);
update.add(CIAdmin.Abstract.RevisionLink.name, appRevInst);
update.executeWithoutTrigger();
}
}
}
} catch (final EFapsException e) {
throw new InstallationException("Exception", e);
}
} | java | {
"resource": ""
} |
q18177 | BlogConnectionFactory.getBlogConnection | train | public static BlogConnection getBlogConnection(final String type, final String url, final String username, final String password)
throws BlogClientException {
BlogConnection blogConnection = null;
if (type == null || type.equals("metaweblog")) {
blogConnection = createBlogConnection(METAWEBLOG_IMPL_CLASS, url, username, password);
} else if (type.equals("atom")) {
blogConnection = createBlogConnection(ATOMPROTOCOL_IMPL_CLASS, url, username, password);
} else {
throw new BlogClientException("Type must be 'atom' or 'metaweblog'");
}
return blogConnection;
} | java | {
"resource": ""
} |
q18178 | ExecutionContext.future | train | @SuppressWarnings("unchecked")
public <G> OrFuture<G, BAD> future(CheckedFunction0<? extends Or<? extends G, ? extends BAD>> task) {
OrFutureImpl<G, BAD> future = new OrFutureImpl<>(this);
executor.execute(() -> {
try {
future.complete((Or<G, BAD>) task.apply());
} catch (Throwable t) {
future.complete(Bad.of(converter.apply(t)));
}
});
return future;
} | java | {
"resource": ""
} |
q18179 | ExecutionContext.when | train | @SafeVarargs
public final <G, ERR> OrFuture<G, Every<ERR>>
when(OrFuture<? extends G, ? extends Every<? extends ERR>> or,
Function<? super G, ? extends Validation<ERR>>... validations) {
OrPromise<G, Every<ERR>> promise = promise();
or.onComplete(o -> promise.complete(Accumulation.when(o, validations)));
return promise.future();
} | java | {
"resource": ""
} |
q18180 | ExecutionContext.withGood | train | public <A, B, ERR, RESULT> OrFuture<RESULT, Every<ERR>>
withGood(OrFuture<? extends A, ? extends Every<? extends ERR>> fa,
OrFuture<? extends B, ? extends Every<? extends ERR>> fb,
BiFunction<? super A, ? super B, ? extends RESULT> function) {
return withPromise(this, promise ->
fa.onComplete(ora ->
fb.onComplete(orb ->
promise.complete(Accumulation.withGood(ora, orb, function)))));
} | java | {
"resource": ""
} |
q18181 | ExecutionContext.firstCompletedOf | train | public <G, ERR> OrFuture<G, ERR>
firstCompletedOf(Iterable<? extends OrFuture<? extends G, ? extends ERR>> input) {
OrPromise<G, ERR> promise = promise();
input.forEach(future -> future.onComplete(promise::tryComplete));
return promise.future();
} | java | {
"resource": ""
} |
q18182 | ExecutionContext.zip | train | public <A, B, ERR> OrFuture<Tuple2<A, B>, Every<ERR>>
zip(OrFuture<? extends A, ? extends Every<? extends ERR>> a,
OrFuture<? extends B, ? extends Every<? extends ERR>> b) {
return withGood(a, b, Tuple::of);
} | java | {
"resource": ""
} |
q18183 | ExecutionContext.zip3 | train | public <A, B, C, ERR> OrFuture<Tuple3<A, B, C>, Every<ERR>>
zip3(OrFuture<? extends A, ? extends Every<? extends ERR>> a,
OrFuture<? extends B, ? extends Every<? extends ERR>> b,
OrFuture<? extends C, ? extends Every<? extends ERR>> c) {
return withGood(a, b, c, Tuple::of);
} | java | {
"resource": ""
} |
q18184 | OracleDatabaseWithAutoSequence.getNewId | train | @Override
public long getNewId(final ConnectionResource _con,
final String _table,
final String _column)
throws SQLException
{
throw new SQLException("The database driver uses auto generated keys and "
+ "a new id could not returned without making "
+ "a new insert.");
} | java | {
"resource": ""
} |
q18185 | Checkout.execute | train | public void execute(final OutputStream _out)
throws EFapsException
{
final boolean hasAccess = super.getInstance().getType().hasAccess(super.getInstance(),
AccessTypeEnums.CHECKOUT.getAccessType());
if (!hasAccess) {
throw new EFapsException(this.getClass(), "execute.NoAccess");
}
this.executeWithoutAccessCheck(_out);
} | java | {
"resource": ""
} |
q18186 | Checkout.executeWithoutTrigger | train | public void executeWithoutTrigger(final OutputStream _out)
throws EFapsException
{
Resource storeRsrc = null;
try {
storeRsrc = Context.getThreadContext().getStoreResource(getInstance(), Resource.StoreEvent.READ);
storeRsrc.read(_out);
this.fileLength = storeRsrc.getFileLength();
this.fileName = storeRsrc.getFileName();
} catch (final EFapsException e) {
Checkout.LOG.error("could not checkout " + super.getInstance(), e);
throw e;
}
} | java | {
"resource": ""
} |
q18187 | DateTimeUtil.getCurrentTimeFromDB | train | public static Timestamp getCurrentTimeFromDB() throws EFapsException
{
Timestamp now = null;
final ConnectionResource rsrc = Context.getThreadContext().getConnectionResource();
final Statement stmt;
try {
stmt = rsrc.createStatement();
final ResultSet resultset = stmt.executeQuery("SELECT " + Context.getDbType().getCurrentTimeStamp());
resultset.next();
now = resultset.getTimestamp(1);
resultset.close();
stmt.close();
} catch (final SQLException e) {
DateTimeUtil.LOG.error("could not execute SQL-Statement", e);
}
return now;
} | java | {
"resource": ""
} |
q18188 | TweenAnimation.start | train | void start(long currentTime) {
this.readyTime = currentTime;
this.startTime = this.readyTime + this.delayTime;
this.endTime = this.startTime + getDuration();
this.status = TweenAnimationStatus.RUNNING;
} | java | {
"resource": ""
} |
q18189 | TweenAnimation.render | train | final void render(long currentTime) {
if (this.getStatus() != TweenAnimationStatus.RUNNING) {
return;
}
if (currentTime >= endTime && this.getStatus() != TweenAnimationStatus.WAIT) {
this.status = TweenAnimationStatus.WAIT;
return;
}
value = equation.compute(currentTime - startTime, getStartValue(), getEndValue() - getStartValue(), getDuration());
} | java | {
"resource": ""
} |
q18190 | AtomEntryIterator.next | train | @Override
public BlogEntry next() {
try {
final ClientEntry entry = iterator.next();
if (entry instanceof ClientMediaEntry) {
return new AtomResource(collection, (ClientMediaEntry) entry);
} else {
return new AtomEntry(collection, entry);
}
} catch (final Exception e) {
LOG.error("An error occured while fetching entry", e);
}
return null;
} | java | {
"resource": ""
} |
q18191 | Phrase.getPhraseValue | train | public String getPhraseValue(final Instance _instance)
throws EFapsException
{
final StringBuilder buf = new StringBuilder();
boolean added = false;
for (final Token token : this.valueList.getTokens()) {
switch (token.getType()) {
case EXPRESSION:
final OneSelect oneselect = this.selectStmt2OneSelect.get(token.getValue());
final Object value = oneselect.getObject();
if (oneselect.getAttribute() != null) {
final UIValue uiValue = UIValue.get(null, oneselect.getAttribute(), value);
final String val = uiValue.getUIProvider().getStringValue(uiValue);
if (val != null) {
added = true;
buf.append(uiValue.getUIProvider().getStringValue(uiValue));
}
} else if (value != null) {
added = true;
buf.append(value);
}
break;
case TEXT:
buf.append(token.getValue());
break;
default:
break;
}
}
return added ? buf.toString() : "";
} | java | {
"resource": ""
} |
q18192 | Indexer.index | train | public static void index()
throws EFapsException
{
final List<IndexDefinition> defs = IndexDefinition.get();
for (final IndexDefinition def : defs) {
final QueryBuilder queryBldr = new QueryBuilder(def.getUUID());
final InstanceQuery query = queryBldr.getQuery();
index(query.execute());
}
} | java | {
"resource": ""
} |
q18193 | LRVerify.VerifyStrings | train | public static boolean VerifyStrings(String signature, String message, String publicKey) throws LRException
{
// Check that none of the inputs are null
if (signature == null || message == null || publicKey == null)
{
throw new LRException(LRException.NULL_FIELD);
}
// Convert all inputs into input streams
InputStream isSignature = null;
InputStream isMessage = null;
InputStream isPublicKey = null;
try
{
isSignature = new ByteArrayInputStream(signature.getBytes());
isMessage = new ByteArrayInputStream(message.getBytes());
isPublicKey = new ByteArrayInputStream(publicKey.getBytes());
}
catch (Exception e)
{
throw new LRException(LRException.INPUT_STREAM_FAILED);
}
// Feed the input streams into the primary verify function
return Verify(isSignature, isMessage, isPublicKey);
} | java | {
"resource": ""
} |
q18194 | LRVerify.Verify | train | private static boolean Verify(InputStream isSignature, InputStream isMessage, InputStream isPublicKey) throws LRException
{
// Get the public key ring collection from the public key input stream
PGPPublicKeyRingCollection pgpRings = null;
try
{
pgpRings = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(isPublicKey));
}
catch (Exception e)
{
throw new LRException(LRException.INVALID_PUBLIC_KEY);
}
// Add the Bouncy Castle security provider
Security.addProvider(new BouncyCastleProvider());
// Build an output stream from the message for verification
boolean verify = false;
int ch;
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
ArmoredInputStream aIn = null;
try
{
aIn = new ArmoredInputStream(isMessage);
// We are making no effort to clean the input for this example
// If this turns into a fully-featured verification utility in a future version, this will need to be handled
while ((ch = aIn.read()) >= 0 && aIn.isClearText())
{
bOut.write((byte)ch);
}
bOut.close();
}
catch (Exception e)
{
throw new LRException(LRException.MESSAGE_INVALID);
}
// Build an object factory from the signature input stream and try to get an object out of it
Object o = null;
try
{
PGPObjectFactory pgpFact = new PGPObjectFactory(PGPUtil.getDecoderStream(isSignature));
o = pgpFact.nextObject();
}
catch (Exception e)
{
throw new LRException(LRException.SIGNATURE_INVALID);
}
// Check if the object we fetched is a signature list and if it is, get the signature and use it to verfiy
try
{
if (o instanceof PGPSignatureList)
{
PGPSignatureList list = (PGPSignatureList)o;
if (list.size() > 0)
{
PGPSignature sig = list.get(0);
PGPPublicKey publicKey = pgpRings.getPublicKey(sig.getKeyID());
sig.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), publicKey);
sig.update(bOut.toByteArray());
verify = sig.verify();
}
}
}
catch (Exception e)
{
throw new LRException(LRException.SIGNATURE_NOT_FOUND);
}
return verify;
} | java | {
"resource": ""
} |
q18195 | StencilEngine.setGlobalScopes | train | public void setGlobalScopes(Iterable<GlobalScope> globalScopes) {
this.globalScopes = Lists.newArrayList(Iterables.concat(globalScopes, serviceGlobalScopes));
} | java | {
"resource": ""
} |
q18196 | StencilEngine.render | train | public void render(String path, Map<String, Object> parameters, Writer out, GlobalScope... extraGlobalScopes) throws IOException, ParseException {
render(load(path), parameters, out);
} | java | {
"resource": ""
} |
q18197 | StencilEngine.renderInline | train | public void renderInline(String text, Map<String, Object> parameters, Writer out, GlobalScope... extraGlobalScopes) throws IOException, ParseException {
render(loadInline(text), parameters, out, extraGlobalScopes);
} | java | {
"resource": ""
} |
q18198 | StencilEngine.render | train | public void render(Template template, Map<String, Object> parameters, Writer out, GlobalScope... extraGlobalScopes) throws IOException {
newInterpreter(extraGlobalScopes).declare(parameters).process((TemplateImpl) template, out);
} | java | {
"resource": ""
} |
q18199 | StencilEngine.render | train | public void render(Template template, Writer out, GlobalScope... extraGlobalScopes) throws IOException {
newInterpreter(extraGlobalScopes).process((TemplateImpl) template, out);
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.