elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Introducción a la Factorización De Semiprimos (RSA)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  Java
| | | |-+  [Aporte] Shutdown en diferentes Plataformas.
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [Aporte] Shutdown en diferentes Plataformas.  (Leído 1,923 veces)
1mpuls0


Desconectado Desconectado

Mensajes: 1.186


Ver Perfil
[Aporte] Shutdown en diferentes Plataformas.
« en: 30 Agosto 2013, 19:58 pm »

JDShutdown v1
Descripción: Aplicación que permite establecer una hora y apagar el sistema una vez transcurrido el tiempo.
Autor: 1mpuls0

Entorno de desarrollo
IDE: Netbeans 7.01
JDK: 1.7.0
SO: Windows 7

Plataformas de prueba
Windows
Linux
Mac

Estoy tratando de mejorar y optimizar el código, solo se utilizan librerías propias de java.
Cualquier sugerencia o recomendación es bienvenida, así como también si tienen dudas pueden consultarlo.

Clase: JDShutdown
Código
  1. /*
  2.  * Autor: 1mpuls0
  3.  */
  4. package projects;
  5.  
  6. import javax.swing.JFrame;
  7. import javax.swing.JPanel;
  8. import javax.swing.WindowConstants;
  9. import javax.swing.JOptionPane;
  10. import javax.swing.JLabel;
  11. import javax.swing.JButton;
  12. import javax.swing.JTextField;
  13. import java.awt.event.ActionListener;
  14. import java.awt.event.ActionEvent;
  15. import javax.swing.BorderFactory;
  16. import java.awt.Font;
  17. import java.awt.FlowLayout;
  18. import java.awt.BorderLayout;
  19. import java.awt.event.WindowAdapter;
  20. import java.awt.event.WindowEvent;
  21. import java.util.logging.Level;
  22. import java.util.logging.Logger;
  23. import java.awt.event.KeyListener;
  24. import java.awt.event.KeyEvent;
  25. import java.util.Date;
  26.  
  27. import projects.date.DateTime;
  28. import projects.actions.Shutdown;
  29.  
  30. import java.util.regex.Matcher;
  31. import java.util.regex.Pattern;
  32.  
  33. public class JDShutdown extends JFrame implements KeyListener, ActionListener  {
  34.  
  35.    private JPanel panelPrincipal;
  36.    private JPanel panelCurrentDate;
  37.    private JLabel labelCurrentDate;
  38.    private JPanel panelLastDate;
  39.    private JTextField textFieldDate;
  40.    private JTextField textFieldTime;
  41.    private JButton buttonStart;
  42.    private JButton buttonCancel;
  43.    private JPanel panelActions;
  44.    private DateTime date;
  45.    private Shutdown threadShutdown;
  46.  
  47.  
  48.    public static void main(String args[]) {
  49.        JDShutdown jds = new JDShutdown();
  50.        jds.setVisible(true);
  51.        jds.setLocationRelativeTo(null);
  52.    }
  53.  
  54.    public JDShutdown() {
  55.        panelPrincipal = new JPanel();
  56.        panelCurrentDate = new JPanel();
  57.        labelCurrentDate = new JLabel();
  58.        panelLastDate = new JPanel();
  59.        textFieldDate = new JTextField();
  60.        textFieldTime = new JTextField();
  61.        panelActions = new JPanel();
  62.        buttonStart = new JButton();
  63.        buttonCancel = new JButton();
  64.        date = new DateTime();
  65.  
  66.  
  67.        setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
  68.        setTitle("JDShutdown V1");
  69.        getContentPane().setLayout(new FlowLayout());
  70.        setResizable(false);
  71.  
  72.        panelPrincipal.setLayout(new BorderLayout());
  73.  
  74.        panelCurrentDate.setBorder(BorderFactory.createTitledBorder("Fecha y hora de inicio"));
  75.  
  76.        labelCurrentDate.setFont(new Font("Tahoma", 0, 24));
  77.        panelCurrentDate.add(labelCurrentDate);
  78.  
  79.        panelPrincipal.add(panelCurrentDate, BorderLayout.PAGE_START);
  80.  
  81.        panelLastDate.setBorder(BorderFactory.createTitledBorder("Fecha y hora de apagado"));
  82.  
  83.        textFieldDate.setColumns(10);
  84.        textFieldDate.setText(date.getCurrentDate().substring(0, 10));
  85.        textFieldDate.addKeyListener(this);
  86.  
  87.        textFieldTime.setColumns(10);
  88.        labelCurrentDate.setText("--/--/---- --:--");
  89.        textFieldTime.addKeyListener(this);
  90.  
  91.        panelLastDate.add(textFieldDate);
  92.        panelLastDate.add(textFieldTime);
  93.        //addDateMask();
  94.  
  95.        panelPrincipal.add(panelLastDate, BorderLayout.CENTER);
  96.  
  97.        panelActions.setBorder(BorderFactory.createTitledBorder("Acciones"));
  98.  
  99.        buttonStart.setText("Iniciar");
  100.        buttonStart.addActionListener(this);
  101.        panelActions.add(buttonStart);
  102.  
  103.        buttonCancel.setText("Cancelar");
  104.        buttonCancel.addActionListener(this);
  105.        buttonCancel.setEnabled(false);
  106.        panelActions.add(buttonCancel);
  107.  
  108.        panelPrincipal.add(panelActions, BorderLayout.PAGE_END);
  109.  
  110.        getContentPane().add(panelPrincipal);
  111.  
  112.        addWindowListener(new AppAdapter());
  113.  
  114.        pack();
  115.    }
  116.  
  117.    private void exit() {
  118.        try {
  119.            int salida = JOptionPane.showConfirmDialog(null, (char)191+"Desea salir?", "Salida", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
  120.            if(salida == JOptionPane.YES_OPTION) {
  121.                setVisible( false );
  122.                dispose();
  123.                System.exit(0);
  124.            }
  125.        } catch(NullPointerException npe) {
  126.            Logger.getLogger(getClass().getName()).log(
  127.            Level.ALL, "Error...", npe);
  128.        }
  129.    }
  130.  
  131.    public void actionPerformed(ActionEvent evt) {
  132.        Object src = evt.getSource();
  133.        if (src == buttonStart) {
  134.            String lastDate = textFieldDate.getText();
  135.            textFieldTime.setText(date.completeTime(textFieldTime.getText()));
  136.            String lastTime = textFieldTime.getText();
  137.  
  138.            if(date.isDateValid(lastDate)) {
  139.                if(date.isTimeValid(lastTime)) {
  140.                    Date currentDateTime = date.getCurrentDateTime();
  141.                    Date lastDateTime = date.stringToDate(lastDate + " " + lastTime);
  142.                    long milisecondsOfDifference = date.differenceTime(currentDateTime, lastDateTime);
  143.                    if(milisecondsOfDifference > 6000 ) {
  144.                        labelCurrentDate.setText(String.valueOf(date.getCurrentDate()));
  145.                        buttonStart.setEnabled(false);
  146.                        buttonCancel.setEnabled(true);
  147.                        textFieldTime.setEditable(false);
  148.                        threadShutdown = new Shutdown(milisecondsOfDifference);
  149.                    } else {
  150.                        labelCurrentDate.setText("--/--/---- --:--");
  151.                        JOptionPane.showMessageDialog(null, "Verifica la hora.\n Coloca una hora con minimo un minuto de diferencia mas a la hora actual.", "Hora no valida", JOptionPane.WARNING_MESSAGE);
  152.                    }
  153.                }else {
  154.                    labelCurrentDate.setText("--/--/---- --:--");
  155.                    JOptionPane.showMessageDialog(null, "Verifica la hora", "Hora no valida", JOptionPane.ERROR_MESSAGE);
  156.                }
  157.            } else {
  158.                labelCurrentDate.setText("--/--/---- --:--");
  159.                JOptionPane.showMessageDialog(null, "Verifica la fecha", "Fecha no valida", JOptionPane.ERROR_MESSAGE);
  160.            }
  161.  
  162.        } else if (src == buttonCancel) {
  163.            threadShutdown.stop();
  164.            buttonStart.setEnabled(true);
  165.            buttonCancel.setEnabled(false);
  166.            textFieldTime.setEditable(true);
  167.        }
  168.    }
  169.  
  170.    public void keyTyped(KeyEvent evt) {
  171.        Object src = evt.getSource();
  172.        char caracter = evt.getKeyChar();
  173.        if (src == textFieldDate) {
  174.            if( ((caracter < '0') ||(caracter > '9')) && (caracter != '/') || textFieldDate.getText().length()== 10 )
  175.                evt.consume();
  176.            if((textFieldDate.getText().length()==2 || textFieldDate.getText().length()==5) && (caracter != '/'))
  177.                evt.consume();
  178.        } else if(src == textFieldTime) {
  179.            if( ((caracter < '0') ||(caracter > '9')) && (caracter != ':') || textFieldTime.getText().length()== 8 )
  180.                evt.consume();
  181.            if((textFieldTime.getText().length()==2 || textFieldTime.getText().length()==5) && (caracter != ':'))
  182.                evt.consume();
  183.        }
  184.    }
  185.  
  186.    public void keyPressed(KeyEvent evt) {      
  187.    }
  188.  
  189.    public void keyReleased(KeyEvent evt) {      
  190.    }
  191.  
  192.    class AppAdapter extends WindowAdapter {
  193.        public void windowClosing(WindowEvent event) {
  194.            exit();
  195.        }
  196.    }
  197. }
  198.  

Clase: DateTime
Código
  1. /*
  2.  * Autor: 1mpuls0
  3.  */
  4. package projects.date;
  5.  
  6. import java.text.SimpleDateFormat;
  7. import java.util.Date;
  8. import java.text.DateFormat;
  9. import java.text.ParseException;
  10. import java.util.logging.Level;
  11. import java.util.logging.Logger;
  12.  
  13. public class DateTime {
  14.  
  15.    private final String FORMAT = "dd/MM/yyyy HH:mm:ss";
  16.  
  17.    public long differenceTime(Date currentDate, Date lastDate) {
  18.        long msDifference = 0;
  19.        long msCurrentDate = currentDate.getTime();
  20.        long msLastDate = lastDate.getTime();
  21.        if(msLastDate>msCurrentDate)
  22.            msDifference = Math.abs(msCurrentDate - msLastDate);
  23.        return msDifference;
  24.    }
  25.  
  26.    public Date getCurrentDateTime() {
  27.        String currentDate;
  28.        SimpleDateFormat dateFormat = new SimpleDateFormat(FORMAT);
  29.        Date date = new Date();
  30.        currentDate = dateFormat.format(date);
  31.        try {
  32.            dateFormat.parse(currentDate);
  33.        } catch (ParseException ex) {
  34.            Logger.getLogger(getClass().getName()).log(
  35.            Level.ALL, "Error...", ex);
  36.        }
  37.        return date;
  38.    }
  39.  
  40.    public String getCurrentDate() {
  41.        String currentDate = "";
  42.        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
  43.        Date date = new Date();
  44.        try {
  45.            currentDate = dateFormat.format(date);
  46.  
  47.        } catch(NullPointerException npe) {
  48.            Logger.getLogger(getClass().getName()).log(
  49.            Level.ALL, "Error...", npe);
  50.        }
  51.        return currentDate;
  52.    }
  53.  
  54.    public Date stringToDate(String strDate) {
  55.        SimpleDateFormat format = new SimpleDateFormat(FORMAT);
  56.        Date date = null;
  57.        try {
  58.            date = format.parse(strDate);
  59.        } catch (ParseException pe) {
  60.            Logger.getLogger(getClass().getName()).log(
  61.            Level.ALL, "Error...", pe);
  62.        }
  63.        return date;
  64.    }
  65.  
  66.    public boolean isDateValid(String strDate) {
  67.         try {
  68.            DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
  69.            df.setLenient(false);
  70.            df.parse(strDate);
  71.            return true;
  72.        } catch (ParseException pe) {
  73.            Logger.getLogger(getClass().getName()).log(
  74.            Level.ALL, "Error...", pe);
  75.            return false;
  76.        }
  77.    }
  78.  
  79.    public boolean isTimeValid(String strDate) {
  80.        try {
  81.            DateFormat df = new SimpleDateFormat("HH:mm:ss");
  82.            df.setLenient(false);
  83.            df.parse(strDate);
  84.            return true;
  85.        } catch (ParseException pe) {
  86.            Logger.getLogger(getClass().getName()).log(
  87.            Level.ALL, "Error...", pe);
  88.            return false;
  89.        }
  90.    }
  91.  
  92.    public String completeTime(String strTime) {
  93.        if(strTime.length()==4 && strTime.charAt(3)<'9') {
  94.            strTime = strTime.substring(0, 3) + "0" + strTime.substring(3) + ":00";
  95.        }
  96.  
  97.        if(strTime.length()==5) {
  98.            strTime+=":00";
  99.        }
  100.  
  101.        if(strTime.length()==7 && strTime.charAt(6)<'9') {
  102.            strTime = strTime.substring(0, 6) + "0" + strTime.substring(6);
  103.        }
  104.        return strTime;
  105.    }
  106. }
  107.  

Clase: OperatingSystem
Código
  1. package projects.information;
  2.  
  3. public class OperatingSystem {
  4.    //The prefix String for all Windows OS.
  5.    private static final String OS_NAME_WINDOWS_PREFIX = "Windows";
  6.  
  7.    //The {@code os.name} System Property. Operating system name.
  8.    public static final String OS_NAME = getSystemProperty("os.name");
  9.    //The {@code os.version} System Property. Operating system version.
  10.    public static final String OS_VERSION = getSystemProperty("os.version");
  11.  
  12.    //Is {@code true} if this is AIX.
  13.    public static final boolean IS_OS_AIX = getOSMatchesName("AIX");
  14.    //Is {@code true} if this is HP-UX.
  15.    public static final boolean IS_OS_HP_UX = getOSMatchesName("HP-UX");
  16.    //Is {@code true} if this is Irix.
  17.    public static final boolean IS_OS_IRIX = getOSMatchesName("Irix");
  18.    //Is {@code true} if this is Linux.
  19.    public static final boolean IS_OS_LINUX = getOSMatchesName("Linux") || getOSMatchesName("LINUX");
  20.    //Is {@code true} if this is Mac.
  21.    public static final boolean IS_OS_MAC = getOSMatchesName("Mac");
  22.    //Is {@code true} if this is Mac.
  23.    public static final boolean IS_OS_MAC_OSX = getOSMatchesName("Mac OS X");
  24.    //Is {@code true} if this is FreeBSD.
  25.    public static final boolean IS_OS_FREE_BSD = getOSMatchesName("FreeBSD");
  26.    //Is {@code true} if this is OpenBSD.
  27.    public static final boolean IS_OS_OPEN_BSD = getOSMatchesName("OpenBSD");
  28.    //Is {@code true} if this is NetBSD.
  29.    public static final boolean IS_OS_NET_BSD = getOSMatchesName("NetBSD");
  30.    //Is {@code true} if this is OS/2.
  31.    public static final boolean IS_OS_OS2 = getOSMatchesName("OS/2");
  32.    //Is {@code true} if this is Solaris.
  33.    public static final boolean IS_OS_SOLARIS = getOSMatchesName("Solaris");
  34.    //Is {@code true} if this is SunOS.
  35.    public static final boolean IS_OS_SUN_OS = getOSMatchesName("SunOS");
  36.  
  37.    //Is {@code true} if this is a UNIX like system, as in any of AIX, HP-UX, Irix, Linux, MacOSX, Solaris or SUN OS.
  38.    public static final boolean IS_OS_UNIX = IS_OS_AIX || IS_OS_HP_UX || IS_OS_IRIX || IS_OS_LINUX || IS_OS_MAC_OSX
  39.            || IS_OS_SOLARIS || IS_OS_SUN_OS || IS_OS_FREE_BSD || IS_OS_OPEN_BSD || IS_OS_NET_BSD;
  40.  
  41.  
  42.    //Is {@code true} if this is Windows.
  43.    public static final boolean IS_OS_WINDOWS = getOSMatchesName(OS_NAME_WINDOWS_PREFIX);
  44.  
  45.    //Gets a System property, defaulting to {@code null} if the property cannot be read.
  46.    private static String getSystemProperty(String property) {
  47.        try {
  48.            return System.getProperty(property);
  49.        } catch (SecurityException ex) {
  50.            // we are not allowed to look at this property
  51.            System.err.println("Caught a SecurityException reading the system property '" + property
  52.                    + "'; the SystemUtils property value will default to null.");
  53.            return null;
  54.        }
  55.    }
  56.  
  57.    //Decides if the operating system matches.
  58.    private static boolean getOSMatchesName(String osNamePrefix) {
  59.        return isOSNameMatch(OS_NAME, osNamePrefix);
  60.    }
  61.  
  62.    //Decides if the operating system matches.
  63.    static boolean isOSNameMatch(String osName, String osNamePrefix) {
  64.        if (osName == null) {
  65.            return false;
  66.        }
  67.        return osName.startsWith(osNamePrefix);
  68.    }
  69.  
  70.    static boolean isOSMatch(String osName, String osVersion, String osNamePrefix, String osVersionPrefix) {
  71.        if (osName == null || osVersion == null) {
  72.            return false;
  73.        }
  74.        return osName.startsWith(osNamePrefix) && osVersion.startsWith(osVersionPrefix);
  75.    }    
  76. }
  77.  
  78.  

Clase: Shutdown
Código
  1. /*
  2.  * Autor: 1mpuls0
  3.  */
  4. package projects.actions;
  5.  
  6. import java.io.IOException;
  7. import java.util.logging.Level;
  8. import java.util.logging.Logger;
  9.  
  10. import projects.information.OperatingSystem;
  11.  
  12. public class Shutdown implements Runnable {
  13.  
  14.    private final Thread thread;
  15.    private long timeDifference = 0;
  16.    private OperatingSystem sys;
  17.  
  18.    public Shutdown(long timeDifference) {
  19.        this.timeDifference = timeDifference;
  20.        thread = new Thread(this);
  21.        thread.start();
  22.    }
  23.  
  24.    private void process(long time) {
  25.        System.out.println("APAGATE!!!");
  26.        String shutdownCommand = null;
  27.  
  28.        if(sys.IS_OS_AIX)
  29.            shutdownCommand = "shutdown -Fh " + time;
  30.        else if(sys.IS_OS_FREE_BSD || sys.IS_OS_LINUX || sys.IS_OS_MAC|| sys.IS_OS_MAC_OSX || sys.IS_OS_NET_BSD || sys.IS_OS_OPEN_BSD || sys.IS_OS_UNIX)
  31.            shutdownCommand = "shutdown -h " + time;
  32.        else if(sys.IS_OS_HP_UX)
  33.            shutdownCommand = "shutdown -hy " + time;
  34.        else if(sys.IS_OS_IRIX)
  35.            shutdownCommand = "shutdown -y -g " + time;
  36.        else if(sys.IS_OS_SOLARIS || sys.IS_OS_SUN_OS)
  37.            shutdownCommand = "shutdown -y -i5 -g" + time;
  38.        else if(sys.IS_OS_WINDOWS)
  39.            shutdownCommand = "shutdown.exe -s -t " + time;
  40.  
  41.        try {
  42.            Runtime.getRuntime().exec(shutdownCommand);
  43.        }catch(IOException ioe) {
  44.            Logger.getLogger(getClass().getName()).log(
  45.            Level.ALL, "Error...", ioe);
  46.            javax.swing.JOptionPane.showMessageDialog(null, "No se pudo apagar", "Comando no aceptado", javax.swing.JOptionPane.ERROR_MESSAGE);
  47.        }
  48.    }
  49.  
  50.    public void run() {
  51.        try {
  52.            thread.sleep(timeDifference);
  53.            process(0);
  54.        }
  55.        catch (InterruptedException ie) {
  56.            Logger.getLogger(getClass().getName()).log(
  57.            Level.ALL, "Error...", ie);
  58.        }
  59.    }
  60.  
  61.    public void stop() {
  62.        thread.stop();
  63.    }
  64. }
  65.  


« Última modificación: 3 Septiembre 2015, 19:12 pm por 1mpuls0 » En línea

abc
Zoik

Desconectado Desconectado

Mensajes: 91


Ver Perfil
Re: [Aporte] Shutdown en diferentes Plataformas.
« Respuesta #1 en: 30 Agosto 2013, 21:46 pm »

Bueno solo he probado el programa con un copy paste, y no se que hago mal que la hora no me la coge, introduzco, la fecha por defecto, y la hora 01:00:00 también e probado la hora 01:00 me salta el dialog de que la revise.

El código cuando tenga tiempo me lo mirare en profundidad, pero tiene una pintaza  ;-)

Un saludo


« Última modificación: 30 Agosto 2013, 21:56 pm por Zoik » En línea

1mpuls0


Desconectado Desconectado

Mensajes: 1.186


Ver Perfil
Re: [Aporte] Shutdown en diferentes Plataformas.
« Respuesta #2 en: 30 Agosto 2013, 21:54 pm »

Bueno solo he probado el programa con un copy paste, y no se que hago mal que la hora no me la coge, introduzco, la fecha por defecto, y la hora 01:00:00 también e probado la hora 01:00 me salta el dialog de que la revise.

El código cuando tenga tiempo me lo mirare en profundidad, pero tiene una pintaza  ;-)

Un saludo

01:00:00 es la 01 AM
Las 01 PM sería 13:00:00

y eso lo modifico el fin de semana :P para que se pueda am o pm aunque aun no tengo idea como mostrarlo al usuario xD

Con respecto a lo segundo estoy trabajando justo en eso xD para que se pueda escribir 01:00

Edito:
Ya lo modifiqué para que acepte HH:mm :P no es lo más adecuado pero mientras se me ocurre algo más :P

Edito:
Las clases JDShutdown y DateTime fueron modificadas para completar el formato de hora. Es decir si el usuario escribe los siguientes formatos.
HH:m, HH:mm, HH:mm:s se autocompleta como HH:mm:ss

Gracias por las observaciones.
« Última modificación: 3 Septiembre 2015, 19:13 pm por 1mpuls0 » En línea

abc
Zoik

Desconectado Desconectado

Mensajes: 91


Ver Perfil
Re: [Aporte] Shutdown en diferentes Plataformas.
« Respuesta #3 en: 30 Agosto 2013, 21:56 pm »

Me lo e leído muy por encima, y tengo curiosidad sobre la class OperatingSystem, podrías pasarme por privado alguna referencia con la cual pudiese aprender a distinguir entre sistemas operativos por favor?

Gracias de antemano.
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
pequeño aporte(proxy),pero aporte al fin.:D
Programación Visual Basic
Tengu 0 2,397 Último mensaje 22 Julio 2007, 17:33 pm
por Tengu
Colaboración en aporte de datos diferentes ESSID
Hacking Wireless
ChimoC 0 9,930 Último mensaje 27 Abril 2010, 23:18 pm
por ChimoC
[Aporte] Peso en diferentes Planetas
Java
Senior++ 7 7,165 Último mensaje 29 Abril 2012, 23:27 pm
por raul_samp
agregar diferentes arraylist a diferentes jlist
Java
manuhendrix 0 2,889 Último mensaje 20 Febrero 2013, 17:09 pm
por manuhendrix
[pregunta]como separo diferentes threats en diferentes ventanas en windows « 1 2 »
Programación C/C++
daryo 10 5,053 Último mensaje 4 Octubre 2013, 23:10 pm
por daryo
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines