code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* 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 server;
import java.awt.Point;
/**
*
* @author Melis
*/
public class StartServerFrame extends javax.swing.JFrame {
/**
* Creates new form StartServerFrame
*/
public StartServerFrame() {
initComponents();
setLocation(new Point(500, 100));
}
/**
* 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">//GEN-BEGIN:initComponents
private void initComponents() {
cmbBanken = new javax.swing.JComboBox();
btnStart = new javax.swing.JButton();
btnStop = new javax.swing.JButton();
lblServerBackground = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Rainbow Sheep Software");
setName("StartFrame"); // NOI18N
setResizable(false);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
cmbBanken.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Rabobank", "Fortis Bank", "ABNAmro Bank", "Rainbow Sheep Bank" }));
cmbBanken.setBorder(null);
getContentPane().add(cmbBanken, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 200, 170, -1));
btnStart.setIcon(new javax.swing.ImageIcon(getClass().getResource("/server/Images/ServerPlayButton.gif"))); // NOI18N
btnStart.setBorder(null);
btnStart.setBorderPainted(false);
btnStart.setContentAreaFilled(false);
btnStart.setDebugGraphicsOptions(javax.swing.DebugGraphics.BUFFERED_OPTION);
btnStart.setDoubleBuffered(true);
btnStart.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/server/Images/ServerPlayButton_Selected.gif"))); // NOI18N
btnStart.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnStartActionPerformed(evt);
}
});
getContentPane().add(btnStart, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 270, -1, -1));
btnStop.setIcon(new javax.swing.ImageIcon(getClass().getResource("/server/Images/ServerStopButton.gif"))); // NOI18N
btnStop.setBorder(null);
btnStop.setBorderPainted(false);
btnStop.setContentAreaFilled(false);
btnStop.setDebugGraphicsOptions(javax.swing.DebugGraphics.BUFFERED_OPTION);
btnStop.setDoubleBuffered(true);
btnStop.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/server/Images/ServerStopButton_Selected.gif"))); // NOI18N
btnStop.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnStopActionPerformed(evt);
}
});
getContentPane().add(btnStop, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 270, -1, -1));
lblServerBackground.setIcon(new javax.swing.ImageIcon(getClass().getResource("/server/Images/StartServerBackground.gif"))); // NOI18N
lblServerBackground.setText("jLabel1");
lblServerBackground.setDebugGraphicsOptions(javax.swing.DebugGraphics.BUFFERED_OPTION);
lblServerBackground.setDoubleBuffered(true);
lblServerBackground.setMaximumSize(null);
lblServerBackground.setMinimumSize(null);
lblServerBackground.setPreferredSize(null);
getContentPane().add(lblServerBackground, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 650, 520));
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStartActionPerformed
if (bankserver == null) {
bankserver = new BankServer(this.cmbBanken.getSelectedItem().toString());
this.cmbBanken.setEnabled(false);
} else {
bankserver.startConnectie();
}
this.btnStart.setEnabled(false);
this.btnStop.setEnabled(true);
}//GEN-LAST:event_btnStartActionPerformed
private void btnStopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStopActionPerformed
bankserver.stopConnectie();
this.btnStart.setEnabled(true);
this.btnStop.setEnabled(false);
}//GEN-LAST:event_btnStopActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(StartServerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(StartServerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(StartServerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(StartServerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new StartServerFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnStart;
private javax.swing.JButton btnStop;
private javax.swing.JComboBox cmbBanken;
private javax.swing.JLabel lblServerBackground;
// End of variables declaration//GEN-END:variables
private BankServer bankserver;
}
| Java |
package server;
import API.Model.Klant;
import API.Model.LoginAccount;
import java.math.BigDecimal;
import managers.KlantManager;
import managers.LoginManager;
import managers.RekeningManager;
import API.Model.Rekening;
/**
* Deze klasse wordt vanuit BankServer geinstantieerd.
* En vult gegevens in de bank.
*/
public class DummyBank {
/**
* Constructor voor DummyBank. Hierin zijn wat dummy gegevens opgenomen.
* @param banknaam
*/
public DummyBank(String banknaam)
{
if (banknaam.equals("Rabobank"))
{
voegKlantToe("Ieme Welling", "Eindhoven", "ieme", "ieme");
voegKlantToe("test", "Ergens", "test", "test");
voegKlantToe("Melissa Coulthard", "Eindhoven", "Mel", "a");
voegKlantToe("Roland Ansems", "Somewhere", "Rollie", "Lolly");
voegKlantToe("Harry Harig", "Baurle-Naussau", "Harry", "Harry");
voegKlantToe("Barry van Bavel", "Loon op Zand", "Bar", "Weinig");
voegKlantToe("Superman", "Superwereld", "Superman", "Hero");
voegKlantToe("Theo Maassen", "Eindhoven", "Theootje", "123");
}
else if (banknaam.equals("Fortis Bank"))
{
voegKlantToe("Mr. Test", "Ergens", "teest", "teest");
voegKlantToe("Mr. Fret", "Ergens", "fret", "fret");
}
}
/**
* Methode om klanten eenvoudig toe te voegen aan de server middels deze dummyklasse.
* @param naam van de klant
* @param woonplaats van de klant
* @param klantlogin van de klant
* @param wachtwoord van de klant
*/
private void voegKlantToe(String naam, String woonplaats, String klantlogin, String wachtwoord)
{
KlantManager km = KlantManager.getInstance();
LoginManager lm = LoginManager.getInstance();
RekeningManager rm = RekeningManager.getInstance();
Klant klant = new Klant(naam, woonplaats);
Rekening rekeningKlant = new Rekening(rm.getBankInitialen());
rekeningKlant.stort(new BigDecimal(50));
LoginAccount loginKlant = new LoginAccount(klantlogin, wachtwoord, klant.getKlantNr(), rekeningKlant.getRekeningnummer());
km.addKlant(klant);
lm.addLogin(loginKlant);
rm.addRekening(rekeningKlant);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package server;
import API.IAuth;
import API.ITransactieHandler;
import CiClient.CiConnector;
import java.rmi.NoSuchObjectException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.logging.Level;
import java.util.logging.Logger;
import controller.Auth;
import controller.TransactieHandler;
import managers.RekeningManager;
/**
* Dit is de klasse waar de server geinstantieerd wordt.
*/
public class BankServer {
private static Auth login;
private static TransactieHandler transactie;
private static Registry registry;
private String bankNaam;
private DummyBank db;
// Om te zorgen dat objecten niet GC'ed worden moet de return waarde van de stubs bijgehouden worden.
// zie: http://stackoverflow.com/questions/5165320/rmi-server-stops
private static IAuth loginStub;
private static ITransactieHandler transactieStub;
/**
* Constructor voor de Server van een bank. Hierin wordt geprobeerd een RMI
* connectie open te zetten zodat clients deze kunnen benaderen. Er worden 2
* stubs gemaakt. Een voor login waarmee simpele data opgehaald wordt bij de
* server. Een voor transactie waarmee transacties opgehaald kunnen worden
* bij de server.
* @param bank Naam van de bank
*/
public BankServer(String bank) {
this.bankNaam = bank;
if (System.getSecurityManager() == null) {
SecurityManager securM = new SecurityManager();
System.setSecurityManager(securM);
}
try {
LocateRegistry.createRegistry(1099);
registry = LocateRegistry.getRegistry();
} catch (RemoteException ex) {
Logger.getLogger(BankServer.class.getName()).log(Level.SEVERE, null, ex);
}
startConnectie();
try {
CiConnector ciConnector = new CiConnector("RABO", "testkey");
} catch (RemoteException | NotBoundException ex) {
Logger.getLogger(BankServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void loadData() {
db = new DummyBank(this.bankNaam);
}
/**
* Methode om de server uit het RMI Registry te halen.
*/
public void stopConnectie()
{
try {
UnicastRemoteObject.unexportObject(login, false);
UnicastRemoteObject.unexportObject(transactie, false);
registry.unbind("transactie");
registry.unbind("auth");
} catch (NoSuchObjectException ex) {
Logger.getLogger(BankServer.class.getName()).log(Level.SEVERE, null, ex);
} catch (RemoteException ex) {
Logger.getLogger(BankServer.class.getName()).log(Level.SEVERE, null, ex);
} catch (NotBoundException ex) {
Logger.getLogger(BankServer.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(this.bankNaam + " Server gestopt");
}
/**
* Methode om de server in het RMI Registry te zetten (maken van stubs).
* Verder wordt in rekeningmanager de bankintialen gezet.
*/
public void startConnectie()
{
this.login = new Auth();
this.transactie = new TransactieHandler();
//zet bankinitialen.
RekeningManager rekman = RekeningManager.getInstance();
rekman.setBankInitialen(bankNaam);
loadData();
try {
transactieStub = (ITransactieHandler) UnicastRemoteObject.exportObject(transactie, 0);
loginStub = (IAuth) UnicastRemoteObject.exportObject(login, 0);
registry.rebind("transactie", transactieStub);
registry.rebind("auth", loginStub);
System.out.println(this.bankNaam + " Server gestart");
} catch (RemoteException ex) {
System.out.println(ex);
Logger.getLogger(BankServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
| Java |
package controller;
import API.IClient;
import API.Model.LoginAccount;
import java.sql.Timestamp;
import java.util.UUID;
/**
* Sessie object om authenticatie te versimpelen. Eenmalig login nodig waarna de
* sessie blijft leven tot 10 minuten na de laatste activiteit.
*/
public class Sessie {
private Timestamp lastActivity;
private final String SessieId;
private final LoginAccount login;
private IClient client;
/**
* Initialiseerd het sessie object. Na initialisatie is er een sessieID
* gegenereerd en wordt er een sessietask ingepland om de sessie te
* beindigen.
* @param login Het login account waarvoor de sessie gestart wordt.
*/
public Sessie(LoginAccount login) {
//UUID genereert een random unique nummer van 128 bits.
//Absolute zekerheid op uniqueness krijg je hiermee niet, maar ruim voldoende voor opdracht.
//Absolute zekerheid alleen te verkrijgen door lijst met verbruikte id's bij te houden of synced counter.
this.SessieId = UUID.randomUUID().toString();
this.login = login;
updateActivity();
}
/**
* Een get-methode voor de sessieID
* @return de sessieID
*/
public String getSessieId() {
return this.SessieId;
}
/**
* Een get-methode voor het loginaccount
* @return het loginaccount
*/
public LoginAccount getLogin() {
updateActivity();
return login;
}
/**
* Een get-methode om de IClient op te vragen
* @return de IClient waarvoor deze sessie geregistreerd is.
*/
public IClient getClient() {
return client;
}
/**
* Methode om de client te zetten bij deze sessie.
* @param client die client die bij deze specifieke sessie hoort.
*/
public void setClient(IClient client) {
updateActivity();
this.client = client;
}
/**
* Een get methode om de laatste activiteit op te halen.
* @return timestamp van laatste activiteit.
*/
public Timestamp getLastActivity() {
return lastActivity;
}
/**
* Methode om laatste activiteit up te daten naar huidige datumtijd.
*/
public void updateActivity() {
java.util.Date date = new java.util.Date();
this.lastActivity = new Timestamp(date.getTime());
}
/**
* Methode om loginaccount op te vragen bij de sessie
* hierbij wordt de lastactivity niet geupdate. Deze methode wordt namelijk via
* de callback functie vanuit de client (sessieframe) aangeroepen wanneer
* de transacties worden opgevraagd.
* @return
*/
public LoginAccount getLoginNoActivityChange() {
return login;
}
}
| Java |
package controller;
import API.IAuth;
import API.IClient;
import API.IObservable;
import API.Model.Klant;
import API.Model.LoginAccount;
import API.Model.Rekening;
import API.Model.SessieExpiredException;
import java.math.BigDecimal;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import managers.*;
/**
* De server verstuurt berichten naar de ClientImpl middels deze klasse. Deze
* klasse implementeert IAuth en bij ClientImpl is IAuth ook bekend. Zodanig kan
* de klant onderstaande methoden opvragen bij de server.
*/
public class Auth implements IAuth {
private static HashMap<IObservable, ArrayList<String>> obs = new HashMap<>();
//private String bankinitialen;
/**
* Methode die overgenomen is uit IAuth. En waarmee een sessie gestart wordt.
* @param username inlognaam van de klant.
* @param password wachtwoord van de klant.
* @return sessieID
* @throws RemoteException moet afgevangen worden wanneer het via RMI gaat.
*/
@Override
public synchronized String startSessie(String username, String password) throws RemoteException {
LoginManager loginManager = LoginManager.getInstance();
try {
LoginAccount login = loginManager.getLoginAccount(username, password);
Sessie newSessie = new Sessie(login);
SessieManager sm = SessieManager.getInstance();
sm.addSessie(newSessie);
return newSessie.getSessieId();
} catch (IllegalArgumentException e) {
throw e;
}
}
/**
* Methode die een nieuwe klant registreert en daarbij kijkt of een klant al bestaat of niet.
* Bestaat de klant al, dan wordt dat klantnummer gebruikt. Bestaat klant niet, dan wordt er
* een nieuwe klant nummer aan gegeven.
* @param klantnaam naam van de klant.
* @param woonplaats woonplaats van de klant.
* @param gebruikersnaam gebruikersnaam van de klant.
* @param wachtwoord wachtwoord van de klant.
* @return true als het gelukt is om de klant te registreren. False als het niet gelukt is.
* @throws RemoteException moet afgevangen worden wanneer het via RMI gaat.
*/
@Override
public synchronized boolean registreerNieuweKlant(String klantnaam, String woonplaats, String gebruikersnaam, String wachtwoord) throws NullPointerException, IllegalArgumentException, RemoteException
{
KlantManager klantmanager = KlantManager.getInstance();
LoginManager loginmanager = LoginManager.getInstance();
RekeningManager rekeningmanager = RekeningManager.getInstance();
//Wanneer klantnaam of woonplaats leeg zijn, moet een exceptie gegooid worden.
if(klantnaam == null | klantnaam.isEmpty() | woonplaats == null | woonplaats.isEmpty())
//verandert naar inclusive ipv xor, beide moeten ingevuld zijn.
{
throw new NullPointerException("Graag alle verplichte velden invullen");
}
klantnaam = klantnaam.trim();
gebruikersnaam = gebruikersnaam.trim();
woonplaats = woonplaats.trim();
if(!Klant.isAlphabetical(klantnaam) | !Klant.isPlaatsnaam(woonplaats)) {
throw new IllegalArgumentException("Naam en of woonplaats bevatten illegale karakters");
}
if(!LoginAccount.isAlphanumeric(gebruikersnaam)) {
throw new IllegalArgumentException("gebruikersnaam bevat illegale karakters, gebruikersnaam mag uit letters en cijfers bestaan");
}
//loginnaam mag niet bekend zijn in het banksysteem. Loginnamen zijn uniek.
if(!loginmanager.bestaatLoginNaam(gebruikersnaam))
{
//Er hoeft geen nieuwe klant toegevoegd te worden als klantobject al bestaat.
if (klantmanager.getBestaandeKlantNummer(klantnaam, woonplaats) != 0){
int klantnummer = klantmanager.getBestaandeKlantNummer(klantnaam, woonplaats);
Rekening rekening = new Rekening(rekeningmanager.getBankInitialen());
LoginAccount loginaccount = new LoginAccount(gebruikersnaam, wachtwoord, klantnummer, rekening.getRekeningnummer());
loginmanager.addLogin(loginaccount);
rekeningmanager.addRekening(rekening);
return true;
}
//Wanneer er nog geen klantobject bestaat dan moet er wel een nieuw klantobject aangemaakt worden en bij klantmanager geregistreerd worden.
else {
Klant klant = new Klant(klantnaam, woonplaats);
Rekening rekening = new Rekening(rekeningmanager.getBankInitialen());
LoginAccount loginaccount = new LoginAccount(gebruikersnaam, wachtwoord, klant.getKlantNr(), rekening.getRekeningnummer());
klantmanager.addKlant(klant);
loginmanager.addLogin(loginaccount);
rekeningmanager.addRekening(rekening);
return true;
}
}
return false;
}
/**
* Methode om de sessie te stoppen.
* @param sessionId sessieID die gestopt moet worden.
* @throws RemoteException moet afgevangen worden wanneer het via RMI gaat.
* @throws SessieExpiredException moet afgevangen worden om te kijken of de klant 10 mins inactief is geweest.
*/
@Override
public synchronized void stopSessie(String sessionId) throws RemoteException, SessieExpiredException {
SessieManager.getInstance().stopSessie(sessionId);
}
/**
* Methode om klant op te vragen.
* @param sessionId SessieId
* @return Klant object
* @throws RemoteException moet afgevangen worden wanneer het via RMI gaat.
* @throws SessieExpiredException moet afgevangen worden om te kijken of de klant 10 mins inactief is geweest.
*/
@Override
public synchronized Klant getKlant(String sessionId) throws RemoteException, SessieExpiredException {
SessieManager sm = SessieManager.getInstance();
try {
LoginAccount login = sm.getAccountFromSessie(sessionId);
KlantManager km = KlantManager.getInstance();
Klant k = km.getKlant(login.getKlantNr());
registerObservable(k, sessionId);
return k;
} catch (SessieExpiredException e) {
throw e;
}
}
/**
* Methode om rekening op te vragen.
* @param sessionId sessieID is nodig om Rekening op te vragen.
* @return Rekening object
* @throws RemoteException moet afgevangen worden wanneer het via RMI gaat.
* @throws SessieExpiredException moet afgevangen worden om te kijken of de klant 10 mins inactief is geweest.
*/
@Override
public synchronized Rekening getRekening(String sessionId) throws RemoteException, SessieExpiredException {
SessieManager sm = SessieManager.getInstance();
try {
LoginAccount login = (LoginAccount) sm.getAccountFromSessie(sessionId);
RekeningManager rm = RekeningManager.getInstance();
Rekening r = rm.getRekening(login.getRekeningNr());
registerObservable(r, sessionId);
return r;
} catch (SessieExpiredException e) {
throw e;
}
}
/** Methode om wachtwoord te resetten. Wordt momenteel nog niet gebruikt.
* @param sessionId SessieID
* @param username gebruikersnaam van de klant
* @param password wachtwoord van de klant.
* @return true als wachtwoord succesvol gereset is, false als het niet gelukt is.
* @throws RemoteException moet afgevangen worden wanneer het via RMI gaat.
* @throws SessieExpiredException moet afgevangen worden om te kijken of de klant 10 mins inactief is geweest.
*/
@Override
public synchronized boolean resetWachtwoord(String sessionId, String username, String password) throws RemoteException, SessieExpiredException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Methode om client object te registreren bij de bankserver.
* @param sessieId sessieID behorende bij client object.
* @param clientObj IClient object.
* @throws RemoteException moet afgevangen worden wanneer het via RMI gaat.
* @throws SessieExpiredException moet afgevangen worden om te kijken of de klant 10 mins inactief is geweest.
*/
@Override
public synchronized void registreerClientObject(String sessieId, IClient clientObj) throws RemoteException, SessieExpiredException {
SessieManager sm = SessieManager.getInstance();
try {
sm.bindClientObjecToSessie(sessieId, clientObj);
} catch (SessieExpiredException e) {
throw e;
}
}
/**
* Deze methode wordt ALLEEN voor demo doeleinden gebruikt. In de deployment moet
* deze methode er natuurlijk uitgehaald worden.
* @param sessieId id van de sessie.
* @param bedrag bedrag dat gestort wordt op het eigen reknr.
* @throws RemoteException moet afgevangen worden wanneer het via RMI gaat.
* @throws SessieExpiredException moet afgevangen worden om te kijken of de klant 10 mins inactief is geweest.
*/
@Override
public synchronized void stort(String sessieId, BigDecimal bedrag) throws RemoteException, SessieExpiredException {
SessieManager sm = SessieManager.getInstance();
LoginAccount login = (LoginAccount) sm.getAccountFromSessie(sessieId);
RekeningManager rm = RekeningManager.getInstance();
Rekening r = rm.getRekening(login.getRekeningNr());
r.stort(bedrag);
}
/**
* Methode om objecten te updaten. Wordt via overerving van IObserver in IAuth hierin opgenomen.
* @param observable Observable object.
* @param arg nieuwe object.
* @throws RemoteException moet afgevangen worden wanneer het via RMI gaat.
*/
@Override
public synchronized void update(Object observable, Object arg) throws RemoteException {
IObservable o = (IObservable) observable;
if (obs.containsKey(o)) {
ArrayList<String> sessieIds = obs.get(o);
if (sessieIds == null || sessieIds.isEmpty()) {
//geen observers bekend bij sessieId
obs.remove(o);
return;
}
ArrayList<String> shadowIds = new ArrayList<>();
for (String sid : sessieIds) {
shadowIds.add(sid);
}
for (String sessieId : shadowIds) {
IClient client = null;
try {
client = SessieManager.getInstance().getClient(sessieId);
} catch (SessieExpiredException ex) {
Logger.getLogger(Auth.class.getName()).log(Level.SEVERE, null, ex);
}
if (client != null) {
client.setObservable(o);
} else {
//geen client object bekend bij observer, uit de lijst gooien want kan nooit geupdate worden.
sessieIds.remove(sessieId);
}
}
}
}
/**
* Methode om observables te registreren bij een instantie van deze klasse.
* @param o IObservable object.
* @param sessieId SessieId
*/
private synchronized void registerObservable(IObservable o, String sessieId) {
ArrayList<String> sessieIds;
o.addObserver(this);
if (obs.containsKey(o)) {
sessieIds = obs.get(o);
boolean exists = false;
while (!exists) {
for (String sId : sessieIds) {
if (sessieId.equals(sId)) {
exists = true;
}
}
break;
}
if (!exists) {
sessieIds.add(sessieId);
}
} else {
sessieIds = new ArrayList<>();
sessieIds.add(sessieId);
obs.put(o, sessieIds);
}
}
/**
* Methode om loginaccount op te vragen.
* @param sessionId SessieID van client die dit opvraagt.
* @return LoginAccount object
* @throws RemoteException moet afgevangen worden wanneer het via RMI gaat.
* @throws SessieExpiredException moet afgevangen worden om te kijken of de klant 10 mins inactief is geweest.
*/
@Override
public synchronized LoginAccount getLoginAccount(String sessionId) throws RemoteException, SessieExpiredException {
SessieManager sm = SessieManager.getInstance();
try {
LoginAccount login = sm.getAccountFromSessie(sessionId);
return login;
} catch (SessieExpiredException e) {
throw e;
}
}
}
| Java |
package controller;
import API.Model.SessieExpiredException;
import API.IClient;
import API.IObservable;
import API.Model.Transactie;
import API.ITransactieHandler;
import API.Model.LoginAccount;
import API.Model.TransactieStatus;
import API.Model.TransactieType;
import java.math.BigDecimal;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import managers.SessieManager;
import managers.TransactieManager;
/**
* De server verstuurt berichten naar de ClientImpl middels deze klasse. Deze
* klasse implementeert ITransactie en bij ClientImpl is ITransactie ook bekend.
* Zodanig kan de klant onderstaande methoden opvragen bij de server.
*/
public class TransactieHandler implements ITransactieHandler {
private static HashMap<IObservable, ArrayList<String>> obs = new HashMap<>();
/**
* Hiermee wordt een nieuwe transactie aangevraagd.
*
* @param sessieId sessieID van een actieve sessie
* @param recipientRekeningnummer rekeningnummer van de ontvanger
* @param bedrag het over te maken bedrag
* @param comment beschrijving die bij de transactie ingevuld is
* @return Transactie object
* @throws RemoteException - Zodra er gebruik gemaakt wordt van Remote, moet
* deze exceptie afgevangen worden.
* @throws SessieExpiredException wordt gegooid wanneer de sessie van de
* klant verlopen is.
*/
@Override
public synchronized Transactie requestTransaction(String sessieId, String recipientRekeningnummer, BigDecimal bedrag, String comment) throws SessieExpiredException, RemoteException, IllegalArgumentException {
//check of tegenrekeningnummer en bedrag gevuld zijn
if (recipientRekeningnummer.isEmpty() || recipientRekeningnummer.equals("") || bedrag == null) {
throw new IllegalArgumentException("Vul alle verplichte velden in");
}
if (bedrag.compareTo(BigDecimal.ZERO) < 1) {
throw new IllegalArgumentException("Over te schrijven bedrag moet groter zijn dan 0");
}
//haal rekeningnummer op van klant behorende bij sessieID
LoginAccount login = SessieManager.getInstance().getAccountFromSessie(sessieId);
if (login != null) {
//check of tegenrekeningnummer anders is dan van-rekeningnummer
if (login.getRekeningNr().equals(recipientRekeningnummer)) {
throw new IllegalArgumentException("Het tegen rekeningnummer kan niet hetzelfde zijn als het eigen rekeningnummer");
}
Transactie trans = new Transactie(login.getRekeningNr(), recipientRekeningnummer, bedrag, comment);
TransactieManager.getInstance().addTransactie(trans);
//voeg observale toe
registerObservable(trans, sessieId);
return trans;
}
return null;
}
/**
* Methode om bestaande transactie op te zoeken tussen gegeven datums. De
* rekening bijbehorende aan het actieve sessieId moet bekend zijn in deze
* transactie!
*
* @param sessieId sessieId van een actieve sessie
* @param vanafDatum Datum vanaf we transactie opzoeken
* @param totDatum Datum tot we transacties opzoeken. Null = heden.
* @return ArrayList met transactie objects.
* @throws RemoteException - Zodra er gebruik gemaakt wordt van Remote, moet
* deze exceptie afgevangen worden.
* @throws SessieExpiredException wordt gegooid wanneer de sessie van de
* klant verlopen is.
*/
@Override
public synchronized ArrayList<Transactie> getTransacties(String sessieId, GregorianCalendar vanafDatum, GregorianCalendar totDatum) throws RemoteException, SessieExpiredException {
return getTransacties(sessieId, vanafDatum, totDatum, null, TransactieType.ALLE);
}
/**
* Methode om bestaande transactie op te zoeken tussen gegeven datums. De
* rekening bijbehorende aan het actieve sessieId moet bekend zijn in deze
* transactie!
*
* @param sessieId sessieId van een actieve sessie
* @param vanafDatum Datum vanaf we transactie opzoeken
* @param totDatum Datum tot we transacties opzoeken. mag null zijn.
* @param status status van de transacties. type TransactieStatus
* @return ArrayList met transactie objects.
* @throws RemoteException - Zodra er gebruik gemaakt wordt van Remote, moet
* deze exceptie afgevangen worden.
* @throws SessieExpiredException wordt gegooid wanneer de sessie van de
* klant verlopen is.
*/
@Override
public synchronized ArrayList<Transactie> getTransacties(String sessieId, GregorianCalendar vanafDatum, GregorianCalendar totDatum, TransactieStatus status) throws RemoteException, SessieExpiredException {
return getTransacties(sessieId, vanafDatum, totDatum, status, TransactieType.ALLE);
}
/**
* Methode om bestaande transactie op te zoeken tussen gegeven datums. De
* rekening bijbehorende aan het actieve sessieId moet bekend zijn in deze
* transactie!
*
* @param sessieId sessieId van een actieve sessie
* @param vanafDatum Datum vanaf we transactie opzoeken
* @param totDatum Datum tot we transacties opzoeken. mag null zijn.
* @param type type van de transactie als TransactieType. (debet of credit
* t.o.v. de aanvrager)
* @return ArrayList met transactie objects.
* @throws RemoteException - Zodra er gebruik gemaakt wordt van Remote, moet
* deze exceptie afgevangen worden.
* @throws SessieExpiredException wordt gegooid wanneer de sessie van de
* klant verlopen is.
*/
@Override
public synchronized ArrayList<Transactie> getTransacties(String sessieId, GregorianCalendar vanafDatum, GregorianCalendar totDatum, TransactieType type) throws RemoteException, SessieExpiredException {
return getTransacties(sessieId, vanafDatum, totDatum, null, type);
}
/**
* Methode om bestaande transactie op te zoeken tussen gegeven datums. De
* rekening bijbehorende aan het actieve sessieId moet bekend zijn in deze
* transactie!
*
* @param sessieId sessieId van een actieve sessie
* @param vanafDatum Datum vanaf we transactie opzoeken
* @param totDatum Datum tot we transacties opzoeken. mag null zijn.
* @param status status van de transacties. type TransactieStatus
* @param type type van de transactie als TransactieType. (debet of credit
* t.o.v. de aanvrager)
* @return ArrayList met transactie objects.
* @throws RemoteException - Zodra er gebruik gemaakt wordt van Remote, moet
* deze exceptie afgevangen worden.
* @throws SessieExpiredException wordt gegooid wanneer de sessie van de
* klant verlopen is.
*/
@Override
public synchronized ArrayList<Transactie> getTransacties(String sessieId, GregorianCalendar vanafDatum, GregorianCalendar totDatum, TransactieStatus status, TransactieType type) throws RemoteException, SessieExpiredException {
LoginAccount login = SessieManager.getInstance().getAccountFromSessieNoActivityChange(sessieId);
if (login != null) {
String rekeningnr = login.getRekeningNr();
ArrayList<Transactie> iTransacties = new ArrayList<>();
ArrayList<Transactie> transacties = TransactieManager.getInstance().getTransacties(rekeningnr, null, vanafDatum, totDatum, status, type);
for (Transactie trans : transacties) {
iTransacties.add(trans);
}
return iTransacties;
}
return null;
}
/**
* Methode om aan het object die een ander object observeert, een update te
* geven van een nieuw object.
*
* @param observable Een object dat observable object
* @param arg Het geupdate object dat door de observable gebruikt wordt.
* @throws RemoteException - Zodra er gebruik gemaakt wordt van Remote, moet
* deze exceptie afgevangen worden.
*/
@Override
public synchronized void update(Object observable, Object arg) throws RemoteException {
IObservable o = (IObservable) observable;
if (obs.containsKey(o)) {
ArrayList<String> sessieIds = obs.get(o);
if (sessieIds == null || sessieIds.isEmpty()) {
//geen observers bekend bij sessieId
obs.remove(o);
return;
}
ArrayList<String> shadowIds = new ArrayList<>();
for (String sid : sessieIds) {
shadowIds.add(sid);
}
for (String sessieId : shadowIds) {
IClient client = null;
try {
client = SessieManager.getInstance().getClient(sessieId);
} catch (SessieExpiredException ex) {
Logger.getLogger(Auth.class.getName()).log(Level.SEVERE, null, ex);
} finally {
//geen client object bekend bij observer, uit de lijst gooien want kan nooit geupdate worden.
sessieIds.remove(sessieId);
}
if (client != null) {
client.setObservable(o);
}
}
}
}
/**
* Methode om Observables te registreren bij een instantie van deze klasse.
*
* @param o IObservable object.
* @param sessieId SessieID van client.
*/
private synchronized void registerObservable(IObservable o, String sessieId) {
ArrayList<String> sessieIds;
o.addObserver(this);
if (obs.containsKey(o)) {
sessieIds = obs.get(o);
boolean exists = false;
while (!exists) {
for (String sId : sessieIds) {
if (sessieId.equals(sId)) {
exists = true;
}
}
break;
}
if (!exists) {
sessieIds.add(sessieId);
}
} else {
sessieIds = new ArrayList<>();
sessieIds.add(sessieId);
obs.put(o, sessieIds);
}
}
}
| Java |
/*
* 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 API;
/**
*
* @author Melis
*/
public enum TransactieStatus {
/** Wanneer een transactie verwerkt is door de bank krijgt het de status voltooid.
*/
VOLTOOID,
/** Wanneer een transactie nog niet verwerkt is door de bank krijgt het de status openstaand,
* alleen tijdens deze status kan de transactie geannuleerd worden.
*/
OPENSTAAND,
/** Wanneer een transactie tijdig geannuleerd wordt, zal het niet door de bank worden
* verwerkt.
*/
GEANNULEERD,
/** Wanneer een transactie niet verwerkt kon worden door de bank omdat er iets mis is gegaan
* (bijvoorbeeld de connectie met de centrale instantie) wordt de transactie tijdelijk uitgesteld.
*/
UITGESTELD,
/** Wanneer de bank de transactie probeerde te verwerken, maar er geen bestaande tegenrekeningnummer
* was, zal de transactie geweigerd worden.
*/
GEWEIGERD;
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package API;
/**
*
* @author Ieme
*/
public interface IKlant {
/**
* Stuurt de klantnaam terug
* @return klantnaam
*/
String getKlantnaam();
/**
* Stuurt de woonplaats van de klant terug
* @return klantwoonplaats
*/
String getKlantwoonplaats();
int getKlantNr();
}
| Java |
/*
* 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 API;
/**
*
*/
public interface IObservable {
/**
* voegt een observer object toe
* @param observer
*/
void addObserver(IObserver observer);
public int getObservableId();
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package API;
import Bank.Model.SessieExpiredException;
import java.math.BigDecimal;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.GregorianCalendar;
/**
*
* @author Ieme
*/
public interface ITransactieHandler extends IObserver {
/**
* Hiermee wordt een nieuwe transactie aangevraagd.
* @param sessieId sessieID van een actieve sessie
* @param recipientRekeningnummer rekeningnummer van de ontvanger
* @param bedrag het over te maken bedrag
* @return Transactie object
* @throws RemoteException
* @throws SessieExpiredException
*/
public ITransactie requestTransaction(String sessieId, int recipientRekeningnummer, BigDecimal bedrag, String comment) throws RemoteException, SessieExpiredException;
/**
* Methode om bestaande transactie op te zoeken tussen gegeven datums.
* De rekening bijbehorende aan het actieve sessieId moet bekend zijn in deze transactie!
* @param sessieId sessieId van een actieve sessie
* @param vanafDatum Datum vanaf we transactie opzoeken
* @param totDatum Datum tot we transacties opzoeken. Null = heden.
* @return ArrayList met transactie objects.
* @throws RemoteException
* @throws SessieExpiredException
*/
public ArrayList<ITransactie> getTransacties(String sessieId, GregorianCalendar vanafDatum, GregorianCalendar totDatum) throws RemoteException, SessieExpiredException;
/**
* Methode om bestaande transactie op te zoeken tussen gegeven datums.
* De rekening bijbehorende aan het actieve sessieId moet bekend zijn in deze transactie!
* @param sessieId sessieId van een actieve sessie
* @param vanafDatum Datum vanaf we transactie opzoeken
* @param totDatum Datum tot we transacties opzoeken. mag null zijn.
* @param status status van de transacties. type TransactieStatus
* @return ArrayList met transactie objects.
* @throws RemoteException
* @throws SessieExpiredException
*/
public ArrayList<ITransactie> getTransacties(String sessieId, GregorianCalendar vanafDatum, GregorianCalendar totDatum, TransactieStatus status) throws RemoteException, SessieExpiredException;
/**
* Methode om bestaande transactie op te zoeken tussen gegeven datums.
* De rekening bijbehorende aan het actieve sessieId moet bekend zijn in deze transactie!
* @param sessieId sessieId van een actieve sessie
* @param vanafDatum Datum vanaf we transactie opzoeken
* @param totDatum Datum tot we transacties opzoeken. mag null zijn.
* @param type type van de transactie als TransactieType. (debet of credit t.o.v. de aanvrager)
* @return ArrayList met transactie objects.
* @throws RemoteException
* @throws SessieExpiredException
*/
public ArrayList<ITransactie> getTransacties(String sessieId, GregorianCalendar vanafDatum, GregorianCalendar totDatum, TransactieType type) throws RemoteException, SessieExpiredException;
/**
* Methode om bestaande transactie op te zoeken tussen gegeven datums.
* De rekening bijbehorende aan het actieve sessieId moet bekend zijn in deze transactie!
* @param sessieId sessieId van een actieve sessie
* @param vanafDatum Datum vanaf we transactie opzoeken
* @param totDatum Datum tot we transacties opzoeken. mag null zijn.
* @param status status van de transacties. type TransactieStatus
* @param type type van de transactie als TransactieType. (debet of credit t.o.v. de aanvrager)
* @return ArrayList met transactie objects.
* @throws RemoteException
* @throws SessieExpiredException
*/
public ArrayList<ITransactie> getTransacties(String sessieId, GregorianCalendar vanafDatum, GregorianCalendar totDatum, TransactieStatus status, TransactieType type) throws RemoteException, SessieExpiredException;
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package API;
import java.math.BigDecimal;
import java.util.GregorianCalendar;
/**
*
* @author Ieme
*/
public interface ITransactie {
public int getTransactieId();
public int getEigenbankrekening();
public int getTegenrekening();
public BigDecimal getBedrag();
public TransactieStatus getStatus();
public GregorianCalendar getTransactieInvoerDatum();
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package API;
/**
*
* @author Ieme
*/
public interface ILoginAccount {
/**
* stuurt de loginnaam van het loginaccount terug
* @return LoginNaam
*/
public String getLoginNaam();
/**
* stuurt het klantnr van het loginaccount terug
* @return KlantNr
*/
public int getKlantNr();
/**
* stuurt het rekeningnr van het loginaccount terug
* @return rekeningnr
*/
public int getRekeningNr();
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package API;
import java.math.BigDecimal;
/**
*
* @author Ieme
*/
public interface IRekening {
/**
* stuurt het rekeningnummer van de rekening terug
* @return Rekeningnummer
*/
public int getRekeningnummer();
/**
* stuurt het saldo van de rekening terug
* @return Saldo
*/
public BigDecimal getSaldo();
/**
* stuurt het kredietlimiet van de rekening terug
* @return Kredietlimiet
*/
public BigDecimal getKredietlimiet();
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package API;
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
* Deze interface wordt geinstantieerd aan de client zijde.
*
* Zodoende kan de server methodes van de client aanroepen. De server kan de
* client remote "uitloggen" en kan de client laten weten dat het saldo van de
* rekening is gewijzigd.
*
*/
public interface IClient extends Remote {
/**
* Methode om de client te melden dat de sessie is verlopen en dat hij uitgelogd wordt.
* @throws java.rmi.RemoteException - Zodra er gebruik gemaakt wordt van Remote, moet deze exceptie afgevangen worden.
*/
public void logOut() throws RemoteException;
public void setObservable(IObservable ob) throws RemoteException;
}
| Java |
/*
* 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 API;
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
*/
public interface IObserver extends Remote {
/**
* Methode om aan het object die een ander object observeert, een update te geven van een nieuw object.
* @param observable
* @param updateBericht
*/
void update(Object observable, Object arg) throws RemoteException;
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package API;
import Bank.Model.SessieExpiredException;
import java.math.BigDecimal;
import java.rmi.RemoteException;
/**
* Interface waarmee client een sessie kan starten en een client haar basis
* gegevens kan opvragen Tevens verantwoordelijk voor bijhouden
* clientRMIobjecten
*
*/
public interface IAuth extends IObserver {
/**
* Deze methode is er alleen als snel voorbeeld. Dit moet als een transactie
* behandeld worden.
*/
public void stort(String sessieId, BigDecimal bedrag) throws RemoteException, SessieExpiredException;
/**
* Starten van een sessie. Mits succesvol wordt er een sessieId terug
* gegeven, anders null
*
* @param username client username om in te loggen
* @param password client password om in te loggen
* @return String sessieId of null
* @throws RemoteException
*/
public String startSessie(String username, String password) throws RemoteException, IllegalArgumentException;
/**
* Hiermee kan een ClientObj geregistreert worden bij de server. Zodoende
* kan de server remote calls maken bij de client.
*
* @param sessieId sessieId van actieve sessie
* @param clientObj IClient object om remote calls uit te voeren bij de
* client.
* @throws RemoteException
* @throws SessieExpiredException
*/
public void registerClientObj(String sessieId, IClient clientObj) throws RemoteException, SessieExpiredException;
/**
* Hiermee kan een bestaande sessie worden beeindigd. Returned true als het
* gelukt is, anders false.
*
* @param sessionId sessieId van bestaande sessie
* @return true wanneer succesvol, false wanneer niet succesvol.
* @throws RemoteException
* @throws SessieExpiredException
*/
public void stopSessie(String sessionId) throws RemoteException, SessieExpiredException;
/**
* Methode om wachtwoord aan te passen.
*
* @param sessionId sessieId van bestaande sessie
* @param username username van de client.
* @param password nieuwe password van de client.
* @return true wanneer succesvol.
* @throws RemoteException
* @throws SessieExpiredException
*/
public boolean resetWachtwoord(String sessionId, String username, String password) throws RemoteException, SessieExpiredException;
/**
* Methode om klant object (gegevens) van een actieve sessie te verkrijgen
*
* @param sessionId sessieID van actieve sessie
* @return Klant object.
* @throws RemoteException
* @throws SessieExpiredException
*/
public IKlant getKlant(String sessionId) throws RemoteException, SessieExpiredException;
/**
* Methode om rekening object bij een actieve sessie te verkrijgen.
*
* @param sessionId sessieId van actieve sessie
* @return Rekening object bij actieve sessie.
* @throws RemoteException
* @throws SessieExpiredException
*/
public IRekening getRekening(String sessionId) throws RemoteException, SessieExpiredException;
/**
* Methode om loginaccount object bij een actieve sessie op te vragen.
* @param sessionId sessieId van actieve sessie
* @return LoginAccount object bij actieve sessie.
* @throws RemoteException
* @throws SessieExpiredException
*/
public ILoginAccount getLoginAccount(String sessionId) throws RemoteException, SessieExpiredException;
/**
* Methode om een nieuwe klant + loginaccount + rekening aan te maken.
* @param klantnaam
* @param woonplaats
* @param gebruikersnaam
* @param wachtwoord
* @return
* @throws RemoteException
*/
public boolean registreerNieuweKlant(String klantnaam, String woonplaats, String gebruikersnaam, String wachtwoord) throws RemoteException;
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package API;
/**
* Gebruiken om transacties op te zoeken.
*
*/
public enum TransactieType {
/** Wanneer er geld op een rekening gestort wordt, zal dit debet zijn.
*/
DEBET,
/** Wanneer er geld van een bankrekening afgehaald wordt, zal dit credit zijn.
*/
CREDIT,
/** Wanneer er geld van een bankrekening wordt gehaald of wordt gestort.
*/
ALLE;
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Balie.Controller;
import API.IClient;
import API.IObservable;
import API.IObserver;
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.*;
/**
* Biedt mogelijkheid voor de server om de client remote uit te loggen.
*/
public class ClientImpl implements IClient {
private static volatile ClientImpl instance;
private static HashMap<Integer, ArrayList<IObserver>> obs = new HashMap();
public ClientImpl() throws RemoteException {
try {
UnicastRemoteObject.exportObject(this, 0);
instance = this;
} catch (RemoteException ex) {
Logger.getLogger(ClientImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public synchronized void logOut() throws RemoteException {
System.out.println("Client Stopped");
UnicastRemoteObject.unexportObject(this, true);
}
@Override
public synchronized void setObservable(IObservable o) throws RemoteException {
if (obs.containsKey(o.getObservableId())) {
ArrayList<IObserver> observers = obs.get(o.getObservableId());
if (observers != null) {
for (IObserver ob : observers) {
ob.update(o, "");
}
}
}
}
public synchronized void addObserver(IObserver ob, IObservable o) {
//Nog check inbouwen of IObserver al eerder geregistreerd is.
ArrayList<IObserver> obsList = new ArrayList<>();
obsList.add(ob);
obs.put(o.getObservableId(), obsList);
}
}
| Java |
/*
* 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 Balie.gui;
import API.ITransactie;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
/**
*
* @author Melis
*/
public class TransactiePanel extends javax.swing.JPanel {
private ArrayList<ITransactie> transacties;
private int eigenRekeningNr = 0;
/**
* Creates new form TransactiePanel
*/
public TransactiePanel() {
initComponents();
this.transacties = new ArrayList<>();
}
public void setEigenRekeningNr(int eigenRekeningNr) {
this.eigenRekeningNr = eigenRekeningNr;
}
public void setTransacties(ArrayList<ITransactie> transacties) {
this.transacties = transacties;
refrestListView();
}
private void refrestListView() {
String col[] = {"Datum", "Tegenrekening", "Bij/af", "Bedrag", "Status"};
DefaultTableModel tableModel = new DefaultTableModel(col, 0);
// The 0 argument is number rows.
int rekening;
String transRichting;
for (int i = 0; i < transacties.size(); i++) {
ITransactie trans = transacties.get(i);
GregorianCalendar datum = trans.getTransactieInvoerDatum();
if (eigenRekeningNr == trans.getEigenbankrekening()) {
transRichting = "Af";
rekening = trans.getTegenrekening();
} else {
transRichting = "Bij";
rekening = trans.getEigenbankrekening();
}
String bedrag = trans.getBedrag().setScale(2, RoundingMode.HALF_EVEN).toString();
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
String datumStr = df.format(datum.getTime());
Object[] data = {datumStr, rekening, transRichting, bedrag, trans.getStatus()};
tableModel.addRow(data);
}
jTable1.setModel(tableModel);
tableModel.fireTableDataChanged();
}
/**
* 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">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
setOpaque(false);
setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jTable1.setFont(new java.awt.Font("Calibri", 0, 13)); // NOI18N
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Datum", "Begunstigde", "Bij/af", "Bedrag"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.Short.class, java.lang.Double.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jTable1.setOpaque(false);
jTable1.getTableHeader().setReorderingAllowed(false);
jScrollPane1.setViewportView(jTable1);
if (jTable1.getColumnModel().getColumnCount() > 0) {
jTable1.getColumnModel().getColumn(0).setResizable(false);
jTable1.getColumnModel().getColumn(0).setHeaderValue("Datum");
jTable1.getColumnModel().getColumn(1).setResizable(false);
jTable1.getColumnModel().getColumn(1).setHeaderValue("Begunstigde");
jTable1.getColumnModel().getColumn(2).setResizable(false);
jTable1.getColumnModel().getColumn(2).setPreferredWidth(50);
jTable1.getColumnModel().getColumn(2).setHeaderValue("Bij/af");
jTable1.getColumnModel().getColumn(3).setResizable(false);
jTable1.getColumnModel().getColumn(3).setHeaderValue("Bedrag");
}
add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 0, 370, 260));
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* 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 Balie.gui;
import API.IKlant;
import API.ILoginAccount;
/**
*
* @author Melis
*/
public class KlantPanel extends javax.swing.JPanel {
/**
* Creates new form KlantPanel
*/
public KlantPanel() {
initComponents();
}
public void setGegevens(IKlant klant, ILoginAccount login)
{
jtfKlantNummer.setText(String.valueOf(klant.getKlantNr()));
jtfKlantnaam.setText(klant.getKlantnaam());
jtfWoonplaats.setText(klant.getKlantwoonplaats());
jtfGebruikersnaam.setText(login.getLoginNaam());
}
/**
* 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">//GEN-BEGIN:initComponents
private void initComponents() {
jtfKlantNummer = new javax.swing.JTextField();
jtfGebruikersnaam = new javax.swing.JTextField();
jtfKlantnaam = new javax.swing.JTextField();
jtfWoonplaats = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jtfKlantNummer.setEditable(false);
jtfKlantNummer.setBackground(new java.awt.Color(238, 238, 238));
jtfKlantNummer.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jtfKlantNummer.setForeground(new java.awt.Color(102, 102, 102));
jtfKlantNummer.setBorder(null);
jtfKlantNummer.setOpaque(false);
add(jtfKlantNummer, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 28, 350, 15));
jtfGebruikersnaam.setEditable(false);
jtfGebruikersnaam.setBackground(new java.awt.Color(238, 238, 238));
jtfGebruikersnaam.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jtfGebruikersnaam.setForeground(new java.awt.Color(102, 102, 102));
jtfGebruikersnaam.setBorder(null);
jtfGebruikersnaam.setOpaque(false);
add(jtfGebruikersnaam, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 208, 350, 15));
jtfKlantnaam.setEditable(false);
jtfKlantnaam.setBackground(new java.awt.Color(238, 238, 238));
jtfKlantnaam.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jtfKlantnaam.setForeground(new java.awt.Color(102, 102, 102));
jtfKlantnaam.setBorder(null);
jtfKlantnaam.setOpaque(false);
add(jtfKlantnaam, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 88, 350, 15));
jtfWoonplaats.setEditable(false);
jtfWoonplaats.setBackground(new java.awt.Color(238, 238, 238));
jtfWoonplaats.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jtfWoonplaats.setForeground(new java.awt.Color(102, 102, 102));
jtfWoonplaats.setBorder(null);
jtfWoonplaats.setOpaque(false);
add(jtfWoonplaats, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 148, 350, 15));
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/KlantPanel.gif"))); // NOI18N
add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 400, 230));
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JTextField jtfGebruikersnaam;
private javax.swing.JTextField jtfKlantNummer;
private javax.swing.JTextField jtfKlantnaam;
private javax.swing.JTextField jtfWoonplaats;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* 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 Balie.gui;
import API.IAuth;
import API.IObserver;
import API.IRekening;
import Bank.Model.SessieExpiredException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Melis
*/
public class BankrekeningPanel extends javax.swing.JPanel implements IObserver {
/**
* Creates new form BankrekeningPanel
*/
public BankrekeningPanel() {
initComponents();
}
public void setGegevens(String sessieID, IRekening rekening, IAuth loginInterface)
{
this.sessieID = sessieID;
this.loginInterface = loginInterface;
this.rekening = rekening;
}
/**
* Deze methode zit er in PUUR voor demo doeleinden!
*/
public void storten() {
try {
this.loginInterface.stort(sessieID, new BigDecimal(5.00).setScale(2, RoundingMode.HALF_EVEN));
} catch (RemoteException ex) {
Logger.getLogger(BankrekeningPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (SessieExpiredException ex) {
Logger.getLogger(BankrekeningPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* 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">//GEN-BEGIN:initComponents
private void initComponents() {
jtfKredietlimiet = new javax.swing.JTextField();
jtfEigenRekening = new javax.swing.JTextField();
jtfSaldo = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jtfKredietlimiet.setEditable(false);
jtfKredietlimiet.setBackground(new java.awt.Color(238, 238, 238));
jtfKredietlimiet.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jtfKredietlimiet.setForeground(new java.awt.Color(102, 102, 102));
jtfKredietlimiet.setBorder(null);
add(jtfKredietlimiet, new org.netbeans.lib.awtextra.AbsoluteConstraints(42, 148, 330, 15));
jtfEigenRekening.setEditable(false);
jtfEigenRekening.setBackground(new java.awt.Color(238, 238, 238));
jtfEigenRekening.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jtfEigenRekening.setForeground(new java.awt.Color(102, 102, 102));
jtfEigenRekening.setBorder(null);
add(jtfEigenRekening, new org.netbeans.lib.awtextra.AbsoluteConstraints(21, 26, 350, 15));
jtfSaldo.setEditable(false);
jtfSaldo.setBackground(new java.awt.Color(238, 238, 238));
jtfSaldo.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jtfSaldo.setForeground(new java.awt.Color(102, 102, 102));
jtfSaldo.setBorder(null);
add(jtfSaldo, new org.netbeans.lib.awtextra.AbsoluteConstraints(42, 87, 330, 15));
jLabel3.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jLabel3.setForeground(new java.awt.Color(102, 102, 102));
jLabel3.setText("€");
add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 148, 20, 15));
jLabel2.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jLabel2.setForeground(new java.awt.Color(102, 102, 102));
jLabel2.setText("€");
add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 87, 20, 15));
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/RekeningPanel.gif"))); // NOI18N
add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 400, 170));
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JTextField jtfEigenRekening;
private javax.swing.JTextField jtfKredietlimiet;
private javax.swing.JTextField jtfSaldo;
// End of variables declaration//GEN-END:variables
private IAuth loginInterface;
private IRekening rekening;
private String sessieID;
@Override
public void update(Object observable, Object arg) throws RemoteException {
rekening = (IRekening) observable;
jtfEigenRekening.setText(rekening.toString());
jtfSaldo.setText(rekening.getSaldo().toString());
jtfKredietlimiet.setText(rekening.getKredietlimiet().toString());
}
}
| Java |
/*
* 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 Balie.gui;
import API.IAuth;
import Balie.Controller.ClientImpl;
import Bank.Model.SessieExpiredException;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
/**
*
* @author Melis
*/
public class NieuweKlantPanel extends javax.swing.JPanel {
private JFrame parentFrame;
/**
* Creates new form NieuweKlantPanel
*/
public NieuweKlantPanel() {
initComponents();
}
public NieuweKlantPanel(JFrame jframereferentie)
{
initComponents();
this.parentFrame = jframereferentie;
}
/**
* 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">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel2 = new javax.swing.JLabel();
jtfWachtwoord = new javax.swing.JPasswordField();
jtfGebruikersnaam = new javax.swing.JTextField();
jtfWoonplaats = new javax.swing.JTextField();
jtfKlantnaam = new javax.swing.JTextField();
btnRegistreren = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
setOpaque(false);
setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel2.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 0, 0));
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setText("Let op! U maakt een nieuwe rekening aan.");
add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 254, 350, -1));
jtfWachtwoord.setBorder(null);
jtfWachtwoord.setOpaque(false);
add(jtfWachtwoord, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 214, 330, 30));
jtfGebruikersnaam.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jtfGebruikersnaam.setBorder(null);
add(jtfGebruikersnaam, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 150, 330, 30));
jtfWoonplaats.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jtfWoonplaats.setBorder(null);
add(jtfWoonplaats, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 88, 330, 30));
jtfKlantnaam.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jtfKlantnaam.setBorder(null);
add(jtfKlantnaam, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 24, 330, 30));
btnRegistreren.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/RegistreerButton.gif"))); // NOI18N
btnRegistreren.setBorder(null);
btnRegistreren.setBorderPainted(false);
btnRegistreren.setFocusPainted(false);
btnRegistreren.setMargin(new java.awt.Insets(0, 0, 0, 0));
btnRegistreren.setOpaque(false);
btnRegistreren.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/RegistreerButtonClicked.gif"))); // NOI18N
btnRegistreren.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRegistrerenActionPerformed(evt);
}
});
add(btnRegistreren, new org.netbeans.lib.awtextra.AbsoluteConstraints(115, 290, 150, 40));
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/NieuweKlantPanel.gif"))); // NOI18N
add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 400, -1));
}// </editor-fold>//GEN-END:initComponents
private void btnRegistrerenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRegistrerenActionPerformed
try {
String bankServerURL = "rmi://localhost/auth";
String sessieId = null;
IAuth loginInterface;
ClientImpl clientcontroller = new ClientImpl();
try {
loginInterface = (IAuth) Naming.lookup(bankServerURL);
if (loginInterface.registreerNieuweKlant(jtfKlantnaam.getText(), jtfWoonplaats.getText(), jtfGebruikersnaam.getText(), jtfWachtwoord.getText()))
{
sessieId = loginInterface.startSessie(jtfGebruikersnaam.getText(), jtfWachtwoord.getText());
loginInterface.registerClientObj(sessieId, clientcontroller);
}
} catch (IllegalArgumentException ex) {
JOptionPane.showMessageDialog(this.parentFrame.getRootPane(), ex.getMessage());
return;
} catch ( NotBoundException | MalformedURLException | SessieExpiredException ex) {
}
SessieFrame sessieFrame = new SessieFrame(sessieId, clientcontroller);
sessieFrame.setVisible(true);
this.parentFrame.dispose();
} catch (RemoteException ex) {
}
}//GEN-LAST:event_btnRegistrerenActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnRegistreren;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField jtfGebruikersnaam;
private javax.swing.JTextField jtfKlantnaam;
private javax.swing.JPasswordField jtfWachtwoord;
private javax.swing.JTextField jtfWoonplaats;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* 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 Balie.gui;
import API.IAuth;
import Balie.Controller.ClientImpl;
import Bank.Model.SessieExpiredException;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
/**
*
* @author Melis
*/
public class InlogPanel extends javax.swing.JPanel {
/**
* Creates new form NewJPanel
* Er moet in dit geval een parameterloze constructor voor inlogpanel aanwezig zijn, daar
* anders de GUI designer van netbeans foutmeldingen gaat geven.
*/
public InlogPanel() {
initComponents();
}
/**
* Creates new form NewJPanel
* @param jframereferentie
* @param jframeReferentie er wordt een JFrame meegegeven omdat, wanneer login
* voltooid is, dan moet het jframe afgesloten worden.
*/
public InlogPanel(JFrame jframereferentie)
{
initComponents();
this.parentFrame = jframereferentie;
}
/**
* 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">//GEN-BEGIN:initComponents
private void initComponents() {
jtfGebruiker = new javax.swing.JTextField();
jtfWachtwoord = new javax.swing.JPasswordField();
jLabel1 = new javax.swing.JLabel();
btnInloggen = new javax.swing.JButton();
setBackground(new java.awt.Color(255, 255, 255));
setOpaque(false);
setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jtfGebruiker.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jtfGebruiker.setBorder(null);
add(jtfGebruiker, new org.netbeans.lib.awtextra.AbsoluteConstraints(32, 84, 340, 30));
jtfWachtwoord.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jtfWachtwoord.setBorder(null);
add(jtfWachtwoord, new org.netbeans.lib.awtextra.AbsoluteConstraints(32, 162, 340, 30));
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/InlogPanel.gif"))); // NOI18N
add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 400, 270));
btnInloggen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/InlogButton.gif"))); // NOI18N
btnInloggen.setBorder(null);
btnInloggen.setBorderPainted(false);
btnInloggen.setFocusPainted(false);
btnInloggen.setMargin(new java.awt.Insets(0, 0, 0, 0));
btnInloggen.setOpaque(false);
btnInloggen.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/InlogButtonClicked.gif"))); // NOI18N
btnInloggen.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnInloggenActionPerformed(evt);
}
});
add(btnInloggen, new org.netbeans.lib.awtextra.AbsoluteConstraints(115, 290, 150, 40));
}// </editor-fold>//GEN-END:initComponents
private void btnInloggenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInloggenActionPerformed
try {
String bankServerURL = "rmi://localhost/auth";
String sessieId = null;
IAuth loginInterface;
ClientImpl clientcontroller = new ClientImpl();
try {
loginInterface = (IAuth) Naming.lookup(bankServerURL);
sessieId = loginInterface.startSessie(jtfGebruiker.getText(), jtfWachtwoord.getText());
loginInterface.registerClientObj(sessieId, clientcontroller);
} catch (IllegalArgumentException ex) {
JOptionPane.showMessageDialog(this.parentFrame.getRootPane(), ex.getMessage());
return;
} catch ( NotBoundException | MalformedURLException | SessieExpiredException ex) {
}
SessieFrame sessieFrame = new SessieFrame(sessieId, clientcontroller);
sessieFrame.setVisible(true);
this.parentFrame.dispose();
} catch (RemoteException ex) {
}
}//GEN-LAST:event_btnInloggenActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnInloggen;
private javax.swing.JLabel jLabel1;
private javax.swing.JTextField jtfGebruiker;
private javax.swing.JPasswordField jtfWachtwoord;
// End of variables declaration//GEN-END:variables
private JFrame parentFrame;
}
| Java |
/*
* 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 Balie.gui;
import API.IRekening;
import API.ITransactieHandler;
import Bank.Model.SessieExpiredException;
import java.awt.Point;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* @author Melis
*/
public class NieuwTransactieDialog extends javax.swing.JDialog {
private IRekening rekening;
private String sessieID;
/**
* Creates new form NieuwTransactieDialog
*
* @param parent
* @param modal
*/
public NieuwTransactieDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
setLocation(new Point(500, 200));
}
/**
*
* @param parent
* @param modal
* @param rekening
* @param sessieID
*/
public NieuwTransactieDialog(java.awt.Frame parent, boolean modal, IRekening rekening, String sessieID) {
super(parent, modal);
initComponents();
setLocation(new Point(500, 200));
this.sessieID = sessieID;
jtfVanRekening.setText(rekening.toString());
}
/**
* 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">//GEN-BEGIN:initComponents
private void initComponents() {
jtfVanRekening = new javax.swing.JTextField();
jtfSaldo = new javax.swing.JTextField();
jtfSaldoCenten = new javax.swing.JTextField();
jtfNaarRekening = new javax.swing.JTextField();
btnAnnuleren = new javax.swing.JButton();
btnVerzenden = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jtaOmschrijving = new javax.swing.JTextArea();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Rainbow Sheep Bank");
setResizable(false);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jtfVanRekening.setEditable(false);
jtfVanRekening.setBackground(new java.awt.Color(238, 238, 238));
jtfVanRekening.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jtfVanRekening.setHorizontalAlignment(javax.swing.JTextField.LEFT);
jtfVanRekening.setBorder(null);
getContentPane().add(jtfVanRekening, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 170, 330, 20));
jtfSaldo.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jtfSaldo.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
jtfSaldo.setBorder(null);
getContentPane().add(jtfSaldo, new org.netbeans.lib.awtextra.AbsoluteConstraints(299, 235, 200, 30));
jtfSaldoCenten.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jtfSaldoCenten.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
jtfSaldoCenten.setBorder(null);
getContentPane().add(jtfSaldoCenten, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 235, 30, 30));
jtfNaarRekening.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jtfNaarRekening.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
jtfNaarRekening.setBorder(null);
getContentPane().add(jtfNaarRekening, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 297, 340, 30));
btnAnnuleren.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/AnnulerenButton.gif"))); // NOI18N
btnAnnuleren.setBorder(null);
btnAnnuleren.setBorderPainted(false);
btnAnnuleren.setContentAreaFilled(false);
btnAnnuleren.setFocusPainted(false);
btnAnnuleren.setMargin(new java.awt.Insets(0, 0, 0, 0));
btnAnnuleren.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/AnnulerenButtonClicked.gif"))); // NOI18N
btnAnnuleren.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/AnnulerenButtonClicked.gif"))); // NOI18N
btnAnnuleren.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAnnulerenActionPerformed(evt);
}
});
getContentPane().add(btnAnnuleren, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 480, 150, 40));
btnVerzenden.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/VerzendenButton.gif"))); // NOI18N
btnVerzenden.setBorder(null);
btnVerzenden.setBorderPainted(false);
btnVerzenden.setContentAreaFilled(false);
btnVerzenden.setFocusPainted(false);
btnVerzenden.setMargin(new java.awt.Insets(0, 0, 0, 0));
btnVerzenden.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/VerzendenButtonClicked.gif"))); // NOI18N
btnVerzenden.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/VerzendenButtonClicked.gif"))); // NOI18N
btnVerzenden.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnVerzendenActionPerformed(evt);
}
});
getContentPane().add(btnVerzenden, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 480, 150, 40));
jScrollPane1.setBorder(null);
jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
jScrollPane1.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jScrollPane1.setMaximumSize(new java.awt.Dimension(340, 60));
jtaOmschrijving.setColumns(20);
jtaOmschrijving.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jtaOmschrijving.setLineWrap(true);
jtaOmschrijving.setRows(5);
jtaOmschrijving.setBorder(null);
jtaOmschrijving.setMaximumSize(new java.awt.Dimension(280, 115));
jScrollPane1.setViewportView(jtaOmschrijving);
getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 370, 340, 60));
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/NieuweTransactieFrame.gif"))); // NOI18N
getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 800, 600));
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnVerzendenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVerzendenActionPerformed
//moet nog netjes gemaakt worden. Dialog sluit zichzelf niet af bijv.
int saldo = -1;
int saldoCenten = -1;
int rekeningnR = 0;
BigDecimal transactieBedrag = new BigDecimal(0);
try {
saldo = Integer.parseInt(this.jtfSaldo.getText());
saldoCenten = Integer.parseInt(this.jtfSaldoCenten.getText());
rekeningnR = Integer.parseInt(this.jtfNaarRekening.getText());
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(rootPane, "Niet goed ingevuld");
}
if (saldo > -1 && saldoCenten > -1) {
float saldoCentenf = saldoCenten;
saldoCentenf = saldoCentenf / 100;
float saldof = saldo + saldoCentenf;
transactieBedrag = new BigDecimal(saldof);
}
if(transactieBedrag.compareTo(new BigDecimal(0)) != 1) {
JOptionPane.showMessageDialog(rootPane, "transactie bedrag moet groter zijn dan 0");
return;
}
ITransactieHandler transHandeler;
try {
String bankServerURL = "rmi://localhost/transactie";
transHandeler = (ITransactieHandler) Naming.lookup(bankServerURL);
transHandeler.requestTransaction(sessieID, rekeningnR, transactieBedrag, this.jtaOmschrijving.getText());
JOptionPane.showMessageDialog(rootPane, "Transactie succesvol aangevraagd");
this.dispose();
} catch (NotBoundException | MalformedURLException | RemoteException ex) {
Logger.getLogger(NieuwTransactieDialog.class.getName()).log(Level.SEVERE, null, ex);
} catch (SessieExpiredException ex) {
Logger.getLogger(NieuwTransactieDialog.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_btnVerzendenActionPerformed
private void btnAnnulerenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAnnulerenActionPerformed
this.dispose();
}//GEN-LAST:event_btnAnnulerenActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NieuwTransactieDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NieuwTransactieDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NieuwTransactieDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NieuwTransactieDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
NieuwTransactieDialog dialog = new NieuwTransactieDialog(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnAnnuleren;
private javax.swing.JButton btnVerzenden;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jtaOmschrijving;
private javax.swing.JTextField jtfNaarRekening;
private javax.swing.JTextField jtfSaldo;
private javax.swing.JTextField jtfSaldoCenten;
private javax.swing.JTextField jtfVanRekening;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* 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 Balie.gui;
import API.IAuth;
import API.IKlant;
import API.ILoginAccount;
import API.IObservable;
import API.IRekening;
import API.ITransactie;
import API.ITransactieHandler;
import Balie.Controller.ClientImpl;
import Bank.Model.SessieExpiredException;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Timer;
/**
*
* @author Melis
*/
public class SessieFrame extends javax.swing.JFrame {
private IAuth auth;
private String sessieID;
private ClientImpl clientController;
private ITransactieHandler transHandler;
private Timer timer;
/**
* Creates new form SessieFrame
*
* @param sessieID
* @param clientcontroller
*/
public SessieFrame(String sessieID, ClientImpl clientcontroller) {
initComponents();
setLocation(new Point(400, 100));
this.clientController = clientcontroller;
this.sessieID = sessieID;
try {
String bankServerURL = "rmi://localhost/auth";
auth = (IAuth) Naming.lookup(bankServerURL);
IRekening rekening = auth.getRekening(sessieID);
lblWelkom.setText("Welkom " + auth.getKlant(sessieID).getKlantnaam());
bankrekeningPanel.setGegevens(sessieID, rekening, auth);
IKlant klant = auth.getKlant(sessieID);
ILoginAccount login = auth.getLoginAccount(sessieID);
klantPanel.setGegevens(klant, login);
IObservable o = (IObservable) rekening;
clientcontroller.addObserver(bankrekeningPanel, o);
bankrekeningPanel.update(rekening, null);
bankServerURL = "rmi://localhost/transactie";
transHandler = (ITransactieHandler) Naming.lookup(bankServerURL);
transactiePanel2.setEigenRekeningNr(login.getRekeningNr());
ArrayList<ITransactie> transacties;
transacties = transHandler.getTransacties(sessieID, null, null);
transactiePanel2.setTransacties(transacties);
} catch (NotBoundException | MalformedURLException | RemoteException | SessieExpiredException ex) {
Logger.getLogger(SessieFrame.class.getName()).log(Level.SEVERE, null, ex);
}
timer = new Timer(5000, taskPerformer);
timer.start();
}
ActionListener taskPerformer = new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
ArrayList<ITransactie> transacties;
try {
transacties = transHandler.getTransacties(sessieID, null, null);
transactiePanel2.setTransacties(transacties);
} catch (RemoteException | SessieExpiredException ex) {
Logger.getLogger(SessieFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
};
/**
* 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">//GEN-BEGIN:initComponents
private void initComponents() {
btnUitloggen = new javax.swing.JButton();
btnNieuweTransactie = new javax.swing.JButton();
bankrekeningPanel = new Balie.gui.BankrekeningPanel();
transactiePanel2 = new Balie.gui.TransactiePanel();
klantPanel = new Balie.gui.KlantPanel();
lblWelkom = new javax.swing.JLabel();
btnMakeMeRich = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Rainbow Sheep Bank");
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
btnUitloggen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/UitlogButton.gif"))); // NOI18N
btnUitloggen.setBorder(null);
btnUitloggen.setBorderPainted(false);
btnUitloggen.setContentAreaFilled(false);
btnUitloggen.setFocusPainted(false);
btnUitloggen.setMargin(new java.awt.Insets(0, 0, 0, 0));
btnUitloggen.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/UitlogButtonClicked.gif"))); // NOI18N
btnUitloggen.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/UitlogButtonClicked.gif"))); // NOI18N
btnUitloggen.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnUitloggenActionPerformed(evt);
}
});
getContentPane().add(btnUitloggen, new org.netbeans.lib.awtextra.AbsoluteConstraints(840, 60, 150, 40));
btnNieuweTransactie.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/TransactieButton.gif"))); // NOI18N
btnNieuweTransactie.setBorder(null);
btnNieuweTransactie.setBorderPainted(false);
btnNieuweTransactie.setContentAreaFilled(false);
btnNieuweTransactie.setFocusPainted(false);
btnNieuweTransactie.setMargin(new java.awt.Insets(0, 0, 0, 0));
btnNieuweTransactie.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/TransactieButtonClicked.gif"))); // NOI18N
btnNieuweTransactie.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/TransactieButtonClicked.gif"))); // NOI18N
btnNieuweTransactie.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnNieuweTransactieActionPerformed(evt);
}
});
getContentPane().add(btnNieuweTransactie, new org.netbeans.lib.awtextra.AbsoluteConstraints(680, 524, 150, 40));
bankrekeningPanel.setOpaque(false);
getContentPane().add(bankrekeningPanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 214, -1, -1));
getContentPane().add(transactiePanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 220, -1, 270));
getContentPane().add(klantPanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 506, -1, -1));
lblWelkom.setFont(new java.awt.Font("Calibri", 1, 48)); // NOI18N
lblWelkom.setText("Welkom");
getContentPane().add(lblWelkom, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 58, 690, 40));
btnMakeMeRich.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/MakeMeRichButton.gif"))); // NOI18N
btnMakeMeRich.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btnMakeMeRichMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
btnMakeMeRichMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
btnMakeMeRichMouseExited(evt);
}
public void mousePressed(java.awt.event.MouseEvent evt) {
btnMakeMeRichMousePressed(evt);
}
public void mouseReleased(java.awt.event.MouseEvent evt) {
btnMakeMeRichMouseReleased(evt);
}
});
getContentPane().add(btnMakeMeRich, new org.netbeans.lib.awtextra.AbsoluteConstraints(540, 702, -1, -1));
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/SessieFrame_Background.gif"))); // NOI18N
jLabel1.setDebugGraphicsOptions(javax.swing.DebugGraphics.BUFFERED_OPTION);
jLabel1.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jLabel1FocusGained(evt);
}
});
getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, 770));
jTextField1.setText("jTextField1");
getContentPane().add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 60, -1, -1));
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnMakeMeRichMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnMakeMeRichMouseClicked
this.bankrekeningPanel.storten();
}//GEN-LAST:event_btnMakeMeRichMouseClicked
private void btnMakeMeRichMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnMakeMeRichMouseEntered
btnMakeMeRich.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/MakeMeRichButtonClicked.gif")));
}//GEN-LAST:event_btnMakeMeRichMouseEntered
private void btnMakeMeRichMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnMakeMeRichMouseExited
btnMakeMeRich.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/MakeMeRichButton.gif")));
}//GEN-LAST:event_btnMakeMeRichMouseExited
private void btnMakeMeRichMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnMakeMeRichMouseReleased
btnMakeMeRich.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/MakeMeRichButton.gif")));
}//GEN-LAST:event_btnMakeMeRichMouseReleased
private void btnMakeMeRichMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnMakeMeRichMousePressed
btnMakeMeRich.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/MakeMeRichButtonClicked.gif")));
}//GEN-LAST:event_btnMakeMeRichMousePressed
private void btnUitloggenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUitloggenActionPerformed
try {
auth.stopSessie(sessieID);
timer.stop();
clientController.logOut();
} catch (RemoteException ex) {
Logger.getLogger(SessieFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (SessieExpiredException ex) {
Logger.getLogger(SessieFrame.class.getName()).log(Level.SEVERE, null, ex);
}
StartFrame startframe = new StartFrame();
startframe.setVisible(true);
this.dispose();
}//GEN-LAST:event_btnUitloggenActionPerformed
/**
* Eventhandler wanneer de gebruiker een nieuwe transactie wilt maken. Er
* wordt een nieuw jdialog scherm opgestart.
*
* @param evt
*/
private void btnNieuweTransactieActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNieuweTransactieActionPerformed
try {
IRekening rekening = auth.getRekening(sessieID);
NieuwTransactieDialog transactieDialog = new NieuwTransactieDialog(this, true, rekening, sessieID);
transactieDialog.setVisible(true);
} catch (RemoteException | SessieExpiredException ex) {
Logger.getLogger(SessieFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_btnNieuweTransactieActionPerformed
/**
* Eventhandler die noodzakelijk wanneer het frame afgesloten wordt. De
* verbinding tussen client en server moet verbroken worden.
*
* @param evt
*/
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
try {
clientController.logOut();
} catch (RemoteException ex) {
Logger.getLogger(SessieFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_formWindowClosing
private void jLabel1FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jLabel1FocusGained
}//GEN-LAST:event_jLabel1FocusGained
// Variables declaration - do not modify//GEN-BEGIN:variables
private Balie.gui.BankrekeningPanel bankrekeningPanel;
private javax.swing.JLabel btnMakeMeRich;
private javax.swing.JButton btnNieuweTransactie;
private javax.swing.JButton btnUitloggen;
private javax.swing.JLabel jLabel1;
private javax.swing.JTextField jTextField1;
private Balie.gui.KlantPanel klantPanel;
private javax.swing.JLabel lblWelkom;
private Balie.gui.TransactiePanel transactiePanel2;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* 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 Balie.gui;
import java.awt.Point;
/**
*
* @author Melis
*/
public class StartFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public StartFrame() {
initComponents();
setLocation(new Point(400,100));
nieuweKlantPanel1.setVisible(false);
}
/**
* 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">//GEN-BEGIN:initComponents
private void initComponents() {
inlogPanel1 = new Balie.gui.InlogPanel(this);
nieuweKlantPanel1 = new Balie.gui.NieuweKlantPanel(this);
tabNieuweKlant = new javax.swing.JButton();
tabInloggen = new javax.swing.JButton();
jlbl_Background = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Rainbow Sheep Bank");
setMinimumSize(new java.awt.Dimension(1024, 768));
setResizable(false);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
getContentPane().add(inlogPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 260, -1, -1));
getContentPane().add(nieuweKlantPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 260, -1, -1));
tabNieuweKlant.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/NieuweKlantTabInactive.gif"))); // NOI18N
tabNieuweKlant.setBorder(null);
tabNieuweKlant.setBorderPainted(false);
tabNieuweKlant.setContentAreaFilled(false);
tabNieuweKlant.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/NieuweKlantTabActive.gif"))); // NOI18N
tabNieuweKlant.setDisabledSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/NieuweKlantTabActive.gif"))); // NOI18N
tabNieuweKlant.setMargin(new java.awt.Insets(0, 0, 0, 0));
tabNieuweKlant.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/NieuweKlantTabHover.gif"))); // NOI18N
tabNieuweKlant.setRolloverSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/NieuweKlantTabActive.gif"))); // NOI18N
tabNieuweKlant.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/NieuweKlantTabActive.gif"))); // NOI18N
tabNieuweKlant.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tabNieuweKlantActionPerformed(evt);
}
});
getContentPane().add(tabNieuweKlant, new org.netbeans.lib.awtextra.AbsoluteConstraints(470, 187, -1, -1));
tabInloggen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/InlogTabInactive.gif"))); // NOI18N
tabInloggen.setBorder(null);
tabInloggen.setBorderPainted(false);
tabInloggen.setContentAreaFilled(false);
tabInloggen.setDisabledIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/InlogTabActive.gif"))); // NOI18N
tabInloggen.setDisabledSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/InlogTabActive.gif"))); // NOI18N
tabInloggen.setEnabled(false);
tabInloggen.setMargin(new java.awt.Insets(0, 0, 0, 0));
tabInloggen.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/InlogTabHover.gif"))); // NOI18N
tabInloggen.setRolloverSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/Buttons/InlogTabActive.gif"))); // NOI18N
tabInloggen.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tabInloggenActionPerformed(evt);
}
});
getContentPane().add(tabInloggen, new org.netbeans.lib.awtextra.AbsoluteConstraints(304, 187, -1, -1));
jlbl_Background.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Balie/gui/Images/BackgroundStartFrame.gif"))); // NOI18N
jlbl_Background.setDebugGraphicsOptions(javax.swing.DebugGraphics.BUFFERED_OPTION);
jlbl_Background.setOpaque(false);
getContentPane().add(jlbl_Background, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1));
pack();
}// </editor-fold>//GEN-END:initComponents
private void tabNieuweKlantActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tabNieuweKlantActionPerformed
tabInloggen.setEnabled(true);
tabNieuweKlant.setEnabled(false);
inlogPanel1.setVisible(false);
nieuweKlantPanel1.setVisible(true);
}//GEN-LAST:event_tabNieuweKlantActionPerformed
private void tabInloggenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tabInloggenActionPerformed
tabInloggen.setEnabled(false);
tabNieuweKlant.setEnabled(true);
inlogPanel1.setVisible(true);
nieuweKlantPanel1.setVisible(false);
}//GEN-LAST:event_tabInloggenActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(StartFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(StartFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(StartFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(StartFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new StartFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private Balie.gui.InlogPanel inlogPanel1;
private javax.swing.JLabel jlbl_Background;
private Balie.gui.NieuweKlantPanel nieuweKlantPanel1;
private javax.swing.JButton tabInloggen;
private javax.swing.JButton tabNieuweKlant;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Bank.Model;
/**
*
*/
public class SessieExpiredException extends Exception {
public SessieExpiredException() {
}
public SessieExpiredException(String message) {
super(message);
}
public SessieExpiredException(Throwable cause) {
super(cause);
}
public SessieExpiredException(String message, Throwable cause) {
super(message, cause);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Bank.Model;
import API.ITransactie;
import API.TransactieStatus;
import java.math.BigDecimal;
import java.util.GregorianCalendar;
import java.util.Locale;
/**
* De klasse transatie is verantwoordelijk voor het registreren van een
* overboeking. Hierbij is het bedrag van belang, en het rekeningnummer waar het
* vanaf geschreven moet worden en de tegenrekening waarbij het bedrag
* bijgeboekt moet worden.
*/
public class Transactie extends BaseObservable implements ITransactie {
//transient zodat het tijdens het serializeren niet wordt opgeslagen (niet meegestuurd over RMI).
//volatile zodat het automatisch gesynchronizeerd wordt en nextTransactieId blijft altijd beschikbaar.
//volatile variablen kunnen niet locked raken.
private transient static volatile int nextTransactieId;
private final int transactieId;
private final int eigenbankrekening;
private final int tegenrekening;
private final String commentaar;
private final BigDecimal bedrag;
private final GregorianCalendar transactieInvoerDatum;
private TransactieStatus status;
/**
* De constructor van Transactie. Hierin wordt als transactieInvoerDatum de
* datum van vandaag gepakt. De status van de transactie staat op OPENSTAAND
* bij het aanmaken van een nieuwe transactie.
*
* @param eigenbankrekening de rekening waarvan het bedrag afgeschreven moet
* worden.
* @param tegenrekening de rekening waar het bedrag bij geschreven moet
* worden.
* @param bedrag het bedrag wat overgemaakt wordt.
* @param comment bij elke overboeking kan er commentaar of een
* betalingskenmerk ingevuld worden.
*/
public Transactie(int eigenbankrekening, int tegenrekening, BigDecimal bedrag, String comment) {
this.eigenbankrekening = eigenbankrekening;
this.tegenrekening = tegenrekening;
this.bedrag = bedrag;
this.commentaar = comment;
this.status = TransactieStatus.OPENSTAAND;
this.transactieInvoerDatum = new GregorianCalendar(Locale.GERMANY);
this.transactieId = nextTransactieId;
Transactie.nextTransactieId++;
}
/**
* De status van een transactie kan veranderen in loop van tijd.
*
* @param status de status die de transactie moet krijgen.
*/
public void setStatus(TransactieStatus status) {
this.status = status;
this.setChanged();
this.notifyObservers();
}
/**
* Een get-methode voor het transactieID.
*
* @return Het transactieID.
*/
public int getTransactieId() {
return transactieId;
}
/**
* Een get-methode voor de rekening waarvan het bedrag afgeschren moet
* worden.
*
* @return de rekening waar het bedrag van afgeschreven wordt.
*/
public int getEigenbankrekening() {
return eigenbankrekening;
}
/**
* Een get-methode voor de rekening waar het bedrag bij geschreven moet
* worden.
*
* @return de tegenrekening
*/
public int getTegenrekening() {
return tegenrekening;
}
/**
* Een get-methode voor het bedrag
*
* @return het bedrag
*/
public BigDecimal getBedrag() {
return bedrag;
}
/**
* Een get-methode voor de transactiestatus
*
* @return de transactiestatus
*/
public TransactieStatus getStatus() {
return status;
}
/**
* Een get-methode voor de datum dat de transactie ingevoerd is.
*
* @return de datum dat de transactie ingevoerd is.
*/
public GregorianCalendar getTransactieInvoerDatum() {
return transactieInvoerDatum;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Bank.Model;
import API.IRekening;
import java.math.BigDecimal;
import java.math.RoundingMode;
/**
* De klasse Rekening heeft als verantwoordelijkheid om rekeninggegevens. zoals
* het saldo en kredietlimiet bij te houden.
*/
public class Rekening extends BaseObservable implements IRekening {
private final int rekeningnummer;
private BigDecimal saldo = new BigDecimal(0.00);
private final BigDecimal kredietlimiet = new BigDecimal(0.00);
//transient zodat het tijdens het serializeren niet wordt opgeslagen (niet meegestuurd over RMI)
private transient static volatile int nextrekeningnummer = 1000;
/**
* Deze constructor maakt een nieuw rekeningnummer. Bij een nieuwe Rekening
* is het saldo altijd 0 en het kredietlimiet is ook 0.
*/
public Rekening() {
super();
this.rekeningnummer = nextrekeningnummer;
nextrekeningnummer++;
}
/**
* Een get-methode voor het rekeningnummer.
*
* @return het rekeningnummer.
*/
@Override
public synchronized int getRekeningnummer() {
return rekeningnummer;
}
/**
* Een get-methode voor het saldo.
*
* @return het saldo.
*/
@Override
public synchronized BigDecimal getSaldo() {
return saldo.setScale(2, RoundingMode.HALF_EVEN);
}
/**
* Een get-methode voor het kredietlimiet.
*
* @return het kredietlimiet.
*/
@Override
public synchronized BigDecimal getKredietlimiet() {
return kredietlimiet.setScale(2, RoundingMode.HALF_EVEN);
}
public synchronized boolean neemOp(BigDecimal bedrag) {
if (bedrag.compareTo(new BigDecimal(0)) == 1) {
BigDecimal saldoTotaal = new BigDecimal(0.00);
saldoTotaal = saldoTotaal.add(this.saldo);
saldoTotaal = saldoTotaal.add(this.kredietlimiet);
if (saldoTotaal.compareTo(bedrag) == 1 | saldoTotaal.compareTo(bedrag)== 0) {
this.saldo = this.saldo.subtract(bedrag);
setChanged();
notifyObservers();
return true;
}
}
return false;
}
public synchronized void stort(BigDecimal bedrag) {
if (bedrag.compareTo(new BigDecimal(0)) == 1) {
this.saldo = this.saldo.add(bedrag);
}
setChanged();
notifyObservers();
}
/**
* Een toString methode voor Rekening die de toString methode van Object
* overschrijft.
*
* @return het rekeningnummer.
*/
@Override
public String toString() {
return Integer.toString(this.rekeningnummer);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (!(obj instanceof Rekening)) {
return false;
}
Rekening r = (Rekening) obj;
return Integer.compare(rekeningnummer, r.getRekeningnummer()) == 0;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Bank.Model;
import API.IClient;
import java.sql.Timestamp;
import java.util.UUID;
/**
* Sessie object om authenticatie te versimpelen. Eenmalig login nodig waarna de
* sessie blijft leven tot 10 minuten na de laatste activiteit.
*
*/
public class Sessie {
private Timestamp lastActivity;
private final String SessieId;
private LoginAccount login;
private IClient client;
/**
* Initialiseerd het sessie object. Na initialisatie is er een sessieID
* gegenereerd en wordt er een sessietask ingepland om de sessie te
* beindigen.
*
* @param login Het login account waarvoor de sessie gestart wordt.
*/
public Sessie(LoginAccount login) {
//UUID genereert een random unique nummer van 128 bits.
//Absolute zekerheid op uniqueness krijg je hiermee niet, maar ruim voldoende voor opdracht.
//Absolute zekerheid alleen te verkrijgen door lijst met verbruikte id's bij te houden of synced counter.
this.SessieId = UUID.randomUUID().toString();
this.login = login;
updateActivity();
}
/**
* Een get-methode voor de sessieID
*
* @return de sessieID
*/
public String getSessieId() {
return this.SessieId;
}
/**
* Een get-methode voor het loginaccount
*
* @return het loginaccount
*/
public LoginAccount getLogin() {
updateActivity();
return login;
}
/**
* Een get-methode om de IClient op te vragen
*
* @return de IClient waarvoor deze sessie geregistreerd is.
*/
public IClient getClient() {
return client;
}
/**
* zet de client bij deze sessie.
*
* @param client
*/
public void setClient(IClient client) {
updateActivity();
this.client = client;
}
public Timestamp getLastActivity() {
return lastActivity;
}
public void updateActivity() {
java.util.Date date = new java.util.Date();
this.lastActivity = new Timestamp(date.getTime());
}
/**
* Methode om loginaccount op te vragen bij de sessie
* hierbij wordt de lastactivity niet geupdate. Deze methode wordt namelijk via
* de callback functie vanuit de client (sessieframe) aangeroepen wanneer
* de transacties worden opgevraagd.
* @return
*/
public LoginAccount getLoginNoActivityChange() {
return login;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Bank.Model;
import API.IClient;
import API.IAuth;
import API.IKlant;
import API.ILoginAccount;
import API.IObservable;
import API.IRekening;
import Bank.Managers.KlantManager;
import Bank.Managers.LoginManager;
import Bank.Managers.RekeningManager;
import Bank.Managers.SessieManager;
import java.math.BigDecimal;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* De server verstuurt berichten naar de ClientImpl middels deze klasse. Deze
* klasse implementeert IAuth en bij ClientImpl is IAuth ook bekend. Zodanig kan
* de klant onderstaande methoden opvragen bij de server.
*/
public class Auth implements IAuth {
private static HashMap<IObservable, ArrayList<String>> obs = new HashMap<>();
@Override
public synchronized String startSessie(String username, String password) throws RemoteException {
LoginManager loginManager = LoginManager.getInstance();
try {
Bank.Model.LoginAccount login = loginManager.getLoginAccount(username, password);
Sessie newSessie = new Sessie(login);
SessieManager sm = SessieManager.getInstance();
sm.addSessie(newSessie);
return newSessie.getSessieId();
} catch (IllegalArgumentException e) {
throw e;
}
}
/**
* Methode die een nieuwe klant registreert en daarbij kijkt of een klant al bestaat of niet.
* Bestaat de klant al, dan wordt dat klantnummer gebruikt. Bestaat klant niet, dan wordt er
* een nieuwe klant nummer aan gegeven.
* @param klantnaam
* @param woonplaats
* @param gebruikersnaam
* @param wachtwoord
* @return
* @throws RemoteException
*/
@Override
public synchronized boolean registreerNieuweKlant(String klantnaam, String woonplaats, String gebruikersnaam, String wachtwoord) throws RemoteException
{
KlantManager klantmanager = KlantManager.getInstance();
LoginManager loginmanager = LoginManager.getInstance();
RekeningManager rekeningmanager = RekeningManager.getInstance();
if(!loginmanager.bestaatLoginNaam(gebruikersnaam))
{
//Er hoeft geen nieuwe klant toegevoegd te worden als klantobject al bestaat.
if (klantmanager.getBestaandeKlantNummer(klantnaam, woonplaats) != 0){
int klantnummer = klantmanager.getBestaandeKlantNummer(klantnaam, woonplaats);
Rekening rekening = new Rekening();
LoginAccount loginaccount = new LoginAccount(gebruikersnaam, wachtwoord, klantnummer, rekening.getRekeningnummer());
loginmanager.addLogin(loginaccount);
rekeningmanager.addRekening(rekening);
return true;
}
//Wanneer er nog geen klantobject bestaat dan moet er wel een nieuw klantobject aangemaakt worden en bij klantmanager geregistreerd worden.
else {
Klant klant = new Klant(klantnaam, woonplaats);
Rekening rekening = new Rekening();
LoginAccount loginaccount = new LoginAccount(gebruikersnaam, wachtwoord, klant.getKlantNr(), rekening.getRekeningnummer());
klantmanager.addKlant(klant);
loginmanager.addLogin(loginaccount);
rekeningmanager.addRekening(rekening);
return true;
}
}
return false;
}
@Override
public synchronized void stopSessie(String sessionId) throws RemoteException, SessieExpiredException {
SessieManager.getInstance().stopSessie(sessionId);
}
@Override
public synchronized IKlant getKlant(String sessionId) throws RemoteException, SessieExpiredException {
SessieManager sm = SessieManager.getInstance();
try {
Bank.Model.LoginAccount login = sm.getAccountFromSessie(sessionId);
KlantManager km = KlantManager.getInstance();
Klant k = km.getKlant(login.getKlantNr());
registerObservable(k, sessionId);
return k;
} catch (SessieExpiredException e) {
throw e;
}
}
@Override
public synchronized IRekening getRekening(String sessionId) throws RemoteException, SessieExpiredException {
SessieManager sm = SessieManager.getInstance();
try {
ILoginAccount login = (ILoginAccount) sm.getAccountFromSessie(sessionId);
RekeningManager rm = RekeningManager.getInstance();
Rekening r = rm.getRekening(login.getRekeningNr());
registerObservable(r, sessionId);
return r;
} catch (SessieExpiredException e) {
throw e;
}
}
@Override
public synchronized boolean resetWachtwoord(String sessionId, String username, String password) throws RemoteException, SessieExpiredException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public synchronized void registerClientObj(String sessieId, IClient clientObj) throws RemoteException, SessieExpiredException {
SessieManager sm = SessieManager.getInstance();
try {
sm.bindClientObjecToSessie(sessieId, clientObj);
} catch (SessieExpiredException e) {
throw e;
}
}
/**
* Deze methode is er alleen als snel voorbeeld. Dit moet als een transactie
* behandeld worden.
* @param sessieId
* @param bedrag
* @throws java.rmi.RemoteException
* @throws Bank.Model.SessieExpiredException
*/
@Override
public synchronized void stort(String sessieId, BigDecimal bedrag) throws RemoteException, SessieExpiredException {
SessieManager sm = SessieManager.getInstance();
ILoginAccount login = (ILoginAccount) sm.getAccountFromSessie(sessieId);
RekeningManager rm = RekeningManager.getInstance();
Rekening r = rm.getRekening(login.getRekeningNr());
r.stort(bedrag);
}
@Override
public synchronized void update(Object observable, Object arg) throws RemoteException {
IObservable o = (IObservable) observable;
if (obs.containsKey(o)) {
ArrayList<String> sessieIds = obs.get(o);
if (sessieIds == null || sessieIds.isEmpty()) {
//geen observers bekend bij sessieId
obs.remove(o);
return;
}
ArrayList<String> shadowIds = new ArrayList<>();
for (String sid : sessieIds) {
shadowIds.add(sid);
}
for (String sessieId : shadowIds) {
IClient client = null;
try {
client = SessieManager.getInstance().getClient(sessieId);
} catch (SessieExpiredException ex) {
Logger.getLogger(Auth.class.getName()).log(Level.SEVERE, null, ex);
}
if (client != null) {
client.setObservable(o);
} else {
//geen client object bekend bij observer, uit de lijst gooien want kan nooit geupdate worden.
sessieIds.remove(sessieId);
}
}
}
}
private synchronized void registerObservable(IObservable o, String sessieId) {
ArrayList<String> sessieIds;
o.addObserver(this);
if (obs.containsKey(o)) {
sessieIds = obs.get(o);
boolean exists = false;
while (!exists) {
for (String sId : sessieIds) {
if (sessieId.equals(sId)) {
exists = true;
}
}
break;
}
if (!exists) {
sessieIds.add(sessieId);
}
} else {
sessieIds = new ArrayList<>();
sessieIds.add(sessieId);
obs.put(o, sessieIds);
}
}
@Override
public synchronized ILoginAccount getLoginAccount(String sessionId) throws RemoteException, SessieExpiredException {
SessieManager sm = SessieManager.getInstance();
try {
Bank.Model.LoginAccount login = sm.getAccountFromSessie(sessionId);
return login;
} catch (SessieExpiredException e) {
throw e;
}
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Bank.Model;
import API.IObservable;
import API.IObserver;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.util.Observable;
import java.util.Observer;
/**
*
* @author ieme
*/
public class BaseObservable extends Observable implements IObservable, Serializable {
private transient static volatile int nextObservableId = 0;
private final int observableId;
private class WrappedObserver implements Observer, Serializable {
private IObserver ro = null;
public WrappedObserver(IObserver ro) {
this.ro = ro;
}
@Override
public void update(Observable o, Object arg) {
try {
ro.update(o, arg);
} catch (RemoteException e) {
System.out
.println("Remote exception removing observer:" + this);
o.deleteObserver(this);
}
}
}
@Override
public synchronized void addObserver(IObserver o) {
WrappedObserver mo = new WrappedObserver(o);
addObserver(mo);
}
public BaseObservable() {
this.observableId = nextObservableId;
nextObservableId++;
}
@Override
public int getObservableId() {
return this.observableId;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Bank.Model;
import API.IKlant;
/** De verantwoordelijkheid van de Klasse klant, is het bijhouden van de naam
* en woonplaats van de klant. De combinatie van naam en woonplaats moeten uniek
* zijn wil de klant zich registreren bij een bank.
*/
public class Klant extends BaseObservable implements IKlant {
private final int klantNr;
private String klantnaam;
private String klantwoonplaats; //nog uit te breiden met postcode etc.
private transient static volatile int nextklantnummer = 1;
/**
* De constructor voor Klant.
* @param klantnaam de naam van de klant.
* @param klantwoonplaats de woonplaats van de klant.
*/
public Klant(String klantnaam, String klantwoonplaats) {
//wanneer klant zijn gegevens heeft ingevoerd zonder hoofdletter(s)
// zal de eerste letter een hoofdletter moeten zijn.
this.klantnaam = capitaliseerWoord(klantnaam);
this.klantwoonplaats = capitaliseerWoord(klantwoonplaats);
this.klantNr = nextklantnummer;
nextklantnummer++;
}
/** Wanneer een klant een naamswijziging doorgeeft kan dat met onderstaande
* methode verwerkt worden.
* @param klantnaam de nieuwe naam van de klant.
*/
public void setKlantnaam(String klantnaam) {
this.klantnaam = klantnaam;
}
/** Wanneer een klant een nieuwe woonplaats doorgeeft, kan dat met
* onderstaande methode worden verwerkt.
* @param klantwoonplaats de nieuwe woonplaats van de klant.
*/
public void setKlantwoonplaats(String klantwoonplaats) {
this.klantwoonplaats = klantwoonplaats;
}
/** Een get-methode voor de klantnaam.
* @return de naam van de klant.
*/
public String getKlantnaam() {
return klantnaam;
}
/** Een get-methode voor de woonplaats van de klant.
* @return de woonplaats van de klant.
*/
public String getKlantwoonplaats() {
return klantwoonplaats;
}
public int getKlantNr() {
return klantNr;
}
private String capitaliseerWoord(String string)
{
String[] token = string.split(" ");
StringBuilder stringbuilder = new StringBuilder();
for(int i = 0; i < token.length; ++i) {
String naam = token[i].toLowerCase();
naam = naam.substring(0, 1).toUpperCase() + naam.substring(1);
stringbuilder.append(naam).append(" ");
}
//laatste spatie er uit halen die automatisch toegevoegd wordt aan de stringbuilder.
return stringbuilder.toString().substring(0, stringbuilder.length()-1);
}
/** Een toString methode voor Klant die de toString methode van Object overschrijft.
* @return de naam van de klant.
*/
@Override
public String toString()
{
return this.klantnaam;
}
}
| Java |
/*
* 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 Bank.Model;
import API.ILoginAccount;
/**
* De verantwoordelijkheid van de klasse LoginAccount is het bijhouden van een
* inlognaam en een wachtwoord. Een inlognaam mag niet vaker voorkomen bij een
* bank (een wachtwoord wel).
*/
public class LoginAccount extends BaseObservable implements ILoginAccount {
private String loginnaam;
private transient String loginwachtwoord;
private final int klantNr;
private final int rekeningNr;
/**
* De constructor van LoginAccount
*
* @param loginnaam de loginnaam van de klant
* @param loginwachtwoord het loginwachtwoord van de klant
*/
public LoginAccount(String loginnaam, String loginwachtwoord, int klantNr, int rekeningNr) {
this.loginnaam = loginnaam;
this.loginwachtwoord = loginwachtwoord;
this.klantNr = klantNr;
this.rekeningNr = rekeningNr;
}
/**
* Een get-methode voor de loginnaam
*
* @return de loginnaam
*/
@Override
public String getLoginNaam() {
return this.loginnaam;
}
@Override
public int getKlantNr() {
return klantNr;
}
public String getLoginwachtwoord() {
return loginwachtwoord;
}
@Override
public int getRekeningNr() {
return rekeningNr;
}
/**
* Wanneer een klant bij het inloggen zijn wachtwoord is vergeten, moet het mogelijk zijn
* (of worden) om het wachtwoord te wijzigen.
*
* @param nieuwwachtwoord het nieuwe wachtwoord
*/
public void setWachtwoord(String nieuwwachtwoord) {
this.loginwachtwoord = nieuwwachtwoord;
}
/**
* Een toString methode voor LoginAccount die de toString methode van Object
* overschrijft.
*
* @return de loginnaam.
*/
@Override
public String toString() {
return this.loginnaam;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Bank.Model;
import API.IClient;
import API.IObservable;
import API.ITransactie;
import API.ITransactieHandler;
import API.TransactieStatus;
import API.TransactieType;
import Bank.Managers.SessieManager;
import Bank.Managers.TransactieManager;
import java.math.BigDecimal;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* De server verstuurt berichten naar de ClientImpl middels deze klasse. Deze
* klasse implementeert ITransactie en bij ClientImpl is ITransactie ook bekend.
* Zodanig kan de klant onderstaande methoden opvragen bij de server.
*/
public class TransactieHandler implements ITransactieHandler {
private static HashMap<IObservable, ArrayList<String>> obs = new HashMap<>();
@Override
public synchronized Transactie requestTransaction(String sessieId, int recipientRekeningnummer, BigDecimal bedrag, String comment) throws SessieExpiredException {
LoginAccount login = SessieManager.getInstance().getAccountFromSessie(sessieId);
if (login != null) {
Transactie trans = new Transactie(login.getRekeningNr(), recipientRekeningnummer, bedrag, comment);
TransactieManager.getInstance().addTransactie(trans);
registerObservable(trans, sessieId);
return trans;
}
return null;
}
@Override
public synchronized ArrayList<ITransactie> getTransacties(String sessieId, GregorianCalendar vanafDatum, GregorianCalendar totDatum) throws RemoteException, SessieExpiredException {
return getTransacties(sessieId, vanafDatum, totDatum, null, TransactieType.ALLE);
}
@Override
public synchronized ArrayList<ITransactie> getTransacties(String sessieId, GregorianCalendar vanafDatum, GregorianCalendar totDatum, TransactieStatus status) throws RemoteException, SessieExpiredException {
return getTransacties(sessieId, vanafDatum, totDatum, status, TransactieType.ALLE);
}
@Override
public synchronized ArrayList<ITransactie> getTransacties(String sessieId, GregorianCalendar vanafDatum, GregorianCalendar totDatum, TransactieType type) throws RemoteException, SessieExpiredException {
return getTransacties(sessieId, vanafDatum, totDatum, null, type);
}
@Override
public synchronized ArrayList<ITransactie> getTransacties(String sessieId, GregorianCalendar vanafDatum, GregorianCalendar totDatum, TransactieStatus status, TransactieType type) throws RemoteException, SessieExpiredException {
LoginAccount login = SessieManager.getInstance().getAccountFromSessieNoActivityChange(sessieId);
if (login != null) {
int rekeningnr = login.getRekeningNr();
ArrayList<ITransactie> iTransacties = new ArrayList<>();
ArrayList<Transactie> transacties = TransactieManager.getInstance().getTransacties(rekeningnr, 0, vanafDatum, totDatum, status, type);
for(Transactie trans : transacties) {
iTransacties.add(trans);
}
return iTransacties;
}
return null;
}
@Override
public synchronized void update(Object observable, Object arg) throws RemoteException {
IObservable o = (IObservable) observable;
if (obs.containsKey(o)) {
ArrayList<String> sessieIds = obs.get(o);
if (sessieIds == null || sessieIds.isEmpty()) {
//geen observers bekend bij sessieId
obs.remove(o);
return;
}
ArrayList<String> shadowIds = new ArrayList<>();
for (String sid : sessieIds) {
shadowIds.add(sid);
}
for (String sessieId : shadowIds) {
IClient client = null;
try {
client = SessieManager.getInstance().getClient(sessieId);
} catch (SessieExpiredException ex) {
Logger.getLogger(Auth.class.getName()).log(Level.SEVERE, null, ex);
}
if (client != null) {
client.setObservable(o);
} else {
//geen client object bekend bij observer, uit de lijst gooien want kan nooit geupdate worden.
sessieIds.remove(sessieId);
}
}
}
}
private synchronized void registerObservable(IObservable o, String sessieId) {
ArrayList<String> sessieIds;
o.addObserver(this);
if (obs.containsKey(o)) {
sessieIds = obs.get(o);
boolean exists = false;
while (!exists) {
for (String sId : sessieIds) {
if (sessieId.equals(sId)) {
exists = true;
}
}
break;
}
if (!exists) {
sessieIds.add(sessieId);
}
} else {
sessieIds = new ArrayList<>();
sessieIds.add(sessieId);
obs.put(o, sessieIds);
}
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Bank.Managers;
import Bank.Model.Klant;
import java.util.HashMap;
/**
* De klantmanager klasse houdt een hashmap waar klanten te zoeken zijn op klantnr
*/
public class KlantManager {
private static volatile KlantManager instance = null;
private HashMap<Integer, Klant> klanten; //klantNr, KlantObject
private static class Loader {
static KlantManager instance = new KlantManager();
}
//constructor
private KlantManager() {
this.klanten = new HashMap<>();
}
public static KlantManager getInstance() {
if (instance == null) {
synchronized (KlantManager.class) {
instance = new KlantManager();
}
}
return instance;
}
/**
* deze methode voegt een klant toe aan de klantmanager
* @param klant
* @return true indien het toevoegen gelukt is, anders false
*/
public boolean addKlant(Klant klant) {
synchronized (this.klanten) {
if (this.klanten.get(klant.getKlantNr()) == null) {
this.klanten.put(klant.getKlantNr(), klant);
return true;
}
}
return false;
}
/**
* deze methode stuurt de klant terug met het gekozen klantnr
* @param klantNr het klantnr van de klant
* @return gekozen klant
*/
public Klant getKlant(int klantNr) {
synchronized (this.klanten) {
return this.klanten.get(klantNr);
}
}
/**
* Methode die kijkt of een klant al bekend is in het systeem wanneer hij/zij
* zich registreert. Dan kan het bestaande klantnummer meegegeven worden.
* @param naam
* @param woonplaats
* @return
*/
public int getBestaandeKlantNummer(String naam, String woonplaats)
{
String klantnaam = capitaliseerWoord(naam);
String klantwoonplaats = capitaliseerWoord(woonplaats);
for (Klant klant : this.klanten.values())
{
if (klant.getKlantnaam().equals(klantnaam) && klant.getKlantwoonplaats().equals(klantwoonplaats))
{
return klant.getKlantNr();
}
}
return 0;
}
/**
* deze functie zet de eerste letter van een string in hoofdletter en de rest van de string in kleine letters.
* @param string de string die aangepast moet worden
* @return string
*/
private String capitaliseerWoord(String string)
{
String[] token = string.split(" ");
StringBuilder stringbuilder = new StringBuilder();
for(int i = 0; i < token.length; ++i) {
String naam = token[i].toLowerCase();
naam = naam.substring(0, 1).toUpperCase() + naam.substring(1);
stringbuilder.append(naam).append(" ");
}
//laatste spatie er uit halen die automatisch toegevoegd wordt aan de stringbuilder.
return stringbuilder.toString().substring(0, stringbuilder.length()-1);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Bank.Managers;
import java.util.TimerTask;
/**
* SessieTask om een sessie te kunnen beindigen na inactiviteit. Kan gebruikt
* worden i.c.m. java.util.Timer.
*
*/
public class SessieTask extends TimerTask {
public SessieTask() {
}
@Override
public void run() {
SessieManager sm = SessieManager.getInstance();
sm.expireCheck();
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Bank.Managers;
import API.IClient;
import Bank.Model.LoginAccount;
import Bank.Model.Sessie;
import Bank.Model.SessieExpiredException;
import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* de SessieManager klasse houdt een hashmap bij waarin alle sessies worden bijgehouden.
* Deze zijn te zoeken op SessieID.
*/
public class SessieManager {
private static volatile SessieManager instance = null;
//Hashmap zodat we met O(1) op sessieId kunnen zoeken.
//zoeken op Sessie referentie is gelijk aan ArrayList O(n);
private HashMap<String, Sessie> sessies;
private Timer timer;
private long timerInterval = 1000;
private SessieTask sessieTask;
/**
* Methode om een loginaccount bij een sessie op te vragen zonder dat de laatste activiteit geupdate wordt.
* Vanuit de gui wordt er elke keer een callback gedaan om de transactielijst te verversen. Hierbij mag de
* lastActivity niet veranderd worden bij de betreffende sessie.
* @param sessieId
* @return
* @throws SessieExpiredException
*/
public LoginAccount getAccountFromSessieNoActivityChange(String sessieId) throws SessieExpiredException {
synchronized (sessies) {
if (sessieId != null) {
Sessie sessie = sessies.get(sessieId);
if (sessie != null) {
return sessie.getLoginNoActivityChange();
} else {
throw new SessieExpiredException("Sessie verlopen");
}
}
}
return null;
}
private static class Loader {
static SessieManager instance = new SessieManager();
}
private SessieManager() {
this.sessies = new HashMap<>();
scheduleExpireCheck();
}
public static SessieManager getInstance() {
if (instance == null) {
synchronized (SessieManager.class) {
instance = new SessieManager();
}
}
return instance;
}
/**
* voegt een sessie toe aan de SessieManager
* @param sessie de toe te voegen sessie
* @return true indien de sessie is toegevoegd, anders false
*/
public boolean addSessie(Sessie sessie) {
if (sessie != null) {
synchronized (this.sessies) {
if (this.sessies.get(sessie.getSessieId()) == null) {
this.sessies.put(sessie.getSessieId(), sessie);
return true;
}
}
}
return false;
}
/**
* stuurt sessie terug met het opgegeven sessieId
* @param sessieId sessieId van de terug te sturen sessie
* @return sessie indien deze in de SessieManager voorkomt, anders null
*/
private Sessie getSessie(String sessieId) {
synchronized (sessies) {
if (sessieId != null) {
Sessie sessie = sessies.get(sessieId);
return sessie;
}
}
return null;
}
/**
* stuurt een loginaccount terug waarbij de sessie het opgegeven sessieId heeft
* @param sessieId het sessieId van de sessie
* @return loginaccount van het gekozen sessieId indien deze is gevonden, anders null
* @throws SessieExpiredException
*/
public LoginAccount getAccountFromSessie(String sessieId) throws SessieExpiredException {
synchronized (sessies) {
if (sessieId != null) {
Sessie sessie = sessies.get(sessieId);
if (sessie != null) {
return sessie.getLogin();
} else {
throw new SessieExpiredException("Sessie verlopen");
}
}
}
return null;
}
private void scheduleExpireCheck() {
try {
if (timer != null) {
timer.cancel();
}
} catch (IllegalStateException e) {
} finally {
timer = new Timer();
sessieTask = new SessieTask();
timer.schedule(sessieTask, timerInterval);
}
}
/**
* Kijk of sessies 10 minuten ongebruikt zijn, logt ze dan uit.
*/
public void expireCheck() {
java.util.Date date = new java.util.Date();
synchronized (this.sessies) {
for (Map.Entry pair : this.sessies.entrySet()) {
Sessie sessie = (Sessie) pair.getValue();
long verschil = date.getTime() - sessie.getLastActivity().getTime();
System.out.println("Sessie ID: " + sessie.getSessieId() + " Verschil: " + verschil );
if (verschil > 10000) {
IClient clientOb = sessie.getClient();
try {
clientOb.logOut();
} catch (RemoteException ex) {
Logger.getLogger(SessieManager.class.getName()).log(Level.SEVERE, null, ex);
} finally {
this.sessies.remove(sessie.getSessieId());
}
}
}
}
scheduleExpireCheck();
}
public void bindClientObjecToSessie(String sessieId, IClient clientObject) throws SessieExpiredException {
synchronized (this.sessies) {
Sessie sessie = this.sessies.get(sessieId);
if (sessie != null) {
sessie.setClient(clientObject);
} else {
throw new SessieExpiredException("Sessie verlopen");
}
}
}
public synchronized IClient getClient(String sessieId) throws SessieExpiredException {
if (sessieId != null && sessies.get(sessieId) != null) {
Sessie sessie = sessies.get(sessieId);
return sessie.getClient();
}
return null;
}
/**
* verwijdert de sessie
* @param sessieId sessieId van de te verwijderen Sessie
*/
public void stopSessie(String sessieId) {
if (sessieId != null) {
synchronized (sessies) {
if (sessies.containsKey(sessieId)) {
sessies.remove(sessieId);
}
}
}
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Bank.Managers;
import Bank.Model.Rekening;
import java.util.HashMap;
/**
* de rekeningmanager klasse houdt een hashmap met rekeningen waarbij
* op rekeningnummer gezocht kan worden.
*/
public class RekeningManager {
private static volatile RekeningManager instance = null;
private HashMap<Integer, Rekening> rekeningen;
private static class Loader {
static RekeningManager instance = new RekeningManager();
}
private RekeningManager() {
this.rekeningen = new HashMap<>();
}
public static RekeningManager getInstance() {
if (instance == null) {
synchronized (RekeningManager.class) {
instance = new RekeningManager();
}
}
return instance;
}
/**
* voegt een rekening toe aan de rekeningmanager
* @param rekening de toe te voegen rekening
* @return true indien de rekening is toegevoegd, anders false
*/
public boolean addRekening(Rekening rekening) {
if (rekening != null) {
synchronized (this.rekeningen) {
if (this.rekeningen.get(rekening.getRekeningnummer()) == null) {
this.rekeningen.put(rekening.getRekeningnummer(), rekening);
return true;
}
}
}
return false;
}
/**
* stuurt rekeningobject terug met gekozen rekeningnr
* @param rekeningNr het rekeningnummer van het terug te sturen rekeningobject.
* @return gekozen Rekening
*/
public Rekening getRekening(int rekeningNr) {
synchronized (this.rekeningen) {
return this.rekeningen.get(rekeningNr);
}
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Bank.Managers;
import Bank.Model.LoginAccount;
import java.util.HashMap;
/**
* De loginmanager klasse houdt een hashmap bij waarin loginaccounts te vinden zijn op loginnr
*/
public class LoginManager {
private static volatile LoginManager instance = null;
private HashMap<String, LoginAccount> logins; //loginNr, loginObject;
private static class Loader {
static LoginManager instance = new LoginManager();
}
private LoginManager() {
this.logins = new HashMap<>();
}
public static LoginManager getInstance() {
if (instance == null) {
synchronized (LoginManager.class) {
instance = new LoginManager();
}
}
return instance;
}
/**
* voegt een loginaccount toe aan de loginmanager
* @param login het toe te voegen loginaccount
* @return true indien het toevoegen is gelukt, false indien dit niet is gelukt.
*/
public boolean addLogin(LoginAccount login) {
if (login != null) {
synchronized (this.logins) {
if (this.logins.get(login.getLoginNaam()) == null) {
this.logins.put(login.getLoginNaam(), login);
return true;
}
}
}
return false;
}
/**
* deze methode stuurt het loginaccount terug indien het opgegeven naam
* en wachtwoord correct zijn.
* Indien de loginnaam niet bestaat of het wachtwoord niet klopt zal dit
* door middel van een exception door worden gegeven.
* @param loginNaam de loginnaam van het op te vragen loginaccount
* @param password het wachtwoord van het op te vragen loginaccount
* @return LoginAccount indien naam en wachtwoord correct
* @throws IllegalArgumentException
*/
public LoginAccount getLoginAccount(String loginNaam, String password) throws IllegalArgumentException {
synchronized (this.logins) {
LoginAccount login = this.logins.get(loginNaam);
if (login == null) {
throw new IllegalArgumentException("Onbekende gebruikersnaam");
}
if (login.getLoginwachtwoord().equals(password)) {
return login;
} else {
throw new IllegalArgumentException("Foutief wachtwoord");
}
}
}
/**
* checkt indien de opgegeven loginNaam al bestaat.
* @param loginNaam de te checken naam van het inlogaccount
* @return false indien de loginnaam niet bestaat
*/
public boolean bestaatLoginNaam(String loginNaam)
{
synchronized(this.logins)
{
LoginAccount login = this.logins.get(loginNaam);
if (login == null) {
return false;
} else {
throw new IllegalArgumentException("Loginnaam is al in gebruik");
}
}
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Bank.Managers;
import API.TransactieStatus;
import API.TransactieType;
import Bank.Model.Rekening;
import Bank.Model.Transactie;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
/**
* houdt een lijst bij van alle transacties
*/
public class TransactieManager {
private static volatile TransactieManager instance = null;
private HashMap<Integer, Transactie> transacties;
private static class Loader {
static TransactieManager instance = new TransactieManager();
}
private TransactieManager() {
this.transacties = new HashMap<>();
}
public static TransactieManager getInstance() {
if (instance == null) {
synchronized (TransactieManager.class) {
instance = new TransactieManager();
}
}
return instance;
}
public void addTransactie(Transactie trans) {
if (trans != null) {
synchronized (transacties) {
if (transacties.get(trans.getTransactieId()) == null) {
if (trans.getStatus() == TransactieStatus.OPENSTAAND) {
Rekening creditRekeningNr = RekeningManager.getInstance().getRekening(trans.getEigenbankrekening());
if (creditRekeningNr == null) {
trans.setStatus(TransactieStatus.GEWEIGERD);
}
}
//hier moet een check komen wanneer tegenrekening geen onderdeel is van deze bank.
transacties.put(trans.getTransactieId(), trans);
executeTransactions();
}
};
}
}
//uitvoeren van transacties kan beter in aparte threads worden gedaan. Voor nu zo gelaten.
//Rekening moet ook nog verschillende banken gaan ondersteunen.
private void executeTransactions() {
synchronized (transacties) {
for (Map.Entry pair : this.transacties.entrySet()) {
Transactie trans = (Transactie) pair.getValue();
executeTransaction(trans);
}
};
}
private void executeTransaction(Transactie trans) {
if (trans != null) {
if (trans.getStatus() == TransactieStatus.OPENSTAAND) {
Rekening creditRekeningNr = RekeningManager.getInstance().getRekening(trans.getEigenbankrekening());
Rekening debitRekeningNr = RekeningManager.getInstance().getRekening(trans.getTegenrekening());
if (debitRekeningNr != null) {
if (creditRekeningNr.neemOp(trans.getBedrag())) {
debitRekeningNr.stort(trans.getBedrag());
trans.setStatus(TransactieStatus.VOLTOOID);
} else {
trans.setStatus(TransactieStatus.GEWEIGERD);
}
} else {
trans.setStatus(TransactieStatus.GEWEIGERD);
}
}
}
}
//niet getest
public ArrayList<Transactie> getTransacties(int creditRknNr, int debetRknNr, GregorianCalendar vanafDatum, GregorianCalendar totDatum, TransactieStatus status, TransactieType type) {
ArrayList<Transactie> gezochteTransactie = new ArrayList<>();
GregorianCalendar searchVanafDatum;
GregorianCalendar searchTotDatum;
if (vanafDatum == null | vanafDatum instanceof GregorianCalendar == false) {
searchVanafDatum = new GregorianCalendar();
//geen datum opgegeven is standaard 30 dagen terug.
searchVanafDatum.add(Calendar.DAY_OF_MONTH, -30);
} else {
searchVanafDatum = vanafDatum;
}
if (totDatum == null | totDatum instanceof GregorianCalendar == false) {
searchTotDatum = new GregorianCalendar();
} else {
searchTotDatum = totDatum;
}
synchronized (transacties) {
for (Map.Entry pair : this.transacties.entrySet()) {
Transactie t = (Transactie) pair.getValue();
if (status == null | status == t.getStatus()) {
//nog aanpassen. Dit is een exclusive search i.p.v. inclusive
if (t.getTransactieInvoerDatum().before(searchTotDatum) && t.getTransactieInvoerDatum().after(searchVanafDatum)) {
//wanneer debetRknr is opgegeven maakt type niet uit.
if (debetRknNr != 0 & creditRknNr == t.getEigenbankrekening()) {
gezochteTransactie.add(t);
} else {
switch (type) {
case ALLE:
//aanvragen die niet voltooid zijn mogen niet zichtbaar zijn voor de ontvanger.
if (t.getStatus() == TransactieStatus.VOLTOOID) {
if (creditRknNr == t.getEigenbankrekening() | creditRknNr == t.getTegenrekening()) {
gezochteTransactie.add(t);
}
} else {
if (creditRknNr == t.getEigenbankrekening()) {
gezochteTransactie.add(t);
}
}
break;
case DEBET:
if (creditRknNr == t.getTegenrekening() & debetRknNr == t.getEigenbankrekening()) {
gezochteTransactie.add(t);
}
break;
case CREDIT:
if (creditRknNr == t.getEigenbankrekening() & debetRknNr == t.getTegenrekening()) {
gezochteTransactie.add(t);
}
break;
}
}
}
}
}
}
return gezochteTransactie;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Bank.Server;
import API.IAuth;
import API.ITransactieHandler;
import Bank.Model.TransactieHandler;
import Bank.Model.Auth;
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Dit is de klasse waar de server geinstantieerd wordt.
*/
public class ServerStarter {
// private ClientImpl client;
private static Auth login;
private static TransactieHandler transactie;
private static Registry registry;
/**
* Constructor voor de Server van een bank. Hierin wordt geprobeerd een RMI
* connectie open te zetten zodat clients deze kunnen benaderen. Er worden 2
* stubs gemaakt. Een voor login waarmee simpele data opgehaald wordt bij de
* server. Een voor transactie waarmee transacties opgehaald kunnen worden
* bij de server.
*/
public ServerStarter() {
try {
registry = LocateRegistry.createRegistry(1099);
} catch (RemoteException ex) {
Logger.getLogger(ServerStarter.class.getName()).log(Level.SEVERE, null, ex);
}
login = new Auth();
transactie = new TransactieHandler();
loadData();
try {
ITransactieHandler transactieStub = (ITransactieHandler) UnicastRemoteObject.exportObject(transactie, 0);
IAuth loginStub = (IAuth) UnicastRemoteObject.exportObject(login, 0);
LocateRegistry.getRegistry().bind("transactie", transactieStub);
LocateRegistry.getRegistry().bind("auth", loginStub);
System.out.println("Server ready");
} catch (RemoteException | AlreadyBoundException ex) {
Logger.getLogger(ServerStarter.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void loadData() {
DummyBank db = new DummyBank();
}
/**
* De start-methode voor de Server. Hier zou nog een GUI voor gemaakt kunnen
* worden mits er voldoende tijd is.
*
* @param args
*/
public static void main(String[] args) {
ServerStarter starter = new ServerStarter();
while (true) {
//do nothing, keeps thread alive.
}
}
}
| Java |
/*
* 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 Bank.Server;
import Bank.Managers.KlantManager;
import Bank.Managers.LoginManager;
import Bank.Managers.RekeningManager;
import Bank.Model.Klant;
import Bank.Model.LoginAccount;
import Bank.Model.Rekening;
import java.math.BigDecimal;
/**
*
* @author Melis
*/
public class DummyBank {
//private int klantnummer = 1;
public DummyBank()
{
voegKlantToe("Ieme Welling", "Eindhoven", "ieme", "ieme");
voegKlantToe("test", "Ergens", "test", "test");
voegKlantToe("Melissa Coulthard", "Eindhoven", "Mel", "a");
voegKlantToe("Roland Ansems", "Somewhere", "Rollie", "Lolly");
voegKlantToe("Harry Harig", "Baurle-Naussau", "Harry", "Harry");
voegKlantToe("Barry van Bavel", "Loon op Zand", "Bar", "Weinig");
voegKlantToe("Superman", "Superwereld", "Superman", "Hero");
voegKlantToe("Theo Maassen", "Eindhoven", "Theootje", "123");
}
private void voegKlantToe(String naam, String woonplaats, String klantlogin, String wachtwoord)
{
// Klant klant = new Klant(naam, woonplaats, this.klantnummer);
Klant klant = new Klant(naam, woonplaats);
Rekening rekeningKlant = new Rekening();
rekeningKlant.stort(new BigDecimal(50));
//LoginAccount loginKlant = new LoginAccount(klantlogin, wachtwoord, this.klantnummer, rekeningKlant.getRekeningnummer());
LoginAccount loginKlant = new LoginAccount(klantlogin, wachtwoord, klant.getKlantNr(), rekeningKlant.getRekeningnummer());
KlantManager km = KlantManager.getInstance();
LoginManager lm = LoginManager.getInstance();
RekeningManager rm = RekeningManager.getInstance();
km.addKlant(klant);
lm.addLogin(loginKlant);
rm.addRekening(rekeningKlant);
//this.klantnummer++;
}
}
| Java |
package com.nexes.wizard;
import java.io.*;
public class WizardPanelNotFoundException extends RuntimeException {
public WizardPanelNotFoundException() {
super();
}
} | Java |
package com.nexes.wizard;
import java.awt.*;
import javax.swing.*;
/**
* A base descriptor class used to reference a Component panel for the Wizard, as
* well as provide general rules as to how the panel should behave.
*/
public class WizardPanelDescriptor {
private static final String DEFAULT_PANEL_IDENTIFIER = "defaultPanelIdentifier";
/**
* Identifier returned by getNextPanelDescriptor() to indicate that this is the
* last panel and the text of the 'Next' button should change to 'Finish'.
*/
public static final FinishIdentifier FINISH = new FinishIdentifier();
private Wizard wizard;
private Component targetPanel;
private Object panelIdentifier;
/**
* Default constructor. The id and the Component panel must be set separately.
*/
public WizardPanelDescriptor() {
panelIdentifier = DEFAULT_PANEL_IDENTIFIER;
targetPanel = new JPanel();
}
/**
* Constructor which accepts both the Object-based identifier and a reference to
* the Component class which makes up the panel.
* @param id Object-based identifier
* @param panel A class which extends java.awt.Component that will be inserted as a
* panel into the wizard dialog.
*/
public WizardPanelDescriptor(Object id, Component panel) {
panelIdentifier = id;
targetPanel = panel;
}
/**
* Returns to java.awt.Component that serves as the actual panel.
* @return A reference to the java.awt.Component that serves as the panel
*/
public final Component getPanelComponent() {
return targetPanel;
}
/**
* Sets the panel's component as a class that extends java.awt.Component
* @param panel java.awt.Component which serves as the wizard panel
*/
public final void setPanelComponent(Component panel) {
targetPanel = panel;
}
/**
* Returns the unique Object-based identifier for this panel descriptor.
* @return The Object-based identifier
*/
public final Object getPanelDescriptorIdentifier() {
return panelIdentifier;
}
/**
* Sets the Object-based identifier for this panel. The identifier must be unique
* from all the other identifiers in the panel.
* @param id Object-based identifier for this panel.
*/
public final void setPanelDescriptorIdentifier(Object id) {
panelIdentifier = id;
}
final void setWizard(Wizard w) {
wizard = w;
}
/**
* Returns a reference to the Wizard component.
* @return The Wizard class hosting this descriptor.
*/
public final Wizard getWizard() {
return wizard;
}
/**
* Returns a reference to the current WizardModel for this Wizard component.
* @return The current WizardModel for this Wizard component.
*/
public WizardModel getWizardModel() {
return wizard.getModel();
}
// Override this method to provide an Object-based identifier
// for the next panel.
/**
* Override this class to provide the Object-based identifier of the panel that the
* user should traverse to when the Next button is pressed. Note that this method
* is only called when the button is actually pressed, so that the panel can change
* the next panel's identifier dynamically at runtime if necessary. Return null if
* the button should be disabled. Return FinishIdentfier if the button text
* should change to 'Finish' and the dialog should end.
* @return Object-based identifier.
*/
public Object getNextPanelDescriptor() {
return null;
}
// Override this method to provide an Object-based identifier
// for the previous panel.
/**
* Override this class to provide the Object-based identifier of the panel that the
* user should traverse to when the Back button is pressed. Note that this method
* is only called when the button is actually pressed, so that the panel can change
* the previous panel's identifier dynamically at runtime if necessary. Return null if
* the button should be disabled.
* @return Object-based identifier
*/
public Object getBackPanelDescriptor() {
return null;
}
// Override this method in the subclass if you wish it to be called
// just before the panel is displayed.
/**
* Override this method to provide functionality that will be performed just before
* the panel is to be displayed.
*/
public void aboutToDisplayPanel() {
}
// Override this method in the subclass if you wish to do something
// while the panel is displaying.
/**
* Override this method to perform functionality when the panel itself is displayed.
*/
public void displayingPanel() {
}
// Override this method in the subclass if you wish it to be called
// just before the panel is switched to another or finished.
/**
* Override this method to perform functionality just before the panel is to be
* hidden.
*/
public void aboutToHidePanel() {
}
static class FinishIdentifier {
public static final String ID = "FINISH";
}
}
| Java |
package com.nexes.wizard;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
import java.util.*;
import java.net.*;
import javax.swing.*;
import javax.swing.border.*;
/**
* This class implements a basic wizard dialog, where the programmer can
* insert one or more Components to act as panels. These panels can be navigated
* through arbitrarily using the 'Next' or 'Back' buttons, or the dialog itself
* can be closed using the 'Cancel' button. Note that even though the dialog
* uses a CardLayout manager, the order of the panels is not linear. Each panel
* determines at runtime what its next and previous panel will be.
*/
public class Wizard extends WindowAdapter implements PropertyChangeListener {
/**
* Indicates that the 'Finish' button was pressed to close the dialog.
*/
public static final int FINISH_RETURN_CODE = 0;
/**
* Indicates that the 'Cancel' button was pressed to close the dialog, or
* the user pressed the close box in the corner of the window.
*/
public static final int CANCEL_RETURN_CODE = 1;
/**
* Indicates that the dialog closed due to an internal error.
*/
public static final int ERROR_RETURN_CODE = 2;
/**
* The String-based action command for the 'Next' button.
*/
public static final String NEXT_BUTTON_ACTION_COMMAND = "NextButtonActionCommand";
/**
* The String-based action command for the 'Back' button.
*/
public static final String BACK_BUTTON_ACTION_COMMAND = "BackButtonActionCommand";
/**
* The String-based action command for the 'Cancel' button.
*/
public static final String CANCEL_BUTTON_ACTION_COMMAND = "CancelButtonActionCommand";
// The i18n text used for the buttons. Loaded from a property resource file.
static String BACK_TEXT;
static String NEXT_TEXT;
static String FINISH_TEXT;
static String CANCEL_TEXT;
// The image icons used for the buttons. Filenames are loaded from a property resource file.
static Icon BACK_ICON;
static Icon NEXT_ICON;
static Icon FINISH_ICON;
static Icon CANCEL_ICON;
private WizardModel wizardModel;
private WizardController wizardController;
private JDialog wizardDialog;
private JPanel cardPanel;
private CardLayout cardLayout;
private JButton backButton;
private JButton nextButton;
private JButton cancelButton;
private int returnCode;
/**
* Default constructor. This method creates a new WizardModel object and passes it
* into the overloaded constructor.
*/
public Wizard() {
this((Frame)null);
}
/**
* This method accepts a java.awt.Dialog object as the javax.swing.JDialog's
* parent.
* @param owner The java.awt.Dialog object that is the owner of this dialog.
*/
public Wizard(Dialog owner) {
wizardModel = new WizardModel();
wizardDialog = new JDialog(owner);
initComponents();
}
/**
* This method accepts a java.awt.Frame object as the javax.swing.JDialog's
* parent.
* @param owner The java.awt.Frame object that is the owner of the javax.swing.JDialog.
*/
public Wizard(Frame owner) {
wizardModel = new WizardModel();
wizardDialog = new JDialog(owner);
initComponents();
}
/**
* Returns an instance of the JDialog that this class created. This is useful in
* the event that you want to change any of the JDialog parameters manually.
* @return The JDialog instance that this class created.
*/
public JDialog getDialog() {
return wizardDialog;
}
/**
* Returns the owner of the generated javax.swing.JDialog.
* @return The owner (java.awt.Frame or java.awt.Dialog) of the javax.swing.JDialog generated
* by this class.
*/
public Component getOwner() {
return wizardDialog.getOwner();
}
/**
* Sets the title of the generated javax.swing.JDialog.
* @param s The title of the dialog.
*/
public void setTitle(String s) {
wizardDialog.setTitle(s);
}
/**
* Returns the current title of the generated dialog.
* @return The String-based title of the generated dialog.
*/
public String getTitle() {
return wizardDialog.getTitle();
}
/**
* Sets the modality of the generated javax.swing.JDialog.
* @param b the modality of the dialog
*/
public void setModal(boolean b) {
wizardDialog.setModal(b);
}
/**
* Returns the modality of the dialog.
* @return A boolean indicating whether or not the generated javax.swing.JDialog is modal.
*/
public boolean isModal() {
return wizardDialog.isModal();
}
/**
* Convienence method that displays a modal wizard dialog and blocks until the dialog
* has completed.
* @return Indicates how the dialog was closed. Compare this value against the RETURN_CODE
* constants at the beginning of the class.
*/
public int showModalDialog() {
wizardDialog.setModal(true);
wizardDialog.pack();
wizardDialog.toFront();
wizardDialog.setVisible(true);
return returnCode;
}
/**
* Returns the current model of the wizard dialog.
* @return A WizardModel instance, which serves as the model for the wizard dialog.
*/
public WizardModel getModel() {
return wizardModel;
}
/**
* Add a Component as a panel for the wizard dialog by registering its
* WizardPanelDescriptor object. Each panel is identified by a unique Object-based
* identifier (often a String), which can be used by the setCurrentPanel()
* method to display the panel at runtime.
* @param id An Object-based identifier used to identify the WizardPanelDescriptor object.
* @param panel The WizardPanelDescriptor object which contains helpful information about the panel.
*/
public void registerWizardPanel(Object id, WizardPanelDescriptor panel) {
// Add the incoming panel to our JPanel display that is managed by
// the CardLayout layout manager.
cardPanel.add(panel.getPanelComponent(), id);
// Set a callback to the current wizard.
panel.setWizard(this);
// Place a reference to it in the model.
wizardModel.registerPanel(id, panel);
}
/**
* Displays the panel identified by the object passed in. This is the same Object-based
* identified used when registering the panel.
* @param id The Object-based identifier of the panel to be displayed.
*/
public void setCurrentPanel(Object id) {
// Get the hashtable reference to the panel that should
// be displayed. If the identifier passed in is null, then close
// the dialog.
if (id == null)
close(ERROR_RETURN_CODE);
WizardPanelDescriptor oldPanelDescriptor = wizardModel.getCurrentPanelDescriptor();
if (oldPanelDescriptor != null)
oldPanelDescriptor.aboutToHidePanel();
wizardModel.setCurrentPanel(id);
wizardModel.getCurrentPanelDescriptor().aboutToDisplayPanel();
// Show the panel in the dialog.
cardLayout.show(cardPanel, id.toString());
wizardModel.getCurrentPanelDescriptor().displayingPanel();
}
/**
* Method used to listen for property change events from the model and update the
* dialog's graphical components as necessary.
* @param evt PropertyChangeEvent passed from the model to signal that one of its properties has changed value.
*/
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(WizardModel.CURRENT_PANEL_DESCRIPTOR_PROPERTY)) {
wizardController.resetButtonsToPanelRules();
} else if (evt.getPropertyName().equals(WizardModel.NEXT_FINISH_BUTTON_TEXT_PROPERTY)) {
nextButton.setText(evt.getNewValue().toString());
} else if (evt.getPropertyName().equals(WizardModel.BACK_BUTTON_TEXT_PROPERTY)) {
backButton.setText(evt.getNewValue().toString());
} else if (evt.getPropertyName().equals(WizardModel.CANCEL_BUTTON_TEXT_PROPERTY)) {
cancelButton.setText(evt.getNewValue().toString());
} else if (evt.getPropertyName().equals(WizardModel.NEXT_FINISH_BUTTON_ENABLED_PROPERTY)) {
nextButton.setEnabled(((Boolean)evt.getNewValue()).booleanValue());
} else if (evt.getPropertyName().equals(WizardModel.BACK_BUTTON_ENABLED_PROPERTY)) {
backButton.setEnabled(((Boolean)evt.getNewValue()).booleanValue());
} else if (evt.getPropertyName().equals(WizardModel.CANCEL_BUTTON_ENABLED_PROPERTY)) {
cancelButton.setEnabled(((Boolean)evt.getNewValue()).booleanValue());
} else if (evt.getPropertyName().equals(WizardModel.NEXT_FINISH_BUTTON_ICON_PROPERTY)) {
nextButton.setIcon((Icon)evt.getNewValue());
} else if (evt.getPropertyName().equals(WizardModel.BACK_BUTTON_ICON_PROPERTY)) {
backButton.setIcon((Icon)evt.getNewValue());
} else if (evt.getPropertyName().equals(WizardModel.CANCEL_BUTTON_ICON_PROPERTY)) {
cancelButton.setIcon((Icon)evt.getNewValue());
}
}
/**
* Retrieves the last return code set by the dialog.
* @return An integer that identifies how the dialog was closed. See the *_RETURN_CODE
* constants of this class for possible values.
*/
public int getReturnCode() {
return returnCode;
}
/**
* Mirrors the WizardModel method of the same name.
* @return A boolean indicating if the button is enabled.
*/
public boolean getBackButtonEnabled() {
return wizardModel.getBackButtonEnabled().booleanValue();
}
/**
* Mirrors the WizardModel method of the same name.
* @param boolean newValue The new enabled status of the button.
*/
public void setBackButtonEnabled(boolean newValue) {
wizardModel.setBackButtonEnabled(new Boolean(newValue));
}
/**
* Mirrors the WizardModel method of the same name.
* @return A boolean indicating if the button is enabled.
*/
public boolean getNextFinishButtonEnabled() {
return wizardModel.getNextFinishButtonEnabled().booleanValue();
}
/**
* Mirrors the WizardModel method of the same name.
* @param boolean newValue The new enabled status of the button.
*/
public void setNextFinishButtonEnabled(boolean newValue) {
wizardModel.setNextFinishButtonEnabled(new Boolean(newValue));
}
/**
* Mirrors the WizardModel method of the same name.
* @return A boolean indicating if the button is enabled.
*/
public boolean getCancelButtonEnabled() {
return wizardModel.getCancelButtonEnabled().booleanValue();
}
/**
* Mirrors the WizardModel method of the same name.
* @param boolean newValue The new enabled status of the button.
*/
public void setCancelButtonEnabled(boolean newValue) {
wizardModel.setCancelButtonEnabled(new Boolean(newValue));
}
/**
* Closes the dialog and sets the return code to the integer parameter.
* @param code The return code.
*/
void close(int code) {
returnCode = code;
wizardDialog.dispose();
}
/**
* This method initializes the components for the wizard dialog: it creates a JDialog
* as a CardLayout panel surrounded by a small amount of space on each side, as well
* as three buttons at the bottom.
*/
private void initComponents() {
wizardModel.addPropertyChangeListener(this);
wizardController = new WizardController(this);
wizardDialog.getContentPane().setLayout(new BorderLayout());
wizardDialog.addWindowListener(this);
// Create the outer wizard panel, which is responsible for three buttons:
// Next, Back, and Cancel. It is also responsible a JPanel above them that
// uses a CardLayout layout manager to display multiple panels in the
// same spot.
JPanel buttonPanel = new JPanel();
JSeparator separator = new JSeparator();
Box buttonBox = new Box(BoxLayout.X_AXIS);
cardPanel = new JPanel();
cardPanel.setBorder(new EmptyBorder(new Insets(5, 10, 5, 10)));
cardLayout = new CardLayout();
cardPanel.setLayout(cardLayout);
backButton = new JButton(new ImageIcon("com/nexes/wizard/backIcon.gif"));
nextButton = new JButton();
cancelButton = new JButton();
backButton.setActionCommand(BACK_BUTTON_ACTION_COMMAND);
nextButton.setActionCommand(NEXT_BUTTON_ACTION_COMMAND);
cancelButton.setActionCommand(CANCEL_BUTTON_ACTION_COMMAND);
backButton.addActionListener(wizardController);
nextButton.addActionListener(wizardController);
cancelButton.addActionListener(wizardController);
// Create the buttons with a separator above them, then place them
// on the east side of the panel with a small amount of space between
// the back and the next button, and a larger amount of space between
// the next button and the cancel button.
buttonPanel.setLayout(new BorderLayout());
buttonPanel.add(separator, BorderLayout.NORTH);
buttonBox.setBorder(new EmptyBorder(new Insets(5, 10, 5, 10)));
buttonBox.add(backButton);
buttonBox.add(Box.createHorizontalStrut(10));
buttonBox.add(nextButton);
buttonBox.add(Box.createHorizontalStrut(30));
buttonBox.add(cancelButton);
buttonPanel.add(buttonBox, java.awt.BorderLayout.EAST);
wizardDialog.getContentPane().add(buttonPanel, java.awt.BorderLayout.SOUTH);
wizardDialog.getContentPane().add(cardPanel, java.awt.BorderLayout.CENTER);
}
private static Object getImage(String name) {
URL url = null;
try {
Class c = Class.forName("com.nexes.wizard.Wizard");
url = c.getResource(name);
} catch (ClassNotFoundException cnfe) {
System.err.println("Unable to find Wizard class");
}
return url;
}
/**
* If the user presses the close box on the dialog's window, treat it
* as a cancel.
* @param WindowEvent The event passed in from AWT.
*/
public void windowClosing(WindowEvent e) {
returnCode = CANCEL_RETURN_CODE;
}
static {
try {
PropertyResourceBundle resources = (PropertyResourceBundle)
ResourceBundle.getBundle("com.nexes.wizard.wizard");
BACK_TEXT = (String)(resources.getObject("backButtonText"));
NEXT_TEXT = (String)(resources.getObject("nextButtonText"));
CANCEL_TEXT = (String)(resources.getObject("cancelButtonText"));
FINISH_TEXT = (String)(resources.getObject("finishButtonText"));
BACK_ICON = new ImageIcon((URL)getImage((String)(resources.getObject("backButtonIcon"))));
NEXT_ICON = new ImageIcon((URL)getImage((String)(resources.getObject("nextButtonIcon"))));
CANCEL_ICON = new ImageIcon((URL)getImage((String)(resources.getObject("cancelButtonIcon"))));
FINISH_ICON = new ImageIcon((URL)getImage((String)(resources.getObject("finishButtonIcon"))));
} catch (MissingResourceException mre) {
System.out.println(mre);
System.exit(1);
}
}
}
| Java |
package com.nexes.wizard;
import java.beans.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
/**
* The model for the Wizard component, which tracks the text, icons, and enabled state
* of each of the buttons, as well as the current panel that is displayed. Note that
* the model, in its current form, is not intended to be subclassed.
*/
public class WizardModel {
/**
* Identification string for the current panel.
*/
public static final String CURRENT_PANEL_DESCRIPTOR_PROPERTY = "currentPanelDescriptorProperty";
/**
* Property identification String for the Back button's text
*/
public static final String BACK_BUTTON_TEXT_PROPERTY = "backButtonTextProperty";
/**
* Property identification String for the Back button's icon
*/
public static final String BACK_BUTTON_ICON_PROPERTY = "backButtonIconProperty";
/**
* Property identification String for the Back button's enabled state
*/
public static final String BACK_BUTTON_ENABLED_PROPERTY = "backButtonEnabledProperty";
/**
* Property identification String for the Next button's text
*/
public static final String NEXT_FINISH_BUTTON_TEXT_PROPERTY = "nextButtonTextProperty";
/**
* Property identification String for the Next button's icon
*/
public static final String NEXT_FINISH_BUTTON_ICON_PROPERTY = "nextButtonIconProperty";
/**
* Property identification String for the Next button's enabled state
*/
public static final String NEXT_FINISH_BUTTON_ENABLED_PROPERTY = "nextButtonEnabledProperty";
/**
* Property identification String for the Cancel button's text
*/
public static final String CANCEL_BUTTON_TEXT_PROPERTY = "cancelButtonTextProperty";
/**
* Property identification String for the Cancel button's icon
*/
public static final String CANCEL_BUTTON_ICON_PROPERTY = "cancelButtonIconProperty";
/**
* Property identification String for the Cancel button's enabled state
*/
public static final String CANCEL_BUTTON_ENABLED_PROPERTY = "cancelButtonEnabledProperty";
private WizardPanelDescriptor currentPanel;
private HashMap panelHashmap;
private HashMap buttonTextHashmap;
private HashMap buttonIconHashmap;
private HashMap buttonEnabledHashmap;
private PropertyChangeSupport propertyChangeSupport;
/**
* Default constructor.
*/
public WizardModel() {
panelHashmap = new HashMap();
buttonTextHashmap = new HashMap();
buttonIconHashmap = new HashMap();
buttonEnabledHashmap = new HashMap();
propertyChangeSupport = new PropertyChangeSupport(this);
}
/**
* Returns the currently displayed WizardPanelDescriptor.
* @return The currently displayed WizardPanelDescriptor
*/
WizardPanelDescriptor getCurrentPanelDescriptor() {
return currentPanel;
}
/**
* Registers the WizardPanelDescriptor in the model using the Object-identifier specified.
* @param id Object-based identifier
* @param descriptor WizardPanelDescriptor that describes the panel
*/
void registerPanel(Object id, WizardPanelDescriptor descriptor) {
// Place a reference to it in a hashtable so we can access it later
// when it is about to be displayed.
panelHashmap.put(id, descriptor);
}
/**
* Sets the current panel to that identified by the Object passed in.
* @param id Object-based panel identifier
* @return boolean indicating success or failure
*/
boolean setCurrentPanel(Object id) {
// First, get the hashtable reference to the panel that should
// be displayed.
WizardPanelDescriptor nextPanel =
(WizardPanelDescriptor)panelHashmap.get(id);
// If we couldn't find the panel that should be displayed, return
// false.
if (nextPanel == null)
throw new WizardPanelNotFoundException();
WizardPanelDescriptor oldPanel = currentPanel;
currentPanel = nextPanel;
if (oldPanel != currentPanel)
firePropertyChange(CURRENT_PANEL_DESCRIPTOR_PROPERTY, oldPanel, currentPanel);
return true;
}
Object getBackButtonText() {
return buttonTextHashmap.get(BACK_BUTTON_TEXT_PROPERTY);
}
void setBackButtonText(Object newText) {
Object oldText = getBackButtonText();
if (!newText.equals(oldText)) {
buttonTextHashmap.put(BACK_BUTTON_TEXT_PROPERTY, newText);
firePropertyChange(BACK_BUTTON_TEXT_PROPERTY, oldText, newText);
}
}
Object getNextFinishButtonText() {
return buttonTextHashmap.get(NEXT_FINISH_BUTTON_TEXT_PROPERTY);
}
void setNextFinishButtonText(Object newText) {
Object oldText = getNextFinishButtonText();
if (!newText.equals(oldText)) {
buttonTextHashmap.put(NEXT_FINISH_BUTTON_TEXT_PROPERTY, newText);
firePropertyChange(NEXT_FINISH_BUTTON_TEXT_PROPERTY, oldText, newText);
}
}
Object getCancelButtonText() {
return buttonTextHashmap.get(CANCEL_BUTTON_TEXT_PROPERTY);
}
void setCancelButtonText(Object newText) {
Object oldText = getCancelButtonText();
if (!newText.equals(oldText)) {
buttonTextHashmap.put(CANCEL_BUTTON_TEXT_PROPERTY, newText);
firePropertyChange(CANCEL_BUTTON_TEXT_PROPERTY, oldText, newText);
}
}
Icon getBackButtonIcon() {
return (Icon)buttonIconHashmap.get(BACK_BUTTON_ICON_PROPERTY);
}
void setBackButtonIcon(Icon newIcon) {
Object oldIcon = getBackButtonIcon();
if (!newIcon.equals(oldIcon)) {
buttonIconHashmap.put(BACK_BUTTON_ICON_PROPERTY, newIcon);
firePropertyChange(BACK_BUTTON_ICON_PROPERTY, oldIcon, newIcon);
}
}
Icon getNextFinishButtonIcon() {
return (Icon)buttonIconHashmap.get(NEXT_FINISH_BUTTON_ICON_PROPERTY);
}
public void setNextFinishButtonIcon(Icon newIcon) {
Object oldIcon = getNextFinishButtonIcon();
if (!newIcon.equals(oldIcon)) {
buttonIconHashmap.put(NEXT_FINISH_BUTTON_ICON_PROPERTY, newIcon);
firePropertyChange(NEXT_FINISH_BUTTON_ICON_PROPERTY, oldIcon, newIcon);
}
}
Icon getCancelButtonIcon() {
return (Icon)buttonIconHashmap.get(CANCEL_BUTTON_ICON_PROPERTY);
}
void setCancelButtonIcon(Icon newIcon) {
Icon oldIcon = getCancelButtonIcon();
if (!newIcon.equals(oldIcon)) {
buttonIconHashmap.put(CANCEL_BUTTON_ICON_PROPERTY, newIcon);
firePropertyChange(CANCEL_BUTTON_ICON_PROPERTY, oldIcon, newIcon);
}
}
Boolean getBackButtonEnabled() {
return (Boolean)buttonEnabledHashmap.get(BACK_BUTTON_ENABLED_PROPERTY);
}
void setBackButtonEnabled(Boolean newValue) {
Boolean oldValue = getBackButtonEnabled();
if (newValue != oldValue) {
buttonEnabledHashmap.put(BACK_BUTTON_ENABLED_PROPERTY, newValue);
firePropertyChange(BACK_BUTTON_ENABLED_PROPERTY, oldValue, newValue);
}
}
Boolean getNextFinishButtonEnabled() {
return (Boolean)buttonEnabledHashmap.get(NEXT_FINISH_BUTTON_ENABLED_PROPERTY);
}
void setNextFinishButtonEnabled(Boolean newValue) {
Boolean oldValue = getNextFinishButtonEnabled();
if (newValue != oldValue) {
buttonEnabledHashmap.put(NEXT_FINISH_BUTTON_ENABLED_PROPERTY, newValue);
firePropertyChange(NEXT_FINISH_BUTTON_ENABLED_PROPERTY, oldValue, newValue);
}
}
Boolean getCancelButtonEnabled() {
return (Boolean)buttonEnabledHashmap.get(CANCEL_BUTTON_ENABLED_PROPERTY);
}
void setCancelButtonEnabled(Boolean newValue) {
Boolean oldValue = getCancelButtonEnabled();
if (newValue != oldValue) {
buttonEnabledHashmap.put(CANCEL_BUTTON_ENABLED_PROPERTY, newValue);
firePropertyChange(CANCEL_BUTTON_ENABLED_PROPERTY, oldValue, newValue);
}
}
public void addPropertyChangeListener(PropertyChangeListener p) {
propertyChangeSupport.addPropertyChangeListener(p);
}
public void removePropertyChangeListener(PropertyChangeListener p) {
propertyChangeSupport.removePropertyChangeListener(p);
}
protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
propertyChangeSupport.firePropertyChange(propertyName, oldValue, newValue);
}
}
| Java |
package com.salesforce.cliq;
import com.nexes.wizard.Wizard;
import com.nexes.wizard.WizardPanelDescriptor;
import com.salesforce.cliq.*;
import com.salesforce.cliq.cliconfig.CliConfig;
import com.salesforce.cliq.cliconfig.CliConfigDml;
import com.salesforce.cliq.cliconfig.CliConfigExport;
import com.salesforce.cliq.cliconfig.CliConfigFactory;
import com.salesforce.cliq.ui.EntityPanelDescriptor;
import com.salesforce.cliq.ui.LoginPanelDescriptor;
import com.salesforce.cliq.ui.OperationPanelDescriptor;
import com.salesforce.cliq.ui.QueryPanelDescriptor;
import com.salesforce.cliq.ui.ResultPanelDescriptor;
import com.salesforce.dataloader.config.*;
import java.io.*;
import java.net.*;
import java.util.MissingResourceException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.Properties;
/**
* DataLoaderCliq is the main class for Data Loader CLIq.
* It provides both a Text and Graphical UI for the CliConfig
* Classes. On execution of main, it will check for newer
* versions in the public SVN repository.
*
* @author Vijay Swamidass
*
*/
public class DataLoaderCliq {
public static final String VERSION_URL = "http://dataloadercliq.googlecode.com/svn/trunk/src/version.properties";
public static final String DOWNLOAD_URL = "http://code.google.com/p/dataloadercliq/";
public static boolean debugMode = false;
/* Used to read user input */
static BufferedReader rdr = new BufferedReader(
new java.io.InputStreamReader(System.in));
/**
* A shared instance of CliConfig used by the various
* Wizard panels
*/
static CliConfig theConfig;
/**
* Used by the Wizard to set the shared instance of CliConfig
*
* @param c An instance of CliConfig
*/
public static void setCliConfig(CliConfig c) {
theConfig = c;
}
/**
* Used by the Wizard to get the shared instance of CliConfig
*
* @param c An instance of CliConfig
*/
public static CliConfig getCliConfig() {
return theConfig;
}
public static boolean isDebugMode() {
return debugMode;
}
public static void log(String m) {
log(m,null);
}
public static void log(String m,Exception e) {
if (DataLoaderCliq.isDebugMode()) {
if (e != null) {
e.printStackTrace();
}
System.out.println("log: " + m);
}
}
/**
* Shows a text prompt, reads the user input, and returns the input.
*
* @param prompt String to show the user
* @return The user input
*/
static String getUserInput(String prompt) {
System.out.print(prompt);
try {
return rdr.readLine();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* Shows a simple text menu
*/
private static void displayMenu() {
// set up a simple menu system
Integer operationNumber = 1;
for (CliConfig.DataLoaderOperation operation : CliConfig.DataLoaderOperation.values()) {
System.out.println(operationNumber++ + ". " + operation.toString());
}
}
/**
* Runs the GUI using the Sun Wizard Class
*/
private static void runGui() {
Wizard wizard = new Wizard();
wizard.getDialog().setTitle("Data Loader CLIq");
WizardPanelDescriptor operationDescriptor = new OperationPanelDescriptor();
wizard.registerWizardPanel(OperationPanelDescriptor.IDENTIFIER, operationDescriptor);
WizardPanelDescriptor loginDescriptor = new LoginPanelDescriptor();
wizard.registerWizardPanel(LoginPanelDescriptor.IDENTIFIER, loginDescriptor);
WizardPanelDescriptor queryDescriptor = new QueryPanelDescriptor();
wizard.registerWizardPanel(QueryPanelDescriptor.IDENTIFIER, queryDescriptor);
WizardPanelDescriptor entityDescriptor = new EntityPanelDescriptor();
wizard.registerWizardPanel(EntityPanelDescriptor.IDENTIFIER, entityDescriptor);
WizardPanelDescriptor resultDescriptor = new ResultPanelDescriptor();
wizard.registerWizardPanel(ResultPanelDescriptor.IDENTIFIER, resultDescriptor);
wizard.setCurrentPanel(OperationPanelDescriptor.IDENTIFIER);
int ret = wizard.showModalDialog();
}
private static void showError(String message) {
System.out.println("=========================================================");
System.out.println("## " + message);
System.out.println("=========================================================");
}
private static void showStepSeparator(Integer stepNumber, String title) {
System.out.println();
System.out.println("#########################################################");
System.out.println("Step " + stepNumber);
System.out.println(title);
System.out.println("#########################################################");
}
/**
* Run the Text-based UI
*/
private static void runTextUi() {
String username;
String processName;
String password;
String dlHome;
showStepSeparator(1, "Choose Operation");
displayMenu();
Integer menuOption = Integer.valueOf(getUserInput("Operation number? "));
while (menuOption < 1 && menuOption > CliConfig.DataLoaderOperation.values().length) { //Get the count of options
System.out.println("Please enter a valid choice: ");
displayMenu();
}
System.out.println("Each process needs a unique indentifier. Use word characters only.");
processName = getUserInput("Enter the name of your process: ");
File dlHomeDir = new File(System.getProperty("user.dir"));
dlHome = dlHomeDir.getParent();
CliConfig.DataLoaderOperation operation = CliConfig.DataLoaderOperation.values()[menuOption-1];
System.out.println("Configuring for operation: " + operation.toString());
theConfig = CliConfigFactory.getCliConfig(operation, dlHome, processName);
showStepSeparator(2, "Verify Salesforce Login");
System.out.println("Using endpoint: " + theConfig.getConfigValue(Config.ENDPOINT));
try {
if (theConfig.getConfigValue(Config.USERNAME).length() > 0) {
System.out.println("Logging in to Salesforce...");
theConfig.doSalesforceLogin();
}
} catch (Exception e) {
showError("Error logging in to Salesforce with cliq.properties: " + e.getMessage());
}
while (!theConfig.isLoggedIn()) {
username = getUserInput("Enter your username: ");
password = getUserInput("Enter your password: ");
theConfig.setConfigValue(Config.USERNAME,username);
theConfig.setPassword(password);
try {
System.out.println("Logging in to Salesforce...");
theConfig.doSalesforceLogin();
} catch (Exception e) {
showError("Error logging in to Salesforce: " + e.getMessage());
}
}
if (theConfig instanceof CliConfigExport) {
String query;
showStepSeparator(3, "Configure Export");
while (!((CliConfigExport)theConfig).isQueryValid()) {
query = getUserInput("Enter your SOQL query: ");
try {
((CliConfigExport)theConfig).setQueryAndEntity(query);
} catch (Exception e) {
showError(e.getMessage());
}
}
} else {
String entity;
showStepSeparator(3, "Validate Salesforce Entity");
while (!theConfig.isEntityNameValid()) {
entity = getUserInput("Enter the Object name: ");
try {
theConfig.setEntityName(entity);
} catch (Exception e) {
showError("Invalid Object - Please try again.");
}
}
}
showStepSeparator(4, "Create Scripts");
System.out.println("Creating files...");
try {
theConfig.createCliConfig();
System.out.println("CLIq completed successfully!");
System.out.println("Your files are in: " + theConfig.SCRIPT_DIR);
} catch (Exception e) {
showError("Error creating configuration files: " + e.getMessage());
}
}
/**
* Checks if newer version is available and pauses for user response if so.
* If an argument is provided (any argument), run the Text UI, otherwise
* run the GUI.
*
* @param args Any single arg will launch the Text UI
*/
public static void main(String[] args) {
DataLoaderCliq dlc = new DataLoaderCliq();
System.out.println("You can download the latest version of CLIq at:");
System.out.println(DOWNLOAD_URL);
boolean textMode = false;
for (String param : args) {
if (param.contains("-d")) {
System.out.println("Enabling debug mode.");
debugMode = true;
} else if (param.contains("-t")) {
textMode = true;
}
}
if (textMode) {
runTextUi();
} else {
System.out.println("Loading GUI...");
runGui();
}
}
} | Java |
package com.salesforce.cliq.ui;
import net.miginfocom.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.net.*;
import javax.swing.*;
import javax.swing.border.*;
public class LoginPanel extends CliqWizardPanel {
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel userPanel;
private JTextArea resultMessage;
private javax.swing.JLabel welcomeTitle;
private javax.swing.JLabel usernameLabel;
private javax.swing.JTextField usernameField;
private javax.swing.JLabel passwordLabel;
private javax.swing.JPasswordField passwordField;
private JButton loginButton = new JButton();
private javax.swing.JLabel messageLabel = new javax.swing.JLabel();
public LoginPanel() {
super("Salesforce Login");
addContentPanel(getContentPanel());
}
public String getUsername() {
return usernameField.getText();
}
public String getPassword() {
return String.valueOf(passwordField.getPassword());
}
public void addLoginActionListener(ActionListener l) {
loginButton.addActionListener(l);
}
public void setMessage(String e) {
resultMessage.setText(e);
}
public void setUsername(String username) {
usernameField.setText(username);
}
public void setPassword(String password) {
passwordField.setText(password);
}
protected JPanel getContentPanel() {
userPanel = new JPanel();
welcomeTitle = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
passwordLabel = new javax.swing.JLabel();
passwordField = new JPasswordField(20);
usernameLabel = new javax.swing.JLabel();
usernameField = new JTextField(20);
messageLabel = new javax.swing.JLabel();
JPanel contentPanel1 = new JPanel();
contentPanel1.setLayout(new java.awt.BorderLayout());
welcomeTitle = new javax.swing.JLabel();
contentPanel1.add(welcomeTitle, java.awt.BorderLayout.NORTH);
jPanel1.setLayout(new MigLayout("wrap 1"));
/* User Panel */
userPanel.setLayout(new MigLayout("wrap 2,w 400"));
userPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),
"Login to Salesforce",
TitledBorder.DEFAULT_JUSTIFICATION,
TitledBorder.DEFAULT_POSITION,
new Font("Courier", Font.BOLD,14)
));
usernameLabel.setText("Username:");
userPanel.add(usernameLabel);
userPanel.add(usernameField);
passwordLabel.setText("Password:");
userPanel.add(passwordLabel);
userPanel.add(passwordField);
loginButton = new JButton();
loginButton.setText("Verify Username and Password");
userPanel.add(loginButton,"wrap,span 2");
jPanel1.add(userPanel);
/* Result Panel */
resultMessage = createResultMessage();
jPanel1.add(createResultPanel(resultMessage));
/* End */
contentPanel1.add(jPanel1, java.awt.BorderLayout.CENTER);
return contentPanel1;
}
} | Java |
package com.salesforce.cliq.ui;
import net.miginfocom.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.net.*;
import javax.swing.*;
import javax.swing.border.*;
public class ResultPanel extends CliqWizardPanel {
public static final String SHOW_FILES_ACTION_COMMAND = "ShowFilesActionCommand";
public static final String CREATE_FILES_ACTION_COMMAND = "CreateFilesActionCommand";
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel summaryPanel;
private javax.swing.JPanel resultPanel;
private javax.swing.JTextArea summaryField;
private JButton createFilesButton;
private JButton showFilesButton;
private javax.swing.JTextArea statusField;
public ResultPanel() {
super("Generate Files");
addContentPanel(getContentPanel());
}
public void addCreateFilesActionListener(ActionListener l) {
createFilesButton.addActionListener(l);
}
public void addShowFilesActionListener(ActionListener l) {
showFilesButton.addActionListener(l);
}
public void setEnabledShowFiles(boolean b) {
showFilesButton.setEnabled(b);
}
public void clearStatus() {
statusField.setText("");
}
public void addStatus(String s) {
statusField.append(s);
}
public void clearSummary() {
statusField.setText("");
}
public void addSummaryItem(String s) {
summaryField.append(s);
}
private JPanel getContentPanel() {
JPanel contentPanel1 = new JPanel();
summaryPanel = new JPanel();
resultPanel = new JPanel();
jPanel1 = new javax.swing.JPanel();
createFilesButton = new JButton();
showFilesButton = new JButton();
contentPanel1.setLayout(new java.awt.BorderLayout());
jPanel1.setLayout(new MigLayout("wrap 1"));
/* Summary */
summaryPanel.setLayout(new MigLayout("wrap 1,w 400"));
summaryPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),
"Summary",
TitledBorder.DEFAULT_JUSTIFICATION,
TitledBorder.DEFAULT_POSITION,
new Font("Courier", Font.BOLD,14)
));
summaryField = new JTextArea("",10,30);
summaryField.setLineWrap(true);
summaryField.setWrapStyleWord(true);
summaryField.setEditable(false);
JScrollPane summaryScrollPane = new JScrollPane(summaryField);
summaryScrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS & JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
summaryPanel.add(summaryScrollPane);
createFilesButton.setText("Create Data Loader CLI Files");
createFilesButton.setActionCommand(CREATE_FILES_ACTION_COMMAND);
summaryPanel.add(createFilesButton,"");
jPanel1.add(summaryPanel);
/* Results */
resultPanel.setLayout(new MigLayout("wrap 1,w 400"));
resultPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),
"Results",
TitledBorder.DEFAULT_JUSTIFICATION,
TitledBorder.DEFAULT_POSITION,
new Font("Courier", Font.BOLD,14)
));
statusField = new JTextArea("",6,30);
statusField.setLineWrap(true);
statusField.setWrapStyleWord(true);
statusField.setEditable(false);
JScrollPane messageScrollPane = new JScrollPane(statusField);
messageScrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS & JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
resultPanel.add(messageScrollPane);
/* Not supported by Java 1.5
showFilesButton.setText("Show Files");
showFilesButton.setActionCommand(SHOW_FILES_ACTION_COMMAND);
showFilesButton.setEnabled(false);
resultPanel.add(showFilesButton,"");
*/
jPanel1.add(resultPanel);
/* End */
contentPanel1.add(jPanel1, java.awt.BorderLayout.CENTER);
return contentPanel1;
}
} | Java |
package com.salesforce.cliq.ui;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import javax.swing.*;
import javax.swing.border.*;
import com.salesforce.cliq.cliconfig.CliConfig;
import net.miginfocom.swing.MigLayout;
public abstract class CliqWizardPanel extends JPanel implements ComponentListener {
private static final String LOGO_URL = "http://code.google.com/p/dataloadercliq/logo?logo_id=1258144218";
private static final String DEFAULT_TITLE = "Data Loader CLIq";
private static final String WELCOME_MESSAGE = "Welcome to CLIq";
private static String currentEndpoint;
private JLabel iconLabel;
private JSeparator separator;
private JLabel textLabel;
private JLabel versionLabel;
private JPanel titlePanel;
private JPanel contentContainer;
private JPanel contentPanel;
public void componentHidden(ComponentEvent e) {}
public void componentMoved(ComponentEvent e) {}
public void componentResized(ComponentEvent e) {}
public void componentShown(ComponentEvent e) {
doDisplayEndpoint();
}
private void doDisplayEndpoint() {
if (currentEndpoint == null) {
versionLabel.setText(WELCOME_MESSAGE);
} else {
versionLabel.setText(currentEndpoint);
}
}
public CliqWizardPanel() {
this(DEFAULT_TITLE);
}
public void setEndpoint(String e) {
currentEndpoint = e;
}
public CliqWizardPanel(String title) {
super();
addComponentListener(this);
titlePanel = new javax.swing.JPanel();
textLabel = new javax.swing.JLabel();
versionLabel = new javax.swing.JLabel();
iconLabel = new javax.swing.JLabel();
separator = new javax.swing.JSeparator();
setLayout(new java.awt.BorderLayout());
titlePanel.setLayout(new java.awt.BorderLayout());
titlePanel.setBackground(Color.white);
try {
URL logoUrl = new URL(LOGO_URL);
Icon icon = new ImageIcon(logoUrl);
textLabel.setIcon(icon);
} catch (Exception e) {
//do something later
}
textLabel.setBackground(Color.white);
textLabel.setIconTextGap(100);
textLabel.setFont(new Font("MS Sans Serif", Font.BOLD, 18));
textLabel.setText(title);
textLabel.setBorder(new EmptyBorder(new Insets(10, 10, 10, 10)));
textLabel.setOpaque(true);
versionLabel.setBackground(Color.gray);
versionLabel.setIconTextGap(100);
versionLabel.setFont(new Font("MS Sans Serif", Font.PLAIN, 10));
doDisplayEndpoint();
versionLabel.setForeground(Color.white);
versionLabel.setBorder(new EmptyBorder(new Insets(3, 3, 3, 3)));
versionLabel.setOpaque(true);
titlePanel.add(textLabel,BorderLayout.CENTER);
titlePanel.add(versionLabel,BorderLayout.SOUTH);
titlePanel.add(iconLabel, BorderLayout.EAST);
//versionLabel.add(separator, BorderLayout.SOUTH);
contentContainer = new JPanel();
contentContainer.setBorder(new EmptyBorder(new Insets(10, 10, 10, 10)));
add(contentContainer, BorderLayout.WEST);
add(titlePanel, BorderLayout.NORTH);
}
public void addContentPanel(JPanel newContentPanel) {
removeContentPanel();
contentPanel = newContentPanel;
contentContainer.add(contentPanel, BorderLayout.NORTH);
}
public void removeContentPanel() {
if (contentPanel != null)
contentContainer.remove(contentPanel);
}
public JPanel createResultPanel(JTextArea message) {
JPanel resultPanel = new JPanel();
resultPanel.setLayout(new MigLayout("wrap 2,w 400"));
resultPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),
"Result",
TitledBorder.DEFAULT_JUSTIFICATION,
TitledBorder.DEFAULT_POSITION,
new Font("Courier", Font.BOLD,14)
));
JScrollPane messageScrollPane = new JScrollPane(message);
messageScrollPane.setPreferredSize(new Dimension(500, 120));
messageScrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS & JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
resultPanel.add(messageScrollPane);
return resultPanel;
}
public JTextArea createResultMessage() {
JTextArea resultMessage = new JTextArea();
resultMessage.setFont(new Font("Arial", Font.ITALIC,12));
resultMessage.setBorder(new EmptyBorder(new Insets(10, 10, 10, 10)));
resultMessage.setLineWrap(true);
return resultMessage;
}
}
| Java |
package com.salesforce.cliq.ui;
import java.awt.*;
import java.awt.event.ActionListener;
import java.net.*;
import javax.swing.*;
import javax.swing.border.*;
import net.miginfocom.swing.MigLayout;
public class EntityPanel extends CliqWizardPanel {
private javax.swing.JTextField entityField = new JTextField(40);
private boolean showExternalIdTextInput;
private javax.swing.JTextField externalIdField = new JTextField(40);
//private javax.swing.JLabel resultMessage = new javax.swing.JLabel();
private JTextArea resultMessage = new JTextArea();
private javax.swing.JLabel entityLabel = new javax.swing.JLabel();
private javax.swing.JLabel externalIdLabel = new javax.swing.JLabel();
private JButton verifyButton = new JButton();
private String operationName;
public EntityPanel() {
super("Salesforce Entity (Object)");
verifyButton = new JButton();
addContentPanel(getContentPanel());
}
public String getEntityName() {
return entityField.getText();
}
public String getExternalIdField() {
return externalIdField.getText();
}
public void setOperationName(String name) {
operationName = name;
addContentPanel(getContentPanel());
}
public String getOperationName() {
return operationName;
}
public void addVerifyActionListener(ActionListener l) {
verifyButton.addActionListener(l);
}
public void setStatus (String s) {
resultMessage.setText(s);
}
public void setShowExternalIdTextInput(boolean shouldShowExternalIdTextInput) {
showExternalIdTextInput = shouldShowExternalIdTextInput;
//Refresh the content to update the display of external id field
addContentPanel(getContentPanel());
}
protected JPanel getContentPanel() {
JPanel contentPanel1 = new JPanel();
JPanel jPanel1 = new javax.swing.JPanel();
JPanel entityPanel = new JPanel();
contentPanel1.setLayout(new java.awt.BorderLayout());
jPanel1.setLayout(new MigLayout("wrap 1"));
/* User Panel */
entityPanel.setLayout(new MigLayout("wrap 2,w 400"));
entityPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),
"Salesforce Entity (Object) to " + getOperationName(),
TitledBorder.DEFAULT_JUSTIFICATION,
TitledBorder.DEFAULT_POSITION,
new Font("Courier", Font.BOLD,14)
));
entityLabel.setText("Entity Name:");
entityPanel.add(entityLabel);
entityPanel.add(entityField);
if (showExternalIdTextInput) {
externalIdLabel.setText("External Id (optional):");
entityPanel.add(externalIdLabel);
entityPanel.add(externalIdField);
}
verifyButton.setText("Verify");
entityPanel.add(verifyButton);
jPanel1.add(entityPanel);
/* Result Panel */
resultMessage = createResultMessage();
jPanel1.add(createResultPanel(resultMessage));
/* End */
contentPanel1.add(jPanel1, java.awt.BorderLayout.CENTER);
return contentPanel1;
}
} | Java |
package com.salesforce.cliq.ui;
import java.awt.*;
import java.util.*;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.DocumentListener;
import com.salesforce.cliq.cliconfig.*;
import net.miginfocom.swing.MigLayout;
public class OperationPanel extends CliqWizardPanel {
private javax.swing.ButtonGroup operationGroup;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel operationPanel;
private javax.swing.JPanel processPanel;
private javax.swing.JTextField processField;
public OperationPanel() {
super("Select Operation");
addContentPanel(getContentPanel());
}
public CliConfig.DataLoaderOperation getRadioButtonSelected() {
if (operationGroup.getSelection() != null) {
return Enum.valueOf(CliConfig.DataLoaderOperation.class,operationGroup.getSelection().getActionCommand());
} else {
return null;
}
}
public String getProcess() {
return processField.getText();
}
public boolean isProcessValid() {
//Word Chars, > 0 length, etc.
return (processField.getText().length() > 0) ? true : false;
}
public Boolean isRadioButtonSelected() {
return getRadioButtonSelected() != null ? true : false;
}
public void addDocumentListener(DocumentListener l) {
processField.getDocument().addDocumentListener(l);
}
public void addRadioActionListener(ActionListener l) {
Enumeration e = operationGroup.getElements();
while (e.hasMoreElements()) {
JRadioButton button = (JRadioButton)e.nextElement();
button.addActionListener(l);
}
}
private JPanel getContentPanel() {
JPanel contentPanel1 = new JPanel();
operationGroup = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
operationPanel = new javax.swing.JPanel();
processPanel = new javax.swing.JPanel();
processField = new JTextField(20);
contentPanel1.setLayout(new java.awt.BorderLayout());
jPanel1.setLayout(new MigLayout("wrap 1"));
/* Operation Choice */
operationPanel.setLayout(new MigLayout("wrap 1,w 300"));
operationPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),
"Select Operation",
TitledBorder.DEFAULT_JUSTIFICATION,
TitledBorder.DEFAULT_POSITION,
new Font("Courier", Font.BOLD,14)
));
jPanel1.add(operationPanel);
//Add all of the operations to the panel
for (CliConfig.DataLoaderOperation op : CliConfig.DataLoaderOperation.values()) {
JRadioButton radioButton = new javax.swing.JRadioButton();
radioButton.setActionCommand(op.toString());
radioButton.setText(op.getDisplayName());
operationGroup.add(radioButton);
operationPanel.add(radioButton);
}
/* Process Name */
processPanel.setLayout(new MigLayout("wrap 1,w 300"));
processPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),
"Enter Process Name (Letters Only)",
TitledBorder.DEFAULT_JUSTIFICATION,
TitledBorder.DEFAULT_POSITION,
new Font("Courier", Font.BOLD,14)
));
processPanel.add(processField);
jPanel1.add(processPanel);
contentPanel1.add(jPanel1, java.awt.BorderLayout.CENTER);
return contentPanel1;
}
}
| Java |
package com.salesforce.cliq.ui;
import net.miginfocom.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
public class QueryPanel extends CliqWizardPanel {
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel welcomeTitle;
private javax.swing.JPanel queryPanel;
private javax.swing.JTextArea queryField;
private javax.swing.JCheckBox includeDeletedRecords;
private JTextArea resultMessage;
private javax.swing.JTextArea messageField;
private JButton loginButton;
public QueryPanel() {
super("Validate SOQL Query");
addContentPanel(getContentPanel());
}
public String getQuery() {
return queryField.getText();
}
public boolean isIncludeDeletedRecordsChecked() {
return includeDeletedRecords.isSelected();
}
public void setMessage(String e) {
resultMessage.setText(e);
}
public void addVerifyActionListener(ActionListener l) {
loginButton.addActionListener(l);
}
public void addDocumentListener(DocumentListener l) {
queryField.getDocument().addDocumentListener(l);
}
private JPanel getContentPanel() {
JPanel contentPanel1 = new JPanel();
loginButton = new JButton();
welcomeTitle = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
queryPanel = new javax.swing.JPanel();
queryField = new JTextArea(5,50); //change to text area
includeDeletedRecords = new javax.swing.JCheckBox();
contentPanel1.setLayout(new java.awt.BorderLayout());
contentPanel1.add(welcomeTitle, java.awt.BorderLayout.NORTH);
jPanel1.setLayout(new MigLayout("wrap 1"));
/* Query Panel */
queryPanel.setLayout(new MigLayout("wrap 1,w 400"));
queryPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),
"Query",
TitledBorder.DEFAULT_JUSTIFICATION,
TitledBorder.DEFAULT_POSITION,
new Font("Courier", Font.BOLD,14)
));
queryPanel.add(queryField);
queryField.setFont(new Font("Courier", Font.PLAIN, 12));
queryField.setLineWrap(true);
queryField.setWrapStyleWord(true);
JScrollPane queryScrollPane = new JScrollPane(queryField);
queryScrollPane.setPreferredSize(new Dimension(500, 120));
queryScrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS & JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
queryPanel.add(queryScrollPane);
loginButton.setText("Verify");
queryPanel.add(loginButton,"span 2,align 50% 50%");
jPanel1.add(queryPanel);
/* Result Panel */
resultMessage = createResultMessage();
jPanel1.add(createResultPanel(resultMessage));
/* End */
contentPanel1.add(jPanel1, java.awt.BorderLayout.CENTER);
return contentPanel1;
}
} | Java |
package com.salesforce.cliq.ui;
import com.nexes.wizard.*;
import com.salesforce.cliq.*;
import com.salesforce.cliq.cliconfig.CliConfigExport;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.event.*;
public class QueryPanelDescriptor extends WizardPanelDescriptor
implements ActionListener,DocumentListener {
public static final String IDENTIFIER = "QUERY_PANEL";
private CliConfigExport myConfig;
QueryPanel queryPanel;
public QueryPanelDescriptor() {
queryPanel = new QueryPanel();
queryPanel.addVerifyActionListener(this);
queryPanel.addDocumentListener(this);
setPanelDescriptorIdentifier(IDENTIFIER);
setPanelComponent(queryPanel);
}
public void insertUpdate(DocumentEvent e) {
displayEditInfo(e);
}
public void removeUpdate(DocumentEvent e) {
displayEditInfo(e);
}
public void changedUpdate(DocumentEvent e) {
displayEditInfo(e);
}
private void displayEditInfo(DocumentEvent e) {
}
public void actionPerformed(ActionEvent e) {
try {
myConfig.setQueryAndEntity(queryPanel.getQuery());
queryPanel.setMessage("Query is valid.");
} catch (Exception ex) {
queryPanel.setMessage(ex.getMessage());
}
setNextButtonAccordingToQuery();
}
public void aboutToDisplayPanel() {
myConfig = (CliConfigExport)DataLoaderCliq.getCliConfig();
setNextButtonAccordingToQuery();
}
public Object getNextPanelDescriptor() {
return ResultPanelDescriptor.IDENTIFIER;
}
public Object getBackPanelDescriptor() {
return LoginPanelDescriptor.IDENTIFIER;
}
private void setNextButtonAccordingToQuery() {
if (myConfig.isQueryValid())
getWizard().setNextFinishButtonEnabled(true);
else
getWizard().setNextFinishButtonEnabled(false);
}
}
| Java |
package com.salesforce.cliq.ui;
import com.salesforce.cliq.*;
import com.salesforce.cliq.cliconfig.CliConfig;
import com.salesforce.cliq.cliconfig.CliConfigExport;
import com.salesforce.dataloader.config.Config;
import com.nexes.wizard.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginPanelDescriptor extends WizardPanelDescriptor implements ActionListener {
public static final String IDENTIFIER = "LOGIN_PANEL";
LoginPanel loginPanel;
private CliConfig myConfig;
public LoginPanelDescriptor() {
loginPanel = new LoginPanel();
loginPanel.addLoginActionListener(this);
setPanelDescriptorIdentifier(IDENTIFIER);
setPanelComponent(loginPanel);
}
public void actionPerformed(ActionEvent e) {
myConfig.setConfigValue(Config.USERNAME,loginPanel.getUsername());
myConfig.setPassword(loginPanel.getPassword());
try {
loginPanel.setMessage("Logging in...");
myConfig.doSalesforceLogin();
loginPanel.setMessage("Login Successful.");
} catch (Exception ex) {
DataLoaderCliq.log("Exception during login: " + ex.getMessage(), ex);
loginPanel.setMessage(ex.getMessage());
}
loginPanel.setEndpoint(myConfig.getConfigValue(Config.ENDPOINT));
setNextButtonAccordingToLogin();
}
public void aboutToDisplayPanel() {
myConfig = DataLoaderCliq.getCliConfig();
loginPanel.setUsername(myConfig.getConfigValue(Config.USERNAME));
loginPanel.setPassword(myConfig.getPlainPassword());
setNextButtonAccordingToLogin();
}
public void aboutToHidePanel() {
}
public Object getNextPanelDescriptor() {
if (myConfig instanceof CliConfigExport) {
return QueryPanelDescriptor.IDENTIFIER;
} else {
return EntityPanelDescriptor.IDENTIFIER;
}
}
public Object getBackPanelDescriptor() {
return OperationPanelDescriptor.IDENTIFIER;
}
private void setNextButtonAccordingToLogin() {
if (myConfig.isLoggedIn())
getWizard().setNextFinishButtonEnabled(true);
else
getWizard().setNextFinishButtonEnabled(false);
}
}
| Java |
package com.salesforce.cliq.ui;
import com.salesforce.cliq.*;
import com.salesforce.cliq.cliconfig.CliConfig;
import com.salesforce.cliq.cliconfig.CliConfigExport;
import com.salesforce.dataloader.config.Config;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import com.nexes.wizard.*;
public class ResultPanelDescriptor extends WizardPanelDescriptor implements ActionListener {
public static final String IDENTIFIER = "RESULT_PANEL";
private CliConfig myConfig;
ResultPanel resultPanel;
private boolean isSuccess = false;
public ResultPanelDescriptor() {
resultPanel = new ResultPanel();
resultPanel.addCreateFilesActionListener(this);
//resultPanel.addShowFilesActionListener(this);
setPanelDescriptorIdentifier(IDENTIFIER);
setPanelComponent(resultPanel);
}
public void actionPerformed(ActionEvent e) {
//Ignoring Show files for now since it is not widely supported
if (e.getActionCommand().equals(ResultPanel.SHOW_FILES_ACTION_COMMAND)) {
Desktop dt = Desktop.getDesktop();
try {
dt.open(CliConfig.SCRIPT_DIR);
} catch (Exception ex) {
System.out.println("Unable to display directory.");
}
} else if (e.getActionCommand().equals(ResultPanel.CREATE_FILES_ACTION_COMMAND)) {
doCreateCliConfig();
}
}
private void doCreateCliConfig() {
resultPanel.clearStatus();
try {
myConfig.createCliConfig();
resultPanel.addStatus("Files created successfully!" + "\n\n");
resultPanel.addStatus("Your files are in: \n" + CliConfig.SCRIPT_DIR);
isSuccess = true;
//resultPanel.setEnabledShowFiles(true);
} catch (Exception e) {
resultPanel.addStatus(e.getMessage());
isSuccess = false;
//resultPanel.setEnabledShowFiles(false);
}
setNextButtonAccordingToResult();
}
public void aboutToDisplayPanel() {
myConfig = DataLoaderCliq.getCliConfig();
resultPanel.clearSummary();
resultPanel.addSummaryItem("Directory: " + CliConfig.SCRIPT_DIR + "\n\n");
resultPanel.addSummaryItem("Entity (Object): " + myConfig.getConfigValue(Config.ENTITY) + "\n\n");
resultPanel.addSummaryItem("Username: " + myConfig.getConfigValue(Config.USERNAME) + "\n\n");
resultPanel.addSummaryItem("Operation: " + myConfig.getConfigValue(Config.OPERATION) + "\n\n");
setNextButtonAccordingToResult();
}
public void aboutToHidePanel() {
}
public Object getNextPanelDescriptor() {
return FINISH;
}
public Object getBackPanelDescriptor() {
if (myConfig instanceof CliConfigExport) {
return QueryPanelDescriptor.IDENTIFIER;
} else {
return EntityPanelDescriptor.IDENTIFIER;
}
}
private void setNextButtonAccordingToResult() {
if (isSuccess) {
getWizard().setNextFinishButtonEnabled(true);
} else {
getWizard().setNextFinishButtonEnabled(false);
}
}
}
| Java |
package com.salesforce.cliq.ui;
import com.salesforce.cliq.*;
import com.salesforce.cliq.cliconfig.CliConfig;
import com.salesforce.cliq.cliconfig.CliConfigDml;
import com.salesforce.cliq.cliconfig.CliConfigExport;
import com.salesforce.cliq.cliconfig.CliConfigFactory;
import com.salesforce.dataloader.config.Config;
import com.nexes.wizard.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.event.*;
public class OperationPanelDescriptor extends WizardPanelDescriptor
implements ActionListener,DocumentListener {
public static final String IDENTIFIER = "OPERATION_PANEL";
OperationPanel operationPanel;
private CliConfig myConfig;
public OperationPanelDescriptor() {
operationPanel = new OperationPanel();
operationPanel.addRadioActionListener(this);
operationPanel.addDocumentListener(this);
setPanelDescriptorIdentifier(IDENTIFIER);
setPanelComponent(operationPanel);
}
public void insertUpdate(DocumentEvent e) {
setNextButtonAccordingToRadio();
}
public void removeUpdate(DocumentEvent e) {
setNextButtonAccordingToRadio();
}
public void changedUpdate(DocumentEvent e) {
setNextButtonAccordingToRadio();
}
public void actionPerformed(ActionEvent e) {
setNextButtonAccordingToRadio();
}
public void aboutToDisplayPanel() {
setNextButtonAccordingToRadio();
if (myConfig == null) {
myConfig = DataLoaderCliq.getCliConfig();
}
}
public void aboutToHidePanel() {
String dlHome;
File dlHomeDir = new File(System.getProperty("user.dir"));
dlHome = dlHomeDir.getParent();
myConfig = CliConfigFactory.getCliConfig(
operationPanel.getRadioButtonSelected(),
dlHome,
operationPanel.getProcess());
DataLoaderCliq.setCliConfig(myConfig);
operationPanel.setEndpoint(myConfig.getConfigValue(Config.ENDPOINT));
}
public Object getNextPanelDescriptor() {
return LoginPanelDescriptor.IDENTIFIER;
}
public Object getBackPanelDescriptor() {
return null;
}
private void setNextButtonAccordingToRadio() {
if (operationPanel.isRadioButtonSelected() && operationPanel.isProcessValid())
getWizard().setNextFinishButtonEnabled(true);
else
getWizard().setNextFinishButtonEnabled(false);
}
}
| Java |
package com.salesforce.cliq.ui;
import com.salesforce.cliq.*;
import com.salesforce.cliq.cliconfig.CliConfigDml;
import com.salesforce.dataloader.config.Config;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import com.nexes.wizard.*;
public class EntityPanelDescriptor extends WizardPanelDescriptor implements ActionListener {
public static final String IDENTIFIER = "ENTITY_PANEL";
private CliConfigDml myConfig;
EntityPanel entityPanel;
public EntityPanelDescriptor() {
entityPanel = new EntityPanel();
entityPanel.addVerifyActionListener(this);
setPanelDescriptorIdentifier(IDENTIFIER);
setPanelComponent(entityPanel);
}
public void actionPerformed(ActionEvent e) {
try {
myConfig.setEntityName(entityPanel.getEntityName());
String externalId = entityPanel.getExternalIdField();
if (externalId != null && externalId.length() > 0) {
myConfig.setExternalIdField(entityPanel.getEntityName(),entityPanel.getExternalIdField());
}
entityPanel.setStatus("Configuration is valid");
} catch (Exception ex) {
entityPanel.setStatus(ex.getMessage());
}
setNextButtonAccordingToQuery();
}
public void aboutToDisplayPanel() {
myConfig = (CliConfigDml)DataLoaderCliq.getCliConfig();
entityPanel.setShowExternalIdTextInput(myConfig.isExternalIdOperation());
entityPanel.setOperationName(myConfig.getConfigValue(Config.OPERATION));
setNextButtonAccordingToQuery();
}
public Object getNextPanelDescriptor() {
return ResultPanelDescriptor.IDENTIFIER;
}
public Object getBackPanelDescriptor() {
return LoginPanelDescriptor.IDENTIFIER;
}
//TODO Recheck the external id field and refresh if the user hit the back button
private void setNextButtonAccordingToQuery() {
if (myConfig.isEntityNameValid()) {
if (myConfig.getDmlOperation() == CliConfigDml.DmlOperation.UPSERT) {
if (entityPanel.getExternalIdField().length() > 0) { //a value was entered
if (myConfig.isExternalIdValid()) { //is it valid?
getWizard().setNextFinishButtonEnabled(true);
} else {
getWizard().setNextFinishButtonEnabled(false);
}
} else {
getWizard().setNextFinishButtonEnabled(true); //external id not provided
}
} else {
getWizard().setNextFinishButtonEnabled(true);
}
} else {
getWizard().setNextFinishButtonEnabled(false);
}
}
}
| Java |
package com.salesforce.cliq.cliconfig;
import java.io.*;
import java.util.*;
import java.security.*;
import com.sforce.soap.partner.*;
import com.sforce.soap.partner.fault.*;
import com.sforce.ws.ConnectorConfig;
import com.sforce.ws.ConnectionException;
import com.salesforce.cliq.DataLoaderCliq;
import com.salesforce.dataloader.client.ClientBase;
import com.salesforce.dataloader.config.*;
import com.salesforce.dataloader.controller.*;
import com.salesforce.dataloader.security.*;
/**
* Abstract class for all CLI configurations.
*
* @author vswamidass
*
*/
public abstract class CliConfig {
public static File HOME_DIR; // The Data Loader Directory
public static File SCRIPT_DIR; // processname directory
public static File WRITE_DIR; // processname/write directory
public static File READ_DIR; // processname/read directory
public static File LOG_DIR; // processname/log directory
public static File CONFIG_DIR; // processname/config directory
public static File OUTPUT_DIR; // location of CLIq output files/scripts
public static String INSTALL_DIR = "/cliq/"; //The cliq home directory
public static String WINDOWS_JAVA_DIR = "Java"; //for windows, the location of the JRE in the DL Directory
/**
* This is the data loader process-conf.xml setting
*/
public static String endpoint;
public static final List<String> allowedCliqProperties = Arrays.asList(
Config.USERNAME,
Config.PASSWORD,
Config.ENDPOINT,
Config.PROXY_HOST,
Config.PROXY_PORT,
Config.PROXY_NTLM_DOMAIN,
Config.PROXY_USERNAME,
Config.PROXY_PASSWORD
);
/*
* Defines the type of operation
*/
public enum DataLoaderOperation {
EXTRACT("Export"),
EXTRACT_ALL("Export All (Include Deleted)"),
INSERT,
UPDATE,
UPSERT,
DELETE,
HARD_DELETE("Hard Delete");
private String displayName;
private DataLoaderOperation() {
String enumName = this.toString().toLowerCase();
displayName = enumName.substring(0,1).toUpperCase() + enumName.substring(1);
}
private DataLoaderOperation(String name) {
displayName = name;
}
public String getDisplayName() {
return displayName;
}
}
/*
* This should be implemented by subclass enums
*/
interface Operation {
public DataLoaderOperation toDataLoaderOperation();
}
public DataLoaderOperation operation;
public static String PROCESS_NAME; // The user specified Process Name
public static String PROCESS_DIR = "cliq_process"; // The user specified Process Name
/* The system newline character used to create the CLI files */
public static final String NEWLINE = System.getProperty("line.separator");
/**
* The unencrypted password, stored temporarily only,
* so we can login to Salesforce
*/
private String password;
/**
* The unencrypted password, stored temporarily only,
* so we can login to Salesforce
*/
private String proxyPassword;
/**
* Map of process-conf.xml property to value
*/
protected Map<String,String> configMap = new TreeMap<String,String>();
/**
* Salesfore API
*/
//protected SoapBindingStub binding = null;
protected ConnectorConfig config = new ConnectorConfig();
protected PartnerConnection connection;
/** Main **/
/**
* Constructor
*
* @param dir The home directory for Data Loader
* @param name The process name used to name the files
* and identify the process in process-conf.xml.
*/
public CliConfig (DataLoaderOperation op, String dir, String name) {
this(op,dir,dir + "/" + PROCESS_DIR,name);
}
/**
* Constructor
*
* @param homeDir The home directory for Data Loader
* @param outputDir The output directory for CLIq files
* @param name The process name used to name the files
* and identify the process in process-conf.xml.
*/
public CliConfig (DataLoaderOperation op, String homeDir, String outputDir, String name) {
operation = op;
HOME_DIR = new File(homeDir);
/* Set a default Output Directory */
OUTPUT_DIR = new File(outputDir);
/* The Directory Names need to be Windows Compatible */
PROCESS_NAME = name.replaceAll("[\\W|\\d]+","_");
SCRIPT_DIR = new File(OUTPUT_DIR.getAbsolutePath() + "/" + PROCESS_NAME);
WRITE_DIR = new File(SCRIPT_DIR.getAbsolutePath() + "/write");
READ_DIR = new File(SCRIPT_DIR.getAbsolutePath() + "/read");
LOG_DIR = new File(SCRIPT_DIR.getAbsolutePath() + "/log");
CONFIG_DIR = new File(SCRIPT_DIR.getAbsolutePath() + "/config");
try {
connection = Connector.newConnection(config);
} catch (Exception e) {
//this is expected, but we are trying a hack to get the endpoint and version from Dataloader.jar
}
String defaultEndpoint = config.getAuthEndpoint();
String fixedUpEndpoint = "https://www.salesforce.com/" + defaultEndpoint.substring(defaultEndpoint.indexOf("services"));
setConfigValue(Config.ENDPOINT,fixedUpEndpoint);
//On Windows, we pass in the value of the java directory location
String javaDirProperty = System.getProperty("java.dir");
if (javaDirProperty != null) {
WINDOWS_JAVA_DIR = javaDirProperty;
}
setConfigDefaults();
}
/**
* Sets default values for process-conf.xml
*/
protected void setConfigDefaults() {
setConfigValue(Config.ENDPOINT,endpoint);
setConfigValue(Config.READ_UTF8,"true");
setConfigValue(Config.WRITE_UTF8,"true");
setConfigValue(Config.ENABLE_EXTRACT_STATUS_OUTPUT,"true");
setConfigValue(Config.ENABLE_LAST_RUN_OUTPUT,"true");
setConfigValue(Config.LAST_RUN_OUTPUT_DIR,LOG_DIR.getAbsolutePath());
setConfigValue(Config.OUTPUT_STATUS_DIR,LOG_DIR.getAbsolutePath());
setConfigValue(Config.BULK_API_CHECK_STATUS_INTERVAL,"5000");
setConfigValue(Config.BULK_API_SERIAL_MODE,"5000");
setConfigValue(Config.DEBUG_MESSAGES,"false");
setConfigValue(Config.ENABLE_RETRIES,"true");
setConfigValue(Config.EXTRACT_REQUEST_SIZE,"500");
setConfigValue(Config.INSERT_NULLS,"false");
setConfigValue(Config.LOAD_BATCH_SIZE,"100");
setConfigValue(Config.MAX_RETRIES,"3");
setConfigValue(Config.MIN_RETRY_SLEEP_SECS,"2");
setConfigValue(Config.NO_COMPRESSION,"false");
setConfigValue(Config.TIMEOUT_SECS,"60");
setConfigValue(Config.BULK_API_ENABLED,"false");
setConfigValue(Config.OPERATION,operation.toString().toLowerCase());
/* Load the settings from the properties file */
try {
Properties cliqProperties = new Properties();
cliqProperties.load(new FileInputStream("cliq.properties"));
for (String property : allowedCliqProperties) {
String propertyValue = cliqProperties.getProperty(property);
if (propertyValue != null) {
if (property == Config.PASSWORD) { //Password must be encrypted
setPassword(propertyValue);
} else {
setConfigValue(property, propertyValue);
}
}
}
} catch (IOException e) {
System.out.println("WARNING: unable to read cliq.properties.");
}
}
/**
* Sets a key/value pair for process-conf.xml
* The list of constants are in com.salesforce.dataloader.config.Config
*
* @param key The process-conf.xml key
* @param value The process-conf.xml value
*/
public void setConfigValue(String key, String value) {
if (key == Config.ENDPOINT) {
if (value != null) {
configMap.put(key,value);
endpoint = value;
}
} else if (key == Config.PROXY_PASSWORD) {
proxyPassword = value; //save the unecrypted value
configMap.put(key,encryptPassword(value)); //save encrypted pass to config
} else {
configMap.put(key,value);
}
}
public String getConfigValue(String key) {
return configMap.get(key);
}
/**
* Checks if the user has logged in to Salesforce.com
*
* @return true if the loginResult is not null
* false if the loginResult is null (not logged in)
*/
public boolean isLoggedIn() {
DataLoaderCliq.log("Session Id: " + config.getSessionId());
return (config.getSessionId() != null);
}
/**
* Gets the Unique Process Name for this instance of CLIq
*
* @return String ProcessName
*/
public String getProcess() {
return PROCESS_NAME;
}
/**
* Sets the entity (Salesforce object)
* Queries Salesforce to verify that it is valid and to get
* the right case
*
* @param name The Entity (Object) name
* @throws Exception Indicates a failure to verify the entity
*/
public void setEntityName(String name) throws Exception {
DescribeSObjectResult describeSObjectResult;
setConfigValue(Config.ENTITY,null);
try {
describeSObjectResult = connection.describeSObject(name);
} catch (ApiFault ex) {
throw new Exception(ex.getExceptionMessage());
}
if (describeSObjectResult != null) {
setConfigValue(Config.ENTITY,describeSObjectResult.getName());
}
}
public boolean isEntityNameValid() {
return getConfigValue(Config.ENTITY) != null;
}
public boolean isFieldExternalId(String entity,String field) throws Exception {
DescribeSObjectResult describeSObjectResult;
try {
describeSObjectResult = connection.describeSObject(entity);
for (Field f : describeSObjectResult.getFields()) {
if (f.getName().equals(field) && f.isExternalId()) {
return true;
}
}
return false; //we didn't find the external id
} catch (Exception ex) {
return false;
}
}
protected void setDataLoaderOperation(DataLoaderOperation op) {
operation = op;
}
protected DataLoaderOperation getDataLoaderOperation() {
return operation;
}
/**
* encryptPassword calls the EncryptionUtil Class
* from the DataLoader.jar library.
*
* @param p plain-text password
* @return CLI compatible encrypted password string
*/
private String encryptPassword(String p) {
EncryptionUtil eu = new EncryptionUtil();
try {
return eu.encryptString(p);
} catch (GeneralSecurityException e) {
return null;
}
}
/**
* Set the process-conf.xml password to the encrypted value.
* Saves the plain-text string for logging into salesforce.
*
* @param p The plain-text password.
*/
public void setPassword(String p) {
password = p; //save unencrypted pw for login
setConfigValue(Config.PASSWORD,encryptPassword(p));
}
public String getPlainPassword() {
return password;
}
public String getPlainProxyPassword() {
return proxyPassword;
}
/**
* Main method to create directories and files for CLI configuation
*/
public void createCliConfig() throws Exception {
/*
* These methods may be overridden by subclasses to
* add new directories or files.
*/
createDirectories();
createFiles();
}
/**
* Creates the Process directory and all subdirectories.
*
* @throws Exception If the Script Directory (Process Name) exists
*/
public void createDirectories() throws Exception {
if (SCRIPT_DIR.isDirectory()) {
throw new Exception("Directory already exists. Please delete first.");
}
OUTPUT_DIR.mkdirs();
SCRIPT_DIR.mkdir();
WRITE_DIR.mkdir();
READ_DIR.mkdir();
LOG_DIR.mkdir();
CONFIG_DIR.mkdir();
}
/**
* Creates all configuration and script files for running the CLI Data Loader.
*
* @throws Exception
*/
public void createFiles() throws Exception {
createProcessXml();
createLogXml();
createConfigProperties();
createBatScript();
createShScript();
}
public void createProcessXml() throws Exception {
File processXml = new File(CONFIG_DIR,"process-conf.xml");
processXml.createNewFile();
FileWriter fw = new FileWriter(processXml);
fw.write("<!DOCTYPE beans PUBLIC \"-//SPRING//DTD BEAN//EN\" \"http://www.springframework.org/dtd/spring-beans.dtd\">" + NEWLINE);
fw.write("<beans>" + NEWLINE);
fw.write("\t<bean id=\"" + PROCESS_NAME + "\" class=\"com.salesforce.dataloader.process.ProcessRunner\" singleton=\"false\">" + NEWLINE);
fw.write("\t\t<description>Created by Dataloader Cliq.</description>" + NEWLINE);
fw.write("\t\t<property name=\"name\" value=\"" + PROCESS_NAME + "\"/>" + NEWLINE);
fw.write("\t\t<property name=\"configOverrideMap\">" + NEWLINE);
fw.write("\t\t\t<map>" + NEWLINE);
//Loop through properties
for (String k : configMap.keySet()) {
fw.write("\t\t\t\t<entry key=\"" + k + "\" value=\"" + configMap.get(k) + "\"/>" + NEWLINE);
}
fw.write("\t\t\t</map>" + NEWLINE);
fw.write("\t\t</property>" + NEWLINE);
fw.write("\t</bean>" + NEWLINE);
fw.write("</beans>" + NEWLINE);
fw.flush();
fw.close();
}
public void createLogXml() throws Exception {
File logXml = new File(CONFIG_DIR,"log-conf.xml");
logXml.createNewFile();
FileWriter fw = new FileWriter(logXml);
fw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + NEWLINE);
fw.write("<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">" + NEWLINE);
fw.write("<log4j:configuration>" + NEWLINE);
fw.write("\t<appender name=\"fileAppender\" class=\"org.apache.log4j.RollingFileAppender\">" + NEWLINE);
fw.write("\t\t<param name=\"File\" value=\"log/sdl.log\" />" + NEWLINE);
fw.write("\t\t<param name=\"Append\" value=\"true\" />" + NEWLINE);
fw.write("\t\t<param name=\"MaxFileSize\" value=\"100KB\" />" + NEWLINE);
fw.write("\t\t<param name=\"MaxBackupIndex\" value=\"1\" />" + NEWLINE);
fw.write("\t\t<layout class=\"org.apache.log4j.PatternLayout\">" + NEWLINE);
fw.write("\t\t\t<param name=\"ConversionPattern\" value=\"%d %-5p [%t] %C{2} %M (%F:%L) - %m%n\"/>" + NEWLINE);
fw.write("\t\t</layout>" + NEWLINE);
fw.write("\t</appender>" + NEWLINE);
fw.write("\t<appender name=\"STDOUT\" class=\"org.apache.log4j.ConsoleAppender\">" + NEWLINE);
fw.write("\t\t<layout class=\"org.apache.log4j.PatternLayout\">" + NEWLINE);
fw.write("\t\t\t<param name=\"ConversionPattern\" value=\"%d %-5p [%t] %C{2} %M (%F:%L) - %m%n\"/>" + NEWLINE);
fw.write("\t\t</layout>" + NEWLINE);
fw.write("\t</appender>" + NEWLINE);
fw.write("\t<category name=\"org.apache.log4j.xml\">" + NEWLINE);
fw.write("\t\t<priority value=\"warn\" />" + NEWLINE);
fw.write("\t\t<appender-ref ref=\"fileAppender\" />" + NEWLINE);
fw.write("\t\t<appender-ref ref=\"STDOUT\" />" + NEWLINE);
fw.write("\t</category>" + NEWLINE);
fw.write("\t<logger name=\"org.apache\" >" + NEWLINE);
fw.write("\t\t<level value =\"warn\" />" + NEWLINE);
fw.write("\t</logger>" + NEWLINE);
fw.write("\t<root>" + NEWLINE);
fw.write("\t\t<priority value =\"info\" />" + NEWLINE);
fw.write("\t\t<appender-ref ref=\"fileAppender\" />" + NEWLINE);
fw.write("\t\t<appender-ref ref=\"STDOUT\" />" + NEWLINE);
fw.write("\t</root>" + NEWLINE);
fw.write("</log4j:configuration>" + NEWLINE);
fw.flush();
fw.close();
}
public void createConfigProperties() {
File configProperties = new File(CONFIG_DIR,"config.properties");
try {
configProperties.createNewFile();
} catch (IOException ie) {
//Do Nothing
}
}
/**
* Creates .bat script for Windows
*
* @throws Exception
*/
public void createBatScript() throws Exception {
File batScript = new File(SCRIPT_DIR,PROCESS_NAME + ".bat");
batScript.createNewFile();
FileWriter fw = new FileWriter(batScript);
fw.write("SET DLPATH=\"" + HOME_DIR + "\"" + NEWLINE);
fw.write("SET DLCONF=\"" + CONFIG_DIR + "\"" + NEWLINE);
fw.write("SET DLDATA=\"" + WRITE_DIR + "\"" + NEWLINE);
fw.write("call %DLPATH%\\" + WINDOWS_JAVA_DIR + "\\bin\\java.exe " +
"-cp %DLPATH%\\* " +
"-Dsalesforce.config.dir=%DLCONF% com.salesforce.dataloader.process.ProcessRunner " +
"process.name=" + PROCESS_NAME + NEWLINE);
fw.write("REM To rotate your export files, uncomment the line below" + NEWLINE);
fw.write("REM copy %DLDATA%\\" + PROCESS_NAME + ".csv " +
"%DLDATA%\\%date:~10,4%%date:~7,2%%date:~4,2%-%time:~0,2%-" + PROCESS_NAME + ".csv" + NEWLINE);
fw.flush();
fw.close();
}
/**
* Creates .sh script for UNIX
*
* @throws Exception
*/
public void createShScript() throws Exception {
File batScript = new File(SCRIPT_DIR,PROCESS_NAME + ".sh");
batScript.createNewFile();
FileWriter fw = new FileWriter(batScript);
fw.write("#!/bin/sh" + NEWLINE);
fw.write("export DLPATH=\"" + HOME_DIR + "\"" + NEWLINE);
fw.write("export DLCONF=\"" + CONFIG_DIR + "\"" + NEWLINE);
fw.write("java -cp \"$DLPATH/*\" " +
"-Dsalesforce.config.dir=$DLCONF " +
"com.salesforce.dataloader.process.ProcessRunner " +
"process.name=" + PROCESS_NAME + NEWLINE);
fw.flush();
fw.close();
}
/**
* Verifies that the username and password are valid with Salesforce
*
* setUsername and setPassword must be called before this method.
*/
public void doSalesforceLogin() throws Exception {
if (getConfigValue(Config.USERNAME).length() == 0 || getPlainPassword().length() == 0)
throw new Exception("Username and password cannot be blank.");
else {
DataLoaderCliq.log("Logging in to salesforce as " + getConfigValue(Config.USERNAME));
config.setUsername(getConfigValue(Config.USERNAME));
config.setPassword(getPlainPassword());
config.setAuthEndpoint(getConfigValue(Config.ENDPOINT));
if (getConfigValue(Config.PROXY_HOST) != null && getConfigValue(Config.PROXY_HOST).length() > 0) {
System.out.println("Enabling proxy host: " + getConfigValue(Config.PROXY_HOST));
config.setProxy(getConfigValue(Config.PROXY_HOST), Integer.valueOf(getConfigValue(Config.PROXY_PORT)));
}
if (getConfigValue(Config.PROXY_USERNAME) != null && getConfigValue(Config.PROXY_USERNAME).length() > 0) {
config.setProxyUsername(getConfigValue(Config.PROXY_USERNAME));
config.setProxyPassword(getConfigValue(Config.PROXY_PASSWORD));
}
try {
connection = new PartnerConnection(config);
connection.login(getConfigValue(Config.USERNAME), getPlainPassword());
} catch (LoginFault ex) {
DataLoaderCliq.log("Login exception: " + ex.getFaultCode(), ex);
throw new Exception(ex.getFaultCode().getLocalPart() + " - " + ex.getExceptionMessage());
} catch (ApiFault ex) {
DataLoaderCliq.log("API exception: " + ex.getCause(), ex);
throw new Exception(ex.getFaultCode().getLocalPart() + " - " + ex.getExceptionMessage());
} catch (ConnectionException ex) {
DataLoaderCliq.log("Connection exception: " + ex.getCause(), ex);
throw ex;
}
}
}
}
| Java |
package com.salesforce.cliq.cliconfig;
import com.salesforce.cliq.cliconfig.CliConfig.Operation;
import com.salesforce.dataloader.config.Config;
import com.sforce.soap.partner.fault.*;
import java.io.File;
import java.util.regex.*;
/**
* Extends CliConfig with specific implementation for Export(Extract) operations
*
* @author vswamidass
*
*/
public class CliConfigExport extends CliConfig {
public enum ExportOperation implements Operation {
EXTRACT, EXTRACT_ALL;
public DataLoaderOperation toDataLoaderOperation() {
switch (this) {
case EXTRACT_ALL:
return CliConfig.DataLoaderOperation.EXTRACT_ALL;
default:
return CliConfig.DataLoaderOperation.EXTRACT;
}
}
}
ExportOperation exportOperation;
/* Indicates if the current query has been validated with Salesforce */
private boolean queryValid = false;
private String queryOriginal = null;
/**
* Constructor
*
* @param dir
* Data Loader home dir
* @param name
* The Process name
*/
public CliConfigExport(ExportOperation operation, String dir, String processName) {
super(operation.toDataLoaderOperation(), dir, processName);
exportOperation = operation;
}
/**
* Sets specific process-conf.xml parameters for Export operations.
*/
@Override
protected void setConfigDefaults() {
setConfigValue(Config.OPERATION, "extract");
setConfigValue(Config.DAO_TYPE, "csvWrite");
File outputFile = new File(WRITE_DIR, PROCESS_NAME + ".csv");
setConfigValue(Config.DAO_NAME, outputFile.getAbsolutePath());
super.setConfigDefaults();
}
/**
* Sets the process-conf.xml extractionSOQL and entity key/values - Verifies
* that the query is valid with Salesforce - Parses out the entity from the
* query
*
* @param q
* SOQL Query to Export
* @throws Exception
* Salesforce reported an error with the query
*/
public void setQueryAndEntity(String q) throws Exception {
String xmlCompatibleQuery = new String();
/* Set the variables */
queryOriginal = q;
setQueryValid(false);
/* Fix > */
Pattern greaterThan = Pattern.compile(">");
xmlCompatibleQuery = greaterThan.matcher(getQueryOriginal())
.replaceAll(">");
/* Fix < */
Pattern lessThan = Pattern.compile("<");
xmlCompatibleQuery = lessThan.matcher(xmlCompatibleQuery).replaceAll(
"<");
setConfigValue(Config.EXTRACT_SOQL, xmlCompatibleQuery);
/* Run the query and verify */
try {
connection.query(getQueryOriginal());
setQueryValid(true);
} catch (UnexpectedErrorFault uef) {
throw new Exception(uef.getExceptionMessage());
} catch (MalformedQueryFault mqf) {
throw new Exception(mqf.getExceptionMessage());
} catch (InvalidFieldFault iff) {
throw new Exception(iff.getExceptionMessage());
} catch (InvalidSObjectFault isf) {
throw new Exception(isf.getExceptionMessage());
} catch (Exception e) {
throw new Exception("Unknown error in query.");
}
/* TODO need to validate */
Pattern p = Pattern.compile("FROM (\\w+)", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(this.getQueryOriginal());
m.find();
setEntityName(m.group(1));
}
public String getQueryOriginal() {
return queryOriginal;
}
public void setQueryValid(boolean v) {
queryValid = v;
}
public boolean isQueryValid() {
return queryValid;
}
public void setExportOperation(ExportOperation op) {
exportOperation = op;
setDataLoaderOperation(op.toDataLoaderOperation());
}
public ExportOperation getExportOperation() {
return exportOperation;
}
} | Java |
package com.salesforce.cliq.cliconfig;
import com.salesforce.cliq.DataLoaderCliq;
import com.salesforce.dataloader.config.Config;
/*
* Based on the CliConfig.DataLoaderOperation, constructs a CliConfig object and returns it
*/
public class CliConfigFactory {
public static CliConfig getCliConfig(CliConfig.DataLoaderOperation op, String dir, String processName, String endPoint) {
CliConfig myConfig;
switch (op) {
case EXTRACT:
myConfig = new CliConfigExport(CliConfigExport.ExportOperation.EXTRACT, dir, processName);
break;
case EXTRACT_ALL:
myConfig = new CliConfigExport(CliConfigExport.ExportOperation.EXTRACT_ALL, dir, processName);
break;
case INSERT:
myConfig = new CliConfigDml(CliConfigDml.DmlOperation.INSERT, dir, processName);
break;
case UPDATE:
myConfig = new CliConfigDml(CliConfigDml.DmlOperation.UPDATE, dir, processName);
break;
case UPSERT:
myConfig = new CliConfigDml(CliConfigDml.DmlOperation.UPSERT, dir, processName);
break;
case DELETE:
myConfig = new CliConfigDml(CliConfigDml.DmlOperation.DELETE, dir, processName);
break;
case HARD_DELETE:
myConfig = new CliConfigDml(CliConfigDml.DmlOperation.HARD_DELETE, dir, processName);
break;
default:
myConfig = null; //this should never be hit
}
myConfig.setConfigValue(Config.ENDPOINT,endPoint);
return myConfig;
}
public static CliConfig getCliConfig(CliConfig.DataLoaderOperation op, String dir, String processName) {
return CliConfigFactory.getCliConfig(op,dir,processName,null);
}
}
| Java |
package com.salesforce.cliq.cliconfig;
import java.io.File;
import java.io.FileWriter;
import com.salesforce.cliq.cliconfig.CliConfig.DataLoaderOperation;
import com.salesforce.cliq.cliconfig.CliConfig.Operation;
import com.salesforce.cliq.cliconfig.CliConfigExport.ExportOperation;
import com.salesforce.dataloader.config.Config;
import com.sforce.soap.partner.fault.LoginFault;
import com.sforce.soap.partner.fault.UnexpectedErrorFault;
/**
* Extends CliConfig with specific implementation for DML operations
* INSERT, UPDATE, UPSERT, DELETE
*
* @author vswamidass
*
*/
public class CliConfigDml extends CliConfig {
public static final String EXTERNAL_ID_PROPERTY = "sfdc.externalIdField";
public enum DmlOperation implements Operation {
INSERT(false), UPDATE(false), UPSERT(true), DELETE(false), HARD_DELETE(false);
public DataLoaderOperation toDataLoaderOperation() {
switch (this) {
case INSERT:
return CliConfig.DataLoaderOperation.INSERT;
case UPDATE:
return CliConfig.DataLoaderOperation.UPDATE;
case UPSERT:
return CliConfig.DataLoaderOperation.UPSERT;
case DELETE:
return CliConfig.DataLoaderOperation.DELETE;
case HARD_DELETE:
return CliConfig.DataLoaderOperation.HARD_DELETE;
default:
return null; //this should never be hit
}
}
private boolean canUseExternalId;
private DmlOperation(boolean usesExternalId) {
canUseExternalId = usesExternalId;
}
public boolean isExternalIdOperation() {
return canUseExternalId;
}
}
DmlOperation dmlOperation;
/**
* Constructor
* Sets the process-conf.xml process.operation to the operation parameter.
*
* @param dir Data Loader Directory
* @param name Process Name
* @param operation DML Operation (enum Operations)
*/
public CliConfigDml(DmlOperation operation, String dir, String name) {
super(operation.toDataLoaderOperation(), dir, name);
//setEndpoint(endPoint);
dmlOperation = operation;
}
/**
* Overrides CliConfig.setConfigDefaults
*
* Sets specific process-conf.xml parameters for DML operations.
*/
protected void setConfigDefaults() {
setConfigValue(Config.MAPPING_FILE,getSdlFile().getAbsolutePath());
setConfigValue(Config.DAO_NAME,getInputFile().getAbsolutePath());
setConfigValue(Config.DAO_TYPE,"csvRead");
super.setConfigDefaults();
}
/**
* Overrides CliConfig.createFiles to add files for DML operations.
*/
public void createFiles() throws Exception {
super.createFiles();
createSdl();
createInputFile();
}
protected File getSdlFile() {
return new File(CONFIG_DIR,PROCESS_NAME + ".sdl");
}
protected File getInputFile() {
return new File(READ_DIR,PROCESS_NAME + ".csv");
}
/**
* Creates a placeholder sdl mapping file
*
* @throws Exception
*/
protected void createSdl() throws Exception {
File sdl = getSdlFile();
sdl.createNewFile();
FileWriter fw = new FileWriter(sdl);
fw.write("# Created by Dataloader Cliq" + NEWLINE);
fw.write("#" + NEWLINE);
fw.write("# Create your field mapping list in the following format" + NEWLINE);
fw.write("# <Your CSV Field1>=<Salesforce Field in " + getConfigValue(Config.ENTITY) + ">" + NEWLINE);
fw.write("# NOTE: Salesforce Fields are case-sensitive. " + NEWLINE);
fw.write(NEWLINE);
fw.write("# Example: " + NEWLINE);
fw.write("ID=Id" + NEWLINE);
fw.flush();
fw.close();
};
/**
* Creates a placeHolder CSV file in the read directory
*
* @throws Exception
*/
protected void createInputFile() throws Exception {
File inputFile = getInputFile();
inputFile.createNewFile();
FileWriter fw = new FileWriter(inputFile);
fw.write("Replace this file with your csv. The first row should have the field names.");
fw.write("Make sure to update the sdl file also " + getSdlFile().getAbsolutePath());
fw.flush();
fw.close();
};
public void setExternalIdField(String entity, String externalIdField)
throws Exception {
if (this.isFieldExternalId(entity, externalIdField)) {
this.setConfigValue(EXTERNAL_ID_PROPERTY, externalIdField);
} else {
this.setConfigValue(EXTERNAL_ID_PROPERTY, null);
throw new Exception("External Id not valid for " + entity);
}
}
public String getExternalIdField() {
return getConfigValue(EXTERNAL_ID_PROPERTY);
}
public boolean isExternalIdOperation() {
return dmlOperation.isExternalIdOperation();
}
public boolean isExternalIdValid() {
try {
return this.isFieldExternalId(this.getConfigValue(Config.ENTITY), this.getExternalIdField());
} catch (Exception e) {
return false;
}
}
public void setDmlOperation(DmlOperation op) {
dmlOperation = op;
setDataLoaderOperation(op.toDataLoaderOperation());
}
public DmlOperation getDmlOperation() {
return dmlOperation;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* AboutJDialog.java
*
* Created on Dec 23, 2010, 8:45:49 PM
*/
package dataclustering;
/**
*
* @author Thuan Loc
*/
public class AboutJDialog extends javax.swing.JDialog {
/** Creates new form AboutJDialog */
public AboutJDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
/** 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">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("About");
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14));
jLabel1.setForeground(new java.awt.Color(0, 0, 204));
jLabel1.setText("Group 10: K-MEANS CLUSTERING");
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12));
jLabel2.setText("1. Ngo Thuan Loc");
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12));
jLabel3.setText("2. Tran Quoc Trieu");
jLabel4.setForeground(new java.awt.Color(0, 136, 0));
jLabel4.setText("Faculty of Computer Science & Engineering - HCMC University");
jLabel5.setForeground(new java.awt.Color(0, 136, 0));
jLabel5.setText("Honor Program 07");
jLabel6.setForeground(new java.awt.Color(200, 0, 0));
jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel6.setText("Version 1.0");
jLabel7.setForeground(new java.awt.Color(200, 0, 0));
jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
jLabel7.setText("12 - 2010");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel5))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(32, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(45, 45, 45)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 166, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(45, 45, 45)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 273, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(jLabel7)
.addGap(18, 18, 18)
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(jLabel3)
.addGap(23, 23, 23)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel6)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dataclustering;
import java.io.File;
import javax.swing.filechooser.FileFilter;
/**
*
* @author Thuan Loc
*/
class ExtensionFileFilter extends FileFilter {
String description;
String extensions[];
public ExtensionFileFilter(String description, String extension) {
this(description, new String[] { extension });
}
public ExtensionFileFilter(String description, String extensions[]) {
if (description == null) {
this.description = extensions[0];
} else {
this.description = description;
}
this.extensions = (String[]) extensions.clone();
toLower(this.extensions);
}
private void toLower(String array[]) {
for (int i = 0, n = array.length; i < n; i++) {
array[i] = array[i].toLowerCase();
}
}
public String getDescription() {
return description;
}
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
} else {
String path = file.getAbsolutePath().toLowerCase();
for (int i = 0, n = extensions.length; i < n; i++) {
String extension = extensions[i];
if ((path.endsWith(extension) && (path.charAt(path.length() - extension.length() - 1)) == '.')) {
return true;
}
}
}
return false;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dataclustering;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import org.math.plot.Plot3DPanel;
class MyComparator implements Comparator<Cluster> {
public int compare(Cluster o1, Cluster o2) {
if (o1.SSE < o2.SSE) {
return 1;
}
if (o1.SSE > o2.SSE) {
return -1;
}
return 0;
}
}
/**
*
* @author Thuan Loc
*/
public class ChartThread extends Thread {
private Vector<Point3D> VP;
private int K;
private int MaxLoops;
private Plot3DPanel ClusteringPanelChart;
private JTable jTable;
private JLabel jLabel4;
private JButton jButton2;
private int KMeansType;
private JTabbedPane jTabbedPane;
private int DistanceType;
ChartThread(int KMeansType, Vector<Point3D> VP, int K, int MaxLoops, Plot3DPanel ClusteringPanelChart, JTable jTable, JLabel jLabel4, JButton jButton2, JTabbedPane jTabbedPane, int DistanceType) {
this.VP = new Vector<Point3D>();
for (int i = 0; i < VP.size(); i++) {
this.VP.add(new Point3D(VP.elementAt(i).x, VP.elementAt(i).y, VP.elementAt(i).z));
}
this.K = K;
this.MaxLoops = MaxLoops;
this.ClusteringPanelChart = ClusteringPanelChart;
this.jTable = jTable;
this.jLabel4 = jLabel4;
this.jButton2 = jButton2;
this.KMeansType = KMeansType;
this.jTabbedPane = jTabbedPane;
this.DistanceType = DistanceType;
}
private void createChart(Vector<Cluster> ClusterVector) {
try {
this.ClusteringPanelChart.removeAllPlots();
Thread.sleep(Math.max(1000, VP.size() / 50));
for (int i = 0; i < ClusterVector.size(); i++) {
double[] x = new double[ClusterVector.elementAt(i).V.size()];
double[] y = new double[ClusterVector.elementAt(i).V.size()];
double[] z = new double[ClusterVector.elementAt(i).V.size()];
for (int j = 0; j < ClusterVector.elementAt(i).V.size(); j++) {
x[j] = ClusterVector.elementAt(i).V.elementAt(j).x;
y[j] = ClusterVector.elementAt(i).V.elementAt(j).y;
z[j] = ClusterVector.elementAt(i).V.elementAt(j).z;
}
this.ClusteringPanelChart.addScatterPlot("Cluster " + Integer.toString(i), x, y, z);
jTable.setValueAt(i + 1, i, 0);
jTable.setValueAt(ClusterVector.elementAt(i).V.size(), i, 1);
BigDecimal bd = new BigDecimal(ClusterVector.elementAt(i).Centroid.x);
jTable.setValueAt(bd.setScale(5, BigDecimal.ROUND_HALF_UP).toString(), i, 2);
bd = new BigDecimal(ClusterVector.elementAt(i).Centroid.y);
jTable.setValueAt(bd.setScale(5, BigDecimal.ROUND_HALF_UP).toString(), i, 3);
bd = new BigDecimal(ClusterVector.elementAt(i).Centroid.z);
jTable.setValueAt(bd.setScale(5, BigDecimal.ROUND_HALF_UP).toString(), i, 4);
Thread.sleep(Math.max(1000, VP.size() / 50));
}
} catch (Exception e) {
}
}
private Vector<Cluster> K_Means_Clustering(Cluster MainCluster, int K, int MaxLoops, int[] Seeds, boolean showChart) {
Vector<Cluster> ClusterVector = new Vector<Cluster>();
for (int i = 0; i < K; i++) {
ClusterVector.add(new Cluster(MainCluster.V.elementAt(Seeds[i])));
}
int loops = 0;
while (loops < Math.min(10, MaxLoops)) {
for (int i = 0; i < K; i++) {
ClusterVector.elementAt(i).V.removeAllElements();
}
for (int i = 0; i < MainCluster.V.size(); i++) {
Point3D p = MainCluster.V.elementAt(i);
double MinDist = CONST.INF;
int ChosenCluster = 0;
for (int j = 0; j < K; j++) {
if (MinDist > CONST.Distance(p, ClusterVector.get(j).Centroid, this.DistanceType)) {
MinDist = CONST.Distance(p, ClusterVector.get(j).Centroid, this.DistanceType);
ChosenCluster = j;
}
}
ClusterVector.get(ChosenCluster).V.add(p);
}
boolean Terminate = true;
for (int i = 0; i < K; i++) {
if (!CONST.Equal(ClusterVector.get(i).Centroid, CONST.getCentroid(ClusterVector.get(i).V), this.DistanceType)) {
Terminate = false;
}
ClusterVector.get(i).Centroid = CONST.getCentroid(ClusterVector.get(i).V);
ClusterVector.get(i).SSE = CONST.calSSE(ClusterVector.get(i), this.DistanceType);
}
if (Terminate) {
break;
}
loops++;
if (CONST.STOP) {
this.jLabel4.setVisible(false);
break;
}
if (showChart) {
createChart(ClusterVector);
}
}
return ClusterVector;
}
private void Bisecting_K_Means_Clustering(Cluster MainCluster, int K, int MaxLoops) {
MainCluster.SSE = CONST.calSSE(MainCluster, this.DistanceType);
Comparator<Cluster> cmp = new MyComparator();
PriorityQueue<Cluster> Q = new PriorityQueue<Cluster>(K, cmp);
Q.add(MainCluster);
while (Q.size() < K) {
Vector<Cluster> V = new Vector<Cluster>();
Iterator<Cluster> I = Q.iterator();
while (I.hasNext()) {
V.add(I.next());
}
createChart(V);
Cluster MaxCluster = Q.poll();
double MinTotalSSE = CONST.INF;
Cluster C1 = null;
Cluster C2 = null;
for (int i = 0; i < MaxCluster.V.size() - 1; i = i * 10 + 1) {
for (int j = i + 1; j < MaxCluster.V.size(); j *= 10) {
int[] Seeds = new int[2];
Seeds[0] = i;
Seeds[1] = j;
Vector<Cluster> BiClusters = K_Means_Clustering(MaxCluster, 2, Math.min(MaxLoops, 5), Seeds, false);
if (MinTotalSSE > BiClusters.elementAt(0).SSE + BiClusters.elementAt(1).SSE) {
C1 = BiClusters.elementAt(0);
C2 = BiClusters.elementAt(1);
MinTotalSSE = BiClusters.elementAt(0).SSE + BiClusters.elementAt(1).SSE;
}
}
}
Q.add(C1);
Q.add(C2);
}
Vector<Cluster> V = new Vector<Cluster>();
Iterator<Cluster> I = Q.iterator();
while (I.hasNext()) {
V.add(I.next());
}
createChart(V);
}
private void EM_K_Means_Clustering(Cluster MainCluster, int K) {
int R = MainCluster.V.size();
Point3D[] Means = new Point3D[K];
double[][] PxBelongsToC = new double[R][K];
Vector<Cluster> ClusterVector;
MainCluster.SSE = CONST.calSSE(MainCluster, CONST.EUCLIDEAN);
double Deviation = MainCluster.SSE;
Deviation /= MainCluster.V.size();
Deviation = Math.sqrt(Deviation);
for (int i = 0; i < K; i++) {
Means[i] = new Point3D(MainCluster.V.elementAt(i));
}
ClusterVector = new Vector<Cluster>();
for (int i = 0; i < K; i++) {
ClusterVector.add(new Cluster(new Point3D(Means[i])));
}
//Expectation Step
for (int k = 0; k < R; k++) {
double SumOfPxBelongsToC = 0;
for (int i = 0; i < K; i++) {
SumOfPxBelongsToC += CONST.NormalDistribution(MainCluster.V.elementAt(k), Means[i], Deviation);
}
for (int i = 0; i < K; i++) {
PxBelongsToC[k][i] = CONST.NormalDistribution(MainCluster.V.elementAt(k), Means[i], Deviation) / SumOfPxBelongsToC;
}
}
//Maximization Step
for (int i = 0; i < K; i++) {
Point3D SumOfMeanPx = new Point3D(0, 0, 0);
double SumOfPx = 0;
for (int k = 0; k < R; k++) {
SumOfMeanPx.x += PxBelongsToC[k][i] * MainCluster.V.elementAt(k).x;
SumOfMeanPx.y += PxBelongsToC[k][i] * MainCluster.V.elementAt(k).y;
SumOfMeanPx.z += PxBelongsToC[k][i] * MainCluster.V.elementAt(k).z;
SumOfPx += PxBelongsToC[k][i];
}
Means[i].x = SumOfMeanPx.x / SumOfPx;
Means[i].y = SumOfMeanPx.y / SumOfPx;
Means[i].z = SumOfMeanPx.z / SumOfPx;
}
ClusterVector = new Vector<Cluster>();
for (int i = 0; i < K; i++) {
ClusterVector.add(new Cluster(new Point3D(Means[i])));
}
for (int i = 0; i < R; i++) {
double Min = CONST.INF;
int pos = 0;
for (int k = 0; k < K; k++) {
if (Min > CONST.Distance(Means[k], MainCluster.V.elementAt(i), CONST.EUCLIDEAN)) {
Min = CONST.Distance(Means[k], MainCluster.V.elementAt(i), CONST.EUCLIDEAN);
pos = k;
}
}
ClusterVector.elementAt(pos).V.add(MainCluster.V.elementAt(i));
}
createChart(ClusterVector);
}
private void K_Medoids_Clustering(Cluster MainCluster, int K) {
int N = MainCluster.V.size();
int[] M = new int[K];//Array Of Medoids
boolean[] IsMedoids = new boolean[N];
Arrays.fill(IsMedoids, false);
for (int i = 0; i < K; i++) {
M[i] = i;
IsMedoids[i] = true;
}
int[] B = new int[N];//which medoid point i belongs to
int[] NB = new int[N];
double SE = CONST.SumOfError(M, B, IsMedoids, K, MainCluster.V, this.DistanceType);
int loops = 0;
while (loops < this.MaxLoops) {
boolean found = false;
int O = 0;
int P = 0;
for (int i = 0; i < K; i++) {
for (int j = 0; j < N; j++) {
if (!IsMedoids[j]&&NB[j]==i) {
IsMedoids[j] = true;
IsMedoids[M[i]] = false;
double tmp = CONST.SumOfError(M, B, IsMedoids, K, MainCluster.V, this.DistanceType);
if (SE > tmp) {
SE = tmp;
O = i;
P = j;
NB = Arrays.copyOf(B, N);
found = true;
}
IsMedoids[j] = false;
IsMedoids[M[i]] = true;
}
}
}
if (found) {
IsMedoids[M[O]] = false;
M[O] = P;
IsMedoids[P] = true;
Vector<Cluster> ClusterVector = new Vector<Cluster>();
for (int i = 0; i < K; i++) {
ClusterVector.add(new Cluster(new Point3D(0, 0, 0)));
}
for (int i = 0; i < K; i++) {
ClusterVector.elementAt(i).V.add(MainCluster.V.elementAt(M[i]));
}
for (int i = 0; i < N; i++) {
if (!IsMedoids[i]) {
ClusterVector.elementAt(NB[i]).V.add(MainCluster.V.elementAt(i));
}
}
for(int i=0;i<K;i++)
ClusterVector.elementAt(i).Centroid = CONST.getCentroid(ClusterVector.elementAt(i).V);
createChart(ClusterVector);
} else {
this.jLabel4.setVisible(false);
break;
}
if (CONST.STOP) {
this.jLabel4.setVisible(false);
break;
}
loops++;
}
}
private void createKMeansChart() {
Cluster C = new Cluster(VP);
jTable.setModel(new javax.swing.table.DefaultTableModel(
new Object[K][5],
new String[]{
"Cluster No", "NOf Objects", "Centroid's X", "Centroid's Y", "Centroid's Z"
}) {
Class[] types = new Class[]{
java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class
};
@Override
public Class getColumnClass(int columnIndex) {
return types[columnIndex];
}
});
switch (KMeansType) {
case CONST.BASIC_KMEANS:
int[] Seeds = new int[K];
for (int i = 0; i < K; i++) {
Seeds[i] = i;
}
K_Means_Clustering(C, K, MaxLoops, Seeds, true);
break;
case CONST.BISECTING_KMEANS:
this.jButton2.setEnabled(false);
Bisecting_K_Means_Clustering(C, K, MaxLoops);
break;
case CONST.EM_KMEANS:
this.jButton2.setEnabled(false);
EM_K_Means_Clustering(C, K);
break;
case CONST.K_MEDOIDS:
K_Medoids_Clustering(C, K);
break;
}
}
@Override
public void run() {
createKMeansChart();
this.jButton2.setEnabled(false);
this.jTabbedPane.setEnabledAt(0, true);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dataclustering;
import java.util.Vector;
/**
*
* @author Thuan Loc
*/
public class CONST {
static final double INF = (double) 2000000000 * (double) 2000000000;
static final int EUCLIDEAN = 1;
static final int MANHATTAN = 2;
static final int BASIC_KMEANS = 1;
static final int EM_KMEANS = 2;
static final int BISECTING_KMEANS = 3;
static final int K_MEDOIDS = 4;
static boolean STOP;
static double Distance(Point3D p1, Point3D p2, int DistanceType) {
switch (DistanceType) {
case EUCLIDEAN:
return Math.sqrt((p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y) + (p2.z - p1.z) * (p2.z - p1.z));
default:
return Math.abs(p2.x - p1.x) + Math.abs(p2.y - p1.y) + Math.abs(p2.z - p1.z);
}
}
static double calSSE(Cluster C, int DistanceType) {
double sum = 0;
for (int i = 0; i < C.V.size(); i++) {
sum += Distance(C.V.elementAt(i), C.Centroid, CONST.EUCLIDEAN) * Distance(C.V.elementAt(i), C.Centroid, DistanceType);
}
return sum;
}
static Point3D getCentroid(Vector<Point3D> V) {
double x = 0;
double y = 0;
double z = 0;
for (int i = 0; i < V.size(); i++) {
x += V.elementAt(i).x;
y += V.elementAt(i).y;
z += V.elementAt(i).z;
}
x /= V.size();
y /= V.size();
z /= V.size();
return new Point3D(x, y, z);
}
static boolean Equal(Point3D p1, Point3D p2, int DistanceType) {
switch (DistanceType) {
case EUCLIDEAN:
if (Distance(p1, p2, EUCLIDEAN) < 0.001) {
return true;
}
return false;
default://MANHATTAN
if (Distance(p1, p2, MANHATTAN) < 0.005) {
return true;
}
return false;
}
}
static double SumOfError(int[] M,int[] B,boolean[] IsMedoids,int K,Vector<Point3D> V,int DistanceType)
{
double SOE = 0;
for(int i=0;i<V.size();i++)
if(!IsMedoids[i])
{
double MinDis = INF;
for(int j=0;j<K;j++)
{
if(MinDis>Distance(V.elementAt(i),V.elementAt(M[j]),DistanceType))
{
MinDis=Distance(V.elementAt(i),V.elementAt(M[j]),DistanceType);
B[i] = j;
}
}
SOE += MinDis;
}
return SOE;
}
static double NormalDistribution(Point3D p, Point3D mean, double Deviation) {
double result = Math.exp(-(Distance(p, mean, EUCLIDEAN) * Distance(p, mean, EUCLIDEAN)) / (2 * Deviation * Deviation));
return result;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dataclustering;
import java.util.Vector;
/**
*
* @author Thuan Loc
*/
public class Cluster {
Vector<Point3D> V;
Point3D Centroid;
double SSE;
Cluster(Point3D Centroid) {
this.V = new Vector<Point3D>();
this.Centroid = Centroid;
}
Cluster(Vector<Point3D> V) {
this.V = V;
double x = 0;
double y = 0;
double z = 0;
for (int i = 0; i < V.size(); i++) {
x += V.elementAt(i).x;
y += V.elementAt(i).y;
z += V.elementAt(i).z;
}
x /= V.size();
y /= V.size();
z /= V.size();
Centroid = new Point3D(x, y, z);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dataclustering;
/**
*
* @author Thuan Loc
*/
public class Point3D {
double x;
double y;
double z;
Point3D(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
Point3D(Point3D newPoint) {
this.x = newPoint.x;
this.y = newPoint.y;
this.z = newPoint.z;
}
}
class Anobject{
public double x;
public double y;
public double z;
public int center;
public int cluster;
public Anobject(double x, double y, double z){
this.x = x;
this.y = y;
this.z = z;
}
}
class SumNum{
public double sumx = 0;
public double sumy = 0;
public double sumz = 0;
public int num = 0;
} | Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dataclustering;
/**
*
* @author Thuan Loc
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
MainFrame mf = new MainFrame();
mf.setVisible(true);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* NewJFrame.java
*
* Created on Nov 14, 2010, 2:35:36 PM
*/
package dataclustering;
import java.awt.Cursor;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.Scanner;
import java.util.Vector;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import javax.swing.filechooser.FileFilter;
/**
*
* @author Thuan Loc
*/
public class MainFrame extends javax.swing.JFrame implements ActionListener, PropertyChangeListener {
Vector<Point3D> VP;
private Task task;
private File FR;
private void hideStatus() {
this.jLabelStatus.setVisible(false);
this.jLabelSizeOfFileName.setVisible(false);
this.jLabelNumOfOName.setVisible(false);
this.jLabelNofO.setVisible(false);
this.jLabelSizeofF.setVisible(false);
this.jLabelSizeOfFileName.setVisible(false);
}
class Task extends SwingWorker<Void, Void> {
/*
* Main task. Executed in background thread.
*/
@Override
public Void doInBackground() {
int progress = 0;
//Initialize progress property.
setProgress(0);
try {
Scanner in = new Scanner(FR);
long len = 0;
for (int i = 0; i < 12; i++) {
len += (in.next().length() + 1);
}
while (in.hasNext()) {
String s = in.next();
len += (s.length() + 1);
String[] SP = s.split(",");
VP.add(new Point3D(Double.parseDouble(SP[0]), Double.parseDouble(SP[1]), Double.parseDouble(SP[2])));
progress = (int) ((double) len / (double) FR.length() * 100);
setProgress(progress);
}
setProgress(100);
} catch (Exception e) {
}
return null;
}
/**
* Invoked when task's progress property changes.
*/
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().compareTo("progress") == 0) {
int progress = (Integer) evt.getNewValue();
jProgressBarTestFile.setValue(progress);
}
}
/*
* Executed in event dispatching thread
*/
@Override
public void done() {
Toolkit.getDefaultToolkit().beep();
if (VP.isEmpty()) {
jLabelStatus.setText("Please choose an .arff file");
jLabelStatus.setVisible(true);
jButtonTestFile.setEnabled(true);
} else {
jLabelSizeofF.setText(Long.toString(FR.length() / 1024) + "KB");
jLabelNofO.setText(Integer.toString(VP.size()));
jButtonTestFile.setEnabled(true);
jLabelStatus.setText("Status");
jLabelStatus.setVisible(true);
jLabelSizeOfFileName.setVisible(true);
jLabelNumOfOName.setVisible(true);
jLabelNofO.setVisible(true);
jLabelSizeofF.setVisible(true);
jLabelSizeOfFileName.setVisible(true);
jTextFieldClusterNumber.setEditable(true);
if (!jRadioButtonMenuItemEM.isSelected()) {
jTextFieldIterations.setEditable(true);
}
}
setCursor(null); //turn off the wait cursor
}
}
/** Creates new form NewJFrame */
public MainFrame() {
initComponents();
VP = new Vector<Point3D>();
this.jTabbedPane.remove(1);
this.jTextFieldClusterNumber.setEditable(false);
this.jTextFieldIterations.setEditable(false);
this.ClusteringPanelChart.plotToolBar.setVisible(false);
this.hideStatus();
}
/** 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">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
buttonGroup2 = new javax.swing.ButtonGroup();
jTabbedPane = new javax.swing.JTabbedPane();
jPanelSpecification = new javax.swing.JPanel();
jTextFieldClusterNumber = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jButtonAnalysis = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
jTextFieldFileChoice = new javax.swing.JTextField();
jButtonBrowse = new javax.swing.JButton();
jButtonTestFile = new javax.swing.JButton();
jLabelSizeOfFileName = new javax.swing.JLabel();
jLabelStatus = new javax.swing.JLabel();
jLabelNumOfOName = new javax.swing.JLabel();
jLabelSizeofF = new javax.swing.JLabel();
jLabelNofO = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jRadioButtonEuclidean = new javax.swing.JRadioButton();
jRadioButtonManhattan = new javax.swing.JRadioButton();
jLabelDistanceMeasureDiscription = new javax.swing.JLabel();
jLabel1DistanceFormula = new javax.swing.JLabel();
jProgressBarTestFile = new javax.swing.JProgressBar();
jPanel2 = new javax.swing.JPanel();
jLabel12 = new javax.swing.JLabel();
jTextFieldIterations = new javax.swing.JTextField();
jPanelPerformance = new javax.swing.JPanel();
ClusteringPanelChart = new org.math.plot.Plot3DPanel();
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jButton2 = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
jMenuBar = new javax.swing.JMenuBar();
jMenuAlgorithm = new javax.swing.JMenu();
jRadioButtonMenuItemBasicKMeans = new javax.swing.JRadioButtonMenuItem();
jSeparatorAlgorithm = new javax.swing.JPopupMenu.Separator();
jRadioButtonMenuItemKMedoids = new javax.swing.JRadioButtonMenuItem();
jRadioButtonMenuItemBisectingKMeans = new javax.swing.JRadioButtonMenuItem();
jRadioButtonMenuItemEM = new javax.swing.JRadioButtonMenuItem();
jMenuHelp = new javax.swing.JMenu();
jSeparatorHelp = new javax.swing.JPopupMenu.Separator();
jMenuItemAbout = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("K-Means Paradigm");
setBounds(new java.awt.Rectangle(55, 45, 50, 50));
jTextFieldClusterNumber.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14));
jLabel1.setText("Number of Clusters");
jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);
jButtonAnalysis.setFont(new java.awt.Font("Tahoma", 0, 14));
jButtonAnalysis.setText("Analyze");
jButtonAnalysis.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonAnalysisActionPerformed(evt);
}
});
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14));
jLabel3.setText("Choose a sample file (*.arff)");
jTextFieldFileChoice.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
jTextFieldFileChoice.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextFieldFileChoiceActionPerformed(evt);
}
});
jButtonBrowse.setText("Browse");
jButtonBrowse.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonBrowseActionPerformed(evt);
}
});
jButtonTestFile.setText("Test File");
jButtonTestFile.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonTestFileActionPerformed(evt);
}
});
jLabelSizeOfFileName.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jLabelSizeOfFileName.setText("Size of file");
jLabelStatus.setFont(new java.awt.Font("Tahoma", 0, 18));
jLabelStatus.setText("Status");
jLabelNumOfOName.setFont(new java.awt.Font("Tahoma", 0, 16));
jLabelNumOfOName.setText("Number of objects");
jLabelSizeofF.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jLabelSizeofF.setText("N/A");
jLabelNofO.setFont(new java.awt.Font("Tahoma", 0, 16));
jLabelNofO.setText("N/A");
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12));
jLabel2.setText("( *Positive integer less or equal to N)");
jLabel11.setFont(new java.awt.Font("Tahoma", 0, 14));
jLabel11.setText("Distance Measures");
buttonGroup2.add(jRadioButtonEuclidean);
jRadioButtonEuclidean.setFont(new java.awt.Font("Tahoma", 0, 12));
jRadioButtonEuclidean.setSelected(true);
jRadioButtonEuclidean.setText("Euclidean");
jRadioButtonEuclidean.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonEuclideanActionPerformed(evt);
}
});
buttonGroup2.add(jRadioButtonManhattan);
jRadioButtonManhattan.setFont(new java.awt.Font("Tahoma", 0, 12));
jRadioButtonManhattan.setText("Manhattan");
jRadioButtonManhattan.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonManhattanActionPerformed(evt);
}
});
jLabelDistanceMeasureDiscription.setText("The most popular distance measure which is defined as");
jLabel1DistanceFormula.setIcon(new javax.swing.ImageIcon("C:\\Users\\Thuan Loc\\Documents\\NetBeansProjects\\Data Clustering\\Picture\\Euclidean_Distance.png")); // NOI18N
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Additional Configuration", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12))); // NOI18N
jLabel12.setFont(new java.awt.Font("Tahoma", 0, 12));
jLabel12.setText("Maximum number of iterations");
jTextFieldIterations.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel12)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
.addComponent(jTextFieldIterations, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(32, 32, 32))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(28, 28, 28)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel12)
.addComponent(jTextFieldIterations, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(27, Short.MAX_VALUE))
);
javax.swing.GroupLayout jPanelSpecificationLayout = new javax.swing.GroupLayout(jPanelSpecification);
jPanelSpecification.setLayout(jPanelSpecificationLayout);
jPanelSpecificationLayout.setHorizontalGroup(
jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelSpecificationLayout.createSequentialGroup()
.addGap(35, 35, 35)
.addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabelSizeOfFileName, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabelNumOfOName, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelSpecificationLayout.createSequentialGroup()
.addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jTextFieldFileChoice, javax.swing.GroupLayout.PREFERRED_SIZE, 294, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jProgressBarTestFile, javax.swing.GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButtonTestFile, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonBrowse, javax.swing.GroupLayout.DEFAULT_SIZE, 76, Short.MAX_VALUE)))
.addComponent(jLabelStatus, javax.swing.GroupLayout.DEFAULT_SIZE, 388, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelSpecificationLayout.createSequentialGroup()
.addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabelNofO, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabelSizeofF, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(113, 113, 113)))
.addGap(35, 35, 35)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(45, 45, 45)
.addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel1DistanceFormula, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabelDistanceMeasureDiscription, javax.swing.GroupLayout.PREFERRED_SIZE, 389, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel11)
.addComponent(jLabel2)
.addGroup(jPanelSpecificationLayout.createSequentialGroup()
.addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addGroup(jPanelSpecificationLayout.createSequentialGroup()
.addGap(68, 68, 68)
.addComponent(jRadioButtonEuclidean)))
.addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelSpecificationLayout.createSequentialGroup()
.addGap(55, 55, 55)
.addComponent(jRadioButtonManhattan))
.addGroup(jPanelSpecificationLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextFieldClusterNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addComponent(jButtonAnalysis, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(45, 45, 45))
);
jPanelSpecificationLayout.setVerticalGroup(
jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelSpecificationLayout.createSequentialGroup()
.addGap(46, 46, 46)
.addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelSpecificationLayout.createSequentialGroup()
.addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jTextFieldFileChoice, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jButtonBrowse))
.addGap(87, 87, 87)
.addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jProgressBarTestFile, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonTestFile, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(64, 64, 64)
.addComponent(jLabelStatus)
.addGap(54, 54, 54)
.addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelSizeOfFileName)
.addComponent(jLabelSizeofF))
.addGap(41, 41, 41)
.addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelNumOfOName)
.addComponent(jLabelNofO)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelSpecificationLayout.createSequentialGroup()
.addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 547, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanelSpecificationLayout.createSequentialGroup()
.addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextFieldClusterNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel2)
.addGap(28, 28, 28)
.addComponent(jLabel11)
.addGap(19, 19, 19)
.addGroup(jPanelSpecificationLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jRadioButtonEuclidean)
.addComponent(jRadioButtonManhattan))
.addGap(24, 24, 24)
.addComponent(jLabelDistanceMeasureDiscription)
.addGap(18, 18, 18)
.addComponent(jLabel1DistanceFormula)
.addGap(70, 70, 70)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(76, 76, 76)
.addComponent(jButtonAnalysis, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(27, 27, 27))))
);
jTabbedPane.addTab("Specification", jPanelSpecification);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null}
},
new String [] {
"Cluster No", "NOf Objects", "Centroid's X", "Centroid's Y", "Centroid's Z"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jScrollPane1.setViewportView(jTable1);
jButton2.setFont(new java.awt.Font("Tahoma", 0, 14));
jButton2.setText("Stop");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14));
jLabel4.setForeground(new java.awt.Color(255, 0, 0));
jLabel4.setText("Please wait...");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 403, Short.MAX_VALUE))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 553, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 48, Short.MAX_VALUE)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 48, Short.MAX_VALUE))
.addContainerGap())
);
javax.swing.GroupLayout jPanelPerformanceLayout = new javax.swing.GroupLayout(jPanelPerformance);
jPanelPerformance.setLayout(jPanelPerformanceLayout);
jPanelPerformanceLayout.setHorizontalGroup(
jPanelPerformanceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanelPerformanceLayout.createSequentialGroup()
.addComponent(ClusteringPanelChart, javax.swing.GroupLayout.PREFERRED_SIZE, 720, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanelPerformanceLayout.setVerticalGroup(
jPanelPerformanceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(ClusteringPanelChart, javax.swing.GroupLayout.DEFAULT_SIZE, 620, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jTabbedPane.addTab("Performance", jPanelPerformance);
jMenuAlgorithm.setText("Algorithms");
buttonGroup1.add(jRadioButtonMenuItemBasicKMeans);
jRadioButtonMenuItemBasicKMeans.setSelected(true);
jRadioButtonMenuItemBasicKMeans.setText("Basic K-Means");
jRadioButtonMenuItemBasicKMeans.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonMenuItemBasicKMeansActionPerformed(evt);
}
});
jMenuAlgorithm.add(jRadioButtonMenuItemBasicKMeans);
jMenuAlgorithm.add(jSeparatorAlgorithm);
buttonGroup1.add(jRadioButtonMenuItemKMedoids);
jRadioButtonMenuItemKMedoids.setText("K-Medoids");
jRadioButtonMenuItemKMedoids.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonMenuItemKMedoidsActionPerformed(evt);
}
});
jMenuAlgorithm.add(jRadioButtonMenuItemKMedoids);
buttonGroup1.add(jRadioButtonMenuItemBisectingKMeans);
jRadioButtonMenuItemBisectingKMeans.setText("Bisecting K-Means");
jRadioButtonMenuItemBisectingKMeans.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonMenuItemBisectingKMeansActionPerformed(evt);
}
});
jMenuAlgorithm.add(jRadioButtonMenuItemBisectingKMeans);
buttonGroup1.add(jRadioButtonMenuItemEM);
jRadioButtonMenuItemEM.setText("Expectation Maximization (EM)");
jRadioButtonMenuItemEM.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButtonMenuItemEMActionPerformed(evt);
}
});
jMenuAlgorithm.add(jRadioButtonMenuItemEM);
jMenuBar.add(jMenuAlgorithm);
jMenuHelp.setText("Help");
jMenuHelp.add(jSeparatorHelp);
jMenuItemAbout.setText("About");
jMenuItemAbout.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItemAboutActionPerformed(evt);
}
});
jMenuHelp.add(jMenuItemAbout);
jMenuBar.add(jMenuHelp);
setJMenuBar(jMenuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 1144, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTabbedPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 648, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private int ensureClusterNumber() {
String s = this.jTextFieldClusterNumber.getText();
if (s.length() == 0 || s.length() > 9) {
JOptionPane.showMessageDialog(this, "Number of Clusters is invalid");
return -1;
}
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) < '0' || s.charAt(i) > '9') {
JOptionPane.showMessageDialog(this, "Number of Clusters is invalid");
return -1;
}
}
int K = Integer.parseInt(s);
if (K == 0 || K > this.VP.size()) {
JOptionPane.showMessageDialog(this, "Number of Clusters is invalid");
return -1;
}
return K;
}
private int ensureIterations() {
String s = this.jTextFieldIterations.getText();
if (s.length() == 0) {
return 1000000000;
}
if (s.length() > 9) {
JOptionPane.showMessageDialog(this, "Number of Interations is not valid");
return -1;
}
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) < '0' || s.charAt(i) > '9') {
JOptionPane.showMessageDialog(this, "Number of Interations is invalid");
return -1;
}
}
int MaxLoops = Integer.parseInt(s);
if (MaxLoops == 0 || MaxLoops > this.VP.size()) {
JOptionPane.showMessageDialog(this, "Number of Interations is invalid");
return -1;
}
return MaxLoops;
}
/**
* Invoked when task's progress property changes.
*/
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().compareTo("progress") == 0) {
int progress = (Integer) evt.getNewValue();
jProgressBarTestFile.setValue(progress);
}
}
private void jRadioButtonMenuItemEMActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonMenuItemEMActionPerformed
// TODO add your handling code here:
this.jTextFieldIterations.setEditable(false);
this.jTextFieldIterations.setText(null);
this.jRadioButtonManhattan.setEnabled(false);
this.jRadioButtonEuclidean.setSelected(true);
jLabelDistanceMeasureDiscription.setText("The most popular distance measure which is defined as");
jLabel1DistanceFormula.setIcon(new javax.swing.ImageIcon("C:\\Users\\Thuan Loc\\Documents\\NetBeansProjects\\Data Clustering\\Picture\\Euclidean_Distance.png"));
}//GEN-LAST:event_jRadioButtonMenuItemEMActionPerformed
private void jRadioButtonMenuItemBasicKMeansActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonMenuItemBasicKMeansActionPerformed
// TODO add your handling code here:
this.jTextFieldIterations.setEditable(true);
this.jRadioButtonManhattan.setEnabled(true);
this.jRadioButtonEuclidean.setSelected(true);
jLabelDistanceMeasureDiscription.setText("The most popular distance measure which is defined as");
jLabel1DistanceFormula.setIcon(new javax.swing.ImageIcon("C:\\Users\\Thuan Loc\\Documents\\NetBeansProjects\\Data Clustering\\Picture\\Euclidean_Distance.png"));
}//GEN-LAST:event_jRadioButtonMenuItemBasicKMeansActionPerformed
private void jRadioButtonMenuItemKMedoidsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonMenuItemKMedoidsActionPerformed
// TODO add your handling code here:
this.jTextFieldIterations.setEditable(true);
this.jRadioButtonManhattan.setEnabled(true);
this.jRadioButtonEuclidean.setSelected(true);
jLabelDistanceMeasureDiscription.setText("The most popular distance measure which is defined as");
jLabel1DistanceFormula.setIcon(new javax.swing.ImageIcon("C:\\Users\\Thuan Loc\\Documents\\NetBeansProjects\\Data Clustering\\Picture\\Euclidean_Distance.png"));
}//GEN-LAST:event_jRadioButtonMenuItemKMedoidsActionPerformed
private void jRadioButtonMenuItemBisectingKMeansActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonMenuItemBisectingKMeansActionPerformed
// TODO add your handling code here:
this.jTextFieldIterations.setEditable(true);
this.jRadioButtonManhattan.setEnabled(true);
this.jRadioButtonEuclidean.setSelected(true);
jLabelDistanceMeasureDiscription.setText("The most popular distance measure which is defined as");
jLabel1DistanceFormula.setIcon(new javax.swing.ImageIcon("C:\\Users\\Thuan Loc\\Documents\\NetBeansProjects\\Data Clustering\\Picture\\Euclidean_Distance.png"));
}//GEN-LAST:event_jRadioButtonMenuItemBisectingKMeansActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
CONST.STOP = true;
this.jLabel4.setVisible(true);
this.jButton2.setEnabled(false);
}//GEN-LAST:event_jButton2ActionPerformed
private void jRadioButtonManhattanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonManhattanActionPerformed
// TODO add your handling code here:
jLabelDistanceMeasureDiscription.setText("A pseudonym is city block distance, which is defined as");
jLabel1DistanceFormula.setIcon(new javax.swing.ImageIcon("C:\\Users\\Thuan Loc\\Documents\\NetBeansProjects\\Data Clustering\\Picture\\Manhattan_Distance.png"));
}//GEN-LAST:event_jRadioButtonManhattanActionPerformed
private void jRadioButtonEuclideanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButtonEuclideanActionPerformed
// TODO add your handling code here:
jLabelDistanceMeasureDiscription.setText("The most popular distance measure which is defined as");
jLabel1DistanceFormula.setIcon(new javax.swing.ImageIcon("C:\\Users\\Thuan Loc\\Documents\\NetBeansProjects\\Data Clustering\\Picture\\Euclidean_Distance.png"));
}//GEN-LAST:event_jRadioButtonEuclideanActionPerformed
private void jButtonTestFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonTestFileActionPerformed
// TODO add your handling code here:
try {
hideStatus();
this.VP.removeAllElements();
jProgressBarTestFile.setValue(0);
jProgressBarTestFile.setStringPainted(true);
this.jButtonTestFile.setEnabled(false);
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
//Instances of javax.swing.SwingWorker are not reusuable, so
//we create new instances as needed.
FR = new File(this.jTextFieldFileChoice.getText());
task = new Task();
task.addPropertyChangeListener(this);
task.execute();
} catch (Exception e) {
}
}//GEN-LAST:event_jButtonTestFileActionPerformed
private void jButtonBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBrowseActionPerformed
// TODO add your handling code here:
FileFilter filter = new ExtensionFileFilter("*.arff", new String[]{"arff"});
JFileChooser fileChooser = new JFileChooser();
// Note: source for ExampleFileFilter can be found in FileChooserDemo,
// under the demo/jfc directory in the Java 2 SDK, Standard Edition
fileChooser.setFileFilter(filter);
int status = fileChooser.showOpenDialog(null);
if (status == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
this.jTextFieldFileChoice.setText(selectedFile.getAbsolutePath());
}
}//GEN-LAST:event_jButtonBrowseActionPerformed
private void jTextFieldFileChoiceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldFileChoiceActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextFieldFileChoiceActionPerformed
private void jButtonAnalysisActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAnalysisActionPerformed
// TODO add your handling code here:
CONST.STOP = false;
this.jTabbedPane.addTab("Performance", this.jPanelPerformance);
this.jButton2.setEnabled(true);
this.jLabel4.setVisible(false);
int K = ensureClusterNumber();
int MaxLoops = ensureIterations();
if (K == -1 || MaxLoops == -1) {
return;
}
this.jTabbedPane.setSelectedIndex(1);
this.jTabbedPane.setEnabledAt(0, false);
int DistanceType = CONST.EUCLIDEAN;
if (this.jRadioButtonManhattan.isSelected()) {
DistanceType = CONST.MANHATTAN;
}
if (this.jRadioButtonMenuItemBasicKMeans.isSelected()) {
Thread thread = new ChartThread(CONST.BASIC_KMEANS, this.VP, K, MaxLoops, this.ClusteringPanelChart, this.jTable1, jLabel4, jButton2, jTabbedPane, DistanceType);
thread.start();
} else if (this.jRadioButtonMenuItemBisectingKMeans.isSelected()) {
Thread thread = new ChartThread(CONST.BISECTING_KMEANS, this.VP, K, MaxLoops, this.ClusteringPanelChart, this.jTable1, jLabel4, jButton2, jTabbedPane, DistanceType);
thread.start();
} else if (this.jRadioButtonMenuItemEM.isSelected()) {
Thread thread = new ChartThread(CONST.EM_KMEANS, this.VP, K, MaxLoops, this.ClusteringPanelChart, this.jTable1, jLabel4, jButton2, jTabbedPane, DistanceType);
thread.start();
} else if (this.jRadioButtonMenuItemKMedoids.isSelected()) {
Thread thread = new ChartThread(CONST.K_MEDOIDS, this.VP, K, MaxLoops, this.ClusteringPanelChart, this.jTable1, jLabel4, jButton2, jTabbedPane, DistanceType);
thread.start();
}
}//GEN-LAST:event_jButtonAnalysisActionPerformed
private void jMenuItemAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemAboutActionPerformed
// TODO add your handling code here:
AboutJDialog aboutJDialog = new AboutJDialog(this, true);
Point O = new Point();
O.setLocation(this.getLocation().x, this.getLocation().y);
O.move(this.getWidth()/2 - aboutJDialog.getWidth()/2, this.getHeight()/2 - aboutJDialog.getHeight()/2);
aboutJDialog.setLocation(O);
aboutJDialog.setVisible(true);
}//GEN-LAST:event_jMenuItemAboutActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private org.math.plot.Plot3DPanel ClusteringPanelChart;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.ButtonGroup buttonGroup2;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButtonAnalysis;
private javax.swing.JButton jButtonBrowse;
private javax.swing.JButton jButtonTestFile;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel1DistanceFormula;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabelDistanceMeasureDiscription;
private javax.swing.JLabel jLabelNofO;
private javax.swing.JLabel jLabelNumOfOName;
private javax.swing.JLabel jLabelSizeOfFileName;
private javax.swing.JLabel jLabelSizeofF;
private javax.swing.JLabel jLabelStatus;
private javax.swing.JMenu jMenuAlgorithm;
private javax.swing.JMenuBar jMenuBar;
private javax.swing.JMenu jMenuHelp;
private javax.swing.JMenuItem jMenuItemAbout;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanelPerformance;
private javax.swing.JPanel jPanelSpecification;
private javax.swing.JProgressBar jProgressBarTestFile;
private javax.swing.JRadioButton jRadioButtonEuclidean;
private javax.swing.JRadioButton jRadioButtonManhattan;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItemBasicKMeans;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItemBisectingKMeans;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItemEM;
private javax.swing.JRadioButtonMenuItem jRadioButtonMenuItemKMedoids;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JPopupMenu.Separator jSeparatorAlgorithm;
private javax.swing.JPopupMenu.Separator jSeparatorHelp;
private javax.swing.JTabbedPane jTabbedPane;
private javax.swing.JTable jTable1;
private javax.swing.JTextField jTextFieldClusterNumber;
private javax.swing.JTextField jTextFieldFileChoice;
private javax.swing.JTextField jTextFieldIterations;
// End of variables declaration//GEN-END:variables
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2010-2013 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.sparserss;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.ClipboardManager;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import de.shandschuh.sparserss.provider.FeedData;
public class EntriesListActivity extends ListActivity implements Requeryable {
private static final int CONTEXTMENU_MARKASREAD_ID = 6;
private static final int CONTEXTMENU_MARKASUNREAD_ID = 7;
private static final int CONTEXTMENU_DELETE_ID = 8;
private static final int CONTEXTMENU_COPYURL = 9;
public static final String EXTRA_SHOWFEEDINFO = "show_feedinfo";
public static final String EXTRA_AUTORELOAD = "autoreload";
private static final String FAVORITES = "favorites";
private static final String ALLENTRIES = "allentries";
private static final String[] FEED_PROJECTION = {FeedData.FeedColumns.NAME,
FeedData.FeedColumns.URL,
FeedData.FeedColumns.ICON,
FeedData.FeedColumns.HIDE_READ
};
private Uri uri;
private EntriesListAdapter entriesListAdapter;
private byte[] iconBytes;
private String feedName;
private long feedId;
private boolean hideRead;
@Override
protected void onCreate(Bundle savedInstanceState) {
if (MainTabActivity.isLightTheme(this)) {
setTheme(R.style.Theme_Light);
}
super.onCreate(savedInstanceState);
feedName = null;
iconBytes = null;
Intent intent = getIntent();
feedId = intent.getLongExtra(FeedData.FeedColumns._ID, 0);
uri = intent.getData();
if (feedId > 0) {
Cursor cursor = getContentResolver().query(FeedData.FeedColumns.CONTENT_URI(feedId), FEED_PROJECTION, null, null, null);
if (cursor.moveToFirst()) {
feedName = cursor.isNull(0) ? cursor.getString(1) : cursor.getString(0);
iconBytes = cursor.getBlob(2);
hideRead = cursor.getInt(3) == 1;
}
cursor.close();
} else {
hideRead = PreferenceManager.getDefaultSharedPreferences(this).getBoolean(new StringBuilder(uri.equals(FeedData.EntryColumns.FAVORITES_CONTENT_URI) ? FAVORITES : ALLENTRIES).append('.').append(FeedData.FeedColumns.HIDE_READ).toString(), false);
}
if (!MainTabActivity.POSTGINGERBREAD && iconBytes != null && iconBytes.length > 0) { // we cannot insert the icon here because it would be overwritten, but we have to reserve the icon here
if (!requestWindowFeature(Window.FEATURE_LEFT_ICON)) {
iconBytes = null;
}
}
setContentView(R.layout.entries);
entriesListAdapter = new EntriesListAdapter(this, uri, intent.getBooleanExtra(EXTRA_SHOWFEEDINFO, false), intent.getBooleanExtra(EXTRA_AUTORELOAD, false), hideRead);
setListAdapter(entriesListAdapter);
if (feedName != null) {
setTitle(feedName);
}
if (iconBytes != null && iconBytes.length > 0) {
int bitmapSizeInDip = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24f, getResources().getDisplayMetrics());
Bitmap bitmap = BitmapFactory.decodeByteArray(iconBytes, 0, iconBytes.length);
if (bitmap != null) {
if (bitmap.getHeight() != bitmapSizeInDip) {
bitmap = Bitmap.createScaledBitmap(bitmap, bitmapSizeInDip, bitmapSizeInDip, false);
}
if (MainTabActivity.POSTGINGERBREAD) {
CompatibilityHelper.setActionBarDrawable(this, new BitmapDrawable(bitmap));
} else {
setFeatureDrawable(Window.FEATURE_LEFT_ICON, new BitmapDrawable(bitmap));
}
}
}
if (RSSOverview.notificationManager != null) {
RSSOverview.notificationManager.cancel(0);
}
getListView().setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
menu.setHeaderTitle(((TextView) ((AdapterView.AdapterContextMenuInfo) menuInfo).targetView.findViewById(android.R.id.text1)).getText());
menu.add(0, CONTEXTMENU_MARKASREAD_ID, Menu.NONE, R.string.contextmenu_markasread).setIcon(android.R.drawable.ic_menu_manage);
menu.add(0, CONTEXTMENU_MARKASUNREAD_ID, Menu.NONE, R.string.contextmenu_markasunread).setIcon(android.R.drawable.ic_menu_manage);
menu.add(0, CONTEXTMENU_DELETE_ID, Menu.NONE, R.string.contextmenu_delete).setIcon(android.R.drawable.ic_menu_delete);
menu.add(0, CONTEXTMENU_COPYURL, Menu.NONE, R.string.contextmenu_copyurl).setIcon(android.R.drawable.ic_menu_share);
}
});
}
@Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
TextView textView = (TextView) view.findViewById(android.R.id.text1);
textView.setTypeface(Typeface.DEFAULT);
textView.setEnabled(false);
view.findViewById(android.R.id.text2).setEnabled(false);
entriesListAdapter.neutralizeReadState();
startActivity(new Intent(Intent.ACTION_VIEW, ContentUris.withAppendedId(uri, id)).putExtra(FeedData.FeedColumns.HIDE_READ, entriesListAdapter.isHideRead()).putExtra(FeedData.FeedColumns.ICON, iconBytes).putExtra(FeedData.FeedColumns.NAME, feedName));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.entrylist, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (menu != null) {
menu.setGroupVisible(R.id.menu_group_0, entriesListAdapter.getCount() > 0);
if (hideRead) {
menu.findItem(R.id.menu_hideread).setChecked(true).setTitle(R.string.contextmenu_showread).setIcon(android.R.drawable.ic_menu_view);
} else {
menu.findItem(R.id.menu_hideread).setChecked(false).setTitle(R.string.contextmenu_hideread).setIcon(android.R.drawable.ic_menu_close_clear_cancel);
}
}
return true;
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_markasread: {
new Thread() { // the update process takes some time
public void run() {
getContentResolver().update(uri, RSSOverview.getReadContentValues(), null, null);
}
}.start();
entriesListAdapter.markAsRead();
break;
}
case R.id.menu_markasunread: {
new Thread() { // the update process takes some time
public void run() {
getContentResolver().update(uri, RSSOverview.getUnreadContentValues(), null, null);
}
}.start();
entriesListAdapter.markAsUnread();
break;
}
case R.id.menu_hideread: {
hideRead = !entriesListAdapter.isHideRead();
if (hideRead) {
item.setChecked(false).setTitle(R.string.contextmenu_hideread).setIcon(android.R.drawable.ic_menu_close_clear_cancel);
entriesListAdapter.setHideRead(true);
} else {
item.setChecked(true).setTitle(R.string.contextmenu_showread).setIcon(android.R.drawable.ic_menu_view);
entriesListAdapter.setHideRead(false);
}
setHideReadFromUri();
break;
}
case R.id.menu_deleteread: {
new Thread() { // the delete process takes some time
public void run() {
String selection = Strings.READDATE_GREATERZERO+Strings.DB_AND+" ("+Strings.DB_EXCUDEFAVORITE+")";
getContentResolver().delete(uri, selection, null);
FeedData.deletePicturesOfFeed(EntriesListActivity.this, uri, selection);
runOnUiThread(new Runnable() {
public void run() {
entriesListAdapter.getCursor().requery();
}
});
}
}.start();
break;
}
case R.id.menu_deleteallentries: {
Builder builder = new AlertDialog.Builder(this);
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setTitle(R.string.contextmenu_deleteallentries);
builder.setMessage(R.string.question_areyousure);
builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new Thread() {
public void run() {
getContentResolver().delete(uri, Strings.DB_EXCUDEFAVORITE, null);
runOnUiThread(new Runnable() {
public void run() {
entriesListAdapter.getCursor().requery();
}
});
}
}.start();
}
});
builder.setNegativeButton(android.R.string.no, null);
builder.show();
break;
}
case CONTEXTMENU_MARKASREAD_ID: {
long id = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id;
getContentResolver().update(ContentUris.withAppendedId(uri, id), RSSOverview.getReadContentValues(), null, null);
entriesListAdapter.markAsRead(id);
break;
}
case CONTEXTMENU_MARKASUNREAD_ID: {
long id = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id;
getContentResolver().update(ContentUris.withAppendedId(uri, id), RSSOverview.getUnreadContentValues(), null, null);
entriesListAdapter.markAsUnread(id);
break;
}
case CONTEXTMENU_DELETE_ID: {
long id = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id;
getContentResolver().delete(ContentUris.withAppendedId(uri, id), null, null);
FeedData.deletePicturesOfEntry(Long.toString(id));
entriesListAdapter.getCursor().requery(); // we have no other choice
break;
}
case CONTEXTMENU_COPYURL: {
((ClipboardManager) getSystemService(CLIPBOARD_SERVICE)).setText(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).targetView.getTag().toString());
break;
}
}
return true;
}
private void setHideReadFromUri() {
if (feedId > 0) {
ContentValues values = new ContentValues();
values.put(FeedData.FeedColumns.HIDE_READ, hideRead);
getContentResolver().update(FeedData.FeedColumns.CONTENT_URI(feedId), values, null, null);
} else {
Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putBoolean(new StringBuilder(uri.equals(FeedData.EntryColumns.FAVORITES_CONTENT_URI) ? FAVORITES : ALLENTRIES).append('.').append(FeedData.FeedColumns.HIDE_READ).toString(), hideRead);
editor.commit();
}
}
@Override
public void requery() {
if (entriesListAdapter != null) {
entriesListAdapter.reloadCursor();
}
}
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2010-2013 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.sparserss;
import java.util.Date;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.animation.Animation;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import de.shandschuh.sparserss.provider.FeedData;
public class EntryActivity extends Activity {
/*
private static final String NEWLINE = "\n";
private static final String BR = "<br/>";
*/
private static final String TEXT_HTML = "text/html";
private static final String UTF8 = "utf-8";
private static final String OR_DATE = " or date ";
private static final String DATE = "(date=";
private static final String AND_ID = " and _id";
private static final String ASC = "date asc, _id desc limit 1";
private static final String DESC = "date desc, _id asc limit 1";
private static final String CSS = "<head><style type=\"text/css\">body {max-width: 100%}\nimg {max-width: 100%; height: auto;}\ndiv[style] {max-width: 100%;}\npre {white-space: pre-wrap;}</style></head>";
private static final String FONT_START = CSS+"<body link=\"#97ACE5\" text=\"#C0C0C0\">";
private static final String FONT_FONTSIZE_START = CSS+"<body link=\"#97ACE5\" text=\"#C0C0C0\"><font size=\"+";
private static final String FONTSIZE_START = "<font size=\"+";
private static final String FONTSIZE_MIDDLE = "\">";
private static final String FONTSIZE_END = "</font>";
private static final String FONT_END = "</font><br/><br/><br/><br/></body>";
private static final String BODY_START = "<body>";
private static final String BODY_END = "<br/><br/><br/><br/></body>";
private static final int BUTTON_ALPHA = 180;
private static final String IMAGE_ENCLOSURE = "[@]image/";
private static final String TEXTPLAIN = "text/plain";
private static final String BRACKET = " (";
private int titlePosition;
private int datePosition;
private int abstractPosition;
private int linkPosition;
private int feedIdPosition;
private int favoritePosition;
private int readDatePosition;
private int enclosurePosition;
private int authorPosition;
private String _id;
private String _nextId;
private String _previousId;
private Uri uri;
private Uri parentUri;
private int feedId;
boolean favorite;
private boolean hideRead;
private boolean canShowIcon;
private byte[] iconBytes;
private String feedName;
private WebView webView;
private WebView webView0; // only needed for the animation
private ViewFlipper viewFlipper;
private ImageButton nextButton;
private ImageButton urlButton;
private ImageButton previousButton;
private ImageButton playButton;
int scrollX;
int scrollY;
private String link;
private LayoutParams layoutParams;
private View content;
private SharedPreferences preferences;
private boolean localPictures;
private TextView titleTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
if (MainTabActivity.isLightTheme(this)) {
setTheme(R.style.Theme_Light);
}
super.onCreate(savedInstanceState);
int titleId = -1;
if (MainTabActivity.POSTGINGERBREAD) {
canShowIcon = true;
setContentView(R.layout.entry);
try {
/* This is a trick as com.android.internal.R.id.action_bar_title is not directly accessible */
titleId = (Integer) Class.forName("com.android.internal.R$id").getField("action_bar_title").get(null);
} catch (Exception exception) {
}
} else {
canShowIcon = requestWindowFeature(Window.FEATURE_LEFT_ICON);
setContentView(R.layout.entry);
titleId = android.R.id.title;
}
try {
titleTextView = (TextView) findViewById(titleId);
titleTextView.setSingleLine(true);
titleTextView.setHorizontallyScrolling(true);
titleTextView.setMarqueeRepeatLimit(1);
titleTextView.setEllipsize(TextUtils.TruncateAt.MARQUEE);
titleTextView.setFocusable(true);
titleTextView.setFocusableInTouchMode(true);
} catch (Exception e) {
// just in case for non standard android, nullpointer etc
}
uri = getIntent().getData();
parentUri = FeedData.EntryColumns.PARENT_URI(uri.getPath());
hideRead = getIntent().getBooleanExtra(FeedData.FeedColumns.HIDE_READ, false);
iconBytes = getIntent().getByteArrayExtra(FeedData.FeedColumns.ICON);
feedName = getIntent().getStringExtra(FeedData.FeedColumns.NAME);
feedId = 0;
Cursor entryCursor = getContentResolver().query(uri, null, null, null, null);
titlePosition = entryCursor.getColumnIndex(FeedData.EntryColumns.TITLE);
datePosition = entryCursor.getColumnIndex(FeedData.EntryColumns.DATE);
abstractPosition = entryCursor.getColumnIndex(FeedData.EntryColumns.ABSTRACT);
linkPosition = entryCursor.getColumnIndex(FeedData.EntryColumns.LINK);
feedIdPosition = entryCursor.getColumnIndex(FeedData.EntryColumns.FEED_ID);
favoritePosition = entryCursor.getColumnIndex(FeedData.EntryColumns.FAVORITE);
readDatePosition = entryCursor.getColumnIndex(FeedData.EntryColumns.READDATE);
enclosurePosition = entryCursor.getColumnIndex(FeedData.EntryColumns.ENCLOSURE);
authorPosition = entryCursor.getColumnIndex(FeedData.EntryColumns.AUTHOR);
entryCursor.close();
if (RSSOverview.notificationManager == null) {
RSSOverview.notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
nextButton = (ImageButton) findViewById(R.id.next_button);
urlButton = (ImageButton) findViewById(R.id.url_button);
urlButton.setAlpha(BUTTON_ALPHA+30);
previousButton = (ImageButton) findViewById(R.id.prev_button);
playButton = (ImageButton) findViewById(R.id.play_button);
playButton.setAlpha(BUTTON_ALPHA);
viewFlipper = (ViewFlipper) findViewById(R.id.content_flipper);
layoutParams = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
webView = new WebView(this);
viewFlipper.addView(webView, layoutParams);
OnKeyListener onKeyEventListener = new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (keyCode == 92 || keyCode == 94) {
scrollUp();
return true;
} else if (keyCode == 93 || keyCode == 95) {
scrollDown();
return true;
}
}
return false;
}
};
webView.setOnKeyListener(onKeyEventListener);
content = findViewById(R.id.entry_content);
webView0 = new WebView(this);
webView0.setOnKeyListener(onKeyEventListener);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
final boolean gestures = preferences.getBoolean(Strings.SETTINGS_GESTURESENABLED, true);
final GestureDetector gestureDetector = new GestureDetector(this, new OnGestureListener() {
public boolean onDown(MotionEvent e) {
return false;
}
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
if (gestures) {
if (Math.abs(velocityY) < Math.abs(velocityX)) {
if (velocityX > 800) {
if (previousButton.isEnabled()) {
previousEntry(true);
}
} else if (velocityX < -800) {
if (nextButton.isEnabled()) {
nextEntry(true);
}
}
}
}
return false;
}
public void onLongPress(MotionEvent e) {
}
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
return false;
}
public void onShowPress(MotionEvent e) {
}
public boolean onSingleTapUp(MotionEvent e) {
return false;
}
});
OnTouchListener onTouchListener = new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
};
webView.setOnTouchListener(onTouchListener);
content.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
gestureDetector.onTouchEvent(event);
return true; // different to the above one!
}
});
webView0.setOnTouchListener(onTouchListener);
scrollX = 0;
scrollY = 0;
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
webView.restoreState(savedInstanceState);
}
@Override
protected void onResume() {
super.onResume();
if (RSSOverview.notificationManager != null) {
RSSOverview.notificationManager.cancel(0);
}
uri = getIntent().getData();
parentUri = FeedData.EntryColumns.PARENT_URI(uri.getPath());
if (MainTabActivity.POSTGINGERBREAD) {
CompatibilityHelper.onResume(webView);
}
reload();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
private void reload() {
if (_id != null && _id.equals(uri.getLastPathSegment())) {
return;
}
_id = uri.getLastPathSegment();
ContentValues values = new ContentValues();
values.put(FeedData.EntryColumns.READDATE, System.currentTimeMillis());
Cursor entryCursor = getContentResolver().query(uri, null, null, null, null);
if (entryCursor.moveToFirst()) {
String abstractText = entryCursor.getString(abstractPosition);
if (entryCursor.isNull(readDatePosition)) {
getContentResolver().update(uri, values, new StringBuilder(FeedData.EntryColumns.READDATE).append(Strings.DB_ISNULL).toString(), null);
}
if (abstractText == null || abstractText.trim().length() == 0) {
link = entryCursor.getString(linkPosition);
entryCursor.close();
finish();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(link)));
} else {
link = entryCursor.getString(linkPosition);
String title = entryCursor.getString(titlePosition);
setTitle(title == null || title.length() == 0 ? link : title);
if (titleTextView != null) {
titleTextView.requestFocus(); // restart ellipsize
}
int _feedId = entryCursor.getInt(feedIdPosition);
if (feedId != _feedId) {
if (feedId != 0) {
iconBytes = null; // triggers re-fetch of the icon
}
feedId = _feedId;
}
if (feedName == null || (canShowIcon && (iconBytes == null || iconBytes.length == 0))) {
Cursor feedCursor = getContentResolver().query(FeedData.FeedColumns.CONTENT_URI(Integer.toString(feedId)), new String[] {FeedData.FeedColumns._ID, FeedData.FeedColumns.NAME, FeedData.FeedColumns.URL, FeedData.FeedColumns.ICON}, null, null, null);
if (feedCursor.moveToFirst()) {
feedName = feedCursor.isNull(1) ? feedCursor.getString(2) : feedCursor.getString(1);
iconBytes = feedCursor.getBlob(3);
}
feedCursor.close();
}
if (canShowIcon) {
Drawable icon = null;
if (iconBytes != null && iconBytes.length > 0) {
int bitmapSizeInDip = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24f, getResources().getDisplayMetrics());
Bitmap bitmap = BitmapFactory.decodeByteArray(iconBytes, 0, iconBytes.length);
if (bitmap != null) {
if (bitmap.getHeight() != bitmapSizeInDip) {
bitmap = Bitmap.createScaledBitmap(bitmap, bitmapSizeInDip, bitmapSizeInDip, false);
}
icon = new BitmapDrawable(bitmap);
}
}
if (MainTabActivity.POSTGINGERBREAD) {
if (icon == null) {
icon = getResources().getDrawable(de.shandschuh.sparserss.R.drawable.icon);
}
CompatibilityHelper.setActionBarDrawable(this, icon);
} else {
setFeatureDrawable(Window.FEATURE_LEFT_ICON, icon);
}
}
long timestamp = entryCursor.getLong(datePosition);
Date date = new Date(timestamp);
StringBuilder dateStringBuilder = new StringBuilder(DateFormat.getDateFormat(this).format(date)).append(' ').append(DateFormat.getTimeFormat(this).format(date));
String author = entryCursor.getString(authorPosition);
if (feedName != null && feedName.length() > 0) {
dateStringBuilder.append(' ').append(feedName);
}
if (author != null && author.length() > 0) {
dateStringBuilder.append(BRACKET).append(author).append(')');
}
((TextView) findViewById(R.id.entry_date)).setText(dateStringBuilder);
final ImageView imageView = (ImageView) findViewById(android.R.id.icon);
favorite = entryCursor.getInt(favoritePosition) == 1;
imageView.setImageResource(favorite ? android.R.drawable.star_on : android.R.drawable.star_off);
imageView.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
favorite = !favorite;
imageView.setImageResource(favorite ? android.R.drawable.star_on : android.R.drawable.star_off);
ContentValues values = new ContentValues();
values.put(FeedData.EntryColumns.FAVORITE, favorite ? 1 : 0);
getContentResolver().update(uri, values, null, null);
}
});
// loadData does not recognize the encoding without correct html-header
localPictures = abstractText.indexOf(Strings.IMAGEID_REPLACEMENT) > -1;
if (localPictures) {
abstractText = abstractText.replace(Strings.IMAGEID_REPLACEMENT, _id+Strings.IMAGEFILE_IDSEPARATOR);
}
if (preferences.getBoolean(Strings.SETTINGS_DISABLEPICTURES, false)) {
abstractText = abstractText.replaceAll(Strings.HTML_IMG_REGEX, Strings.EMPTY);
webView.getSettings().setBlockNetworkImage(true);
} else {
if (webView.getSettings().getBlockNetworkImage()) {
/*
* setBlockNetwortImage(false) calls postSync, which takes time,
* so we clean up the html first and change the value afterwards
*/
webView.loadData(Strings.EMPTY, TEXT_HTML, UTF8);
webView.getSettings().setBlockNetworkImage(false);
}
}
int fontsize = Integer.parseInt(preferences.getString(Strings.SETTINGS_FONTSIZE, Strings.ONE));
/*
if (abstractText.indexOf('<') > -1 && abstractText.indexOf('>') > -1) {
abstractText = abstractText.replace(NEWLINE, BR);
}
*/
if (MainTabActivity.isLightTheme(this) || preferences.getBoolean(Strings.SETTINGS_BLACKTEXTONWHITE, false)) {
if (fontsize > 0) {
webView.loadDataWithBaseURL(null, new StringBuilder(CSS).append(FONTSIZE_START).append(fontsize).append(FONTSIZE_MIDDLE).append(abstractText).append(FONTSIZE_END).toString(), TEXT_HTML, UTF8, null);
} else {
webView.loadDataWithBaseURL(null, new StringBuilder(CSS).append(BODY_START).append(abstractText).append(BODY_END).toString(), TEXT_HTML, UTF8, null);
}
webView.setBackgroundColor(Color.WHITE);
content.setBackgroundColor(Color.WHITE);
} else {
if (fontsize > 0) {
webView.loadDataWithBaseURL(null, new StringBuilder(FONT_FONTSIZE_START).append(fontsize).append(FONTSIZE_MIDDLE).append(abstractText).append(FONT_END).toString(), TEXT_HTML, UTF8, null);
} else {
webView.loadDataWithBaseURL(null, new StringBuilder(FONT_START).append(abstractText).append(BODY_END).toString(), TEXT_HTML, UTF8, null);
}
webView.setBackgroundColor(Color.BLACK);
content.setBackgroundColor(Color.BLACK);
}
if (link != null && link.length() > 0) {
urlButton.setEnabled(true);
urlButton.setAlpha(BUTTON_ALPHA+20);
urlButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse(link)), 0);
}
});
} else {
urlButton.setEnabled(false);
urlButton.setAlpha(80);
}
final String enclosure = entryCursor.getString(enclosurePosition);
if (enclosure != null && enclosure.length() > 6 && enclosure.indexOf(IMAGE_ENCLOSURE) == -1) {
playButton.setVisibility(View.VISIBLE);
playButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final int position1 = enclosure.indexOf(Strings.ENCLOSURE_SEPARATOR);
final int position2 = enclosure.indexOf(Strings.ENCLOSURE_SEPARATOR, position1+3);
final Uri uri = Uri.parse(enclosure.substring(0, position1));
if (preferences.getBoolean(Strings.SETTINGS_ENCLOSUREWARNINGSENABLED, true)) {
Builder builder = new AlertDialog.Builder(EntryActivity.this);
builder.setTitle(R.string.question_areyousure);
builder.setIcon(android.R.drawable.ic_dialog_alert);
if (position2+4 > enclosure.length()) {
builder.setMessage(getString(R.string.question_playenclosure, uri, position2+4 > enclosure.length() ? Strings.QUESTIONMARKS : enclosure.substring(position2+3)));
} else {
try {
builder.setMessage(getString(R.string.question_playenclosure, uri, (Integer.parseInt(enclosure.substring(position2+3)) / 1024f)+getString(R.string.kb)));
} catch (Exception e) {
builder.setMessage(getString(R.string.question_playenclosure, uri, enclosure.substring(position2+3)));
}
}
builder.setCancelable(true);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
showEnclosure(uri, enclosure, position1, position2);
}
});
builder.setNeutralButton(R.string.button_alwaysokforall, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
preferences.edit().putBoolean(Strings.SETTINGS_ENCLOSUREWARNINGSENABLED, false).commit();
showEnclosure(uri, enclosure, position1, position2);
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
} else {
showEnclosure(uri, enclosure, position1, position2);
}
}
});
} else {
playButton.setVisibility(View.GONE);
}
entryCursor.close();
setupButton(previousButton, false, timestamp);
setupButton(nextButton, true, timestamp);
webView.scrollTo(scrollX, scrollY); // resets the scrolling
}
} else {
entryCursor.close();
}
/*
new Thread() {
public void run() {
sendBroadcast(new Intent(Strings.ACTION_UPDATEWIDGET)); // this is slow
}
}.start();
*/
}
private void showEnclosure(Uri uri, String enclosure, int position1, int position2) {
try {
startActivityForResult(new Intent(Intent.ACTION_VIEW).setDataAndType(uri, enclosure.substring(position1+3, position2)), 0);
} catch (Exception e) {
try {
startActivityForResult(new Intent(Intent.ACTION_VIEW, uri), 0); // fallbackmode - let the browser handle this
} catch (Throwable t) {
Toast.makeText(EntryActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
private void setupButton(ImageButton button, final boolean successor, long date) {
StringBuilder queryString = new StringBuilder(DATE).append(date).append(AND_ID).append(successor ? '>' : '<').append(_id).append(')').append(OR_DATE).append(successor ? '<' : '>').append(date);
if (hideRead) {
queryString.append(Strings.DB_AND).append(EntriesListAdapter.READDATEISNULL);
}
Cursor cursor = getContentResolver().query(parentUri, new String[] {FeedData.EntryColumns._ID}, queryString.toString() , null, successor ? DESC : ASC);
if (cursor.moveToFirst()) {
button.setEnabled(true);
button.setAlpha(BUTTON_ALPHA);
final String id = cursor.getString(0);
if (successor) {
_nextId = id;
} else {
_previousId = id;
}
button.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if (successor) {
nextEntry(false);
} else {
previousEntry(false);
}
}
});
} else {
button.setEnabled(false);
button.setAlpha(60);
}
cursor.close();
}
private void switchEntry(String id, boolean animate, Animation inAnimation, Animation outAnimation) {
uri = parentUri.buildUpon().appendPath(id).build();
getIntent().setData(uri);
scrollX = 0;
scrollY = 0;
if (animate) {
WebView dummy = webView; // switch reference
webView = webView0;
webView0 = dummy;
}
reload();
if (animate) {
viewFlipper.setInAnimation(inAnimation);
viewFlipper.setOutAnimation(outAnimation);
viewFlipper.addView(webView, layoutParams);
viewFlipper.showNext();
viewFlipper.removeViewAt(0);
}
}
private void nextEntry(boolean animate) {
switchEntry(_nextId, animate, Animations.SLIDE_IN_RIGHT, Animations.SLIDE_OUT_LEFT);
}
private void previousEntry(boolean animate) {
switchEntry(_previousId, animate, Animations.SLIDE_IN_LEFT, Animations.SLIDE_OUT_RIGHT);
}
@Override
protected void onPause() {
super.onPause();
if (MainTabActivity.POSTGINGERBREAD) {
CompatibilityHelper.onPause(webView);
}
scrollX = webView.getScrollX();
scrollY = webView.getScrollY();
}
@Override
protected void onSaveInstanceState(Bundle outState)
{
webView.saveState(outState);
super.onSaveInstanceState(outState);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.entry, menu);
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_copytoclipboard: {
if (link != null) {
((ClipboardManager) getSystemService(CLIPBOARD_SERVICE)).setText(link);
}
break;
}
case R.id.menu_delete: {
getContentResolver().delete(uri, null, null);
if (localPictures) {
FeedData.deletePicturesOfEntry(_id);
}
if (nextButton.isEnabled()) {
nextButton.performClick();
} else {
if (previousButton.isEnabled()) {
previousButton.performClick();
} else {
finish();
}
}
break;
}
case R.id.menu_share: {
if (link != null) {
startActivity(Intent.createChooser(new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_TEXT, link).setType(TEXTPLAIN), getString(R.string.menu_share)));
}
break;
}
}
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (keyCode == 92 || keyCode == 94) {
scrollUp();
return true;
} else if (keyCode == 93 || keyCode == 95) {
scrollDown();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
private void scrollUp() {
if (webView != null) {
webView.pageUp(false);
}
}
private void scrollDown() {
if (webView != null) {
webView.pageDown(false);
}
}
/**
* Works around android issue 6191
*/
@Override
public void unregisterReceiver(BroadcastReceiver receiver) {
try {
super.unregisterReceiver(receiver);
} catch (Exception e) {
// do nothing
}
}
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2010-2013 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.sparserss.handler;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.text.Html;
import de.shandschuh.sparserss.Strings;
import de.shandschuh.sparserss.provider.FeedData;
import de.shandschuh.sparserss.provider.FeedDataContentProvider;
import de.shandschuh.sparserss.service.FetcherService;
public class RSSHandler extends DefaultHandler {
private static final String ANDRHOMBUS = "&#";
private static final String TAG_RSS = "rss";
private static final String TAG_RDF = "rdf";
private static final String TAG_FEED = "feed";
private static final String TAG_ENTRY = "entry";
private static final String TAG_ITEM = "item";
private static final String TAG_UPDATED = "updated";
private static final String TAG_TITLE = "title";
private static final String TAG_LINK = "link";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_MEDIA_DESCRIPTION = "media:description";
private static final String TAG_CONTENT = "content";
private static final String TAG_MEDIA_CONTENT = "media:content";
private static final String TAG_ENCODEDCONTENT = "encoded";
private static final String TAG_SUMMARY = "summary";
private static final String TAG_PUBDATE = "pubDate";
private static final String TAG_DATE = "date";
private static final String TAG_LASTBUILDDATE = "lastBuildDate";
private static final String TAG_ENCLOSURE = "enclosure";
private static final String TAG_GUID = "guid";
private static final String TAG_AUTHOR = "author";
private static final String TAG_NAME = "name";
private static final String TAG_CREATOR = "creator";
private static final String TAG_ENCLOSUREURL = "url";
private static final String TAG_ENCLOSURETYPE = "type";
private static final String TAG_ENCLOSURELENGTH = "length";
private static final String ATTRIBUTE_URL = "url";
private static final String ATTRIBUTE_HREF = "href";
private static final String ATTRIBUTE_TYPE = "type";
private static final String ATTRIBUTE_LENGTH = "length";
private static final String ATTRIBUTE_REL = "rel";
private static final String UTF8 = "UTF-8";
private static final String PERCENT = "%";
/** This can be any valid filename character sequence which does not contain '%' */
private static final String PERCENT_REPLACE = "____";
private static final String[] TIMEZONES = {"MEST", "EST", "PST"};
private static final String[] TIMEZONES_REPLACE = {"+0200", "-0500", "-0800"};
private static final int TIMEZONES_COUNT = 3;
private static long KEEP_TIME = 345600000l; // 4 days
private static final DateFormat[] PUBDATE_DATEFORMATS = {
new SimpleDateFormat("EEE', 'd' 'MMM' 'yyyy' 'HH:mm:ss' 'Z", Locale.US),
new SimpleDateFormat("d' 'MMM' 'yyyy' 'HH:mm:ss' 'Z", Locale.US),
new SimpleDateFormat("EEE', 'd' 'MMM' 'yyyy' 'HH:mm:ss' 'z", Locale.US),
};
private static final int PUBDATEFORMAT_COUNT = 3;
private static final DateFormat[] UPDATE_DATEFORMATS = {
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"),
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSz", Locale.US),
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US),
};
private static final int DATEFORMAT_COUNT = 3;
private static final String Z = "Z";
private static final String GMT = "GMT";
private static final StringBuilder DB_FAVORITE = new StringBuilder(" AND (").append(Strings.DB_EXCUDEFAVORITE).append(')');
private static final Pattern imgPattern = Pattern.compile("<img src=\\s*['\"]([^'\"]+)['\"][^>]*>", Pattern.CASE_INSENSITIVE); // middle () is group 1; s* is important for non-whitespaces; ' also usable
private Context context;
private Date lastUpdateDate;
String id;
private boolean titleTagEntered;
private boolean updatedTagEntered;
private boolean linkTagEntered;
private boolean descriptionTagEntered;
private boolean pubDateTagEntered;
private boolean dateTagEntered;
private boolean lastUpdateDateTagEntered;
private boolean guidTagEntered;
private StringBuilder title;
private StringBuilder dateStringBuilder;
private Date entryDate;
private StringBuilder entryLink;
private StringBuilder description;
private StringBuilder enclosure;
private Uri feedEntiresUri;
private int newCount;
private boolean feedRefreshed;
private String feedTitle;
private String feedBaseUrl;
private boolean done;
private Date keepDateBorder;
private InputStream inputStream;
private Reader reader;
private boolean fetchImages;
private boolean cancelled;
private Date lastBuildDate;
private long realLastUpdate;
private long now;
private StringBuilder guid;
private boolean efficientFeedParsing;
private boolean authorTagEntered;
private StringBuilder author;
private boolean nameTagEntered;
private boolean enclosureTagEntered;
private boolean enclosureUrlTagEntered;
private boolean enclosureTypeTagEntered;
private boolean enclosureLengthTagEntered;
private StringBuilder enclosureUrl;
private StringBuilder enclosureType;
private StringBuilder enclosureLength;
public RSSHandler(Context context) {
KEEP_TIME = Long.parseLong(PreferenceManager.getDefaultSharedPreferences(context).getString(Strings.SETTINGS_KEEPTIME, "4"))*86400000l;
this.context = context;
this.efficientFeedParsing = true;
}
public void init(Date lastUpdateDate, final String id, String title, String url) {
final long keepDateBorderTime = KEEP_TIME > 0 ? System.currentTimeMillis()-KEEP_TIME : 0;
keepDateBorder = new Date(keepDateBorderTime);
this.lastUpdateDate = lastUpdateDate;
this.id = id;
feedEntiresUri = FeedData.EntryColumns.CONTENT_URI(id);
final String query = new StringBuilder(FeedData.EntryColumns.DATE).append('<').append(keepDateBorderTime).append(DB_FAVORITE).toString();
FeedData.deletePicturesOfFeed(context, feedEntiresUri, query);
context.getContentResolver().delete(feedEntiresUri, query, null);
newCount = 0;
feedRefreshed = false;
feedTitle = title;
initFeedBaseUrl(url);
this.title = null;
this.dateStringBuilder = null;
this.entryLink = null;
this.description = null;
this.enclosure = null;
inputStream = null;
reader = null;
entryDate = null;
lastBuildDate = null;
realLastUpdate = lastUpdateDate.getTime();
done = false;
cancelled = false;
titleTagEntered = false;
updatedTagEntered = false;
linkTagEntered = false;
descriptionTagEntered = false;
pubDateTagEntered = false;
dateTagEntered = false;
lastUpdateDateTagEntered = false;
now = System.currentTimeMillis();
guid = null;
guidTagEntered = false;
authorTagEntered = false;
author = null;
enclosureTagEntered = false;
enclosureUrlTagEntered = false;
enclosureUrl = null;
enclosureTypeTagEntered = false;
enclosureType = null;
enclosureLengthTagEntered = false;
enclosureLength = null;
}
public void initFeedBaseUrl(String url) {
int index = url.indexOf('/', 8); // this also covers https://
if (index > -1) {
feedBaseUrl = url.substring(0, index);
} else {
feedBaseUrl = null;
}
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (TAG_UPDATED.equals(localName)) {
updatedTagEntered = true;
dateStringBuilder = new StringBuilder();
} else if (TAG_ENTRY.equals(localName) || TAG_ITEM.equals(localName)) {
description = null;
entryLink = null;
if (!feedRefreshed) {
ContentValues values = new ContentValues();
if (feedTitle == null && title != null && title.length() > 0) {
values.put(FeedData.FeedColumns.NAME, title.toString().trim());
}
values.put(FeedData.FeedColumns.ERROR, (String) null);
values.put(FeedData.FeedColumns.LASTUPDATE, System.currentTimeMillis() - 1000);
if (lastBuildDate != null) {
realLastUpdate = Math.max(entryDate != null && entryDate.after(lastBuildDate) ? entryDate.getTime() : lastBuildDate.getTime(), realLastUpdate);
} else {
realLastUpdate = Math.max(entryDate != null ? entryDate.getTime() : System.currentTimeMillis() - 1000, realLastUpdate);
}
values.put(FeedData.FeedColumns.REALLASTUPDATE, realLastUpdate);
context.getContentResolver().update(FeedData.FeedColumns.CONTENT_URI(id), values, null, null);
title = null;
feedRefreshed = true;
}
} else if (TAG_TITLE.equals(localName)) {
if (title == null) {
titleTagEntered = true;
title = new StringBuilder();
}
} else if (TAG_LINK.equals(localName)) {
if (authorTagEntered) {
return;
}
if (TAG_ENCLOSURE.equals(attributes.getValue(Strings.EMPTY, ATTRIBUTE_REL))) {
startEnclosure(attributes, attributes.getValue(Strings.EMPTY, ATTRIBUTE_HREF));
} else if (entryLink == null || qName.equals(localName)) {
// this indicates either there is no link yet or it is a non prefix tag which is preferred
entryLink = new StringBuilder();
boolean foundLink = false;
for (int n = 0, i = attributes.getLength(); n < i; n++) {
if (ATTRIBUTE_HREF.equals(attributes.getLocalName(n))) {
if (attributes.getValue(n) != null) {
entryLink.append(attributes.getValue(n));
foundLink = true;
linkTagEntered = false;
} else {
linkTagEntered = true;
}
break;
}
}
if (!foundLink) {
linkTagEntered = true;
}
}
} else if ((TAG_DESCRIPTION.equals(localName) && !TAG_MEDIA_DESCRIPTION.equals(qName)) || (TAG_CONTENT.equals(localName) && !TAG_MEDIA_CONTENT.equals(qName))) {
descriptionTagEntered = true;
description = new StringBuilder();
} else if (TAG_SUMMARY.equals(localName)) {
if (description == null) {
descriptionTagEntered = true;
description = new StringBuilder();
}
} else if (TAG_PUBDATE.equals(localName)) {
pubDateTagEntered = true;
dateStringBuilder = new StringBuilder();
} else if (TAG_DATE.equals(localName)) {
dateTagEntered = true;
dateStringBuilder = new StringBuilder();
} else if (TAG_LASTBUILDDATE.equals(localName)) {
lastUpdateDateTagEntered = true;
dateStringBuilder = new StringBuilder();
} else if (TAG_ENCODEDCONTENT.equals(localName)) {
descriptionTagEntered = true;
description = new StringBuilder();
} else if (TAG_ENCLOSURE.equals(localName)) {
enclosureTagEntered = true;
startEnclosure(attributes, attributes.getValue(Strings.EMPTY, ATTRIBUTE_URL));
} else if (TAG_GUID.equals(localName)) {
guidTagEntered = true;
guid = new StringBuilder();
} else if (TAG_AUTHOR.equals(localName) || TAG_CREATOR.equals(localName)) {
authorTagEntered = true;
if (TAG_CREATOR.equals(localName)) {
nameTagEntered = true; // we simulate the existence of a name tag to trigger the characters(..) method
}
if (author == null) {
author = new StringBuilder();
} else if (author.length() > 0){
// this indicates multiple authors
author.append(Strings.COMMASPACE);
}
} else if (TAG_NAME.equals(localName)) {
nameTagEntered = true;
} else if (enclosureTagEntered) {
if (TAG_ENCLOSUREURL.equals(localName)) {
enclosureUrlTagEntered = true;
enclosureUrl = new StringBuilder();
} else if (TAG_ENCLOSURETYPE.equals(localName)) {
enclosureTypeTagEntered = true;
enclosureType = new StringBuilder();
} else if (TAG_ENCLOSURELENGTH.equals(localName)) {
enclosureLengthTagEntered = true;
enclosureLength = new StringBuilder();
}
}
}
private void startEnclosure(Attributes attributes, String url) {
if (enclosure == null && url != null && url.length() > 0) { // fetch the first enclosure only
enclosure = new StringBuilder(url);
enclosure.append(Strings.ENCLOSURE_SEPARATOR);
String value = attributes.getValue(Strings.EMPTY, ATTRIBUTE_TYPE);
if (value != null) {
enclosure.append(value);
}
enclosure.append(Strings.ENCLOSURE_SEPARATOR);
value = attributes.getValue(Strings.EMPTY, ATTRIBUTE_LENGTH);
if (value != null) {
enclosure.append(value);
}
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (titleTagEntered) {
title.append(ch, start, length);
} else if (updatedTagEntered) {
dateStringBuilder.append(ch, start, length);
} else if (linkTagEntered) {
entryLink.append(ch, start, length);
} else if (descriptionTagEntered) {
description.append(ch, start, length);
} else if (pubDateTagEntered) {
dateStringBuilder.append(ch, start, length);
} else if (dateTagEntered) {
dateStringBuilder.append(ch, start, length);
} else if (lastUpdateDateTagEntered) {
dateStringBuilder.append(ch, start, length);
} else if (guidTagEntered) {
guid.append(ch, start, length);
} else if (authorTagEntered && nameTagEntered) {
author.append(ch, start, length);
} else if (enclosureUrlTagEntered) {
enclosureUrl.append(ch, start, length);
} else if (enclosureTypeTagEntered) {
enclosureType.append(ch, start, length);
} else if (enclosureLengthTagEntered) {
enclosureLength.append(ch, start, length);
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (TAG_TITLE.equals(localName)) {
titleTagEntered = false;
} else if ((TAG_DESCRIPTION.equals(localName) && !TAG_MEDIA_DESCRIPTION.equals(qName)) || TAG_SUMMARY.equals(localName) || (TAG_CONTENT.equals(localName) && !TAG_MEDIA_CONTENT.equals(qName)) || TAG_ENCODEDCONTENT.equals(localName)) {
descriptionTagEntered = false;
} else if (TAG_LINK.equals(localName)) {
linkTagEntered = false;
} else if (TAG_UPDATED.equals(localName)) {
entryDate = parseUpdateDate(dateStringBuilder.toString());
updatedTagEntered = false;
} else if (TAG_PUBDATE.equals(localName)) {
entryDate = parsePubdateDate(dateStringBuilder.toString().replace(Strings.TWOSPACE, Strings.SPACE));
pubDateTagEntered = false;
} else if (TAG_LASTBUILDDATE.equals(localName)) {
lastBuildDate = parsePubdateDate(dateStringBuilder.toString().replace(Strings.TWOSPACE, Strings.SPACE));
lastUpdateDateTagEntered = false;
} else if (TAG_DATE.equals(localName)) {
entryDate = parseUpdateDate(dateStringBuilder.toString());
dateTagEntered = false;
} else if (TAG_ENTRY.equals(localName) || TAG_ITEM.equals(localName)) {
if (title != null && (entryDate == null || ((entryDate.after(lastUpdateDate) || !efficientFeedParsing) && entryDate.after(keepDateBorder)))) {
ContentValues values = new ContentValues();
if (entryDate != null && entryDate.getTime() > realLastUpdate) {
realLastUpdate = entryDate.getTime();
values.put(FeedData.FeedColumns.REALLASTUPDATE, realLastUpdate);
context.getContentResolver().update(FeedData.FeedColumns.CONTENT_URI(id), values, null, null);
values.clear();
}
if (entryDate != null) {
values.put(FeedData.EntryColumns.DATE, entryDate.getTime());
values.putNull(FeedData.EntryColumns.READDATE);
}
values.put(FeedData.EntryColumns.TITLE, unescapeString(title.toString().trim()));
if (author != null) {
values.put(FeedData.EntryColumns.AUTHOR, unescapeString(author.toString()));
}
Vector<String> images = null;
if (description != null) {
String descriptionString = description.toString().trim().replaceAll(Strings.HTML_SPAN_REGEX, Strings.EMPTY);
if (descriptionString.length() > 0) {
if (fetchImages) {
images = new Vector<String>(4);
Matcher matcher = imgPattern.matcher(description);
while (matcher.find()) {
String match = matcher.group(1).replace(Strings.SPACE, Strings.URL_SPACE);
images.add(match);
try {
// replace the '%' that may occur while urlencode such that the img-src url (in the abstract text) does reinterpret the parameters
descriptionString = descriptionString.replace(match, new StringBuilder(Strings.FILEURL).append(FeedDataContentProvider.IMAGEFOLDER).append(Strings.IMAGEID_REPLACEMENT).append(URLEncoder.encode(match.substring(match.lastIndexOf('/')+1), UTF8)).toString().replace(PERCENT, PERCENT_REPLACE));
} catch (UnsupportedEncodingException e) {
// UTF-8 should be supported
}
}
}
values.put(FeedData.EntryColumns.ABSTRACT, descriptionString);
}
}
String enclosureString = null;
StringBuilder existanceStringBuilder = new StringBuilder(FeedData.EntryColumns.LINK).append(Strings.DB_ARG);
if (enclosure == null && enclosureUrl != null && enclosureUrl.length() > 0) {
enclosure = enclosureUrl;
enclosure.append(Strings.ENCLOSURE_SEPARATOR);
if (enclosureType != null && enclosureType.length() > 0) {
enclosure.append(enclosureType);
}
enclosure.append(Strings.ENCLOSURE_SEPARATOR);
if (enclosureLength != null && enclosureLength.length() > 0) {
enclosure.append(enclosureLength);
}
}
if (enclosure != null && enclosure.length() > 0) {
enclosureString = enclosure.toString();
values.put(FeedData.EntryColumns.ENCLOSURE, enclosureString);
existanceStringBuilder.append(Strings.DB_AND).append(FeedData.EntryColumns.ENCLOSURE).append(Strings.DB_ARG);
}
String guidString = null;
if (guid != null && guid.length() > 0) {
guidString = guid.toString();
values.put(FeedData.EntryColumns.GUID, guidString);
existanceStringBuilder.append(Strings.DB_AND).append(FeedData.EntryColumns.GUID).append(Strings.DB_ARG);
}
String entryLinkString = Strings.EMPTY; // don't set this to null as we need *some* value
if (entryLink != null && entryLink.length() > 0) {
entryLinkString = entryLink.toString().trim();
if (feedBaseUrl != null && !entryLinkString.startsWith(Strings.HTTP) && !entryLinkString.startsWith(Strings.HTTPS)) {
entryLinkString = feedBaseUrl + (entryLinkString.startsWith(Strings.SLASH) ? entryLinkString : Strings.SLASH + entryLinkString);
}
}
String[] existanceValues = enclosureString != null ? (guidString != null ? new String[] {entryLinkString, enclosureString, guidString}: new String[] {entryLinkString, enclosureString}) : (guidString != null ? new String[] {entryLinkString, guidString} : new String[] {entryLinkString});
boolean skip = false;
if (!efficientFeedParsing) {
if (context.getContentResolver().update(feedEntiresUri, values, existanceStringBuilder.toString()+" AND "+FeedData.EntryColumns.DATE+"<"+entryDate.getTime(), existanceValues) == 1) {
newCount++;
skip = true;
} else {
values.remove(FeedData.EntryColumns.READDATE);
// continue with the standard procedure but don't reset the read-date
}
}
if (!skip && ((entryLinkString.length() == 0 && guidString == null) || context.getContentResolver().update(feedEntiresUri, values, existanceStringBuilder.toString(), existanceValues) == 0)) {
values.put(FeedData.EntryColumns.LINK, entryLinkString);
if (entryDate == null) {
values.put(FeedData.EntryColumns.DATE, now--);
}
String entryId = context.getContentResolver().insert(feedEntiresUri, values).getLastPathSegment();
if (fetchImages) {
FeedDataContentProvider.IMAGEFOLDER_FILE.mkdir(); // create images dir
for (int n = 0, i = images != null ? images.size() : 0; n < i; n++) {
try {
String match = images.get(n);
byte[] data = FetcherService.getBytes(new URL(images.get(n)).openStream());
// see the comment where the img regex is executed for details about this replacement
FileOutputStream fos = new FileOutputStream(new StringBuilder(FeedDataContentProvider.IMAGEFOLDER).append(entryId).append(Strings.IMAGEFILE_IDSEPARATOR).append(URLEncoder.encode(match.substring(match.lastIndexOf('/')+1), UTF8)).toString().replace(PERCENT, PERCENT_REPLACE));
fos.write(data);
fos.close();
} catch (Exception e) {
}
}
}
newCount++;
} else if (entryDate == null && efficientFeedParsing) {
cancel();
}
} else if (efficientFeedParsing) {
cancel();
}
description = null;
title = null;
enclosure = null;
guid = null;
author = null;
enclosureUrl = null;
enclosureType = null;
enclosureLength = null;
entryLink = null;
} else if (TAG_RSS.equals(localName) || TAG_RDF.equals(localName) || TAG_FEED.equals(localName)) {
done = true;
} else if (TAG_GUID.equals(localName)) {
guidTagEntered = false;
} else if (TAG_NAME.equals(localName)) {
nameTagEntered = false;
} else if (TAG_AUTHOR.equals(localName) || TAG_CREATOR.equals(localName)) {
authorTagEntered = false;
} else if (TAG_ENCLOSURE.equals(localName)) {
enclosureTagEntered = false;
} else if (TAG_ENCLOSUREURL.equals(localName)) {
enclosureUrlTagEntered = false;
} else if (TAG_ENCLOSURETYPE.equals(localName)) {
enclosureTypeTagEntered = false;
} else if (TAG_ENCLOSURELENGTH.equals(localName)) {
enclosureLengthTagEntered = false;
}
}
public int getNewCount() {
return newCount;
}
public boolean isDone() {
return done;
}
public boolean isCancelled() {
return cancelled;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
reader = null;
}
public void setReader(Reader reader) {
this.reader = reader;
inputStream = null;
}
public void cancel() {
if (!cancelled) {
cancelled = true;
done = true;
if (inputStream != null) {
try {
inputStream.close(); // stops all parsing
} catch (IOException e) {
}
} else if (reader != null) {
try {
reader.close(); // stops all parsing
} catch (IOException e) {
}
}
}
}
public void setFetchImages(boolean fetchImages) {
this.fetchImages = fetchImages;
}
private static Date parseUpdateDate(String string) {
string = string.replace(Z, GMT);
for (int n = 0; n < DATEFORMAT_COUNT; n++) {
try {
return UPDATE_DATEFORMATS[n].parse(string);
} catch (ParseException e) { } // just do nothing
}
return null;
}
private static Date parsePubdateDate(String string) {
for (int n = 0; n < TIMEZONES_COUNT; n++) {
string = string.replace(TIMEZONES[n], TIMEZONES_REPLACE[n]);
}
for (int n = 0; n < PUBDATEFORMAT_COUNT; n++) {
try {
return PUBDATE_DATEFORMATS[n].parse(string);
} catch (ParseException e) { } // just do nothing
}
return null;
}
private static String unescapeString(String str) {
String result = str.replace(Strings.AMP_SG, Strings.AMP).replaceAll(Strings.HTML_TAG_REGEX, Strings.EMPTY).replace(Strings.HTML_LT, Strings.LT).replace(Strings.HTML_GT, Strings.GT).replace(Strings.HTML_QUOT, Strings.QUOT).replace(Strings.HTML_APOS, Strings.APOSTROPHE);
if (result.indexOf(ANDRHOMBUS) > -1) {
return Html.fromHtml(result, null, null).toString();
} else {
return result;
}
}
public void setEfficientFeedParsing(boolean efficientFeedParsing) {
this.efficientFeedParsing = efficientFeedParsing;
}
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2012 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.sparserss.handler;
import java.io.File;
import java.io.FilenameFilter;
import java.util.regex.Pattern;
import de.shandschuh.sparserss.provider.FeedDataContentProvider;
public class PictureFilenameFilter implements FilenameFilter {
private static final String REGEX = "__[^\\.]*\\.[A-Za-z]*";
private Pattern pattern;
public PictureFilenameFilter(String entryId) {
setEntryId(entryId);
}
public PictureFilenameFilter() {
}
public void setEntryId(String entryId) {
pattern = Pattern.compile(entryId+REGEX);
}
public boolean accept(File dir, String filename) {
if (dir != null && dir.equals(FeedDataContentProvider.IMAGEFOLDER_FILE)) { // this should be always true but lets check it anyway
return pattern.matcher(filename).find();
} else {
return false;
}
}
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2013 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.sparserss;
public interface Requeryable {
public void requery();
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2012 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.sparserss;
import android.app.Activity;
public class EmptyActivity extends Activity {
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2010 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.sparserss.service;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.IBinder;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import de.shandschuh.sparserss.Strings;
public class RefreshService extends Service {
private static final String SIXTYMINUTES = "3600000";
private OnSharedPreferenceChangeListener listener = new OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (Strings.SETTINGS_REFRESHINTERVAL.equals(key)) {
restartTimer(false);
}
}
};
private Intent refreshBroadcastIntent;
private AlarmManager alarmManager;
private PendingIntent timerIntent;
private SharedPreferences preferences = null;
@Override
public IBinder onBind(Intent intent) {
onRebind(intent);
return null;
}
@Override
public void onRebind(Intent intent) {
super.onRebind(intent);
}
@Override
public boolean onUnbind(Intent intent) {
return true; // we want to use rebind
}
@Override
public void onCreate() {
super.onCreate();
try {
preferences = PreferenceManager.getDefaultSharedPreferences(createPackageContext(Strings.PACKAGE, 0));
} catch (NameNotFoundException e) {
preferences = PreferenceManager.getDefaultSharedPreferences(this);
}
refreshBroadcastIntent = new Intent(Strings.ACTION_REFRESHFEEDS).putExtra(Strings.SCHEDULED, true);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
preferences.registerOnSharedPreferenceChangeListener(listener);
restartTimer(true);
}
private void restartTimer(boolean created) {
if (timerIntent == null) {
timerIntent = PendingIntent.getBroadcast(this, 0, refreshBroadcastIntent, 0);
} else {
alarmManager.cancel(timerIntent);
}
int time = 3600000;
try {
time = Math.max(60000, Integer.parseInt(preferences.getString(Strings.SETTINGS_REFRESHINTERVAL, SIXTYMINUTES)));
} catch (Exception exception) {
}
long initialRefreshTime = SystemClock.elapsedRealtime() + 10000;
if (created) {
long lastRefresh = preferences.getLong(Strings.PREFERENCE_LASTSCHEDULEDREFRESH, 0);
if (lastRefresh > 0) {
// this indicates a service restart by the system
initialRefreshTime = Math.max(SystemClock.elapsedRealtime() + 10000, lastRefresh+time);
}
}
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, initialRefreshTime, time, timerIntent);
}
@Override
public void onDestroy() {
if (timerIntent != null) {
alarmManager.cancel(timerIntent);
}
preferences.unregisterOnSharedPreferenceChangeListener(listener);
super.onDestroy();
}
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2010-2013 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.sparserss.service;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.IBinder;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Xml;
import de.shandschuh.sparserss.BASE64;
import de.shandschuh.sparserss.MainTabActivity;
import de.shandschuh.sparserss.R;
import de.shandschuh.sparserss.Strings;
import de.shandschuh.sparserss.handler.RSSHandler;
import de.shandschuh.sparserss.provider.FeedData;
public class FetcherService extends IntentService {
private static final int FETCHMODE_DIRECT = 1;
private static final int FETCHMODE_REENCODE = 2;
private static final String KEY_USERAGENT = "User-agent";
private static final String VALUE_USERAGENT = "Mozilla/5.0";
private static final String CHARSET = "charset=";
private static final String COUNT = "COUNT(*)";
private static final String CONTENT_TYPE_TEXT_HTML = "text/html";
private static final String HREF = "href=\"";
private static final String HTML_BODY = "<body";
private static final String ENCODING = "encoding=\"";
private static final String SERVICENAME = "RssFetcherService";
private static final String ZERO = "0";
private static final String GZIP = "gzip";
/* Allow different positions of the "rel" attribute w.r.t. the "href" attribute */
private static final Pattern feedLinkPattern = Pattern.compile("[.]*<link[^>]* ((rel=alternate|rel=\"alternate\")[^>]* href=\"[^\"]*\"|href=\"[^\"]*\"[^>]* (rel=alternate|rel=\"alternate\"))[^>]*>", Pattern.CASE_INSENSITIVE);
/* Case insensitive */
private static final Pattern feedIconPattern = Pattern.compile("[.]*<link[^>]* (rel=(\"shortcut icon\"|\"icon\"|icon)[^>]* href=\"[^\"]*\"|href=\"[^\"]*\"[^>]* rel=(\"shortcut icon\"|\"icon\"|icon))[^>]*>", Pattern.CASE_INSENSITIVE);
private NotificationManager notificationManager;
private static SharedPreferences preferences = null;
private static Proxy proxy;
private boolean destroyed;
private RSSHandler handler;
public FetcherService() {
super(SERVICENAME);
destroyed = false;
HttpURLConnection.setFollowRedirects(true);
}
@Override
public synchronized void onHandleIntent(Intent intent) {
if (preferences == null) {
try {
preferences = PreferenceManager.getDefaultSharedPreferences(createPackageContext(Strings.PACKAGE, 0));
} catch (NameNotFoundException e) {
preferences = PreferenceManager.getDefaultSharedPreferences(FetcherService.this);
}
}
if (intent.getBooleanExtra(Strings.SCHEDULED, false)) {
SharedPreferences.Editor editor = preferences.edit();
editor.putLong(Strings.PREFERENCE_LASTSCHEDULEDREFRESH, SystemClock.elapsedRealtime());
editor.commit();
}
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED && intent != null) {
if (preferences.getBoolean(Strings.SETTINGS_PROXYENABLED, false) && (networkInfo.getType() == ConnectivityManager.TYPE_WIFI || !preferences.getBoolean(Strings.SETTINGS_PROXYWIFIONLY, false))) {
try {
proxy = new Proxy(ZERO.equals(preferences.getString(Strings.SETTINGS_PROXYTYPE, ZERO)) ? Proxy.Type.HTTP : Proxy.Type.SOCKS, new InetSocketAddress(preferences.getString(Strings.SETTINGS_PROXYHOST, Strings.EMPTY), Integer.parseInt(preferences.getString(Strings.SETTINGS_PROXYPORT, Strings.DEFAULTPROXYPORT))));
} catch (Exception e) {
proxy = null;
}
} else {
proxy = null;
}
int newCount = refreshFeeds(FetcherService.this, intent.getStringExtra(Strings.FEEDID), networkInfo, intent.getBooleanExtra(Strings.SETTINGS_OVERRIDEWIFIONLY, false));
if (newCount > 0) {
if (preferences.getBoolean(Strings.SETTINGS_NOTIFICATIONSENABLED, false)) {
Cursor cursor = getContentResolver().query(FeedData.EntryColumns.CONTENT_URI, new String[] {COUNT}, new StringBuilder(FeedData.EntryColumns.READDATE).append(Strings.DB_ISNULL).toString(), null, null);
cursor.moveToFirst();
newCount = cursor.getInt(0);
cursor.close();
String text = new StringBuilder().append(newCount).append(' ').append(getString(R.string.newentries)).toString();
Notification notification = new Notification(R.drawable.ic_statusbar_rss, text, System.currentTimeMillis());
Intent notificationIntent = new Intent(FetcherService.this, MainTabActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(FetcherService.this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
if (preferences.getBoolean(Strings.SETTINGS_NOTIFICATIONSVIBRATE, false)) {
notification.defaults = Notification.DEFAULT_VIBRATE;
}
notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;
notification.ledARGB = 0xffffffff;
notification.ledOnMS = 300;
notification.ledOffMS = 1000;
String ringtone = preferences.getString(Strings.SETTINGS_NOTIFICATIONSRINGTONE, null);
if (ringtone != null && ringtone.length() > 0) {
notification.sound = Uri.parse(ringtone);
}
notification.setLatestEventInfo(FetcherService.this, getString(R.string.rss_feeds), text, contentIntent);
notificationManager.notify(0, notification);
} else {
notificationManager.cancel(0);
}
}
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
@Override
public void onDestroy() {
if (MainTabActivity.INSTANCE != null) {
MainTabActivity.INSTANCE.internalSetProgressBarIndeterminateVisibility(false);
}
destroyed = true;
if (handler != null) {
handler.cancel();
}
super.onDestroy();
}
private int refreshFeeds(Context context, String feedId, NetworkInfo networkInfo, boolean overrideWifiOnly) {
String selection = null;
if (!overrideWifiOnly && networkInfo.getType() != ConnectivityManager.TYPE_WIFI) {
selection = new StringBuilder(FeedData.FeedColumns.WIFIONLY).append("=0 or ").append(FeedData.FeedColumns.WIFIONLY).append(" IS NULL").toString(); // "IS NOT 1" does not work on 2.1
}
Cursor cursor = context.getContentResolver().query(feedId == null ? FeedData.FeedColumns.CONTENT_URI : FeedData.FeedColumns.CONTENT_URI(feedId), null, selection, null, null); // no managed query here
int urlPosition = cursor.getColumnIndex(FeedData.FeedColumns.URL);
int idPosition = cursor.getColumnIndex(FeedData.FeedColumns._ID);
int lastUpdatePosition = cursor.getColumnIndex(FeedData.FeedColumns.REALLASTUPDATE);
int titlePosition = cursor.getColumnIndex(FeedData.FeedColumns.NAME);
int fetchmodePosition = cursor.getColumnIndex(FeedData.FeedColumns.FETCHMODE);
int iconPosition = cursor.getColumnIndex(FeedData.FeedColumns.ICON);
int imposeUseragentPosition = cursor.getColumnIndex(FeedData.FeedColumns.IMPOSE_USERAGENT);
boolean followHttpHttpsRedirects = preferences.getBoolean(Strings.SETTINGS_HTTPHTTPSREDIRECTS, false);
int result = 0;
if (handler == null) {
handler = new RSSHandler(context);
}
handler.setEfficientFeedParsing(preferences.getBoolean(Strings.SETTINGS_EFFICIENTFEEDPARSING, true));
handler.setFetchImages(preferences.getBoolean(Strings.SETTINGS_FETCHPICTURES, false));
while(!destroyed && cursor.moveToNext()) {
String id = cursor.getString(idPosition);
boolean imposeUserAgent = !cursor.isNull(imposeUseragentPosition) && cursor.getInt(imposeUseragentPosition) == 1;
HttpURLConnection connection = null;
try {
String feedUrl = cursor.getString(urlPosition);
connection = setupConnection(feedUrl, imposeUserAgent, followHttpHttpsRedirects);
String redirectHost = connection.getURL().getHost(); // Feed icon should be fetched from target site, not from feedburner, so we're tracking all redirections
String contentType = connection.getContentType();
int fetchMode = cursor.getInt(fetchmodePosition);
String iconUrl = null;
handler.init(new Date(cursor.getLong(lastUpdatePosition)), id, cursor.getString(titlePosition), feedUrl);
if (fetchMode == 0) {
if (contentType != null && contentType.startsWith(CONTENT_TYPE_TEXT_HTML)) {
BufferedReader reader = new BufferedReader(new InputStreamReader(getConnectionInputStream(connection)));
String line = null;
String newFeedUrl = null;
while ((line = reader.readLine()) != null) {
if (line.indexOf(HTML_BODY) > -1) {
break;
} else {
if (newFeedUrl == null) {
Matcher matcher = feedLinkPattern.matcher(line);
if (matcher.find()) { // not "while" as only one link is needed
newFeedUrl = getHref(matcher.group(), feedUrl);
}
}
if (iconUrl == null) {
Matcher matcher = feedIconPattern.matcher(line);
if (matcher.find()) { // not "while" as only one link is needed
iconUrl = getHref(matcher.group(), feedUrl);
}
}
if (newFeedUrl != null && iconUrl != null) {
break;
}
}
}
if (newFeedUrl != null) {
redirectHost = connection.getURL().getHost();
connection.disconnect();
connection = setupConnection(newFeedUrl, imposeUserAgent, followHttpHttpsRedirects);
contentType = connection.getContentType();
handler.initFeedBaseUrl(newFeedUrl);
ContentValues values = new ContentValues();
values.put(FeedData.FeedColumns.URL, newFeedUrl);
context.getContentResolver().update(FeedData.FeedColumns.CONTENT_URI(id), values, null, null);
}
}
if (contentType != null) {
int index = contentType.indexOf(CHARSET);
if (index > -1) {
int index2 = contentType.indexOf(';', index);
try {
Xml.findEncodingByName(index2 > -1 ?contentType.substring(index+8, index2) : contentType.substring(index+8));
fetchMode = FETCHMODE_DIRECT;
} catch (UnsupportedEncodingException usee) {
fetchMode = FETCHMODE_REENCODE;
}
} else {
fetchMode = FETCHMODE_REENCODE;
}
} else {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getConnectionInputStream(connection)));
char[] chars = new char[20];
int length = bufferedReader.read(chars);
String xmlDescription = new String(chars, 0, length);
redirectHost = connection.getURL().getHost();
connection.disconnect();
connection = setupConnection(connection.getURL(), imposeUserAgent, followHttpHttpsRedirects);
int start = xmlDescription != null ? xmlDescription.indexOf(ENCODING) : -1;
if (start > -1) {
try {
Xml.findEncodingByName(xmlDescription.substring(start+10, xmlDescription.indexOf('"', start+11)));
fetchMode = FETCHMODE_DIRECT;
} catch (UnsupportedEncodingException usee) {
fetchMode = FETCHMODE_REENCODE;
}
} else {
fetchMode = FETCHMODE_DIRECT; // absolutely no encoding information found
}
}
ContentValues values = new ContentValues();
values.put(FeedData.FeedColumns.FETCHMODE, fetchMode);
context.getContentResolver().update(FeedData.FeedColumns.CONTENT_URI(id), values, null, null);
}
/* check and optionally find favicon */
byte[] iconBytes = cursor.getBlob(iconPosition);
if (iconBytes == null) {
if (iconUrl == null) {
String baseUrl = new StringBuilder(connection.getURL().getProtocol()).append(Strings.PROTOCOL_SEPARATOR).append(redirectHost).toString();
HttpURLConnection iconURLConnection = setupConnection(new URL(baseUrl), imposeUserAgent, followHttpHttpsRedirects);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(getConnectionInputStream(iconURLConnection)));
String line = null;
while ((line = reader.readLine()) != null) {
if (line.indexOf(HTML_BODY) > -1) {
break;
} else {
Matcher matcher = feedIconPattern.matcher(line);
if (matcher.find()) { // not "while" as only one link is needed
iconUrl = getHref(matcher.group(), baseUrl);
if (iconUrl != null) {
break;
}
}
}
}
} catch (Exception e) {
} finally {
iconURLConnection.disconnect();
}
if (iconUrl == null) {
iconUrl = new StringBuilder(baseUrl).append(Strings.FILE_FAVICON).toString();
}
}
HttpURLConnection iconURLConnection = setupConnection(new URL(iconUrl), imposeUserAgent, followHttpHttpsRedirects);
try {
iconBytes = getBytes(getConnectionInputStream(iconURLConnection));
ContentValues values = new ContentValues();
values.put(FeedData.FeedColumns.ICON, iconBytes);
context.getContentResolver().update(FeedData.FeedColumns.CONTENT_URI(id), values, null, null);
} catch (Exception e) {
ContentValues values = new ContentValues();
values.put(FeedData.FeedColumns.ICON, new byte[0]); // no icon found or error
context.getContentResolver().update(FeedData.FeedColumns.CONTENT_URI(id), values, null, null);
} finally {
iconURLConnection.disconnect();
}
}
switch (fetchMode) {
default:
case FETCHMODE_DIRECT: {
if (contentType != null) {
int index = contentType.indexOf(CHARSET);
int index2 = contentType.indexOf(';', index);
InputStream inputStream = getConnectionInputStream(connection);
handler.setInputStream(inputStream);
Xml.parse(inputStream, Xml.findEncodingByName(index2 > -1 ?contentType.substring(index+8, index2) : contentType.substring(index+8)), handler);
} else {
InputStreamReader reader = new InputStreamReader(getConnectionInputStream(connection));
handler.setReader(reader);
Xml.parse(reader, handler);
}
break;
}
case FETCHMODE_REENCODE: {
ByteArrayOutputStream ouputStream = new ByteArrayOutputStream();
InputStream inputStream = getConnectionInputStream(connection);
byte[] byteBuffer = new byte[4096];
int n;
while ( (n = inputStream.read(byteBuffer)) > 0 ) {
ouputStream.write(byteBuffer, 0, n);
}
String xmlText = ouputStream.toString();
int start = xmlText != null ? xmlText.indexOf(ENCODING) : -1;
if (start > -1) {
Xml.parse(new StringReader(new String(ouputStream.toByteArray(), xmlText.substring(start+10, xmlText.indexOf('"', start+11)))), handler);
} else {
// use content type
if (contentType != null) {
int index = contentType.indexOf(CHARSET);
if (index > -1) {
int index2 = contentType.indexOf(';', index);
try {
StringReader reader = new StringReader(new String(ouputStream.toByteArray(), index2 > -1 ?contentType.substring(index+8, index2) : contentType.substring(index+8)));
handler.setReader(reader);
Xml.parse(reader, handler);
} catch (Exception e) {
}
} else {
StringReader reader = new StringReader(new String(ouputStream.toByteArray()));
handler.setReader(reader);
Xml.parse(reader, handler);
}
}
}
break;
}
}
connection.disconnect();
} catch (FileNotFoundException e) {
if (!handler.isDone() && !handler.isCancelled()) {
ContentValues values = new ContentValues();
values.put(FeedData.FeedColumns.FETCHMODE, 0); // resets the fetchmode to determine it again later
values.put(FeedData.FeedColumns.ERROR, context.getString(R.string.error_feederror));
context.getContentResolver().update(FeedData.FeedColumns.CONTENT_URI(id), values, null, null);
}
} catch (Throwable e) {
if (!handler.isDone() && !handler.isCancelled()) {
ContentValues values = new ContentValues();
values.put(FeedData.FeedColumns.FETCHMODE, 0); // resets the fetchmode to determine it again later
values.put(FeedData.FeedColumns.ERROR, e.getMessage());
context.getContentResolver().update(FeedData.FeedColumns.CONTENT_URI(id), values, null, null);
}
} finally {
if (connection != null) {
connection.disconnect();
}
}
result += handler.getNewCount();
}
cursor.close();
if (result > 0) {
context.sendBroadcast(new Intent(Strings.ACTION_UPDATEWIDGET).putExtra(Strings.COUNT, result));
}
return result;
}
private static String getHref(String line, String baseUrl) {
int posStart = line.indexOf(HREF);
if (posStart > -1) {
String url = line.substring(posStart+6, line.indexOf('"', posStart+10)).replace(Strings.AMP_SG, Strings.AMP);
if (url.startsWith(Strings.SLASH)) {
int index = baseUrl.indexOf('/', 8);
if (index > -1) {
url = baseUrl.substring(0, index)+url;
} else {
url = baseUrl+url;
}
} else if (!url.startsWith(Strings.HTTP) && !url.startsWith(Strings.HTTPS)) {
url = new StringBuilder(baseUrl).append('/').append(url).toString();
}
return url;
} else {
return null;
}
}
private static final HttpURLConnection setupConnection(String url, boolean imposeUseragent, boolean followHttpHttpsRedirects) throws IOException, NoSuchAlgorithmException, KeyManagementException {
return setupConnection(new URL(url), imposeUseragent, followHttpHttpsRedirects);
}
private static final HttpURLConnection setupConnection(URL url, boolean imposeUseragent, boolean followHttpHttpsRedirects) throws IOException, NoSuchAlgorithmException, KeyManagementException {
return setupConnection(url, imposeUseragent, followHttpHttpsRedirects, 0);
}
private static final HttpURLConnection setupConnection(URL url, boolean imposeUseragent, boolean followHttpHttpsRedirects, int cycle) throws IOException, NoSuchAlgorithmException, KeyManagementException {
HttpURLConnection connection = proxy == null ? (HttpURLConnection) url.openConnection() : (HttpURLConnection) url.openConnection(proxy);
connection.setDoInput(true);
connection.setDoOutput(false);
if (imposeUseragent) {
connection.setRequestProperty(KEY_USERAGENT, VALUE_USERAGENT); // some feeds need this to work properly
}
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setUseCaches(false);
if (url.getUserInfo() != null) {
connection.setRequestProperty("Authorization", "Basic "+BASE64.encode(url.getUserInfo().getBytes()));
}
connection.setRequestProperty("connection", "close"); // Workaround for android issue 7786
connection.setRequestProperty("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
connection.connect();
String location = connection.getHeaderField("Location");
if (location != null && (url.getProtocol().equals(Strings._HTTP) && location.startsWith(Strings.HTTPS) || url.getProtocol().equals(Strings._HTTPS) && location.startsWith(Strings.HTTP))) {
// if location != null, the system-automatic redirect has failed which indicates a protocol change
if (followHttpHttpsRedirects) {
connection.disconnect();
if (cycle < 5) {
return setupConnection(new URL(location), imposeUseragent, followHttpHttpsRedirects, cycle+1);
} else {
throw new IOException("Too many redirects.");
}
} else {
throw new IOException("https<->http redirect - enable in settings");
}
}
return connection;
}
public static byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n;
while ((n = inputStream.read(buffer)) > 0) {
output.write(buffer, 0, n);
}
byte[] result = output.toByteArray();
output.close();
inputStream.close();
return result;
}
/**
* This is a small wrapper for getting the properly encoded inputstream if is is gzip compressed
* and not properly recognized.
*/
private static InputStream getConnectionInputStream(HttpURLConnection connection) throws IOException {
InputStream inputStream = connection.getInputStream();
if (GZIP.equals(connection.getContentEncoding()) && !(inputStream instanceof GZIPInputStream)) {
return new GZIPInputStream(inputStream);
} else {
return inputStream;
}
}
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2010-2013 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.sparserss;
import java.util.Vector;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import de.shandschuh.sparserss.provider.FeedData;
import de.shandschuh.sparserss.service.FetcherService;
public class MainTabActivity extends TabActivity {
private static final int DIALOG_LICENSEAGREEMENT = 0;
private boolean tabsAdded;
private static final String TAG_NORMAL = "normal";
private static final String TAG_ALL = "all";
private static final String TAG_FAVORITE = "favorite";
public static MainTabActivity INSTANCE;
public static final boolean POSTGINGERBREAD = !Build.VERSION.RELEASE.startsWith("1") &&
!Build.VERSION.RELEASE.startsWith("2"); // this way around is future save
private static Boolean LIGHTTHEME;
public static boolean isLightTheme(Context context) {
if (LIGHTTHEME == null) {
LIGHTTHEME = PreferenceManager.getDefaultSharedPreferences(context).getBoolean(Strings.SETTINGS_LIGHTTHEME, false);
}
return LIGHTTHEME;
}
private Menu menu;
private BroadcastReceiver refreshReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
internalSetProgressBarIndeterminateVisibility(true);
}
};
private boolean hasContent;
private boolean progressBarVisible;
private Vector<String> visitedTabs;
public void onCreate(Bundle savedInstanceState) {
if (isLightTheme(this)) {
setTheme(R.style.Theme_Light);
}
super.onCreate(savedInstanceState);
// We need to display progress information
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.tabs);
INSTANCE = this;
hasContent = false;
visitedTabs = new Vector<String>(3);
if (getPreferences(MODE_PRIVATE).getBoolean(Strings.PREFERENCE_LICENSEACCEPTED, false)) {
setContent();
} else {
/* Workaround for android issue 4499 on 1.5 devices */
getTabHost().addTab(getTabHost().newTabSpec(Strings.EMPTY).setIndicator(Strings.EMPTY).setContent(new Intent(this, EmptyActivity.class)));
showDialog(DIALOG_LICENSEAGREEMENT);
}
}
@Override
protected void onResume() {
super.onResume();
internalSetProgressBarIndeterminateVisibility(isCurrentlyRefreshing());
registerReceiver(refreshReceiver, new IntentFilter("de.shandschuh.sparserss.REFRESH"));
}
@Override
protected void onPause() {
unregisterReceiver(refreshReceiver);
super.onPause();
}
@Override
protected Dialog onCreateDialog(int id) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setTitle(R.string.dialog_licenseagreement);
builder.setNegativeButton(R.string.button_decline, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
finish();
}
});
builder.setPositiveButton(R.string.button_accept, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putBoolean(Strings.PREFERENCE_LICENSEACCEPTED, true);
editor.commit();
/* Part of workaround for android issue 4499 on 1.5 devices */
getTabHost().clearAllTabs();
/* we only want to invoke actions if the license is accepted */
setContent();
}
});
setupLicenseText(builder);
builder.setOnKeyListener(new OnKeyListener() {
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
dialog.cancel();
finish();
}
return true;
}
});
return builder.create();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
this.menu = menu;
Activity activity = getCurrentActivity();
if (hasContent && activity != null) {
return activity.onCreateOptionsMenu(menu);
} else {
menu.add(Strings.EMPTY); // to let the menu be available
return true;
}
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
Activity activity = getCurrentActivity();
if (hasContent && activity != null) {
return activity.onMenuItemSelected(featureId, item);
} else {
return super.onMenuItemSelected(featureId, item);
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
Activity activity = getCurrentActivity();
if (hasContent && activity != null) {
return activity.onPrepareOptionsMenu(menu);
} else {
return super.onPrepareOptionsMenu(menu);
}
}
private void setContent() {
TabHost tabHost = getTabHost();
tabHost.addTab(tabHost.newTabSpec(TAG_NORMAL).setIndicator(getString(R.string.overview)).setContent(new Intent().setClass(this, RSSOverview.class)));
hasContent = true;
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Strings.SETTINGS_SHOWTABS, false)) {
setTabWidgetVisible(true);
}
final MainTabActivity mainTabActivity = this;
if (POSTGINGERBREAD) {
/* Change the menu also on ICS when tab is changed */
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
public void onTabChanged(String tabId) {
if (menu != null) {
menu.clear();
onCreateOptionsMenu(menu);
}
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(mainTabActivity).edit();
editor.putString(Strings.PREFERENCE_LASTTAB, tabId);
editor.commit();
setCurrentTab(tabId);
}
});
if (menu != null) {
menu.clear();
onCreateOptionsMenu(menu);
}
} else {
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
@Override
public void onTabChanged(String tabId) {
setCurrentTab(tabId);
}
});
}
}
private void setCurrentTab(String currentTab) {
if (visitedTabs.contains(currentTab)) {
// requery the tab but only if it has been shown already
Activity activity = getCurrentActivity();
if (hasContent && activity != null) {
((Requeryable) activity).requery();
}
} else {
visitedTabs.add(currentTab);
}
}
public void setTabWidgetVisible(boolean visible) {
if (visible) {
TabHost tabHost = getTabHost();
if (!tabsAdded) {
tabHost.addTab(tabHost.newTabSpec(TAG_ALL).setIndicator(getString(R.string.all)).setContent(new Intent(Intent.ACTION_VIEW, FeedData.EntryColumns.CONTENT_URI).putExtra(EntriesListActivity.EXTRA_SHOWFEEDINFO, true)));
tabHost.addTab(tabHost.newTabSpec(TAG_FAVORITE).setIndicator(getString(R.string.favorites), getResources().getDrawable(android.R.drawable.star_big_on)).setContent(new Intent(Intent.ACTION_VIEW, FeedData.EntryColumns.FAVORITES_CONTENT_URI).putExtra(EntriesListActivity.EXTRA_SHOWFEEDINFO, true).putExtra(EntriesListActivity.EXTRA_AUTORELOAD, true)));
tabsAdded = true;
}
getTabWidget().setVisibility(View.VISIBLE);
String lastTab = PreferenceManager.getDefaultSharedPreferences(this).getString(Strings.PREFERENCE_LASTTAB, TAG_NORMAL);
boolean tabFound = false;
for(int i = 0; i < tabHost.getTabWidget().getChildCount(); ++i) {
tabHost.setCurrentTab(i);
String currentTab = tabHost.getCurrentTabTag();
if (lastTab.equals(currentTab)) {
tabFound = true;
break;
}
}
if (!tabFound) {
tabHost.setCurrentTab(0);
}
} else {
getTabWidget().setVisibility(View.GONE);
}
}
void setupLicenseText(AlertDialog.Builder builder) {
View view = getLayoutInflater().inflate(R.layout.license, null);
final TextView textView = (TextView) view.findViewById(R.id.license_text);
textView.setTextColor(textView.getTextColors().getDefaultColor()); // disables color change on selection
textView.setText(new StringBuilder(getString(R.string.license_intro)).append(Strings.THREENEWLINES).append(getString(R.string.license)));
final TextView contributorsTextView = (TextView) view.findViewById(R.id.contributors_togglebutton);
contributorsTextView.setOnClickListener(new OnClickListener() {
boolean showingLicense = true;
@Override
public void onClick(View view) {
if (showingLicense) {
textView.setText(R.string.contributors_list);
contributorsTextView.setText(R.string.license_word);
} else {
textView.setText(new StringBuilder(getString(R.string.license_intro)).append(Strings.THREENEWLINES).append(getString(R.string.license)));
contributorsTextView.setText(R.string.contributors);
}
showingLicense = !showingLicense;
}
});
builder.setView(view);
}
private boolean isCurrentlyRefreshing() {
ActivityManager manager = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service: manager.getRunningServices(Integer.MAX_VALUE)) {
if (FetcherService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
public void internalSetProgressBarIndeterminateVisibility(boolean progressBarVisible) {
setProgressBarIndeterminateVisibility(progressBarVisible);
this.progressBarVisible = progressBarVisible;
Activity activity = getCurrentActivity();
if (activity != null) {
activity.onPrepareOptionsMenu(null);
}
}
public boolean isProgressBarVisible() {
return progressBarVisible;
}
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2010, 2011 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* (this is an excerpt from BASE64 class of jaolt, except for the license)
*/
package de.shandschuh.sparserss;
public class BASE64 {
private static char[] TOCHAR = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
public static String encode(byte[] bytes) {
StringBuilder builder = new StringBuilder();
int i = bytes.length;
int k = i/3;
for (int n = 0; n < k; n++) {
if (n > 0 && n % 19 == 0) {
builder.append('\n');
}
builder.append(convertToString(bytes[3*n], bytes[3*n+1], bytes[3*n+2]));
}
k = i % 3;
if (k == 2) {
char[] chars = convertToString(bytes[i-2], bytes[i-1], 0);
chars[3] = '=';
builder.append(chars);
} else if (k == 1) {
char[] chars = convertToString(bytes[i-1], 0, 0);
chars[2] = '=';
chars[3] = '=';
builder.append(chars);
}
return builder.toString();
}
private static char[] convertToString(int b, int c, int d) {
char[] result = new char[4];
if (b < 0) {
b += 256;
}
if (c < 0) {
c += 256;
}
if (d < 0) {
d += 256;
}
int f = d+(c+b*256)*256;
result[3] = TOCHAR[f % 64];
f /= 64;
result[2] = TOCHAR[f % 64];
f /= 64;
result[1] = TOCHAR[f % 64];
f /= 64;
result[0] = TOCHAR[f % 64];
return result;
}
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2010-2013 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.sparserss;
import java.io.File;
import java.io.FilenameFilter;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.NotificationManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import de.shandschuh.sparserss.provider.FeedData;
import de.shandschuh.sparserss.provider.OPML;
import de.shandschuh.sparserss.service.RefreshService;
public class RSSOverview extends ListActivity implements Requeryable {
private static final int DIALOG_ERROR_FEEDIMPORT = 3;
private static final int DIALOG_ERROR_FEEDEXPORT = 4;
private static final int DIALOG_ERROR_INVALIDIMPORTFILE = 5;
private static final int DIALOG_ERROR_EXTERNALSTORAGENOTAVAILABLE = 6;
private static final int DIALOG_ABOUT = 7;
private static final int CONTEXTMENU_EDIT_ID = 3;
private static final int CONTEXTMENU_REFRESH_ID = 4;
private static final int CONTEXTMENU_DELETE_ID = 5;
private static final int CONTEXTMENU_MARKASREAD_ID = 6;
private static final int CONTEXTMENU_MARKASUNREAD_ID = 7;
private static final int CONTEXTMENU_DELETEREAD_ID = 8;
private static final int CONTEXTMENU_DELETEALLENTRIES_ID = 9;
private static final int CONTEXTMENU_RESETUPDATEDATE_ID = 10;
private static final int ACTIVITY_APPLICATIONPREFERENCES_ID = 1;
private static final Uri CANGELOG_URI = Uri.parse("http://code.google.com/p/sparserss/wiki/Changelog");
static NotificationManager notificationManager; // package scope
boolean feedSort;
private RSSOverviewListAdapter listAdapter;
private Menu menu;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
if (MainTabActivity.isLightTheme(this)) {
setTheme(R.style.Theme_Light);
}
super.onCreate(savedInstanceState);
if (notificationManager == null) {
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
setContentView(R.layout.main);
listAdapter = new RSSOverviewListAdapter(this);
setListAdapter(listAdapter);
getListView().setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
menu.setHeaderTitle(((TextView) ((AdapterView.AdapterContextMenuInfo) menuInfo).targetView.findViewById(android.R.id.text1)).getText());
menu.add(0, CONTEXTMENU_REFRESH_ID, Menu.NONE, R.string.contextmenu_refresh);
menu.add(0, CONTEXTMENU_MARKASREAD_ID, Menu.NONE, R.string.contextmenu_markasread);
menu.add(0, CONTEXTMENU_MARKASUNREAD_ID, Menu.NONE, R.string.contextmenu_markasunread);
menu.add(0, CONTEXTMENU_DELETEREAD_ID, Menu.NONE, R.string.contextmenu_deleteread);
menu.add(0, CONTEXTMENU_DELETEALLENTRIES_ID, Menu.NONE, R.string.contextmenu_deleteallentries);
menu.add(0, CONTEXTMENU_EDIT_ID, Menu.NONE, R.string.contextmenu_edit);
menu.add(0, CONTEXTMENU_RESETUPDATEDATE_ID, Menu.NONE, R.string.contextmenu_resetupdatedate);
menu.add(0, CONTEXTMENU_DELETE_ID, Menu.NONE, R.string.contextmenu_delete);
}
});
getListView().setOnTouchListener(new OnTouchListener() {
private int dragedItem = -1;
private ImageView dragedView;
private WindowManager windowManager = RSSOverview.this.getWindowManager();
private LayoutParams layoutParams;
private int minY;
private ListView listView = getListView();
public boolean onTouch(View v, MotionEvent event) {
if (feedSort) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE: {
// this is the drag/move action
if (dragedItem == -1) {
dragedItem = listView.pointToPosition((int) event.getX(), (int) event.getY());
if (dragedItem > -1) {
dragedView = new ImageView(listView.getContext());
View item = listView.getChildAt(dragedItem - listView.getFirstVisiblePosition());
if (item != null) {
View sortView = item.findViewById(R.id.sortitem);
if (sortView.getLeft() <= event.getX()) {
minY = getMinY(); // this has to be determined after the layouting process
item.setDrawingCacheEnabled(true);
dragedView.setImageBitmap(Bitmap.createBitmap(item.getDrawingCache()));
layoutParams = new LayoutParams();
layoutParams.height = LayoutParams.WRAP_CONTENT;
layoutParams.gravity = Gravity.TOP;
layoutParams.y = (int) event.getY();
windowManager.addView(dragedView, layoutParams);
} else {
dragedItem = -1;
return false; // do not consume
}
} else {
dragedItem = -1;
}
}
} else if (dragedView != null) {
layoutParams.y = Math.max(minY, Math.max(0, Math.min((int) event.getY(), listView.getHeight()-minY)));
windowManager.updateViewLayout(dragedView, layoutParams);
}
break;
}
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL: {
// this is the drop action
if (dragedItem > -1) {
windowManager.removeView(dragedView);
int newPosition = listView.pointToPosition((int) event.getX(), (int) event.getY());
if (newPosition == -1) {
newPosition = listView.getCount()-1;
}
if (newPosition != dragedItem) {
ContentValues values = new ContentValues();
values.put(FeedData.FeedColumns.PRIORITY, newPosition);
getContentResolver().update(FeedData.FeedColumns.CONTENT_URI(listView.getItemIdAtPosition(dragedItem)), values, null, null);
}
dragedItem = -1;
return true;
} else {
return false;
}
}
}
return true;
} else {
return false;
}
}
private int getMinY() {
int[] xy = new int[2];
getListView().getLocationInWindow(xy);
return xy[1] - 25;
}
});
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Strings.SETTINGS_REFRESHENABLED, false)) {
startService(new Intent(this, RefreshService.class)); // starts the service independent to this activity
} else {
stopService(new Intent(this, RefreshService.class));
}
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(Strings.SETTINGS_REFRESHONPENENABLED, false)) {
new Thread() {
public void run() {
sendBroadcast(new Intent(Strings.ACTION_REFRESHFEEDS));
}
}.start();
}
}
@Override
protected void onResume() {
super.onResume();
if (RSSOverview.notificationManager != null) {
notificationManager.cancel(0);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.feedoverview, menu);
this.menu = menu;
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (menu == null) {
menu = this.menu;
}
if (menu != null) { // menu can still be null since the MainTabActivity.internalSetProgressBarIndeterminateVisibility method may be called first
menu.setGroupVisible(R.id.menu_group_1, feedSort);
if (feedSort) {
menu.setGroupVisible(R.id.menu_group_0, false);
} else {
menu.setGroupVisible(R.id.menu_group_0, true);
MenuItem refreshMenuItem = menu.findItem(R.id.menu_refresh);
if (MainTabActivity.INSTANCE.isProgressBarVisible()) {
refreshMenuItem.setIcon(android.R.drawable.ic_menu_close_clear_cancel);
refreshMenuItem.setTitle(R.string.menu_cancelrefresh);
} else {
refreshMenuItem.setIcon(android.R.drawable.ic_menu_rotate);
refreshMenuItem.setTitle(R.string.menu_refresh);
}
}
}
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, final MenuItem item) {
setFeedSortEnabled(false);
switch (item.getItemId()) {
case R.id.menu_addfeed: {
startActivity(new Intent(Intent.ACTION_INSERT).setData(FeedData.FeedColumns.CONTENT_URI));
break;
}
case R.id.menu_refresh: {
if (MainTabActivity.INSTANCE.isProgressBarVisible()) {
sendBroadcast(new Intent(Strings.ACTION_STOPREFRESHFEEDS));
} else {
new Thread() {
public void run() {
sendBroadcast(new Intent(Strings.ACTION_REFRESHFEEDS).putExtra(Strings.SETTINGS_OVERRIDEWIFIONLY, PreferenceManager.getDefaultSharedPreferences(RSSOverview.this).getBoolean(Strings.SETTINGS_OVERRIDEWIFIONLY, false)));
}
}.start();
}
break;
}
case CONTEXTMENU_EDIT_ID: {
startActivity(new Intent(Intent.ACTION_EDIT).setData(FeedData.FeedColumns.CONTENT_URI(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id)));
break;
}
case CONTEXTMENU_REFRESH_ID: {
final String id = Long.toString(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id);
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED) { // since we have acquired the networkInfo, we use it for basic checks
final Intent intent = new Intent(Strings.ACTION_REFRESHFEEDS).putExtra(Strings.FEEDID, id);
final Thread thread = new Thread() {
public void run() {
sendBroadcast(intent);
}
};
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI || PreferenceManager.getDefaultSharedPreferences(RSSOverview.this).getBoolean(Strings.SETTINGS_OVERRIDEWIFIONLY, false)) {
intent.putExtra(Strings.SETTINGS_OVERRIDEWIFIONLY, true);
thread.start();
} else {
Cursor cursor = getContentResolver().query(FeedData.FeedColumns.CONTENT_URI(id), new String[] {FeedData.FeedColumns.WIFIONLY}, null, null, null);
cursor.moveToFirst();
if (cursor.isNull(0) || cursor.getInt(0) == 0) {
thread.start();
} else {
Builder builder = new AlertDialog.Builder(this);
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setTitle(R.string.dialog_hint);
builder.setMessage(R.string.question_refreshwowifi);
builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
intent.putExtra(Strings.SETTINGS_OVERRIDEWIFIONLY, true);
thread.start();
}
});
builder.setNeutralButton(R.string.button_alwaysokforall, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
PreferenceManager.getDefaultSharedPreferences(RSSOverview.this).edit().putBoolean(Strings.SETTINGS_OVERRIDEWIFIONLY, true).commit();
intent.putExtra(Strings.SETTINGS_OVERRIDEWIFIONLY, true);
thread.start();
}
});
builder.setNegativeButton(android.R.string.no, null);
builder.show();
}
cursor.close();
}
}
break;
}
case CONTEXTMENU_DELETE_ID: {
String id = Long.toString(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id);
Cursor cursor = getContentResolver().query(FeedData.FeedColumns.CONTENT_URI(id), new String[] {FeedData.FeedColumns.NAME}, null, null, null);
cursor.moveToFirst();
Builder builder = new AlertDialog.Builder(this);
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setTitle(cursor.getString(0));
builder.setMessage(R.string.question_deletefeed);
builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new Thread() {
public void run() {
getContentResolver().delete(FeedData.FeedColumns.CONTENT_URI(Long.toString(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id)), null, null);
sendBroadcast(new Intent(Strings.ACTION_UPDATEWIDGET));
}
}.start();
}
});
builder.setNegativeButton(android.R.string.no, null);
cursor.close();
builder.show();
break;
}
case CONTEXTMENU_MARKASREAD_ID: {
new Thread() {
public void run() {
String id = Long.toString(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id);
if (getContentResolver().update(FeedData.EntryColumns.CONTENT_URI(id), getReadContentValues(), new StringBuilder(FeedData.EntryColumns.READDATE).append(Strings.DB_ISNULL).toString(), null) > 0) {
getContentResolver().notifyChange(FeedData.FeedColumns.CONTENT_URI(id), null);
}
}
}.start();
break;
}
case CONTEXTMENU_MARKASUNREAD_ID: {
new Thread() {
public void run() {
String id = Long.toString(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id);
if (getContentResolver().update(FeedData.EntryColumns.CONTENT_URI(id), getUnreadContentValues(), null, null) > 0) {
getContentResolver().notifyChange(FeedData.FeedColumns.CONTENT_URI(id), null);;
}
}
}.start();
break;
}
case CONTEXTMENU_DELETEREAD_ID: {
new Thread() {
public void run() {
String id = Long.toString(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id);
Uri uri = FeedData.EntryColumns.CONTENT_URI(id);
String selection = Strings.READDATE_GREATERZERO+Strings.DB_AND+" ("+Strings.DB_EXCUDEFAVORITE+")";
FeedData.deletePicturesOfFeed(RSSOverview.this, uri, selection);
if (getContentResolver().delete(uri, selection, null) > 0) {
getContentResolver().notifyChange(FeedData.FeedColumns.CONTENT_URI(id), null);
}
}
}.start();
break;
}
case CONTEXTMENU_DELETEALLENTRIES_ID: {
showDeleteAllEntriesQuestion(this, FeedData.EntryColumns.CONTENT_URI(Long.toString(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id)));
break;
}
case CONTEXTMENU_RESETUPDATEDATE_ID: {
ContentValues values = new ContentValues();
values.put(FeedData.FeedColumns.LASTUPDATE, 0);
values.put(FeedData.FeedColumns.REALLASTUPDATE, 0);
getContentResolver().update(FeedData.FeedColumns.CONTENT_URI(Long.toString(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).id)), values, null, null);
break;
}
case R.id.menu_settings: {
startActivityForResult(new Intent(this, ApplicationPreferencesActivity.class), ACTIVITY_APPLICATIONPREFERENCES_ID);
break;
}
case R.id.menu_allread: {
new Thread() {
public void run() {
if (getContentResolver().update(FeedData.EntryColumns.CONTENT_URI, getReadContentValues(), new StringBuilder(FeedData.EntryColumns.READDATE).append(Strings.DB_ISNULL).toString(), null) > 0) {
getContentResolver().notifyChange(FeedData.FeedColumns.CONTENT_URI, null);
}
}
}.start();
break;
}
case R.id.menu_about: {
showDialog(DIALOG_ABOUT);
break;
}
case R.id.menu_import: {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ||Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.select_file);
try {
final String[] fileNames = Environment.getExternalStorageDirectory().list(new FilenameFilter() {
public boolean accept(File dir, String filename) {
return new File(dir, filename).isFile();
}
});
builder.setItems(fileNames, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
OPML.importFromFile(new StringBuilder(Environment.getExternalStorageDirectory().toString()).append(File.separator).append(fileNames[which]).toString(), RSSOverview.this);
} catch (Exception e) {
showDialog(DIALOG_ERROR_FEEDIMPORT);
}
}
});
builder.show();
} catch (Exception e) {
showDialog(DIALOG_ERROR_FEEDIMPORT);
}
} else {
showDialog(DIALOG_ERROR_EXTERNALSTORAGENOTAVAILABLE);
}
break;
}
case R.id.menu_export: {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ||Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
try {
String filename = new StringBuilder(Environment.getExternalStorageDirectory().toString()).append("/sparse_rss_").append(System.currentTimeMillis()).append(".opml").toString();
OPML.exportToFile(filename, this);
Toast.makeText(this, String.format(getString(R.string.message_exportedto), filename), Toast.LENGTH_LONG).show();
} catch (Exception e) {
showDialog(DIALOG_ERROR_FEEDEXPORT);
}
} else {
showDialog(DIALOG_ERROR_EXTERNALSTORAGENOTAVAILABLE);
}
break;
}
case R.id.menu_enablefeedsort: {
setFeedSortEnabled(true);
break;
}
case R.id.menu_deleteread: {
FeedData.deletePicturesOfFeedAsync(this, FeedData.EntryColumns.CONTENT_URI, Strings.READDATE_GREATERZERO);
getContentResolver().delete(FeedData.EntryColumns.CONTENT_URI, Strings.READDATE_GREATERZERO, null);
((RSSOverviewListAdapter) getListAdapter()).notifyDataSetChanged();
break;
}
case R.id.menu_deleteallentries: {
showDeleteAllEntriesQuestion(this, FeedData.EntryColumns.CONTENT_URI);
break;
}
case R.id.menu_disablefeedsort: {
// do nothing as the feed sort gets disabled anyway
break;
}
}
return true;
}
public static final ContentValues getReadContentValues() {
ContentValues values = new ContentValues();
values.put(FeedData.EntryColumns.READDATE, System.currentTimeMillis());
return values;
}
public static final ContentValues getUnreadContentValues() {
ContentValues values = new ContentValues();
values.putNull(FeedData.EntryColumns.READDATE);
return values;
}
@Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
setFeedSortEnabled(false);
Intent intent = new Intent(Intent.ACTION_VIEW, FeedData.EntryColumns.CONTENT_URI(Long.toString(id)));
intent.putExtra(FeedData.FeedColumns._ID, id);
startActivity(intent);
}
@Override
protected Dialog onCreateDialog(int id) {
Dialog dialog;
switch (id) {
case DIALOG_ERROR_FEEDIMPORT: {
dialog = createErrorDialog(R.string.error_feedimport);
break;
}
case DIALOG_ERROR_FEEDEXPORT: {
dialog = createErrorDialog(R.string.error_feedexport);
break;
}
case DIALOG_ERROR_INVALIDIMPORTFILE: {
dialog = createErrorDialog(R.string.error_invalidimportfile);
break;
}
case DIALOG_ERROR_EXTERNALSTORAGENOTAVAILABLE: {
dialog = createErrorDialog(R.string.error_externalstoragenotavailable);
break;
}
case DIALOG_ABOUT: {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(android.R.drawable.ic_dialog_info);
builder.setTitle(R.string.menu_about);
MainTabActivity.INSTANCE.setupLicenseText(builder);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setNeutralButton(R.string.changelog, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(Intent.ACTION_VIEW, CANGELOG_URI));
}
});
return builder.create();
}
default: dialog = null;
}
return dialog;
}
private Dialog createErrorDialog(int messageId) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(messageId);
builder.setTitle(R.string.error);
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setPositiveButton(android.R.string.ok, null);
return builder.create();
}
private static void showDeleteAllEntriesQuestion(final Context context, final Uri uri) {
Builder builder = new AlertDialog.Builder(context);
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setTitle(R.string.contextmenu_deleteallentries);
builder.setMessage(R.string.question_areyousure);
builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new Thread() {
public void run() {
FeedData.deletePicturesOfFeed(context, uri, Strings.DB_EXCUDEFAVORITE);
if (context.getContentResolver().delete(uri, Strings.DB_EXCUDEFAVORITE, null) > 0) {
context.getContentResolver().notifyChange(FeedData.FeedColumns.CONTENT_URI, null);
}
}
}.start();
}
});
builder.setNegativeButton(android.R.string.no, null);
builder.show();
}
private void setFeedSortEnabled(boolean enabled) {
if (enabled != feedSort) {
listAdapter.setFeedSortEnabled(enabled);
feedSort = enabled;
}
}
@Override
public void requery() {
if (listAdapter != null) {
listAdapter.notifyDataSetChanged();
}
}
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2012 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.sparserss;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
public class Animations {
/** Slide in from right */
public static final TranslateAnimation SLIDE_IN_RIGHT = generateAnimation(1, 0);
/** Slide in from left */
public static final TranslateAnimation SLIDE_IN_LEFT = generateAnimation(-1, 0);
/** Slide out to right */
public static final TranslateAnimation SLIDE_OUT_RIGHT = generateAnimation(0, 1);
/** Slide out to left */
public static final TranslateAnimation SLIDE_OUT_LEFT = generateAnimation(0, -1);
/** Duration of one animation */
private static final long DURATION = 180;
private static TranslateAnimation generateAnimation(float fromX, float toX) {
TranslateAnimation transformAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, fromX, Animation.RELATIVE_TO_SELF, toX, 0, 0, 0, 0);
transformAnimation.setDuration(DURATION);
return transformAnimation;
}
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2010-2013 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.sparserss;
import java.text.DateFormat;
import java.util.Date;
import java.util.Vector;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;
import de.shandschuh.sparserss.provider.FeedData;
public class EntriesListAdapter extends ResourceCursorAdapter {
private static final int STATE_NEUTRAL = 0;
private static final int STATE_ALLREAD = 1;
private static final int STATE_ALLUNREAD = 2;
private int titleColumnPosition;
private int dateColumn;
private int readDateColumn;
private int favoriteColumn;
private int idColumn;
private int feedIconColumn;
private int feedNameColumn;
private int linkColumn;
private static final String SQLREAD = "length(readdate) ASC, ";
public static final String READDATEISNULL = FeedData.EntryColumns.READDATE+Strings.DB_ISNULL;
private boolean hideRead;
private Activity context;
private Uri uri;
private boolean showFeedInfo;
private int forcedState;
private Vector<Long> markedAsRead;
private Vector<Long> markedAsUnread;
private Vector<Long> favorited;
private Vector<Long> unfavorited;
private DateFormat dateFormat;
private DateFormat timeFormat;
public EntriesListAdapter(Activity context, Uri uri, boolean showFeedInfo, boolean autoreload, boolean hideRead) {
super(context, R.layout.entrylistitem, createManagedCursor(context, uri, hideRead), autoreload);
this.hideRead = hideRead;
this.context = context;
this.uri = uri;
Cursor cursor = getCursor();
titleColumnPosition = cursor.getColumnIndex(FeedData.EntryColumns.TITLE);
dateColumn = cursor.getColumnIndex(FeedData.EntryColumns.DATE);
readDateColumn = cursor.getColumnIndex(FeedData.EntryColumns.READDATE);
favoriteColumn = cursor.getColumnIndex(FeedData.EntryColumns.FAVORITE);
idColumn = cursor.getColumnIndex(FeedData.EntryColumns._ID);
linkColumn = cursor.getColumnIndex(FeedData.EntryColumns.LINK);
this.showFeedInfo = showFeedInfo;
if (showFeedInfo) {
feedIconColumn = cursor.getColumnIndex(FeedData.FeedColumns.ICON);
feedNameColumn = cursor.getColumnIndex(FeedData.FeedColumns.NAME);
}
forcedState = STATE_NEUTRAL;
markedAsRead = new Vector<Long>();
markedAsUnread = new Vector<Long>();
favorited = new Vector<Long>();
unfavorited = new Vector<Long>();
dateFormat = android.text.format.DateFormat.getDateFormat(context);
timeFormat = android.text.format.DateFormat.getTimeFormat(context);
}
@Override
public void bindView(View view, final Context context, Cursor cursor) {
TextView textView = (TextView) view.findViewById(android.R.id.text1);
String link = cursor.getString(linkColumn);
String title = cursor.getString(titleColumnPosition);
textView.setText(title == null || title.length() == 0 ? link : title);
TextView dateTextView = (TextView) view.findViewById(android.R.id.text2);
final ImageView imageView = (ImageView) view.findViewById(android.R.id.icon);
final long id = cursor.getLong(idColumn);
view.setTag(link);
final boolean favorite = !unfavorited.contains(id) && (cursor.getInt(favoriteColumn) == 1 || favorited.contains(id));
imageView.setImageResource(favorite ? android.R.drawable.star_on : android.R.drawable.star_off);
imageView.setTag(favorite ? Strings.TRUE : Strings.FALSE);
imageView.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
boolean newFavorite = !Strings.TRUE.equals(view.getTag());
if (newFavorite) {
view.setTag(Strings.TRUE);
imageView.setImageResource(android.R.drawable.star_on);
favorited.add(id);
unfavorited.remove(id);
} else {
view.setTag(Strings.FALSE);
imageView.setImageResource(android.R.drawable.star_off);
unfavorited.add(id);
favorited.remove(id);
}
ContentValues values = new ContentValues();
values.put(FeedData.EntryColumns.FAVORITE, newFavorite ? 1 : 0);
view.getContext().getContentResolver().update(uri, values, new StringBuilder(FeedData.EntryColumns._ID).append(Strings.DB_ARG).toString(), new String[] {Long.toString(id)});
context.getContentResolver().notifyChange(FeedData.EntryColumns.FAVORITES_CONTENT_URI, null);
}
});
Date date = new Date(cursor.getLong(dateColumn));
if (showFeedInfo && feedIconColumn > -1 && feedNameColumn > -1) {
byte[] iconBytes = cursor.getBlob(feedIconColumn);
if (iconBytes != null && iconBytes.length > 0) {
Bitmap bitmap = BitmapFactory.decodeByteArray(iconBytes, 0, iconBytes.length);
if (bitmap != null) {
int bitmapSizeInDip = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 18f, context.getResources().getDisplayMetrics());
if (bitmap.getHeight() != bitmapSizeInDip) {
bitmap = Bitmap.createScaledBitmap(bitmap, bitmapSizeInDip, bitmapSizeInDip, false);
}
dateTextView.setText(new StringBuilder().append(' ').append(dateFormat.format(date)).append(' ').append(timeFormat.format(date)).append(Strings.COMMASPACE).append(cursor.getString(feedNameColumn))); // bad style
} else {
dateTextView.setText(new StringBuilder(dateFormat.format(date)).append(' ').append(timeFormat.format(date)).append(Strings.COMMASPACE).append(cursor.getString(feedNameColumn)));
}
dateTextView.setCompoundDrawablesWithIntrinsicBounds(new BitmapDrawable(bitmap), null, null, null);
} else {
dateTextView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
dateTextView.setText(new StringBuilder(dateFormat.format(date)).append(' ').append(timeFormat.format(date)).append(Strings.COMMASPACE).append(cursor.getString(feedNameColumn)));
}
} else {
dateTextView.setText(new StringBuilder(dateFormat.format(date)).append(' ').append(timeFormat.format(date)));
}
if (forcedState == STATE_ALLUNREAD && !markedAsRead.contains(id) || (forcedState != STATE_ALLREAD && cursor.isNull(readDateColumn) && !markedAsRead.contains(id)) || markedAsUnread.contains(id)) {
textView.setEnabled(true);
} else {
textView.setEnabled(false);
}
}
public boolean isHideRead() {
return hideRead;
}
public void setHideRead(boolean hideRead) {
if (hideRead != this.hideRead) {
this.hideRead = hideRead;
reloadCursor();
}
}
public void reloadCursor() {
markedAsRead.clear();
markedAsUnread.clear();
favorited.clear();
unfavorited.clear();
context.stopManagingCursor(getCursor());
forcedState = STATE_NEUTRAL;
changeCursor(createManagedCursor(context, uri, hideRead));
notifyDataSetInvalidated();
}
private static Cursor createManagedCursor(Activity context, Uri uri, boolean hideRead) {
return context.managedQuery(uri, null, hideRead ? READDATEISNULL : null, null, new StringBuilder(PreferenceManager.getDefaultSharedPreferences(context).getBoolean(Strings.SETTINGS_PRIORITIZE, false) ? SQLREAD : Strings.EMPTY).append(FeedData.EntryColumns.DATE).append(Strings.DB_DESC).toString());
}
public void markAsRead() {
if (hideRead) {
reloadCursor(); // well, the cursor should be empty
} else {
forcedState = STATE_ALLREAD;
markedAsRead.clear();
markedAsUnread.clear();
notifyDataSetInvalidated();
}
}
public void markAsUnread() {
forcedState = STATE_ALLUNREAD;
markedAsRead.clear();
markedAsUnread.clear();
notifyDataSetInvalidated();
}
public void neutralizeReadState() {
forcedState = STATE_NEUTRAL;
}
public void markAsRead(long id) {
if (hideRead) {
reloadCursor();
} else {
markedAsRead.add(id);
markedAsUnread.remove(id);
notifyDataSetInvalidated();
}
}
public void markAsUnread(long id) {
markedAsUnread.add(id);
markedAsRead.remove(id);
notifyDataSetInvalidated();
}
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2012 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.sparserss;
public abstract class SimpleTask implements Runnable {
private boolean canceled = false;
private int postCount = 0;
public abstract void runControlled();
public void cancel() {
canceled = true;
}
public boolean isCanceled() {
return canceled;
}
public void post() {
post(1);
}
public synchronized void post(int count) {
postCount += count;
canceled = false;
}
public boolean isPosted() {
return postCount > 0;
}
public int getPostCount() {
return postCount;
}
public final synchronized void run() {
if (!canceled) {
runControlled();
}
postRun();
postCount--;
}
/**
* Override to use
*/
public void postRun() {
}
public void enable() {
canceled = false;
}
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2010-2012 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.sparserss.widget;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.view.View;
import android.view.View.OnClickListener;
import de.shandschuh.sparserss.R;
import de.shandschuh.sparserss.provider.FeedData;
public class WidgetConfigActivity extends PreferenceActivity {
private int widgetId;
private static final String NAMECOLUMN = new StringBuilder("ifnull(").append(FeedData.FeedColumns.NAME).append(',').append(FeedData.FeedColumns.URL).append(") as title").toString();
public static final String ZERO = "0";
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setResult(RESULT_CANCELED);
Bundle extras = getIntent().getExtras();
if (extras != null) {
widgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
}
if (widgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
finish();
}
addPreferencesFromResource(R.layout.widgetpreferences);
setContentView(R.layout.widgetconfig);
final ListPreference entryCountPreference = (ListPreference) findPreference("widget.entrycount");
final PreferenceCategory feedsPreferenceCategory = (PreferenceCategory) findPreference("widget.visiblefeeds");
Cursor cursor = this.getContentResolver().query(FeedData.FeedColumns.CONTENT_URI, new String[] {FeedData.FeedColumns._ID, NAMECOLUMN}, null, null, null);
if (cursor.moveToFirst()) {
int[] ids = new int[cursor.getCount()+1];
CheckBoxPreference checkboxPreference = new CheckBoxPreference(this);
checkboxPreference.setTitle(R.string.all_feeds);
feedsPreferenceCategory.addPreference(checkboxPreference);
checkboxPreference.setKey(ZERO);
checkboxPreference.setDisableDependentsState(true);
ids[0] = 0;
for (int n = 1; !cursor.isAfterLast(); cursor.moveToNext(), n++) {
checkboxPreference = new CheckBoxPreference(this);
checkboxPreference.setTitle(cursor.getString(1));
ids[n] = cursor.getInt(0);
checkboxPreference.setKey(Integer.toString(ids[n]));
feedsPreferenceCategory.addPreference(checkboxPreference);
checkboxPreference.setDependency(ZERO);
}
cursor.close();
findViewById(R.id.save_button).setOnClickListener(new OnClickListener() {
public void onClick(View view) {
SharedPreferences.Editor preferences = getSharedPreferences(SparseRSSAppWidgetProvider.class.getName(), 0).edit();
boolean hideRead = false;//((CheckBoxPreference) getPreferenceManager().findPreference("widget.hideread")).isChecked();
preferences.putBoolean(widgetId+".hideread", hideRead);
StringBuilder builder = new StringBuilder();
for (int n = 0, i = feedsPreferenceCategory.getPreferenceCount(); n < i; n++) {
CheckBoxPreference preference = (CheckBoxPreference) feedsPreferenceCategory.getPreference(n);
if (preference.isChecked()) {
if (n == 0) {
break;
} else {
if (builder.length() > 0) {
builder.append(',');
}
builder.append(preference.getKey());
}
}
}
String feedIds = builder.toString();
String entryCount = entryCountPreference.getValue();
preferences.putString(widgetId+".feeds", feedIds);
preferences.putString(widgetId+".entrycount", entryCount);
int color = getPreferenceManager().getSharedPreferences().getInt("widget.background", SparseRSSAppWidgetProvider.STANDARD_BACKGROUND);
preferences.putInt(widgetId+".background", color);
preferences.commit();
SparseRSSAppWidgetProvider.updateAppWidget(WidgetConfigActivity.this, widgetId, hideRead, entryCount, feedIds, color);
setResult(RESULT_OK, new Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId));
finish();
}
});
} else {
// no feeds found --> use all feeds, no dialog needed
cursor.close();
setResult(RESULT_OK, new Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId));
}
}
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2012 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.sparserss.widget;
import android.content.Context;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import de.shandschuh.sparserss.R;
public class ColorPickerDialogPreference extends DialogPreference {
private SeekBar redSeekBar;
private SeekBar greenSeekBar;
private SeekBar blueSeekBar;
private SeekBar transparencySeekBar;
int color;
public ColorPickerDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
color = SparseRSSAppWidgetProvider.STANDARD_BACKGROUND;
}
@Override
protected View onCreateDialogView() {
final View view = super.onCreateDialogView();
view.setBackgroundColor(color);
redSeekBar = (SeekBar) view.findViewById(R.id.seekbar_red);
greenSeekBar = (SeekBar) view.findViewById(R.id.seekbar_green);
blueSeekBar = (SeekBar) view.findViewById(R.id.seekbar_blue);
transparencySeekBar = (SeekBar) view.findViewById(R.id.seekbar_transparency);
int _color = color;
transparencySeekBar.setProgress(((_color / 0x01000000)*100)/255);
_color %= 0x01000000;
redSeekBar.setProgress(((_color / 0x00010000)*100)/255);
_color %= 0x00010000;
greenSeekBar.setProgress(((_color / 0x00000100)*100)/255);
_color %= 0x00000100;
blueSeekBar.setProgress((_color*100)/255);
OnSeekBarChangeListener onSeekBarChangeListener = new OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
int red = (redSeekBar.getProgress()*255) / 100;
int green = (greenSeekBar.getProgress()*255) / 100;
int blue = (blueSeekBar.getProgress()*255) / 100;
int transparency = (transparencySeekBar.getProgress()*255) / 100;
color = transparency*0x01000000 + red*0x00010000 + green*0x00000100 + blue;
view.setBackgroundColor(color);
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
redSeekBar.setOnSeekBarChangeListener(onSeekBarChangeListener);
greenSeekBar.setOnSeekBarChangeListener(onSeekBarChangeListener);
blueSeekBar.setOnSeekBarChangeListener(onSeekBarChangeListener);
transparencySeekBar.setOnSeekBarChangeListener(onSeekBarChangeListener);
return view;
}
@Override
protected void onDialogClosed(boolean positiveResult) {
if (positiveResult) {
persistInt(color);
}
super.onDialogClosed(positiveResult);
}
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2010-2012 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.sparserss.widget;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.widget.RemoteViews;
import de.shandschuh.sparserss.MainTabActivity;
import de.shandschuh.sparserss.R;
import de.shandschuh.sparserss.Strings;
import de.shandschuh.sparserss.provider.FeedData;
public class SparseRSSAppWidgetProvider extends AppWidgetProvider {
private static final String LIMIT = " limit ";
private static final int[] IDS = {R.id.news_1, R.id.news_2, R.id.news_3, R.id.news_4, R.id.news_5, R.id.news_6, R.id.news_7, R.id.news_8, R.id.news_9, R.id.news_10};
private static final int[] ICON_IDS = {R.id.news_icon_1, R.id.news_icon_2, R.id.news_icon_3, R.id.news_icon_4, R.id.news_icon_5, R.id.news_icon_6, R.id.news_icon_7, R.id.news_icon_8, R.id.news_icon_9, R.id.news_icon_10};
public static final int STANDARD_BACKGROUND = 0x7c000000;
@Override
public void onReceive(Context context, Intent intent) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
onUpdate(context, appWidgetManager, appWidgetManager.getAppWidgetIds(new ComponentName(context, SparseRSSAppWidgetProvider.class)));
}
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
SharedPreferences preferences = context.getSharedPreferences(SparseRSSAppWidgetProvider.class.getName(), 0);
for (int n = 0, i = appWidgetIds.length; n < i; n++) {
updateAppWidget(context, appWidgetManager, appWidgetIds[n], preferences.getBoolean(appWidgetIds[n]+".hideread", false), preferences.getString(appWidgetIds[n]+".entrycount", "10"), preferences.getString(appWidgetIds[n]+".feeds", Strings.EMPTY), preferences.getInt(appWidgetIds[n]+".background", STANDARD_BACKGROUND));
}
}
static void updateAppWidget(Context context, int appWidgetId, boolean hideRead, String entryCount, String feedIds, int backgroundColor) {
updateAppWidget(context, AppWidgetManager.getInstance(context), appWidgetId, hideRead, entryCount, feedIds, backgroundColor);
}
private static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId, boolean hideRead, String entryCount, String feedIds, int backgroundColor) {
StringBuilder selection = new StringBuilder();
if (hideRead) {
selection.append(FeedData.EntryColumns.READDATE).append(Strings.DB_ISNULL);
}
if (feedIds.length() > 0) {
if (selection.length() > 0) {
selection.append(Strings.DB_AND);
}
selection.append(FeedData.EntryColumns.FEED_ID).append(" IN ("+feedIds).append(')');
}
Cursor cursor = context.getContentResolver().query(FeedData.EntryColumns.CONTENT_URI, new String[] {FeedData.EntryColumns.TITLE, FeedData.EntryColumns._ID, FeedData.FeedColumns.ICON}, selection.toString(), null, new StringBuilder(FeedData.EntryColumns.DATE).append(Strings.DB_DESC).append(LIMIT).append(entryCount).toString());
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.homescreenwidget);
views.setOnClickPendingIntent(R.id.feed_icon, PendingIntent.getActivity(context, 0, new Intent(context, MainTabActivity.class), 0));
int k = 0;
while (cursor.moveToNext() && k < IDS.length) {
views.setViewVisibility(IDS[k], View.VISIBLE);
if (!cursor.isNull(2)) {
try {
byte[] iconBytes = cursor.getBlob(2);
if (iconBytes != null && iconBytes.length > 0) {
Bitmap bitmap = BitmapFactory.decodeByteArray(iconBytes, 0, iconBytes.length);
if (bitmap != null) {
views.setBitmap(ICON_IDS[k], "setImageBitmap", bitmap);
views.setViewVisibility(ICON_IDS[k], View.VISIBLE);
views.setTextViewText(IDS[k], " "+cursor.getString(0)); // bad style
} else {
views.setViewVisibility(ICON_IDS[k], View.GONE);
views.setTextViewText(IDS[k], cursor.getString(0));
}
} else {
views.setViewVisibility(ICON_IDS[k], View.GONE);
views.setTextViewText(IDS[k], cursor.getString(0));
}
} catch (Throwable e) {
views.setViewVisibility(ICON_IDS[k], View.GONE);
views.setTextViewText(IDS[k], cursor.getString(0));
}
} else {
views.setViewVisibility(ICON_IDS[k], View.GONE);
views.setTextViewText(IDS[k], cursor.getString(0));
}
views.setOnClickPendingIntent(IDS[k++], PendingIntent.getActivity(context, 0, new Intent(Intent.ACTION_VIEW, FeedData.EntryColumns.ENTRY_CONTENT_URI(cursor.getString(1))), PendingIntent.FLAG_CANCEL_CURRENT));
}
cursor.close();
for (; k < IDS.length; k++) {
views.setViewVisibility(ICON_IDS[k], View.GONE);
views.setViewVisibility(IDS[k], View.GONE);
views.setTextViewText(IDS[k], Strings.EMPTY);
}
views.setInt(R.id.widgetlayout, "setBackgroundColor", backgroundColor);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2012 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*
* ==============================================================================
* This helper class is needed for older Android versions that verify all
* existing references on startup.
*/
package de.shandschuh.sparserss;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.webkit.WebView;
public class CompatibilityHelper {
private static final String METHOD_GETACTIONBAR = "getActionBar";
private static final String METHOD_SETICON = "setIcon";
private static final String METHOD_ONRESUME = "onResume";
private static final String METHOD_ONPAUSE = "onPause";
public static void setActionBarDrawable(Activity activity, Drawable drawable) {
try {
Object actionBar = Activity.class.getMethod(METHOD_GETACTIONBAR).invoke(activity);
actionBar.getClass().getMethod(METHOD_SETICON, Drawable.class).invoke(actionBar, drawable);
} catch (Exception e) {
}
}
public static void onResume(WebView webView) {
try {
WebView.class.getMethod(METHOD_ONRESUME).invoke(webView);
} catch (Exception e) {
}
}
public static void onPause(WebView webView) {
try {
WebView.class.getMethod(METHOD_ONPAUSE).invoke(webView);
} catch (Exception e) {
}
}
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2010-2012 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.sparserss;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import de.shandschuh.sparserss.service.RefreshService;
public class ApplicationPreferencesActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
if (MainTabActivity.isLightTheme(this)) {
setTheme(R.style.Theme_Light);
}
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.preferences);
Preference preference = (Preference) findPreference(Strings.SETTINGS_REFRESHENABLED);
preference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (Boolean.TRUE.equals(newValue)) {
new Thread() {
public void run() {
startService(new Intent(ApplicationPreferencesActivity.this, RefreshService.class));
}
}.start();
} else {
getPreferences(MODE_PRIVATE).edit().putLong(Strings.PREFERENCE_LASTSCHEDULEDREFRESH, 0).commit();
stopService(new Intent(ApplicationPreferencesActivity.this, RefreshService.class));
}
return true;
}
});
preference = (Preference) findPreference(Strings.SETTINGS_SHOWTABS);
preference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (MainTabActivity.INSTANCE != null ) {
MainTabActivity.INSTANCE.setTabWidgetVisible(Boolean.TRUE.equals(newValue));
}
return true;
}
});
preference = (Preference) findPreference(Strings.SETTINGS_LIGHTTHEME);
preference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
Editor editor = PreferenceManager.getDefaultSharedPreferences(ApplicationPreferencesActivity.this).edit();
editor.putBoolean(Strings.SETTINGS_LIGHTTHEME, Boolean.TRUE.equals(newValue));
editor.commit();
android.os.Process.killProcess(android.os.Process.myPid());
// this return statement will never be reached
return true;
}
});
preference = (Preference) findPreference(Strings.SETTINGS_EFFICIENTFEEDPARSING);
preference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(final Preference preference, Object newValue) {
if (newValue.equals(Boolean.FALSE)) {
AlertDialog.Builder builder = new AlertDialog.Builder(ApplicationPreferencesActivity.this);
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setTitle(android.R.string.dialog_alert_title);
builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Editor editor = PreferenceManager.getDefaultSharedPreferences(ApplicationPreferencesActivity.this).edit();
editor.putBoolean(Strings.SETTINGS_EFFICIENTFEEDPARSING, Boolean.FALSE);
editor.commit();
((CheckBoxPreference) preference).setChecked(false);
dialog.dismiss();
}
});
builder.setNegativeButton(android.R.string.cancel, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setMessage(R.string.warning_moretraffic);
builder.show();
return false;
} else {
return true;
}
}
});
}
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2010-2013 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.sparserss;
import de.shandschuh.sparserss.provider.FeedData;
public final class Strings {
public static final String PACKAGE = "de.shandschuh.sparserss";
public static final String SETTINGS_REFRESHINTERVAL = "refresh.interval";
public static final String SETTINGS_NOTIFICATIONSENABLED = "notifications.enabled";
public static final String SETTINGS_REFRESHENABLED = "refresh.enabled";
public static final String SETTINGS_REFRESHONPENENABLED = "refreshonopen.enabled";
public static final String SETTINGS_NOTIFICATIONSRINGTONE = "notifications.ringtone";
public static final String SETTINGS_NOTIFICATIONSVIBRATE = "notifications.vibrate";
public static final String SETTINGS_PRIORITIZE = "contentpresentation.prioritize";
public static final String SETTINGS_SHOWTABS = "tabs.show";
public static final String SETTINGS_FETCHPICTURES = "pictures.fetch";
public static final String SETTINGS_PROXYENABLED = "proxy.enabled";
public static final String SETTINGS_PROXYPORT = "proxy.port";
public static final String SETTINGS_PROXYHOST = "proxy.host";
public static final String SETTINGS_PROXYWIFIONLY = "proxy.wifionly";
public static final String SETTINGS_PROXYTYPE = "proxy.type";
public static final String SETTINGS_KEEPTIME = "keeptime";
public static final String SETTINGS_BLACKTEXTONWHITE = "blacktextonwhite";
public static final String SETTINGS_LIGHTTHEME = "lighttheme";
public static final String SETTINGS_FONTSIZE = "fontsize";
public static final String SETTINGS_STANDARDUSERAGENT = "standarduseragent";
public static final String SETTINGS_DISABLEPICTURES = "pictures.disable";
public static final String SETTINGS_HTTPHTTPSREDIRECTS = "httphttpsredirects";
public static final String SETTINGS_OVERRIDEWIFIONLY = "overridewifionly";
public static final String SETTINGS_GESTURESENABLED = "gestures.enabled";
public static final String SETTINGS_ENCLOSUREWARNINGSENABLED = "enclosurewarnings.enabled";
public static final String SETTINGS_EFFICIENTFEEDPARSING = "efficientfeedparsing";
public static final String ACTION_REFRESHFEEDS = "de.shandschuh.sparserss.REFRESH";
public static final String ACTION_STOPREFRESHFEEDS = "de.shandschuh.sparserss.STOPREFRESH";
public static final String ACTION_UPDATEWIDGET = "de.shandschuh.sparserss.FEEDUPDATED";
public static final String ACTION_RESTART = "de.shandschuh.sparserss.RESTART";
public static final String FEEDID = "feedid";
public static final String DB_ISNULL = " IS NULL";
public static final String DB_DESC = " DESC";
public static final String DB_ARG = "=?";
public static final String DB_AND = " AND ";
public static final String DB_EXCUDEFAVORITE = new StringBuilder(FeedData.EntryColumns.FAVORITE).append(Strings.DB_ISNULL).append(" OR ").append(FeedData.EntryColumns.FAVORITE).append("=0").toString();
public static final String EMPTY = "";
public static final String HTTP = "http://";
public static final String HTTPS = "https://";
public static final String _HTTP = "http";
public static final String _HTTPS = "https";
public static final String PROTOCOL_SEPARATOR = "://";
public static final String FILE_FAVICON = "/favicon.ico";
public static final String SPACE = " ";
public static final String TWOSPACE = " ";
public static final String HTML_TAG_REGEX = "<(.|\n)*?>";
public static final String FILEURL = "file://";
public static final String IMAGEFILE_IDSEPARATOR = "__";
public static final String IMAGEID_REPLACEMENT = "##ID##";
public static final String DEFAULTPROXYPORT = "8080";
public static final String URL_SPACE = "%20";
public static final String HTML_SPAN_REGEX = "<[/]?[ ]?span(.|\n)*?>";
public static final String HTML_IMG_REGEX = "<[/]?[ ]?img(.|\n)*?>";
public static final String ONE = "1";
public static final Object THREENEWLINES = "\n\n\n";
public static final String PREFERENCE_LICENSEACCEPTED = "license.accepted";
public static final String PREFERENCE_LASTSCHEDULEDREFRESH = "lastscheduledrefresh";
public static final String PREFERENCE_LASTTAB = "lasttab";
public static final String HTML_LT = "<";
public static final String HTML_GT = ">";
public static final String LT = "<";
public static final String GT = ">";
protected static final String TRUE = "true";
protected static final String FALSE = "false";
public static final String READDATE_GREATERZERO = FeedData.EntryColumns.READDATE+">0";
public static final String COUNT = "count";
public static final String ENCLOSURE_SEPARATOR = "[@]"; // exactly three characters!
public static final String QUESTIONMARKS = "'??'";
public static final String HTML_QUOT = """;
public static final String QUOT = "\"";
public static final String HTML_APOS = "'";
public static final String APOSTROPHE = "'";
public static final String AMP = "&";
public static final String AMP_SG = "&";
public static final String SLASH = "/";
public static final String COMMASPACE = ", ";
public static final String SCHEDULED = "scheduled";
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2010-2013 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.sparserss.provider;
import java.io.File;
import de.shandschuh.sparserss.handler.PictureFilenameFilter;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
public class FeedData {
public static final String CONTENT = "content://";
public static final String AUTHORITY = "de.shandschuh.sparserss.provider.FeedData";
private static final String TYPE_PRIMARY_KEY = "INTEGER PRIMARY KEY AUTOINCREMENT";
protected static final String TYPE_TEXT = "TEXT";
protected static final String TYPE_DATETIME = "DATETIME";
protected static final String TYPE_INT = "INT";
protected static final String TYPE_BOOLEAN = "INTEGER(1)";
public static final String FEED_DEFAULTSORTORDER = FeedColumns.PRIORITY;
public static class FeedColumns implements BaseColumns {
public static final Uri CONTENT_URI = Uri.parse(new StringBuilder(CONTENT).append(AUTHORITY).append("/feeds").toString());
public static final String URL = "url";
public static final String NAME = "name";
public static final String LASTUPDATE = "lastupdate";
public static final String ICON = "icon";
public static final String ERROR = "error";
public static final String PRIORITY = "priority";
public static final String FETCHMODE = "fetchmode";
public static final String REALLASTUPDATE = "reallastupdate";
public static final String WIFIONLY = "wifionly";
public static final String IMPOSE_USERAGENT = "impose_useragent";
public static final String HIDE_READ = "hide_read";
public static final String[] COLUMNS = new String[] {_ID, URL, NAME, LASTUPDATE, ICON, ERROR, PRIORITY, FETCHMODE, REALLASTUPDATE, WIFIONLY, IMPOSE_USERAGENT, HIDE_READ};
public static final String[] TYPES = new String[] {TYPE_PRIMARY_KEY, "TEXT UNIQUE", TYPE_TEXT, TYPE_DATETIME, "BLOB", TYPE_TEXT, TYPE_INT, TYPE_INT, TYPE_DATETIME, TYPE_BOOLEAN, TYPE_BOOLEAN, TYPE_BOOLEAN};
public static final Uri CONTENT_URI(String feedId) {
return Uri.parse(new StringBuilder(CONTENT).append(AUTHORITY).append("/feeds/").append(feedId).toString());
}
public static final Uri CONTENT_URI(long feedId) {
return Uri.parse(new StringBuilder(CONTENT).append(AUTHORITY).append("/feeds/").append(feedId).toString());
}
}
public static class EntryColumns implements BaseColumns {
public static final String FEED_ID = "feedid";
public static final String TITLE = "title";
public static final String ABSTRACT = "abstract";
public static final String DATE = "date";
public static final String READDATE = "readdate";
public static final String LINK = "link";
public static final String FAVORITE = "favorite";
public static final String ENCLOSURE = "enclosure";
public static final String GUID = "guid";
public static final String AUTHOR = "author";
public static final String[] COLUMNS = new String[] {_ID, FEED_ID, TITLE, ABSTRACT, DATE, READDATE, LINK, FAVORITE, ENCLOSURE, GUID, AUTHOR};
public static final String[] TYPES = new String[] {TYPE_PRIMARY_KEY, "INTEGER(7)", TYPE_TEXT, TYPE_TEXT, TYPE_DATETIME, TYPE_DATETIME, TYPE_TEXT, TYPE_BOOLEAN, TYPE_TEXT, TYPE_TEXT, TYPE_TEXT};
public static Uri CONTENT_URI = Uri.parse(new StringBuilder(CONTENT).append(AUTHORITY).append("/entries").toString());
public static Uri FAVORITES_CONTENT_URI = Uri.parse(new StringBuilder(CONTENT).append(AUTHORITY).append("/favorites").toString());
public static Uri CONTENT_URI(String feedId) {
return Uri.parse(new StringBuilder(CONTENT).append(AUTHORITY).append("/feeds/").append(feedId).append("/entries").toString());
}
public static Uri ENTRY_CONTENT_URI(String entryId) {
return Uri.parse(new StringBuilder(CONTENT).append(AUTHORITY).append("/entries/").append(entryId).toString());
}
public static Uri PARENT_URI(String path) {
return Uri.parse(new StringBuilder(CONTENT).append(AUTHORITY).append(path.substring(0, path.lastIndexOf('/'))).toString());
}
}
private static String[] IDPROJECTION = new String[] {FeedData.EntryColumns._ID};
public static void deletePicturesOfFeedAsync(final Context context, final Uri entriesUri, final String selection) {
if (FeedDataContentProvider.IMAGEFOLDER_FILE.exists()) {
new Thread() {
public void run() {
deletePicturesOfFeed(context, entriesUri, selection);
}
}.start();
}
}
public static synchronized void deletePicturesOfFeed(Context context, Uri entriesUri, String selection) {
if (FeedDataContentProvider.IMAGEFOLDER_FILE.exists()) {
PictureFilenameFilter filenameFilter = new PictureFilenameFilter();
Cursor cursor = context.getContentResolver().query(entriesUri, IDPROJECTION, selection, null, null);
while (cursor.moveToNext()) {
filenameFilter.setEntryId(cursor.getString(0));
File[] files = FeedDataContentProvider.IMAGEFOLDER_FILE.listFiles(filenameFilter);
for (int n = 0, i = files != null ? files.length : 0; n < i; n++) {
files[n].delete();
}
}
cursor.close();
}
}
public static synchronized void deletePicturesOfEntry(String entryId) {
if (FeedDataContentProvider.IMAGEFOLDER_FILE.exists()) {
PictureFilenameFilter filenameFilter = new PictureFilenameFilter(entryId);
File[] files = FeedDataContentProvider.IMAGEFOLDER_FILE.listFiles(filenameFilter);
for (int n = 0, i = files != null ? files.length : 0; n < i; n++) {
files[n].delete();
}
}
}
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2010-2013 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.sparserss.provider;
import java.io.File;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import de.shandschuh.sparserss.Strings;
public class FeedDataContentProvider extends ContentProvider {
private static final String FOLDER = Environment.getExternalStorageDirectory()+"/sparserss/";
private static final String DATABASE_NAME = "sparserss.db";
private static final int DATABASE_VERSION = 13;
private static final int URI_FEEDS = 1;
private static final int URI_FEED = 2;
private static final int URI_ENTRIES = 3;
private static final int URI_ENTRY= 4;
private static final int URI_ALLENTRIES = 5;
private static final int URI_ALLENTRIES_ENTRY = 6;
private static final int URI_FAVORITES = 7;
private static final int URI_FAVORITES_ENTRY = 8;
protected static final String TABLE_FEEDS = "feeds";
private static final String TABLE_ENTRIES = "entries";
private static final String ALTER_TABLE = "ALTER TABLE ";
private static final String ADD = " ADD ";
private static final String EQUALS_ONE = "=1";
public static final String IMAGEFOLDER = Environment.getExternalStorageDirectory()+"/sparserss/images/"; // faster than FOLDER+"images/"
public static final File IMAGEFOLDER_FILE = new File(IMAGEFOLDER);
private static final String BACKUPOPML = Environment.getExternalStorageDirectory()+"/sparserss/backup.opml";
private static UriMatcher URI_MATCHER;
private static final String[] PROJECTION_PRIORITY = new String[] {FeedData.FeedColumns.PRIORITY};
static {
URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
URI_MATCHER.addURI(FeedData.AUTHORITY, "feeds", URI_FEEDS);
URI_MATCHER.addURI(FeedData.AUTHORITY, "feeds/#", URI_FEED);
URI_MATCHER.addURI(FeedData.AUTHORITY, "feeds/#/entries", URI_ENTRIES);
URI_MATCHER.addURI(FeedData.AUTHORITY, "feeds/#/entries/#", URI_ENTRY);
URI_MATCHER.addURI(FeedData.AUTHORITY, "entries", URI_ALLENTRIES);
URI_MATCHER.addURI(FeedData.AUTHORITY, "entries/#", URI_ALLENTRIES_ENTRY);
URI_MATCHER.addURI(FeedData.AUTHORITY, "favorites", URI_FAVORITES);
URI_MATCHER.addURI(FeedData.AUTHORITY, "favorites/#", URI_FAVORITES_ENTRY);
IMAGEFOLDER_FILE.mkdirs();
// Create .nomedia file, that will prevent Android image gallery from showing random parts of webpages we've saved
File nomedia = new File(IMAGEFOLDER+".nomedia");
try {
if (!nomedia.exists()) {
nomedia.createNewFile();
}
} catch (Exception e) {
}
}
private static class DatabaseHelper extends SQLiteOpenHelper {
private Context context;
public DatabaseHelper(Context context, String name, int version) {
super(context, name, null, version); // the constructor just sets the values and returns, therefore context cannot be null
this.context = context;
context.sendBroadcast(new Intent(Strings.ACTION_UPDATEWIDGET));
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(createTable(TABLE_FEEDS, FeedData.FeedColumns.COLUMNS, FeedData.FeedColumns.TYPES));
database.execSQL(createTable(TABLE_ENTRIES, FeedData.EntryColumns.COLUMNS, FeedData.EntryColumns.TYPES));
File backupFile = new File(BACKUPOPML);
if (backupFile.exists()) {
/** Perform an automated import of the backup */
OPML.importFromFile(backupFile, database);
}
}
private String createTable(String tableName, String[] columns, String[] types) {
if (tableName == null || columns == null || types == null || types.length != columns.length || types.length == 0) {
throw new IllegalArgumentException("Invalid parameters for creating table "+tableName);
} else {
StringBuilder stringBuilder = new StringBuilder("CREATE TABLE ");
stringBuilder.append(tableName);
stringBuilder.append(" (");
for (int n = 0, i = columns.length; n < i; n++) {
if (n > 0) {
stringBuilder.append(", ");
}
stringBuilder.append(columns[n]).append(' ').append(types[n]);
}
return stringBuilder.append(");").toString();
}
}
@Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
if (oldVersion < 2) {
executeCatchedSQL(database, new StringBuilder(ALTER_TABLE).append(TABLE_FEEDS).append(ADD).append(FeedData.FeedColumns.PRIORITY).append(' ').append(FeedData.TYPE_INT).toString());
}
if (oldVersion < 3) {
executeCatchedSQL(database, new StringBuilder(ALTER_TABLE).append(TABLE_ENTRIES).append(ADD).append(FeedData.EntryColumns.FAVORITE).append(' ').append(FeedData.TYPE_BOOLEAN).toString());
}
if (oldVersion < 4) {
executeCatchedSQL(database, new StringBuilder(ALTER_TABLE).append(TABLE_FEEDS).append(ADD).append(FeedData.FeedColumns.FETCHMODE).append(' ').append(FeedData.TYPE_INT).toString());
}
if (oldVersion < 5) {
executeCatchedSQL(database, new StringBuilder(ALTER_TABLE).append(TABLE_FEEDS).append(ADD).append(FeedData.FeedColumns.REALLASTUPDATE).append(' ').append(FeedData.TYPE_DATETIME).toString());
}
if (oldVersion < 6) {
Cursor cursor = database.query(TABLE_FEEDS, new String[] {FeedData.FeedColumns._ID}, null, null, null, null, FeedData.FeedColumns._ID);
int count = 0;
while (cursor.moveToNext()) {
executeCatchedSQL(database, new StringBuilder("UPDATE ").append(TABLE_FEEDS).append(" SET ").append(FeedData.FeedColumns.PRIORITY).append('=').append(count++).append(" WHERE _ID=").append(cursor.getLong(0)).toString());
}
cursor.close();
}
if (oldVersion < 7) {
executeCatchedSQL(database, new StringBuilder(ALTER_TABLE).append(TABLE_FEEDS).append(ADD).append(FeedData.FeedColumns.WIFIONLY).append(' ').append(FeedData.TYPE_BOOLEAN).toString());
}
// we simply leave the "encoded" column untouched
if (oldVersion < 9) {
executeCatchedSQL(database, new StringBuilder(ALTER_TABLE).append(TABLE_ENTRIES).append(ADD).append(FeedData.EntryColumns.ENCLOSURE).append(' ').append(FeedData.TYPE_TEXT).toString());
}
if (oldVersion < 10) {
executeCatchedSQL(database, new StringBuilder(ALTER_TABLE).append(TABLE_ENTRIES).append(ADD).append(FeedData.EntryColumns.GUID).append(' ').append(FeedData.TYPE_TEXT).toString());
}
if (oldVersion < 11) {
executeCatchedSQL(database, new StringBuilder(ALTER_TABLE).append(TABLE_ENTRIES).append(ADD).append(FeedData.EntryColumns.AUTHOR).append(' ').append(FeedData.TYPE_TEXT).toString());
}
if (oldVersion < 12) {
executeCatchedSQL(database, new StringBuilder(ALTER_TABLE).append(TABLE_FEEDS).append(ADD).append(FeedData.FeedColumns.IMPOSE_USERAGENT).append(' ').append(FeedData.TYPE_BOOLEAN).toString());
if (!PreferenceManager.getDefaultSharedPreferences(context).getBoolean(Strings.SETTINGS_STANDARDUSERAGENT, true)) {
// no "DEFAULT" syntax
executeCatchedSQL(database, new StringBuilder("UPDATE ").append(TABLE_FEEDS).append(" SET ").append(FeedData.FeedColumns.IMPOSE_USERAGENT).append("='1'").toString());
}
}
if (oldVersion < 13) {
executeCatchedSQL(database, new StringBuilder(ALTER_TABLE).append(TABLE_FEEDS).append(ADD).append(FeedData.FeedColumns.HIDE_READ).append(' ').append(FeedData.TYPE_BOOLEAN).toString());
}
}
private void executeCatchedSQL(SQLiteDatabase database, String query) {
try {
database.execSQL(query);
} catch (Exception e) {
}
}
@Override
public synchronized SQLiteDatabase getWritableDatabase() {
File oldDatabaseFile = new File(Environment.getExternalStorageDirectory()+"/sparserss/sparserss.db");
if (oldDatabaseFile.exists()) { // get rid of the old structure
SQLiteDatabase newDatabase = super.getWritableDatabase();
try {
SQLiteDatabase oldDatabase = SQLiteDatabase.openDatabase(Environment.getExternalStorageDirectory()+"/sparserss/sparserss.db", null, SQLiteDatabase.OPEN_READWRITE + SQLiteDatabase.CREATE_IF_NECESSARY);
Cursor cursor = oldDatabase.query(TABLE_ENTRIES, null, null, null, null, null, null);
newDatabase.beginTransaction();
String[] columnNames = cursor.getColumnNames();
int i = columnNames.length;
int[] columnIndices = new int[i];
for (int n = 0; n < i; n++) {
columnIndices[n] = cursor.getColumnIndex(columnNames[n]);
}
while (cursor.moveToNext()) {
ContentValues values = new ContentValues();
for (int n = 0; n < i; n++) {
if (!cursor.isNull(columnIndices[n])) {
values.put(columnNames[n], cursor.getString(columnIndices[n]));
}
}
newDatabase.insert(TABLE_ENTRIES, null, values);
}
cursor.close();
cursor = oldDatabase.query(TABLE_FEEDS, null, null, null, null, null, FeedData.FeedColumns._ID);
columnNames = cursor.getColumnNames();
i = columnNames.length;
columnIndices = new int[i];
for (int n = 0; n < i; n++) {
columnIndices[n] = cursor.getColumnIndex(columnNames[n]);
}
int count = 0;
while (cursor.moveToNext()) {
ContentValues values = new ContentValues();
for (int n = 0; n < i; n++) {
if (!cursor.isNull(columnIndices[n])) {
if (FeedData.FeedColumns.ICON.equals(columnNames[n])) {
values.put(FeedData.FeedColumns.ICON, cursor.getBlob(columnIndices[n]));
} else {
values.put(columnNames[n], cursor.getString(columnIndices[n]));
}
}
}
values.put(FeedData.FeedColumns.PRIORITY, count++);
newDatabase.insert(TABLE_FEEDS, null, values);
}
cursor.close();
oldDatabase.close();
oldDatabaseFile.delete();
newDatabase.setTransactionSuccessful();
newDatabase.endTransaction();
OPML.exportToFile(BACKUPOPML, newDatabase);
} catch (Exception e) {
}
return newDatabase;
} else {
return super.getWritableDatabase();
}
}
}
private DatabaseHelper databaseHelper;
private String[] MAXPRIORITY = new String[] {"MAX("+FeedData.FeedColumns.PRIORITY+")"};
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int option = URI_MATCHER.match(uri);
String table = null;
StringBuilder where = new StringBuilder();
SQLiteDatabase database = databaseHelper.getWritableDatabase();
switch(option) {
case URI_FEED : {
table = TABLE_FEEDS;
final String feedId = uri.getPathSegments().get(1);
new Thread() {
public void run() {
delete(FeedData.EntryColumns.CONTENT_URI(feedId), null, null);
}
}.start();
where.append(FeedData.FeedColumns._ID).append('=').append(feedId);
/** Update the priorities */
Cursor priorityCursor = database.query(TABLE_FEEDS, PROJECTION_PRIORITY, FeedData.FeedColumns._ID+"="+feedId, null, null, null, null);
if (priorityCursor.moveToNext()) {
database.execSQL("UPDATE "+TABLE_FEEDS+" SET "+FeedData.FeedColumns.PRIORITY+" = "+FeedData.FeedColumns.PRIORITY+"-1 WHERE "+FeedData.FeedColumns.PRIORITY+" > "+priorityCursor.getInt(0));
priorityCursor.close();
} else {
priorityCursor.close();
}
break;
}
case URI_FEEDS : {
table = TABLE_FEEDS;
break;
}
case URI_ENTRY : {
table = TABLE_ENTRIES;
where.append(FeedData.EntryColumns._ID).append('=').append(uri.getPathSegments().get(3));
break;
}
case URI_ENTRIES : {
table = TABLE_ENTRIES;
where.append(FeedData.EntryColumns.FEED_ID).append('=').append(uri.getPathSegments().get(1));
break;
}
case URI_ALLENTRIES : {
table = TABLE_ENTRIES;
break;
}
case URI_FAVORITES_ENTRY :
case URI_ALLENTRIES_ENTRY : {
table = TABLE_ENTRIES;
where.append(FeedData.EntryColumns._ID).append('=').append(uri.getPathSegments().get(1));
break;
}
case URI_FAVORITES : {
table = TABLE_ENTRIES;
where.append(FeedData.EntryColumns.FAVORITE).append(EQUALS_ONE);
break;
}
}
if (!TextUtils.isEmpty(selection)) {
if (where.length() > 0) {
where.append(Strings.DB_AND);
}
where.append(selection);
}
int count = database.delete(table, where.toString(), selectionArgs);
if (table == TABLE_FEEDS) { // == is ok here
OPML.exportToFile(BACKUPOPML, database);
}
if (count > 0) {
getContext().getContentResolver().notifyChange(uri, null);
getContext().sendBroadcast(new Intent(Strings.ACTION_UPDATEWIDGET));
}
return count;
}
@Override
public String getType(Uri uri) {
int option = URI_MATCHER.match(uri);
switch(option) {
case URI_FEEDS : return "vnd.android.cursor.dir/vnd.feeddata.feed";
case URI_FEED : return "vnd.android.cursor.item/vnd.feeddata.feed";
case URI_FAVORITES :
case URI_ALLENTRIES :
case URI_ENTRIES : return "vnd.android.cursor.dir/vnd.feeddata.entry";
case URI_FAVORITES_ENTRY :
case URI_ALLENTRIES_ENTRY :
case URI_ENTRY : return "vnd.android.cursor.item/vnd.feeddata.entry";
default : throw new IllegalArgumentException("Unknown URI: "+uri);
}
}
@Override
public Uri insert(Uri uri, ContentValues values) {
long newId = -1;
int option = URI_MATCHER.match(uri);
SQLiteDatabase database = databaseHelper.getWritableDatabase();
switch (option) {
case URI_FEEDS : {
Cursor cursor = database.query(TABLE_FEEDS, MAXPRIORITY, null, null, null, null, null, null);
if (cursor.moveToNext()) {
values.put(FeedData.FeedColumns.PRIORITY, cursor.getInt(0)+1);
} else {
values.put(FeedData.FeedColumns.PRIORITY, 1);
}
cursor.close();
newId = database.insert(TABLE_FEEDS, null, values);
OPML.exportToFile(BACKUPOPML, database);
break;
}
case URI_ENTRIES : {
values.put(FeedData.EntryColumns.FEED_ID, uri.getPathSegments().get(1));
newId = database.insert(TABLE_ENTRIES, null, values);
break;
}
case URI_ALLENTRIES : {
newId = database.insert(TABLE_ENTRIES, null, values);
break;
}
default : throw new IllegalArgumentException("Illegal insert");
}
if (newId > -1) {
getContext().getContentResolver().notifyChange(uri, null);
return ContentUris.withAppendedId(uri, newId);
} else {
throw new SQLException("Could not insert row into "+uri);
}
}
@Override
public boolean onCreate() {
try {
File folder = new File(FOLDER);
folder.mkdir(); // maybe we use the boolean return value later
} catch (Exception e) {
}
databaseHelper = new DatabaseHelper(getContext(), DATABASE_NAME, DATABASE_VERSION);
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
int option = URI_MATCHER.match(uri);
if ((option == URI_FEED || option == URI_FEEDS) && sortOrder == null) {
sortOrder = FeedData.FEED_DEFAULTSORTORDER;
}
switch(option) {
case URI_FEED : {
queryBuilder.setTables(TABLE_FEEDS);
queryBuilder.appendWhere(new StringBuilder(FeedData.FeedColumns._ID).append('=').append(uri.getPathSegments().get(1)));
break;
}
case URI_FEEDS : {
queryBuilder.setTables(TABLE_FEEDS);
break;
}
case URI_ENTRY : {
queryBuilder.setTables(TABLE_ENTRIES);
queryBuilder.appendWhere(new StringBuilder(FeedData.EntryColumns._ID).append('=').append(uri.getPathSegments().get(3)));
break;
}
case URI_ENTRIES : {
queryBuilder.setTables(TABLE_ENTRIES);
queryBuilder.appendWhere(new StringBuilder(FeedData.EntryColumns.FEED_ID).append('=').append(uri.getPathSegments().get(1)));
break;
}
case URI_ALLENTRIES : {
queryBuilder.setTables("entries join (select name, icon, _id as feed_id from feeds) as F on (entries.feedid = F.feed_id)");
break;
}
case URI_FAVORITES_ENTRY :
case URI_ALLENTRIES_ENTRY : {
queryBuilder.setTables(TABLE_ENTRIES);
queryBuilder.appendWhere(new StringBuilder(FeedData.EntryColumns._ID).append('=').append(uri.getPathSegments().get(1)));
break;
}
case URI_FAVORITES : {
queryBuilder.setTables("entries join (select name, icon, _id as feed_id from feeds) as F on (entries.feedid = F.feed_id)");
queryBuilder.appendWhere(new StringBuilder(FeedData.EntryColumns.FAVORITE).append(EQUALS_ONE));
break;
}
}
SQLiteDatabase database = databaseHelper.getReadableDatabase();
Cursor cursor = queryBuilder.query(database, projection, selection, selectionArgs, null, null, sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int option = URI_MATCHER.match(uri);
String table = null;
StringBuilder where = new StringBuilder();
SQLiteDatabase database = databaseHelper.getWritableDatabase();
switch(option) {
case URI_FEED : {
table = TABLE_FEEDS;
long feedId = Long.parseLong(uri.getPathSegments().get(1));
where.append(FeedData.FeedColumns._ID).append('=').append(feedId);
if (values != null && values.containsKey(FeedData.FeedColumns.PRIORITY)) {
int newPriority = values.getAsInteger(FeedData.FeedColumns.PRIORITY);
Cursor priorityCursor = database.query(TABLE_FEEDS, PROJECTION_PRIORITY, FeedData.FeedColumns._ID+"="+feedId, null, null, null, null);
if (priorityCursor.moveToNext()) {
int oldPriority = priorityCursor.getInt(0);
priorityCursor.close();
if (newPriority > oldPriority) {
database.execSQL("UPDATE "+TABLE_FEEDS+" SET "+FeedData.FeedColumns.PRIORITY+" = "+FeedData.FeedColumns.PRIORITY+"-1 WHERE "+FeedData.FeedColumns.PRIORITY+" BETWEEN "+(oldPriority+1)+" AND "+newPriority);
} else if (newPriority < oldPriority) {
database.execSQL("UPDATE "+TABLE_FEEDS+" SET "+FeedData.FeedColumns.PRIORITY+" = "+FeedData.FeedColumns.PRIORITY+"+1 WHERE "+FeedData.FeedColumns.PRIORITY+" BETWEEN "+newPriority+" AND "+(oldPriority-1));
}
} else {
priorityCursor.close();
}
}
break;
}
case URI_FEEDS : {
table = TABLE_FEEDS;
// maybe this should be disabled
break;
}
case URI_ENTRY : {
table = TABLE_ENTRIES;
where.append(FeedData.EntryColumns._ID).append('=').append(uri.getPathSegments().get(3));
break;
}
case URI_ENTRIES : {
table = TABLE_ENTRIES;
where.append(FeedData.EntryColumns.FEED_ID).append('=').append(uri.getPathSegments().get(1));
break;
}
case URI_ALLENTRIES: {
table = TABLE_ENTRIES;
break;
}
case URI_FAVORITES_ENTRY :
case URI_ALLENTRIES_ENTRY : {
table = TABLE_ENTRIES;
where.append(FeedData.EntryColumns._ID).append('=').append(uri.getPathSegments().get(1));
break;
}
case URI_FAVORITES : {
table = TABLE_ENTRIES;
where.append(FeedData.EntryColumns.FAVORITE).append(EQUALS_ONE);
break;
}
}
if (!TextUtils.isEmpty(selection)) {
if (where.length() > 0) {
where.append(Strings.DB_AND).append(selection);
} else {
where.append(selection);
}
}
int count = database.update(table, values, where.toString(), selectionArgs);
if (table == TABLE_FEEDS && (values.containsKey(FeedData.FeedColumns.NAME) || values.containsKey(FeedData.FeedColumns.URL) || values.containsKey(FeedData.FeedColumns.PRIORITY))) { // == is ok here
OPML.exportToFile(BACKUPOPML, database);
}
if (count > 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return count;
}
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2010-2012 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.sparserss.provider;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import android.util.Xml;
import de.shandschuh.sparserss.Strings;
public class OPML {
private static final String START = "<?xml version=\"1.0\" encoding=\"utf-8\"?><opml version=\"1.1\"><head><title>Sparse RSS export</title><dateCreated>";
private static final String AFTERDATE = "</dateCreated></head><body>";
private static final String OUTLINE_TITLE = "<outline title=\"";
private static final String OUTLINE_XMLURL = "\" type=\"rss\" xmlUrl=\"";
private static final String ATTRIBUTE_CATEGORY_VALUE = "/"+FeedData.FeedColumns.WIFIONLY;
private static final String OUTLINE_CATEGORY = "\" category=\"";
private static final String OUTLINE_CLOSING = "\" />";
private static final String CLOSING = "</body></opml>\n";
private static OPMLParser parser = new OPMLParser();
public static void importFromFile(String filename, Context context) throws FileNotFoundException, IOException, SAXException {
parser.context = context;
parser.database = null;
Xml.parse(new InputStreamReader(new FileInputStream(filename)), parser);
}
protected static void importFromInputStream(InputStream inputStream, SQLiteDatabase database) {
parser.context = null;
parser.database = database;
try {
database.beginTransaction();
Xml.parse(new InputStreamReader(inputStream), parser);
/** This is ok since the database is empty */
database.execSQL(new StringBuilder("UPDATE ").append(FeedDataContentProvider.TABLE_FEEDS).append(" SET ").append(FeedData.FeedColumns.PRIORITY).append('=').append(FeedData.FeedColumns._ID).append("-1").toString());
database.setTransactionSuccessful();
} catch (Exception e) {
} finally {
database.endTransaction();
}
}
protected static void importFromFile(File file, SQLiteDatabase database) {
try {
importFromInputStream(new FileInputStream(file), database);
} catch (FileNotFoundException e) {
// do nothing
}
}
public static void exportToFile(String filename, Context context) throws IOException {
Cursor cursor = context.getContentResolver().query(FeedData.FeedColumns.CONTENT_URI, new String[] {FeedData.FeedColumns._ID, FeedData.FeedColumns.NAME, FeedData.FeedColumns.URL, FeedData.FeedColumns.WIFIONLY}, null, null, null);
try {
writeData(filename, cursor);
} finally {
cursor.close();
}
}
protected static void exportToFile(String filename, SQLiteDatabase database) {
Cursor cursor = database.query(FeedDataContentProvider.TABLE_FEEDS, new String[] {FeedData.FeedColumns._ID, FeedData.FeedColumns.NAME, FeedData.FeedColumns.URL, FeedData.FeedColumns.WIFIONLY}, null, null, null, null, FeedData.FEED_DEFAULTSORTORDER);
try {
writeData(filename, cursor);
} catch (Exception e) {
}
cursor.close();
}
private static void writeData(String filename, Cursor cursor) throws IOException {
StringBuilder builder = new StringBuilder(START);
builder.append(System.currentTimeMillis());
builder.append(AFTERDATE);
while(cursor.moveToNext()) {
builder.append(OUTLINE_TITLE);
builder.append(cursor.isNull(1) ? Strings.EMPTY : TextUtils.htmlEncode(cursor.getString(1)));
builder.append(OUTLINE_XMLURL);
builder.append(TextUtils.htmlEncode(cursor.getString(2)));
if (cursor.getInt(3) == 1) {
builder.append(OUTLINE_CATEGORY);
builder.append(ATTRIBUTE_CATEGORY_VALUE);
}
builder.append(OUTLINE_CLOSING);
}
builder.append(CLOSING);
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
writer.write(builder.toString());
writer.close();
}
private static class OPMLParser extends DefaultHandler {
private static final String TAG_BODY = "body";
private static final String TAG_OUTLINE = "outline";
private static final String ATTRIBUTE_TITLE = "title";
private static final String ATTRIBUTE_XMLURL = "xmlUrl";
private static final String ATTRIBUTE_CATEGORY = "category";
private boolean bodyTagEntered;
private boolean probablyValidElement = false;
private Context context;
private SQLiteDatabase database;
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (!bodyTagEntered) {
if (TAG_BODY.equals(localName)) {
bodyTagEntered = true;
probablyValidElement = true;
}
} else if (TAG_OUTLINE.equals(localName)) {
String url = attributes.getValue(Strings.EMPTY, ATTRIBUTE_XMLURL);
if (url != null) {
String title = attributes.getValue(Strings.EMPTY, ATTRIBUTE_TITLE);
ContentValues values = new ContentValues();
values.put(FeedData.FeedColumns.URL, url);
values.put(FeedData.FeedColumns.NAME, title != null && title.length() > 0 ? title : null);
values.put(FeedData.FeedColumns.WIFIONLY, ATTRIBUTE_CATEGORY_VALUE.equals(attributes.getValue(Strings.EMPTY, ATTRIBUTE_CATEGORY)) ? 1 : 0);
if (context != null) {
Cursor cursor = context.getContentResolver().query(FeedData.FeedColumns.CONTENT_URI, null, new StringBuilder(FeedData.FeedColumns.URL).append(Strings.DB_ARG).toString(), new String[] {url}, null);
if (!cursor.moveToFirst()) {
context.getContentResolver().insert(FeedData.FeedColumns.CONTENT_URI, values);
}
cursor.close();
} else { // this happens only, if the db is new and therefore empty
database.insert(FeedDataContentProvider.TABLE_FEEDS, null, values);
}
}
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (bodyTagEntered && TAG_BODY.equals(localName)) {
bodyTagEntered = false;
}
}
@Override
public void endDocument() throws SAXException {
if (!probablyValidElement) {
throw new SAXException();
} else {
super.endDocument();
}
}
}
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2010-2012 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.sparserss;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.preference.PreferenceManager;
import de.shandschuh.sparserss.service.RefreshService;
public class BootCompletedBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
try {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context.createPackageContext(Strings.PACKAGE, 0));
preferences.edit().putLong(Strings.PREFERENCE_LASTSCHEDULEDREFRESH, 0).commit();
if (preferences.getBoolean(Strings.SETTINGS_REFRESHENABLED, false)) {
context.startService(new Intent(context, RefreshService.class));
}
context.sendBroadcast(new Intent(Strings.ACTION_UPDATEWIDGET));
} catch (NameNotFoundException e) {
}
}
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2012, 2013 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.sparserss;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import de.shandschuh.sparserss.provider.FeedData;
public class FeedConfigActivity extends Activity {
private static final String WASACTIVE = "wasactive";
private static final String[] PROJECTION = new String[] {FeedData.FeedColumns.NAME, FeedData.FeedColumns.URL, FeedData.FeedColumns.WIFIONLY, FeedData.FeedColumns.IMPOSE_USERAGENT, FeedData.FeedColumns.HIDE_READ};
private EditText nameEditText;
private EditText urlEditText;
private CheckBox refreshOnlyWifiCheckBox;
private CheckBox standardUseragentCheckBox;
private CheckBox hideReadCheckBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.feedsettings);
setResult(RESULT_CANCELED);
Intent intent = getIntent();
nameEditText = (EditText) findViewById(R.id.feed_title);
urlEditText = (EditText) findViewById(R.id.feed_url);
refreshOnlyWifiCheckBox = (CheckBox) findViewById(R.id.wifionlycheckbox);
standardUseragentCheckBox = (CheckBox) findViewById(R.id.standarduseragentcheckbox);
hideReadCheckBox = (CheckBox) findViewById(R.id.hidereadcheckbox);
if (intent.getAction().equals(Intent.ACTION_INSERT)) {
setTitle(R.string.newfeed_title);
restoreInstanceState(savedInstanceState);
((Button) findViewById(R.id.button_ok)).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String url = urlEditText.getText().toString();
if (!url.startsWith(Strings.HTTP) && !url.startsWith(Strings.HTTPS)) {
url = Strings.HTTP+url;
}
Cursor cursor = getContentResolver().query(FeedData.FeedColumns.CONTENT_URI, null, new StringBuilder(FeedData.FeedColumns.URL).append(Strings.DB_ARG).toString(), new String[] {url}, null);
if (cursor.moveToFirst()) {
cursor.close();
Toast.makeText(FeedConfigActivity.this, R.string.error_feedurlexists, Toast.LENGTH_LONG).show();
} else {
cursor.close();
ContentValues values = new ContentValues();
values.put(FeedData.FeedColumns.WIFIONLY, refreshOnlyWifiCheckBox.isChecked() ? 1 : 0);
values.put(FeedData.FeedColumns.IMPOSE_USERAGENT, standardUseragentCheckBox.isChecked() ? 0 : 1);
values.put(FeedData.FeedColumns.HIDE_READ, hideReadCheckBox.isChecked() ? 1 : 0);
values.put(FeedData.FeedColumns.URL, url);
values.put(FeedData.FeedColumns.ERROR, (String) null);
String name = nameEditText.getText().toString();
if (name.trim().length() > 0) {
values.put(FeedData.FeedColumns.NAME, name);
}
getContentResolver().insert(FeedData.FeedColumns.CONTENT_URI, values);
setResult(RESULT_OK);
finish();
}
}
});
} else {
setTitle(R.string.editfeed_title);
if (!restoreInstanceState(savedInstanceState)) {
Cursor cursor = getContentResolver().query(intent.getData(), PROJECTION, null, null, null);
if (cursor.moveToNext()) {
nameEditText.setText(cursor.getString(0));
urlEditText.setText(cursor.getString(1));
refreshOnlyWifiCheckBox.setChecked(cursor.getInt(2) == 1);
standardUseragentCheckBox.setChecked(cursor.isNull(3) || cursor.getInt(3) == 0);
hideReadCheckBox.setChecked(cursor.getInt(4) == 1);
cursor.close();
} else {
cursor.close();
Toast.makeText(FeedConfigActivity.this, R.string.error, Toast.LENGTH_LONG).show();
finish();
}
}
((Button) findViewById(R.id.button_ok)).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String url = urlEditText.getText().toString();
Cursor cursor = getContentResolver().query(FeedData.FeedColumns.CONTENT_URI, new String[] {FeedData.FeedColumns._ID}, new StringBuilder(FeedData.FeedColumns.URL).append(Strings.DB_ARG).toString(), new String[] {url}, null);
if (cursor.moveToFirst() && !getIntent().getData().getLastPathSegment().equals(cursor.getString(0))) {
cursor.close();
Toast.makeText(FeedConfigActivity.this, R.string.error_feedurlexists, Toast.LENGTH_LONG).show();
} else {
cursor.close();
ContentValues values = new ContentValues();
if (!url.startsWith(Strings.HTTP) && !url.startsWith(Strings.HTTPS)) {
url = Strings.HTTP+url;
}
values.put(FeedData.FeedColumns.URL, url);
String name = nameEditText.getText().toString();
values.put(FeedData.FeedColumns.NAME, name.trim().length() > 0 ? name : null);
values.put(FeedData.FeedColumns.FETCHMODE, 0);
values.put(FeedData.FeedColumns.WIFIONLY, refreshOnlyWifiCheckBox.isChecked() ? 1 : 0);
values.put(FeedData.FeedColumns.IMPOSE_USERAGENT, standardUseragentCheckBox.isChecked() ? 0 : 1);
values.put(FeedData.FeedColumns.HIDE_READ, hideReadCheckBox.isChecked() ? 1 : 0);
values.put(FeedData.FeedColumns.ERROR, (String) null);
getContentResolver().update(getIntent().getData(), values, null, null);
setResult(RESULT_OK);
finish();
}
}
});
}
((Button) findViewById(R.id.button_cancel)).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
private boolean restoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState != null && savedInstanceState.getBoolean(WASACTIVE, false)) {
nameEditText.setText(savedInstanceState.getCharSequence(FeedData.FeedColumns.NAME));
urlEditText.setText(savedInstanceState.getCharSequence(FeedData.FeedColumns.URL));
refreshOnlyWifiCheckBox.setChecked(savedInstanceState.getBoolean(FeedData.FeedColumns.WIFIONLY));
standardUseragentCheckBox.setChecked(!savedInstanceState.getBoolean(FeedData.FeedColumns.IMPOSE_USERAGENT));
// we don't have to negate this here, if we would not negate it in the OnSaveInstanceStage, but lets do it for the sake of readability
return true;
} else {
return false;
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(WASACTIVE, true);
outState.putCharSequence(FeedData.FeedColumns.NAME, nameEditText.getText());
outState.putCharSequence(FeedData.FeedColumns.URL, urlEditText.getText());
outState.putBoolean(FeedData.FeedColumns.WIFIONLY, refreshOnlyWifiCheckBox.isChecked());
outState.putBoolean(FeedData.FeedColumns.IMPOSE_USERAGENT, !standardUseragentCheckBox.isChecked());
}
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2010-2013 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.sparserss;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import de.shandschuh.sparserss.service.FetcherService;
public class RefreshBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Strings.ACTION_REFRESHFEEDS.equals(intent.getAction())) {
context.startService(new Intent(context, FetcherService.class).putExtras(intent)); // a thread would mark the process as inactive
} else if (Strings.ACTION_STOPREFRESHFEEDS.equals(intent.getAction())) {
context.stopService(new Intent(context, FetcherService.class));
}
}
}
| Java |
/**
* Sparse rss
*
* Copyright (c) 2010-2013 Stefan Handschuh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package de.shandschuh.sparserss;
import java.text.DateFormat;
import java.util.Date;
import java.util.Vector;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.util.TypedValue;
import android.view.View;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;
import de.shandschuh.sparserss.provider.FeedData;
public class RSSOverviewListAdapter extends ResourceCursorAdapter {
private static final String COUNT_UNREAD = "COUNT(*) - COUNT(readdate)";
private static final String COUNT = "COUNT(*)";
private String COLON;
private int nameColumnPosition;
private int lastUpdateColumn;
private int idPosition;
private int linkPosition;
private int errorPosition;
private int iconPosition;
private Handler handler;
private SimpleTask updateTask;
private boolean feedSort;
private Vector<View> sortViews;
private DateFormat dateFormat;
private DateFormat timeFormat;
public RSSOverviewListAdapter(Activity activity) {
super(activity, R.layout.feedlistitem, activity.managedQuery(FeedData.FeedColumns.CONTENT_URI, null, null, null, null));
nameColumnPosition = getCursor().getColumnIndex(FeedData.FeedColumns.NAME);
lastUpdateColumn = getCursor().getColumnIndex(FeedData.FeedColumns.LASTUPDATE);
idPosition = getCursor().getColumnIndex(FeedData.FeedColumns._ID);
linkPosition = getCursor().getColumnIndex(FeedData.FeedColumns.URL);
errorPosition = getCursor().getColumnIndex(FeedData.FeedColumns.ERROR);
iconPosition = getCursor().getColumnIndex(FeedData.FeedColumns.ICON);
COLON = activity.getString(R.string.colon);
handler = new Handler();
updateTask = new SimpleTask() {
@Override
public void runControlled() {
RSSOverviewListAdapter.super.onContentChanged();
cancel(); // cancel the task such that it does not run more than once without explicit intention
}
@Override
public void postRun() {
if (getPostCount() > 1) { // enforce second run even if task is canceled
handler.postDelayed(updateTask, 1500);
}
}
};
sortViews = new Vector<View>();
dateFormat = android.text.format.DateFormat.getDateFormat(activity);
timeFormat = android.text.format.DateFormat.getTimeFormat(activity);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView textView = ((TextView) view.findViewById(android.R.id.text1));
textView.setSingleLine();
Cursor countCursor = context.getContentResolver().query(FeedData.EntryColumns.CONTENT_URI(cursor.getString(idPosition)), new String[] {COUNT_UNREAD, COUNT}, null, null, null);
countCursor.moveToFirst();
int unreadCount = countCursor.getInt(0);
int count = countCursor.getInt(1);
countCursor.close();
long timestamp = cursor.getLong(lastUpdateColumn);
TextView updateTextView = ((TextView) view.findViewById(android.R.id.text2));;
if (cursor.isNull(errorPosition)) {
Date date = new Date(timestamp);
updateTextView.setText(new StringBuilder(context.getString(R.string.update)).append(COLON).append(timestamp == 0 ? context.getString(R.string.never) : new StringBuilder(dateFormat.format(date)).append(' ').append(timeFormat.format(date)).append(Strings.COMMASPACE).append(unreadCount).append('/').append(count).append(' ').append(context.getString(R.string.unread))));
} else {
updateTextView.setText(new StringBuilder(context.getString(R.string.error)).append(COLON).append(cursor.getString(errorPosition)));
}
textView.setEnabled(unreadCount > 0);
byte[] iconBytes = cursor.getBlob(iconPosition);
if (iconBytes != null && iconBytes.length > 0) {
Bitmap bitmap = BitmapFactory.decodeByteArray(iconBytes, 0, iconBytes.length);
if (bitmap != null && bitmap.getHeight() > 0 && bitmap.getWidth() > 0) {
int bitmapSizeInDip = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 18f, context.getResources().getDisplayMetrics());
if (bitmap.getHeight() != bitmapSizeInDip) {
bitmap = Bitmap.createScaledBitmap(bitmap, bitmapSizeInDip, bitmapSizeInDip, false);
}
textView.setCompoundDrawablesWithIntrinsicBounds(new BitmapDrawable(bitmap), null, null, null);
textView.setText(" " + (cursor.isNull(nameColumnPosition) ? cursor.getString(linkPosition) : cursor.getString(nameColumnPosition)));
} else {
textView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
textView.setText(cursor.isNull(nameColumnPosition) ? cursor.getString(linkPosition) : cursor.getString(nameColumnPosition));
}
} else {
view.setTag(null);
textView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
textView.setText(cursor.isNull(nameColumnPosition) ? cursor.getString(linkPosition) : cursor.getString(nameColumnPosition));
}
View sortView = view.findViewById(R.id.sortitem);
if (!sortViews.contains(sortView)) { // as we are reusing views, this is fine
sortViews.add(sortView);
}
sortView.setVisibility(feedSort ? View.VISIBLE : View.GONE);
}
@Override
protected synchronized void onContentChanged() {
/*
* we delay the second(!) content change by 1.5 second such that it gets called at most once per 1.5 seconds
* to take stress away from the UI and avoid not needed updates
*/
if (!updateTask.isPosted()) {
super.onContentChanged();
updateTask.post(2); // we post 2 tasks
handler.postDelayed(updateTask, 1500); // waits one second until the task gets unposted
updateTask.cancel(); // put the canceled task in the queue to enable it again optionally
} else {
if (updateTask.getPostCount() < 2) {
updateTask.post(); // enables the task and adds a new one
} else {
updateTask.enable();
}
}
}
public void setFeedSortEnabled(boolean enabled) {
feedSort = enabled;
/* we do not want to call notifyDataSetChanged as this requeries the cursor*/
int visibility = feedSort ? View.VISIBLE : View.GONE;
for (View sortView : sortViews) {
sortView.setVisibility(visibility);
}
}
}
| Java |
// Copyright 2012, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ad.catalog.layouts;
import com.google.ad.catalog.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
/**
* Menu system for different ad layouts.
*
* @author api.eleichtenschl@gmail.com (Eric Leichtenschlag)
*/
public class AdvancedLayouts extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.advancedlayouts);
}
/** Handles the on click events for each button. */
@Override
public void onClick(View view) {
final int id = view.getId();
Intent intent = null;
switch (id) {
// Uncomment corresponding intent when implementing an example.
case R.id.tabbedView:
intent = new Intent(AdvancedLayouts.this, TabbedViewExample.class);
break;
case R.id.listView:
intent = new Intent(AdvancedLayouts.this, ListViewExample.class);
break;
case R.id.openGLView:
intent = new Intent(AdvancedLayouts.this, OpenGLViewExample.class);
break;
case R.id.scrollView:
intent = new Intent(AdvancedLayouts.this, ScrollViewExample.class);
break;
}
if (intent != null) {
startActivity(intent);
}
}
}
| Java |
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ad.catalog.layouts;
import com.google.ad.catalog.AdCatalog;
import com.google.ad.catalog.R;
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
/**
* Example of a ScrollView with an AdMob banner.
*
* @author api.eleichtenschl@gmail.com (Eric Leichtenschlag)
*/
public class ScrollViewExample extends Activity implements AdListener {
private static final String LOGTAG = "ScrollViewExample";
private AdView adView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scrollviewexample);
adView = (AdView) findViewById(R.id.adView);
AdRequest adRequestBanner = new AdRequest();
// Set testing according to our preference.
if (AdCatalog.isTestMode) {
adRequestBanner.addTestDevice(AdRequest.TEST_EMULATOR);
}
adView.setAdListener(this);
adView.loadAd(adRequestBanner);
}
/** Overwrite the onDestroy() method to dispose of banners first. */
@Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
@Override
public void onReceiveAd(Ad ad) {
Log.d(LOGTAG, "I received an ad");
}
@Override
public void onFailedToReceiveAd(Ad ad, AdRequest.ErrorCode error) {
Log.d(LOGTAG, "I failed to receive an ad");
}
@Override
public void onPresentScreen(Ad ad) {
Log.d(LOGTAG, "Presenting screen");
}
@Override
public void onDismissScreen(Ad ad) {
Log.d(LOGTAG, "Dismissing screen");
}
@Override
public void onLeaveApplication(Ad ad) {
Log.d(LOGTAG, "Leaving application");
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.