venerdì 28 dicembre 2012

Errore con DOMPDF on Codeigniter 2 + dompdf-0.5.2

Ho fatto così e ho risolto anch'io:
" have solved this problem by creating ci_exceptions.cls.php,an empty php file in that directory and i am not getting errors anymore.I dont know whether it is right way bt it is working well and not showing errors now"

Post originale: http://ellislab.com/forums/viewthread/186021/#1031424

giovedì 12 luglio 2012

Stampa in Java

 Una possibile soluzione, adatta a un pò tutte le stampanti (anche di rete!).

 Nota: La JTextArea è utilizzata per ottenere un Printable...forse è possibile ottenerlo in maniera più pulita e corretta.


import java.awt.Font;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaSizeName;
import javax.print.attribute.standard.OrientationRequested;
import javax.swing.JTextArea;

public class Printer {


    /**
     * Restituisce le stampanti driver disponibili al momento sul client.
     */
    public static PrintService[] getAvailableSystemPrinters() {
        return PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.AUTOSENSE, null);
    }

    /**
     * @return Restituisce il {@link PrintService} di nome dato se presente,
     * {@literal null} altrinmenti.
     * @throws NullPointerException se l'argomento é {@literal null}.
     */
    public static PrintService getPrinterByName(String name) {
        if (name == null)
            throw new NullPointerException("name");
        PrintService[] printServices = PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.AUTOSENSE, null);
        for (PrintService ps : printServices) {
            if (name.equals(ps.getName()))
                return ps;
        }
        return null;
    }
    /**
     * @param args
     * @throws IOException
     * @throws FileNotFoundException
     */
    public static void main(String[] args) throws IOException  {

        //InputStream is = Printer.class.getResourceAsStream("content.txt");
        InputStream is = new FileInputStream("C:\\content_largo.txt");
        //Lista stampanti installate
        System.out.println("Stampanti installate:");
        for (PrintService service : getAvailableSystemPrinters()) {
            System.out.println(" - " + service.getName());
        }

        if (args.length > 0) {

            PrintService defaultPrintService = getPrinterByName(args[0]);
            DocPrintJob printerJob = defaultPrintService.createPrintJob();
            SimpleDoc simpleDoc = null;
            try {
                JTextArea textArea = new JTextArea(convertStreamToString(is));
                textArea.setFont(new Font("courier New", Font.PLAIN, 8));
                PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
                aset.add(MediaSizeName.ISO_A4);
                aset.add(OrientationRequested.PORTRAIT);
                simpleDoc = new SimpleDoc(textArea.getPrintable(null, null), new DocFlavor("application/x-java-jvm-local-objectref", "java.awt.print.Printable"), null);
                printerJob.print(simpleDoc, aset);
            } catch (PrintException ex) {
                ex.printStackTrace();
            }
        }
        else {
            System.err.println("Bisogna indicare una stampante!");
        }
    }

    private static String convertStreamToString(InputStream is) throws IOException {
        /*
         * To convert the InputStream to String we use the
         * Reader.read(char[] buffer) method. We iterate until the
         * Reader return -1 which means there's no more data to
         * read. We use the StringWriter class to produce the string.
         */
        if (is != null) {
            Writer writer = new StringWriter();

            char[] buffer = new char[1024];
            try {
                Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); //anche IBM-850
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
            } finally {
                is.close();
            }
            return writer.toString();
        } else {      
            return "";
        }
    }
}

giovedì 14 giugno 2012

Mostrare cartelle e file nascosti su Mac OS X Lion


Mostrare cartelle e file nascosti su Mac OS X Lion

Nei sistemi Mac OS X la visualizzazione delle cartelle e dei file nascosti è disabilitata di default e non è possibile abilitarla dalle preferenze di sistema, tuttavia se avete la necessità di visualizzare tali oggetti bisogna utilizzare il terminale come segue:
  1. Aprire il Terminale (da Applicazioni > Utility > Terminale).
  2. Copia il codice seguente defaults write com.apple.Finder AppleShowAllFiles YES e incollalo nella finestra del Terminale.
  3. Premi Invio
  4. Tieni premuto il tasto “alt” sulla tastiera e fai clic con il tasto destro del mouse sull’icona del Finder
  5. Clicca su Riapri
Per tornare all’impostazione originale e nascondere nuovamente i file e le cartelle nascoste basta ripetere la procedura andando a sostituire la riga di codice presente al punto 2 con la riga seguente:
defaults write com.apple.Finder AppleShowAllFiles NO

venerdì 8 giugno 2012

Java: riportare in Reflection-Mode una serie di operazioni

import com.ulcjava.container.servlet.client.ConnectorCommandException;


....


    if ((reason instanceof ConnectorException) && (reason.getCause() instanceof ConnectorCommandException) ) {
        ConnectorCommandException cause = (ConnectorCommandException) reason.getCause();
        if (cause.getResponseInfo().getResponseCode() == 500) {
        JOptionPane.showMessageDialog(getOwner(), "La sessione non è più attiva.","La sessione non è più attiva.", JOptionPane.ERROR_MESSAGE);
        return;
        }
       
    }




-------------------- Con Reflection ----------------
Nota...senza import!!

try {
        Class connector_command_exception = Class.forName(CONNECTOR_COMMAND_EXCEPTION);

        if ((reason instanceof ConnectorException) && (connector_command_exception.isInstance(reason.getCause())) ) {
        Object causeInstance = reason.getCause();
        Method responseInfoMethod = causeInstance.getClass().getMethod("getResponseInfo");
        Object responseCodeInstance = responseInfoMethod.invoke(causeInstance, new Object[]{});
        Method responseCodeMethod = responseCodeInstance.getClass().getMethod("getResponseCode");
        int cause=((Integer)responseCodeMethod.invoke(responseCodeInstance, new Object[]{})).intValue();
        if (cause == 500) {
            JOptionPane.showMessageDialog(getOwner(), "Sessione utente terminata.","La sessione utente è terminata.", JOptionPane.ERROR_MESSAGE);
            return;
        }
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }

lunedì 4 giugno 2012

Installare SDK android su ubuntu 12.04

1) Sono partito da un'installazione pulita di eclipse (la indigo)
  • la cartella l'ho scompattata nella mia home
2) installare android sdk
  • scaricare http://developer.android.com/sdk/index.html
  • ho scompattato la cartella nella mia home
  • nella cartella /tools/ ho lanciato ./android
3) installare ADT plugin for Eclipse
  • Start Eclipse, then select Help > Install New Software....
  • Click Add, in the top-right corner.
  • In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and the following URL for the Location: https://dl-ssl.google.com/android/eclipse/

mercoledì 14 marzo 2012

Creare directory in JAVA

Per creare una o più directory, es. temporanea, in java bisogna fare un giochetto:

 private  File createTempDirectories(String prefix) throws Error {
    File parentDir;
    try {
        parentDir = File.createTempFile(prefix, "");
        parentDir.delete();
        System.out.println("result mkdir di " + parentDir.getAbsolutePath() + ":" +   parentDir.mkdir());   

        File child = new File(parentDir, "it/ibttn/test.txt");
        System.out.println("result mkdirs di " + child.getAbsolutePath() + ":" + child.mkdirs());
    } catch (IOException e) {
        throw new Error("Failed to create temporary directory: " + e);
    }
    return parentDir;
    }



Per eliminare + directory c'è bisogno di un metodo ricorsivo:

  public boolean deleteDirectories(File path) {
        if( path.exists() ) {
          for (File file : path.listFiles()) {
             if(file.isDirectory())
                deleteDirectories(file);
                else
                file.delete();
          }
        }
        return( path.delete() );
      }
   

giovedì 1 marzo 2012

Leggere file in progetti JAVA

HelpDialog.class.getResourceAsStream("/directory/nomefile")

Retrieving Resources from JAR files

// Get current classloader
   ClassLoader cl = this.getClass().getClassLoader();
   // Create icons
   Icon saveIcon  = new ImageIcon(cl.getResource("images/save.gif"));

mercoledì 25 gennaio 2012

Da Runtime.exec() a ProcessBuilder

Il Runtime.exec chiama direttamente la shell o il processo cmd.exe. Dalla JDK 5 invece è possibile eseguire un comando in un processo separato del sistema operativo, con la classe ProcessBuilder. Vedi http://docs.oracle.com/javase/6/docs/api/java/lang/ProcessBuilder.html