code stringlengths 73 34.1k | label stringclasses 1 value |
|---|---|
public void fetchUninitializedAttributes() {
for (String prefixedId : getPrefixedAttributeNames()) {
BeanIdentifier id = getNamingScheme().deprefix(prefixedId);
if (!beanStore.contains(id)) {
ContextualInstance<?> instance = (ContextualInstance<?>) getAttribute(prefixedId);
beanStore.put(id, instance);
ContextLogger.LOG.addingDetachedContextualUnderId(instance, id);
}
}
} | java |
static void merge(Map<ConfigurationKey, Object> original, Map<ConfigurationKey, Object> toMerge, String mergedSourceDescription) {
for (Entry<ConfigurationKey, Object> entry : toMerge.entrySet()) {
Object existing = original.get(entry.getKey());
if (existing != null) {
ConfigurationLogger.LOG.configurationKeyAlreadySet(entry.getKey().get(), existing, entry.getValue(), mergedSourceDescription);
} else {
original.put(entry.getKey(), entry.getValue());
}
}
} | java |
private Map<ConfigurationKey, Object> getObsoleteSystemProperties() {
Map<ConfigurationKey, Object> found = new EnumMap<ConfigurationKey, Object>(ConfigurationKey.class);
String concurrentDeployment = getSystemProperty("org.jboss.weld.bootstrap.properties.concurrentDeployment");
if (concurrentDeployment != null) {
processKeyValue(found, ConfigurationKey.CONCURRENT_DEPLOYMENT, concurrentDeployment);
found.put(ConfigurationKey.CONCURRENT_DEPLOYMENT, ConfigurationKey.CONCURRENT_DEPLOYMENT.convertValue(concurrentDeployment));
}
String preloaderThreadPoolSize = getSystemProperty("org.jboss.weld.bootstrap.properties.preloaderThreadPoolSize");
if (preloaderThreadPoolSize != null) {
found.put(ConfigurationKey.PRELOADER_THREAD_POOL_SIZE, ConfigurationKey.PRELOADER_THREAD_POOL_SIZE.convertValue(preloaderThreadPoolSize));
}
return found;
} | java |
@SuppressFBWarnings(value = "DMI_COLLECTION_OF_URLS", justification = "Only local URLs involved")
private Map<ConfigurationKey, Object> readFileProperties(Set<URL> files) {
Map<ConfigurationKey, Object> found = new EnumMap<ConfigurationKey, Object>(ConfigurationKey.class);
for (URL file : files) {
ConfigurationLogger.LOG.readingPropertiesFile(file);
Properties fileProperties = loadProperties(file);
for (String name : fileProperties.stringPropertyNames()) {
processKeyValue(found, name, fileProperties.getProperty(name));
}
}
return found;
} | java |
private void processKeyValue(Map<ConfigurationKey, Object> properties, ConfigurationKey key, Object value) {
if (value instanceof String) {
value = key.convertValue((String) value);
}
if (key.isValidValue(value)) {
Object previous = properties.put(key, value);
if (previous != null && !previous.equals(value)) {
throw ConfigurationLogger.LOG.configurationKeyHasDifferentValues(key.get(), previous, value);
}
} else {
throw ConfigurationLogger.LOG.invalidConfigurationPropertyValue(value, key.get());
}
} | java |
public static <T, X> ObserverMethodImpl<T, X> create(EnhancedAnnotatedMethod<T, ? super X> method, RIBean<X> declaringBean, BeanManagerImpl manager, boolean isAsync) {
if (declaringBean instanceof ExtensionBean) {
return new ExtensionObserverMethodImpl<T, X>(method, declaringBean, manager, isAsync);
}
return new ObserverMethodImpl<T, X>(method, declaringBean, manager, isAsync);
} | java |
public static TransactionPhase getTransactionalPhase(EnhancedAnnotatedMethod<?, ?> observer) {
EnhancedAnnotatedParameter<?, ?> parameter = observer.getEnhancedParameters(Observes.class).iterator().next();
return parameter.getAnnotation(Observes.class).during();
} | java |
static WeldContainer startInitialization(String id, Deployment deployment, Bootstrap bootstrap) {
if (SINGLETON.isSet(id)) {
throw WeldSELogger.LOG.weldContainerAlreadyRunning(id);
}
WeldContainer weldContainer = new WeldContainer(id, deployment, bootstrap);
SINGLETON.set(id, weldContainer);
RUNNING_CONTAINER_IDS.add(id);
return weldContainer;
} | java |
static void endInitialization(WeldContainer container, boolean isShutdownHookEnabled) {
container.complete();
// If needed, register one shutdown hook for all containers
if (shutdownHook == null && isShutdownHookEnabled) {
synchronized (LOCK) {
if (shutdownHook == null) {
shutdownHook = new ShutdownHook();
SecurityActions.addShutdownHook(shutdownHook);
}
}
}
container.fireContainerInitializedEvent();
} | java |
public synchronized void shutdown() {
checkIsRunning();
try {
beanManager().fireEvent(new ContainerBeforeShutdown(id), BeforeDestroyed.Literal.APPLICATION);
} finally {
discard(id);
// Destroy all the dependent beans correctly
creationalContext.release();
beanManager().fireEvent(new ContainerShutdown(id), Destroyed.Literal.APPLICATION);
bootstrap.shutdown();
WeldSELogger.LOG.weldContainerShutdown(id);
}
} | java |
@Override
public Collection<EnhancedAnnotatedConstructor<T>> getEnhancedConstructors(Class<? extends Annotation> annotationType) {
Set<EnhancedAnnotatedConstructor<T>> ret = new HashSet<EnhancedAnnotatedConstructor<T>>();
for (EnhancedAnnotatedConstructor<T> constructor : constructors) {
if (constructor.isAnnotationPresent(annotationType)) {
ret.add(constructor);
}
}
return ret;
} | java |
protected void setBeanStore(BoundBeanStore beanStore) {
if (beanStore == null) {
this.beanStore.remove();
} else {
this.beanStore.set(beanStore);
}
} | java |
public void setArgs(String[] args) {
if (args == null) {
args = new String[]{};
}
this.args = args;
this.argsList = Collections.unmodifiableList(new ArrayList<String>(Arrays.asList(args)));
} | java |
public Weld addPackages(boolean scanRecursively, Class<?>... packageClasses) {
for (Class<?> packageClass : packageClasses) {
addPackage(scanRecursively, packageClass);
}
return this;
} | java |
public Weld addPackage(boolean scanRecursively, Class<?> packageClass) {
packages.add(new PackInfo(packageClass, scanRecursively));
return this;
} | java |
public Weld extensions(Extension... extensions) {
this.extensions.clear();
for (Extension extension : extensions) {
addExtension(extension);
}
return this;
} | java |
public Weld addExtension(Extension extension) {
extensions.add(new MetadataImpl<Extension>(extension, SYNTHETIC_LOCATION_PREFIX + extension.getClass().getName()));
return this;
} | java |
public Weld property(String key, Object value) {
properties.put(key, value);
return this;
} | java |
public Weld addBeanDefiningAnnotations(Class<? extends Annotation>... annotations) {
for (Class<? extends Annotation> annotation : annotations) {
this.extendedBeanDefiningAnnotations.add(annotation);
}
return this;
} | java |
private static void checkSensibility(AnnotatedType<?> type) {
// check if it has a constructor
if (type.getConstructors().isEmpty() && !type.getJavaClass().isInterface()) {
MetadataLogger.LOG.noConstructor(type);
}
Set<Class<?>> hierarchy = new HashSet<Class<?>>();
for (Class<?> clazz = type.getJavaClass(); clazz != null; clazz = clazz.getSuperclass()) {
hierarchy.add(clazz);
hierarchy.addAll(Reflections.getInterfaceClosure(clazz));
}
checkMembersBelongToHierarchy(type.getConstructors(), hierarchy, type);
checkMembersBelongToHierarchy(type.getMethods(), hierarchy, type);
checkMembersBelongToHierarchy(type.getFields(), hierarchy, type);
} | java |
private static boolean isWideningPrimitive(Class<?> argumentClass, Class<?> targetClass) {
return WIDENING_TABLE.containsKey(argumentClass) && WIDENING_TABLE.get(argumentClass).contains(targetClass);
} | java |
public static <X> String createTypeId(AnnotatedType<X> annotatedType) {
String id = createTypeId(annotatedType.getJavaClass(), annotatedType.getAnnotations(), annotatedType.getMethods(), annotatedType.getFields(), annotatedType.getConstructors());
String hash = hash(id);
MetadataLogger.LOG.tracef("Generated AnnotatedType id hash for %s: %s", id, hash);
return hash;
} | java |
public static boolean compareAnnotatedParameters(AnnotatedParameter<?> p1, AnnotatedParameter<?> p2) {
return compareAnnotatedCallable(p1.getDeclaringCallable(), p2.getDeclaringCallable()) && p1.getPosition() == p2.getPosition() && compareAnnotated(p1, p2);
} | java |
public static boolean compareAnnotatedTypes(AnnotatedType<?> t1, AnnotatedType<?> t2) {
if (!t1.getJavaClass().equals(t2.getJavaClass())) {
return false;
}
if (!compareAnnotated(t1, t2)) {
return false;
}
if (t1.getFields().size() != t2.getFields().size()) {
return false;
}
Map<Field, AnnotatedField<?>> fields = new HashMap<Field, AnnotatedField<?>>();
for (AnnotatedField<?> f : t2.getFields()) {
fields.put(f.getJavaMember(), f);
}
for (AnnotatedField<?> f : t1.getFields()) {
if (fields.containsKey(f.getJavaMember())) {
if (!compareAnnotatedField(f, fields.get(f.getJavaMember()))) {
return false;
}
} else {
return false;
}
}
if (t1.getMethods().size() != t2.getMethods().size()) {
return false;
}
Map<Method, AnnotatedMethod<?>> methods = new HashMap<Method, AnnotatedMethod<?>>();
for (AnnotatedMethod<?> f : t2.getMethods()) {
methods.put(f.getJavaMember(), f);
}
for (AnnotatedMethod<?> f : t1.getMethods()) {
if (methods.containsKey(f.getJavaMember())) {
if (!compareAnnotatedCallable(f, methods.get(f.getJavaMember()))) {
return false;
}
} else {
return false;
}
}
if (t1.getConstructors().size() != t2.getConstructors().size()) {
return false;
}
Map<Constructor<?>, AnnotatedConstructor<?>> constructors = new HashMap<Constructor<?>, AnnotatedConstructor<?>>();
for (AnnotatedConstructor<?> f : t2.getConstructors()) {
constructors.put(f.getJavaMember(), f);
}
for (AnnotatedConstructor<?> f : t1.getConstructors()) {
if (constructors.containsKey(f.getJavaMember())) {
if (!compareAnnotatedCallable(f, constructors.get(f.getJavaMember()))) {
return false;
}
} else {
return false;
}
}
return true;
} | java |
public static boolean isPassivatingScope(Bean<?> bean, BeanManagerImpl manager) {
if (bean == null) {
return false;
} else {
return manager.getServices().get(MetaAnnotationStore.class).getScopeModel(bean.getScope()).isPassivating();
}
} | java |
public static boolean isBeanProxyable(Bean<?> bean, BeanManagerImpl manager) {
if (bean instanceof RIBean<?>) {
return ((RIBean<?>) bean).isProxyable();
} else {
return Proxies.isTypesProxyable(bean.getTypes(), manager.getServices());
}
} | java |
public static boolean containsAllQualifiers(Set<QualifierInstance> requiredQualifiers, Set<QualifierInstance> qualifiers) {
return qualifiers.containsAll(requiredQualifiers);
} | java |
public static <T extends Bean<?>> Set<T> removeDisabledBeans(Set<T> beans, final BeanManagerImpl beanManager) {
if (beans.isEmpty()) {
return beans;
} else {
for (Iterator<T> iterator = beans.iterator(); iterator.hasNext();) {
if (!isBeanEnabled(iterator.next(), beanManager.getEnabled())) {
iterator.remove();
}
}
return beans;
}
} | java |
public static boolean isAlternative(EnhancedAnnotated<?, ?> annotated, MergedStereotypes<?, ?> mergedStereotypes) {
return annotated.isAnnotationPresent(Alternative.class) || mergedStereotypes.isAlternative();
} | java |
public static <T> void injectEEFields(Iterable<Set<ResourceInjection<?>>> resourceInjectionsHierarchy,
T beanInstance, CreationalContext<T> ctx) {
for (Set<ResourceInjection<?>> resourceInjections : resourceInjectionsHierarchy) {
for (ResourceInjection<?> resourceInjection : resourceInjections) {
resourceInjection.injectResourceReference(beanInstance, ctx);
}
}
} | java |
public static Type getDeclaredBeanType(Class<?> clazz) {
Type[] actualTypeArguments = Reflections.getActualTypeArguments(clazz);
if (actualTypeArguments.length == 1) {
return actualTypeArguments[0];
} else {
return null;
}
} | java |
public static <T> void injectBoundFields(T instance, CreationalContext<T> creationalContext, BeanManagerImpl manager,
Iterable<? extends FieldInjectionPoint<?, ?>> injectableFields) {
for (FieldInjectionPoint<?, ?> injectableField : injectableFields) {
injectableField.inject(instance, manager, creationalContext);
}
} | java |
public static <T> void callInitializers(T instance, CreationalContext<T> creationalContext, BeanManagerImpl manager,
Iterable<? extends MethodInjectionPoint<?, ?>> initializerMethods) {
for (MethodInjectionPoint<?, ?> initializer : initializerMethods) {
initializer.invoke(instance, null, manager, creationalContext, CreationException.class);
}
} | java |
public static boolean isTypeManagedBeanOrDecoratorOrInterceptor(AnnotatedType<?> annotatedType) {
Class<?> javaClass = annotatedType.getJavaClass();
return !javaClass.isEnum() && !Extension.class.isAssignableFrom(javaClass)
&& Reflections.isTopLevelOrStaticNestedClass(javaClass) && !Reflections.isParameterizedTypeWithWildcard(javaClass)
&& hasSimpleCdiConstructor(annotatedType);
} | java |
public static <T> NewSessionBean<T> of(BeanAttributes<T> attributes, InternalEjbDescriptor<T> ejbDescriptor, BeanManagerImpl beanManager) {
EnhancedAnnotatedType<T> type = beanManager.getServices().get(ClassTransformer.class).getEnhancedAnnotatedType(ejbDescriptor.getBeanClass(), beanManager.getId());
return new NewSessionBean<T>(attributes, type, ejbDescriptor, new StringBeanIdentifier(SessionBeans.createIdentifierForNew(ejbDescriptor)), beanManager);
} | java |
public static <X, T> ProducerField<X, T> of(BeanAttributes<T> attributes, EnhancedAnnotatedField<T, ? super X> field, AbstractClassBean<X> declaringBean, DisposalMethod<X, ?> disposalMethod, BeanManagerImpl beanManager, ServiceRegistry services) {
return new ProducerField<X, T>(attributes, field, declaringBean, disposalMethod, beanManager, services);
} | java |
public static boolean hasPermission(Permission permission) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
try {
security.checkPermission(permission);
} catch (java.security.AccessControlException e) {
return false;
}
}
return true;
} | java |
public static <T> ManagedBean<T> of(BeanAttributes<T> attributes, EnhancedAnnotatedType<T> clazz, BeanManagerImpl beanManager) {
return new ManagedBean<T>(attributes, clazz, createId(attributes, clazz), beanManager);
} | java |
@Override
public void destroy(T instance, CreationalContext<T> creationalContext) {
super.destroy(instance, creationalContext);
try {
getProducer().preDestroy(instance);
// WELD-1010 hack?
if (creationalContext instanceof CreationalContextImpl) {
((CreationalContextImpl<T>) creationalContext).release(this, instance);
} else {
creationalContext.release();
}
} catch (Exception e) {
BeanLogger.LOG.errorDestroying(instance, this);
BeanLogger.LOG.catchingDebug(e);
}
} | java |
@Override
protected void checkType() {
if (!isDependent() && getEnhancedAnnotated().isParameterizedType()) {
throw BeanLogger.LOG.managedBeanWithParameterizedBeanClassMustBeDependent(type);
}
boolean passivating = beanManager.isPassivatingScope(getScope());
if (passivating && !isPassivationCapableBean()) {
if (!getEnhancedAnnotated().isSerializable()) {
throw BeanLogger.LOG.passivatingBeanNeedsSerializableImpl(this);
} else if (hasDecorators() && !allDecoratorsArePassivationCapable()) {
throw BeanLogger.LOG.passivatingBeanHasNonPassivationCapableDecorator(this, getFirstNonPassivationCapableDecorator());
} else if (hasInterceptors() && !allInterceptorsArePassivationCapable()) {
throw BeanLogger.LOG.passivatingBeanHasNonPassivationCapableInterceptor(this, getFirstNonPassivationCapableInterceptor());
}
}
} | java |
@SafeVarargs
public static <T> Set<T> of(T... elements) {
Preconditions.checkNotNull(elements);
return ImmutableSet.<T> builder().addAll(elements).build();
} | java |
Object readResolve() throws ObjectStreamException {
Bean<?> bean = Container.instance(contextId).services().get(ContextualStore.class).<Bean<Object>, Object>getContextual(beanId);
if (bean == null) {
throw BeanLogger.LOG.proxyDeserializationFailure(beanId);
}
return Container.instance(contextId).deploymentManager().getClientProxyProvider().getClientProxy(bean);
} | java |
@Override
protected String getToken() {
GetAccessTokenResult token = accessToken.get();
if (token == null || isExpired(token)
|| (isAboutToExpire(token) && refreshInProgress.compareAndSet(false, true))) {
lock.lock();
try {
token = accessToken.get();
if (token == null || isAboutToExpire(token)) {
token = accessTokenProvider.getNewAccessToken(oauthScopes);
accessToken.set(token);
cacheExpirationHeadroom.set(getNextCacheExpirationHeadroom());
}
} finally {
refreshInProgress.set(false);
lock.unlock();
}
}
return token.getAccessToken();
} | java |
private void waitForOutstandingRequest() throws IOException {
if (outstandingRequest == null) {
return;
}
try {
RetryHelper.runWithRetries(new Callable<Void>() {
@Override
public Void call() throws IOException, InterruptedException {
if (RetryHelper.getContext().getAttemptNumber() > 1) {
outstandingRequest.retry();
}
token = outstandingRequest.waitForNextToken();
outstandingRequest = null;
return null;
}
}, retryParams, GcsServiceImpl.exceptionHandler);
} catch (RetryInterruptedException ex) {
token = null;
throw new ClosedByInterruptException();
} catch (NonRetriableException e) {
Throwables.propagateIfInstanceOf(e.getCause(), IOException.class);
throw e;
}
} | java |
static Date parseDate(String dateString) {
try {
return DATE_FORMAT.parseDateTime(dateString).toDate();
} catch (IllegalArgumentException e) {
return null;
}
} | java |
@Override
public Future<RawGcsCreationToken> continueObjectCreationAsync(final RawGcsCreationToken token,
final ByteBuffer chunk, long timeoutMillis) {
try {
ensureInitialized();
} catch (IOException e) {
throw new RuntimeException(e);
}
final Environment environment = ApiProxy.getCurrentEnvironment();
return writePool.schedule(new Callable<RawGcsCreationToken>() {
@Override
public RawGcsCreationToken call() throws Exception {
ApiProxy.setEnvironmentForCurrentThread(environment);
return append(token, chunk);
}
}, 50, TimeUnit.MILLISECONDS);
} | java |
private void requestBlock() {
next = ByteBuffer.allocate(blockSizeBytes);
long requestTimeout = retryParams.getRequestTimeoutMillisForCurrentAttempt();
pendingFetch = raw.readObjectAsync(next, filename, fetchPosition, requestTimeout);
} | java |
GcsRestCreationToken handlePutResponse(final GcsRestCreationToken token,
final boolean isFinalChunk,
final int length,
final HTTPRequestInfo reqInfo,
HTTPResponse resp) throws Error, IOException {
switch (resp.getResponseCode()) {
case 200:
if (!isFinalChunk) {
throw new RuntimeException("Unexpected response code 200 on non-final chunk. Request: \n"
+ URLFetchUtils.describeRequestAndResponse(reqInfo, resp));
} else {
return null;
}
case 308:
if (isFinalChunk) {
throw new RuntimeException("Unexpected response code 308 on final chunk: "
+ URLFetchUtils.describeRequestAndResponse(reqInfo, resp));
} else {
return new GcsRestCreationToken(token.filename, token.uploadId, token.offset + length);
}
default:
throw HttpErrorHandler.error(resp.getResponseCode(),
URLFetchUtils.describeRequestAndResponse(reqInfo, resp));
}
} | java |
private RawGcsCreationToken put(final GcsRestCreationToken token, ByteBuffer chunk,
final boolean isFinalChunk, long timeoutMillis) throws IOException {
final int length = chunk.remaining();
HTTPRequest req = createPutRequest(token, chunk, isFinalChunk, timeoutMillis, length);
HTTPRequestInfo info = new HTTPRequestInfo(req);
HTTPResponse response;
try {
response = urlfetch.fetch(req);
} catch (IOException e) {
throw createIOException(info, e);
}
return handlePutResponse(token, isFinalChunk, length, info, response);
} | java |
@Override
public boolean deleteObject(GcsFilename filename, long timeoutMillis) throws IOException {
HTTPRequest req = makeRequest(filename, null, DELETE, timeoutMillis);
HTTPResponse resp;
try {
resp = urlfetch.fetch(req);
} catch (IOException e) {
throw createIOException(new HTTPRequestInfo(req), e);
}
switch (resp.getResponseCode()) {
case 204:
return true;
case 404:
return false;
default:
throw HttpErrorHandler.error(new HTTPRequestInfo(req), resp);
}
} | java |
@Override
public Future<GcsFileMetadata> readObjectAsync(final ByteBuffer dst, final GcsFilename filename,
long startOffsetBytes, long timeoutMillis) {
Preconditions.checkArgument(startOffsetBytes >= 0, "%s: offset must be non-negative: %s", this,
startOffsetBytes);
final int n = dst.remaining();
Preconditions.checkArgument(n > 0, "%s: dst full: %s", this, dst);
final int want = Math.min(READ_LIMIT_BYTES, n);
final HTTPRequest req = makeRequest(filename, null, GET, timeoutMillis);
req.setHeader(
new HTTPHeader(RANGE, "bytes=" + startOffsetBytes + "-" + (startOffsetBytes + want - 1)));
final HTTPRequestInfo info = new HTTPRequestInfo(req);
return new FutureWrapper<HTTPResponse, GcsFileMetadata>(urlfetch.fetchAsync(req)) {
@Override
protected GcsFileMetadata wrap(HTTPResponse resp) throws IOException {
long totalLength;
switch (resp.getResponseCode()) {
case 200:
totalLength = getLengthFromHeader(resp, X_GOOG_CONTENT_LENGTH);
break;
case 206:
totalLength = getLengthFromContentRange(resp);
break;
case 404:
throw new FileNotFoundException("Could not find: " + filename);
case 416:
throw new BadRangeException("Requested Range not satisfiable; perhaps read past EOF? "
+ URLFetchUtils.describeRequestAndResponse(info, resp));
default:
throw HttpErrorHandler.error(info, resp);
}
byte[] content = resp.getContent();
Preconditions.checkState(content.length <= want, "%s: got %s > wanted %s", this,
content.length, want);
dst.put(content);
return getMetadataFromResponse(filename, resp, totalLength);
}
@Override
protected Throwable convertException(Throwable e) {
return OauthRawGcsService.convertException(info, e);
}
};
} | java |
private void copy(InputStream input, OutputStream output) throws IOException {
try {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = input.read(buffer);
while (bytesRead != -1) {
output.write(buffer, 0, bytesRead);
bytesRead = input.read(buffer);
}
} finally {
input.close();
output.close();
}
} | java |
public Collection<Locale> getCountries() {
Collection<Locale> result = get(KEY_QUERY_COUNTRIES, Collection.class);
if (result == null) {
return Collections.emptySet();
}
return result;
} | java |
public Collection<String> getCurrencyCodes() {
Collection<String> result = get(KEY_QUERY_CURRENCY_CODES, Collection.class);
if (result == null) {
return Collections.emptySet();
}
return result;
} | java |
public Collection<Integer> getNumericCodes() {
Collection<Integer> result = get(KEY_QUERY_NUMERIC_CODES, Collection.class);
if (result == null) {
return Collections.emptySet();
}
return result;
} | java |
public Class<? extends MonetaryAmount> getAmountType() {
Class<?> clazz = get(AMOUNT_TYPE, Class.class);
return clazz.asSubclass(MonetaryAmount.class);
} | java |
@Override
public Set<String> getProviderNames() {
Set<String> result = new HashSet<>();
for (RoundingProviderSpi prov : Bootstrap.getServices(RoundingProviderSpi.class)) {
try {
result.add(prov.getProviderName());
} catch (Exception e) {
Logger.getLogger(Monetary.class.getName())
.log(Level.SEVERE, "Error loading RoundingProviderSpi from provider: " + prov, e);
}
}
return result;
} | java |
@Override
public List<String> getDefaultProviderChain() {
List<String> result = new ArrayList<>(Monetary.getRoundingProviderNames());
Collections.sort(result);
return result;
} | java |
@Override
public Set<String> getRoundingNames(String... providers) {
Set<String> result = new HashSet<>();
String[] providerNames = providers;
if (providerNames.length == 0) {
providerNames = Monetary.getDefaultRoundingProviderChain().toArray(new String[Monetary.getDefaultRoundingProviderChain().size()]);
}
for (String providerName : providerNames) {
for (RoundingProviderSpi prov : Bootstrap.getServices(RoundingProviderSpi.class)) {
try {
if (prov.getProviderName().equals(providerName) || prov.getProviderName().matches(providerName)) {
result.addAll(prov.getRoundingNames());
}
} catch (Exception e) {
Logger.getLogger(DefaultMonetaryRoundingsSingletonSpi.class.getName())
.log(Level.SEVERE, "Error loading RoundingProviderSpi from provider: " + prov, e);
}
}
}
return result;
} | java |
@SuppressWarnings("unchecked")
public Set<RateType> getRateTypes() {
Set<RateType> result = get(KEY_RATE_TYPES, Set.class);
if (result == null) {
return Collections.emptySet();
}
return result;
} | java |
public CurrencyQueryBuilder setCountries(Locale... countries) {
return set(CurrencyQuery.KEY_QUERY_COUNTRIES, Arrays.asList(countries));
} | java |
public CurrencyQueryBuilder setCurrencyCodes(String... codes) {
return set(CurrencyQuery.KEY_QUERY_CURRENCY_CODES, Arrays.asList(codes));
} | java |
public CurrencyQueryBuilder setNumericCodes(int... codes) {
return set(CurrencyQuery.KEY_QUERY_NUMERIC_CODES,
Arrays.stream(codes).boxed().collect(Collectors.toList()));
} | java |
public static List<String> getDefaultConversionProviderChain(){
List<String> defaultChain = getMonetaryConversionsSpi()
.getDefaultProviderChain();
Objects.requireNonNull(defaultChain, "No default provider chain provided by SPI: " +
getMonetaryConversionsSpi().getClass().getName());
return defaultChain;
} | java |
public Set<String> getKeys(Class<?> type) {
return data.entrySet().stream().filter(val -> type.isAssignableFrom(val.getValue()
.getClass())).map(Map.Entry::getKey).collect(Collectors
.toSet());
} | java |
public Class<?> getType(String key) {
Object val = this.data.get(key);
return val == null ? null : val.getClass();
} | java |
public <T> T get(String key, Class<T> type) {
Object value = this.data.get(key);
if (value != null && type.isAssignableFrom(value.getClass())) {
return (T) value;
}
return null;
} | java |
public <T> T get(Class<T> type) {
return get(type.getName(), type);
} | java |
@SuppressWarnings("unchecked")
public B setTargetType(Class<?> type) {
Objects.requireNonNull(type);
set(AbstractQuery.KEY_QUERY_TARGET_TYPE, type);
return (B) this;
} | java |
public Set<RateType> getRateTypes() {
@SuppressWarnings("unchecked")
Set<RateType> rateSet = get(KEY_RATE_TYPES, Set.class);
if (rateSet == null) {
return Collections.emptySet();
}
return Collections.unmodifiableSet(rateSet);
} | java |
private static MonetaryFormatsSingletonSpi loadMonetaryFormatsSingletonSpi() {
try {
return Optional.ofNullable(Bootstrap.getService(MonetaryFormatsSingletonSpi.class))
.orElseGet(DefaultMonetaryFormatsSingletonSpi::new);
} catch (Exception e) {
Logger.getLogger(MonetaryFormats.class.getName())
.log(Level.WARNING, "Failed to load MonetaryFormatsSingletonSpi, using default.", e);
return new DefaultMonetaryFormatsSingletonSpi();
}
} | java |
public static Collection<String> getFormatProviderNames() {
Collection<String> providers = Optional.ofNullable(getMonetaryFormatsSpi()).orElseThrow(
() -> new MonetaryException(
"No MonetaryFormatsSingletonSpi loaded, query functionality is not available."))
.getProviderNames();
if (Objects.isNull(providers)) {
Logger.getLogger(MonetaryFormats.class.getName()).warning(
"No supported rate/conversion providers returned by SPI: " +
getMonetaryFormatsSpi().getClass().getName());
return Collections.emptySet();
}
return providers;
} | java |
public ProviderContextBuilder setRateTypes(Collection<RateType> rateTypes) {
Objects.requireNonNull(rateTypes);
if (rateTypes.isEmpty()) {
throw new IllegalArgumentException("At least one RateType is required.");
}
Set<RateType> rtSet = new HashSet<>(rateTypes);
set(ProviderContext.KEY_RATE_TYPES, rtSet);
return this;
} | java |
public B importContext(AbstractContext context, boolean overwriteDuplicates){
for (Map.Entry<String, Object> en : context.data.entrySet()) {
if (overwriteDuplicates) {
this.data.put(en.getKey(), en.getValue());
}else{
this.data.putIfAbsent(en.getKey(), en.getValue());
}
}
return (B) this;
} | java |
public B importContext(AbstractContext context){
Objects.requireNonNull(context);
return importContext(context, false);
} | java |
public B set(String key, int value) {
this.data.put(key, value);
return (B) this;
} | java |
public static Set<String> getRoundingNames(String... providers) {
return Optional.ofNullable(monetaryRoundingsSingletonSpi()).orElseThrow(
() -> new MonetaryException("No MonetaryRoundingsSpi loaded, query functionality is not available."))
.getRoundingNames(providers);
} | java |
@SuppressWarnings("rawtypes")
public static MonetaryAmountFactory getAmountFactory(MonetaryAmountFactoryQuery query) {
return Optional.ofNullable(monetaryAmountsSingletonQuerySpi()).orElseThrow(() -> new MonetaryException(
"No MonetaryAmountsSingletonQuerySpi loaded, query functionality is not available."))
.getAmountFactory(query);
} | java |
public static Collection<MonetaryAmountFactory<?>> getAmountFactories(MonetaryAmountFactoryQuery query) {
return Optional.ofNullable(monetaryAmountsSingletonQuerySpi()).orElseThrow(() -> new MonetaryException(
"No MonetaryAmountsSingletonQuerySpi loaded, query functionality is not available."))
.getAmountFactories(query);
} | java |
public static Collection<CurrencyUnit> getCurrencies(String... providers) {
return Optional.ofNullable(MONETARY_CURRENCIES_SINGLETON_SPI()).orElseThrow(
() -> new MonetaryException("No MonetaryCurrenciesSingletonSpi loaded, check your system setup."))
.getCurrencies(providers);
} | java |
private PoolingHttpClientConnectionManager createConnectionMgr() {
PoolingHttpClientConnectionManager connectionMgr;
// prepare SSLContext
SSLContext sslContext = buildSslContext();
ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
// we allow to disable host name verification against CA certificate,
// notice: in general this is insecure and should be avoided in production,
// (this type of configuration is useful for development purposes)
boolean noHostVerification = false;
LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext,
noHostVerification ? NoopHostnameVerifier.INSTANCE : new DefaultHostnameVerifier()
);
Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", plainsf)
.register("https", sslsf)
.build();
connectionMgr = new PoolingHttpClientConnectionManager(r, null, null,
null, connectionPoolTimeToLive, TimeUnit.SECONDS);
connectionMgr.setMaxTotal(maxConnectionsTotal);
connectionMgr.setDefaultMaxPerRoute(maxConnectionsPerRoute);
HttpHost localhost = new HttpHost("localhost", 80);
connectionMgr.setMaxPerRoute(new HttpRoute(localhost), maxConnectionsPerRoute);
return connectionMgr;
} | java |
@Override
public ArtifactoryResponse restCall(ArtifactoryRequest artifactoryRequest) throws IOException {
HttpRequestBase httpRequest;
String requestPath = "/" + artifactoryRequest.getApiUrl();
ContentType contentType = Util.getContentType(artifactoryRequest.getRequestType());
String queryPath = "";
if (!artifactoryRequest.getQueryParams().isEmpty()) {
queryPath = Util.getQueryPath("?", artifactoryRequest.getQueryParams());
}
switch (artifactoryRequest.getMethod()) {
case GET:
httpRequest = new HttpGet();
break;
case POST:
httpRequest = new HttpPost();
setEntity((HttpPost)httpRequest, artifactoryRequest.getBody(), contentType);
break;
case PUT:
httpRequest = new HttpPut();
setEntity((HttpPut)httpRequest, artifactoryRequest.getBody(), contentType);
break;
case DELETE:
httpRequest = new HttpDelete();
break;
case PATCH:
httpRequest = new HttpPatch();
setEntity((HttpPatch)httpRequest, artifactoryRequest.getBody(), contentType);
break;
case OPTIONS:
httpRequest = new HttpOptions();
break;
default:
throw new IllegalArgumentException("Unsupported request method.");
}
httpRequest.setURI(URI.create(url + requestPath + queryPath));
addAccessTokenHeaderIfNeeded(httpRequest);
if (contentType != null) {
httpRequest.setHeader("Content-type", contentType.getMimeType());
}
Map<String, String> headers = artifactoryRequest.getHeaders();
for (String key : headers.keySet()) {
httpRequest.setHeader(key, headers.get(key));
}
HttpResponse httpResponse = httpClient.execute(httpRequest);
return new ArtifactoryResponseImpl(httpResponse);
} | java |
protected void createDocument() throws ParserConfigurationException
{
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
DocumentType doctype = builder.getDOMImplementation().createDocumentType("html", "-//W3C//DTD XHTML 1.1//EN", "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd");
doc = builder.getDOMImplementation().createDocument("http://www.w3.org/1999/xhtml", "html", doctype);
head = doc.createElement("head");
Element meta = doc.createElement("meta");
meta.setAttribute("http-equiv", "content-type");
meta.setAttribute("content", "text/html;charset=utf-8");
head.appendChild(meta);
title = doc.createElement("title");
title.setTextContent("PDF Document");
head.appendChild(title);
globalStyle = doc.createElement("style");
globalStyle.setAttribute("type", "text/css");
//globalStyle.setTextContent(createGlobalStyle());
head.appendChild(globalStyle);
body = doc.createElement("body");
Element root = doc.getDocumentElement();
root.appendChild(head);
root.appendChild(body);
} | java |
@Override
public void writeText(PDDocument doc, Writer outputStream) throws IOException
{
try
{
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl = (DOMImplementationLS)registry.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
LSOutput output = impl.createLSOutput();
writer.getDomConfig().setParameter("format-pretty-print", true);
output.setCharacterStream(outputStream);
createDOM(doc);
writer.write(getDocument(), output);
} catch (ClassCastException e) {
throw new IOException("Error: cannot initialize the DOM serializer", e);
} catch (ClassNotFoundException e) {
throw new IOException("Error: cannot initialize the DOM serializer", e);
} catch (InstantiationException e) {
throw new IOException("Error: cannot initialize the DOM serializer", e);
} catch (IllegalAccessException e) {
throw new IOException("Error: cannot initialize the DOM serializer", e);
}
} | java |
public Document createDOM(PDDocument doc) throws IOException
{
/* We call the original PDFTextStripper.writeText but nothing should
be printed actually because our processing methods produce no output.
They create the DOM structures instead */
super.writeText(doc, new OutputStreamWriter(System.out));
return this.doc;
} | java |
protected Element createPageElement()
{
String pstyle = "";
PDRectangle layout = getCurrentMediaBox();
if (layout != null)
{
/*System.out.println("x1 " + layout.getLowerLeftX());
System.out.println("y1 " + layout.getLowerLeftY());
System.out.println("x2 " + layout.getUpperRightX());
System.out.println("y2 " + layout.getUpperRightY());
System.out.println("rot " + pdpage.findRotation());*/
float w = layout.getWidth();
float h = layout.getHeight();
final int rot = pdpage.getRotation();
if (rot == 90 || rot == 270)
{
float x = w; w = h; h = x;
}
pstyle = "width:" + w + UNIT + ";" + "height:" + h + UNIT + ";";
pstyle += "overflow:hidden;";
}
else
log.warn("No media box found");
Element el = doc.createElement("div");
el.setAttribute("id", "page_" + (pagecnt++));
el.setAttribute("class", "page");
el.setAttribute("style", pstyle);
return el;
} | java |
protected Element createTextElement(float width)
{
Element el = doc.createElement("div");
el.setAttribute("id", "p" + (textcnt++));
el.setAttribute("class", "p");
String style = curstyle.toString();
style += "width:" + width + UNIT + ";";
el.setAttribute("style", style);
return el;
} | java |
protected Element createTextElement(String data, float width)
{
Element el = createTextElement(width);
Text text = doc.createTextNode(data);
el.appendChild(text);
return el;
} | java |
protected Element createRectangleElement(float x, float y, float width, float height, boolean stroke, boolean fill)
{
float lineWidth = transformWidth(getGraphicsState().getLineWidth());
float wcor = stroke ? lineWidth : 0.0f;
float strokeOffset = wcor == 0 ? 0 : wcor / 2;
width = width - wcor < 0 ? 1 : width - wcor;
height = height - wcor < 0 ? 1 : height - wcor;
StringBuilder pstyle = new StringBuilder(50);
pstyle.append("left:").append(style.formatLength(x - strokeOffset)).append(';');
pstyle.append("top:").append(style.formatLength(y - strokeOffset)).append(';');
pstyle.append("width:").append(style.formatLength(width)).append(';');
pstyle.append("height:").append(style.formatLength(height)).append(';');
if (stroke)
{
String color = colorString(getGraphicsState().getStrokingColor());
pstyle.append("border:").append(style.formatLength(lineWidth)).append(" solid ").append(color).append(';');
}
if (fill)
{
String fcolor = colorString(getGraphicsState().getNonStrokingColor());
pstyle.append("background-color:").append(fcolor).append(';');
}
Element el = doc.createElement("div");
el.setAttribute("class", "r");
el.setAttribute("style", pstyle.toString());
el.appendChild(doc.createEntityReference("nbsp"));
return el;
} | java |
protected Element createLineElement(float x1, float y1, float x2, float y2)
{
HtmlDivLine line = new HtmlDivLine(x1, y1, x2, y2);
String color = colorString(getGraphicsState().getStrokingColor());
StringBuilder pstyle = new StringBuilder(50);
pstyle.append("left:").append(style.formatLength(line.getLeft())).append(';');
pstyle.append("top:").append(style.formatLength(line.getTop())).append(';');
pstyle.append("width:").append(style.formatLength(line.getWidth())).append(';');
pstyle.append("height:").append(style.formatLength(line.getHeight())).append(';');
pstyle.append(line.getBorderSide()).append(':').append(style.formatLength(line.getLineStrokeWidth())).append(" solid ").append(color).append(';');
if (line.getAngleDegrees() != 0)
pstyle.append("transform:").append("rotate(").append(line.getAngleDegrees()).append("deg);");
Element el = doc.createElement("div");
el.setAttribute("class", "r");
el.setAttribute("style", pstyle.toString());
el.appendChild(doc.createEntityReference("nbsp"));
return el;
} | java |
protected Element createImageElement(float x, float y, float width, float height, ImageResource resource) throws IOException
{
StringBuilder pstyle = new StringBuilder("position:absolute;");
pstyle.append("left:").append(x).append(UNIT).append(';');
pstyle.append("top:").append(y).append(UNIT).append(';');
pstyle.append("width:").append(width).append(UNIT).append(';');
pstyle.append("height:").append(height).append(UNIT).append(';');
//pstyle.append("border:1px solid red;");
Element el = doc.createElement("img");
el.setAttribute("style", pstyle.toString());
String imgSrc = config.getImageHandler().handleResource(resource);
if (!disableImageData && !imgSrc.isEmpty())
el.setAttribute("src", imgSrc);
else
el.setAttribute("src", "");
return el;
} | java |
protected String createGlobalStyle()
{
StringBuilder ret = new StringBuilder();
ret.append(createFontFaces());
ret.append("\n");
ret.append(defaultStyle);
return ret.toString();
} | java |
public void createPdfLayout(Dimension dim)
{
if (pdfdocument != null) //processing a PDF document
{
try {
if (createImage)
img = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_RGB);
Graphics2D ig = img.createGraphics();
log.info("Creating PDF boxes");
VisualContext ctx = new VisualContext(null, null);
boxtree = new CSSBoxTree(ig, ctx, dim, baseurl);
boxtree.setConfig(config);
boxtree.processDocument(pdfdocument, startPage, endPage);
viewport = boxtree.getViewport();
root = boxtree.getDocument().getDocumentElement();
log.info("We have " + boxtree.getLastId() + " boxes");
viewport.initSubtree();
log.info("Layout for "+dim.width+"px");
viewport.doLayout(dim.width, true, true);
log.info("Resulting size: " + viewport.getWidth() + "x" + viewport.getHeight() + " (" + viewport + ")");
log.info("Updating viewport size");
viewport.updateBounds(dim);
log.info("Resulting size: " + viewport.getWidth() + "x" + viewport.getHeight() + " (" + viewport + ")");
if (createImage && (viewport.getWidth() > dim.width || viewport.getHeight() > dim.height))
{
img = new BufferedImage(Math.max(viewport.getWidth(), dim.width),
Math.max(viewport.getHeight(), dim.height),
BufferedImage.TYPE_INT_RGB);
ig = img.createGraphics();
}
log.info("Positioning for "+img.getWidth()+"x"+img.getHeight()+"px");
viewport.absolutePositions();
clearCanvas();
viewport.draw(new GraphicsRenderer(ig));
setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));
revalidate();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else if (root != null) //processing a DOM tree
{
super.createLayout(dim);
}
} | java |
protected BlockBox createBlock(BlockBox parent, Element n, boolean replaced)
{
BlockBox root;
if (replaced)
{
BlockReplacedBox rbox = new BlockReplacedBox((Element) n, (Graphics2D) parent.getGraphics().create(), parent.getVisualContext().create());
rbox.setViewport(viewport);
rbox.setContentObj(new ReplacedImage(rbox, rbox.getVisualContext(), baseurl, n.getAttribute("src")));
root = rbox;
}
else
{
root = new BlockBox((Element) n, (Graphics2D) parent.getGraphics().create(), parent.getVisualContext().create());
root.setViewport(viewport);
}
root.setBase(baseurl);
root.setParent(parent);
root.setContainingBlockBox(parent);
root.setClipBlock(viewport);
root.setOrder(next_order++);
return root;
} | java |
protected TextBox createTextBox(BlockBox contblock, Text n)
{
TextBox text = new TextBox(n, (Graphics2D) contblock.getGraphics().create(), contblock.getVisualContext().create());
text.setOrder(next_order++);
text.setContainingBlockBox(contblock);
text.setClipBlock(contblock);
text.setViewport(viewport);
text.setBase(baseurl);
return text;
} | java |
protected NodeData createBlockStyle()
{
NodeData ret = CSSFactory.createNodeData();
TermFactory tf = CSSFactory.getTermFactory();
ret.push(createDeclaration("display", tf.createIdent("block")));
return ret;
} | java |
protected NodeData createBodyStyle()
{
NodeData ret = createBlockStyle();
TermFactory tf = CSSFactory.getTermFactory();
ret.push(createDeclaration("background-color", tf.createColor(255, 255, 255)));
return ret;
} | java |
protected NodeData createPageStyle()
{
NodeData ret = createBlockStyle();
TermFactory tf = CSSFactory.getTermFactory();
ret.push(createDeclaration("position", tf.createIdent("relative")));
ret.push(createDeclaration("border-width", tf.createLength(1f, Unit.px)));
ret.push(createDeclaration("border-style", tf.createIdent("solid")));
ret.push(createDeclaration("border-color", tf.createColor(0, 0, 255)));
ret.push(createDeclaration("margin", tf.createLength(0.5f, Unit.em)));
PDRectangle layout = getCurrentMediaBox();
if (layout != null)
{
float w = layout.getWidth();
float h = layout.getHeight();
final int rot = pdpage.getRotation();
if (rot == 90 || rot == 270)
{
float x = w; w = h; h = x;
}
ret.push(createDeclaration("width", tf.createLength(w, unit)));
ret.push(createDeclaration("height", tf.createLength(h, unit)));
}
else
log.warn("No media box found");
return ret;
} | java |
protected NodeData createRectangleStyle(float x, float y, float width, float height, boolean stroke, boolean fill)
{
float lineWidth = transformLength((float) getGraphicsState().getLineWidth());
float lw = (lineWidth < 1f) ? 1f : lineWidth;
float wcor = stroke ? lw : 0.0f;
NodeData ret = CSSFactory.createNodeData();
TermFactory tf = CSSFactory.getTermFactory();
ret.push(createDeclaration("position", tf.createIdent("absolute")));
ret.push(createDeclaration("left", tf.createLength(x, unit)));
ret.push(createDeclaration("top", tf.createLength(y, unit)));
ret.push(createDeclaration("width", tf.createLength(width - wcor, unit)));
ret.push(createDeclaration("height", tf.createLength(height - wcor, unit)));
if (stroke)
{
ret.push(createDeclaration("border-width", tf.createLength(lw, unit)));
ret.push(createDeclaration("border-style", tf.createIdent("solid")));
String color = colorString(getGraphicsState().getStrokingColor());
ret.push(createDeclaration("border-color", tf.createColor(color)));
}
if (fill)
{
String color = colorString(getGraphicsState().getNonStrokingColor());
if (color != null)
ret.push(createDeclaration("background-color", tf.createColor(color)));
}
return ret;
} | java |
protected Declaration createDeclaration(String property, Term<?> term)
{
Declaration d = CSSFactory.getRuleFactory().createDeclaration();
d.unlock();
d.setProperty(property);
d.add(term);
return d;
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.