Search in sources :

Example 11 with MultiException

use of org.glassfish.hk2.api.MultiException in project docker-client by spotify.

the class DefaultDockerClient method propagate.

private RuntimeException propagate(final String method, final WebTarget resource, final Exception ex) throws DockerException, InterruptedException {
    Throwable cause = ex.getCause();
    // So we unpack it here.
    if (ex instanceof MultiException) {
        cause = cause.getCause();
    }
    Response response = null;
    if (cause instanceof ResponseProcessingException) {
        response = ((ResponseProcessingException) cause).getResponse();
    } else if (cause instanceof WebApplicationException) {
        response = ((WebApplicationException) cause).getResponse();
    } else if ((cause instanceof ProcessingException) && (cause.getCause() != null)) {
        // For a ProcessingException, The exception message or nested Throwable cause SHOULD contain
        // additional information about the reason of the processing failure.
        cause = cause.getCause();
    }
    if (response != null) {
        throw new DockerRequestException(method, resource.getUri(), response.getStatus(), message(response), cause);
    } else if ((cause instanceof SocketTimeoutException) || (cause instanceof ConnectTimeoutException)) {
        throw new DockerTimeoutException(method, resource.getUri(), ex);
    } else if ((cause instanceof InterruptedIOException) || (cause instanceof InterruptedException)) {
        throw new InterruptedException("Interrupted: " + method + " " + resource);
    } else {
        throw new DockerException(ex);
    }
}
Also used : DockerException(com.spotify.docker.client.exceptions.DockerException) InterruptedIOException(java.io.InterruptedIOException) WebApplicationException(javax.ws.rs.WebApplicationException) DockerRequestException(com.spotify.docker.client.exceptions.DockerRequestException) DockerTimeoutException(com.spotify.docker.client.exceptions.DockerTimeoutException) ConfigCreateResponse(com.spotify.docker.client.messages.swarm.ConfigCreateResponse) Response(javax.ws.rs.core.Response) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) SecretCreateResponse(com.spotify.docker.client.messages.swarm.SecretCreateResponse) ServiceCreateResponse(com.spotify.docker.client.messages.ServiceCreateResponse) SocketTimeoutException(java.net.SocketTimeoutException) ResponseProcessingException(javax.ws.rs.client.ResponseProcessingException) MultiException(org.glassfish.hk2.api.MultiException) ProcessingException(javax.ws.rs.ProcessingException) ResponseProcessingException(javax.ws.rs.client.ResponseProcessingException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 12 with MultiException

use of org.glassfish.hk2.api.MultiException in project Payara by payara.

the class OpenAPISupplier method getServerURL.

private List<URL> getServerURL(String contextRoot) {
    List<URL> result = new ArrayList<>();
    ServerContext context = Globals.get(ServerContext.class);
    String hostName;
    try {
        hostName = InetAddress.getLocalHost().getCanonicalHostName();
    } catch (UnknownHostException ex) {
        hostName = "localhost";
    }
    String instanceType = Globals.get(ServerEnvironment.class).getRuntimeType().toString();
    List<Integer> httpPorts = new ArrayList<>();
    List<Integer> httpsPorts = new ArrayList<>();
    List<NetworkListener> networkListeners = context.getConfigBean().getConfig().getNetworkConfig().getNetworkListeners().getNetworkListener();
    String adminListener = context.getConfigBean().getConfig().getAdminListener().getName();
    networkListeners.stream().filter(networkListener -> Boolean.parseBoolean(networkListener.getEnabled())).forEach(networkListener -> {
        int port;
        try {
            // get the dynamic config port
            port = Globals.get(GrizzlyService.class).getRealPort(networkListener);
        } catch (MultiException ex) {
            // get the port in the domain xml
            port = Integer.parseInt(networkListener.getPort());
        }
        // Check if this listener is using HTTP or HTTPS
        boolean securityEnabled = Boolean.parseBoolean(networkListener.findProtocol().getSecurityEnabled());
        List<Integer> ports = securityEnabled ? httpsPorts : httpPorts;
        // If this listener isn't the admin listener, it must be an HTTP/HTTPS listener
        if (!networkListener.getName().equals(adminListener)) {
            ports.add(port);
        } else if (instanceType.equals("MICRO")) {
            // micro instances can use the admin listener as both an admin and HTTP/HTTPS port
            ports.add(port);
        }
    });
    for (Integer httpPort : httpPorts) {
        try {
            result.add(new URL("http", hostName, httpPort, contextRoot));
        } catch (MalformedURLException ex) {
        // ignore
        }
    }
    for (Integer httpsPort : httpsPorts) {
        try {
            result.add(new URL("https", hostName, httpsPort, contextRoot));
        } catch (MalformedURLException ex) {
        // ignore
        }
    }
    return result;
}
Also used : StructuredDeploymentTracing(org.glassfish.internal.deployment.analysis.StructuredDeploymentTracing) OpenApiConfiguration(fish.payara.microprofile.openapi.impl.config.OpenApiConfiguration) ConfigPropertyProcessor(fish.payara.microprofile.openapi.impl.processor.ConfigPropertyProcessor) Enumeration(java.util.Enumeration) Globals(org.glassfish.internal.api.Globals) URL(java.net.URL) ApplicationProcessor(fish.payara.microprofile.openapi.impl.processor.ApplicationProcessor) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) InetAddress(java.net.InetAddress) HashSet(java.util.HashSet) ReadableArchive(org.glassfish.api.deployment.archive.ReadableArchive) ServerEnvironment(org.glassfish.api.admin.ServerEnvironment) FileProcessor(fish.payara.microprofile.openapi.impl.processor.FileProcessor) NetworkListener(org.glassfish.grizzly.config.dom.NetworkListener) Collectors.toSet(java.util.stream.Collectors.toSet) Types(org.glassfish.hk2.classmodel.reflect.Types) MalformedURLException(java.net.MalformedURLException) ApplicationLifecycle(com.sun.enterprise.v3.server.ApplicationLifecycle) Set(java.util.Set) IOException(java.io.IOException) OpenAPIImpl(fish.payara.microprofile.openapi.impl.model.OpenAPIImpl) Logger(java.util.logging.Logger) UnknownHostException(java.net.UnknownHostException) Parser(org.glassfish.hk2.classmodel.reflect.Parser) Objects(java.util.Objects) OpenAPI(org.eclipse.microprofile.openapi.models.OpenAPI) ServerContext(org.glassfish.internal.api.ServerContext) List(java.util.List) FilterProcessor(fish.payara.microprofile.openapi.impl.processor.FilterProcessor) GrizzlyService(com.sun.enterprise.v3.services.impl.GrizzlyService) MultiException(org.glassfish.hk2.api.MultiException) BaseProcessor(fish.payara.microprofile.openapi.impl.processor.BaseProcessor) ModelReaderProcessor(fish.payara.microprofile.openapi.impl.processor.ModelReaderProcessor) Collections(java.util.Collections) Type(org.glassfish.hk2.classmodel.reflect.Type) MalformedURLException(java.net.MalformedURLException) UnknownHostException(java.net.UnknownHostException) ArrayList(java.util.ArrayList) URL(java.net.URL) ServerContext(org.glassfish.internal.api.ServerContext) MultiException(org.glassfish.hk2.api.MultiException) NetworkListener(org.glassfish.grizzly.config.dom.NetworkListener)

Example 13 with MultiException

use of org.glassfish.hk2.api.MultiException in project Payara by payara.

the class ConfigSupport method revealProxy.

/**
 * Unwrap HK2 proxy to ConfigBeanProxy.
 * @param ConfigBeanProxy probably proxied by HK2.
 * @return actual ConfigBeanProxy.
 * @throws MultiException If there was an error resolving the proxy.
 */
@SuppressWarnings("unchecked")
public static <T extends ConfigBeanProxy> T revealProxy(T proxy) {
    if (proxy instanceof ProxyCtl) {
        ProxyCtl proxyCtl = (ProxyCtl) proxy;
        proxy = (T) proxyCtl.__make();
    }
    return proxy;
}
Also used : ProxyCtl(org.glassfish.hk2.api.ProxyCtl)

Example 14 with MultiException

use of org.glassfish.hk2.api.MultiException in project Payara by payara.

the class GenericCrudCommand method getInjectionResolver.

public InjectionResolver<Param> getInjectionResolver() {
    final InjectionResolver<Param> delegate = injector;
    return new InjectionResolver<Param>(Param.class) {

        @Override
        public <V> V getValue(Object component, AnnotatedElement annotated, Type genericType, Class<V> type) throws MultiException {
            if (type.isAssignableFrom(List.class)) {
                final List<ConfigBeanProxy> values;
                try {
                    if (annotated instanceof Method) {
                        values = (List<ConfigBeanProxy>) ((Method) annotated).invoke(component);
                    } else if (annotated instanceof Field) {
                        values = (List<ConfigBeanProxy>) ((Field) annotated).get(component);
                    } else {
                        String msg = LOCAL_STRINGS.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.invalid_type", "Invalid annotated type {0} passed to InjectionResolver:getValue()", annotated.getClass().toString());
                        LOGGER.log(Level.SEVERE, ConfigApiLoggerInfo.INVALID_ANNO_TYPE, annotated.getClass().toString());
                        throw new MultiException(new IllegalArgumentException(msg));
                    }
                } catch (IllegalAccessException | InvocationTargetException e) {
                    String msg = LOCAL_STRINGS.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.invocation_failure", "Failure {0} while getting List<?> values from component", e.getMessage());
                    LOGGER.log(Level.SEVERE, ConfigApiLoggerInfo.INVOKE_FAILURE);
                    throw new MultiException(new IllegalStateException(msg, e));
                }
                Object value = delegate.getValue(component, annotated, genericType, type);
                if (value == null) {
                    LOGGER.log(level, "Value of {0} is null", annotated);
                    return null;
                }
                Type genericReturnType = null;
                if (annotated instanceof Method) {
                    genericReturnType = ((Method) annotated).getGenericReturnType();
                } else if (annotated instanceof Field) {
                    genericReturnType = ((Field) annotated).getGenericType();
                }
                if (genericReturnType == null) {
                    throw new MultiException(new IllegalArgumentException("Cannot determine parametized type from " + annotated));
                }
                final Class<? extends ConfigBeanProxy> itemType = Types.erasure(Types.getTypeArgument(genericReturnType, 0));
                if (LOGGER.isLoggable(level)) {
                    LOGGER.log(level, "Found that List<?> really is a List<{0}>", itemType);
                }
                if (itemType == null) {
                    String msg = LOCAL_STRINGS.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.nongeneric_type", "The List type returned by {0} must be a generic type", annotated.toString());
                    LOGGER.log(Level.SEVERE, ConfigApiLoggerInfo.LIST_NOT_GENERIC_TYPE, annotated.toString());
                    throw new MultiException(new IllegalArgumentException(msg));
                }
                if (!ConfigBeanProxy.class.isAssignableFrom(itemType)) {
                    String msg = LOCAL_STRINGS.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.wrong_type", "The generic type {0} is not supported, only List<? extends ConfigBeanProxy> is", annotated.toString());
                    LOGGER.log(Level.SEVERE, ConfigApiLoggerInfo.GENERIC_TYPE_NOT_SUPPORTED, annotated.toString());
                    throw new MultiException(new IllegalArgumentException(msg));
                }
                Properties props = convertStringToProperties(value.toString(), ':');
                if (LOGGER.isLoggable(level)) {
                    for (Map.Entry<Object, Object> entry : props.entrySet()) {
                        LOGGER.log(level, "Subtype {0} key:{1} value:{2}", new Object[] { itemType, entry.getKey(), entry.getValue() });
                    }
                }
                final BeanInfo beanInfo;
                try {
                    beanInfo = Introspector.getBeanInfo(itemType);
                } catch (IntrospectionException e) {
                    String msg = LOCAL_STRINGS.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.introspection_failure", "Failure {0} while instrospecting {1} to find all getters and setters", e.getMessage(), itemType.getName());
                    LogHelper.log(LOGGER, Level.SEVERE, ConfigApiLoggerInfo.INTROSPECTION_FAILED, e, itemType.getName());
                    throw new MultiException(new IllegalStateException(msg, e));
                }
                for (final Map.Entry<Object, Object> entry : props.entrySet()) {
                    ConfigBeanProxy child = (ConfigBeanProxy) component;
                    try {
                        ConfigBeanProxy cc = child.createChild(itemType);
                        new InjectionManager().inject(cc, itemType, new InjectionResolver<Attribute>(Attribute.class) {

                            @Override
                            public boolean isOptional(AnnotatedElement annotated, Attribute annotation) {
                                return true;
                            }

                            @Override
                            public Method getSetterMethod(Method annotated, Attribute annotation) {
                                // variant.
                                for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
                                    if (pd.getReadMethod().equals(annotated)) {
                                        return pd.getWriteMethod();
                                    }
                                }
                                return annotated;
                            }

                            @Override
                            public <V> V getValue(Object component, AnnotatedElement annotated, Type genericType, Class<V> type) throws MultiException {
                                String name = annotated.getAnnotation(Attribute.class).value();
                                if ((name == null || name.length() == 0) && annotated instanceof Method) {
                                    // maybe there is a better way to do this...
                                    name = ((Method) annotated).getName().substring(3);
                                    if (name.equalsIgnoreCase("name") || name.equalsIgnoreCase("key")) {
                                        return type.cast(entry.getKey());
                                    }
                                    if (name.equalsIgnoreCase("value")) {
                                        return type.cast(entry.getValue());
                                    }
                                }
                                return null;
                            }
                        });
                        values.add(cc);
                    } catch (TransactionFailure transactionFailure) {
                        String msg = LOCAL_STRINGS.getLocalString(GenericCrudCommand.class, "GenericCrudCommand.transactionException", "Transaction exception {0} while injecting {1}", transactionFailure.getMessage(), itemType);
                        LogHelper.log(LOGGER, Level.SEVERE, ConfigApiLoggerInfo.TX_FAILED, transactionFailure, itemType);
                        throw new MultiException(new IllegalStateException(msg, transactionFailure));
                    }
                }
                return null;
            }
            return delegate.getValue(component, annotated, genericType, type);
        }

        @Override
        public boolean isOptional(AnnotatedElement annotated, Param annotation) {
            return annotation.optional();
        }
    };
}
Also used : TransactionFailure(org.jvnet.hk2.config.TransactionFailure) Attribute(org.jvnet.hk2.config.Attribute) BeanInfo(java.beans.BeanInfo) AnnotatedElement(java.lang.reflect.AnnotatedElement) IntrospectionException(java.beans.IntrospectionException) Properties(java.util.Properties) Field(java.lang.reflect.Field) ConfigBeanProxy(org.jvnet.hk2.config.ConfigBeanProxy) List(java.util.List) PropertyDescriptor(java.beans.PropertyDescriptor) GenerateServiceFromMethod(org.jvnet.hk2.config.GenerateServiceFromMethod) Method(java.lang.reflect.Method) InjectionResolver(org.jvnet.hk2.config.InjectionResolver) InvocationTargetException(java.lang.reflect.InvocationTargetException) Type(java.lang.reflect.Type) Param(org.glassfish.api.Param) MultiException(org.glassfish.hk2.api.MultiException) Map(java.util.Map) InjectionManager(org.jvnet.hk2.config.InjectionManager)

Example 15 with MultiException

use of org.glassfish.hk2.api.MultiException in project Payara by payara.

the class CommandResourceMetaData method getRestRedirectPointToBean.

@SuppressWarnings("unchecked")
public static List<CommandResourceMetaData> getRestRedirectPointToBean(String beanName) {
    synchronized (restRedirects) {
        if (restRedirects.isEmpty()) {
            final ServiceLocator habitat = Globals.getDefaultHabitat();
            processConfigBeans(habitat);
            List<ActiveDescriptor<?>> iter = habitat.getDescriptors(BuilderHelper.createContractFilter(AdminCommand.class.getName()));
            for (ActiveDescriptor<?> ad : iter) {
                if (!(ad.getQualifiers().contains(RestEndpoints.class.getName()))) {
                    continue;
                }
                if (!ad.isReified()) {
                    try {
                        habitat.reifyDescriptor(ad);
                    } catch (MultiException me) {
                        // If we can't see the command, forget it
                        continue;
                    }
                }
                final Class<? extends AdminCommand> clazz = (Class<? extends AdminCommand>) ad.getImplementationClass();
                RestEndpoints endpoints = clazz.getAnnotation(RestEndpoints.class);
                if (endpoints != null) {
                    RestEndpoint[] list = endpoints.value();
                    if ((list != null) && (list.length > 0)) {
                        for (RestEndpoint endpoint : list) {
                            Service service = clazz.getAnnotation(Service.class);
                            String configBean = endpoint.configBean().getSimpleName();
                            CommandResourceMetaData metaData = new CommandResourceMetaData();
                            metaData.command = service.name();
                            metaData.httpMethod = endpoint.opType().name();
                            metaData.resourcePath = endpoint.path().isEmpty() ? service.name() : endpoint.path();
                            metaData.displayName = endpoint.description().isEmpty() ? metaData.resourcePath : endpoint.description();
                            metaData.commandParams = new ParameterMetaData[endpoint.params().length];
                            int index = 0;
                            for (RestParam param : endpoint.params()) {
                                ParameterMetaData currentParam = new ParameterMetaData();
                                metaData.commandParams[index] = currentParam;
                                currentParam.name = param.name();
                                currentParam.value = param.value();
                                index++;
                            }
                            addCommandMetaData(configBean, metaData);
                        }
                    }
                }
            }
        }
    }
    return restRedirects.get(beanName);
}
Also used : ActiveDescriptor(org.glassfish.hk2.api.ActiveDescriptor) Service(org.jvnet.hk2.annotations.Service) RestEndpoints(org.glassfish.api.admin.RestEndpoints) RestEndpoint(org.glassfish.api.admin.RestEndpoint) RestEndpoint(org.glassfish.api.admin.RestEndpoint) RestParam(org.glassfish.api.admin.RestParam) ServiceLocator(org.glassfish.hk2.api.ServiceLocator) AdminCommand(org.glassfish.api.admin.AdminCommand) MultiException(org.glassfish.hk2.api.MultiException)

Aggregations

MultiException (org.glassfish.hk2.api.MultiException)20 IOException (java.io.IOException)5 Method (java.lang.reflect.Method)5 Param (org.glassfish.api.Param)3 RemoteCLICommand (com.sun.enterprise.admin.cli.remote.RemoteCLICommand)2 GrizzlyService (com.sun.enterprise.v3.services.impl.GrizzlyService)2 MalformedURLException (java.net.MalformedURLException)2 List (java.util.List)2 LogRecord (java.util.logging.LogRecord)2 MethodMetaData (org.glassfish.admin.rest.provider.MethodMetaData)2 ParameterMetaData (org.glassfish.admin.rest.provider.ParameterMetaData)2 ActionReport (org.glassfish.api.ActionReport)2 CommandModelImpl (org.glassfish.common.util.admin.CommandModelImpl)2 Attribute (org.jvnet.hk2.config.Attribute)2 ConfigModel (org.jvnet.hk2.config.ConfigModel)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 GraphHopper (com.graphhopper.GraphHopper)1 GraphHopperConfig (com.graphhopper.GraphHopperConfig)1 GraphHopperHealthCheck (com.graphhopper.http.health.GraphHopperHealthCheck)1 JTSTriangulator (com.graphhopper.isochrone.algorithm.JTSTriangulator)1