я еще не делала рефактор, все тут в двух классах напичкано.. не сильно громко смейтесь...
Код | package monitor_test;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.awt.AWTException; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.Image; import java.awt.MenuItem; import java.awt.PopupMenu; import java.awt.SystemTray; import java.awt.Toolkit; import java.awt.TrayIcon; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.RandomAccessFile; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit;
import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel;
//import org.apache.commons.lang3.StringUtils;
//import com.sun.jersey.api.client.Client; //import com.sun.jersey.api.client.ClientResponse; //import com.sun.jersey.api.client.WebResource;
public class StartForTEST {
private JLabel lab1; private JLabel lab2;
private SimpleDateFormat sdf; private SimpleDateFormat sdfLabel; private File fTime; private File fName; private BufferedReader buf;
String str; String resLine; // //////////////////////// // private Client client; // private WebResource webresourse; // private ClientResponse cr = null; private String adres; private String logName; // whoHasMonitor ==> return name in firm monitoring // ////////////////////////
private Container content; private JDialog jd; private String webAdres; private URI urladres; private JPanel panel;
public StartForTEST() throws Exception { // constructor // adres = "http://возвращает из таблицы кто дежурит.php"; // webAdres = "http://адрес наблюдения"; webAdres = "https://www.google.ru/"; urladres = new URI(webAdres); // в time.txt заносится нужное время, его можно менять в любое время )) fTime = new File("Time.txt"); sdfLabel = new SimpleDateFormat("HH:mm:ss"); setTrayIcon(); new CreatFiles(); ini2(); // methSchedul(); beepForAnHour();
}
public void ini2() throws IOException { jd = new JDialog(); jd.setTitle("Monitoring"); jd.setSize(300, 150); jd.setVisible(false); jd.setAlwaysOnTop(true); jd.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); setIcon(); setRightLocation(jd); panel = new JPanel(new GridLayout(3, 1)); panel.setBackground(Color.orange); content = jd.getContentPane(); content.add(panel);
lab1 = new JLabel("", null, JLabel.CENTER); lab1.setFont(new Font("Serif", Font.BOLD, 22)); lab1.setForeground(Color.blue); lab2 = new JLabel("", null, JLabel.CENTER); lab2.setFont(new Font("arial", Font.BOLD, 18)); lab2.setForeground(Color.blue);
lab2.setText("click here for monitoring"); panel.add(lab1); panel.add(lab2);
panel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) {
super.mousePressed(e); jd.setVisible(false); setRightLocation(jd); try { webpageCall(); } catch (IOException e1) { e1.printStackTrace(); } catch (URISyntaxException e1) { e1.printStackTrace(); } } }); }
// //////////////////////////////////
private void setIcon() {
jd.setIconImage(Toolkit.getDefaultToolkit().getImage( getClass().getResource("time.png"))); }
public void changVisible2(boolean wind) throws Exception { // if name and time == true : setRightLocation(jd); jd.setVisible(true); }
public void setTrayIcon() throws AWTException {
Image image = Toolkit.getDefaultToolkit().getImage( getClass().getResource("gg2.png")); PopupMenu popMenu = new PopupMenu(); MenuItem item1 = new MenuItem("Exit"); popMenu.add(item1);
TrayIcon trayIcon = new TrayIcon(image, "monitoring", popMenu); SystemTray.getSystemTray().add(trayIcon); item1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) {
System.exit(0); } }); }
// //////////////////////////////////////////////////////////////////
public boolean metTimeCompare3() throws Exception {
Date d3 = new Date(new Date().getTime()); sdf = new SimpleDateFormat("HH:mm"); String curTime = sdf.format(d3);
buf = new BufferedReader(new FileReader(fTime));
System.out.println(curTime + " timeComp"); while ((str = buf.readLine()) != null) {
Date readTime = new Date(); // String testToNull = StringUtils.trimToEmpty(""); // System.out.println(testToNull); try { readTime = sdf.parse(str);
System.out.println("good time format " + sdf.format(readTime));
} catch (ParseException e) { System.out.println("bad time format " + sdf.format(readTime)); System.out.println(e.toString()); } if (str.equals(curTime)) { lab1.setText(str + " o'clock"); buf.close(); return true; }
}
buf.close(); return false; }
// ///****************////
// ///****************//// public boolean nameComp() throws Exception { /* это код из фирмы возвращает имя дежурного */ // client = new Client(); // webresourse = client.resource(adres); // cr = webresourse.get(ClientResponse.class); // logName = cr.getEntity(String.class); // сравнивается с дежурным, которого я получаю из таблички фирмочки logName = "aa"; try {
fName = new File("Name.txt"); // logName == return name plan buf = new BufferedReader(new FileReader(fName));
while ((str = buf.readLine()) != null) { if (str.equalsIgnoreCase(logName)) { buf.close(); return true; } }
} catch (java.io.FileNotFoundException e) { e.printStackTrace(); System.out.println(" netu name txt"); } buf.close(); return false;
}
public void webpageCall() throws IOException, URISyntaxException { try { urladres = new URI(webAdres); java.awt.Desktop.getDesktop().browse(urladres); } catch (MalformedURLException e) { e.printStackTrace(); } }
// я пробовала этот метод private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public void beepForAnHour() { final Runnable beeper = new Runnable() { public void run() { System.out.println("beep"); /*-------------------------------------------------------*/ try { if (nameComp() && metTimeCompare3()) {
System.out.println(" equals"); changVisible2(true); } else { System.out.println("nothing equals"); } System.out.println(" label ");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.toString() + " from meth shedul e.printStackTrace()", "warning", JOptionPane.ERROR_MESSAGE); System.out.println(e.toString() + " from shedul meth"); try { new CreatFiles(); } catch (IOException e1) {
e1.printStackTrace(); } catch (AWTException e1) {
e1.printStackTrace(); } } } }; final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate( beeper, 10, 10, SECONDS); scheduler.schedule(new Runnable() { public void run() { beeperHandle.cancel(true); } }, 60 * 60, SECONDS); } // и этот метод public void methSchedul2() throws Exception { ScheduledExecutorService ses = Executors.newScheduledThreadPool(1); Runnable pinger = new Runnable() { public void run() { System.out.println("PING!"); try { if (nameComp() && metTimeCompare3()) { System.out.println(" equals"); changVisible2(true); } else { System.out.println("nothing equals"); } System.out.println(" label "); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.toString() + " from meth shedul e.printStackTrace()", "warning", JOptionPane.ERROR_MESSAGE); System.out.println(e.toString() + " tut ?"); try { new CreatFiles(); } catch (IOException e1) { e1.printStackTrace(); } catch (AWTException e1) { e1.printStackTrace(); } } } }; ses.scheduleAtFixedRate(pinger, 3, 10, TimeUnit.SECONDS); // ses.scheduleAtFixedRate(pinger, 0, 1, TimeUnit.MINUTES); }
// //////////////// /** * set right Location for component */ public void setRightLocation(Component comp) { // right down Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension frameSize = comp.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } comp.setLocation((screenSize.width - frameSize.width) - 100, (screenSize.height - frameSize.height) - 50); }
private static File f; private static FileChannel channel; private static FileLock lock;
// ///////////// public static void main(String[] args) throws IOException, URISyntaxException, Exception { // main try { f = new File("RingOnRequest.lock"); // Check if the lock exist if (f.exists()) {
// if exist try to delete it f.delete(); } // Try to get the lock channel = new RandomAccessFile(f, "rw").getChannel();
lock = channel.tryLock(); if (lock == null) { // File is lock by other application channel.close(); JOptionPane.showMessageDialog(null, "Allready running. Only 1 instance of MyApp can run ", "warning", JOptionPane.ERROR_MESSAGE); throw new RuntimeException("Only 1 instance of MyApp can run."); } // Add shutdown hook to release lock when application shutdown ShutdownHook shutdownHook = new ShutdownHook(); Runtime.getRuntime().addShutdownHook(shutdownHook);
// Your application tasks here.. System.out.println("Running"); try { new StartForTEST(); Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); }
} catch (IOException e) { throw new RuntimeException("Could not start process.", e); }
}// main
public static void unlockFile() { // release and delete file lock try { if (lock != null) {
lock.release(); channel.close(); f.delete(); } } catch (IOException e) { e.printStackTrace(); } }
static class ShutdownHook extends Thread {
public void run() { unlockFile(); } }
}
|
------------------------------------ Создаются файлики для программочки
Добавлено @ 19:45
Код | package monitor_test;
import java.awt.AWTException; import java.awt.Image; import java.awt.MenuItem; import java.awt.PopupMenu; import java.awt.SystemTray; import java.awt.Toolkit; import java.awt.TrayIcon; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.io.RandomAccessFile; import java.nio.channels.FileLock;
import javax.swing.JOptionPane;
public class CreatFiles {
String timeTitleDefault = "18:35";
String nameTitleDefault = "";
File fTime; File fName;
public CreatFiles() throws IOException, AWTException { // TODO constructor fTime = new File("Time.txt"); fName = new File("Name.txt"); createNameFolders(); createTimeFolders();
}
public void createNameFolders() throws IOException { System.out.println("fName exists? => " + fName.exists()); if (fName.exists()) { return; } else { nameTitleDefault = JOptionPane .showInputDialog("Enter abbreviation name : (for test enter : aa)"); fName.createNewFile(); System.out.println("has been created to the current directory fName.txt"); PrintStream outName = null; try { outName = new PrintStream(fName); outName.print(nameTitleDefault); } finally { if (outName != null) outName.flush(); outName.close(); } } }
public void createTimeFolders() throws IOException { System.out.println("fTime exists? => " + fTime.exists()); System.out.println(""); if (fTime.exists()) { System.out.println(); return; }
else { fTime.createNewFile(); System.out.println("has been created to the current directory for fTime");
PrintStream outTime = null; try { outTime = new PrintStream(fName); outTime.print(nameTitleDefault); } finally { if (outTime != null) outTime.flush(); outTime.close(); } } }
public static void main(String[] args) throws IOException, AWTException { new CreatFiles(); } }
|
Добавлено @ 19:56 там два метода для имени и shedul, но работает по одному )) не успела удалить, сообщение уже отправилось сюды .. |