Search in sources :

Example 6 with Element

use of org.jvnet.hk2.config.Element in project Payara by payara.

the class GMSAdapterImpl method generateDiscoveryUriList.

/*
     * Get existing nodes based on cluster element in domain.
     * Then check for DAS address in das.properties. When the
     * list is set to 'generate' then the gms listener port
     * must also be specified. So the same port is used for
     * each cluster member.
     */
private String generateDiscoveryUriList() {
    String clusterPort = null;
    Property gmsPortProp = cluster.getProperty("GMS_LISTENER_PORT");
    if (gmsPortProp == null || gmsPortProp.getValue() == null || gmsPortProp.getValue().trim().charAt(0) == '$') {
        clusterPort = "9090";
        GMS_LOGGER.log(LogLevel.WARNING, GMS_LISTENER_PORT_REQUIRED, new Object[] { cluster.getName(), clusterPort });
    } else {
        clusterPort = gmsPortProp.getValue();
        if (GMS_LOGGER.isLoggable(LogLevel.FINE)) {
            GMS_LOGGER.log(LogLevel.FINE, "will use gms listener port: " + clusterPort);
        }
    }
    // get cluster member server refs
    Set<String> instanceNames = new HashSet<String>();
    if (GMS_LOGGER.isLoggable(LogLevel.FINE)) {
        GMS_LOGGER.log(LogLevel.FINE, String.format("checking cluster.getServerRef() for '%s'", cluster.getName()));
    }
    for (ServerRef sRef : cluster.getServerRef()) {
        /*
             * When an instance (not DAS) starts up, it will add
             * its own address to the discovery list. This is ok
             * now. If we want to skip it, here's the place to
             * check.
             */
        if (GMS_LOGGER.isLoggable(LogLevel.FINE)) {
            GMS_LOGGER.log(LogLevel.FINE, String.format("adding server ref %s to set of instance names", sRef.getRef()));
        }
        instanceNames.add(sRef.getRef());
    }
    StringBuilder sb = new StringBuilder();
    final String SEP = ",";
    final String scheme = "tcp://";
    // use server refs to find matching nodes
    for (String name : instanceNames) {
        Server server = servers.getServer(name);
        if (server != null) {
            if (GMS_LOGGER.isLoggable(LogLevel.FINE)) {
                GMS_LOGGER.log(LogLevel.FINE, String.format("found server for name %s", name));
            }
            Node node = nodes.getNode(server.getNodeRef());
            if (node != null) {
                String host = scheme + node.getNodeHost() + ":" + clusterPort;
                if (GMS_LOGGER.isLoggable(LogLevel.FINE)) {
                    GMS_LOGGER.log(LogLevel.FINE, String.format("Adding host '%s' to discovery list", host));
                }
                sb.append(host).append(SEP);
            }
        }
    }
    // add das location from das.properties if needed
    if (server.isInstance()) {
        try {
            ServerDirs sDirs = new ServerDirs(env.getInstanceRoot());
            File dasPropsFile = sDirs.getDasPropertiesFile();
            if (GMS_LOGGER.isLoggable(LogLevel.FINE)) {
                GMS_LOGGER.log(LogLevel.FINE, String.format("found das.props file at %s", dasPropsFile.getAbsolutePath()));
            }
            Properties dasProps = getProperties(dasPropsFile);
            String host = scheme + dasProps.getProperty("agent.das.host") + ":" + clusterPort;
            if (GMS_LOGGER.isLoggable(LogLevel.FINE)) {
                GMS_LOGGER.log(LogLevel.FINE, String.format("adding '%s' from das.props file", host));
            }
            sb.append(host).append(SEP);
        } catch (IOException ioe) {
            GMS_LOGGER.log(LogLevel.WARNING, ioe.toString());
        }
    }
    // trim list if needed and return
    int lastCommaIndex = sb.lastIndexOf(SEP);
    if (lastCommaIndex != -1) {
        sb.deleteCharAt(lastCommaIndex);
    }
    if (GMS_LOGGER.isLoggable(LogLevel.FINE)) {
        GMS_LOGGER.log(LogLevel.FINE, String.format("returning discovery list '%s'", sb.toString()));
    }
    return sb.toString();
}
Also used : Server(com.sun.enterprise.config.serverbeans.Server) Node(com.sun.enterprise.config.serverbeans.Node) IOException(java.io.IOException) Properties(java.util.Properties) ServerDirs(com.sun.enterprise.util.io.ServerDirs) Property(org.jvnet.hk2.config.types.Property) ServerRef(com.sun.enterprise.config.serverbeans.ServerRef) File(java.io.File) HashSet(java.util.HashSet)

Example 7 with Element

use of org.jvnet.hk2.config.Element in project Payara by payara.

the class ActionReportResultHtmlProvider method getContent.

@Override
public String getContent(ActionReportResult proxy) {
    RestActionReporter ar = (RestActionReporter) proxy.getActionReport();
    StringBuilder result = new StringBuilder(ProviderUtil.getHtmlHeader(getBaseUri()));
    final String message = ResourceUtil.encodeString(ar.getCombinedMessage());
    if (!message.isEmpty()) {
        result.append("<h3>").append(message).append("</h3>");
    }
    if (proxy.isError()) {
        result.append("<h2>").append(ar.getActionDescription()).append(" Error:</h2>").append(proxy.getErrorMessage());
    } else {
        final Map<String, String> childResources = (Map<String, String>) ar.getExtraProperties().get("childResources");
        final List<Map<String, String>> commands = (List<Map<String, String>>) ar.getExtraProperties().get("commands");
        final MethodMetaData postMetaData = proxy.getMetaData().getMethodMetaData("POST");
        final MethodMetaData deleteMetaData = proxy.getMetaData().getMethodMetaData("DELETE");
        final MethodMetaData getMetaData = proxy.getMetaData().getMethodMetaData("GET");
        final ConfigBean entity = proxy.getEntity();
        if ((proxy.getCommandDisplayName() != null) && (getMetaData != null)) {
            // for commands, we want the output of the command before the form
            if (entity == null) {
                // show extra properties only for non entity pages
                result.append(processReport(ar));
            }
        }
        if ((postMetaData != null) && (entity == null)) {
            String postCommand = getHtmlRespresentationsForCommand(postMetaData, "POST", (proxy.getCommandDisplayName() == null) ? "Create" : proxy.getCommandDisplayName(), uriInfo.get());
            result.append(getHtmlForComponent(postCommand, "Create " + ar.getActionDescription(), ""));
        }
        if ((deleteMetaData != null) && (entity == null)) {
            String deleteCommand = getHtmlRespresentationsForCommand(deleteMetaData, "DELETE", (proxy.getCommandDisplayName() == null) ? "Delete" : proxy.getCommandDisplayName(), uriInfo.get());
            result.append(getHtmlForComponent(deleteCommand, "Delete " + ar.getActionDescription(), ""));
        }
        if ((getMetaData != null) && (entity == null) && (proxy.getCommandDisplayName() != null)) {
            String getCommand = getHtmlRespresentationsForCommand(getMetaData, "GET", (proxy.getCommandDisplayName() == null) ? "Get" : proxy.getCommandDisplayName(), uriInfo.get());
            result.append(getHtmlForComponent(getCommand, "Get " + ar.getActionDescription(), ""));
        }
        if (entity != null) {
            String attributes = ProviderUtil.getHtmlRepresentationForAttributes(proxy.getEntity(), uriInfo.get());
            result.append(ProviderUtil.getHtmlForComponent(attributes, ar.getActionDescription() + " Attributes", ""));
            String deleteCommand = ProviderUtil.getHtmlRespresentationsForCommand(proxy.getMetaData().getMethodMetaData("DELETE"), "DELETE", (proxy.getCommandDisplayName() == null) ? "Delete" : proxy.getCommandDisplayName(), uriInfo.get());
            result.append(ProviderUtil.getHtmlForComponent(deleteCommand, "Delete " + entity.model.getTagName(), ""));
        } else if (proxy.getLeafContent() != null) {
            // it is a single leaf @Element
            String content = "<form action=\"" + uriInfo.get().getAbsolutePath().toString() + "\" method=\"post\">" + "<dl><dt>" + "<label for=\"" + proxy.getLeafContent().name + "\">" + proxy.getLeafContent().name + ":&nbsp;</label>" + "</dt><dd>" + "<input name=\"" + proxy.getLeafContent().name + "\" value =\"" + proxy.getLeafContent().value + "\" type=\"text\" >" + "</dd><dt class=\"button\"></dt><dd class=\"button\"><input value=\"Update\" type=\"submit\"></dd></dl>" + "</form><br><hr class=\"separator\"/";
            result.append(content);
        } else {
            // This is a monitoring result!!!
            final Map vals = (Map) ar.getExtraProperties().get("entity");
            if ((vals != null) && (!vals.isEmpty())) {
                result.append("<ul>");
                for (Map.Entry entry : (Set<Map.Entry>) vals.entrySet()) {
                    Object object = entry.getValue();
                    if (object == null) {
                    // do nothing
                    } else if (object instanceof Collection) {
                        if (!((Collection) object).isEmpty()) {
                            Collection c = ((Collection) object);
                            Iterator i = c.iterator();
                            result.append("<li>").append(entry.getKey());
                            result.append("<ul>");
                            while (i.hasNext()) {
                                result.append("<li>").append(getHtmlRepresentation(i.next())).append("</li>");
                            }
                            result.append("</ul>");
                            result.append("</li>");
                        }
                    } else if (object instanceof Map) {
                        if (!((Map) object).isEmpty()) {
                            Map m = (Map) object;
                            if (vals.size() != 1) {
                                // add a link if more than 1 child
                                result.append("<li>").append("<a href=\"" + uriInfo.get().getAbsolutePath().toString() + "/" + entry.getKey() + "\">" + entry.getKey() + "</a>");
                            } else {
                                result.append("<li>").append(entry.getKey());
                            }
                            result.append("<ul>");
                            for (Map.Entry anEntry : (Set<Map.Entry>) m.entrySet()) {
                                final String htmlRepresentation = getHtmlRepresentation(anEntry.getValue());
                                if (htmlRepresentation != null) {
                                    result.append("<li>").append(anEntry.getKey()).append(" : ").append(htmlRepresentation).append("</li>");
                                }
                            }
                            result.append("</ul>");
                            result.append("</li>");
                        }
                    } else {
                        result.append("<li>").append(entry.getKey()).append(" : ").append(object.toString()).append("</li>");
                    }
                }
                result.append("</ul>");
            } else {
                // no values to show... give an hint
                if ((childResources == null) || (childResources.isEmpty())) {
                    if ((uriInfo != null) && (uriInfo.get().getPath().equalsIgnoreCase("domain"))) {
                        result.append(getHint(uriInfo.get(), MediaType.TEXT_HTML));
                    }
                }
            }
        }
        if ((childResources != null) && (!childResources.isEmpty())) {
            String childResourceLinks = getResourcesLinks(childResources);
            result.append(ProviderUtil.getHtmlForComponent(childResourceLinks, "Child Resources", ""));
        }
        if ((commands != null) && (!commands.isEmpty())) {
            String commandLinks = getCommandLinks(commands);
            result.append(ProviderUtil.getHtmlForComponent(commandLinks, "Commands", ""));
        }
    }
    return result.append("</div></body></html>").toString();
}
Also used : ConfigBean(org.jvnet.hk2.config.ConfigBean) RestActionReporter(org.glassfish.admin.rest.utils.xml.RestActionReporter) Iterator(java.util.Iterator) Collection(java.util.Collection) List(java.util.List) Map(java.util.Map)

Example 8 with Element

use of org.jvnet.hk2.config.Element in project Payara by payara.

the class BaseProvider method getResourceLinks.

protected Map<String, String> getResourceLinks(List<Dom> proxyList) {
    Map<String, String> links = new TreeMap<String, String>();
    Collections.sort(proxyList, new DomConfigurator());
    for (Dom proxy : proxyList) {
        // for each element
        try {
            links.put(proxy.getKey(), getElementLink(uriInfo.get(), proxy.getKey()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    return links;
}
Also used : Dom(org.jvnet.hk2.config.Dom) DomConfigurator(org.glassfish.admin.rest.utils.DomConfigurator) TreeMap(java.util.TreeMap) IOException(java.io.IOException) WebApplicationException(javax.ws.rs.WebApplicationException)

Example 9 with Element

use of org.jvnet.hk2.config.Element in project Payara by payara.

the class BaseProvider method getResourceLinks.

protected Map<String, String> getResourceLinks(Dom dom) {
    Map<String, String> links = new TreeMap<String, String>();
    Set<String> elementNames = dom.model.getElementNames();
    for (String elementName : elementNames) {
        // for each element
        if (elementName.equals("*")) {
            ConfigModel.Node node = (ConfigModel.Node) dom.model.getElement(elementName);
            ConfigModel childModel = node.getModel();
            List<ConfigModel> lcm = ResourceUtil.getRealChildConfigModels(childModel, dom.document);
            Collections.sort(lcm, new ConfigModelComparator());
            if (lcm != null) {
                Collections.sort(lcm, new ConfigModelComparator());
                for (ConfigModel cmodel : lcm) {
                    links.put(cmodel.getTagName(), ProviderUtil.getElementLink(uriInfo.get(), cmodel.getTagName()));
                }
            }
        } else {
            links.put(elementName, ProviderUtil.getElementLink(uriInfo.get(), elementName));
        }
    }
    return links;
}
Also used : ConfigModel(org.jvnet.hk2.config.ConfigModel) ConfigModelComparator(org.glassfish.admin.rest.utils.ConfigModelComparator) TreeMap(java.util.TreeMap)

Example 10 with Element

use of org.jvnet.hk2.config.Element in project Payara by payara.

the class WebServiceReferenceManagerImpl method resolveWSReference.

public Object resolveWSReference(ServiceReferenceDescriptor desc, Context context) throws NamingException {
    // Taken from NamingManagerImpl.getClientServiceObject
    Class serviceInterfaceClass = null;
    Object returnObj = null;
    WsUtil wsUtil = new WsUtil();
    // Implementation for new lookup element in WebserviceRef
    InitialContext iContext = new InitialContext();
    if (desc.hasLookupName()) {
        return iContext.lookup(desc.getLookupName());
    }
    try {
        WSContainerResolver.set(desc);
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        serviceInterfaceClass = cl.loadClass(desc.getServiceInterface());
        resolvePortComponentLinks(desc);
        javax.xml.rpc.Service serviceDelegate = null;
        javax.xml.ws.Service jaxwsDelegate = null;
        Object injValue = null;
        if (desc.hasGeneratedServiceInterface() || desc.hasWsdlFile()) {
            String serviceImplName = desc.getServiceImplClassName();
            if (serviceImplName != null) {
                Class serviceImplClass = cl.loadClass(serviceImplName);
                serviceDelegate = (javax.xml.rpc.Service) serviceImplClass.newInstance();
            } else {
                // as the interface through DD
                if (javax.xml.ws.Service.class.isAssignableFrom(serviceInterfaceClass) && !javax.xml.ws.Service.class.equals(serviceInterfaceClass)) {
                    // OK - the interface class is indeed the generated service class; get an instance
                    injValue = initiateInstance(serviceInterfaceClass, desc);
                } else {
                    // interface, therefore I take the first one.
                    if (desc.isInjectable()) {
                        InjectionTarget target = desc.getInjectionTargets().iterator().next();
                        Class serviceType = null;
                        if (target.isFieldInjectable()) {
                            java.lang.reflect.Field f = target.getField();
                            if (f == null) {
                                String fName = target.getFieldName();
                                Class targetClass = cl.loadClass(target.getClassName());
                                try {
                                    f = targetClass.getDeclaredField(fName);
                                }// ignoring exception
                                 catch (java.lang.NoSuchFieldException nsfe) {
                                }
                            }
                            if (f != null) {
                                serviceType = f.getType();
                            }
                        }
                        if (target.isMethodInjectable()) {
                            Method m = target.getMethod();
                            if (m == null) {
                                String mName = target.getMethodName();
                                Class targetClass = cl.loadClass(target.getClassName());
                                try {
                                    m = targetClass.getDeclaredMethod(mName);
                                }// ignoring exception
                                 catch (java.lang.NoSuchMethodException nsfe) {
                                }
                            }
                            if (m != null && m.getParameterTypes().length == 1) {
                                serviceType = m.getParameterTypes()[0];
                            }
                        }
                        if (serviceType != null) {
                            Class loadedSvcClass = cl.loadClass(serviceType.getCanonicalName());
                            injValue = initiateInstance(loadedSvcClass, desc);
                        }
                    }
                }
                // Unable to get hold of generated service class -> try the Service.create avenue to get a Service
                if (injValue == null) {
                    // Here create the service with WSDL (overridden wsdl if wsdl-override is present)
                    // so that JAXWS runtime uses this wsdl @ runtime
                    javax.xml.ws.Service svc = javax.xml.ws.Service.create((new WsUtil()).privilegedGetServiceRefWsdl(desc), desc.getServiceName());
                    jaxwsDelegate = new JAXWSServiceDelegate(desc, svc, cl);
                }
            }
            if (desc.hasHandlers()) {
                // We need the service's ports to configure the
                // handler chain (since service-ref handler chain can
                // optionally specify handler-port association)
                // so create a configured service and call getPorts
                javax.xml.rpc.Service configuredService = wsUtil.createConfiguredService(desc);
                Iterator ports = configuredService.getPorts();
                wsUtil.configureHandlerChain(desc, serviceDelegate, ports, cl);
            }
            // check if this is a post 1.1 web service
            if (javax.xml.ws.Service.class.isAssignableFrom(serviceInterfaceClass)) {
                // This is a JAXWS based webservice client;
                // process handlers and mtom setting
                // moved test for handlers into wsUtil, in case
                // we have to add system handler
                javax.xml.ws.Service service = (injValue != null ? (javax.xml.ws.Service) injValue : jaxwsDelegate);
                if (service != null) {
                    // Now configure client side handlers
                    wsUtil.configureJAXWSClientHandlers(service, desc);
                }
                // the requested resource is not the service but one of its port.
                if (injValue != null && desc.getInjectionTargetType() != null) {
                    Class requestedPortType = service.getClass().getClassLoader().loadClass(desc.getInjectionTargetType());
                    ArrayList<WebServiceFeature> wsFeatures = getWebServiceFeatures(desc);
                    if (wsFeatures.size() > 0) {
                        injValue = service.getPort(requestedPortType, wsFeatures.toArray(new WebServiceFeature[wsFeatures.size()]));
                    } else {
                        injValue = service.getPort(requestedPortType);
                    }
                }
            }
        } else {
            // Generic service interface / no WSDL
            QName serviceName = desc.getServiceName();
            if (serviceName == null) {
                // ServiceFactory API requires a service-name.
                // However, 109 does not allow getServiceName() to be
                // called, so it's ok to use a dummy value.
                serviceName = new QName("urn:noservice", "servicename");
            }
            ServiceFactory serviceFac = ServiceFactory.newInstance();
            serviceDelegate = serviceFac.createService(serviceName);
        }
        // Create a proxy for the service object.
        // Get a proxy only in jaxrpc case because in jaxws the service class is not
        // an interface any more
        InvocationHandler handler = null;
        if (serviceDelegate != null) {
            handler = new ServiceInvocationHandler(desc, serviceDelegate, cl);
            returnObj = Proxy.newProxyInstance(cl, new Class[] { serviceInterfaceClass }, handler);
        } else if (jaxwsDelegate != null) {
            returnObj = jaxwsDelegate;
        } else if (injValue != null) {
            returnObj = injValue;
        }
    } catch (PrivilegedActionException pae) {
        logger.log(Level.WARNING, LogUtils.EXCEPTION_THROWN, pae);
        NamingException ne = new NamingException();
        ne.initCause(pae.getCause());
        throw ne;
    } catch (Exception e) {
        logger.log(Level.WARNING, LogUtils.EXCEPTION_THROWN, e);
        NamingException ne = new NamingException();
        ne.initCause(e);
        throw ne;
    } finally {
        WSContainerResolver.unset();
    }
    return returnObj;
}
Also used : ServiceFactory(javax.xml.rpc.ServiceFactory) java.lang.reflect(java.lang.reflect) Iterator(java.util.Iterator) NamingException(javax.naming.NamingException) PrivilegedActionException(java.security.PrivilegedActionException) QName(javax.xml.namespace.QName) Service(org.jvnet.hk2.annotations.Service) InitialContext(javax.naming.InitialContext) NamingException(javax.naming.NamingException) PrivilegedActionException(java.security.PrivilegedActionException) WebServiceException(javax.xml.ws.WebServiceException) WebServiceFeature(javax.xml.ws.WebServiceFeature)

Aggregations

Property (org.jvnet.hk2.config.types.Property)14 PropertyVetoException (java.beans.PropertyVetoException)13 TransactionFailure (org.jvnet.hk2.config.TransactionFailure)13 IOException (java.io.IOException)8 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)4 List (java.util.List)4 TreeMap (java.util.TreeMap)4 ActionReport (org.glassfish.api.ActionReport)4 MultiException (org.glassfish.hk2.api.MultiException)4 ExtendedDeploymentContext (org.glassfish.internal.deployment.ExtendedDeploymentContext)4 ConfigModel (org.jvnet.hk2.config.ConfigModel)4 Dom (org.jvnet.hk2.config.Dom)4 Application (com.sun.enterprise.config.serverbeans.Application)3 Domain (com.sun.enterprise.config.serverbeans.Domain)3 Server (com.sun.enterprise.config.serverbeans.Server)3 SystemProperty (com.sun.enterprise.config.serverbeans.SystemProperty)3 File (java.io.File)3 HashSet (java.util.HashSet)3 Iterator (java.util.Iterator)3