Search in sources :

Example 1 with Strings

use of io.fabric8.utils.Strings in project fabric8 by jboss-fuse.

the class ServerInvokerImpl method onCommand.

protected void onCommand(final Transport transport, Object data) {
    try {
        final DataByteArrayInputStream bais = new DataByteArrayInputStream((Buffer) data);
        final int size = bais.readInt();
        final long correlation = bais.readVarLong();
        // Use UTF8Buffer instead of string to avoid encoding/decoding UTF-8 strings
        // for every request.
        final UTF8Buffer service = readBuffer(bais).utf8();
        final Buffer encoded_method = readBuffer(bais);
        final ServiceFactoryHolder holder = holders.get(service);
        final MethodData methodData = holder.getMethodData(encoded_method);
        final Object svc = holder.factory.get();
        Runnable task = new Runnable() {

            public void run() {
                final DataByteArrayOutputStream baos = new DataByteArrayOutputStream();
                try {
                    // make space for the size field.
                    baos.writeInt(0);
                    baos.writeVarLong(correlation);
                } catch (IOException e) {
                    // should not happen
                    throw new RuntimeException(e);
                }
                // Lets decode the remaining args on the target's executor
                // to take cpu load off the
                methodData.invocationStrategy.service(methodData.serializationStrategy, holder.loader, methodData.method, svc, bais, baos, new Runnable() {

                    public void run() {
                        holder.factory.unget();
                        final Buffer command = baos.toBuffer();
                        // Update the size field.
                        BufferEditor editor = command.buffer().bigEndianEditor();
                        editor.writeInt(command.length);
                        queue().execute(new Runnable() {

                            public void run() {
                                transport.offer(command);
                            }
                        });
                    }
                });
            }
        };
        Executor executor;
        if (svc instanceof Dispatched) {
            executor = ((Dispatched) svc).queue();
        } else {
            executor = blockingExecutor;
        }
        executor.execute(task);
    } catch (Exception e) {
        LOGGER.info("Error while reading request", e);
    }
}
Also used : IOException(java.io.IOException) IOException(java.io.IOException) EOFException(java.io.EOFException) Dispatched(io.fabric8.dosgi.api.Dispatched) Executor(java.util.concurrent.Executor)

Example 2 with Strings

use of io.fabric8.utils.Strings in project fabric8 by jboss-fuse.

the class ServiceFactoryTest method testDiscoveryOnRestartCurator.

@Test
public void testDiscoveryOnRestartCurator() throws Exception {
    underTest = new ActiveMQServiceFactory();
    underTest.curator = curator;
    Properties props = new Properties();
    props.put("config", "amq.xml");
    props.put("broker-name", "amq");
    props.put("group", "amq");
    props.put("connectors", "openwire");
    props.put("openwire-port", "0");
    props.put("container.ip", "localhost");
    underTest.updated("b", props);
    final AtomicReference<CuratorFramework> curatorFrameworkAtomicReference = new AtomicReference<>(curator);
    OsgiFabricDiscoveryAgent osgiFabricDiscoveryAgent = new OsgiFabricDiscoveryAgent(new BundleContext() {

        @Override
        public String getProperty(String s) {
            return null;
        }

        @Override
        public Bundle getBundle() {
            return null;
        }

        @Override
        public Bundle installBundle(String s, InputStream inputStream) throws BundleException {
            return null;
        }

        @Override
        public Bundle installBundle(String s) throws BundleException {
            return null;
        }

        @Override
        public Bundle getBundle(long l) {
            return null;
        }

        @Override
        public Bundle[] getBundles() {
            return new Bundle[0];
        }

        @Override
        public void addServiceListener(ServiceListener serviceListener, String s) throws InvalidSyntaxException {
        }

        @Override
        public void addServiceListener(ServiceListener serviceListener) {
        }

        @Override
        public void removeServiceListener(ServiceListener serviceListener) {
        }

        @Override
        public void addBundleListener(BundleListener bundleListener) {
        }

        @Override
        public void removeBundleListener(BundleListener bundleListener) {
        }

        @Override
        public void addFrameworkListener(FrameworkListener frameworkListener) {
        }

        @Override
        public void removeFrameworkListener(FrameworkListener frameworkListener) {
        }

        @Override
        public ServiceRegistration<?> registerService(String[] strings, Object o, Dictionary<String, ?> dictionary) {
            return null;
        }

        @Override
        public ServiceRegistration<?> registerService(String s, Object o, Dictionary<String, ?> dictionary) {
            return null;
        }

        @Override
        public <S> ServiceRegistration<S> registerService(Class<S> aClass, S s, Dictionary<String, ?> dictionary) {
            return null;
        }

        @Override
        public ServiceReference<?>[] getServiceReferences(String s, String s1) throws InvalidSyntaxException {
            return new ServiceReference<?>[0];
        }

        @Override
        public ServiceReference<?>[] getAllServiceReferences(String s, String s1) throws InvalidSyntaxException {
            return new ServiceReference<?>[0];
        }

        @Override
        public ServiceReference<?> getServiceReference(String s) {
            return null;
        }

        @Override
        public <S> ServiceReference<S> getServiceReference(Class<S> aClass) {
            return null;
        }

        @Override
        public <S> Collection<ServiceReference<S>> getServiceReferences(Class<S> aClass, String s) throws InvalidSyntaxException {
            return null;
        }

        @Override
        public <S> S getService(ServiceReference<S> serviceReference) {
            return (S) curatorFrameworkAtomicReference.get();
        }

        @Override
        public boolean ungetService(ServiceReference<?> serviceReference) {
            return false;
        }

        @Override
        public File getDataFile(String s) {
            return null;
        }

        @Override
        public Filter createFilter(String s) throws InvalidSyntaxException {
            return null;
        }

        @Override
        public Bundle getBundle(String s) {
            return null;
        }
    });
    final LinkedBlockingQueue<DiscoveryEvent> discoveryEvents = new LinkedBlockingQueue<DiscoveryEvent>(10);
    osgiFabricDiscoveryAgent.setDiscoveryListener(new DiscoveryListener() {

        @Override
        public void onServiceAdd(DiscoveryEvent discoveryEvent) {
            discoveryEvents.offer(discoveryEvent);
        }

        @Override
        public void onServiceRemove(DiscoveryEvent discoveryEvent) {
        }
    });
    // will call into dummy bundle and get curator
    osgiFabricDiscoveryAgent.addingService(null);
    osgiFabricDiscoveryAgent.setGroupName("amq");
    osgiFabricDiscoveryAgent.start();
    DiscoveryEvent event = discoveryEvents.poll(5, TimeUnit.SECONDS);
    LOG.info("event: " + event);
    assertNotNull("got added service", event);
    underTest.deleted("b");
    // swap curator ref
    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder().connectString("localhost:" + zkPort).sessionTimeoutMs(15000).retryPolicy(new RetryNTimes(5000, 1000));
    curator = builder.build();
    LOG.debug("Starting new curator " + curator);
    curator.start();
    curatorFrameworkAtomicReference.get().close();
    curatorFrameworkAtomicReference.set(curator);
    // will call into dummy bundle and get new curator ref
    osgiFabricDiscoveryAgent.addingService(null);
    // start broker again
    underTest.curator = curator;
    underTest.updated("b", props);
    event = discoveryEvents.poll(5, TimeUnit.SECONDS);
    LOG.info("new event: " + event);
    assertNotNull("got newly added service", event);
    underTest.deleted("b");
}
Also used : CuratorFrameworkFactory(org.apache.curator.framework.CuratorFrameworkFactory) DiscoveryEvent(org.apache.activemq.command.DiscoveryEvent) Properties(java.util.Properties) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) CuratorFramework(org.apache.curator.framework.CuratorFramework) RetryNTimes(org.apache.curator.retry.RetryNTimes) InputStream(java.io.InputStream) AtomicReference(java.util.concurrent.atomic.AtomicReference) OsgiFabricDiscoveryAgent(io.fabric8.mq.fabric.discovery.OsgiFabricDiscoveryAgent) Collection(java.util.Collection) File(java.io.File) DiscoveryListener(org.apache.activemq.transport.discovery.DiscoveryListener) Test(org.junit.Test)

Example 3 with Strings

use of io.fabric8.utils.Strings in project fabric8 by fabric8io.

the class Templates method processTemplatesLocally.

/**
 * Lets locally process the templates so that we can process templates on any kubernetes environment
 */
public static KubernetesList processTemplatesLocally(Template entity, boolean failOnMissingParameterValue) throws IOException {
    List<HasMetadata> objects = null;
    if (entity != null) {
        objects = entity.getObjects();
        if (objects == null || objects.isEmpty()) {
            return null;
        }
    }
    List<Parameter> parameters = entity != null ? entity.getParameters() : null;
    if (parameters != null && !parameters.isEmpty()) {
        String json = "{\"kind\": \"List\", \"apiVersion\": \"" + KubernetesHelper.defaultApiVersion + "\",\n" + "  \"items\": " + KubernetesHelper.toJson(objects) + " }";
        // lets make a few passes in case there's expressions in values
        for (int i = 0; i < 5; i++) {
            for (Parameter parameter : parameters) {
                String name = parameter.getName();
                String regex = "${" + name + "}";
                String value = parameter.getValue();
                // TODO generate random strings for passwords etc!
                if (Strings.isNullOrBlank(value)) {
                    if (failOnMissingParameterValue) {
                        throw new IllegalArgumentException("No value available for parameter name: " + name);
                    } else {
                        value = "";
                    }
                }
                json = Strings.replaceAllWithoutRegex(json, regex, value);
            }
        }
        return OBJECT_MAPPER.readerFor(KubernetesList.class).readValue(json);
    } else {
        KubernetesList answer = new KubernetesList();
        answer.setItems(objects);
        return answer;
    }
}
Also used : HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) Parameter(io.fabric8.openshift.api.model.Parameter) KubernetesList(io.fabric8.kubernetes.api.model.KubernetesList)

Example 4 with Strings

use of io.fabric8.utils.Strings in project docker-maven-plugin by fabric8io.

the class DockerComposeServiceWrapper method getNetworkConfig.

NetworkConfig getNetworkConfig() {
    String net = asString("network_mode");
    if (net != null) {
        return new NetworkConfig(net);
    }
    Object networks = asObject("networks");
    if (networks == null) {
        return null;
    }
    if (networks instanceof List) {
        List<String> toJoin = (List<String>) networks;
        if (toJoin.size() > 1) {
            throwIllegalArgumentException("'networks:' Only one custom network to join is supported currently");
        }
        return new NetworkConfig(NetworkConfig.Mode.custom, toJoin.get(0));
    } else if (networks instanceof Map) {
        Map<String, Object> toJoin = (Map<String, Object>) networks;
        if (toJoin.size() > 1) {
            throwIllegalArgumentException("'networks:' Only one custom network to join is supported currently");
        }
        String custom = toJoin.keySet().iterator().next();
        NetworkConfig ret = new NetworkConfig(NetworkConfig.Mode.custom, custom);
        Object aliases = toJoin.get(custom);
        if (aliases != null) {
            if (aliases instanceof List) {
                for (String alias : (List<String>) aliases) {
                    ret.addAlias(alias);
                }
            } else if (aliases instanceof Map) {
                Map<String, List<String>> map = (Map<String, List<String>>) aliases;
                if (map.containsKey("aliases")) {
                    for (String alias : map.get("aliases")) {
                        ret.addAlias(alias);
                    }
                } else {
                    throwIllegalArgumentException("'networks:' Aliases must be given as a map of strings. 'aliases' key not founded");
                }
            } else {
                throwIllegalArgumentException("'networks:' No aliases entry found in network config map");
            }
        }
        return ret;
    } else {
        throwIllegalArgumentException("'networks:' must beu either a list or a map");
        return null;
    }
}
Also used : NetworkConfig(io.fabric8.maven.docker.config.NetworkConfig) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

Dispatched (io.fabric8.dosgi.api.Dispatched)1 HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)1 KubernetesList (io.fabric8.kubernetes.api.model.KubernetesList)1 NetworkConfig (io.fabric8.maven.docker.config.NetworkConfig)1 OsgiFabricDiscoveryAgent (io.fabric8.mq.fabric.discovery.OsgiFabricDiscoveryAgent)1 Parameter (io.fabric8.openshift.api.model.Parameter)1 EOFException (java.io.EOFException)1 File (java.io.File)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Map (java.util.Map)1 Properties (java.util.Properties)1 Executor (java.util.concurrent.Executor)1 LinkedBlockingQueue (java.util.concurrent.LinkedBlockingQueue)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1 DiscoveryEvent (org.apache.activemq.command.DiscoveryEvent)1