Search in sources :

Example 16 with Attribute

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

the class V2DottedNameSupport method getAllSubDottedNames.

protected void getAllSubDottedNames(String prefix, Dom parent, Map<Dom, String> result) {
    Set<String> elementNames = parent.getElementNames();
    for (String childName : elementNames) {
        // by default, it's a collection unless I can find the model for it
        // and ensure this is one or not.
        // not finding the model usually means that it was a "*" element therefore
        // a collection.
        boolean collection = true;
        if (parent.model.findIgnoreCase(childName) != null) {
            // if this is a leaf node, we should really treat it as an attribute.
            if (parent.model.getElement(childName).isLeaf())
                continue;
            collection = parent.model.getElement(childName).isCollection();
        }
        List<Dom> childNodes;
        synchronized (parent) {
            childNodes = parent.nodeElements(childName);
        }
        for (Dom child : childNodes) {
            StringBuilder newPrefix = new StringBuilder();
            if (prefix == null) {
                newPrefix.append(childName);
            } else {
                newPrefix.append(prefix).append(".").append(childName);
            }
            if (collection) {
                String name = child.getKey();
                if (name == null) {
                    name = child.attribute("name");
                }
                if (name != null) {
                    newPrefix.append(".").append(name);
                }
                // now traverse the child
                getAllSubDottedNames(newPrefix.toString(), child, result);
            } else {
                getAllSubDottedNames(newPrefix.toString(), child, result);
            }
        }
    }
    if (prefix != null) {
        result.put(parent, prefix);
    }
}
Also used : Dom(org.jvnet.hk2.config.Dom)

Example 17 with Attribute

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

the class Property method _isKey.

private boolean _isKey() {
    Element e = getAnnotation(Element.class);
    if (e != null && e.key())
        return true;
    Attribute a = getAnnotation(Attribute.class);
    return a != null && a.key();
}
Also used : Attribute(org.jvnet.hk2.config.Attribute) ExecutableElement(javax.lang.model.element.ExecutableElement) Element(org.jvnet.hk2.config.Element) VariableElement(javax.lang.model.element.VariableElement)

Example 18 with Attribute

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

the class WebContainer method createHttpListener.

protected WebConnector createHttpListener(NetworkListener listener, HttpService httpService, Mapper mapper) {
    if (!Boolean.valueOf(listener.getEnabled())) {
        return null;
    }
    int port = 8080;
    WebConnector connector;
    checkHostnameUniqueness(listener.getName(), httpService);
    try {
        port = Integer.parseInt(listener.getPort());
    } catch (NumberFormatException nfe) {
        String msg = rb.getString(LogFacade.HTTP_LISTENER_INVALID_PORT);
        msg = MessageFormat.format(msg, listener.getPort(), listener.getName());
        throw new IllegalArgumentException(msg);
    }
    if (mapper == null) {
        for (Mapper m : habitat.<Mapper>getAllServices(Mapper.class)) {
            if (m.getPort() == port && m instanceof ContextMapper) {
                ContextMapper cm = (ContextMapper) m;
                if (listener.getName().equals(cm.getId())) {
                    mapper = m;
                    break;
                }
            }
        }
    }
    String defaultVS = listener.findHttpProtocol().getHttp().getDefaultVirtualServer();
    if (!defaultVS.equals(org.glassfish.api.web.Constants.ADMIN_VS)) {
        // Before we start a WebConnector, let's makes sure there is
        // not another Container already listening on that port
        DataChunk host = DataChunk.newInstance();
        char[] c = defaultVS.toCharArray();
        host.setChars(c, 0, c.length);
        DataChunk mb = DataChunk.newInstance();
        mb.setChars(new char[] { '/' }, 0, 1);
        MappingData md = new MappingData();
        try {
            mapper.map(host, mb, md);
        } catch (Exception e) {
            if (logger.isLoggable(Level.FINE)) {
                logger.log(Level.FINE, "", e);
            }
        }
        if (md.context != null && md.context instanceof ContextRootInfo) {
            ContextRootInfo r = (ContextRootInfo) md.context;
            if (!(r.getHttpHandler() instanceof ContainerMapper)) {
                new BindException("Port " + port + " is already used by Container: " + r.getHttpHandler() + " and will not get started.").printStackTrace();
                return null;
            }
        }
    }
    /*
         * Create Connector. Connector is SSL-enabled if
         * 'security-enabled' attribute in <http-listener>
         * element is set to TRUE.
         */
    boolean isSecure = Boolean.valueOf(listener.findHttpProtocol().getSecurityEnabled());
    if (isSecure && defaultRedirectPort == -1) {
        defaultRedirectPort = port;
    }
    String address = listener.getAddress();
    if ("any".equals(address) || "ANY".equals(address) || "INADDR_ANY".equals(address)) {
        address = null;
    /*
             * Setting 'address' to NULL will cause Tomcat to pass a
             * NULL InetAddress argument to the java.net.ServerSocket
             * constructor, meaning that the server socket will accept
             * connections on any/all local addresses.
             */
    }
    connector = (WebConnector) _embedded.createConnector(address, port, isSecure);
    connector.setMapper(mapper);
    connector.setJvmRoute(engine.getJvmRoute());
    if (logger.isLoggable(Level.INFO)) {
        logger.log(Level.INFO, LogFacade.HTTP_LISTENER_CREATED, new Object[] { listener.getName(), listener.getAddress(), listener.getPort() });
    }
    connector.setDefaultHost(listener.findHttpProtocol().getHttp().getDefaultVirtualServer());
    connector.setName(listener.getName());
    connector.setInstanceName(instanceName);
    connector.configure(listener, isSecure, httpService);
    _embedded.addConnector(connector);
    connectorMap.put(listener.getName(), connector);
    // If we already know the redirect port, then set it now
    // This situation will occurs when dynamic reconfiguration occurs
    String redirectPort = listener.findHttpProtocol().getHttp().getRedirectPort();
    if (redirectPort != null) {
        connector.setRedirectPort(Integer.parseInt(redirectPort));
    } else if (defaultRedirectPort != -1) {
        connector.setRedirectPort(defaultRedirectPort);
    }
    ObservableBean httpListenerBean = (ObservableBean) ConfigSupport.getImpl(listener);
    httpListenerBean.addListener(configListener);
    return connector;
}
Also used : BindException(java.net.BindException) LifecycleException(org.apache.catalina.LifecycleException) NamingException(javax.naming.NamingException) BindException(java.net.BindException) MalformedURLException(java.net.MalformedURLException) ContextRootInfo(org.glassfish.grizzly.config.ContextRootInfo) Mapper(org.glassfish.grizzly.http.server.util.Mapper) ContextMapper(org.glassfish.internal.grizzly.ContextMapper) ContainerMapper(com.sun.enterprise.v3.services.impl.ContainerMapper) MappingData(org.glassfish.grizzly.http.server.util.MappingData) DataChunk(org.glassfish.grizzly.http.util.DataChunk) ObservableBean(org.jvnet.hk2.config.ObservableBean) ContextMapper(org.glassfish.internal.grizzly.ContextMapper) ContainerMapper(com.sun.enterprise.v3.services.impl.ContainerMapper)

Example 19 with Attribute

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

the class SetLogAttributes method execute.

@Override
public void execute(AdminCommandContext context) {
    final ActionReport report = context.getActionReport();
    StringBuilder sbfSuccessMsg = new StringBuilder(LINE_SEP);
    boolean success = false;
    boolean invalidAttribute = false;
    Map<String, String> m = new HashMap<String, String>();
    try {
        for (final Object key : properties.keySet()) {
            final String att_name = (String) key;
            final String att_value = (String) properties.get(att_name);
            // that is is a valid level
            if (validate) {
                boolean vlAttribute = false;
                for (String attrName : validAttributes) {
                    if (attrName.equals(att_name)) {
                        try {
                            validateAttributeValue(att_name, att_value);
                        } catch (Exception e) {
                            // Add in additional error message information if present
                            if (e.getMessage() != null) {
                                report.setMessage(e.getMessage() + "\n");
                            }
                            break;
                        }
                        m.put(att_name, att_value);
                        vlAttribute = true;
                        sbfSuccessMsg.append(localStrings.getLocalString("set.log.attribute.properties", "{0} logging attribute set with value {1}.", att_name, att_value)).append(LINE_SEP);
                    }
                }
                if (!vlAttribute) {
                    report.appendMessage(localStrings.getLocalString("set.log.attribute.invalid", "Invalid logging attribute name {0} or value {1}.", att_name, att_value));
                    invalidAttribute = true;
                    break;
                }
            } else {
                m.put(att_name, att_value);
                sbfSuccessMsg.append(localStrings.getLocalString("set.log.attribute.properties", "{0} logging attribute set with value {1}.", att_name, att_value)).append(LINE_SEP);
            }
        }
        if (invalidAttribute) {
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        }
        TargetInfo targetInfo = new TargetInfo(domain, target);
        String targetConfigName = targetInfo.getConfigName();
        boolean isDas = targetInfo.isDas();
        if (targetConfigName != null && !targetConfigName.isEmpty()) {
            loggingConfig.updateLoggingProperties(m, targetConfigName);
            success = true;
        } else if (isDas) {
            loggingConfig.updateLoggingProperties(m);
            success = true;
        }
        if (success) {
            // do not record duplicate logging attribute restart events
            boolean triggerRestart = true;
            unprocessedLoop: for (UnprocessedChangeEvents evts : ucl.getUnprocessedChangeEvents()) {
                for (UnprocessedChangeEvent evt : evts.getUnprocessed()) {
                    if (evt.getEvent().getSource().getClass().getName().equals(this.getClass().getName())) {
                        triggerRestart = false;
                        break unprocessedLoop;
                    }
                }
            }
            if (triggerRestart) {
                List<UnprocessedChangeEvents> logAttrChanges = new ArrayList<>();
                logAttrChanges.add(new UnprocessedChangeEvents(new UnprocessedChangeEvent(new PropertyChangeEvent(this, "Logging Attribute", null, null), "logging attribute(s) modified")));
                ucl.unprocessedTransactedEvents(logAttrChanges);
            }
            String effectiveTarget = (isDas ? SystemPropertyConstants.DAS_SERVER_NAME : targetConfigName);
            sbfSuccessMsg.append(localStrings.getLocalString("set.log.attribute.success", "These logging attributes are set for {0}.", effectiveTarget)).append(LINE_SEP);
            report.setMessage(sbfSuccessMsg.toString());
            report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
        } else {
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            String msg = localStrings.getLocalString("invalid.target.sys.props", "Invalid target: {0}. Valid default target is a server named ''server'' (default) or cluster name.", target);
            report.setMessage(msg);
            return;
        }
    } catch (IOException e) {
        report.setMessage(localStrings.getLocalString("set.log.attribute.failed", "Could not set logging attributes for {0}.", target));
        report.setActionExitCode(ActionReport.ExitCode.FAILURE);
    }
}
Also used : UnprocessedChangeEvents(org.jvnet.hk2.config.UnprocessedChangeEvents) PropertyChangeEvent(java.beans.PropertyChangeEvent) HashMap(java.util.HashMap) UnprocessedChangeEvent(org.jvnet.hk2.config.UnprocessedChangeEvent) ArrayList(java.util.ArrayList) IOException(java.io.IOException) ActionReport(org.glassfish.api.ActionReport) IOException(java.io.IOException)

Example 20 with Attribute

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

the class WriteableView method commit.

/**
 * Commit this Transaction.
 *
 * @param t the transaction commiting.
 * @throws TransactionFailure
 *          if the transaction commit failed
 */
public synchronized List<PropertyChangeEvent> commit(Transaction t) throws TransactionFailure {
    if (currentTx == t) {
        currentTx = null;
    }
    // a key attribute must be non-null and have length >= 1
    final ConfigBean master = getMasterView();
    final String keyStr = master.model.key;
    if (keyStr != null) {
        final String key = stripMarkers(keyStr);
        final String value = getPropertyValue(key);
        if (value == null) {
            throw new TransactionFailure("Key value cannot be null: " + key);
        }
        if (value.length() == 0) {
            throw new TransactionFailure("Key value cannot be empty string: " + key);
        }
    }
    try {
        List<PropertyChangeEvent> appliedChanges = new ArrayList<PropertyChangeEvent>();
        for (PropertyChangeEvent event : changedAttributes.values()) {
            ConfigModel.Property property = bean.model.findIgnoreCase(event.getPropertyName());
            ConfigBeanInterceptor interceptor = bean.getOptionalFeature(ConfigBeanInterceptor.class);
            try {
                if (interceptor != null) {
                    interceptor.beforeChange(event);
                }
            } catch (PropertyVetoException e) {
                throw new TransactionFailure(e.getMessage(), e);
            }
            property.set(bean, event.getNewValue());
            if (interceptor != null) {
                interceptor.afterChange(event, System.currentTimeMillis());
            }
            appliedChanges.add(event);
        }
        for (ProtectedList entry : changedCollections.values()) {
            List<Object> originalList = entry.readOnly;
            for (PropertyChangeEvent event : entry.changeEvents) {
                if (event.getOldValue() == null) {
                    originalList.add(event.getNewValue());
                } else {
                    final Object toBeRemovedObj = event.getOldValue();
                    if (toBeRemovedObj instanceof ConfigBeanProxy) {
                        final Dom toBeRemoved = Dom.unwrap((ConfigBeanProxy) toBeRemovedObj);
                        for (int index = 0; index < originalList.size(); index++) {
                            Object element = originalList.get(index);
                            Dom dom = Dom.unwrap((ConfigBeanProxy) element);
                            if (dom == toBeRemoved) {
                                Object newValue = event.getNewValue();
                                if (newValue == null) {
                                    originalList.remove(index);
                                } else {
                                    originalList.set(index, newValue);
                                }
                            }
                        }
                    } else if (toBeRemovedObj instanceof String) {
                        final String toBeRemoved = (String) toBeRemovedObj;
                        for (int index = 0; index < originalList.size(); index++) {
                            final String item = (String) originalList.get(index);
                            if (item.equals(toBeRemoved)) {
                                originalList.remove(index);
                            }
                        }
                    } else {
                        throw new IllegalArgumentException();
                    }
                }
                appliedChanges.add(event);
            }
        }
        changedAttributes.clear();
        changedCollections.clear();
        return appliedChanges;
    } catch (TransactionFailure e) {
        throw e;
    } catch (Exception e) {
        throw new TransactionFailure(e.getMessage(), e);
    } finally {
        bean.getLock().unlock();
    }
}
Also used : PropertyChangeEvent(java.beans.PropertyChangeEvent) PropertyVetoException(java.beans.PropertyVetoException) PropertyVetoException(java.beans.PropertyVetoException) Property(org.jvnet.hk2.config.ConfigModel.Property)

Aggregations

Attribute (org.jvnet.hk2.config.Attribute)11 TransactionFailure (org.jvnet.hk2.config.TransactionFailure)7 Method (java.lang.reflect.Method)6 ArrayList (java.util.ArrayList)6 PropertyChangeEvent (java.beans.PropertyChangeEvent)5 HashMap (java.util.HashMap)5 MultiException (org.glassfish.hk2.api.MultiException)5 ConfigBeanProxy (org.jvnet.hk2.config.ConfigBeanProxy)5 Map (java.util.Map)4 Dom (org.jvnet.hk2.config.Dom)4 Property (org.jvnet.hk2.config.types.Property)4 Cluster (com.sun.enterprise.config.serverbeans.Cluster)3 SystemProperty (com.sun.enterprise.config.serverbeans.SystemProperty)3 PropertyVetoException (java.beans.PropertyVetoException)3 List (java.util.List)3 Param (org.glassfish.api.Param)3 ParameterMap (org.glassfish.api.admin.ParameterMap)3 Domain (com.sun.enterprise.config.serverbeans.Domain)2 MonitoringService (com.sun.enterprise.config.serverbeans.MonitoringService)2 Server (com.sun.enterprise.config.serverbeans.Server)2