JDShutdown v1Descripción: Aplicación que permite establecer una hora y apagar el sistema una vez transcurrido el tiempo.
Autor: 1mpuls0
Entorno de desarrolloIDE: Netbeans 7.01
JDK: 1.7.0
SO: Windows 7
Plataformas de pruebaWindows
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/*
* Autor: 1mpuls0
*/
package projects;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.BorderFactory;
import java.awt.Font;
import java.awt.FlowLayout;
import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.util.Date;
import projects.date.DateTime;
import projects.actions.Shutdown;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
private JPanel panelPrincipal
; private JPanel panelCurrentDate
; private JLabel labelCurrentDate
; private DateTime date;
private Shutdown threadShutdown;
public static void main
(String args
[]) { JDShutdown jds = new JDShutdown();
jds.setVisible(true);
jds.setLocationRelativeTo(null);
}
public JDShutdown() {
panelPrincipal
= new JPanel(); panelCurrentDate
= new JPanel(); labelCurrentDate
= new JLabel(); date = new DateTime();
setTitle("JDShutdown V1");
setResizable(false);
panelCurrentDate.
setBorder(BorderFactory.
createTitledBorder("Fecha y hora de inicio"));
labelCurrentDate.
setFont(new Font("Tahoma",
0,
24)); panelCurrentDate.add(labelCurrentDate);
panelPrincipal.
add(panelCurrentDate,
BorderLayout.
PAGE_START);
panelLastDate.
setBorder(BorderFactory.
createTitledBorder("Fecha y hora de apagado"));
textFieldDate.setColumns(10);
textFieldDate.setText(date.getCurrentDate().substring(0, 10));
textFieldDate.addKeyListener(this);
textFieldTime.setColumns(10);
labelCurrentDate.setText("--/--/---- --:--");
textFieldTime.addKeyListener(this);
panelLastDate.add(textFieldDate);
panelLastDate.add(textFieldTime);
//addDateMask();
panelActions.
setBorder(BorderFactory.
createTitledBorder("Acciones"));
buttonStart.setText("Iniciar");
buttonStart.addActionListener(this);
panelActions.add(buttonStart);
buttonCancel.setText("Cancelar");
buttonCancel.addActionListener(this);
buttonCancel.setEnabled(false);
panelActions.add(buttonCancel);
getContentPane().add(panelPrincipal);
addWindowListener(new AppAdapter());
pack();
}
private void exit() {
try {
setVisible( false );
dispose();
}
Logger.getLogger(getClass().getName()).log(
Level.ALL, "Error...", npe);
}
}
if (src == buttonStart) {
String lastDate
= textFieldDate.
getText(); textFieldTime.setText(date.completeTime(textFieldTime.getText()));
String lastTime
= textFieldTime.
getText();
if(date.isDateValid(lastDate)) {
if(date.isTimeValid(lastTime)) {
Date currentDateTime
= date.
getCurrentDateTime(); Date lastDateTime
= date.
stringToDate(lastDate
+ " " + lastTime
); long milisecondsOfDifference = date.differenceTime(currentDateTime, lastDateTime);
if(milisecondsOfDifference > 6000 ) {
labelCurrentDate.
setText(String.
valueOf(date.
getCurrentDate())); buttonStart.setEnabled(false);
buttonCancel.setEnabled(true);
textFieldTime.setEditable(false);
threadShutdown = new Shutdown(milisecondsOfDifference);
} else {
labelCurrentDate.setText("--/--/---- --:--");
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); }
}else {
labelCurrentDate.setText("--/--/---- --:--");
}
} else {
labelCurrentDate.setText("--/--/---- --:--");
}
} else if (src == buttonCancel) {
threadShutdown.stop();
buttonStart.setEnabled(true);
buttonCancel.setEnabled(false);
textFieldTime.setEditable(true);
}
}
char caracter = evt.getKeyChar();
if (src == textFieldDate) {
if( ((caracter < '0') ||(caracter > '9')) && (caracter != '/') || textFieldDate.getText().length()== 10 )
evt.consume();
if((textFieldDate.getText().length()==2 || textFieldDate.getText().length()==5) && (caracter != '/'))
evt.consume();
} else if(src == textFieldTime) {
if( ((caracter < '0') ||(caracter > '9')) && (caracter != ':') || textFieldTime.getText().length()== 8 )
evt.consume();
if((textFieldTime.getText().length()==2 || textFieldTime.getText().length()==5) && (caracter != ':'))
evt.consume();
}
}
}
}
exit();
}
}
}
Clase: DateTime/*
* Autor: 1mpuls0
*/
package projects.date;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DateTime {
private final String FORMAT
= "dd/MM/yyyy HH:mm:ss";
public long differenceTime
(Date currentDate,
Date lastDate
) { long msDifference = 0;
long msCurrentDate = currentDate.getTime();
long msLastDate = lastDate.getTime();
if(msLastDate>msCurrentDate)
msDifference
= Math.
abs(msCurrentDate
- msLastDate
); return msDifference;
}
public Date getCurrentDateTime
() { currentDate = dateFormat.format(date);
try {
dateFormat.parse(currentDate);
Logger.getLogger(getClass().getName()).log(
Level.ALL, "Error...", ex);
}
return date;
}
public String getCurrentDate
() { try {
currentDate = dateFormat.format(date);
Logger.getLogger(getClass().getName()).log(
Level.ALL, "Error...", npe);
}
return currentDate;
}
try {
date = format.parse(strDate);
Logger.getLogger(getClass().getName()).log(
Level.ALL, "Error...", pe);
}
return date;
}
public boolean isDateValid
(String strDate
) { try {
df.setLenient(false);
df.parse(strDate);
return true;
Logger.getLogger(getClass().getName()).log(
Level.ALL, "Error...", pe);
return false;
}
}
public boolean isTimeValid
(String strDate
) { try {
df.setLenient(false);
df.parse(strDate);
return true;
Logger.getLogger(getClass().getName()).log(
Level.ALL, "Error...", pe);
return false;
}
}
if(strTime.length()==4 && strTime.charAt(3)<'9') {
strTime = strTime.substring(0, 3) + "0" + strTime.substring(3) + ":00";
}
if(strTime.length()==5) {
strTime+=":00";
}
if(strTime.length()==7 && strTime.charAt(6)<'9') {
strTime = strTime.substring(0, 6) + "0" + strTime.substring(6);
}
return strTime;
}
}
Clase: OperatingSystempackage projects.information;
public class OperatingSystem {
//The prefix String for all Windows OS.
private static final String OS_NAME_WINDOWS_PREFIX
= "Windows";
//The {@code os.name} System Property. Operating system name.
public static final String OS_NAME
= getSystemProperty
("os.name"); //The {@code os.version} System Property. Operating system version.
public static final String OS_VERSION
= getSystemProperty
("os.version");
//Is {@code true} if this is AIX.
public static final boolean IS_OS_AIX = getOSMatchesName("AIX");
//Is {@code true} if this is HP-UX.
public static final boolean IS_OS_HP_UX = getOSMatchesName("HP-UX");
//Is {@code true} if this is Irix.
public static final boolean IS_OS_IRIX = getOSMatchesName("Irix");
//Is {@code true} if this is Linux.
public static final boolean IS_OS_LINUX = getOSMatchesName("Linux") || getOSMatchesName("LINUX");
//Is {@code true} if this is Mac.
public static final boolean IS_OS_MAC = getOSMatchesName("Mac");
//Is {@code true} if this is Mac.
public static final boolean IS_OS_MAC_OSX = getOSMatchesName("Mac OS X");
//Is {@code true} if this is FreeBSD.
public static final boolean IS_OS_FREE_BSD = getOSMatchesName("FreeBSD");
//Is {@code true} if this is OpenBSD.
public static final boolean IS_OS_OPEN_BSD = getOSMatchesName("OpenBSD");
//Is {@code true} if this is NetBSD.
public static final boolean IS_OS_NET_BSD = getOSMatchesName("NetBSD");
//Is {@code true} if this is OS/2.
public static final boolean IS_OS_OS2 = getOSMatchesName("OS/2");
//Is {@code true} if this is Solaris.
public static final boolean IS_OS_SOLARIS = getOSMatchesName("Solaris");
//Is {@code true} if this is SunOS.
public static final boolean IS_OS_SUN_OS = getOSMatchesName("SunOS");
//Is {@code true} if this is a UNIX like system, as in any of AIX, HP-UX, Irix, Linux, MacOSX, Solaris or SUN OS.
public static final boolean IS_OS_UNIX = IS_OS_AIX || IS_OS_HP_UX || IS_OS_IRIX || IS_OS_LINUX || IS_OS_MAC_OSX
|| IS_OS_SOLARIS || IS_OS_SUN_OS || IS_OS_FREE_BSD || IS_OS_OPEN_BSD || IS_OS_NET_BSD;
//Is {@code true} if this is Windows.
public static final boolean IS_OS_WINDOWS = getOSMatchesName(OS_NAME_WINDOWS_PREFIX);
//Gets a System property, defaulting to {@code null} if the property cannot be read.
try {
return System.
getProperty(property
); // we are not allowed to look at this property
System.
err.
println("Caught a SecurityException reading the system property '" + property
+ "'; the SystemUtils property value will default to null.");
return null;
}
}
//Decides if the operating system matches.
private static boolean getOSMatchesName
(String osNamePrefix
) { return isOSNameMatch(OS_NAME, osNamePrefix);
}
//Decides if the operating system matches.
static boolean isOSNameMatch
(String osName,
String osNamePrefix
) { if (osName == null) {
return false;
}
return osName.startsWith(osNamePrefix);
}
if (osName == null || osVersion == null) {
return false;
}
return osName.startsWith(osNamePrefix) && osVersion.startsWith(osVersionPrefix);
}
}
Clase: Shutdown/*
* Autor: 1mpuls0
*/
package projects.actions;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import projects.information.OperatingSystem;
public class Shutdown
implements Runnable {
private long timeDifference = 0;
private OperatingSystem sys;
public Shutdown(long timeDifference) {
this.timeDifference = timeDifference;
thread.start();
}
private void process(long time) {
System.
out.
println("APAGATE!!!"); String shutdownCommand
= null;
if(sys.IS_OS_AIX)
shutdownCommand = "shutdown -Fh " + time;
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)
shutdownCommand = "shutdown -h " + time;
else if(sys.IS_OS_HP_UX)
shutdownCommand = "shutdown -hy " + time;
else if(sys.IS_OS_IRIX)
shutdownCommand = "shutdown -y -g " + time;
else if(sys.IS_OS_SOLARIS || sys.IS_OS_SUN_OS)
shutdownCommand = "shutdown -y -i5 -g" + time;
else if(sys.IS_OS_WINDOWS)
shutdownCommand = "shutdown.exe -s -t " + time;
try {
Runtime.
getRuntime().
exec(shutdownCommand
); Logger.getLogger(getClass().getName()).log(
Level.ALL, "Error...", ioe);
javax.
swing.
JOptionPane.
showMessageDialog(null,
"No se pudo apagar",
"Comando no aceptado", javax.
swing.
JOptionPane.
ERROR_MESSAGE); }
}
public void run() {
try {
thread.sleep(timeDifference);
process(0);
}
Logger.getLogger(getClass().getName()).log(
Level.ALL, "Error...", ie);
}
}
public void stop() {
thread.stop();
}
}
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
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.
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.