martedì 7 febbraio 2017

Installazione e configurazione di apt-cacher-ng

In una LAN con più installazioni della stessa distribuzione Linux è utile, per risparmiare banda, l'installazione di un "package cacher" che permetta di scaricare una sola volta ogni pacchetto. Il primo pc che necessita di un pacchetto lo farà scaricare al cacher il quale lo metterà a disposizione per gli altri. Per distribuzioni Debian o derivate (Ubuntu, Mint ...) uno dei software più diffusi è apt-cacher-ng, evoluzione di apt-cacher.

L'installazione nel server avviene con il consueto comando
sudo apt-get install apt-cacher-ng

Dopo l'installazione il software è già funzionante ma può essere configurato a piacimento agendo nel file di configurazione acng.conf, per modificarlo
sudo nano /etc/apt-cacher-ng/acng.conf

Uno dei parametri è la directory in cui viene memorizzata la cache, questa deve essere di proprietà dell'utente e del gruppo apt-cacher-ng. Per modificare la directory cambiare il parametro come segue:
CacheDir: /media/disk-500-A/cache/apt-cacher

e riavviare apt-cacher-ng con il comando:
sudo invoke-rc.d apt-cacher-ng restart

Per cambiare proprietario alla direcotry:
sudo chown -R apt-cacher-ng:apt-cacher-ng /media/disk-500-A/cache/apt-cacher


Nei client è necessario modificare la configurazione di apt per far sì che utilizzino il "package cacher".

Creare il file /etc/apt/apt.conf.d/01proxy con il comando
sudo nano /etc/apt/apt.conf.d/01proxy

con il seguente contenuto:
Acquire::http::Proxy "http://IP_DEL_SERVER:3142";
Acquire::http::Proxy {
        download.oracle.com DIRECT;
};
La prima riga indica l'ip del server, le altre servono per evitare che certe richieste vengano inviate al cacher, nel caso specifico il download dai server Oracle di Java non viene gestito dal cacher.

sabato 9 aprile 2011

Download di un file in Java

In Java per scaricare un file, ma più in generale per ottenere una risorsa identificata da un URL, è necessario:
  1. Istanziare un URL con l'indirizzo della risorsa. Il metodo più semplice è quello di utilizzare il costruttore della classe java.net.URL che ha come unico paramentro la stringa corrispondente all'indirizzo (riga 105 del codice d'esempio).
  2. Aprire l'inputStream corrispondente (riga 39).
  3. Allocare un java.io.BufferedInputStream (riga 43) corrispondente all'InputStream aperto in precedenza. Questa operazione, al pari della precedente, migliora le prestazioni limitando le chiamate di sistema alle funzioni di I/O
  4. Allocare un java.io.BufferedOutputStream (riga 46) corrispondente all'outputStream sul quale scrivere il contenuto della risorsa.
  5. Allocare un array di byte da usare come buffer per la copia dei dati. La dimensione del buffer va ponderata a seconda delle esigenze, tenendo conto che un buffer troppo piccolo limita le prestazioni mentre una dimensione troppo grande fa sì che tutto il contenuto rimanga in memoria (potrebbero sorgere problemi anche gravi come java.lang.OutOfMemoryError).
  6. Le righe 51 e 52 sono quelle in cui avviene la copia. Vengono infatti letti ad ogni iterazione un certo numero di byte (variabile count) dall'input e scritti nell'output.
  7. Le righe successive servono per chiudere le risorse allocate in precedenza, secondo il "dispose pattern"

Il secondo metodo alloca un java.io.FileOutputStream per implementare quello che sarà probabilmente l'utilizzo più diffuso del metodo precedente cioè il download su un file locale della risorsa desiderata.

Post correlati:
Download di un file in Java: codice d'esempio

Download di un file in Java: codice d'esempio


001  package com.blogspot.pilloledijava.download;
002  
003  import java.io.BufferedInputStream;
004  import java.io.BufferedOutputStream;
005  import java.io.File;
006  import java.io.FileOutputStream;
007  import java.io.IOException;
008  import java.io.InputStream;
009  import java.io.OutputStream;
010  import java.net.URL;
011  
012  /**
013    * Classe che implementa due metodi per scaricare la risorsa identificata da un
014    * URL su un outputstream o su un file
015    
016    @author pdj
017    
018    */
019  public class Downloader {
020  
021    /**
022     * Metodo che scrive su un java.io.OutputStream la risorsa identificata da
023     * un URL
024     
025     @param url
026     *            URL da scaricare
027     @param outputStream
028     *            outputstream di destinazione
029     @param bufferSize
030     *            numero di byte letti ad ogni iterazione
031     @throws IOException
032     *             potrebbe essere causata da problemi sia nella sorgente (ad
033     *             esempio url irraggiungibile) che nella destinazione (problemi
034     *             vari di I/O).
035     */
036    public static void download(final URL url, final OutputStream outputStream,
037        final int bufferSizethrows IOException {
038      // Url input stream
039      final InputStream inputStream = url.openStream();
040      try {
041        // I BufferedInputStream e BufferedOutputStream non sono necessari
042        // ma migliorano le performance
043        final BufferedInputStream bufferedInputStream = new BufferedInputStream(
044            inputStream);
045        try {
046          final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
047              outputStream);
048          try {
049            final byte[] buffer = new byte[bufferSize];
050            int count;
051            while ((count = bufferedInputStream.read(buffer)) 0) {
052              bufferedOutputStream.write(buffer, 0, count);
053            }
054  
055          finally {
056            bufferedOutputStream.close();
057          }
058        finally {
059          bufferedInputStream.close();
060        }
061      finally {
062        inputStream.close();
063      }
064    }
065  
066    /**
067     * Metodo che salva su un file su un java.io.File la risorsa identificata da
068     * un URL
069     
070     @param url
071     *            URL da scaricare
072     @param outputStream
073     *            outputstream di destinazione
074     @param bufferSize
075     *            numero di byte letti ad ogni iterazione
076     @throws IOException
077     *             potrebbe essere causata da problemi sia nella sorgente (ad
078     *             esempio url irraggiungibile) che nella destinazione (file già
079     *             esistente, problemi di permessi, ...).
080     */
081  
082    public static void download(final URL url, final File file,
083        final int bufferSizethrows IOException {
084      if (file.exists()) {
085        throw new IllegalArgumentException(file.getAbsolutePath()
086            " already exists");
087      }
088  
089      final FileOutputStream fileOutputStream = new FileOutputStream(file);
090      try {
091        download(url, fileOutputStream, bufferSize);
092        fileOutputStream.flush();
093      finally {
094        fileOutputStream.close();
095      }
096    }
097  
098    /**
099     * Metodo main usato per test
100     
101     @param args
102     */
103    public static void main(String[] args) {
104      try {
105        URL url = new URL("http://pilloledijava.blogspot.com/");
106        File f = new File("/home/pdj/Scrivania/blog.html");
107        download(url, f, 4096);
108      catch (Exception e) {
109        e.printStackTrace();
110      }
111    }
112  
113  }

Post correlati:
Download di un file in Java

martedì 24 agosto 2010

Mac address in Java

Con Java 6 è possibile ottenere anche il mac address di una scheda di rete (valore non ottenibile con Java 5 e precedenti).

Il codice è molto semplice:
con il metodo
java.net.NetworkInterface.getNetworkInterfaces();
si ottiene una Enumeration di tutte le interfacce di rete del sistema, la classe NetworkInterface presenta un metodo getHardwareAddress() che restituisce un array di byte corrispondente ad un generico indirizzo fisico della scheda (che corrisponde al mac address nel caso di schede ethernet).
Tale array può:
  • essere a null nel caso di interfacce di rete particolari come quella di loop (individuabile anche tramite il metodo isLoopback() ) o altre fittizie
  • avere esattamente 6 byte per le schede di rete
  • avere lunghezza diversa da 6 byte per altre interfacce non ethernet (es. Firewire ha 8 byte).

Il metodo byte2String trasforma l'array in una stringa nella tipica notazione esadecimale con i ":".

Post correlati:
Mac address in Java: codice d'esempio

Mac address in Java: codice d'esempio


import java.net.NetworkInterface;
import java.util.Enumeration;

public class SimpleMacAddress{

/** Lunghezza della stringa contente il mac address (6 * 2)numeri esadecimali + 5 separatori */
public final static int MAC_ADDRESS_STRING_LEN = 17;
/** Lunghezza dell'array di byte */
public final static int MAC_ADDRESS_BYTE_LEN = 6;
/** Base dei numeri per la stringa */
public final static int MAC_ADDRESS_RADIX = 16;

public static void main(String[] args)
{
try{
//Elenco di tutte le interfacce di rete
Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
while(e.hasMoreElements())
{
NetworkInterface ni = e.nextElement();
System.out.println("Name = " + ni.getName());
byte[] b = ni.getHardwareAddress();
System.out.println("hw = " + (b == null ? "null" : byte2String(b)));
System.out.println();
System.out.println("------------");
}

}catch(Exception e)
{
e.printStackTrace();
}
}

public static String byte2String(byte[] vByte)
{
if(vByte.length != MAC_ADDRESS_BYTE_LEN)
return "Mac address con lunghezza " + vByte.length;
StringBuilder sb = new StringBuilder();
int len = vByte.length;
for(int i = 0; i < len; i++)
{
//Utilizzo un int per evitare di avere numeri negativi
int a = vByte[i];
if(a < 0)
a = a + 256;
String s = Integer.toHexString(a/MAC_ADDRESS_RADIX) + "" + Integer.toHexString(a%MAC_ADDRESS_RADIX);
sb.append(s);
//tutte le coppie tranne l'ultima
if(i != len - 1)
sb.append(":");
}
return sb.toString();
}
}

Post correlati:
Mac address in Java

venerdì 25 giugno 2010

Apache Derby: query SQL

Derby: creazione del database e delle tabelle
  1. Dopo aver caricato il driver JDBC in maniera analoga a quanto accade con gli altri DBMS:

    Class.forName("org.apache.derby.jdbc.EmbeddedDriver");

    È necessario istanziare la connessione, questo non avviene impostando indirizzo ip e porta (non avrebbe senso) ma specificando la directory nella quale mettere il database:

    DriverManager.getConnection("jdbc:derby:" + path.getAbsolutePath() + ";create=true");

    nell'esempio viene specificato il path relativo della directory data/example; il parametro create=true/false indica come deve comportarsi Derby se nella directory non è presente un database.

  2. Ora il database può essere utilizzato via JDBC come qualunque altro DBMS, con l'accortezza di non aprire mai più connessioni contemporaneamente!
    Se si commentano le righe dalla 23 alla 28 e si esegue il programma, verrà creato un database (da Eclipse facendo un refresh nella cartella data si vedranno i nuovi file) con dentro una tabella "item".
Derby: query per inserimento e lettura dei dati
  1. Per ri-eseguire il programma è necessario commentare la riga 22 (altrimenti solleverebbe un'eccezione poiché le tabelle esistono già) e decommentare le righe dalla 23 alla 28.

  2. Il metodo invocato alla riga 23 inserisce nella tabella 100 righe con delle normali INSERT

  3. Anche le SELECT sono scritte in SQL e rispecchiamo la sintassi standard del linguaggio, la prima

    SELECT description FROM item where price = (select min(price) from item)

    non ha parametri e restitusce la descrizione dell'articolo meno costoso, mentre la seconda

    select count(*) as c from item where price <= ?

    ha un parametro e restituisce il numero di articoli con un prezzo minore uguale di threshold.

  4. Una piccola nota "stonata" (almeno dal mio punto di vista) è che Derby non accetta il "punto e virgola" alla fine del comando come da standard SQL.


Post correlati:
Apache Derby: il DBMS portabile (Introduzione)
Apache Derby: configurare Eclipse per iniziare un progetto
Codice d'esempio

venerdì 11 giugno 2010

Apache Derby: codice d'esempio





001 package com.blogspot.pilloledijava.derby;
002 
003 import java.io.File;
004 import java.math.BigDecimal;
005 import java.sql.Connection;
006 import java.sql.DriverManager;
007 import java.sql.PreparedStatement;
008 import java.sql.ResultSet;
009 import java.sql.SQLException;
010 import java.sql.Statement;
011 
012 public class DerbyExample {
013 
014   private static ExampleDbManager dbManager;
015 
016   /**
017    @param args
018    */
019   public static void main(String[] args) {
020     try {
021       dbManager = new ExampleDbManager(new File("data/example"));
022       dbManager.createTable();
023       dbManager.insertSample(100);
024       final String all = dbManager.getCheapest();
025       System.out.println("Cheapest item description: " + all);
026       final int count = dbManager.countCheaperThen(BigDecimal
027           .valueOf(5.0));
028       System.out.println("Cheap item: " + count);
029 
030       System.out.println();
031       System.out
032           .println("Apache Derby example: http://pilloledijava.blogspot.com/");
033       System.out.println("Enjoy !!!!");
034 
035     catch (Exception e) {
036       e.printStackTrace();
037       System.out
038           .println("Apache Derby example: http://pilloledijava.blogspot.com/");
039       System.out.println("Something wrong, sorry...");
040     finally {
041       try {
042         if (dbManager != null)
043           dbManager.close();
044       catch (SQLException e) {
045         // nothing in finally statement
046       }
047     }
048 
049   }
050 
051   /**
052    * Derby connection wrapper
053    
054    @author pdj
055    
056    */
057   public static class DbManager {
058 
059     protected final Connection connection;
060 
061     /**
062      * Embedded derby connection wrapper
063      
064      @param path
065      *            database location
066      @throws ClassNotFoundException
067      @throws SQLException
068      */
069     public DbManager(final File paththrows ClassNotFoundException,
070         SQLException {
071       // load Derby driver
072       Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
073       // instantiate derby connection, if necessary creates database
074       connection = DriverManager.getConnection("jdbc:derby:"
075           + path.getAbsolutePath() ";create=true");
076     }
077 
078     /**
079      * Close connection
080      
081      @throws SQLException
082      */
083     public void close() throws SQLException {
084       connection.close();
085     }
086 
087   }
088 
089   /**
090    * Example query
091    
092    @author pdj
093    
094    */
095   public static class ExampleDbManager extends DbManager {
096 
097     public ExampleDbManager(final File paththrows ClassNotFoundException,
098         SQLException {
099       super(path);
100     }
101 
102     /**
103      * Create item table
104      
105      * run one time!
106      
107      @throws SQLException
108      */
109     public void createTable() throws SQLException {
110       Statement createStatement = null;
111       try {
112         createStatement = connection.createStatement();
113         createStatement
114             .execute("create table item(id integer primary key generated always as identity, description varchar(50) not null, price numeric(10,2)) ");
115       finally {
116         if (createStatement != null)
117           createStatement.close();
118       }
119     }
120 
121     /**
122      * Insert a lot of dummy item
123      
124      @param count
125      @throws SQLException
126      */
127     public void insertSample(final int countthrows SQLException {
128       PreparedStatement insertStatement = null;
129       try {
130         insertStatement = connection
131             .prepareStatement("insert into item (description, price) values(?, ?)");
132         for (int i = 0; i < 100; i++) {
133           final String randomName = "item_" + Math.random();
134           insertStatement.setString(1, randomName);
135           final BigDecimal randomPrice = BigDecimal.valueOf(
136               (long) (Math.random() 1000)2);
137           insertStatement.setBigDecimal(2, randomPrice);
138           insertStatement.execute();
139         }
140       finally {
141         if (insertStatement != null)
142           insertStatement.close();
143       }
144     }
145 
146     /**
147      * Return the description of the cheapest item
148      
149      @return
150      @throws SQLException
151      */
152     public String getCheapest() throws SQLException {
153       Statement createStatement = null;
154       try {
155         createStatement = connection.createStatement();
156         final ResultSet rs = createStatement
157             .executeQuery("SELECT description FROM item where price = (select min(price) from item)");
158         try {
159           return rs.next() ? rs.getString("description"null;
160         finally {
161           if (rs != null)
162             rs.close();
163         }
164       finally {
165         if (createStatement != null)
166           createStatement.close();
167       }
168     }
169 
170     /**
171      * Count item cheaper the threshold
172      
173      @param threshold
174      @return
175      @throws SQLException
176      */
177     public int countCheaperThen(final BigDecimal threshold)
178         throws SQLException {
179       PreparedStatement createStatement = null;
180       try {
181         createStatement = connection
182             .prepareStatement("select count(*) as c from item where price <= ?");
183         createStatement.setBigDecimal(1, threshold);
184         final ResultSet rs = createStatement.executeQuery();
185         try {
186           return rs.next() ? rs.getInt("c"null;
187         finally {
188           if (rs != null)
189             rs.close();
190         }
191       finally {
192         if (createStatement != null)
193           createStatement.close();
194       }
195     }
196 
197   }
198 
199 }




Post correlati:
Apache Derby: il DBMS portabile (Introduzione)
Apache Derby: configurare Eclipse per iniziare un progetto
Query SQL: tutorial passo-passo