/*
- To change this license header, choose License Headers in Project Properties.
- To change this template file, choose Tools | Templates
- and open the template in the editor.
*/
package HelloImpressora;
import static HelloImpressora.FrmPrincipal.imagemTray;
import static HelloImpressora.FrmPrincipal.lblStatus;
import static HelloImpressora.FrmPrincipal.opcoes;
import java.awt.AWTException;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.Attribute;
import javax.print.attribute.PrintServiceAttribute;
import javax.print.attribute.PrintServiceAttributeSet;
import javax.print.event.PrintServiceAttributeEvent;
import javax.print.event.PrintServiceAttributeListener;
import javax.swing.JLabel;
import javax.swing.UIManager;
public class HelloPrinter {
/**
* @param args
*/
private static String impressora;
static FrmPrincipal principal;
private static int status = 1;
@SuppressWarnings("empty-statement")
public static void main(String[] args) {
Process p;
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}catch(Exception ex) {
ex.printStackTrace(System.err);
}
//FORM de Mensagem
principal = new FrmPrincipal();
//Objeto instancia em segundo plano
SystemTray tray = SystemTray.getSystemTray();
// adiciona o mouseListener no TrayIcon
// Criamos um ActionListener para a ação de encerramento do programa.
ActionListener exitListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//Imprime uma mensagem de despedida na tela
System.exit(0);
}
};
// Criamos um ActionListener para a exibir uma mensagem na tela ao clicarmos
//em um item do menu.
ActionListener mostramsglistener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new FrmSobre().setVisible(true);
}
};
//Criando um objeto PopupMenu
PopupMenu popup = new PopupMenu("Mensagem de Impressão");
//criando itens do menu
MenuItem mostramsg = new MenuItem("Sobre");
//MenuItem defaultItem = new MenuItem("Sair");
//na linha a seguir associamos os objetos aos eventos
mostramsg.addActionListener(mostramsglistener);
//defaultItem.addActionListener(exitListener);
//Adicionando itens ao PopupMenu
popup.add(mostramsg);
//adiconando um separador
//popup.addSeparator();
//Criando objetos do tipo Checkbox
//Criando um submenu
/*
PopupMenu popup2 = new PopupMenu("SubMenu de Opções");
MenuItem mostramsg2 = new MenuItem("Item1");
MenuItem mostramsg3 = new MenuItem("Item2");
MenuItem mostramsg4 = new MenuItem("Item3");
popup2.add(mostramsg2);
popup2.add(mostramsg3);
popup2.add(mostramsg4);
popup.add(popup2);
*/
//popup.add(defaultItem);
//Icone Tray
final TrayIcon trayIcon = new TrayIcon(imagemTray,"Mensagem de Impressão",popup);
MouseListener mlOpcoes = new MouseListener(){
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
};
trayIcon.setImageAutoSize(true);
trayIcon.addMouseListener(mlOpcoes);
try {
// Adiciona o Ícone no SystemTray
tray.add(trayIcon);
} catch (AWTException e) {}
/*********************************************************************************************************************/
// TODO Auto-generated method stub
//PrintRequestAttributeSet requestAttributeSet = new HashPrintRequestAttributeSet();
//requestAttributeSet.add(new Copies(1));
/*PrintService[] services = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
for (PrintService service1 : services) {
System.out.println(service1);
}
PrintService service = services[2];
*/
//CLASSE USADA PARA OBTER PARAMETROS DA FILA DE IMPRESSAO
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
service.addPrintServiceAttributeListener(new PrintServiceAttributeListener(){
@Override
public void attributeUpdate(PrintServiceAttributeEvent event) {
PrintServiceAttributeSet serviceAttributeSet = event.getAttributes();
StringBuilder s = new StringBuilder();
s.append("PrintServiceAttributeEvent\n");
for (Attribute attribute : serviceAttributeSet.toArray()) {
PrintServiceAttribute printServiceAttribute = (PrintServiceAttribute)attribute;
s.append(printServiceAttribute.getCategory().getName() + "/" +
printServiceAttribute.getName() + " = " + printServiceAttribute.toString() + "\n");
}
}
});
//LOOP COM THREAD PARA FICA MONITORANDO ALTERAÇOES NA FILA
while (true) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
//SAIDAS DE CONTROLE APENAS
System.out.println("I'm alive and it's " + new Date());
System.out.println("Job attributes");
/*for (Attribute attribute : job.getAttributes().toArray()) {
System.out.println((attribute.getCategory().getName() + "/" +
attribute.getName() + " = " + attribute.toString() + "\n"));
}*/
System.out.println("Service attributes");
for (Attribute attribute : service.getAttributes().toArray()) {
opcoes = FrmPrincipal.config.carregarOpcoes();
if(attribute.getName().equals("printer-name")){
setImpressora(attribute.toString());
}
if(attribute.getName().equals("queued-job-count")){
if(Integer.parseInt(attribute.toString()) > 0){
/*if(isMaquinaEquals(getImpressora())){*///METODO QUE FOI USADO PARA TENTAR DEFINIR MELHOR QUE IMPRIME MAIS SEM SUCESSO
if(!principal.isVisible()){
setTextStatus(lblStatus, FrmPrincipal.opcoes[1]);
principal.setVisible(true);
principal.setExtendedState(Frame.NORMAL);
//principal = new FrmPrincipal();
//Abrir na frente
principal.setAlwaysOnTop(true);
//Voltar ao normal
principal.setAlwaysOnTop(false);
}
/* } */
}else{
if(principal.isVisible()){
setTextStatus(lblStatus, FrmPrincipal.opcoes[2]);
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Logger.getLogger(HelloPrinter.class.getName()).log(Level.SEVERE, null, ex);
}
principal.dispose();
}
}
}
//System.out.println((attribute.getCategory().getName() + "/" + attribute.getName() + " = " + attribute.toString() + "\n"));
}
}
}
public static void setTextStatus(final JLabel label, final String text)
{
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
label.setText(text);
}
});
}
public static int getPosicao(String linha, String ocorrencia) {
return linha.indexOf(ocorrencia)+1;
}
//METODO USANDO ARQUIVO Prnjobs.vbs PARA TENTAR OBTER NOME DA MAQUINA OU USUARIO
public static boolean isMaquinaEquals(String print){
boolean result = false;
ProcessBuilder processBuilder;
Process process = null;
if(System.getProperty("os.name").contains("XP")){
String[] cmd = {"cmd","/c", "Cscript %WINDIR%\\System32\\Prnjobs.vbs -l"};
processBuilder = new ProcessBuilder(cmd);
}else{
String[] cmd = {"cmd","/c", "Cscript %WINDIR%\\System32\\Printing_Admin_Scripts\\pt-BR\\Prnjobs.vbs -l"};
processBuilder = new ProcessBuilder(cmd);
}
//String print = "Cscript.exe %WINDIR%\\System32\\Printing_Admin_Scripts\\pt-BR\\Prnjobs.vbs -l -s SERVIDOR -p RECEPÇÃO";
try {
process = processBuilder.start();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String s1 = null;
while (br.readLine() != null){
s1 = "|"+br.readLine()+"#";
//System.out.println(s1);
//System.out.println("getInputStream:");
//System.out.println(s1);
String maquina = s1.substring(s1.indexOf("|")+1, s1.indexOf("#"));
/*if(maquina.contains("Propriet")){
System.out.println(System.getProperty("os.name"));//SO
String PC = null;
if(maquina.contains("\\\\")){
PC = maquina.substring(maquina.lastIndexOf(" ")+3);
}else{
PC = maquina.substring(maquina.lastIndexOf(" ")+1);
}
System.out.println(PC);
String nome = System.getProperty("user.name");
System.out.println(nome);
if(PC.equalsIgnoreCase(nome)){
result = true;
System.out.println("YES");
}else{
result = false;
System.out.println("NO");
}
} */
if(maquina.contains("Nome da m")){
System.out.println(System.getProperty("os.name"));//SO
String PC = null;
if(maquina.contains("\\\\")){
PC = maquina.substring(maquina.lastIndexOf(" ")+3);
}else{
PC = maquina.substring(maquina.lastIndexOf(" ")+1);
}
System.out.println(PC);
String nome = InetAddress.getLocalHost().getHostName();
System.out.println(nome);
if(PC.equalsIgnoreCase(nome)){
result = true;
System.out.println("YES");
}else{
result = false;
System.out.println("NO");
}
}
}
} catch (IOException ex) {
Logger.getLogger(HelloPrinter.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
/**
* @return the impressora
*/
public static String getImpressora() {
return impressora;
}
/**
* @param aImpressora the impressora to set
*/
public static void setImpressora(String aImpressora) {
impressora = aImpressora;
}
/**
* @return the status
*/
public static int getStatus() {
return status;
}
/**
* @param aStatus the status to set
*/
public static void setStatus(int aStatus) {
status = aStatus;
}
}
FrmPrincipal.java
package HelloImpressora;
import java.awt.Desktop;
import java.awt.Image;
import java.awt.Toolkit;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.concurrent.Executor;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
/*
- To change this license header, choose License Headers in Project Properties.
- To change this template file, choose Tools | Templates
- and open the template in the editor.
*/
PrintMonitorTest.zip (330,9 KB)
public class FrmPrincipal extends javax.swing.JFrame {
/**
* Creates new form FrmPrincipal
*/
static Propriedades config;
static String[] opcoes;
public static Image imagemTitulo,imagemTray,imagemFundo;
Executor executor1;
Thread network;
public FrmPrincipal() {
initComponents();
//ICONE NA BARRA DE TITULO
URL url = this.getClass().getResource("icones/icoRecart.png");
imagemTitulo = Toolkit.getDefaultToolkit().getImage(url);
//ARQUIVO DE CONFIGURAÇÃO PARA PUXAR DIRETORIOS
config = new Propriedades();
opcoes = config.carregarOpcoes();
//ICONE BANDEJA DO SISTEMA (SEGUNDO PLANO)
URL urlTray = this.getClass().getResource("icones/iconTray.png");
imagemTray = Toolkit.getDefaultToolkit().getImage(urlTray);
this.setIconImage(imagemTitulo);
//CAMINHO DA IMAGEM PADRAO
String destino = System.getenv("ProgramFiles")+"\\Mensagem de Impressão\\ArteMsg.png";
InputStream is = null;
FileOutputStream fos = null;
int bytes = 0;
URL urlImg = null;
try {
urlImg = new URL(opcoes[0]);
is = urlImg.openStream();
fos = new FileOutputStream(destino);
while ((bytes = is.read()) != -1) {
fos.write(bytes);
}
is.close();
fos.close();
} catch (IOException ex) {
try {
urlImg = new URL("file:///"+System.getenv("ProgramFiles")+"/Mensagem de Impressão/ArteMsg.png");
} catch (MalformedURLException ex1) {
Logger.getLogger(FrmPrincipal.class.getName()).log(Level.SEVERE, null, ex1);
}
}
//SETAR IMAGEM
ImageIcon imgIcon = new ImageIcon(urlImg);
lblArte.setIcon(imgIcon);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
lblLink = new javax.swing.JLabel();
lblArte = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
setTitle("Mensagem de Impressão");
setResizable(false);
jPanel1.setLayout(null);
lblLink.setToolTipText("Recart Informática");
lblLink.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
lblLink.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
lblLinkMouseClicked(evt);
}
});
jPanel1.add(lblLink);
lblLink.setBounds(324, 390, 110, 30);
lblStatus.setFont(new java.awt.Font("Arial Narrow", 0, 16)); // NOI18N
lblStatus.setForeground(new java.awt.Color(102, 102, 102));
lblStatus.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jPanel1.add(lblStatus);
lblStatus.setBounds(0, 330, 450, 30);
lblArte.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblArte.setIcon(new javax.swing.ImageIcon(getClass().getResource("/HelloImpressora/icones/ArteMsg.png"))); // NOI18N
jPanel1.add(lblArte);
lblArte.setBounds(0, 0, 455, 430);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 445, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 420, Short.MAX_VALUE)
);
setSize(new java.awt.Dimension(461, 459));
setLocationRelativeTo(null);
}// </editor-fold>
private void lblLinkMouseClicked(java.awt.event.MouseEvent evt) {
try {
try {
Desktop.getDesktop().browse(new URI("http://recartinformatica.com.br"));
} catch (IOException ex) {
Logger.getLogger(FrmPrincipal.class.getName()).log(Level.SEVERE, null, ex);
}} catch (URISyntaxException ex) {
Logger.getLogger(FrmPrincipal.class.getName()).log(Level.SEVERE, null, ex);}
}
// Variables declaration - do not modify
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel lblArte;
private javax.swing.JLabel lblLink;
public static final javax.swing.JLabel lblStatus = new javax.swing.JLabel();
// End of variables declaration
}
/*
- To change this license header, choose License Headers in Project Properties.
- To change this template file, choose Tools | Templates
- and open the template in the editor.
*/
package HelloImpressora;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class Propriedades {
public File file = new File(System.getenv("ProgramFiles")+"\\Mensagem de Impressão\\properties.properties");
//File file = new File("properties.properties");
//Grava as opções de configuração
public void preencherOpcoes(String[] opcoes){
Properties props = new Properties();
try{
props.setProperty("caminho_fundo", opcoes[0]);
props.setProperty("msg_inicial", opcoes[1]);
props.setProperty("msg_impressao", opcoes[2]);
}catch(Exception er){
er.printStackTrace();
}
try{
FileOutputStream fos = new FileOutputStream(file);
props.store(fos, null);
fos.flush();
fos.close();
}catch(IOException er){
}
}
//Retorna as opções de configuração
public String[] carregarOpcoes(){
String[] opcoes = new String[3];
Properties props = new Properties();
try{
FileInputStream selecionado = new FileInputStream(file);
props.load(selecionado);
}catch(IOException er){
}
try{
opcoes[0] = props.getProperty("caminho_fundo");
opcoes[1] = props.getProperty("msg_inicial");
opcoes[2] = props.getProperty("msg_impressao");
}catch(Exception er){
er.printStackTrace();
}
return opcoes;
}
public String opcoesReq(String opcoes){
String retorno = "";
Properties props = new Properties();
try{
FileInputStream selecionado = new FileInputStream(file);
props.load(selecionado);
}catch(IOException er){
}
try{
retorno = props.getProperty(opcoes);
}catch(Exception er){
er.printStackTrace();
}
return retorno;
}
}
Ai esta alguns trechos dos código, esta mandando o arquivo completo em zip.
Mesmo usando o Crt+Shift+I não funcionou.