问:
Spring kafka no message received
I'm using spring boot 2.2.4-RELEASE, spring-kafka 2.4.2.RELEASE

My scenario is the following one:

In my microservice (let's call it producer microservice) I need to create kakfa topic and then, on some circumstances, I need to send message over a single topic.

This message must be received and handled by another microservice (let's call it consumer microservice). In this consumer microservice I must create kafka-listener every time a new topic is created on the server side.

So I wrote the folloqing code

producer microservice

spring kafka config:

```<code>@Configuration
public class WebmailKafkaConfig {
    @Autowired
    private Environment environment;
    @Bean
    public KafkaAdmin kafkaAdmin(){
        Map<String, Object> configuration = new HashMap<String, Object>();
        configuration.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, environment.getProperty("webmail.be.messaging.kafka.bootstrap.address"));
        KafkaAdmin result = new KafkaAdmin(configuration);
        return result;
    }
    @Bean
    public ProducerFactory<String, RicezioneMailMessage> producerFactory() {
        Map<String, Object> configProps = new HashMap<>();
        configProps.put( ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, environment.getProperty("webmail.be.messaging.kafka.bootstrap.address"));
        configProps.put( ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        //configProps.put( ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        configProps.put( ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class);
        return new DefaultKafkaProducerFactory<>(configProps);
    }

    @Bean("ricezioneMailMessageKafkaTemplate")
    public KafkaTemplate<String, RicezioneMailMessage> ricezioneMailMessageKafkaTemplate() {
        return new KafkaTemplate<>(producerFactory());
    }
}
</code>```

spring service kafka manager

```<code>@Service
public class WebmailKafkaTopicSvcImpl implements WebmailKafkaTopicSvc {
    private static final Logger logger = LoggerFactory.getLogger(WebmailKafkaTopicSvcImpl.class.getName());
    @Autowired
    private KafkaAdmin kafkaAdmin;
    @Value("${webmail.be.messaging.kafka.topic.numero.partizioni}")
    private int numeroPartizioni;
    @Value("${webmail.be.messaging.kafka.topic.fattore.replica}")
    private short fattoreReplica;
    @Autowired
    @Qualifier("ricezioneMailMessageKafkaTemplate")
    private KafkaTemplate<String, RicezioneMailMessage> ricezioneMailMessageKafkaTemplate;
    @Override
    public void createKafkaTopic(String topicName) throws Exception {
        if(!StringUtils.hasText(topicName)){
            throw new IllegalArgumentException("Passato un topic name non valido ["+topicName+"]");
        }
        AdminClient adminClient = null;
        try{
            adminClient = AdminClient.create(kafkaAdmin.getConfig());
            List<NewTopic> topics = new ArrayList<>(1);
            NewTopic topic = new NewTopic(topicName, numeroPartizioni, fattoreReplica);
            topics.add(topic);
            CreateTopicsResult result = adminClient.createTopics(topics);
            result.all().whenComplete(new KafkaFuture.BiConsumer<Void, Throwable>() {
                @Override
                public void accept(Void aVoid, Throwable throwable) {
                    if( throwable != null ){
                        logger.error("Errore creazione topic", throwable);
                    }
                }
            });

        }finally {
            if( adminClient != null ){
                adminClient.close();
            }
        }
    }

    @Override
    public void sendMessage(RicezioneMailMessage rmm) throws Exception {
        ListenableFuture<SendResult<String, RicezioneMailMessage>> future = ricezioneMailMessageKafkaTemplate.send(rmm.getPk(), rmm);
        future.addCallback(new ListenableFutureCallback<SendResult<String, RicezioneMailMessage>>() {
            @Override
            public void onFailure(Throwable ex) {
                if( logger.isWarnEnabled() ){
                    logger.warn("Impossibile inviare il messaggio=["
                            + rmm + "] a causa di : " + ex.getMessage(),ex);
                }
            }

            @Override
            public void onSuccess(SendResult<String, RicezioneMailMessage> result) {
                if(logger.isTraceEnabled()){
                    logger.trace("Inviato messaggio=[" + rmm +
                            "] con offset=[" + result.getRecordMetadata().offset() + "]");
                }
            }
        });
    }
}
</code>```

In the producer side all works pretty good. I'm able in creating topics and sending messages.

consumer microservice

dynamic listener class

```<code>public class DynamicKafkaConsumer {
    private final String brokerAddress;
    private final String topicName;
    private boolean stopTest;
    private static final Logger logger = LoggerFactory.getLogger(DynamicKafkaConsumer.class.getName());
    public DynamicKafkaConsumer(String brokerAddress, String topicName) {
        if( !StringUtils.hasText(brokerAddress)){
            throw new IllegalArgumentException("Passato un broker address non valido");
        }
        if( !StringUtils.hasText(topicName)){
            throw new IllegalArgumentException("Passato un topicName non valido");
        }
        this.brokerAddress = brokerAddress;
        this.topicName = topicName;
        if( logger.isTraceEnabled() ){
            logger.trace("Creato {} con topicName {} e brokerAddress {}", this.getClass().getName(), this.topicName, this.brokerAddress);
        }
    }
    public final void start() {
        MessageListener<String, RicezioneMailMessage> messageListener = (record -> {
            RicezioneMailMessage messaggioRicevuto = record.value();

            if( logger.isInfoEnabled() ){
                logger.info("Ricevuto messaggio {} su topic {}", messaggioRicevuto, topicName);
            }
            stopTest = true;
        });
        ConcurrentMessageListenerContainer<String, RicezioneMailMessage> container =
                new ConcurrentMessageListenerContainer<>(
                        consumerFactory(brokerAddress),
                        containerProperties(topicName, messageListener));

        container.start();
    }
    private DefaultKafkaConsumerFactory<String, RicezioneMailMessage> consumerFactory(String brokerAddress) {
        return new DefaultKafkaConsumerFactory<>(
                consumerConfig(brokerAddress),
                new StringDeserializer(),
                new JsonDeserializer<>(RicezioneMailMessage.class));
    }

    private ContainerProperties containerProperties(String topic, MessageListener<String, RicezioneMailMessage> messageListener) {
        ContainerProperties containerProperties = new ContainerProperties(topic);
        containerProperties.setMessageListener(messageListener);
        return containerProperties;
    }

    private Map<String, Object> consumerConfig(String brokerAddress) {
        return Map.of(
                BOOTSTRAP_SERVERS_CONFIG, brokerAddress,
                GROUP_ID_CONFIG, "groupId",
                AUTO_OFFSET_RESET_CONFIG, "earliest",
                ALLOW_AUTO_CREATE_TOPICS_CONFIG, "false"
        );
    }

    public boolean isStopTest() {
        return stopTest;
    }

    public void setStopTest(boolean stopTest) {
        this.stopTest = stopTest;
    }
}
</code>```

simple unit test

```<code>public class TestRicezioneMessaggiCasellaPostale {
    private static final Logger logger = LoggerFactory.getLogger(TestRicezioneMessaggiCasellaPostale.class.getName());

    @Test
    public void testRicezioneMessaggiMail() {
        try {

            String brokerAddress = "localhost:9092";
            DynamicKafkaConsumer consumer = new DynamicKafkaConsumer(brokerAddress, "f586caf2-ffdc-4e3a-88b9-a262a502f8ac");
            consumer.start();
            boolean stopTest = consumer.isStopTest();
            while (!stopTest) {

                stopTest = consumer.isStopTest();
            }
        } catch (Exception e) {
            logger.error("Errore nella configurazione della casella postale; {}", e.getMessage(), e);
        }
    }
}
</code>```

In the consumer side I can't read any message; note that the topic "f586caf2-ffdc-4e3a-88b9-a262a502f8ac" exsists and it's the same topic used on the producer side.

When I send a message on the producer side I can see this log:

```<code>2020-02-19 22:00:22,320 52822 [kafka-producer-network-thread | producer-1] TRACE i.e.t.r.p.w.b.s.i.WebmailKafkaTopicSvcImpl - Inviato messaggio=[RicezioneMailMessage{pk='c5c8f8a4-8ddd-407a-9e51-f6b14d84f304', tipoMessaggio='mail'}] con offset=[0]

</code>```

On the consumer side I don't see any message. I just see the following prints:

```<code>2020-02-19 22:00:03,194 1442 [main] INFO  o.a.k.c.consumer.ConsumerConfig - ConsumerConfig values:
allow.auto.create.topics = false
auto.commit.interval.ms = 5000
auto.offset.reset = earliest
bootstrap.servers = [localhost:9092]
check.crcs = true
client.dns.lookup = default
client.id =
client.rack =
connections.max.idle.ms = 540000
default.api.timeout.ms = 60000
enable.auto.commit = false
exclude.internal.topics = true
fetch.max.bytes = 52428800
fetch.max.wait.ms = 500
fetch.min.bytes = 1
group.id = groupId
group.instance.id = null
heartbeat.interval.ms = 3000
interceptor.classes = []
internal.leave.group.on.close = true
isolation.level = read_uncommitted
key.deserializer = class org.apache.kafka.common.serialization.StringDeserializer
max.partition.fetch.bytes = 1048576
max.poll.interval.ms = 300000
max.poll.records = 500
metadata.max.age.ms = 300000
metric.reporters = []
metrics.num.samples = 2
metrics.recording.level = INFO
metrics.sample.window.ms = 30000
partition.assignment.strategy = [class org.apache.kafka.clients.consumer.RangeAssignor]
receive.buffer.bytes
= 65536
reconnect.backoff.max.ms = 1000
reconnect.backoff.ms = 50
request.timeout.ms = 30000
retry.backoff.ms = 100
sasl.client.callback.handler.class = null
sasl.jaas.config = null
sasl.kerberos.kinit.cmd = /usr/bin/kinit    sasl.kerberos.min.time.before.relogin = 60000
sasl.kerberos.service.name = null
sasl.kerberos.ticket.renew.jitter = 0.05
sasl.kerberos.ticket.renew.window.factor = 0.8
sasl.login.callback.handler.class = null
sasl.login.class = null
sasl.login.refresh.buffer.seconds = 300
sasl.login.refresh.min.period.seconds = 60
sasl.login.refresh.window.factor = 0.8
sasl.login.refresh.window.jitter = 0.05
sasl.mechanism = GSSAPI
security.protocol = PLAINTEXT
security.providers = null
send.buffer.bytes = 131072
session.timeout.ms = 10000
ssl.cipher.suites = null
ssl.enabled.protocols = [TLSv1.2, TLSv1.1, TLSv1]
ssl.endpoint.identification.algorithm = https
ssl.key.password = null
ssl.keymanager.algorithm = SunX509
ssl.keystore.location = null
ssl.keystore.password = null
ssl.keystore.type = JKS
ssl.protocol = TLS
ssl.provider = null
ssl.secure.random.implementation = null
ssl.trustmanager.algorithm = PKIX
ssl.truststore.location = null
ssl.truststore.password = null
ssl.truststore.type = JKS
value.deserializer = class org.springframework.kafka.support.serializer.JsonDeserializer
2020-02-19 22:00:03,630 1878 [main] INFO  o.a.k.common.utils.AppInfoParser - Kafka version: 2.4.0
2020-02-19 22:00:03,630 1878 [main] INFO  o.a.k.common.utils.AppInfoParser - Kafka commitId: 77a89fcf8d7fa018
2020-02-19 22:00:03,630 1878 [main] INFO  o.a.k.common.utils.AppInfoParser - Kafka startTimeMs: 1582146003626
2020-02-19 22:00:03,636 1884 [main] INFO  o.a.k.c.consumer.KafkaConsumer - [Consumer clientId=consumer-groupId-1, groupId=groupId] Subscribed to topic(s): f586caf2-ffdc-4e3a-88b9-a262a502f8ac
2020-02-19 22:00:03,645 1893 [main] INFO  o.s.s.c.ThreadPoolTaskScheduler - Initializing ExecutorService
2020-02-19 22:00:03,667 1915 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Commit list: {}
2020-02-19 22:00:04,123 2371 [consumer-0-C-1] INFO  org.apache.kafka.clients.Metadata - [Consumer clientId=consumer-groupId-1, groupId=groupId] Cluster ID: hOOJH-WNTNiXD4il0Y7_0Q
2020-02-19 22:00:05,052 3300 [consumer-0-C-1] INFO  o.a.k.c.c.i.AbstractCoordinator - [Consumer clientId=consumer-groupId-1, groupId=groupId] Discovered group coordinator localhost:9092 (id: 2147483647 rack: null)
2020-02-19 22:00:05,059 3307 [consumer-0-C-1] INFO  o.a.k.c.c.i.AbstractCoordinator - [Consumer clientId=consumer-groupId-1, groupId=groupId] (Re-)joining group
2020-02-19 22:00:05,116 3364 [consumer-0-C-1] INFO  o.a.k.c.c.i.AbstractCoordinator - [Consumer clientId=consumer-groupId-1, groupId=groupId] (Re-)joining group
2020-02-19 22:00:05,154 3402 [consumer-0-C-1] INFO  o.a.k.c.c.i.ConsumerCoordinator - [Consumer clientId=consumer-groupId-1, groupId=groupId] Finished assignment for group at generation 1: {consumer-groupId-1-41df9153-7c33-46b1-8274-2d7ee2bfb35c=org.apache.kafka.clients.consumer.ConsumerPartitionAssignor$Assignment@a95df1b}
2020-02-19 22:00:05,327 3575 [consumer-0-C-1] INFO  o.a.k.c.c.i.AbstractCoordinator - [Consumer clientId=consumer-groupId-1, groupId=groupId] Successfully joined group with generation 1
2020-02-19 22:00:05,335 3583 [consumer-0-C-1] INFO  o.a.k.c.c.i.ConsumerCoordinator - [Consumer clientId=consumer-groupId-1, groupId=groupId] Adding newly assigned partitions: f586caf2-ffdc-4e3a-88b9-a262a502f8ac-0
2020-02-19 22:00:05,363 3611 [consumer-0-C-1] INFO  o.a.k.c.c.i.ConsumerCoordinator - [Consumer clientId=consumer-groupId-1, groupId=groupId] Found no committed offset for partition f586caf2-ffdc-4e3a-88b9-a262a502f8ac-0
2020-02-19 22:00:05,401 3649 [consumer-0-C-1] INFO  o.a.k.c.c.i.SubscriptionState - [Consumer clientId=consumer-groupId-1, groupId=groupId] Resetting offset for partition f586caf2-ffdc-4e3a-88b9-a262a502f8ac-0 to offset 0.
2020-02-19 22:00:05,404 3652 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Committing on assignment: {f586caf2-ffdc-4e3a-88b9-a262a502f8ac-0=OffsetAndMetadata{offset=0, leaderEpoch=null, metadata=''}}
2020-02-19 22:00:05,432 3680 [consumer-0-C-1] INFO  o.s.k.l.ConcurrentMessageListenerContainer - groupId: partitions assigned: [f586caf2-ffdc-4e3a-88b9-a262a502f8ac-0]
2020-02-19 22:00:08,669 6917 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Received: 0 records
2020-02-19 22:00:08,670 6918 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Commit list: {}
2020-02-19 22:00:13,671 11919 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Received: 0 records
2020-02-19 22:00:13,671 11919 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Commit list: {}
2020-02-19 22:00:18,673 16921 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Received: 0 records
2020-02-19 22:00:18,673 16921 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Commit list: {}
2020-02-19 22:00:23,674 21922 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Received: 0 records
2020-02-19 22:00:23,674 21922 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Commit list: {}
2020-02-19 22:00:28,676 26924 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Received: 0 records
2020-02-19 22:00:28,676 26924 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Commit list: {}
2020-02-19 22:00:33,677 31925 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Received: 0 records
2020-02-19 22:00:33,677 31925 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Commit list: {}
2020-02-19 22:00:38,678 36926 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Received: 0 records
2020-02-19 22:00:38,678 36926 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Commit list: {}
2020-02-19 22:00:43,678 41926 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Received: 0 records
2020-02-19 22:00:43,679 41927 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Commit list: {}

</code>```

Can anybody tell me where I'm wrong?

Thank you

Angelo

答:
I found the root cause of your code.

Code to send message and log from client side:

```<code>ricezioneMailMessageKafkaTemplate.send(rmm.getPk(), rmm);

Inviato messaggio=[RicezioneMailMessage{pk='c5c8f8a4-8ddd-407a-9e51-f6b14d84f304', tipoMessaggio='mail'}] con offset=[0]
</code>```

Code and log from consumer:

```<code>DynamicKafkaConsumer consumer = new DynamicKafkaConsumer(brokerAddress, "f586caf2-ffdc-4e3a-88b9-a262a502f8ac");

2020-02-19 22:00:03,636 1884 [main] INFO  o.a.k.c.consumer.KafkaConsumer - [Consumer clientId=consumer-groupId-1, groupId=groupId] Subscribed to topic(s): f586caf2-ffdc-4e3a-88b9-a262a502f8ac
</code>```

You are sending to topic: c5c8f8a4-8ddd-407a-9e51-f6b14d84f304

You are listening on topic: f586caf2-ffdc-4e3a-88b9-a262a502f8ac

Producer/consumer are sending/listening on difference topics.

Title: Spring kafka no message received

Body:
I'm using spring boot 2.2.4-RELEASE, spring-kafka 2.4.2.RELEASE

My scenario is the following one:

In my microservice (let's call it producer microservice) I need to create kakfa topic and then, on some circumstances, I need to send message over a single topic.

This message must be received and handled by another microservice (let's call it consumer microservice). In this consumer microservice I must create kafka-listener every time a new topic is created on the server side.

So I wrote the folloqing code

producer microservice

spring kafka config:

@Configuration
public class WebmailKafkaConfig {
    @Autowired
    private Environment environment;
    @Bean
    public KafkaAdmin kafkaAdmin(){
        Map<String, Object> configuration = new HashMap<String, Object>();
        configuration.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, environment.getProperty("webmail.be.messaging.kafka.bootstrap.address"));
        KafkaAdmin result = new KafkaAdmin(configuration);
        return result;
    }
    @Bean
    public ProducerFactory<String, RicezioneMailMessage> producerFactory() {
        Map<String, Object> configProps = new HashMap<>();
        configProps.put( ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, environment.getProperty("webmail.be.messaging.kafka.bootstrap.address"));
        configProps.put( ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        //configProps.put( ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        configProps.put( ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class);
        return new DefaultKafkaProducerFactory<>(configProps);
    }

    @Bean("ricezioneMailMessageKafkaTemplate")
    public KafkaTemplate<String, RicezioneMailMessage> ricezioneMailMessageKafkaTemplate() {
        return new KafkaTemplate<>(producerFactory());
    }
}

spring service kafka manager

@Service
public class WebmailKafkaTopicSvcImpl implements WebmailKafkaTopicSvc {
    private static final Logger logger = LoggerFactory.getLogger(WebmailKafkaTopicSvcImpl.class.getName());
    @Autowired
    private KafkaAdmin kafkaAdmin;
    @Value("${webmail.be.messaging.kafka.topic.numero.partizioni}")
    private int numeroPartizioni;
    @Value("${webmail.be.messaging.kafka.topic.fattore.replica}")
    private short fattoreReplica;
    @Autowired
    @Qualifier("ricezioneMailMessageKafkaTemplate")
    private KafkaTemplate<String, RicezioneMailMessage> ricezioneMailMessageKafkaTemplate;
    @Override
    public void createKafkaTopic(String topicName) throws Exception {
        if(!StringUtils.hasText(topicName)){
            throw new IllegalArgumentException("Passato un topic name non valido ["+topicName+"]");
        }
        AdminClient adminClient = null;
        try{
            adminClient = AdminClient.create(kafkaAdmin.getConfig());
            List<NewTopic> topics = new ArrayList<>(1);
            NewTopic topic = new NewTopic(topicName, numeroPartizioni, fattoreReplica);
            topics.add(topic);
            CreateTopicsResult result = adminClient.createTopics(topics);
            result.all().whenComplete(new KafkaFuture.BiConsumer<Void, Throwable>() {
                @Override
                public void accept(Void aVoid, Throwable throwable) {
                    if( throwable != null ){
                        logger.error("Errore creazione topic", throwable);
                    }
                }
            });

        }finally {
            if( adminClient != null ){
                adminClient.close();
            }
        }
    }

    @Override
    public void sendMessage(RicezioneMailMessage rmm) throws Exception {
        ListenableFuture<SendResult<String, RicezioneMailMessage>> future = ricezioneMailMessageKafkaTemplate.send(rmm.getPk(), rmm);
        future.addCallback(new ListenableFutureCallback<SendResult<String, RicezioneMailMessage>>() {
            @Override
            public void onFailure(Throwable ex) {
                if( logger.isWarnEnabled() ){
                    logger.warn("Impossibile inviare il messaggio=["
                            + rmm + "] a causa di : " + ex.getMessage(),ex);
                }
            }

            @Override
            public void onSuccess(SendResult<String, RicezioneMailMessage> result) {
                if(logger.isTraceEnabled()){
                    logger.trace("Inviato messaggio=[" + rmm +
                            "] con offset=[" + result.getRecordMetadata().offset() + "]");
                }
            }
        });
    }
}

In the producer side all works pretty good. I'm able in creating topics and sending messages.

consumer microservice

dynamic listener class

public class DynamicKafkaConsumer {
    private final String brokerAddress;
    private final String topicName;
    private boolean stopTest;
    private static final Logger logger = LoggerFactory.getLogger(DynamicKafkaConsumer.class.getName());
    public DynamicKafkaConsumer(String brokerAddress, String topicName) {
        if( !StringUtils.hasText(brokerAddress)){
            throw new IllegalArgumentException("Passato un broker address non valido");
        }
        if( !StringUtils.hasText(topicName)){
            throw new IllegalArgumentException("Passato un topicName non valido");
        }
        this.brokerAddress = brokerAddress;
        this.topicName = topicName;
        if( logger.isTraceEnabled() ){
            logger.trace("Creato {} con topicName {} e brokerAddress {}", this.getClass().getName(), this.topicName, this.brokerAddress);
        }
    }
    public final void start() {
        MessageListener<String, RicezioneMailMessage> messageListener = (record -> {
            RicezioneMailMessage messaggioRicevuto = record.value();

            if( logger.isInfoEnabled() ){
                logger.info("Ricevuto messaggio {} su topic {}", messaggioRicevuto, topicName);
            }
            stopTest = true;
        });
        ConcurrentMessageListenerContainer<String, RicezioneMailMessage> container =
                new ConcurrentMessageListenerContainer<>(
                        consumerFactory(brokerAddress),
                        containerProperties(topicName, messageListener));

        container.start();
    }
    private DefaultKafkaConsumerFactory<String, RicezioneMailMessage> consumerFactory(String brokerAddress) {
        return new DefaultKafkaConsumerFactory<>(
                consumerConfig(brokerAddress),
                new StringDeserializer(),
                new JsonDeserializer<>(RicezioneMailMessage.class));
    }

    private ContainerProperties containerProperties(String topic, MessageListener<String, RicezioneMailMessage> messageListener) {
        ContainerProperties containerProperties = new ContainerProperties(topic);
        containerProperties.setMessageListener(messageListener);
        return containerProperties;
    }

    private Map<String, Object> consumerConfig(String brokerAddress) {
        return Map.of(
                BOOTSTRAP_SERVERS_CONFIG, brokerAddress,
                GROUP_ID_CONFIG, "groupId",
                AUTO_OFFSET_RESET_CONFIG, "earliest",
                ALLOW_AUTO_CREATE_TOPICS_CONFIG, "false"
        );
    }

    public boolean isStopTest() {
        return stopTest;
    }

    public void setStopTest(boolean stopTest) {
        this.stopTest = stopTest;
    }
}

simple unit test

public class TestRicezioneMessaggiCasellaPostale {
    private static final Logger logger = LoggerFactory.getLogger(TestRicezioneMessaggiCasellaPostale.class.getName());

    @Test
    public void testRicezioneMessaggiMail() {
        try {

            String brokerAddress = "localhost:9092";
            DynamicKafkaConsumer consumer = new DynamicKafkaConsumer(brokerAddress, "f586caf2-ffdc-4e3a-88b9-a262a502f8ac");
            consumer.start();
            boolean stopTest = consumer.isStopTest();
            while (!stopTest) {

                stopTest = consumer.isStopTest();
            }
        } catch (Exception e) {
            logger.error("Errore nella configurazione della casella postale; {}", e.getMessage(), e);
        }
    }
}

In the consumer side I can't read any message; note that the topic "f586caf2-ffdc-4e3a-88b9-a262a502f8ac" exsists and it's the same topic used on the producer side.

When I send a message on the producer side I can see this log:

2020-02-19 22:00:22,320 52822 [kafka-producer-network-thread | producer-1] TRACE i.e.t.r.p.w.b.s.i.WebmailKafkaTopicSvcImpl - Inviato messaggio=[RicezioneMailMessage{pk='c5c8f8a4-8ddd-407a-9e51-f6b14d84f304', tipoMessaggio='mail'}] con offset=[0]

On the consumer side I don't see any message. I just see the following prints:

2020-02-19 22:00:03,194 1442 [main] INFO  o.a.k.c.consumer.ConsumerConfig - ConsumerConfig values:
allow.auto.create.topics = false
auto.commit.interval.ms = 5000
auto.offset.reset = earliest
bootstrap.servers = [localhost:9092]
check.crcs = true
client.dns.lookup = default
client.id =
client.rack =
connections.max.idle.ms = 540000
default.api.timeout.ms = 60000
enable.auto.commit = false
exclude.internal.topics = true
fetch.max.bytes = 52428800
fetch.max.wait.ms = 500
fetch.min.bytes = 1
group.id = groupId
group.instance.id = null
heartbeat.interval.ms = 3000
interceptor.classes = []
internal.leave.group.on.close = true
isolation.level = read_uncommitted
key.deserializer = class org.apache.kafka.common.serialization.StringDeserializer
max.partition.fetch.bytes = 1048576
max.poll.interval.ms = 300000
max.poll.records = 500
metadata.max.age.ms = 300000
metric.reporters = []
metrics.num.samples = 2
metrics.recording.level = INFO
metrics.sample.window.ms = 30000
partition.assignment.strategy = [class org.apache.kafka.clients.consumer.RangeAssignor]
receive.buffer.bytes
= 65536
reconnect.backoff.max.ms = 1000
reconnect.backoff.ms = 50
request.timeout.ms = 30000
retry.backoff.ms = 100
sasl.client.callback.handler.class = null
sasl.jaas.config = null
sasl.kerberos.kinit.cmd = /usr/bin/kinit    sasl.kerberos.min.time.before.relogin = 60000
sasl.kerberos.service.name = null
sasl.kerberos.ticket.renew.jitter = 0.05
sasl.kerberos.ticket.renew.window.factor = 0.8
sasl.login.callback.handler.class = null
sasl.login.class = null
sasl.login.refresh.buffer.seconds = 300
sasl.login.refresh.min.period.seconds = 60
sasl.login.refresh.window.factor = 0.8
sasl.login.refresh.window.jitter = 0.05
sasl.mechanism = GSSAPI
security.protocol = PLAINTEXT
security.providers = null
send.buffer.bytes = 131072
session.timeout.ms = 10000
ssl.cipher.suites = null
ssl.enabled.protocols = [TLSv1.2, TLSv1.1, TLSv1]
ssl.endpoint.identification.algorithm = https
ssl.key.password = null
ssl.keymanager.algorithm = SunX509
ssl.keystore.location = null
ssl.keystore.password = null
ssl.keystore.type = JKS
ssl.protocol = TLS
ssl.provider = null
ssl.secure.random.implementation = null
ssl.trustmanager.algorithm = PKIX
ssl.truststore.location = null
ssl.truststore.password = null
ssl.truststore.type = JKS
value.deserializer = class org.springframework.kafka.support.serializer.JsonDeserializer
2020-02-19 22:00:03,630 1878 [main] INFO  o.a.k.common.utils.AppInfoParser - Kafka version: 2.4.0
2020-02-19 22:00:03,630 1878 [main] INFO  o.a.k.common.utils.AppInfoParser - Kafka commitId: 77a89fcf8d7fa018
2020-02-19 22:00:03,630 1878 [main] INFO  o.a.k.common.utils.AppInfoParser - Kafka startTimeMs: 1582146003626
2020-02-19 22:00:03,636 1884 [main] INFO  o.a.k.c.consumer.KafkaConsumer - [Consumer clientId=consumer-groupId-1, groupId=groupId] Subscribed to topic(s): f586caf2-ffdc-4e3a-88b9-a262a502f8ac
2020-02-19 22:00:03,645 1893 [main] INFO  o.s.s.c.ThreadPoolTaskScheduler - Initializing ExecutorService
2020-02-19 22:00:03,667 1915 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Commit list: {}
2020-02-19 22:00:04,123 2371 [consumer-0-C-1] INFO  org.apache.kafka.clients.Metadata - [Consumer clientId=consumer-groupId-1, groupId=groupId] Cluster ID: hOOJH-WNTNiXD4il0Y7_0Q
2020-02-19 22:00:05,052 3300 [consumer-0-C-1] INFO  o.a.k.c.c.i.AbstractCoordinator - [Consumer clientId=consumer-groupId-1, groupId=groupId] Discovered group coordinator localhost:9092 (id: 2147483647 rack: null)
2020-02-19 22:00:05,059 3307 [consumer-0-C-1] INFO  o.a.k.c.c.i.AbstractCoordinator - [Consumer clientId=consumer-groupId-1, groupId=groupId] (Re-)joining group
2020-02-19 22:00:05,116 3364 [consumer-0-C-1] INFO  o.a.k.c.c.i.AbstractCoordinator - [Consumer clientId=consumer-groupId-1, groupId=groupId] (Re-)joining group
2020-02-19 22:00:05,154 3402 [consumer-0-C-1] INFO  o.a.k.c.c.i.ConsumerCoordinator - [Consumer clientId=consumer-groupId-1, groupId=groupId] Finished assignment for group at generation 1: {consumer-groupId-1-41df9153-7c33-46b1-8274-2d7ee2bfb35c=org.apache.kafka.clients.consumer.ConsumerPartitionAssignor$Assignment@a95df1b}
2020-02-19 22:00:05,327 3575 [consumer-0-C-1] INFO  o.a.k.c.c.i.AbstractCoordinator - [Consumer clientId=consumer-groupId-1, groupId=groupId] Successfully joined group with generation 1
2020-02-19 22:00:05,335 3583 [consumer-0-C-1] INFO  o.a.k.c.c.i.ConsumerCoordinator - [Consumer clientId=consumer-groupId-1, groupId=groupId] Adding newly assigned partitions: f586caf2-ffdc-4e3a-88b9-a262a502f8ac-0
2020-02-19 22:00:05,363 3611 [consumer-0-C-1] INFO  o.a.k.c.c.i.ConsumerCoordinator - [Consumer clientId=consumer-groupId-1, groupId=groupId] Found no committed offset for partition f586caf2-ffdc-4e3a-88b9-a262a502f8ac-0
2020-02-19 22:00:05,401 3649 [consumer-0-C-1] INFO  o.a.k.c.c.i.SubscriptionState - [Consumer clientId=consumer-groupId-1, groupId=groupId] Resetting offset for partition f586caf2-ffdc-4e3a-88b9-a262a502f8ac-0 to offset 0.
2020-02-19 22:00:05,404 3652 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Committing on assignment: {f586caf2-ffdc-4e3a-88b9-a262a502f8ac-0=OffsetAndMetadata{offset=0, leaderEpoch=null, metadata=''}}
2020-02-19 22:00:05,432 3680 [consumer-0-C-1] INFO  o.s.k.l.ConcurrentMessageListenerContainer - groupId: partitions assigned: [f586caf2-ffdc-4e3a-88b9-a262a502f8ac-0]
2020-02-19 22:00:08,669 6917 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Received: 0 records
2020-02-19 22:00:08,670 6918 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Commit list: {}
2020-02-19 22:00:13,671 11919 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Received: 0 records
2020-02-19 22:00:13,671 11919 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Commit list: {}
2020-02-19 22:00:18,673 16921 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Received: 0 records
2020-02-19 22:00:18,673 16921 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Commit list: {}
2020-02-19 22:00:23,674 21922 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Received: 0 records
2020-02-19 22:00:23,674 21922 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Commit list: {}
2020-02-19 22:00:28,676 26924 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Received: 0 records
2020-02-19 22:00:28,676 26924 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Commit list: {}
2020-02-19 22:00:33,677 31925 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Received: 0 records
2020-02-19 22:00:33,677 31925 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Commit list: {}
2020-02-19 22:00:38,678 36926 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Received: 0 records
2020-02-19 22:00:38,678 36926 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Commit list: {}
2020-02-19 22:00:43,678 41926 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Received: 0 records
2020-02-19 22:00:43,679 41927 [consumer-0-C-1] DEBUG o.s.k.l.KafkaMessageListenerContainer$ListenerConsumer - Commit list: {}

Can anybody tell me where I'm wrong?

Thank you

Angelo

Body:
I found the root cause of your code.

Code to send message and log from client side:

ricezioneMailMessageKafkaTemplate.send(rmm.getPk(), rmm);

Inviato messaggio=[RicezioneMailMessage{pk='c5c8f8a4-8ddd-407a-9e51-f6b14d84f304', tipoMessaggio='mail'}] con offset=[0]

Code and log from consumer:

DynamicKafkaConsumer consumer = new DynamicKafkaConsumer(brokerAddress, "f586caf2-ffdc-4e3a-88b9-a262a502f8ac");

2020-02-19 22:00:03,636 1884 [main] INFO  o.a.k.c.consumer.KafkaConsumer - [Consumer clientId=consumer-groupId-1, groupId=groupId] Subscribed to topic(s): f586caf2-ffdc-4e3a-88b9-a262a502f8ac

You are sending to topic: c5c8f8a4-8ddd-407a-9e51-f6b14d84f304

You are listening on topic: f586caf2-ffdc-4e3a-88b9-a262a502f8ac

Producer/consumer are sending/listening on difference topics.


来源: stackexchange

问:
Debugging this OCaml code? Functional Programming
```<code>let rec fold_inorder f acc t =
match t with
| Leaf -> acc
| Node (l, n, r) -> f (fold_inorder f acc l) (f n (fold_inorder f acc r))
</code>```

I'm trying to print the infold of a tree as following :

```<code>fold_inorder (fun acc x -> acc @ [x]) [] (Node (Node (Leaf,1,Leaf), 2, Node (Leaf,3,Leaf))) = [1;2;3]
</code>```

I'm getting an error saying my [x] is

```<code>This expression has type 'a list
       but an expression was expected of type 'a
       The type variable 'a occurs inside 'a list
</code>```

I'm really not sure what to do from here. Can anyone nudge me in the right direction?

答:
In your definition of fold_inorder, what type do you expect f to have?

If I look at this call:

```<code>f n (fold_inorder f acc r)
</code>```

it appears that the first parameter of f is a new value from a tree node and the second parameter is an accumulated value.

But in your test call you define f like this:

```<code>(fun acc x -> ...)
</code>```

This suggests that the first parameter is the accumulated value and the second parameter is a new value from a tree node.

ContentLicense: CC BY-SA 4.0

Body:
let rec fold_inorder f acc t =
match t with
| Leaf -> acc
| Node (l, n, r) -> f (fold_inorder f acc l) (f n (fold_inorder f acc r))

I'm trying to print the infold of a tree as following :

fold_inorder (fun acc x -> acc @ [x]) [] (Node (Node (Leaf,1,Leaf), 2, Node (Leaf,3,Leaf))) = [1;2;3]

I'm getting an error saying my [x] is

This expression has type 'a list
       but an expression was expected of type 'a
       The type variable 'a occurs inside 'a list

I'm really not sure what to do from here. Can anyone nudge me in the right direction?

Body:
In your definition of fold_inorder, what type do you expect f to have?

If I look at this call:

f n (fold_inorder f acc r)

it appears that the first parameter of f is a new value from a tree node and the second parameter is an accumulated value.

But in your test call you define f like this:

(fun acc x -> ...)

This suggests that the first parameter is the accumulated value and the second parameter is a new value from a tree node.


问:
Is possible to React Native run a socket server?
I'd like to make a app with React-Native that's accept connections from another devices (Desktops or mobiles) through raw tcp sockets (like node's Net API) or WebSockets (like Socket.io). The point is that, socket server must be running on the React-Native's App.

I already tried Socket.io and react-native-tcp, it works when i make the server run on a nodeJS's application and the client on RN's app, but not the reverse.

When i try to import Socket.io and make it listen on a port, a error is raisen, because RN don't have node's http module. Just Socket.io/clients works.

I think that i'm doing something wrong, but is really possible to do that? and what is the best way?

Obs: I'm really new in RN's world.

答:
No, we can't create a server although if we create a server we can't connect any other external applications to the server.

So create a server and deploy it in any could service then use it in your react-native app.


问:
_tkinter.TclError: image "..." doesn't exist
I know that this question has already been asked several times, but I still couldn't figure out the answer to my problem. I keep getting the same error and don't know how to solve it.

This is my code:

```<code>from Tkinter import *
from PIL import Image, ImageTk
import os

window = Tk()
i = Image.open(pathToImage)
if os.path.isfile(pathToImage):

     print 'image exists'
else:
     print 'image does not exits'

label=Label(window, image=i)
label.pack()
window.mainloop()
</code>```

It says that the image exists at the indicated path, but I keep getting this error message:

```<code>Traceback (most recent call last):
  File "ImageTest.py", line 31, in <module>
    label=Label(window, image=i)
  File "C:\Users\username\Anaconda2\lib\lib-tk\Tkinter.py", line 2597, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
  File "C:\Users\username\Anaconda2\lib\lib-tk\Tkinter.py", line 2096, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=640x480 at 0x36DF278>" doesn't exist
</code>```

I could not figure out how to solve this problem. Any help would be appreciated!

答:
A quick hacky fix is to provide the .PhotoImage with the correct master:

i = ImageTk.PhotoImage(pathToImage, master=window)
```

ContentLicense: CC BY-SA 3.0

Body:
I know that this question has already been asked several times, but I still couldn't figure out the answer to my problem. I keep getting the same error and don't know how to solve it.

This is my code:

from Tkinter import *
from PIL import Image, ImageTk
import os

window = Tk()
i = Image.open(pathToImage)
if os.path.isfile(pathToImage):

     print 'image exists'
else:
     print 'image does not exits'

label=Label(window, image=i)
label.pack()
window.mainloop()

It says that the image exists at the indicated path, but I keep getting this error message:

Traceback (most recent call last):
  File "ImageTest.py", line 31, in <module>
    label=Label(window, image=i)
  File "C:\Users\username\Anaconda2\lib\lib-tk\Tkinter.py", line 2597, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
  File "C:\Users\username\Anaconda2\lib\lib-tk\Tkinter.py", line 2096, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=640x480 at 0x36DF278>" doesn't exist

I could not figure out how to solve this problem. Any help would be appreciated!


问:
IBM Asset Monitor - Test Custom Function DLL load failed: The specified module could not be found
I am following the steps in this link, https://www.ibm.com/support/knowledgecenter/SSQP8H/iot/analytics/tutorials/as_adding_complex_function_tutorial.html, and have created a function successfully.

My files can be found here, https://github.com/tiongghee/AssetMonitor

I have created the test script, test_my_custom_function.py, to test my function and have encountered the under-mentioned error.

```<code>C:\Users\TIONGGHEETAN\Desktop\projects>python3 test_my_custom_function.py
Traceback (most recent call last):
  File "test_my_custom_function.py", line 6, in <module>
    from iotfunctions.base import BaseTransformer
  File "D:\WIOTProgram_Files\python372\lib\site-packages\iotfunctions\base.py", line 30, in <module>
    from .db import Database
  File "D:\WIOTProgram_Files\python372\lib\site-packages\iotfunctions\db.py", line 31, in <module>
    from . import metadata as md
  File "D:\WIOTProgram_Files\python372\lib\site-packages\iotfunctions\metadata.py", line 28, in <module>
    from .pipeline import (CalcPipeline, DropNull, JobController, JobLogNull, Trace, AggregateItems)
  File "D:\WIOTProgram_Files\python372\lib\site-packages\iotfunctions\pipeline.py", line 29, in <module>
    from .stages import DataWriterSqlAlchemy, ProduceAlerts
  File "D:\WIOTProgram_Files\python372\lib\site-packages\iotfunctions\stages.py", line 15, in <module>
    import ibm_db
  File "D:\WIOTProgram_Files\python372\lib\site-packages\ibm_db.py", line 10, in <module>
    __bootstrap__()
  File "D:\WIOTProgram_Files\python372\lib\site-packages\ibm_db.py", line 9, in __bootstrap__
    imp.load_dynamic(__name__,__file__)
  File "D:\WIOTProgram_Files\python372\lib\imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: The specified module could not be found.
</code>```

答:
To update:
I encountered the same problem after updating requirements.txt.

My code are finally working now after I followed the instructions from here.
https://github.com/IBM/watson-analytics-dashboard/blob/master/README.md

Body:
I am following the steps in this link, https://www.ibm.com/support/knowledgecenter/SSQP8H/iot/analytics/tutorials/as_adding_complex_function_tutorial.html, and have created a function successfully.

My files can be found here, https://github.com/tiongghee/AssetMonitor

I have created the test script, test_my_custom_function.py, to test my function and have encountered the under-mentioned error.

C:\Users\TIONGGHEETAN\Desktop\projects>python3 test_my_custom_function.py
Traceback (most recent call last):
  File "test_my_custom_function.py", line 6, in <module>
    from iotfunctions.base import BaseTransformer
  File "D:\WIOTProgram_Files\python372\lib\site-packages\iotfunctions\base.py", line 30, in <module>
    from .db import Database
  File "D:\WIOTProgram_Files\python372\lib\site-packages\iotfunctions\db.py", line 31, in <module>
    from . import metadata as md
  File "D:\WIOTProgram_Files\python372\lib\site-packages\iotfunctions\metadata.py", line 28, in <module>
    from .pipeline import (CalcPipeline, DropNull, JobController, JobLogNull, Trace, AggregateItems)
  File "D:\WIOTProgram_Files\python372\lib\site-packages\iotfunctions\pipeline.py", line 29, in <module>
    from .stages import DataWriterSqlAlchemy, ProduceAlerts
  File "D:\WIOTProgram_Files\python372\lib\site-packages\iotfunctions\stages.py", line 15, in <module>
    import ibm_db
  File "D:\WIOTProgram_Files\python372\lib\site-packages\ibm_db.py", line 10, in <module>
    __bootstrap__()
  File "D:\WIOTProgram_Files\python372\lib\site-packages\ibm_db.py", line 9, in __bootstrap__
    imp.load_dynamic(__name__,__file__)
  File "D:\WIOTProgram_Files\python372\lib\imp.py", line 342, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: The specified module could not be found.


问:
Failed to notify build listener Gradle Artifactory Plugin
I'm trying to publish an artifact to jfrog artifactory using gradle. I figured out that Gradle Actifactory Plugin might be the one I need. Unfortunately, upon calling gradlew -i artifactoryPublish an error is thrown :

```<code>    Exception is:
org.gradle.internal.event.ListenerNotificationException: Failed to notify build listener.
        at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:86)
        at org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:324)
        at org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:234)
        at org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:140)
        at org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:37)
        at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
        at com.sun.proxy.$Proxy17.projectsEvaluated(Unknown Source)
        at org.gradle.initialization.DefaultGradleLauncher.projectsEvaluated(DefaultGradleLauncher.java:329)
        at org.gradle.initialization.DefaultGradleLauncher.access$1200(DefaultGradleLauncher.java:46)
        at org.gradle.initialization.DefaultGradleLauncher$ConfigureBuild.run(DefaultGradleLauncher.java:252)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
        at org.gradle.initialization.DefaultGradleLauncher.configureBuild(DefaultGradleLauncher.java:167)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:126)
        at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:109)
        at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:78)
        at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:75)
        at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:152)
        at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:100)
        at org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:75)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
        at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$1.run(RunAsBuildOperationBuildActionRunner.java:43)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
        at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
        at org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:47)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:30)
        at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
        at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:80)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:53)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:57)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:32)
        at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
        at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
        at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
        at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
        at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:69)
        at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:30)
        at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:59)
        at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:44)
        at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:45)
        at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:30)
        at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
        at org.gradle.util.Swapper.swap(Swapper.java:38)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:82)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
        at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:295)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
        at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
        at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: java.lang.BootstrapMethodError: java.lang.NoClassDefFoundError:
        at org.jfrog.gradle.plugin.artifactory.task.helper.TaskHelperPublications.dependOn(TaskHelperPublications.java:171)
        at org.jfrog.gradle.plugin.artifactory.task.helper.TaskHelperPublications.checkDependsOnArtifactsToPublish(TaskHelperPublications.java:159)
        at org.jfrog.gradle.plugin.artifactory.task.ArtifactoryTask.checkDependsOnArtifactsToPublish(ArtifactoryTask.java:72)
        at org.jfrog.gradle.plugin.artifactory.task.ArtifactoryTask.publications(ArtifactoryTask.java:110)
        at org.gradle.internal.metaobject.BeanDynamicObject$MetaClassAdapter.invokeMethod(BeanDynamicObject.java:479)
        at org.gradle.internal.metaobject.BeanDynamicObject.tryInvokeMethod(BeanDynamicObject.java:191)
        at org.gradle.internal.metaobject.CompositeDynamicObject.tryInvokeMethod(CompositeDynamicObject.java:98)
        at org.gradle.internal.metaobject.MixInClosurePropertiesAsMethodsDynamicObject.tryInvokeMethod(MixInClosurePropertiesAsMethodsDynamicObject.java:30)
        at org.gradle.internal.metaobject.ConfigureDelegate.invokeMethod(ConfigureDelegate.java:57)
        at build_84hxiqveouy516qtdye6ljohx$_run_closure2$_closure14$_closure16.doCall(D:\GIT_ROOT\RND\tools\GeneratorV2\build.gradle:50)
        at org.gradle.api.internal.ClosureBackedAction.execute(ClosureBackedAction.java:71)
        at org.gradle.util.ConfigureUtil.configureTarget(ConfigureUtil.java:160)
        at org.gradle.util.ConfigureUtil.configureSelf(ConfigureUtil.java:136)
        at org.gradle.api.internal.AbstractTask.configure(AbstractTask.java:634)
        at org.gradle.api.internal.AbstractTask.configure(AbstractTask.java:86)
        at org.gradle.util.ConfigureUtil.configure(ConfigureUtil.java:104)
        at org.jfrog.gradle.plugin.artifactory.task.ArtifactoryTask.projectEvaluated(ArtifactoryTask.java:216)
        at org.jfrog.gradle.plugin.artifactory.task.ArtifactoryTask$projectEvaluated$0.call(Unknown Source)
        at org.jfrog.gradle.plugin.artifactory.extractor.listener.ProjectsEvaluatedBuildListener.evaluate(ProjectsEvaluatedBuildListener.groovy:114)
        at org.jfrog.gradle.plugin.artifactory.extractor.listener.ProjectsEvaluatedBuildListener$_projectsEvaluated_closure8.doCall(ProjectsEvaluatedBuildListener.groovy:197)
        at org.jfrog.gradle.plugin.artifactory.extractor.listener.ProjectsEvaluatedBuildListener.projectsEvaluated(ProjectsEvaluatedBuildListener.groovy:195)
        at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
        at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
        at org.gradle.internal.event.DefaultListenerManager$ListenerDetails.dispatch(DefaultListenerManager.java:371)
        at org.gradle.internal.event.DefaultListenerManager$ListenerDetails.dispatch(DefaultListenerManager.java:353)
        at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:58)
        at org.gradle.internal.event.DefaultListenerManager$EventBroadcast$ListenerDispatch.dispatch(DefaultListenerManager.java:341)
        at org.gradle.internal.event.DefaultListenerManager$EventBroadcast$ListenerDispatch.dispatch(DefaultListenerManager.java:328)
        at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:42)
        at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:230)
        at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:149)
        at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:58)
        ... 76 more
Caused by: java.lang.NoClassDefFoundError:
        ... 108 more
</code>```

Here is the relevan configuration :

```<code>publishing {
    publications {
        maven(MavenPublication) {
            groupId    = 'com.artifact'
            artifactId = 'Artifact'
            version    = '1.0'

            //from components.java
            artifact "target/artifact.jar"
        }
    }
}

artifactory{
    contextUrl = 'http://my.artifactory/artifactory'
    publish{
        contextUrl = 'http://my.artifactory/artifactory'
        repository{
            repoKey  = 'myrepo'
            username = 'lalala'
            password = 'isthisapassword'
        }
        defaults {
            publications ('maven')
        }
    }
}
</code>```

The log say the error happened when it executing publications ('maven') I wonder where I did wrong?

答:
This doesn't really solve the initial error, but I managed to find a workaround that satisfy my need without relying on Artifactory Gradle Plugin.

So instead of relying on gradle plugin, I found out it is far easier to just call the artifactory API directly :
https://www.jfrog.com/confluence/display/RTF/Artifactory+REST+API

```<code>task deployArtifactory{
        dependsOn assembleProject
        doLast {
            def response = ['curl', '-u', "user:password", '-X', 'PUT',
    "http://my.artifactory/artifactory/MyRepository/my.group.id/artifactId/version/artifactId.file_extension",
'-T', "path/to/file.jar"].execute()
            def json = new JsonSlurper().parseText(response.text)
            println(json)
        }
    }
</code>```

Note that this solution might depends on the availability of curl in the system, but it is good enough for my need.

Body:
I'm trying to publish an artifact to jfrog artifactory using gradle. I figured out that Gradle Actifactory Plugin might be the one I need. Unfortunately, upon calling gradlew -i artifactoryPublish an error is thrown :

    Exception is:
org.gradle.internal.event.ListenerNotificationException: Failed to notify build listener.
        at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:86)
        at org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:324)
        at org.gradle.internal.event.BroadcastDispatch$CompositeDispatch.dispatch(BroadcastDispatch.java:234)
        at org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:140)
        at org.gradle.internal.event.ListenerBroadcast.dispatch(ListenerBroadcast.java:37)
        at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
        at com.sun.proxy.$Proxy17.projectsEvaluated(Unknown Source)
        at org.gradle.initialization.DefaultGradleLauncher.projectsEvaluated(DefaultGradleLauncher.java:329)
        at org.gradle.initialization.DefaultGradleLauncher.access$1200(DefaultGradleLauncher.java:46)
        at org.gradle.initialization.DefaultGradleLauncher$ConfigureBuild.run(DefaultGradleLauncher.java:252)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
        at org.gradle.initialization.DefaultGradleLauncher.configureBuild(DefaultGradleLauncher.java:167)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:126)
        at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:109)
        at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:78)
        at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:75)
        at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:152)
        at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:100)
        at org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:75)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
        at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$1.run(RunAsBuildOperationBuildActionRunner.java:43)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
        at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
        at org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:47)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:30)
        at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
        at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:80)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:53)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:57)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:32)
        at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
        at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
        at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
        at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
        at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:69)
        at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:30)
        at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:59)
        at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:44)
        at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:45)
        at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:30)
        at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
        at org.gradle.util.Swapper.swap(Swapper.java:38)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:82)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:122)
        at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
        at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:295)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
        at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
        at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: java.lang.BootstrapMethodError: java.lang.NoClassDefFoundError:
        at org.jfrog.gradle.plugin.artifactory.task.helper.TaskHelperPublications.dependOn(TaskHelperPublications.java:171)
        at org.jfrog.gradle.plugin.artifactory.task.helper.TaskHelperPublications.checkDependsOnArtifactsToPublish(TaskHelperPublications.java:159)
        at org.jfrog.gradle.plugin.artifactory.task.ArtifactoryTask.checkDependsOnArtifactsToPublish(ArtifactoryTask.java:72)
        at org.jfrog.gradle.plugin.artifactory.task.ArtifactoryTask.publications(ArtifactoryTask.java:110)
        at org.gradle.internal.metaobject.BeanDynamicObject$MetaClassAdapter.invokeMethod(BeanDynamicObject.java:479)
        at org.gradle.internal.metaobject.BeanDynamicObject.tryInvokeMethod(BeanDynamicObject.java:191)
        at org.gradle.internal.metaobject.CompositeDynamicObject.tryInvokeMethod(CompositeDynamicObject.java:98)
        at org.gradle.internal.metaobject.MixInClosurePropertiesAsMethodsDynamicObject.tryInvokeMethod(MixInClosurePropertiesAsMethodsDynamicObject.java:30)
        at org.gradle.internal.metaobject.ConfigureDelegate.invokeMethod(ConfigureDelegate.java:57)
        at build_84hxiqveouy516qtdye6ljohx$_run_closure2$_closure14$_closure16.doCall(D:\GIT_ROOT\RND\tools\GeneratorV2\build.gradle:50)
        at org.gradle.api.internal.ClosureBackedAction.execute(ClosureBackedAction.java:71)
        at org.gradle.util.ConfigureUtil.configureTarget(ConfigureUtil.java:160)
        at org.gradle.util.ConfigureUtil.configureSelf(ConfigureUtil.java:136)
        at org.gradle.api.internal.AbstractTask.configure(AbstractTask.java:634)
        at org.gradle.api.internal.AbstractTask.configure(AbstractTask.java:86)
        at org.gradle.util.ConfigureUtil.configure(ConfigureUtil.java:104)
        at org.jfrog.gradle.plugin.artifactory.task.ArtifactoryTask.projectEvaluated(ArtifactoryTask.java:216)
        at org.jfrog.gradle.plugin.artifactory.task.ArtifactoryTask$projectEvaluated$0.call(Unknown Source)
        at org.jfrog.gradle.plugin.artifactory.extractor.listener.ProjectsEvaluatedBuildListener.evaluate(ProjectsEvaluatedBuildListener.groovy:114)
        at org.jfrog.gradle.plugin.artifactory.extractor.listener.ProjectsEvaluatedBuildListener$_projectsEvaluated_closure8.doCall(ProjectsEvaluatedBuildListener.groovy:197)
        at org.jfrog.gradle.plugin.artifactory.extractor.listener.ProjectsEvaluatedBuildListener.projectsEvaluated(ProjectsEvaluatedBuildListener.groovy:195)
        at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
        at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
        at org.gradle.internal.event.DefaultListenerManager$ListenerDetails.dispatch(DefaultListenerManager.java:371)
        at org.gradle.internal.event.DefaultListenerManager$ListenerDetails.dispatch(DefaultListenerManager.java:353)
        at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:58)
        at org.gradle.internal.event.DefaultListenerManager$EventBroadcast$ListenerDispatch.dispatch(DefaultListenerManager.java:341)
        at org.gradle.internal.event.DefaultListenerManager$EventBroadcast$ListenerDispatch.dispatch(DefaultListenerManager.java:328)
        at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:42)
        at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:230)
        at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:149)
        at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:58)
        ... 76 more
Caused by: java.lang.NoClassDefFoundError:
        ... 108 more

Here is the relevan configuration :

publishing {
    publications {
        maven(MavenPublication) {
            groupId    = 'com.artifact'
            artifactId = 'Artifact'
            version    = '1.0'

            //from components.java
            artifact "target/artifact.jar"
        }
    }
}

artifactory{
    contextUrl = 'http://my.artifactory/artifactory'
    publish{
        contextUrl = 'http://my.artifactory/artifactory'
        repository{
            repoKey  = 'myrepo'
            username = 'lalala'
            password = 'isthisapassword'
        }
        defaults {
            publications ('maven')
        }
    }
}

The log say the error happened when it executing publications ('maven') I wonder where I did wrong?

Body:
This doesn't really solve the initial error, but I managed to find a workaround that satisfy my need without relying on Artifactory Gradle Plugin.

So instead of relying on gradle plugin, I found out it is far easier to just call the artifactory API directly :
https://www.jfrog.com/confluence/display/RTF/Artifactory+REST+API

task deployArtifactory{
        dependsOn assembleProject
        doLast {
            def response = ['curl', '-u', "user:password", '-X', 'PUT',
    "http://my.artifactory/artifactory/MyRepository/my.group.id/artifactId/version/artifactId.file_extension",
'-T', "path/to/file.jar"].execute()
            def json = new JsonSlurper().parseText(response.text)
            println(json)
        }
    }

Note that this solution might depends on the availability of curl in the system, but it is good enough for my need.


问:
.NetCore 2.2 Web Api with windows authentication returns 401 from other domains
Before I write this I spent a lot of time searching and trying a lot of things, but nothing worked. It's a .NetCore 2.2 Web Api and I'm consuming it from Angular 8 application.

If I call the web api from the same domain it works fine.

If I call the web api from other domain (or localhost) it returns 401 (Unauthorized).

If I call the web api from other domain (or localhost) with windows authentication disabled - it works fine (so CORS is properly configured).

In my launchSettings.json I have:

```<code>  "iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
</code>```

In my web.config i have:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <httpProtocol>
        <customHeaders>
          <add name="Access-Control-Allow-Origin" value="*" />
        </customHeaders>
      </httpProtocol>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" />
      </handlers>
      <aspNetCore processPath="%LAUNCHER_PATH%" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" hostingModel="InProcess" arguments="%LAUNCHER_ARGS%" />
      <security>
        <authentication>
           <anonymousAuthentication enabled="false" />
           <windowsAuthentication enabled="true" />
        </authentication>
      </security>
    </system.webServer>
  </location>
</configuration>
</code>```

In IIS i have Windowsauthentication enabled and Anonymousauthentication disabled.

In my Startup.cs I have:

```<code>public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(IISDefaults.AuthenticationScheme);
        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
            builder =>
            {
               builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader()
               .AllowCredentials();
            });
        });

        services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
     }
</code>```

and

```<code>    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseAuthentication();
        app.UseCors("CorsPolicy");
        app.UseMvc();
    }
</code>```

What I'm missing? Any ideas on this?

答:
Changing the order of the middleware might be all you need to fix this issue--see this Microsoft source on Middleware Order which specifies that UseCors() should be added before UseAuthentication().

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors("CorsPolicy");
    app.UseAuthentication();
    app.UseMvc();
}
```

This answer may be too late to help the OP, but maybe it will help someone later.

Body:
Before I write this I spent a lot of time searching and trying a lot of things, but nothing worked. It's a .NetCore 2.2 Web Api and I'm consuming it from Angular 8 application.

If I call the web api from the same domain it works fine.

If I call the web api from other domain (or localhost) it returns 401 (Unauthorized).

If I call the web api from other domain (or localhost) with windows authentication disabled - it works fine (so CORS is properly configured).

In my launchSettings.json I have:

  "iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,

In my web.config i have:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <httpProtocol>
        <customHeaders>
          <add name="Access-Control-Allow-Origin" value="*" />
        </customHeaders>
      </httpProtocol>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" />
      </handlers>
      <aspNetCore processPath="%LAUNCHER_PATH%" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" hostingModel="InProcess" arguments="%LAUNCHER_ARGS%" />
      <security>
        <authentication>
           <anonymousAuthentication enabled="false" />
           <windowsAuthentication enabled="true" />
        </authentication>
      </security>
    </system.webServer>
  </location>
</configuration>

In IIS i have Windowsauthentication enabled and Anonymousauthentication disabled.

In my Startup.cs I have:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(IISDefaults.AuthenticationScheme);
        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
            builder =>
            {
               builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader()
               .AllowCredentials();
            });
        });

        services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
     }

and

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseAuthentication();
        app.UseCors("CorsPolicy");
        app.UseMvc();
    }

What I'm missing? Any ideas on this?

Body:
Changing the order of the middleware might be all you need to fix this issue--see this Microsoft source on Middleware Order which specifies that UseCors() should be added before UseAuthentication().

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors("CorsPolicy");
    app.UseAuthentication();
    app.UseMvc();
}

This answer may be too late to help the OP, but maybe it will help someone later.


问:
Possible to '--eval' with javascript file?
is it possible to call Node.js interpreter to evaluate a javascript file instead of script string on the CMD with the '--eval' parameter? I am using a Windows machine for development, but I hope what CMD envirement shouldn't really matter much.

What I am trying to achieve is combine two separate javascript files, so that the code (class, object, method, functions) in the first javascript file can be shared with code in the second javascript file, as if they are in a single file.

I know it's sounds like I should be using module. But my problem is not exactly 'how to design my code base so that I can have separate JS files'. So if you want to know way, please bear with me: I have a few small projects, the code were written by someone else which often is using modules internal already, but not exposed as library. But I want extent its functions. The code works fine for it's purpose so there is normally no need for me modified those code at all. So what's happens often is I only need write a few lines of code based on the existing code, reusing the majority of the code, which might already doing require already. And once I have a working solution, I start over, trying different approach, which may or may not end up as a working solution. So I potentially have a few new files in the projects.

The main things is that I want separate my code from the existing code. I think the sensible ways to do it is just code the existing code I need and import the modules I need into my code again. Or if I insist, redesign the existing code to be modules so I can easily import the function to my need. But I think I like the idea of separating my code, but do not expose existing code to a library which might be end up need be res-structured as well. So yes, I don't think modules is answer for all the situations.

To achieve what I wan I think the best solution is possible using --eval in Node.js to load the code in the first javascript file. But I just can't get it working. The alternative is eval(require("fs").readFileSync(".\\Code\\baseCode.js", "utf8"));, but I think the --eval in CMD is slightly better as I can then put the full path js file into a launch file in VS code.

Update

Latest update, it occurred to me that Windows CMD might broken or NodeJs not working that well with Windows CMD, so I tried integrated terminal in VS Code and node --eval "$(cat first.js second.js) works as expected.

Solution I tried in Windows CMD but doesn't working

```<code>D:\Test\JSNodeJSEval>node --eval "$(cat first.js second.js)"
[eval]:1
$(cat first.js second.js)
  ^^^

SyntaxError: missing ) after argument list
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Object.<anonymous> ([eval]-wrapper:6:22)
    at Module._compile (module.js:652:30)
    at evalScript (bootstrap_node.js:466:27)
    at startup (bootstrap_node.js:167:9)
    at bootstrap_node.js:612:3

D:\Test\JSNodeJSEval>node --eval "$(< first.js second.js)"
[eval]:1
$(< first.js second.js)
  ^

SyntaxError: Unexpected token <
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Object.<anonymous> ([eval]-wrapper:6:22)
    at Module._compile (module.js:652:30)
    at evalScript (bootstrap_node.js:466:27)
    at startup (bootstrap_node.js:167:9)
    at bootstrap_node.js:612:3
</code>```

答:
If you really wanted to you could just output the two files in order and evaluate the string. Example:

```<code>echo 'var a = 1;' > first.js
echo 'console.log(a);' > second.js

node --eval "$(cat first.js second.js)"
1
</code>```

Of course, programming with implicit global variables is something we try not to do, especially when import a from './first.js';  is so easy to write and has more benefits.

Body:
is it possible to call Node.js interpreter to evaluate a javascript file instead of script string on the CMD with the '--eval' parameter? I am using a Windows machine for development, but I hope what CMD envirement shouldn't really matter much.

What I am trying to achieve is combine two separate javascript files, so that the code (class, object, method, functions) in the first javascript file can be shared with code in the second javascript file, as if they are in a single file.

I know it's sounds like I should be using module. But my problem is not exactly 'how to design my code base so that I can have separate JS files'. So if you want to know way, please bear with me: I have a few small projects, the code were written by someone else which often is using modules internal already, but not exposed as library. But I want extent its functions. The code works fine for it's purpose so there is normally no need for me modified those code at all. So what's happens often is I only need write a few lines of code based on the existing code, reusing the majority of the code, which might already doing require already. And once I have a working solution, I start over, trying different approach, which may or may not end up as a working solution. So I potentially have a few new files in the projects.

The main things is that I want separate my code from the existing code. I think the sensible ways to do it is just code the existing code I need and import the modules I need into my code again. Or if I insist, redesign the existing code to be modules so I can easily import the function to my need. But I think I like the idea of separating my code, but do not expose existing code to a library which might be end up need be res-structured as well. So yes, I don't think modules is answer for all the situations.

To achieve what I wan I think the best solution is possible using --eval in Node.js to load the code in the first javascript file. But I just can't get it working. The alternative is eval(require("fs").readFileSync(".\\Code\\baseCode.js", "utf8"));, but I think the --eval in CMD is slightly better as I can then put the full path js file into a launch file in VS code.

Update

Latest update, it occurred to me that Windows CMD might broken or NodeJs not working that well with Windows CMD, so I tried integrated terminal in VS Code and node --eval "$(cat first.js second.js) works as expected.

Solution I tried in Windows CMD but doesn't working

D:\Test\JSNodeJSEval>node --eval "$(cat first.js second.js)"
[eval]:1
$(cat first.js second.js)
  ^^^

SyntaxError: missing ) after argument list
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Object.<anonymous> ([eval]-wrapper:6:22)
    at Module._compile (module.js:652:30)
    at evalScript (bootstrap_node.js:466:27)
    at startup (bootstrap_node.js:167:9)
    at bootstrap_node.js:612:3

D:\Test\JSNodeJSEval>node --eval "$(< first.js second.js)"
[eval]:1
$(< first.js second.js)
  ^

SyntaxError: Unexpected token <
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Object.<anonymous> ([eval]-wrapper:6:22)
    at Module._compile (module.js:652:30)
    at evalScript (bootstrap_node.js:466:27)
    at startup (bootstrap_node.js:167:9)
    at bootstrap_node.js:612:3

Body:
If you really wanted to you could just output the two files in order and evaluate the string. Example:

echo 'var a = 1;' > first.js
echo 'console.log(a);' > second.js

node --eval "$(cat first.js second.js)"
1

Of course, programming with implicit global variables is something we try not to do, especially when import a from './first.js';  is so easy to write and has more benefits.


问:
Bypass a rule in web.config file based on incoming IP address
I have been trying solutions for 6 hours to get this right but cannot find anything on either stack or microsoft's dev blogs. I am trying to force an HTTPS redirect from all external calls to my website while still going to the HTTP site when the website is accessed via an internal call, in this case by use of the IP address 192.168.8.68 in the URL bar of the browser. This worked perfectly until we installed an SSL certificate yesterday and implemented the following redirect rule:

```<code><rule name="Redirect to HTTPS" patternSyntax="Wildcard" stopProcessing="true">
    <match url="*" />
    <conditions logicalGrouping="MatchAny">
        <add input="{HTTPS}" pattern="OFF" />
    </conditions>
    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" appendQueryString="false" />
</rule>
</code>```

What I would like to know is, how would i bypass this if the incoming IP Address has the form 192.168.8.*? Adding specific iPs in regex causes the website to fail to load with a "Too many redirects error". I have already looked at the following list of questions in an attempt to solve this problem:

https://forums.iis.net/t/1166994.aspx?Rewrite+Redirection+for+only+external+users

IIS 7.5 redirect certain requests to other server using ip address

IIS | Block page specific url except for specific internal IP address

https://docs.secureauth.com/display/KBA/Use+URL+Rewrite+for+IP+Restrictions

Two instances of the same Website on IIS with different web.config (two different databases)

Single Website Directory / Multiple IIS Websites (Multiple web.config files)

答:
You could use this rule to bypass the request from ip 192.168.8.*.</p>

```<code><rule name="Redirect to HTTPS" enabled="true" patternSyntax="ECMAScript" stopProcessing="true">
    <match url=".*" />
    <conditions logicalGrouping="MatchAny">
                        <add input="{HTTPS}" pattern="OFF" />
                        <add input="{REMOTE_ADDR}" pattern="192\.168\.8\.[0-9]+" negate="true" />
    </conditions>
    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" appendQueryString="false" redirectType="Permanent" />
</rule>
</code>```

Body:
I have been trying solutions for 6 hours to get this right but cannot find anything on either stack or microsoft's dev blogs. I am trying to force an HTTPS redirect from all external calls to my website while still going to the HTTP site when the website is accessed via an internal call, in this case by use of the IP address 192.168.8.68 in the URL bar of the browser. This worked perfectly until we installed an SSL certificate yesterday and implemented the following redirect rule:

<rule name="Redirect to HTTPS" patternSyntax="Wildcard" stopProcessing="true">
    <match url="*" />
    <conditions logicalGrouping="MatchAny">
        <add input="{HTTPS}" pattern="OFF" />
    </conditions>
    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" appendQueryString="false" />
</rule>

What I would like to know is, how would i bypass this if the incoming IP Address has the form 192.168.8.*? Adding specific iPs in regex causes the website to fail to load with a "Too many redirects error". I have already looked at the following list of questions in an attempt to solve this problem:

https://forums.iis.net/t/1166994.aspx?Rewrite+Redirection+for+only+external+users

IIS 7.5 redirect certain requests to other server using ip address

IIS | Block page specific url except for specific internal IP address

https://docs.secureauth.com/display/KBA/Use+URL+Rewrite+for+IP+Restrictions

Two instances of the same Website on IIS with different web.config (two different databases)

Single Website Directory / Multiple IIS Websites (Multiple web.config files)

Body:
You could use this rule to bypass the request from ip 192.168.8.*.

<rule name="Redirect to HTTPS" enabled="true" patternSyntax="ECMAScript" stopProcessing="true">
    <match url=".*" />
    <conditions logicalGrouping="MatchAny">
                        <add input="{HTTPS}" pattern="OFF" />
                        <add input="{REMOTE_ADDR}" pattern="192\.168\.8\.[0-9]+" negate="true" />
    </conditions>
    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" appendQueryString="false" redirectType="Permanent" />
</rule>


问:
Equal Sign and Type Mismatch
When working with the standard widget toolkit (SWT), I usually use something like this to define my GridLayout:

```<code>layout.marginTop = layout.marginBottom =
    layout.marginLeft = layout.marginRight =
        layout.horizontalSpacing = layout.verticalSpacing = 20
</code>```

It works in java but not in scala.
It gives me type mismatch; Found: Unit Required: Int.

So how can this solve it?

答:
You cannot do this in one line in scala because the result type of an assignment expression (e.g. a = b) is Unit. You'd have to have 6 separate calls:

```<code>layout.marginTop = 20
layout.marginBottom = 20
... etc
</code>```

Why is the result type of an assignment Unit and nmot the assigned value? I believe this was chosen for performance reasons as outlined in this question.

There is a related question on assignment which points out that at declaration site, it is possible via:

```<code>val a, b, c = X
</code>```

Title: Equal Sign and Type Mismatch

Body:
When working with the standard widget toolkit (SWT), I usually use something like this to define my GridLayout:

layout.marginTop = layout.marginBottom =
    layout.marginLeft = layout.marginRight =
        layout.horizontalSpacing = layout.verticalSpacing = 20

It works in java but not in scala.
It gives me type mismatch; Found: Unit Required: Int.

So how can this solve it?

Body:
You cannot do this in one line in scala because the result type of an assignment expression (e.g. a = b) is Unit. You'd have to have 6 separate calls:

layout.marginTop = 20
layout.marginBottom = 20
... etc

Why is the result type of an assignment Unit and nmot the assigned value? I believe this was chosen for performance reasons as outlined in this question.

There is a related question on assignment which points out that at declaration site, it is possible via:

val a, b, c = X


问:
Is it posible to implement functions that use non blocking setTimeout synchronically?
I wonder if it is possible to call these 2 IIF synchronically that they produce at the end something like that?

```<code>######
#####
####
###
##
#
#
##
###
####
#####
###### ?
</code>```

the functions below do delayed console log. The idea is to console log with some delay row by row.

```<code> (function whileLoop(n) {
        setTimeout(function () {
            let hashArr = Array.apply(null, Array(n)).map(() => {
                return hashSymbol
            });
            console.log(hashArr);
            if (--n) whileLoop(n);
        }, 2000)
    })(6);

    (function whileLoop(n, m) {
        setTimeout(function () {
            let hashArr = Array.apply(null, Array(n)).map(() => {
                return hashSymbol
            });
            console.log(hashArr);
            if (n < m) {
                ++n;
                whileLoop(n, m);
            }
        }, 2000)
    })(1, 6);
</code>```

答:
In order for you to display it one by one, you need to use async await.
 Please check here: https://javascript.info/async-await

 const row = 6;
    (async() => {
   for (let r = 1;r < row * 2; r++) {
     await displayAsync('#'.repeat((r >= 7 ? (r % 6) : row - r ) + 1));
   }
})();

function displayAsync(str) {
   return new Promise((resolve, reject) => {
      setTimeout(()=> {
       console.log(str);
       resolve(null);
      }, 1000);
   });
}```

Body:
I wonder if it is possible to call these 2 IIF synchronically that they produce at the end something like that?

######
#####
####
###
##
#
#
##
###
####
#####
###### ?

the functions below do delayed console log. The idea is to console log with some delay row by row.

 (function whileLoop(n) {
        setTimeout(function () {
            let hashArr = Array.apply(null, Array(n)).map(() => {
                return hashSymbol
            });
            console.log(hashArr);
            if (--n) whileLoop(n);
        }, 2000)
    })(6);

    (function whileLoop(n, m) {
        setTimeout(function () {
            let hashArr = Array.apply(null, Array(n)).map(() => {
                return hashSymbol
            });
            console.log(hashArr);
            if (n < m) {
                ++n;
                whileLoop(n, m);
            }
        }, 2000)
    })(1, 6);


问:
Gatsby - How to set ENABLE_GATSBY_REFRESH_ENDPOINT to true
To enable /__refresh end point, I have to set ENABLE_GATSBY_REFRESH_ENDPOINT to true, but I don't know how to add environment variables to gatsby. How can I do that?</p>

答:
In the root of your project, you'll want to create a .env.development file if you don't have one already and add the following:

```<code>ENABLE_GATSBY_REFRESH_ENDPOINT=true
</code>```

You will also want to add that file to your project's .gitignore, it's good practice to not commit .env files to source control. Gatsby outlines how to use environment variables here.

Body:
In the root of your project, you'll want to create a .env.development file if you don't have one already and add the following:

ENABLE_GATSBY_REFRESH_ENDPOINT=true

You will also want to add that file to your project's .gitignore, it's good practice to not commit .env files to source control. Gatsby outlines how to use environment variables here.


问:
Segmentation Fault for a Program that Indexes Words from a File
I am getting a segmentation fault for a C program that first reads the characters of a given file, identifies words, indexes words, and prints the first word. I have been troubleshooting for a long time but cannot seem to find what the error is.</p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <string.h>

int main (int argc, char *argv[])
{
    if (argc != 2)
    {
        printf("Usage: ./test15 text\n");
        return 1;
    }
    char *file = argv[1];
    FILE *ptr = fopen(file, "r");
    char ch;
    int i = 0;
    int k = 0;
    int j = 0;
    char *text = malloc(sizeof(char));
    string word[k];
    while ((ch = fgetc(ptr)) != EOF)
    {
        text[i] = ch;
        if (ch == ' ')
        {
            for (int l = j; l < i; l++)
            {
                strcat(word[k], &text[l]);
            }
            k++;
            j = i;
        }
        i++;
    }
    printf("%s\n", word[0]);
    return 0;
}
</code>```

答:
Just like @Zen said, a SEGFAULT will occur if you try to access a memory location you are not allowed to or not allocated.

Your program terminates just after the first iteration because i becomes 1 at that moment and text[1] becomes inaccessible because text was allocated the size of a single character only:
char *text = malloc(sizeof(char)); here.

Yet, I have not checked your algorithm right now so I am only providing an initial observation. If any errors still pop up, feel free to post on this thread here.

Best.

Body:
I am getting a segmentation fault for a C program that first reads the characters of a given file, identifies words, indexes words, and prints the first word. I have been troubleshooting for a long time but cannot seem to find what the error is.

#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <string.h>

int main (int argc, char *argv[])
{
    if (argc != 2)
    {
        printf("Usage: ./test15 text\n");
        return 1;
    }
    char *file = argv[1];
    FILE *ptr = fopen(file, "r");
    char ch;
    int i = 0;
    int k = 0;
    int j = 0;
    char *text = malloc(sizeof(char));
    string word[k];
    while ((ch = fgetc(ptr)) != EOF)
    {
        text[i] = ch;
        if (ch == ' ')
        {
            for (int l = j; l < i; l++)
            {
                strcat(word[k], &text[l]);
            }
            k++;
            j = i;
        }
        i++;
    }
    printf("%s\n", word[0]);
    return 0;
}