Uno scrittoio digitale …

6 febbraio 2017

TestPyramid

Archiviato in: code — Tag:, — admin @ 09:34

remember what MF says

29 dicembre 2016

NPE Java8 Stream

Archiviato in: code — Tag:, , — admin @ 17:40

Volendo convertire una lista in una mappa … c’è un metodo sicuramente sbagliato:

	final Map data = new HashMap<>();
	data.put(1, "uno");

	System.out.println("1.");
	System.out.println(
		IntStream.rangeClosed(1, 2).boxed()
			.collect(
				HashMap::new,
				(map, i) -> map.put(i, data.get(i)),
				HashMap::putAll
			)
	);

	System.out.println("2.");
	//questa implementazione si basa sul metodo HashMap.merge (che lancia exception)
	System.out.println(
		IntStream.rangeClosed(1, 2).boxed()
			.collect(Collectors.toMap(
				i -> i, i -> data.get(i)
			))
	);

ottengo a console:

1.
{1=uno, 2=null}
2.
Exception in thread "main" java.lang.NullPointerException
	at java.util.HashMap.merge(HashMap.java:1224)
	at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
	at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
	at java.util.stream.IntPipeline$4$1.accept(IntPipeline.java:250)
	at java.util.stream.Streams$RangeIntSpliterator.forEachRemaining(Streams.java:114)
	at java.util.Spliterator$OfInt.forEachRemaining(Spliterator.java:693)
	at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
	at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
	at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
	at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
	at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
	at com.contactlab.at.Errors.main(Errors.java:28)

7 luglio 2016

java mysql driver

Archiviato in: code, java — Tag:, — admin @ 10:10

avoid OutOfMemory with simulated streaming:


            conn = DriverManager.getConnection(ds.getJdbcUrl(), ds.getUser(), ds.getPassword());
            stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
            stmt.setFetchSize(Integer.MIN_VALUE);

24 maggio 2016

msgpack

Archiviato in: code — Tag:, , , , — admin @ 09:18

It’s like JSON. but fast and small.

14 aprile 2016

Classic programmer paintings

Archiviato in: code — Tag:, — admin @ 14:03

http://classicprogrammerpaintings.tumblr.com/

17 luglio 2015

js

Archiviato in: code, web — Tag:, — admin @ 22:55

to read …

promisejs
browserify
amcharts

25 giugno 2015

Simple decorator in ruby

Archiviato in: code — Tag:, , , — admin @ 15:15

require 'securerandom'

class EventQueue
  attr_accessor :messages

  def initialize
    @messages = []
  end

  def enqueue(event, args, state)
    @messages << [event, args, state]
  end
end

module Notifier
  def notify_on(event)
    guid = SecureRandom.uuid
    puts "#{guid} ==> #{event}"

    define_method("#{guid}") do |*args|
      @event_queue.enqueue(event, args, :start)
      begin
        result = __send__("#{guid}_#{event}", *args)
      ensure
        @event_queue.enqueue(event, args, :end)
      end
      result
    end

    alias_method "#{guid}_#{event}", event
    alias_method event, "#{guid}"
  end
end

class Store
  extend Notifier

  def initialize(event_queue)
    @event_queue = event_queue
  end

  def order_purchase(user, items)
    ## @event_queue.enqueue(__method__, [user, items], :start)
    do_stuff
    ## @event_queue.enqueue(__method__, [user, items], :end)
  end

  def decrease_inventory(items)
    ## @event_queue.enqueue(__method__, [items], :start)
    do_stuff
    ## @event_queue.enqueue(__method__, [items], :end)
  end

  notify_on :order_purchase
  notify_on :decrease_inventory      

  private

  def do_stuff
    puts "called from #{caller[0]}"
  end
end

puts "#" * 100
queue = EventQueue.new
store = Store.new(queue)
store.order_purchase("alan", ["book", "pen"])
puts "#" * 100
puts "messages = #{queue.messages.inspect}"
puts "#" * 100
puts Store.new(queue).methods.sort - Object.methods.sort

Output:

d02ad4da-a5ec-4ae8-b5ed-53845dd2b391 ==> order_purchase
56df2c28-b927-42d2-8e19-07d115b2c818 ==> decrease_inventory
####################################################################################################
called from /home/alan/Dropbox/clab/Aptana Studio 3 Workspace/2016-06-18/decorator.rb:188:in `d02ad4da-a5ec-4ae8-b5ed-53845dd2b391_order_purchase'
####################################################################################################
messages = [[:order_purchase, ["alan", ["book", "pen"]], :start], [:order_purchase, ["alan", ["book", "pen"]], :end]]
####################################################################################################
56df2c28-b927-42d2-8e19-07d115b2c818
56df2c28-b927-42d2-8e19-07d115b2c818_decrease_inventory
d02ad4da-a5ec-4ae8-b5ed-53845dd2b391
d02ad4da-a5ec-4ae8-b5ed-53845dd2b391_order_purchase
decrease_inventory
order_purchase


16 giugno 2015

Byteman

Archiviato in: code, java — Tag:, , — admin @ 20:59

Byteman is a byte code manipulation and injection tool kit. It allows us to intercept and replace arbitrary parts of Java code to make it behave differently or break it (on purpose):

> get all threads stuck in a certain place and let them continue at the same time (hello race condition)
> throw Exceptions at unexpected locations
> tracing through your code during execution
>change return values

and a lot more things.

19 aprile 2015

Measure Anything, Measure Everything

Archiviato in: code — Tag:, — admin @ 16:01

statsd

13 aprile 2015

Run your code online

Archiviato in: code — Tag: — admin @ 10:14

http://runnable.com/

Fatto veramente bene e molto semplice da usare.

15 gennaio 2015

A Visual Explanation of SQL Joins

Archiviato in: code — Tag:, — admin @ 18:36

Visto che me le scordo sempre … qua c’è un modo visuale per ricordarsi delle diverse JOIN.

JPA 2.*

Archiviato in: code, java — admin @ 00:41

Solo qualche link utile … a capirci qualcosa :D

guice and jpa
example
wiki

6 novembre 2014

Ruby on Rails application server solution

Archiviato in: code, rails — Tag:, — admin @ 17:24

Giusto qualche link utile per capire le alternative:

phusion-passenger-for-dummies
ruby-on-rails-server-options
rack

10 ottobre 2014

Jcabi

Archiviato in: code, java — Tag:, , — admin @ 17:42

hanno sviluppato un casino di progetti … come si può vedere qua

31 marzo 2014

Eclipse Inside Proxy

Archiviato in: code, java — admin @ 21:37

Cosa è … e come si usa si trova QUI

17 luglio 2013

ThreadLocal

Archiviato in: java, oracle — Tag:, , , — admin @ 22:22

The javadoc says this:

“Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

If your application or (if you are talking about request threads) container uses a thread pool that means that threads don’t die. If necessary, you would need to deal with the thread locals yourself. The only clean way to do this is to call the ThreadLocal.remove() method.

There are two reasons you might want to clean up thread locals for threads in a thread pool:

to prevent memory (or hypothetically resource) leaks, or
to prevent accidental leakage of information from one request to another via thread locals.

Thread local memory leaks should not normally be a major issue with bounded thread pools since any thread locals are likely to get overwritten eventually; i.e. when the thread is reused. However, if you make the mistake of creating a new ThreadLocal instances over and over again (instead of using a static variable to hold a singleton instance), the thread local values won’t get overwritten, and will accumulate in each thread’s threadlocals map. This could result in a serious leak.

private void cleanThreadLocals() {
        try {
            // Get a reference to the thread locals table of the current thread
            Thread thread = Thread.currentThread();
            Field threadLocalsField = Thread.class.getDeclaredField("threadLocals");
            threadLocalsField.setAccessible(true);
            Object threadLocalTable = threadLocalsField.get(thread);

            // Get a reference to the array holding the thread local variables inside the
            // ThreadLocalMap of the current thread
            Class threadLocalMapClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap");
            Field tableField = threadLocalMapClass.getDeclaredField("table");
            tableField.setAccessible(true);
            Object table = tableField.get(threadLocalTable);

            // The key to the ThreadLocalMap is a WeakReference object. The referent field of this object
            // is a reference to the actual ThreadLocal variable
            Field referentField = Reference.class.getDeclaredField("referent");
            referentField.setAccessible(true);

            for (int i=0; i < Array.getLength(table); i++) {
                // Each entry in the table array of ThreadLocalMap is an Entry object
                // representing the thread local reference and its value
                Object entry = Array.get(table, i);
                if (entry != null) {
                    // Get a reference to the thread local object and remove it from the table
                    ThreadLocal threadLocal = (ThreadLocal)referentField.get(entry);
                    threadLocal.remove();
                }
            }
        } catch(Exception e) {
            // We will tolerate an exception here and just log it
            throw new IllegalStateException(e);
        }
    }

A good place to do such cleanup is ServletRequestListener.requestDestroyed().

11 luglio 2013

codepen

Archiviato in: code, sapere è potere — admin @ 22:57

html … css … js framework … on codepen

3 giugno 2013

Da tenere sott’occhio

Archiviato in: code — admin @ 22:22

mapstruct
dagger

enjoy

4 marzo 2013

Il codice muta ed io lo eSeguo

Archiviato in: code, java — Tag:, — admin @ 22:53

pitest && stackoverflow.

7 dicembre 2012

Google

Archiviato in: code — Tag: — admin @ 19:55

my-other-computer-is-a-data-center

Articoli precedenti »

Funziona con WordPress