file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
BCHostnameResolutionPlugin.java
/FileExtraction/Java_unseen/catageek_ByteCart/src/com/github/catageek/ByteCart/plugins/BCHostnameResolutionPlugin.java
package com.github.catageek.ByteCart.plugins; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.Normalizer; import java.text.Normalizer.Form; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.MissingResourceException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.util.StringUtil; import com.github.catageek.ByteCart.ByteCart; import com.github.catageek.ByteCartAPI.AddressLayer.Address; import com.github.catageek.ByteCartAPI.AddressLayer.Resolver; import com.github.catageek.ByteCartAPI.Event.SignCreateEvent; import com.github.catageek.ByteCartAPI.Event.SignRemoveEvent; import com.github.catageek.ByteCartAPI.Event.UpdaterClearStationEvent; import com.github.catageek.ByteCartAPI.Event.UpdaterPassStationEvent; import com.github.catageek.ByteCartAPI.Event.UpdaterSetStationEvent; import com.github.catageek.ByteCartAPI.Signs.Station; import com.google.common.collect.Lists; import code.husky.Database; import code.husky.mysql.MySQL; import code.husky.sqlite.SQLite; public final class BCHostnameResolutionPlugin implements Resolver, Listener, CommandExecutor, TabCompleter { private String database = ByteCart.myPlugin.getConfig().getString("database","BCHostnames"); private String sql = ByteCart.myPlugin.getConfig().getString("sql", "sqllite"); private String host,port,user,password; private Database mysql; private Connection con; private Statement s; public void onLoad() { if(sql.equalsIgnoreCase("mysql")) { FileConfiguration config = ByteCart.myPlugin.getConfig(); host=config.getString("hostname"); port=config.getString("port"); user=config.getString("user"); password=config.getString("password"); mysql = new MySQL(ByteCart.myPlugin, host, port, database, user, password); } else { mysql = new SQLite(ByteCart.myPlugin, database); } con=mysql.openConnection(); try { s = con.createStatement(); s.execute("create table if not exists cart_dns (ip varchar(11) not null primary key,username varchar(20) not null,uuid varchar(128) not null,name varchar(20) not null unique)"); } catch (SQLException e) { throw new MissingResourceException("Could not create SQL table", "BCHostname", "BCHostname"); } } @Override public boolean onCommand(CommandSender a, Command b , String c, String[] d) { return onCommand(a,b,c,d,0); } private boolean onCommand(CommandSender a, Command b , String c, String[] d,int n) { if(b.getName().equalsIgnoreCase("host")) { if(d.length==0) { return false; } else if(d.length>=1) { // Strip diacritics from Station name try{ switch(d[0]) { case "create": if (a.hasPermission("bytecart.host.manager")) { String hostname = getName(d,1,1); hostname = Normalizer.normalize(hostname, Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); if(!safeName(hostname)) { a.sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.RED + "No hacking this time"); return true; } else if(d.length<3 || d[d.length-1].equals("") || hostname.length()>20) { a.sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.RED + "Wrong IP/Name or not enough args."); return true; } if(!existEntryByName(hostname, a)) { String uu="Console",user="Console"; if((a instanceof Player)) { uu=((Player)a).getUniqueId().toString(); user=((Player)a).getName(); } createEntry(hostname, safeIP(d[d.length-1]), uu, user); a.sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.YELLOW + "Hostname added"); } return true; } else { a.sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.RED + "You don't have permission to use this command."); return true; } case "remove": if (a.hasPermission("bytecart.host.manager")) { String hostname = getName(d,1,0); hostname = Normalizer.normalize(hostname, Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); if(!safeName(hostname)) { a.sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.RED + "No hacking this time"); return true; } if(removeEntry(hostname)) { a.sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.YELLOW + "Hostname deleted"); return true; } } else { a.sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.RED + "You don't have permission to use this command."); return true; } case "list": if(! a.hasPermission("bytecart.host.list")) { a.sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.RED + "You don't have permission to use this command."); return true; } else { if(d.length==0) { return false; } else if(d.length>=1) { int listc=0; if(d.length>=2 && d[1].matches("-?\\d+")) { listc=Integer.parseInt(d[1]); } try { ResultSet res=s.executeQuery("SELECT * FROM `cart_dns` LIMIT "+(listc*10)+", "+(listc*10+10)); if(!res.next()) a.sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.YELLOW + "No DNS records"); else { a.sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.YELLOW + "DNS record table page ("+(listc+1)+")"); listc*=10; do { a.sendMessage(listc+": "+res.getString("ip")+" "+res.getString("name")); listc++; } while(res.next()); } } catch (SQLException e) { if(n<2) { n++; con=mysql.getConnection(); if(con==null) con=mysql.openConnection(); return onCommand(a, b, c, d,n); } else { ByteCart.log.info("SQL error code: "+e.getErrorCode()); ByteCart.log.info("SQL error msg: "+e.getMessage()); ByteCart.log.info("SQL error state: "+e.getSQLState()); return false; } } } return true; } default: if (! a.hasPermission("bytecart.host.user")) { a.sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.RED + "You don't have permission to use this command."); return true; } // HAXX, if not /dns lookup, then make [name] first parameter String hostname; if (d[0].equalsIgnoreCase("lookup")) { if (d.length != 2) return false; hostname = this.getName(d, 1, 0); } else { hostname = this.getName(d, 0, 0); } hostname = Normalizer.normalize(hostname, Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); if(!safeName(hostname)) { a.sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.RED + "No hacking this time"); return true; } if(!existEntryByName(hostname)) { if(hostname.equals("")) {a.sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.RED + "No station with this name/ip"); return true;} if(!existEntryByIP(safeIP(hostname))) { a.sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.RED + "No station with this name/ip"); } else { ResultSet ress = getEntryByIP(safeIP(hostname)); a.sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.YELLOW + "Name: "+ress.getString("name")+" IP: "+ress.getString("ip")); a.sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.YELLOW + "Author: "+ress.getString("username")); } return true; } else { ResultSet ress = getEntryByName(hostname); a.sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.YELLOW + "Name: "+ress.getString("name")+" IP: "+ress.getString("ip")); a.sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.YELLOW + "Author: "+ress.getString("username")); return true; } } } catch (SQLException e) { if(n<2) { n++; con=mysql.getConnection(); if(con==null) con=mysql.openConnection(); return onCommand(a, b, c, d,n); } else { ByteCart.log.info("SQL error code: "+e.getErrorCode()); ByteCart.log.info("SQL error msg: "+e.getMessage()); ByteCart.log.info("SQL error state: "+e.getSQLState()); return false; } } } } return true; } @Override public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) { if (args.length <= 1) { return StringUtil.copyPartialMatches(args[0], Arrays.asList("create", "remove", "lookup", "list"), Lists.newArrayList()); } else if (args[0].equalsIgnoreCase("lookup")) { List<String> options = Lists.newArrayList(); String prefix = getName(args, 1, 0); List<String> names = getMatchingNames(prefix); for (String name : names) { name = name.substring(prefix.length()); if (name.contains(" ")) { name = name.substring(0, name.indexOf(' ')); } options.add(name); } return options; } else { return Collections.emptyList(); } } @EventHandler @SuppressWarnings("ucd") public void onSignCreate(SignCreateEvent event) { if (event.getIc() instanceof Station) { try { String ip = event.getStrings()[3]; String name = event.getStrings()[2]; Player player = event.getPlayer(); if (! ip.equals("") && ! name.equals("")) { name = Normalizer.normalize(name, Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); if (safeName(name) && ! existEntryByName(name,player)) createEntry(name, safeIP(ip), player.getUniqueId().toString(), player.getName()); } } catch (SQLException e) { ByteCart.log.info("SQL error code: "+e.getErrorCode()); ByteCart.log.info("SQL error msg: "+e.getMessage()); ByteCart.log.info("SQL error state: "+e.getSQLState()); } } } @EventHandler @SuppressWarnings("ucd") public void onSignRemove(SignRemoveEvent event) { if (event.getIc() instanceof Station) { try { String name = ((Station) event.getIc()).getStationName(); name = Normalizer.normalize(name, Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); if (safeName(name)) removeEntry(name); } catch (SQLException e) { ByteCart.log.info("SQL error code: "+e.getErrorCode()); ByteCart.log.info("SQL error msg: "+e.getMessage()); ByteCart.log.info("SQL error state: "+e.getSQLState()); } } } @EventHandler @SuppressWarnings("ucd") public void onUpdaterSetStation(UpdaterSetStationEvent event) { try { String ip = event.getNewAddress().toString(); String name = event.getName(); if (! name.equals("")) { name = Normalizer.normalize(name, Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); if (safeName(name)) { removeEntry(name); createEntry(name, ip, "updater", "updater"); } } } catch (SQLException e) { ByteCart.log.info("SQL error code: "+e.getErrorCode()); ByteCart.log.info("SQL error msg: "+e.getMessage()); ByteCart.log.info("SQL error state: "+e.getSQLState()); } } @EventHandler @SuppressWarnings("ucd") public void onUpdaterClearStation(UpdaterClearStationEvent event) { try { String name = event.getName(); if (! name.equals("")) { name = Normalizer.normalize(name, Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); if (safeName(name)) { removeEntry(name); } } } catch (SQLException e) { ByteCart.log.info("SQL error code: "+e.getErrorCode()); ByteCart.log.info("SQL error msg: "+e.getMessage()); ByteCart.log.info("SQL error state: "+e.getSQLState()); } } @EventHandler @SuppressWarnings("ucd") public void onUpdaterPassStation(UpdaterPassStationEvent event) { try { String name = event.getName(); if (! name.equals("")) { Address ip = event.getAddress(); name = Normalizer.normalize(name, Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); if (ip.isValid() && safeName(name) && ! existEntryByName(name)) { createEntry(name, ip.toString(), "updater", "updater"); } } } catch (SQLException e) { ByteCart.log.info("SQL error code: "+e.getErrorCode()); ByteCart.log.info("SQL error msg: "+e.getMessage()); ByteCart.log.info("SQL error state: "+e.getSQLState()); } } @Override public String resolve(String name) { name = Normalizer.normalize(name, Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); try { if(safeName(name) && existEntryByName(name)) { return getEntryByName(name).getString("ip"); } } catch (SQLException e) { ByteCart.log.info("SQL error code: "+e.getErrorCode()); ByteCart.log.info("SQL error msg: "+e.getMessage()); ByteCart.log.info("SQL error state: "+e.getSQLState()); } return ""; } @Override public List<String> getNames() { List<String> result = Lists.newArrayList(); try { ResultSet set = s.executeQuery("SELECT name FROM `cart_dns`"); while (set.next()) { result.add(set.getString("name")); } } catch (SQLException e) { ByteCart.log.info("SQL error code: "+e.getErrorCode()); ByteCart.log.info("SQL error msg: "+e.getMessage()); ByteCart.log.info("SQL error state: "+e.getSQLState()); } return result; } @Override public List<String> getMatchingNames(String prefix) { List<String> result = Lists.newArrayList(); if (!safeName(prefix)) { return result; } try { ResultSet set = s.executeQuery("SELECT name FROM `cart_dns` WHERE LOWER(`name`) LIKE '" + prefix.toLowerCase() + "%'"); while (set.next()) { result.add(set.getString("name")); } } catch (SQLException e) { ByteCart.log.info("SQL error code: "+e.getErrorCode()); ByteCart.log.info("SQL error msg: "+e.getMessage()); ByteCart.log.info("SQL error state: "+e.getSQLState()); } return result; } private boolean removeEntry(String name) throws SQLException { if(existEntryByName(name)) { s.executeUpdate("DELETE FROM `cart_dns` WHERE LOWER(`name`)='"+name.toLowerCase()+"'"); return true; } return false; } private boolean existEntryByName(String name, CommandSender a) throws SQLException { if (existEntryByName(name)) { ResultSet res = getEntryByName(name); a.sendMessage(ChatColor.DARK_GREEN+"[Bytecart] " + ChatColor.RED + "hostname "+res.getString("name")+" exist with ip "+res.getString("ip")+" ."); return true; } return false; } private boolean existEntryByName(String name) throws SQLException { ResultSet res=s.executeQuery("SELECT * FROM `cart_dns` WHERE LOWER(`name`)='"+name.toLowerCase()+"'"); return res.next(); } private boolean existEntryByIP(String ip) throws SQLException { ResultSet res=s.executeQuery("SELECT * FROM `cart_dns` WHERE `ip`='"+ ip +"'"); return res.next(); } private ResultSet getEntryByName(String name) throws SQLException { return s.executeQuery("SELECT * FROM `cart_dns` WHERE LOWER(`name`)='"+name.toLowerCase()+"'"); } private ResultSet getEntryByIP(String ip) throws SQLException { return s.executeQuery("SELECT * FROM `cart_dns` WHERE `ip`='"+ip+"'"); } private void createEntry(String name, String ip, String uu, String username) throws SQLException { String ds="INSERT INTO `cart_dns` (`ip`,`name`,`username`,`uuid`) VALUES('"+ip+"','" + name +"','"+username+"','"+uu+"')"; s.executeUpdate(ds); } private String safeIP(String input) { char[] ch=input.toCharArray(); String output=""; int cnt=0,cnt2=0; for(char c:ch) { if(Character.isDigit(c)) { if(cnt>=5) return ""; else output+=c; } else if(c=='.') { if(cnt==0) return ""; if(cnt2==2) return ""; output+=c; cnt=0; cnt2++; } else return ""; cnt++; } return output; } private boolean safeName(String input) { if(input.toLowerCase().contains(" or ") || input.toLowerCase().contains(" and ") || input.toLowerCase().contains(" union ")) return false; Pattern p = Pattern.compile("[^a-z0-9/*+$!:.@_\\-#&\\s]", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(input); if(m.find()) return false; return true; } private String getName(String[] input, int s, int e) { String output=input[s]; for(int i=s+1;i<input.length-e;i++) output+=" "+input[i]; return output; } }
16,957
Java
.java
catageek/ByteCart
28
9
5
2012-03-11T08:15:46Z
2018-10-18T04:55:47Z
SettingsActivity.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/SettingsActivity.java
package de.georgsieber.customerdb; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import androidx.appcompat.app.AppCompatDelegate; import androidx.appcompat.widget.Toolbar; import androidx.appcompat.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.SeekBar; import android.widget.Spinner; import android.widget.TextView; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.util.Date; import java.util.List; import de.georgsieber.customerdb.model.CustomField; import de.georgsieber.customerdb.model.Customer; import de.georgsieber.customerdb.model.CustomerCalendar; import de.georgsieber.customerdb.tools.ColorControl; import de.georgsieber.customerdb.tools.CommonDialog; import de.georgsieber.customerdb.tools.StorageControl; public class SettingsActivity extends AppCompatActivity { private final static int PICK_IMAGE_REQUEST = 1; private final static int INAPP_REQUEST = 2; private final static int SYNCINFO_REQUEST = 3; private SettingsActivity me; private CustomerDatabase mDb; private FeatureCheck mFc; private SharedPreferences mSettings; Spinner mSpinnerCustomFields; Spinner mSpinnerCalendars; RadioButton mRadioButtonNoSync; RadioButton mRadioButtonCloudSync; RadioButton mRadioButtonOwnServerSync; EditText mEditTextUrl; EditText mEditTextUsername; EditText mEditTextPassword; EditText mEditTextBirthdayPreviewDays; EditText mEditTextCurrency; CheckBox mCheckBoxAllowTextInPhoneNumbers; RadioGroup mRadioGroupTheme; RadioButton mRadioButtonDarkModeSystem; RadioButton mRadioButtonDarkModeOn; RadioButton mRadioButtonDarkModeOff; SeekBar mSeekBarRed; SeekBar mSeekBarGreen; SeekBar mSeekBarBlue; View mViewColorPreview; CheckBox mCheckBoxShowPicture; CheckBox mCheckBoxShowPhoneField; CheckBox mCheckBoxShowEmailField; CheckBox mCheckBoxShowAddressField; CheckBox mCheckBoxShowNotesField; CheckBox mCheckBoxShowNewsletterField; CheckBox mCheckBoxShowBirthdayField; CheckBox mCheckBoxShowGroupField; CheckBox mCheckBoxShowFiles; CheckBox mCheckBoxShowConsentField; private int mRemoteDatabaseConnType = 0; private String mRemoteDatabaseConnURL = ""; private String mRemoteDatabaseConnUsername = ""; private String mRemoteDatabaseConnPassword = ""; private int mBirthdayPreviewDays = 0; private String mCurrency = ""; private Boolean mAllowTextInPhoneNumbers = false; private String mDefaultCustomerTitle = ""; private String mDefaultCustomerCity = ""; private String mDefaultCustomerCountry = ""; private String mDefaultCustomerGroup = ""; private String mEmailSubject = ""; private String mEmailTemplate = ""; private String mEmailNewsletterTemplate = ""; private String mEmailExportSubject = ""; private String mEmailExportTemplate = ""; private String mDefaultAppointmentTitle = ""; private String mDefaultAppointmentLocation = ""; private String mIomPassword = ""; private int mColorDarkMode = -1; private int mColorRed = 0; private int mColorGreen = 0; private int mColorBlue = 0; private boolean showCustomerPicture; private boolean showPhoneField; private boolean showEmailField; private boolean showAddressField; private boolean showNotesField; private boolean showNewsletterField; private boolean showBirthdayField; private boolean showGroupField; private boolean showFiles; private boolean showConsentField; @SuppressLint("SetTextI18n") @Override protected void onCreate(Bundle savedInstanceState) { // init settings mSettings = getSharedPreferences(MainActivity.PREFS_NAME, 0); // init activity view super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); me = this; getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); // init toolbar Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); if(getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); // find views mSpinnerCustomFields = findViewById(R.id.spinnerCustomField); mSpinnerCalendars = findViewById(R.id.spinnerCalendar); mRadioButtonNoSync = findViewById(R.id.radioButtonNoSync); mRadioButtonCloudSync = findViewById(R.id.radioButtonCloudSync); mRadioButtonOwnServerSync = findViewById(R.id.radioButtonOwnServerSync); mEditTextUrl = findViewById(R.id.editTextURL); mEditTextUsername = findViewById(R.id.editTextUsername); mEditTextPassword = findViewById(R.id.editTextPassword); mEditTextBirthdayPreviewDays = findViewById(R.id.editTextBirthdayPreviewDays); mEditTextCurrency = findViewById(R.id.editTextCurrency); mCheckBoxAllowTextInPhoneNumbers = findViewById(R.id.checkBoxAllowTextInPhoneNumbers); mRadioGroupTheme = findViewById(R.id.radioGroupTheme); mRadioButtonDarkModeSystem = findViewById(R.id.radioButtonDarkModeSystem); mRadioButtonDarkModeOn = findViewById(R.id.radioButtonDarkModeOn); mRadioButtonDarkModeOff = findViewById(R.id.radioButtonDarkModeOff); mSeekBarRed = findViewById(R.id.seekBarRed); mSeekBarGreen = findViewById(R.id.seekBarGreen); mSeekBarBlue = findViewById(R.id.seekBarBlue); mViewColorPreview = findViewById(R.id.viewColorPreview); mCheckBoxShowPicture = findViewById(R.id.checkBoxShowPicture); mCheckBoxShowPhoneField = findViewById(R.id.checkBoxShowPhoneField); mCheckBoxShowEmailField = findViewById(R.id.checkBoxShowEmailField); mCheckBoxShowAddressField = findViewById(R.id.checkBoxShowAddressField); mCheckBoxShowNotesField = findViewById(R.id.checkBoxShowNotesField); mCheckBoxShowNewsletterField = findViewById(R.id.checkBoxShowNewsletterField); mCheckBoxShowBirthdayField = findViewById(R.id.checkBoxShowBirthdayField); mCheckBoxShowGroupField = findViewById(R.id.checkBoxShowGroupField); mCheckBoxShowFiles = findViewById(R.id.checkBoxShowFiles); mCheckBoxShowConsentField = findViewById(R.id.checkBoxShowConsentField); // init DB mDb = new CustomerDatabase(this); reloadCustomFields(); reloadCalendars(); // register events mSeekBarRed.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { mColorRed = progress; updateColorPreview(mColorRed, mColorGreen, mColorBlue, mViewColorPreview); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); mSeekBarGreen.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { mColorGreen = progress; updateColorPreview(mColorRed, mColorGreen, mColorBlue, mViewColorPreview); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); mSeekBarBlue.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { mColorBlue = progress; updateColorPreview(mColorRed, mColorGreen, mColorBlue, mViewColorPreview); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); // load settings loadSettings(); // update color updateColorPreview(mColorRed, mColorGreen, mColorBlue, mViewColorPreview); ColorControl.updateActionBarColor(this, mSettings); // init logo buttons showHideLogoButtons(); // load in-app purchases mFc = new FeatureCheck(this); mFc.setFeatureCheckReadyListener(new FeatureCheck.featureCheckReadyListener() { @Override public void featureCheckReady(boolean fetchSuccess) { if(mFc.unlockedInputOnlyMode) { (findViewById(R.id.linearLayoutPassword)).setVisibility(View.VISIBLE); } else { (findViewById(R.id.linearLayoutPassword)).setVisibility(View.GONE); } if(!mFc.unlockedDesignOptions) { (findViewById(R.id.seekBarRed)).setEnabled(false); (findViewById(R.id.seekBarGreen)).setEnabled(false); (findViewById(R.id.seekBarBlue)).setEnabled(false); (findViewById(R.id.radioButtonDarkModeSystem)).setEnabled(false); (findViewById(R.id.radioButtonDarkModeOn)).setEnabled(false); (findViewById(R.id.radioButtonDarkModeOff)).setEnabled(false); } } }); mFc.init(); } void loadSettings() { // restore preferences mRemoteDatabaseConnType = mSettings.getInt("webapi-type", 0); mRemoteDatabaseConnURL = mSettings.getString("webapi-url",""); mRemoteDatabaseConnUsername = mSettings.getString("webapi-username",""); mRemoteDatabaseConnPassword = mSettings.getString("webapi-password",""); mBirthdayPreviewDays = mSettings.getInt("birthday-preview-days", BirthdayActivity.DEFAULT_BIRTHDAY_PREVIEW_DAYS); mCurrency = mSettings.getString("currency", "€"); mAllowTextInPhoneNumbers = mSettings.getBoolean("phone-allow-text", false); mDefaultCustomerTitle = mSettings.getString("default-customer-title", ""); mDefaultCustomerCity = mSettings.getString("default-customer-city", ""); mDefaultCustomerCountry = mSettings.getString("default-customer-country", ""); mDefaultCustomerGroup = mSettings.getString("default-customer-group", ""); mEmailSubject = mSettings.getString("email-subject", getResources().getString(R.string.email_subject_template)); mEmailTemplate = mSettings.getString("email-template", getResources().getString(R.string.email_text_template)); mEmailNewsletterTemplate = mSettings.getString("email-newsletter-template", getResources().getString(R.string.newsletter_text_template)); mEmailExportSubject = mSettings.getString("email-export-subject", getResources().getString(R.string.email_export_subject_template)); mEmailExportTemplate = mSettings.getString("email-export-template", getResources().getString(R.string.email_export_text_template)); mDefaultAppointmentTitle = mSettings.getString("default-appointment-title", ""); mDefaultAppointmentLocation = mSettings.getString("default-appointment-location", ""); mIomPassword = mSettings.getString("iom-password", ""); mColorDarkMode = mSettings.getInt("dark-mode-native", -1); mColorRed = mSettings.getInt("design-red", ColorControl.DEFAULT_COLOR_R); mColorGreen = mSettings.getInt("design-green", ColorControl.DEFAULT_COLOR_G); mColorBlue = mSettings.getInt("design-blue", ColorControl.DEFAULT_COLOR_B); showCustomerPicture = mSettings.getBoolean("show-customer-picture", true); showPhoneField = mSettings.getBoolean("show-phone-field", true); showEmailField = mSettings.getBoolean("show-email-field", true); showAddressField = mSettings.getBoolean("show-address-field", true); showNotesField = mSettings.getBoolean("show-notes-field", true); showNewsletterField = mSettings.getBoolean("show-newsletter-field", true); showBirthdayField = mSettings.getBoolean("show-birthday-field", true); showGroupField = mSettings.getBoolean("show-group-field", true); showFiles = mSettings.getBoolean("show-files", true); showConsentField = mSettings.getBoolean("show-consent-field", false); String lastCallReceived = mSettings.getString("last-call-received", ""); // fill text boxes switch(mRemoteDatabaseConnType) { case 0: mRadioButtonNoSync.setChecked(true); break; case 1: mRadioButtonCloudSync.setChecked(true); break; case 2: mRadioButtonOwnServerSync.setChecked(true); break; } showHideSyncOptions(null); if(mColorDarkMode == AppCompatDelegate.MODE_NIGHT_YES) { mRadioButtonDarkModeOn.setChecked(true); } else if(mColorDarkMode == AppCompatDelegate.MODE_NIGHT_NO) { mRadioButtonDarkModeOff.setChecked(true); } else { mRadioButtonDarkModeSystem.setChecked(true); } mEditTextUrl.setText(mRemoteDatabaseConnURL); mEditTextUsername.setText(mRemoteDatabaseConnUsername); mEditTextPassword.setText(mRemoteDatabaseConnPassword); mEditTextBirthdayPreviewDays.setText(Integer.toString(mBirthdayPreviewDays)); mEditTextCurrency.setText(mCurrency); mCheckBoxAllowTextInPhoneNumbers.setChecked(mAllowTextInPhoneNumbers); mSeekBarRed.setProgress(mColorRed); mSeekBarGreen.setProgress(mColorGreen); mSeekBarBlue.setProgress(mColorBlue); mCheckBoxShowPicture.setChecked(showCustomerPicture); mCheckBoxShowPhoneField.setChecked(showPhoneField); mCheckBoxShowEmailField.setChecked(showEmailField); mCheckBoxShowAddressField.setChecked(showAddressField); mCheckBoxShowNotesField.setChecked(showNotesField); mCheckBoxShowNewsletterField.setChecked((showNewsletterField)); mCheckBoxShowBirthdayField.setChecked(showBirthdayField); mCheckBoxShowGroupField.setChecked(showGroupField); mCheckBoxShowFiles.setChecked(showFiles); mCheckBoxShowConsentField.setChecked(showConsentField); if(lastCallReceived != null && lastCallReceived.equals("")) { findViewById(R.id.textViewLastCallReceived).setVisibility(View.GONE); } else { ((TextView) findViewById(R.id.textViewLastCallReceived)).setText( getResources().getString(R.string.last_call) + " " + lastCallReceived ); } } public void showHideSyncOptions(View v) { mEditTextUrl.setVisibility(View.GONE); mEditTextUsername.setVisibility(View.GONE); mEditTextPassword.setVisibility(View.GONE); if(((RadioButton) findViewById(R.id.radioButtonCloudSync)).isChecked()) { mEditTextUsername.setVisibility(View.VISIBLE); mEditTextPassword.setVisibility(View.VISIBLE); } else if(((RadioButton) findViewById(R.id.radioButtonOwnServerSync)).isChecked()) { mEditTextUrl.setVisibility(View.VISIBLE); mEditTextUsername.setVisibility(View.VISIBLE); mEditTextPassword.setVisibility(View.VISIBLE); } } private void showHideLogoButtons() { File logo = StorageControl.getStorageLogo(this); if(logo.exists()) { findViewById(R.id.buttonSettingsRemoveLogo).setVisibility(View.VISIBLE); findViewById(R.id.buttonSettingsSetLogo).setVisibility(View.GONE); } else { findViewById(R.id.buttonSettingsRemoveLogo).setVisibility(View.GONE); findViewById(R.id.buttonSettingsSetLogo).setVisibility(View.VISIBLE); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case android.R.id.home: finish(); return true; case R.id.action_settings_done: onSetMiscButtonClick(); return true; case R.id.action_settings_help: Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().getString(R.string.help_website))); startActivity(browserIntent); return true; default: return super.onOptionsItemSelected(item); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_settings, menu); return true; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch(requestCode) { case(PICK_IMAGE_REQUEST) : { if(resultCode == RESULT_OK && data != null && data.getData() != null) { try { InputStream inputStream = this.getContentResolver().openInputStream(data.getData()); byte[] targetArray = new byte[inputStream.available()]; inputStream.read(targetArray); File fl = StorageControl.getStorageLogo(this); FileOutputStream stream = new FileOutputStream(fl); stream.write(targetArray); stream.flush(); stream.close(); scanFile(fl); showHideLogoButtons(); } catch(Exception e) { e.printStackTrace(); } } break; } case(INAPP_REQUEST) : { mFc.init(); break; } case(SYNCINFO_REQUEST) : { loadSettings(); break; } } } private void scanFile(File f) { Uri uri = Uri.fromFile(f); Intent scanFileIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri); sendBroadcast(scanFileIntent); } private void updateColorPreview(int red, int green, int blue, View v) { v.setBackgroundColor(Color.argb(0xff, red, green, blue)); } protected void saveSettings() { SharedPreferences.Editor editor = mSettings.edit(); editor.putInt("webapi-type", mRemoteDatabaseConnType); editor.putString("webapi-url", mRemoteDatabaseConnURL); editor.putString("webapi-username", mRemoteDatabaseConnUsername); editor.putString("webapi-password", mRemoteDatabaseConnPassword); editor.putInt("birthday-preview-days", mBirthdayPreviewDays); editor.putString("currency", mCurrency); editor.putBoolean("phone-allow-text", mAllowTextInPhoneNumbers); editor.putString("default-customer-title", mDefaultCustomerTitle); editor.putString("default-customer-city", mDefaultCustomerCity); editor.putString("default-customer-country", mDefaultCustomerCountry); editor.putString("default-customer-group", mDefaultCustomerGroup); editor.putString("email-subject", mEmailSubject); editor.putString("email-template", mEmailTemplate); editor.putString("email-newsletter-template", mEmailNewsletterTemplate); editor.putString("email-export-subject", mEmailExportSubject); editor.putString("email-export-template", mEmailExportTemplate); editor.putString("default-appointment-title", mDefaultAppointmentTitle); editor.putString("default-appointment-location", mDefaultAppointmentLocation); editor.putString("iom-password", mIomPassword); editor.putInt("dark-mode-native", mColorDarkMode); editor.putInt("design-red", mColorRed); editor.putInt("design-green", mColorGreen); editor.putInt("design-blue", mColorBlue); editor.putBoolean("show-customer-picture", showCustomerPicture); editor.putBoolean("show-phone-field", showPhoneField); editor.putBoolean("show-email-field", showEmailField); editor.putBoolean("show-address-field", showAddressField); editor.putBoolean("show-notes-field", showNotesField); editor.putBoolean("show-newsletter-field", showNewsletterField); editor.putBoolean("show-birthday-field", showBirthdayField); editor.putBoolean("show-group-field", showGroupField); editor.putBoolean("show-files", showFiles); editor.putBoolean("show-consent-field", showConsentField); editor.apply(); } public void dialog(String text, final boolean finishActivity) { AlertDialog ad = new AlertDialog.Builder(this).create(); ad.setCancelable(false); ad.setMessage(text); ad.setButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if(finishActivity) finish(); } }); ad.show(); } public void onSetMiscButtonClick() { mRemoteDatabaseConnURL = mEditTextUrl.getText().toString(); mRemoteDatabaseConnUsername = mEditTextUsername.getText().toString(); mRemoteDatabaseConnPassword = mEditTextPassword.getText().toString(); if(mRadioButtonCloudSync.isChecked()) mRemoteDatabaseConnType = 1; else if(mRadioButtonOwnServerSync.isChecked()) mRemoteDatabaseConnType = 2; else { mRemoteDatabaseConnType = 0; mRemoteDatabaseConnURL = ""; mRemoteDatabaseConnUsername = ""; mRemoteDatabaseConnPassword = ""; } if(mRadioButtonDarkModeOn.isChecked()) { mColorDarkMode = AppCompatDelegate.MODE_NIGHT_YES; } else if(mRadioButtonDarkModeOff.isChecked()) { mColorDarkMode = AppCompatDelegate.MODE_NIGHT_NO; } else { mColorDarkMode = AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM; } if(mColorDarkMode != CustomerDatabaseApp.getAppTheme(me)) { CustomerDatabaseApp.setAppTheme(mColorDarkMode); } try { mBirthdayPreviewDays = Integer.parseInt(mEditTextBirthdayPreviewDays.getText().toString()); } catch(NumberFormatException ignored) {} mCurrency = mEditTextCurrency.getText().toString(); mAllowTextInPhoneNumbers = mCheckBoxAllowTextInPhoneNumbers.isChecked(); showCustomerPicture = mCheckBoxShowPicture.isChecked(); showPhoneField = mCheckBoxShowPhoneField.isChecked(); showEmailField = mCheckBoxShowEmailField.isChecked(); showAddressField = mCheckBoxShowAddressField.isChecked(); showNotesField = mCheckBoxShowNotesField.isChecked(); showNewsletterField = mCheckBoxShowNewsletterField.isChecked(); showBirthdayField = mCheckBoxShowBirthdayField.isChecked(); showGroupField = mCheckBoxShowGroupField.isChecked(); showFiles = mCheckBoxShowFiles.isChecked(); showConsentField = mCheckBoxShowConsentField.isChecked(); String lastUsername = mSettings.getString("webapi-username",""); if(mRemoteDatabaseConnType != 0 && !lastUsername.equals("") && !lastUsername.equals(mRemoteDatabaseConnUsername)) { // exit after dialog DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch(which) { case DialogInterface.BUTTON_POSITIVE: mSettings.edit().putLong("last-successful-sync", 0).apply(); mDb.truncateCustomers(); mDb.truncateVouchers(); mDb.truncateCalendars(); mDb.truncateAppointments(); saveSettings(); finish(); break; case DialogInterface.BUTTON_NEGATIVE: saveSettings(); finish(); break; } } }; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getString(R.string.sync_account_changed)) .setMessage(getString(R.string.sync_account_changed_text)) .setPositiveButton(getString(R.string.yes), dialogClickListener) .setNegativeButton(getString(R.string.no), dialogClickListener).show(); } else { // normal exit saveSettings(); finish(); } } public void onApiHelpButtonClick(View v) { Intent infoIntent = new Intent(this, InfoActivity.class); startActivityForResult(infoIntent, SYNCINFO_REQUEST); } private void dialogInApp(String title, String text) { AlertDialog.Builder ad = new AlertDialog.Builder(this); ad.setTitle(title); ad.setMessage(text); ad.setIcon(getResources().getDrawable(R.drawable.ic_warning_orange_24dp)); ad.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); ad.setNeutralButton(getResources().getString(R.string.more), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startActivityForResult(new Intent(me, AboutActivity.class), INAPP_REQUEST); } }); ad.show(); } private void setTextFieldsFocusable(boolean focusable) { mEditTextUrl.setFocusable(focusable); mEditTextUsername.setFocusable(focusable); mEditTextPassword.setFocusable(focusable); mEditTextBirthdayPreviewDays.setFocusable(focusable); mEditTextCurrency.setFocusable(focusable); mEditTextUrl.setFocusableInTouchMode(focusable); mEditTextUsername.setFocusableInTouchMode(focusable); mEditTextPassword.setFocusableInTouchMode(focusable); mEditTextCurrency.setFocusableInTouchMode(focusable); } public void onSetPasswordButtonClick(View v) { final Dialog ad = new Dialog(this); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_set_password); if(ad.getWindow() != null) ad.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); ad.show(); ad.findViewById(R.id.buttonInputBoxOK).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String password1 = ((EditText) ad.findViewById(R.id.editTextPassword)).getText().toString(); String password2 = ((EditText) ad.findViewById(R.id.editTextPasswordConfirm)).getText().toString(); if(!password1.equals(password2)) { dialog(getResources().getString(R.string.passwords_not_matching), false); return; } mIomPassword = password1; ad.dismiss(); } }); } public void onAddCustomFieldButtonClick(View v) { if(mFc == null || !mFc.unlockedCustomFields) { dialogInApp(getResources().getString(R.string.feature_locked), getResources().getString(R.string.feature_locked_text)); return; } setTextFieldsFocusable(false); final Dialog ad = new Dialog(this); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_new_custom_field); if(ad.getWindow() != null) ad.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); ad.findViewById(R.id.buttonNewCustomFieldOK).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); String input = ((EditText) ad.findViewById(R.id.editTextCustomFieldTitle)).getText().toString(); if(input.trim().equals("")) { CommonDialog.show(me, getString(R.string.error), getString(R.string.name_cannot_be_empty), CommonDialog.TYPE.FAIL, false); return; } int type = -1; if(((RadioButton) ad.findViewById(R.id.radioButtonNewFieldAlphanumeric)).isChecked()) type = 0; if(((RadioButton) ad.findViewById(R.id.radioButtonNewFieldNumeric)).isChecked()) type = 1; if(((RadioButton) ad.findViewById(R.id.radioButtonNewFieldDropDown)).isChecked()) type = 2; if(((RadioButton) ad.findViewById(R.id.radioButtonNewFieldDate)).isChecked()) type = 3; if(((RadioButton) ad.findViewById(R.id.radioButtonNewFieldAlphanumericMultiLine)).isChecked()) type = 4; mDb.addCustomField(new CustomField(input, type)); reloadCustomFields(); } }); ad.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { setTextFieldsFocusable(true); } }); ad.show(); } public void onRemoveCustomFieldButtonClick(View v) { if(mSpinnerCustomFields.getSelectedItem() != null) { AlertDialog.Builder ad = new AlertDialog.Builder(me); ad.setPositiveButton(getResources().getString(R.string.delete), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mDb.removeCustomField(((CustomField) mSpinnerCustomFields.getSelectedItem()).mId); reloadCustomFields(); }}); ad.setNegativeButton(getResources().getString(R.string.abort), null); ad.setTitle(getResources().getString(R.string.reallydelete_title)); ad.setMessage(((CustomField) mSpinnerCustomFields.getSelectedItem()).mTitle); ad.show(); } } public void onEditCustomFieldButtonClick(View v) { final CustomField currentCustomField = (CustomField) mSpinnerCustomFields.getSelectedItem(); final String oldFieldTitle = currentCustomField.mTitle; setTextFieldsFocusable(false); final Dialog ad = new Dialog(this); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_new_custom_field); if(ad.getWindow() != null) ad.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); ((EditText) ad.findViewById(R.id.editTextCustomFieldTitle)).setText(currentCustomField.mTitle); final RadioButton radioButtonAlphanumeric = ad.findViewById(R.id.radioButtonNewFieldAlphanumeric); final RadioButton radioButtonNumeric = ad.findViewById(R.id.radioButtonNewFieldNumeric); final RadioButton radioButtonDropDown = ad.findViewById(R.id.radioButtonNewFieldDropDown); final RadioButton radioButtonDate = ad.findViewById(R.id.radioButtonNewFieldDate); final RadioButton radioButtonAlphanumericMultiLine = ad.findViewById(R.id.radioButtonNewFieldAlphanumericMultiLine); if(currentCustomField.mType == 0) radioButtonAlphanumeric.setChecked(true); else if(currentCustomField.mType == 1) radioButtonNumeric.setChecked(true); else if(currentCustomField.mType == 2) radioButtonDropDown.setChecked(true); else if(currentCustomField.mType == 3) radioButtonDate.setChecked(true); else if(currentCustomField.mType == 4) radioButtonAlphanumericMultiLine.setChecked(true); ad.findViewById(R.id.buttonNewCustomFieldOK).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); String input = ((EditText) ad.findViewById(R.id.editTextCustomFieldTitle)).getText().toString(); int type = -1; if(radioButtonAlphanumeric.isChecked()) type = 0; if(radioButtonNumeric.isChecked()) type = 1; if(radioButtonDropDown.isChecked()) type = 2; if(radioButtonDate.isChecked()) type = 3; if(radioButtonAlphanumericMultiLine.isChecked()) type = 4; if(input.trim().equals("")) { CommonDialog.show(me, getString(R.string.error), getString(R.string.name_cannot_be_empty), CommonDialog.TYPE.FAIL, false); return; } currentCustomField.mTitle = input; currentCustomField.mType = type; mDb.updateCustomField(currentCustomField); // rebase custom fields in customer objects if(!oldFieldTitle.equals(input)) { for(Customer c : mDb.getCustomers(null, false, false, null)) { List<CustomField> fields = c.getCustomFields(); for(CustomField field : fields) { if(field.mTitle.equals(oldFieldTitle)) { fields.add(new CustomField(input, field.mValue)); fields.remove(field); c.setCustomFields(fields); c.mLastModified = new Date(); mDb.updateCustomer(c); break; } } } } reloadCustomFields(); } }); ad.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { setTextFieldsFocusable(true); } }); ad.show(); ((EditText) ad.findViewById(R.id.editTextCustomFieldTitle)).selectAll(); } public void onAddCustomFieldValueButtonClick(View v) { Spinner s1 = (findViewById(R.id.spinnerCustomField)); CustomField cf = (CustomField) s1.getSelectedItem(); if(cf == null) return; final int fieldId = cf.mId; setTextFieldsFocusable(false); final Dialog ad = new Dialog(this); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_input_box); ((TextView) ad.findViewById(R.id.textViewInputBox)).setText(getResources().getString(R.string.new_drop_down_value)); if(ad.getWindow() != null) ad.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); ad.findViewById(R.id.buttonInputBoxOK).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); String input = ((EditText) ad.findViewById(R.id.editTextInputBox)).getText().toString(); mDb.addCustomFieldPreset(fieldId, input); reloadCustomFieldPresets(); } }); ad.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { setTextFieldsFocusable(true); } }); ad.show(); } public void onRemoveCustomFieldValueButtonClick(View v) { final Spinner s = findViewById(R.id.spinnerCustomFieldDropDownValues); if(s.getSelectedItem() != null) { AlertDialog.Builder ad = new AlertDialog.Builder(me); ad.setPositiveButton(getResources().getString(R.string.delete), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mDb.removeCustomFieldPreset(((CustomField) s.getSelectedItem()).mId); reloadCustomFieldPresets(); }}); ad.setNegativeButton(getResources().getString(R.string.abort), null); ad.setTitle(getResources().getString(R.string.reallydelete_title)); ad.setMessage(((CustomField) s.getSelectedItem()).mTitle); ad.show(); } } private void reloadCustomFields() { ArrayAdapter<CustomField> a = new ArrayAdapter<>(this, R.layout.item_list_simple, mDb.getCustomFields()); mSpinnerCustomFields.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { CustomField cf = (CustomField) parent.getSelectedItem(); if(cf.mType == 2) { findViewById(R.id.linearLayoutCustomFieldsSettingsDropDownValues).setVisibility(View.VISIBLE); reloadCustomFieldPresets(); } else { findViewById(R.id.linearLayoutCustomFieldsSettingsDropDownValues).setVisibility(View.GONE); } } @Override public void onNothingSelected(AdapterView<?> parent) { findViewById(R.id.linearLayoutCustomFieldsSettingsDropDownValues).setVisibility(View.GONE); } }); mSpinnerCustomFields.setAdapter(a); if(a.getCount() == 0) { findViewById(R.id.linearLayoutCustomFieldsSettingsDropDownValues).setVisibility(View.GONE); findViewById(R.id.buttonEditCustomFieldSettings).setVisibility(View.GONE); findViewById(R.id.buttonRemoveCustomFieldSettings).setVisibility(View.GONE); } else { findViewById(R.id.buttonEditCustomFieldSettings).setVisibility(View.VISIBLE); findViewById(R.id.buttonRemoveCustomFieldSettings).setVisibility(View.VISIBLE); } } private void reloadCustomFieldPresets() { Spinner s1 = (findViewById(R.id.spinnerCustomField)); CustomField cf = (CustomField) s1.getSelectedItem(); if(cf == null) return; ArrayAdapter<CustomField> a = new ArrayAdapter<>(this, R.layout.item_list_simple, mDb.getCustomFieldPresets(cf.mId)); Spinner s2 = (findViewById(R.id.spinnerCustomFieldDropDownValues)); s2.setAdapter(a); s2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { } @Override public void onNothingSelected(AdapterView<?> parent) { } }); if(a.getCount() == 0) { findViewById(R.id.buttonRemoveCustomFieldValueSettings).setVisibility(View.GONE); } else { findViewById(R.id.buttonRemoveCustomFieldValueSettings).setVisibility(View.VISIBLE); } } private void reloadCalendars() { ArrayAdapter<CustomerCalendar> a = new ArrayAdapter<>(this, R.layout.item_list_simple, mDb.getCalendars(false)); mSpinnerCalendars.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {} @Override public void onNothingSelected(AdapterView<?> parent) {} }); mSpinnerCalendars.setAdapter(a); if(a.getCount() == 0) { findViewById(R.id.buttonEditCalendarSettings).setVisibility(View.GONE); findViewById(R.id.buttonRemoveCalendarSettings).setVisibility(View.GONE); } else { findViewById(R.id.buttonEditCalendarSettings).setVisibility(View.VISIBLE); findViewById(R.id.buttonRemoveCalendarSettings).setVisibility(View.VISIBLE); } } public void onAddCalendarButtonClick(View v) { if(mFc == null || !mFc.unlockedCalendar) { dialogInApp(getResources().getString(R.string.feature_locked), getResources().getString(R.string.feature_locked_text)); return; } setTextFieldsFocusable(false); final Dialog ad = new Dialog(this); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_new_calendar); if(ad.getWindow() != null) ad.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); final EditText editTextTitle = (EditText) ad.findViewById(R.id.editTextTitle); final View colorPreviewCalendar = ad.findViewById(R.id.viewColorPreview); final SeekBar seekBarRed = ((SeekBar) ad.findViewById(R.id.seekBarRed)); final SeekBar seekBarGreen = ((SeekBar) ad.findViewById(R.id.seekBarGreen)); final SeekBar seekBarBlue = ((SeekBar) ad.findViewById(R.id.seekBarBlue)); seekBarRed.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { updateColorPreview(seekBarRed.getProgress(), seekBarGreen.getProgress(), seekBarBlue.getProgress(), colorPreviewCalendar); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); seekBarGreen.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { updateColorPreview(seekBarRed.getProgress(), seekBarGreen.getProgress(), seekBarBlue.getProgress(), colorPreviewCalendar); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); seekBarBlue.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { updateColorPreview(seekBarRed.getProgress(), seekBarGreen.getProgress(), seekBarBlue.getProgress(), colorPreviewCalendar); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); updateColorPreview(seekBarRed.getProgress(), seekBarGreen.getProgress(), seekBarBlue.getProgress(), colorPreviewCalendar); ad.findViewById(R.id.buttonOK).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); if(editTextTitle.getText().toString().trim().equals("")) { CommonDialog.show(me, getString(R.string.error), getString(R.string.name_cannot_be_empty), CommonDialog.TYPE.FAIL, false); return; } CustomerCalendar c = new CustomerCalendar(); c.mId = CustomerCalendar.generateID(); c.mTitle = editTextTitle.getText().toString(); c.mColor = ColorControl.getHexColor(Color.rgb(seekBarRed.getProgress(), seekBarGreen.getProgress(), seekBarBlue.getProgress())); if(!c.mTitle.equals("")) mDb.addCalendar(c); reloadCalendars(); } }); ad.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { setTextFieldsFocusable(true); } }); ad.show(); } public void onRemoveCalendarButtonClick(View v) { if(mSpinnerCalendars.getSelectedItem() != null) { AlertDialog.Builder ad = new AlertDialog.Builder(me); ad.setPositiveButton(getResources().getString(R.string.delete), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mDb.removeCalendar(((CustomerCalendar) mSpinnerCalendars.getSelectedItem())); reloadCalendars(); }}); ad.setNegativeButton(getResources().getString(R.string.abort), null); ad.setTitle(getResources().getString(R.string.reallydelete_title)); ad.setMessage(((CustomerCalendar) mSpinnerCalendars.getSelectedItem()).mTitle); ad.show(); } } public void onEditCalendarButtonClick(View v) { final CustomerCalendar currentCalendar = (CustomerCalendar) mSpinnerCalendars.getSelectedItem(); int color = Color.parseColor(currentCalendar.mColor); setTextFieldsFocusable(false); final Dialog ad = new Dialog(this); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_new_calendar); if(ad.getWindow() != null) ad.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); final View colorPreviewCalendar = ad.findViewById(R.id.viewColorPreview); final EditText editTextTitle = (EditText) ad.findViewById(R.id.editTextTitle); editTextTitle.setText(currentCalendar.mTitle); final SeekBar seekBarRed = ((SeekBar) ad.findViewById(R.id.seekBarRed)); final SeekBar seekBarGreen = ((SeekBar) ad.findViewById(R.id.seekBarGreen)); final SeekBar seekBarBlue = ((SeekBar) ad.findViewById(R.id.seekBarBlue)); seekBarRed.setProgress(Color.red(color)); seekBarRed.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { updateColorPreview(seekBarRed.getProgress(), seekBarGreen.getProgress(), seekBarBlue.getProgress(), colorPreviewCalendar); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); seekBarGreen.setProgress(Color.green(color)); seekBarGreen.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { updateColorPreview(seekBarRed.getProgress(), seekBarGreen.getProgress(), seekBarBlue.getProgress(), colorPreviewCalendar); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); seekBarBlue.setProgress(Color.blue(color)); seekBarBlue.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { updateColorPreview(seekBarRed.getProgress(), seekBarGreen.getProgress(), seekBarBlue.getProgress(), colorPreviewCalendar); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); updateColorPreview(seekBarRed.getProgress(), seekBarGreen.getProgress(), seekBarBlue.getProgress(), colorPreviewCalendar); ad.findViewById(R.id.buttonOK).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); if(editTextTitle.getText().toString().trim().equals("")) { CommonDialog.show(me, getString(R.string.error), getString(R.string.name_cannot_be_empty), CommonDialog.TYPE.FAIL, false); return; } currentCalendar.mTitle = editTextTitle.getText().toString(); currentCalendar.mColor = ColorControl.getHexColor(Color.rgb(seekBarRed.getProgress(), seekBarGreen.getProgress(), seekBarBlue.getProgress())); currentCalendar.mLastModified = new Date(); mDb.updateCalendar(currentCalendar); reloadCalendars(); } }); ad.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { setTextFieldsFocusable(true); } }); ad.show(); editTextTitle.selectAll(); } public void onChooseLogoButtonClick(View v) { if(mFc != null && mFc.unlockedDesignOptions) { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST); } else { dialogInApp(getResources().getString(R.string.feature_locked), getResources().getString(R.string.feature_locked_text)); } } public void onRemoveLogoButtonClick(View v) { File logo = StorageControl.getStorageLogo(this); if(logo.exists()) { if(logo.delete()) { scanFile(logo); dialog(getResources().getString(R.string.removed_logo), false); } else { dialog(getResources().getString(R.string.removed_logo_failed), false); } } showHideLogoButtons(); } public void onResetColorButtonClick(View v) { ((SeekBar) findViewById(R.id.seekBarRed)).setProgress(ColorControl.DEFAULT_COLOR_R); ((SeekBar) findViewById(R.id.seekBarGreen)).setProgress(ColorControl.DEFAULT_COLOR_G); ((SeekBar) findViewById(R.id.seekBarBlue)).setProgress(ColorControl.DEFAULT_COLOR_B); } public void changeDefaultCustomerTitle(View v) { final Dialog ad = inputBox(getResources().getString(R.string.default_customer_title), this.mDefaultCustomerTitle); ad.findViewById(R.id.buttonInputBoxOK).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { me.mDefaultCustomerTitle = ((EditText) ad.findViewById(R.id.editTextInputBox)).getText().toString(); ad.dismiss(); } }); } public void changeDefaultCustomerCity(View v) { final Dialog ad = inputBox(getResources().getString(R.string.default_customer_city), this.mDefaultCustomerCity); ad.findViewById(R.id.buttonInputBoxOK).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { me.mDefaultCustomerCity = ((EditText) ad.findViewById(R.id.editTextInputBox)).getText().toString(); ad.dismiss(); } }); } public void changeDefaultCustomerCountry(View v) { final Dialog ad = inputBox(getResources().getString(R.string.default_customer_country), this.mDefaultCustomerCountry); ad.findViewById(R.id.buttonInputBoxOK).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { me.mDefaultCustomerCountry = ((EditText) ad.findViewById(R.id.editTextInputBox)).getText().toString(); ad.dismiss(); } }); } public void changeDefaultCustomerGroup(View v) { final Dialog ad = inputBox(getResources().getString(R.string.default_customer_group), this.mDefaultCustomerGroup); ad.findViewById(R.id.buttonInputBoxOK).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { me.mDefaultCustomerGroup = ((EditText) ad.findViewById(R.id.editTextInputBox)).getText().toString(); ad.dismiss(); } }); } public void changeEmailSubject(View v) { final Dialog ad = inputBox(getResources().getString(R.string.email_subject), this.mEmailSubject); ad.findViewById(R.id.buttonInputBoxOK).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { me.mEmailSubject = ((EditText) ad.findViewById(R.id.editTextInputBox)).getText().toString(); ad.dismiss(); } }); } public void changeEmailTemplate(View v) { final Dialog ad = inputBox(getResources().getString(R.string.email_template_long), this.mEmailTemplate); ad.findViewById(R.id.buttonInputBoxOK).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { me.mEmailTemplate = ((EditText) ad.findViewById(R.id.editTextInputBox)).getText().toString(); ad.dismiss(); } }); } public void changeNewsletterTemplate(View v) { final Dialog ad = inputBox(getResources().getString(R.string.newsletter_template), this.mEmailNewsletterTemplate); ad.findViewById(R.id.buttonInputBoxOK).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { me.mEmailNewsletterTemplate = ((EditText) ad.findViewById(R.id.editTextInputBox)).getText().toString(); ad.dismiss(); } }); } public void changeExportSubject(View v) { final Dialog ad = inputBox(getResources().getString(R.string.email_export_subject), this.mEmailExportSubject); ad.findViewById(R.id.buttonInputBoxOK).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { me.mEmailExportSubject = ((EditText) ad.findViewById(R.id.editTextInputBox)).getText().toString(); ad.dismiss(); } }); } public void changeExportTemplate(View v) { final Dialog ad = inputBox(getResources().getString(R.string.email_export_template), this.mEmailExportTemplate); ad.findViewById(R.id.buttonInputBoxOK).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { me.mEmailExportTemplate = ((EditText) ad.findViewById(R.id.editTextInputBox)).getText().toString(); ad.dismiss(); } }); } public void changeDefaultAppointmentTitle(View v) { final Dialog ad = inputBox(getResources().getString(R.string.default_appointment_title), this.mDefaultAppointmentTitle); ad.findViewById(R.id.buttonInputBoxOK).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { me.mDefaultAppointmentTitle = ((EditText) ad.findViewById(R.id.editTextInputBox)).getText().toString(); ad.dismiss(); } }); } public void changeDefaultAppointmentLocation(View v) { final Dialog ad = inputBox(getResources().getString(R.string.default_appointment_location), this.mDefaultAppointmentLocation); ad.findViewById(R.id.buttonInputBoxOK).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { me.mDefaultAppointmentLocation = ((EditText) ad.findViewById(R.id.editTextInputBox)).getText().toString(); ad.dismiss(); } }); } private Dialog inputBox(String text, String defaultValue) { final Dialog ad = new Dialog(this); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_input_box); ((TextView) ad.findViewById(R.id.textViewInputBox)).setText(text); ((EditText) ad.findViewById(R.id.editTextInputBox)).setText(defaultValue); ((EditText) ad.findViewById(R.id.editTextInputBox)).selectAll(); if(ad.getWindow() != null) ad.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); ad.show(); return ad; } public void onClickInstallPluginApp(View v) { Intent intent = getPackageManager().getLaunchIntentForPackage(getString(R.string.plugin_app_package_name)); if(intent == null) { // open download page Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().getString(R.string.plugin_app_url))); startActivity(browserIntent); } else { // start plugin app startActivity(intent); } } }
57,897
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
BirthdayActivity.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/BirthdayActivity.java
package de.georgsieber.customerdb; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import de.georgsieber.customerdb.model.Customer; import de.georgsieber.customerdb.tools.ColorControl; public class BirthdayActivity extends AppCompatActivity { final static int DEFAULT_BIRTHDAY_PREVIEW_DAYS = 14; private final static int VIEW_REQUEST = 1; private BirthdayActivity me; private CustomerDatabase mDb; @Override protected void onCreate(Bundle savedInstanceState) { // init settings SharedPreferences settings = getSharedPreferences(MainActivity.PREFS_NAME, 0); // init db mDb = new CustomerDatabase(this); // init activity view super.onCreate(savedInstanceState); setContentView(R.layout.activity_birthday); me = this; // init toolbar Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); if(getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); // init colors ColorControl.updateActionBarColor(this, settings); // show birthdays from intent extra try { int previewDays = BirthdayActivity.getBirthdayPreviewDays(settings); ArrayList<Customer> birthdays = getSoonBirthdayCustomers(mDb.getCustomers(null, false, false, null), previewDays); bindToListView(birthdays); } catch(Exception e) { e.printStackTrace(); } // ListView init final ListView listView = findViewById(R.id.mainBirthdayList); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Customer customerObject = (Customer) listView.getItemAtPosition(position); Intent myIntent = new Intent(me, CustomerDetailsActivity.class); myIntent.putExtra("customer-id", customerObject.mId); startActivityForResult(myIntent, VIEW_REQUEST); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case android.R.id.home: finish(); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch(requestCode) { case(VIEW_REQUEST): { if(resultCode == Activity.RESULT_OK) { // end birthday activity if changes were made and pass data to MainActivity if(data.getStringExtra("action").equals("update")) { Intent output = new Intent(); output.putExtra("action", "update"); setResult(RESULT_OK, output); finish(); } } break; } } } private void bindToListView(ArrayList<Customer> customers) { ((ListView)findViewById(R.id.mainBirthdayList)).setAdapter(new CustomerAdapterBirthday(this, customers)); } static int getBirthdayPreviewDays(SharedPreferences settings) { int days = BirthdayActivity.DEFAULT_BIRTHDAY_PREVIEW_DAYS; if(settings != null) { days = settings.getInt("birthday-preview-days", days); } return days; } static ArrayList<Customer> getSoonBirthdayCustomers(List<Customer> customers, int days) { ArrayList<Customer> birthdayCustomers = new ArrayList<>(); Date start = new Date(); Date end = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(end); cal.add(Calendar.DATE, days); // number of days to add end = cal.getTime(); cal.setTime(start); cal.add(Calendar.DATE, -1); // number of days to add start = cal.getTime(); for(Customer c: customers) { Date birthday = c.getNextBirthday(); if(birthday != null && isWithinRange(birthday, start, end)) birthdayCustomers.add(c); } Collections.sort(birthdayCustomers, new Comparator<Customer>() { public int compare(Customer o1, Customer o2) { return o1.getNextBirthday().compareTo(o2.getNextBirthday()); } }); return birthdayCustomers; } private static boolean isWithinRange(Date testDate, Date startDate, Date endDate) { return ((!testDate.before(startDate)) && (!testDate.after(endDate))); } }
5,242
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
DrawingView.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/DrawingView.java
package de.georgsieber.customerdb; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; class DrawingView extends View { public int width; public int height; public Path mPath; private Paint mPaint; public Canvas mCanvas; private Bitmap mBitmap; private Paint mBitmapPaint; private Paint circlePaint; private Path circlePath; private Context context; public DrawingView(Context c) { super(c); context = c; init(); } public DrawingView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public DrawingView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { mPath = new Path(); mBitmapPaint = new Paint(Paint.DITHER_FLAG); circlePaint = new Paint(); circlePath = new Path(); circlePaint.setAntiAlias(true); circlePaint.setColor(Color.argb(255,0,0,80)); circlePaint.setStyle(Paint.Style.STROKE); circlePaint.setStrokeJoin(Paint.Join.MITER); circlePaint.setStrokeWidth(6f); mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setDither(true); mPaint.setColor(Color.BLACK); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeJoin(Paint.Join.ROUND); mPaint.setStrokeCap(Paint.Cap.ROUND); mPaint.setStrokeWidth(9); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); try { mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); mCanvas = new Canvas(mBitmap); mCanvas.drawColor(Color.WHITE); } catch(Exception e) { e.printStackTrace(); } } @Override protected void onDraw(Canvas canvas) { canvas.drawColor(Color.WHITE); super.onDraw(canvas); canvas.drawBitmap( mBitmap, 0, 0, mBitmapPaint); canvas.drawPath( mPath, mPaint); canvas.drawPath( circlePath, circlePaint); } private float mX, mY; private static final float TOUCH_TOLERANCE = 4; private void touch_start(float x, float y) { mPath.reset(); mPath.moveTo(x, y); mX = x; mY = y; } private void touch_move(float x, float y) { float dx = Math.abs(x - mX); float dy = Math.abs(y - mY); if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) { mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2); mX = x; mY = y; circlePath.reset(); circlePath.addCircle(mX, mY, 35, Path.Direction.CW); } } private void touch_up() { mPath.lineTo(mX, mY); circlePath.reset(); // commit the path to our offscreen mCanvas.drawPath(mPath, mPaint); // kill this so we don't double draw mPath.reset(); } @Override public boolean onTouchEvent(MotionEvent event) { float x = event.getX(); float y = event.getY(); switch(event.getAction()) { case MotionEvent.ACTION_DOWN: touch_start(x, y); invalidate(); break; case MotionEvent.ACTION_MOVE: touch_move(x, y); invalidate(); break; case MotionEvent.ACTION_UP: touch_up(); invalidate(); break; } return true; } }
3,833
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
CalendarFragment.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/CalendarFragment.java
package de.georgsieber.customerdb; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import de.georgsieber.customerdb.model.Customer; import de.georgsieber.customerdb.model.CustomerAppointment; import de.georgsieber.customerdb.model.CustomerCalendar; import de.georgsieber.customerdb.tools.DateControl; public class CalendarFragment extends Fragment { private CustomerDatabase mDb; private Date mShowDate = new Date(); private List<CustomerCalendar> mShowCalendars = new ArrayList<>(); private RelativeLayout relativeLayoutCalendarRoot; private static final int MINUTES_IN_A_HOUR = 24 * 60; private static List<CustomerAppointment> mAppointments = new ArrayList<>(); private static final int EDIT_APPOINTMENT_REQUEST = 1; public void show(List<CustomerCalendar> calendars, Date date) { mShowDate = date; mShowCalendars = calendars; drawEvents(); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // init db mDb = new CustomerDatabase(getContext()); // register event for redraw View v = inflater.inflate(R.layout.fragment_calendar, container, false); relativeLayoutCalendarRoot = (RelativeLayout)v.findViewById(R.id.rl_calendar_root); relativeLayoutCalendarRoot.post(new Runnable() { @Override public void run() { drawEvents(); } }); return v; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch(requestCode) { case(EDIT_APPOINTMENT_REQUEST): { drawEvents(); } } } private void drawEvents() { // clear old entries mAppointments.clear(); for(int i = relativeLayoutCalendarRoot.getChildCount()-1; i >= 0; i--) { if(relativeLayoutCalendarRoot.getChildAt(i) instanceof CalendarAppointmentView) relativeLayoutCalendarRoot.removeViewAt(i); } // add new entries for(CustomerCalendar c : mShowCalendars) { for(CustomerAppointment a : mDb.getAppointments(c.mId, mShowDate, false, null)) { a.mColor = c.mColor; mAppointments.add(a); } } // draw entries if(mAppointments != null && !mAppointments.isEmpty()) { Collections.sort(mAppointments, new TimeComparator()); int screenWidth = relativeLayoutCalendarRoot.getWidth(); int screenHeight = relativeLayoutCalendarRoot.getHeight(); List<Cluster> clusters = createClusters(createCliques(mAppointments)); for(Cluster c : clusters) { for(final CustomerAppointment a : c.getAppointments()) { int itemWidth = screenWidth / c.getMaxCliqueSize(); int leftMargin = c.getNextPosition() * itemWidth; int itemHeight = Math.max(minutesToPixels(screenHeight, a.getEndTimeInMinutes()) - minutesToPixels(screenHeight, a.getStartTimeInMinutes()), (int)getResources().getDimension(R.dimen.appointment_min_height)); int topMargin = minutesToPixels(screenHeight, a.getStartTimeInMinutes()); int color = Color.LTGRAY; try { color = Color.parseColor(a.mColor); } catch(Exception ignored) {} CalendarAppointmentView appointmentView = (CalendarAppointmentView) getLayoutInflater().inflate(R.layout.item_appointment, null); appointmentView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getContext(), CalendarAppointmentEditActivity.class); intent.putExtra("appointment-id", a.mId); startActivityForResult(intent, EDIT_APPOINTMENT_REQUEST); } }); String customerText = ""; if(a.mCustomerId != null) { Customer relatedCustomer = mDb.getCustomerById(a.mCustomerId, false, false); if(relatedCustomer != null) { customerText = relatedCustomer.getFullName(false); } } else { customerText = a.mCustomer; } appointmentView.setValues(a.mTitle, (customerText+" "+a.mLocation).trim(), DateControl.displayTimeFormat.format(a.mTimeStart)+" - "+DateControl.displayTimeFormat.format(a.mTimeEnd), color); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(itemWidth, itemHeight); params.setMargins(leftMargin, topMargin, 0, 0); relativeLayoutCalendarRoot.addView(appointmentView, params); } } } } private int minutesToPixels(int screenHeight, int minutes) { return (screenHeight * minutes) / MINUTES_IN_A_HOUR; } public static List<Clique> createCliques(List<CustomerAppointment> appointments) { int startTime = appointments.get(0).getStartTimeInMinutes(); int endTime = appointments.get(appointments.size() - 1).getEndTimeInMinutes(); List<Clique> cliques = new ArrayList<>(); for(int i = startTime; i <= endTime; i++) { Clique c = null; for(CustomerAppointment e : appointments) { if(e.getStartTimeInMinutes() < i && e.getEndTimeInMinutes() > i) { if(c == null) { c = new Clique(); } c.addAppointment(e); } } if(c != null) { if(!cliques.contains(c)) { cliques.add(c); } } } return cliques; } public static List<Cluster> createClusters(List<Clique> cliques) { List<Cluster> clusters = new ArrayList<>(); Cluster cluster = null; for(Clique c : cliques) { if(cluster == null) { cluster = new Cluster(); cluster.addClique(c); } else { if(cluster.getLastClique().intersects(c)) { cluster.addClique(c); } else { clusters.add(cluster); cluster = new Cluster(); cluster.addClique(c); } } } if(cluster != null) { clusters.add(cluster); } return clusters; } public static class TimeComparator implements Comparator { public int compare(Object obj1, Object obj2) { CustomerAppointment o1 = (CustomerAppointment)obj1; CustomerAppointment o2 = (CustomerAppointment)obj2; int change1 = o1.getStartTimeInMinutes(); int change2 = o2.getStartTimeInMinutes(); if(change1 < change2) return -1; if(change1 > change2) return 1; int change3 = o1.getEndTimeInMinutes(); int change4 = o2.getEndTimeInMinutes(); if(change3 < change4) return -1; if(change3 > change4) return 1; return 0; } } public static class Clique { private List<CustomerAppointment> mAppointments = new ArrayList<>(); public List<CustomerAppointment> getAppointments() { return mAppointments; } public void addAppointment(CustomerAppointment a) { mAppointments.add(a); } public boolean intersects(Clique clique2) { for(CustomerAppointment i : mAppointments) { for(CustomerAppointment k : clique2.mAppointments) { if(i.equals(k)) { return true; } } } return false; } } public static class Cluster { private List<Clique> cliques = new ArrayList<>(); private int maxCliqueSize = 1; private int nextCurrentDrawPosition = 0; public void addClique(Clique c) { this.cliques.add(c); this.maxCliqueSize = Math.max(maxCliqueSize, c.getAppointments().size()); } public int getMaxCliqueSize() { return maxCliqueSize; } public Clique getLastClique() { if(cliques.size() > 0){ return cliques.get(cliques.size() - 1); } return null; } public List<CustomerAppointment> getAppointments() { List<CustomerAppointment> events = new ArrayList<>(); for(Clique clique : cliques) { for(CustomerAppointment a : clique.getAppointments()) { if(!events.contains(a)) { events.add(a); } } } return events; } public int getNextPosition() { int position = nextCurrentDrawPosition; if(position >= maxCliqueSize) { position = 0; } nextCurrentDrawPosition = position + 1; return position; } } }
9,974
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
CalendarAppointmentView.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/CalendarAppointmentView.java
package de.georgsieber.customerdb; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.os.Build; import android.util.AttributeSet; import android.widget.LinearLayout; import android.widget.TextView; import de.georgsieber.customerdb.tools.ColorControl; public class CalendarAppointmentView extends LinearLayout { public CalendarAppointmentView(Context context) { super(context); } public CalendarAppointmentView(Context context, AttributeSet attrs) { super(context, attrs); } public CalendarAppointmentView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void setValues(String text, String subtitle, String time, int backgroundColor) { TextView textViewTitle = findViewById(R.id.textViewAppointmentTitle); if(text.equals("")) textViewTitle.setVisibility(GONE); textViewTitle.setText(text); TextView textViewSubtitle = findViewById(R.id.textViewAppointmentSubtitle); if(subtitle.equals("")) textViewSubtitle.setVisibility(GONE); textViewSubtitle.setText(subtitle); TextView textViewTime = findViewById(R.id.textViewAppointmentTime); if(time.equals("")) textViewTime.setVisibility(GONE); textViewTime.setText(time); if(ColorControl.isColorDark(backgroundColor)) { int colorSecondary = Color.argb(180, 255, 255, 255); textViewTitle.setTextColor(Color.WHITE); textViewSubtitle.setTextColor(colorSecondary); textViewTime.setTextColor(colorSecondary); } else { int colorSecondary = Color.argb(180, 0, 0, 0); textViewTitle.setTextColor(Color.BLACK); textViewSubtitle.setTextColor(colorSecondary); textViewTime.setTextColor(colorSecondary); } if(ColorControl.isColorDark(backgroundColor)) { textViewTitle.setTextColor(Color.WHITE); } else { textViewTitle.setTextColor(Color.BLACK); } GradientDrawable border = new GradientDrawable(); border.setCornerRadius(12); border.setColor(backgroundColor); border.setAlpha(220); border.setStroke((int)getResources().getDimension(R.dimen.hour_divider_height), getResources().getColor(R.color.colorDivider)); if(Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { setBackgroundDrawable(border); } else { setBackground(border); } } }
2,584
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
FeatureCheck.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/FeatureCheck.java
package de.georgsieber.customerdb; import android.content.Context; import android.content.SharedPreferences; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.android.billingclient.api.AcknowledgePurchaseParams; import com.android.billingclient.api.AcknowledgePurchaseResponseListener; import com.android.billingclient.api.BillingClient; import com.android.billingclient.api.BillingClientStateListener; import com.android.billingclient.api.BillingResult; import com.android.billingclient.api.Purchase; import com.android.billingclient.api.PurchasesResponseListener; import com.android.billingclient.api.PurchasesUpdatedListener; import com.android.billingclient.api.QueryPurchasesParams; import java.util.List; class FeatureCheck { /* It is not allowed to modify this file in order to bypass license checks. I made this app open source hoping people will learn something from this project. But keep in mind: open source means free as "free speech" but not as in "free beer". Please be so kind and support further development by purchasing the in-app purchases in one of the app stores. It's up to you how long this app will be maintained. Thanks for your support. */ private BillingClient mBillingClient; private Context mContext; private SharedPreferences mSettings; FeatureCheck(Context c) { mContext = c; } private featureCheckReadyListener listener = null; public interface featureCheckReadyListener { void featureCheckReady(boolean fetchSuccess); } void setFeatureCheckReadyListener(featureCheckReadyListener listener) { this.listener = listener; } void init() { // get settings (faster than google play - after purchase done, billing client needs minutes to realize the purchase) mSettings = mContext.getSharedPreferences(MainActivity.PREFS_NAME, 0); unlockedCommercialUsage = mSettings.getBoolean("purchased-cu", false); unlockedAdFree = mSettings.getBoolean("purchased-ad", false); unlockedLargeCompany = mSettings.getBoolean("purchased-lc", false); unlockedLocalSync = mSettings.getBoolean("purchased-ls", false); unlockedInputOnlyMode = mSettings.getBoolean("purchased-iom", false); unlockedDesignOptions = mSettings.getBoolean("purchased-do", false); unlockedCustomFields = mSettings.getBoolean("purchased-cf", false); unlockedScript = mSettings.getBoolean("purchased-sc", false); unlockedFiles = mSettings.getBoolean("purchased-fs", false); unlockedCalendar = mSettings.getBoolean("purchased-cl", false); // init billing client - get purchases later for other devices mBillingClient = BillingClient.newBuilder(mContext) .enablePendingPurchases() .setListener(new PurchasesUpdatedListener() { @Override public void onPurchasesUpdated(@NonNull BillingResult billingResult, @Nullable List<Purchase> list) { } }).build(); mBillingClient.startConnection(new BillingClientStateListener() { @Override public void onBillingSetupFinished(@NonNull BillingResult billingResult) { if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) { // query purchases mBillingClient.queryPurchasesAsync( QueryPurchasesParams.newBuilder().setProductType(BillingClient.ProductType.INAPP).build(), new PurchasesResponseListener() { @Override public void onQueryPurchasesResponse(@NonNull BillingResult billingResult, @NonNull List<Purchase> list) { processPurchases(billingResult.getResponseCode(), list); } } ); mBillingClient.queryPurchasesAsync( QueryPurchasesParams.newBuilder().setProductType(BillingClient.ProductType.SUBS).build(), new PurchasesResponseListener() { @Override public void onQueryPurchasesResponse(@NonNull BillingResult billingResult, @NonNull List<Purchase> list) { processSubscription(billingResult.getResponseCode(), list); } } ); isReady = true; } else { isReady = true; if(listener != null) listener.featureCheckReady(false); } } @Override public void onBillingServiceDisconnected() { } }); } private Boolean processPurchasesResult = null; private Boolean processSubscriptionsResult = null; static void acknowledgePurchase(BillingClient client, Purchase purchase) { if(!purchase.isAcknowledged()) { AcknowledgePurchaseParams acknowledgePurchaseParams = AcknowledgePurchaseParams.newBuilder() .setPurchaseToken(purchase.getPurchaseToken()) .build(); client.acknowledgePurchase(acknowledgePurchaseParams, new AcknowledgePurchaseResponseListener() { @Override public void onAcknowledgePurchaseResponse(@NonNull BillingResult billingResult) { } }); } } private void processPurchases(int responseCode, List<Purchase> purchasesList) { if(responseCode == BillingClient.BillingResponseCode.OK) { for(Purchase p : purchasesList) { if(p.getPurchaseState() == Purchase.PurchaseState.PURCHASED) { for(String sku : p.getProducts()) { unlockPurchase(sku, p); } acknowledgePurchase(mBillingClient, p); } } processPurchasesResult = true; } else { processPurchasesResult = false; } finish(); } private void processSubscription(int responseCode, List<Purchase> purchasesList) { if(responseCode == BillingClient.BillingResponseCode.OK) { for(Purchase p : purchasesList) { if(p.getPurchaseState() == Purchase.PurchaseState.PURCHASED) { for(String sku : p.getProducts()) { if(p.isAutoRenewing()) { unlockPurchase(sku, p); } } acknowledgePurchase(mBillingClient, p); } } processSubscriptionsResult = true; } else { processSubscriptionsResult = false; } finish(); } private void finish() { if(processPurchasesResult != null && processSubscriptionsResult != null) { if(listener != null) { if(processPurchasesResult && processSubscriptionsResult) { listener.featureCheckReady(true); } else { listener.featureCheckReady(false); } } } } boolean isReady = false; boolean unlockedCommercialUsage = false; boolean unlockedLargeCompany = false; boolean unlockedInputOnlyMode = false; boolean unlockedDesignOptions = false; boolean unlockedCustomFields = false; boolean unlockedFiles = false; boolean unlockedCalendar = false; boolean activeSync = false; // deprecated private boolean unlockedAdFree = false; private boolean unlockedLocalSync = false; private boolean unlockedScript = false; private void unlockPurchase(String sku, Purchase purchase) { switch(sku) { case "cu": unlockedCommercialUsage = true; break; case "ad": unlockedAdFree = true; break; case "lc": unlockedLargeCompany = true; break; case "ls": unlockedLocalSync = true; break; case "iom": unlockedInputOnlyMode = true; break; case "do": unlockedDesignOptions = true; break; case "cf": unlockedCustomFields = true; break; case "sc": unlockedScript = true; break; case "fs": unlockedFiles = true; break; case "cl": unlockedCalendar = true; break; case "sync": activeSync = true; if(purchase != null) { // store the sync subscription token in order to send it to the Customer Database Cloud API for access validation SharedPreferences.Editor editor = mSettings.edit(); editor.putString("sync-purchase-token", purchase.getPurchaseToken()); editor.apply(); } break; } } }
9,332
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
AboutActivity.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/AboutActivity.java
package de.georgsieber.customerdb; import android.annotation.SuppressLint; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.android.billingclient.api.BillingResult; import com.android.billingclient.api.ProductDetails; import com.android.billingclient.api.ProductDetailsResponseListener; import com.android.billingclient.api.QueryProductDetailsParams; import com.google.android.material.snackbar.Snackbar; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.os.SystemClock; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import com.android.billingclient.api.BillingClient; import com.android.billingclient.api.BillingClientStateListener; import com.android.billingclient.api.BillingFlowParams; import com.android.billingclient.api.Purchase; import com.android.billingclient.api.PurchasesUpdatedListener; import org.json.JSONObject; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Objects; import de.georgsieber.customerdb.tools.ColorControl; import de.georgsieber.customerdb.tools.CommonDialog; import de.georgsieber.customerdb.tools.HttpRequest; public class AboutActivity extends AppCompatActivity { public static abstract class DoubleClickListener implements View.OnClickListener { // The time in which the second tap should be done in order to qualify as // a double click private static final long DEFAULT_QUALIFICATION_SPAN = 200; private long doubleClickQualificationSpanInMillis; private long timestampLastClick; public DoubleClickListener() { doubleClickQualificationSpanInMillis = DEFAULT_QUALIFICATION_SPAN; timestampLastClick = 0; } public DoubleClickListener(long doubleClickQualificationSpanInMillis) { this.doubleClickQualificationSpanInMillis = doubleClickQualificationSpanInMillis; timestampLastClick = 0; } @Override public void onClick(View v) { if((SystemClock.elapsedRealtime() - timestampLastClick) < doubleClickQualificationSpanInMillis) { onDoubleClick(); } timestampLastClick = SystemClock.elapsedRealtime(); } public abstract void onDoubleClick(); } AboutActivity me = this; private BillingClient mBillingClient; SharedPreferences mSettings; @SuppressLint("SetTextI18n") @Override protected void onCreate(Bundle savedInstanceState) { // init settings mSettings = getSharedPreferences(MainActivity.PREFS_NAME, 0); // init activity view super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); findViewById(R.id.imageVendorLogo).setOnClickListener(new DoubleClickListener() { @Override public void onDoubleClick() { openUnlockSelection(); } }); // init toolbar Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); if(getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); // init colors ColorControl.updateActionBarColor(this, mSettings); // get version String versionString = "v?"; try { PackageInfo pInfo = this.getPackageManager().getPackageInfo(getPackageName(), 0); versionString = String.format(getResources().getString(R.string.version), pInfo.versionName); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } // set info label text ((TextView) findViewById(R.id.textViewVersion)).setText( versionString ); // do feature check final FeatureCheck fc = new FeatureCheck(this); fc.setFeatureCheckReadyListener(new FeatureCheck.featureCheckReadyListener() { @Override public void featureCheckReady(boolean fetchSuccess) { runOnUiThread(new Runnable(){ @Override public void run() { if(fc.unlockedCommercialUsage) unlockPurchase("cu", null); if(fc.unlockedLargeCompany) unlockPurchase("lc", null); if(fc.unlockedInputOnlyMode) unlockPurchase("iom", null); if(fc.unlockedDesignOptions) unlockPurchase("do", null); if(fc.unlockedCustomFields) unlockPurchase("cf", null); if(fc.unlockedFiles) unlockPurchase("fs", null); if(fc.unlockedCalendar) unlockPurchase("cl", null); if(fc.activeSync) unlockPurchase("sync", null); } }); } }); fc.init(); // show licensee String licensee = mSettings.getString("licensee", ""); if(licensee != null && !licensee.equals("")) { findViewById(R.id.spaceLicensee).setVisibility(View.VISIBLE); findViewById(R.id.textViewLicensee).setVisibility(View.VISIBLE); ((TextView) findViewById(R.id.textViewLicensee)).setText(licensee); } // init billing client mBillingClient = BillingClient.newBuilder(this) .enablePendingPurchases() .setListener(new PurchasesUpdatedListener() { @Override public void onPurchasesUpdated(@NonNull BillingResult billingResult, @Nullable List<Purchase> purchases) { int responseCode = billingResult.getResponseCode(); if(responseCode == BillingClient.BillingResponseCode.OK && purchases != null) { for(final Purchase purchase : purchases) { if(purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED) { for(final String sku : purchase.getProducts()) { runOnUiThread(new Runnable(){ @Override public void run() { unlockPurchase(sku, purchase); } }); } FeatureCheck.acknowledgePurchase(mBillingClient, purchase); } } } else if(responseCode == BillingClient.BillingResponseCode.USER_CANCELED) { CommonDialog.show(me, getResources().getString(R.string.purchase_canceled), getResources().getString(R.string.purchase_canceled_description), CommonDialog.TYPE.WARN, false ); } else if(responseCode != BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED) { try { CommonDialog.show(me, getResources().getString(R.string.purchase_failed), getResources().getString(R.string.check_internet_conn), CommonDialog.TYPE.FAIL, false ); } catch(Exception e) { e.printStackTrace(); } } } }).build(); mBillingClient.startConnection(new BillingClientStateListener() { @Override public void onBillingSetupFinished(@NonNull BillingResult billingResult) { if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) { querySkus(); } else { Snackbar.make( findViewById(R.id.aboutMainView), getResources().getString(R.string.store_not_avail) + " - " + getResources().getString(R.string.could_not_fetch_prices), Snackbar.LENGTH_LONG) .show(); } } @Override public void onBillingServiceDisconnected() { CommonDialog.show(me, getResources().getString(R.string.store_not_avail), getResources().getString(R.string.check_internet_conn), CommonDialog.TYPE.WARN, true ); } }); } @Override protected void onDestroy() { super.onDestroy(); mBillingClient.endConnection(); } private void unlockPurchase(String sku, Purchase purchase) { SharedPreferences.Editor editor = mSettings.edit(); switch(sku) { case "cu": ((ImageView) findViewById(R.id.imageViewBuyCommercialUse)).setImageResource(R.drawable.ic_tick_green_24dp); editor.putBoolean("purchased-cu", true); editor.apply(); break; case "lc": ((ImageView) findViewById(R.id.imageViewBuyLargeCompany)).setImageResource(R.drawable.ic_tick_green_24dp); editor.putBoolean("purchased-lc", true); editor.apply(); break; case "iom": ((ImageView) findViewById(R.id.imageViewBuyInputOnlyMode)).setImageResource(R.drawable.ic_tick_green_24dp); editor.putBoolean("purchased-iom", true); editor.apply(); break; case "do": ((ImageView) findViewById(R.id.imageViewBuyDesignOptions)).setImageResource(R.drawable.ic_tick_green_24dp); editor.putBoolean("purchased-do", true); editor.apply(); break; case "cf": ((ImageView) findViewById(R.id.imageViewBuyCustomFields)).setImageResource(R.drawable.ic_tick_green_24dp); editor.putBoolean("purchased-cf", true); editor.apply(); break; case "fs": ((ImageView) findViewById(R.id.imageViewBuyFiles)).setImageResource(R.drawable.ic_tick_green_24dp); editor.putBoolean("purchased-fs", true); editor.apply(); break; case "cl": ((ImageView) findViewById(R.id.imageViewBuyCalendar)).setImageResource(R.drawable.ic_tick_green_24dp); editor.putBoolean("purchased-cl", true); editor.apply(); break; case "sync": ((ImageView) findViewById(R.id.imageViewBuySync)).setImageResource(R.drawable.ic_tick_green_24dp); if(purchase != null) { // store the sync subscription token in order to send it to the Customer Database Cloud API for access validation editor.putString("sync-purchase-token", purchase.getPurchaseToken()); editor.apply(); } break; } } @SuppressLint("SetTextI18n") private void querySkus() { ArrayList<QueryProductDetailsParams.Product> productList = new ArrayList<>(); productList.add(QueryProductDetailsParams.Product.newBuilder() .setProductId("cu").setProductType(BillingClient.ProductType.INAPP).build()); productList.add(QueryProductDetailsParams.Product.newBuilder() .setProductId("lc").setProductType(BillingClient.ProductType.INAPP).build()); productList.add(QueryProductDetailsParams.Product.newBuilder() .setProductId("iom").setProductType(BillingClient.ProductType.INAPP).build()); productList.add(QueryProductDetailsParams.Product.newBuilder() .setProductId("do").setProductType(BillingClient.ProductType.INAPP).build()); productList.add(QueryProductDetailsParams.Product.newBuilder() .setProductId("cf").setProductType(BillingClient.ProductType.INAPP).build()); productList.add(QueryProductDetailsParams.Product.newBuilder() .setProductId("fs").setProductType(BillingClient.ProductType.INAPP).build()); productList.add(QueryProductDetailsParams.Product.newBuilder() .setProductId("cl").setProductType(BillingClient.ProductType.INAPP).build()); QueryProductDetailsParams params = QueryProductDetailsParams.newBuilder() .setProductList(productList) .build(); mBillingClient.queryProductDetailsAsync(params, new ProductDetailsResponseListener() { @Override public void onProductDetailsResponse(@NonNull BillingResult billingResult, @NonNull List<ProductDetails> productDetailsList) { if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) { for(final ProductDetails skuDetails : productDetailsList) { final String sku = skuDetails.getProductId(); final String price = Objects.requireNonNull(skuDetails.getOneTimePurchaseOfferDetails()).getFormattedPrice(); runOnUiThread(new Runnable(){ @Override public void run() { setupPayButton(sku, price, skuDetails); } }); } } else { CommonDialog.show(me, getResources().getString(R.string.store_not_avail), getResources().getString(R.string.could_not_fetch_prices), CommonDialog.TYPE.WARN, false ); } } }); ArrayList<QueryProductDetailsParams.Product> productList2 = new ArrayList<>(); productList2.add(QueryProductDetailsParams.Product.newBuilder() .setProductId("sync").setProductType(BillingClient.ProductType.SUBS).build()); QueryProductDetailsParams params2 = QueryProductDetailsParams.newBuilder() .setProductList(productList2) .build(); mBillingClient.queryProductDetailsAsync(params2, new ProductDetailsResponseListener() { @Override public void onProductDetailsResponse(@NonNull BillingResult billingResult, @NonNull List<ProductDetails> productDetailsList) { if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) { for(final ProductDetails skuDetails : productDetailsList) { final String sku = skuDetails.getProductId(); Log.e("PURCHASE", sku); final List<ProductDetails.SubscriptionOfferDetails> offers = Objects.requireNonNull(skuDetails.getSubscriptionOfferDetails()); if(offers.isEmpty()) continue; mSkuDetailsSyncOfferToken = offers.get(0).getOfferToken(); final List<ProductDetails.PricingPhase> pricingPhaseList = offers.get(0).getPricingPhases().getPricingPhaseList(); if(pricingPhaseList.isEmpty()) continue; final String price = pricingPhaseList.get(0).getFormattedPrice(); Log.e("PURCHASE", price); runOnUiThread(new Runnable(){ @Override public void run() { setupPayButton(sku, price, skuDetails); } }); } } } }); } @SuppressLint("SetTextI18n") private void setupPayButton(String sku, String price, ProductDetails skuDetails) { switch(sku) { case "cu": mSkuDetailsCommercialUse = skuDetails; ((Button) findViewById(R.id.buttonBuyCommercialUse)).setText(price+"\n"+getResources().getString(R.string.buy_now)); ((Button) findViewById(R.id.buttonBuyCommercialUse)).setEnabled(true); break; case "lc": mSkuDetailsLargeCompany = skuDetails; ((Button) findViewById(R.id.buttonBuyLargeCompany)).setText(price+"\n"+getResources().getString(R.string.buy_now)); ((Button) findViewById(R.id.buttonBuyLargeCompany)).setEnabled(true); break; case "iom": mSkuDetailsInputOnlyMode = skuDetails; ((Button) findViewById(R.id.buttonBuyInputOnlyMode)).setText(price+"\n"+getResources().getString(R.string.buy_now)); ((Button) findViewById(R.id.buttonBuyInputOnlyMode)).setEnabled(true); break; case "do": getmSkuDetailsDesignOptions = skuDetails; ((Button) findViewById(R.id.buttonBuyDesignOptions)).setText(price+"\n"+getResources().getString(R.string.buy_now)); ((Button) findViewById(R.id.buttonBuyDesignOptions)).setEnabled(true); break; case "cf": mSkuDetailsCustomFields = skuDetails; ((Button) findViewById(R.id.buttonBuyCustomFields)).setText(price+"\n"+getResources().getString(R.string.buy_now)); ((Button) findViewById(R.id.buttonBuyCustomFields)).setEnabled(true); break; case "fs": mSkuDetailsFiles = skuDetails; ((Button) findViewById(R.id.buttonBuyFiles)).setText(price+"\n"+getResources().getString(R.string.buy_now)); ((Button) findViewById(R.id.buttonBuyFiles)).setEnabled(true); break; case "cl": mSkuDetailsCalendar = skuDetails; ((Button) findViewById(R.id.buttonBuyCalendar)).setText(price+"\n"+getResources().getString(R.string.buy_now)); ((Button) findViewById(R.id.buttonBuyCalendar)).setEnabled(true); break; case "sync": mSkuDetailsSync = skuDetails; ((Button) findViewById(R.id.buttonSubCloud)).setText(price+"\n"+getResources().getString(R.string.buy_now)); ((Button) findViewById(R.id.buttonSubCloud)).setEnabled(true); break; } } @SuppressWarnings("UnusedReturnValue") private BillingResult doBuy(ProductDetails sku, String offerToken) { if(sku == null) return null; BillingFlowParams.ProductDetailsParams.Builder builder = BillingFlowParams.ProductDetailsParams.newBuilder().setProductDetails(sku); if(offerToken != null) builder.setOfferToken(offerToken); List<BillingFlowParams.ProductDetailsParams> productDetailsParamsList = new ArrayList<>(); productDetailsParamsList.add(builder.build()); BillingFlowParams flowParams = BillingFlowParams.newBuilder() .setProductDetailsParamsList(productDetailsParamsList) .build(); return mBillingClient.launchBillingFlow(this, flowParams); } ProductDetails mSkuDetailsSync; String mSkuDetailsSyncOfferToken; ProductDetails mSkuDetailsCommercialUse; ProductDetails mSkuDetailsLargeCompany; ProductDetails mSkuDetailsInputOnlyMode; ProductDetails getmSkuDetailsDesignOptions; ProductDetails mSkuDetailsCustomFields; ProductDetails mSkuDetailsFiles; ProductDetails mSkuDetailsCalendar; public void doSubCloud(View v) { doBuy(mSkuDetailsSync, mSkuDetailsSyncOfferToken); } public void doBuyCommercialUse(View v) { doBuy(mSkuDetailsCommercialUse, null); } public void doBuyLargeCompany(View v) { doBuy(mSkuDetailsLargeCompany, null); } public void doBuyInputOnlyMode(View v) { doBuy(mSkuDetailsInputOnlyMode, null); } public void doBuyDesignOptions(View v) { doBuy(getmSkuDetailsDesignOptions, null); } public void doBuyCustomFields(View v) { doBuy(mSkuDetailsCustomFields, null); } public void doBuyFiles(View v) { doBuy(mSkuDetailsFiles, null); } public void doBuyCalendar(View v) { doBuy(mSkuDetailsCalendar, null); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_about, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { //noinspection SwitchStatementWithTooFewBranches switch(item.getItemId()) { case android.R.id.home: finish(); return true; case R.id.action_settings_help: Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().getString(R.string.help_website))); startActivity(browserIntent); return true; default: return super.onOptionsItemSelected(item); } } public void openUnlockSelection() { // collect all available inapp purchases final String[][] inappPurchases = new String[][] { new String[] {getString(R.string.calendar), "systems.sieber.customerdb.cl", "cl"}, new String[] {getString(R.string.commercial_use), "systems.sieber.customerdb.cu", "cu"}, new String[] {getString(R.string.custom_fields), "systems.sieber.customerdb.cf", "cf"}, new String[] {getString(R.string.design_options), "systems.sieber.customerdb.do", "do"}, new String[] {getString(R.string.files), "systems.sieber.customerdb.fs", "fs"}, new String[] {getString(R.string.input_only_mode_inapp_title), "systems.sieber.customerdb.iom", "iom"}, new String[] {getString(R.string.more_than_500_customers), "systems.sieber.customerdb.lc", "lc"} }; // generate name array for dialog ArrayList<String> names = new ArrayList<>(); for(String[] s : inappPurchases) { names.add(s[0]); } // show selection dialog AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getString(R.string.unlock)); builder.setItems(names.toArray(new String[0]), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { openUnlockInputBox(inappPurchases[which][1], inappPurchases[which][2]); } }); builder.show(); } private void openUnlockInputBox(final String requestFeature, final String sku) { final Dialog ad = new Dialog(this); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_input_box); ((TextView) ad.findViewById(R.id.textViewInputBox)).setText(R.string.unlock_code); ad.findViewById(R.id.buttonInputBoxOK).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); String text = ((EditText) ad.findViewById(R.id.editTextInputBox)).getText().toString().trim(); HttpRequest hr = new HttpRequest(getResources().getString(R.string.unlock_api), null); ArrayList<HttpRequest.KeyValueItem> headers = new ArrayList<>(); headers.add(new HttpRequest.KeyValueItem("X-Unlock-Feature",requestFeature)); headers.add(new HttpRequest.KeyValueItem("X-Unlock-Code",text)); hr.setRequestHeaders(headers); hr.setReadyListener(new HttpRequest.readyListener() { @Override public void ready(int statusCode, String responseBody) { try { if(statusCode != 999) { throw new Exception("Invalid status code: " + statusCode); } JSONObject licenseInfo = new JSONObject(responseBody); String licensee = licenseInfo.getString("licensee"); String remaining = licenseInfo.getString("remaining"); final SharedPreferences.Editor editor = mSettings.edit(); editor.putString("licensee", licensee); editor.apply(); unlockPurchase(sku, null); CommonDialog.show(me, getResources().getString(R.string.success), licensee + "\n\n" + String.format(getString(R.string.activations_remaining), remaining), CommonDialog.TYPE.OK, false ); } catch(Exception e) { Log.e("ACTIVATION", e.getMessage() + " - " + responseBody); if(me == null || me.isFinishing()) return; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { if(me.isDestroyed()) return; } CommonDialog.show(me, getResources().getString(R.string.error), getResources().getString(R.string.activation_failed_description), CommonDialog.TYPE.FAIL, false); } } }); hr.execute(); } }); if(ad.getWindow() != null) ad.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); ad.show(); } public void onClickApacheLicenseLink(View v) { try { InputStream in_s = getResources().openRawResource(R.raw.apache_license); byte[] b = new byte[in_s.available()]; in_s.read(b); Intent licenseViewIntent = new Intent(this, TextViewActivity.class); licenseViewIntent.putExtra("content", new String(b)); startActivity(licenseViewIntent); } catch(Exception e) { e.printStackTrace(); } } public void onClickMoreInfoBackup(View v) { Intent licenseViewIntent = new Intent(this, TextViewActivity.class); licenseViewIntent.putExtra("title", getString(R.string.backup)); licenseViewIntent.putExtra("content", getString(R.string.backup_info)); startActivity(licenseViewIntent); } public void onClickMoreInfoInputOnlyMode(View v) { Intent licenseViewIntent = new Intent(this, TextViewActivity.class); licenseViewIntent.putExtra("title", getString(R.string.input_only_mode)); licenseViewIntent.putExtra("content", getString(R.string.input_only_mode_instructions)); startActivity(licenseViewIntent); } public void onClickMoreInfoCardDavApi(View v) { Intent licenseViewIntent = new Intent(this, TextViewActivity.class); licenseViewIntent.putExtra("title", getString(R.string.carddav_api)); licenseViewIntent.putExtra("content", getString(R.string.carddav_api_info)); startActivity(licenseViewIntent); } public void onClickMoreInfoEula(View v) { Intent licenseViewIntent = new Intent(this, TextViewActivity.class); licenseViewIntent.putExtra("title", getString(R.string.eula_title)); licenseViewIntent.putExtra("content", getString(R.string.eula)); startActivity(licenseViewIntent); } public void onClickEmailLink(View v) { DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch(which) { case DialogInterface.BUTTON_POSITIVE: final Intent emailIntent = new Intent(Intent.ACTION_VIEW); Uri data = Uri.parse("mailto:" + getResources().getString(R.string.developer_email) + "?subject=" + getResources().getString(R.string.feedbacktitle) + "&body=" + ""); emailIntent.setData(data); startActivity(Intent.createChooser(emailIntent, getResources().getString(R.string.sendfeedback))); break; case DialogInterface.BUTTON_NEGATIVE: break; } } }; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(getString(R.string.support_only_english_german)) .setPositiveButton(getString(R.string.cont), dialogClickListener) .setNegativeButton(getString(R.string.cancel), dialogClickListener) .show(); } public void onClickWebLink(View v) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().getString(R.string.developer_website))); startActivity(browserIntent); } public void onClickGithub(View v) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().getString(R.string.repo_link))); startActivity(browserIntent); } public void onClickCustomerDatabaseIosApp(View v) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://apps.apple.com/us/app/customer-database/id1496659447")); startActivity(browserIntent); } public void onClickRemotePointerAndroidApp(View v) { MainActivity.openPlayStore(this, "systems.sieber.remotespotlight"); } public void onClickFsClockAndroidApp(View v) { MainActivity.openPlayStore(this, "systems.sieber.fsclock"); } public void onClickBallBreakAndroidApp(View v) { MainActivity.openPlayStore(this, "de.georgsieber.ballbreak"); } public void onClickOco(View v) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/schorschii/oco-server")); startActivity(browserIntent); } public void onClickMasterplan(View v) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/schorschii/masterplan")); startActivity(browserIntent); } }
31,220
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
CustomerAdapter.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/CustomerAdapter.java
package de.georgsieber.customerdb; import android.content.Context; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import de.georgsieber.customerdb.model.Customer; class CustomerAdapter extends BaseAdapter { private Context mContext; private List<Customer> mCustomers; private LayoutInflater mInflater; private boolean mShowCheckbox = false; CustomerAdapter(Context context, List<Customer> customers) { mContext = context; mCustomers = customers; mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } CustomerAdapter(Context context, List<Customer> customers, checkedChangedListener listener) { mContext = context; mCustomers = customers; mListener = listener; mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return mCustomers.size(); } @Override public Object getItem(int position) { return mCustomers.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { Customer c = mCustomers.get(position); if(convertView == null) { convertView = mInflater.inflate(R.layout.item_list_customer, null); } TextView tv1 = (convertView.findViewById(R.id.textViewCustomerListItem1)); TextView tv2 = (convertView.findViewById(R.id.textViewCustomerListItem2)); tv1.setText(c.getFirstLine()); if(c.getSecondLine().trim().equals("")) { tv2.setText(mContext.getString(R.string.no_details)); } else { tv2.setText(c.getSecondLine()); } CheckBox currentListItemCheckBox = convertView.findViewById(R.id.checkBoxCustomerListItem); if(mShowCheckbox) { currentListItemCheckBox.setTag(position); currentListItemCheckBox.setChecked(mSparseBooleanArray.get(position)); currentListItemCheckBox.setOnCheckedChangeListener(mCheckedChangeListener); currentListItemCheckBox.setVisibility(View.VISIBLE); } else { currentListItemCheckBox.setVisibility(View.GONE); } return convertView; } boolean getShowCheckbox() { return mShowCheckbox; } void setShowCheckbox(boolean visible) { mShowCheckbox = visible; notifyDataSetChanged(); } private SparseBooleanArray mSparseBooleanArray = new SparseBooleanArray(); private CompoundButton.OnCheckedChangeListener mCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked); if(mListener != null) mListener.checkedChanged(getCheckedItems()); } }; void setAllChecked(boolean checked) { for(int i=0; i<mCustomers.size(); i++) { mSparseBooleanArray.put(i, checked); } if(mListener != null) mListener.checkedChanged(getCheckedItems()); } ArrayList<Customer> getCheckedItems() { ArrayList<Customer> mTempArray = new ArrayList<Customer>(); for(int i=0;i<mCustomers.size();i++) { if(mSparseBooleanArray.get(i)) { mTempArray.add(mCustomers.get(i)); } } return mTempArray; } private checkedChangedListener mListener = null; public interface checkedChangedListener { void checkedChanged(ArrayList<Customer> checked); } void setCheckedChangedListener(checkedChangedListener listener) { this.mListener = listener; } }
4,108
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
PhoneStateReceiver2.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/PhoneStateReceiver2.java
package de.georgsieber.customerdb; import android.annotation.SuppressLint; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Handler; import android.util.Log; import android.widget.Toast; import java.text.SimpleDateFormat; import java.util.Date; import de.georgsieber.customerdb.model.Customer; public class PhoneStateReceiver2 extends BroadcastReceiver { @Override public void onReceive(final Context context, Intent intent) { // local database init CustomerDatabase localDBConn = new CustomerDatabase(context); if(intent.getExtras() != null) { String incomingNumber = intent.getExtras().getString("number"); final Customer callingCustomer = localDBConn.getCustomerByNumber(incomingNumber); if(callingCustomer != null) { Log.d("cutomerdbphonedbg", "SHOW_INFO__FOUND"); new Handler().postDelayed(new Runnable() { @Override public void run() { showCallInfo(context, callingCustomer); } }, 500); new Handler().postDelayed(new Runnable() { @Override public void run() { showCallInfo(context, callingCustomer); } }, 3500); new Handler().postDelayed(new Runnable() { @Override public void run() { showCallInfo(context, callingCustomer); } }, 7000); saveLastCallInfo(context, incomingNumber, callingCustomer.getFullName(false)); } else { Log.d("cutomerdbphonedbg", "SHOW_INFO__NOT_FOUND"); saveLastCallInfo(context, incomingNumber, null); } } } private void showCallInfo(Context context, Customer callingCustomer) { Toast.makeText(context, context.getResources().getString(R.string.app_name) + ":\n" + callingCustomer.getFullName(false) + " " + context.getResources().getString(R.string.calling), Toast.LENGTH_LONG) .show(); } protected void saveLastCallInfo(Context c, String number, String customer) { @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); String callInfo = sdf.format(new Date()) +" "+ number +" ("+ (customer == null ? c.getResources().getString(R.string.no_customer_found) : customer) +")"; SharedPreferences settings = c.getSharedPreferences(MainActivity.PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putString("last-call-received", callInfo); editor.apply(); } }
2,931
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
VoucherEditActivity.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/VoucherEditActivity.java
package de.georgsieber.customerdb; import android.annotation.SuppressLint; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import java.text.DateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import de.georgsieber.customerdb.model.Customer; import de.georgsieber.customerdb.model.Voucher; import de.georgsieber.customerdb.tools.ColorControl; import de.georgsieber.customerdb.tools.CommonDialog; import de.georgsieber.customerdb.tools.NumTools; public class VoucherEditActivity extends AppCompatActivity { private VoucherEditActivity me; private long mCurrentVoucherId = -1; private Voucher mCurrentVoucher; private SharedPreferences mSettings; private CustomerDatabase mDb; private DateFormat mDateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault()); private Calendar mValidUntilCalendar; ImageButton mButtonShowFromCustomer; ImageButton mButtonShowForCustomer; EditText mEditTextValue; EditText mEditTextVoucherNo; Button mButtonValidUntil; EditText mEditTextFromCustomer; EditText mEditTextForCustomer; EditText mEditTextNotes; @Override protected void onCreate(Bundle savedInstanceState) { // init settings mSettings = getSharedPreferences(MainActivity.PREFS_NAME, 0); // init database mDb = new CustomerDatabase(this); // init activity view super.onCreate(savedInstanceState); me = this; setContentView(R.layout.activity_voucher_edit); // init toolbar Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); if(getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); // init colors ColorControl.updateActionBarColor(this, mSettings); // set currency label ((TextView) findViewById(R.id.textViewCurrency)).setText(mSettings.getString("currency", "€")); // find views mButtonShowFromCustomer = findViewById(R.id.buttonShowFromCustomer); mButtonShowFromCustomer.setEnabled(false); mButtonShowForCustomer = findViewById(R.id.buttonShowForCustomer); mButtonShowForCustomer.setEnabled(false); mEditTextValue = findViewById(R.id.editTextValue); mEditTextVoucherNo = findViewById(R.id.editTextVoucherNo); mButtonValidUntil = findViewById(R.id.buttonValidUntil); mEditTextFromCustomer = findViewById(R.id.editTextFromCustomer); mEditTextForCustomer = findViewById(R.id.editTextForCustomer); mEditTextNotes = findViewById(R.id.editTextNotes); // get extra from parent intent Intent intent = getIntent(); mCurrentVoucherId = intent.getLongExtra("voucher-id", -1); mCurrentVoucher = mDb.getVoucherById(mCurrentVoucherId); if(mCurrentVoucher != null) { fillFields(mCurrentVoucher); getSupportActionBar().setTitle(getResources().getString(R.string.edit_voucher)); } else { mCurrentVoucher = new Voucher(); getSupportActionBar().setTitle(getResources().getString(R.string.new_voucher)); // show sync hint if(mSettings.getInt("webapi-type", 0) > 0) { findViewById(R.id.linearLayoutSyncInfo).setVisibility(View.VISIBLE); } } getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_voucher_edit, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case android.R.id.home: finish(); return true; case R.id.action_edit_done: saveAndExit(); return true; default: return super.onOptionsItemSelected(item); } } @SuppressLint("SetTextI18n") public void insertVoucherNumber(View v) { int newVoucherNo = mSettings.getInt("voucher-no", 0)+1; while(existsVoucherNo(Integer.toString(newVoucherNo))) { newVoucherNo ++; } mEditTextVoucherNo.setText(Integer.toString(newVoucherNo)); } private boolean existsVoucherNo(String voucherNo) { CustomerDatabase db = new CustomerDatabase(this); for(Voucher v : db.getVouchers(null, true, null)) { if(v.mVoucherNo.equals(voucherNo)) { return true; } } return false; } private void saveAndExit() { if(updateVoucherObjectByInputs()) { Integer currentVoucherNo = NumTools.tryParseInt(mEditTextVoucherNo.getText().toString()); if(currentVoucherNo != null) { SharedPreferences.Editor editor = mSettings.edit(); editor.putInt("voucher-no", currentVoucherNo); editor.apply(); } if(mCurrentVoucher.mId == -1) { // insert new voucher mDb.addVoucher(mCurrentVoucher); } else { // update in database mCurrentVoucher.mLastModified = new Date(); mDb.updateVoucher(mCurrentVoucher); } MainActivity.setUnsyncedChanges(this); setResult(RESULT_OK); finish(); } else { CommonDialog.show(this, getResources().getString(R.string.invalid_number), getResources().getString(R.string.invalid_number_text), CommonDialog.TYPE.FAIL, false); } } private void fillFields(Voucher v) { mEditTextValue.setText(v.getCurrentValueString()); mEditTextVoucherNo.setText(v.mVoucherNo); mEditTextVoucherNo.setEnabled(false); findViewById(R.id.buttonInsertVoucherNumber).setVisibility(View.GONE); mEditTextNotes.setText(v.mNotes); if(v.mFromCustomerId != null) { Customer relatedCustomer = mDb.getCustomerById(v.mFromCustomerId, false, false); if(relatedCustomer != null) { mEditTextFromCustomer.setText(relatedCustomer.getFullName(false)); mButtonShowFromCustomer.setEnabled(true); } else { mEditTextFromCustomer.setText(getString(R.string.removed_placeholder)); } } else { mEditTextFromCustomer.setText(v.mFromCustomer); } if(v.mForCustomerId != null) { Customer relatedCustomer = mDb.getCustomerById(v.mForCustomerId, false, false); if(relatedCustomer != null) { mEditTextForCustomer.setText(relatedCustomer.getFullName(false)); mButtonShowForCustomer.setEnabled(true); } else { mEditTextForCustomer.setText(getString(R.string.removed_placeholder)); } } else { mEditTextForCustomer.setText(v.mFromCustomer); } if(v.mValidUntil == null) { mValidUntilCalendar = null; } else { mValidUntilCalendar = Calendar.getInstance(); } if(mValidUntilCalendar == null) { mButtonValidUntil.setText(getString(R.string.no_date_set)); } else { mValidUntilCalendar.setTime(v.mValidUntil); mButtonValidUntil.setText(mDateFormat.format(mValidUntilCalendar.getTime())); } } private boolean updateVoucherObjectByInputs() { String newValueString = mEditTextValue.getText().toString(); Double newValueDouble = NumTools.tryParseDouble(newValueString); if(newValueDouble == null) return false; mCurrentVoucher.mCurrentValue = newValueDouble; if(mCurrentVoucher.mId == -1) { mCurrentVoucher.mOriginalValue = mCurrentVoucher.mCurrentValue; } mCurrentVoucher.mVoucherNo = mEditTextVoucherNo.getText().toString(); mCurrentVoucher.mNotes = mEditTextNotes.getText().toString(); mCurrentVoucher.mValidUntil = mValidUntilCalendar == null ? null : mValidUntilCalendar.getTime(); mCurrentVoucher.mLastModified = new Date(); return true; } public void setValidUntil(View v) { if(mValidUntilCalendar == null) { mValidUntilCalendar = Calendar.getInstance(); } final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { mValidUntilCalendar.set(Calendar.YEAR, year); mValidUntilCalendar.set(Calendar.MONTH, monthOfYear); mValidUntilCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); mButtonValidUntil.setText(mDateFormat.format(mValidUntilCalendar.getTime())); } }; new DatePickerDialog( VoucherEditActivity.this, date, mValidUntilCalendar.get(Calendar.YEAR), mValidUntilCalendar.get(Calendar.MONTH), mValidUntilCalendar.get(Calendar.DAY_OF_MONTH) ).show(); } public void removeValidUntil(View v) { mValidUntilCalendar = null; mButtonValidUntil.setText(getString(R.string.no_date_set)); } public void onClickShowFromCustomer(View v) { if(mCurrentVoucher.mFromCustomerId != null) { showCustomerDetails(mCurrentVoucher.mFromCustomerId); } } public void onClickAddFromCustomer(View v) { chooseCustomerDialog(true); } public void onClickRemoveFromCustomer(View v) { mCurrentVoucher.mFromCustomer = ""; mCurrentVoucher.mFromCustomerId = null; mEditTextFromCustomer.setText(""); mButtonShowFromCustomer.setEnabled(false); } public void onClickShowForCustomer(View v) { if(mCurrentVoucher.mForCustomerId != null) { showCustomerDetails(mCurrentVoucher.mForCustomerId); } } public void onClickAddForCustomer(View v) { chooseCustomerDialog(false); } public void onClickRemoveForCustomer(View v) { mCurrentVoucher.mForCustomer = ""; mCurrentVoucher.mForCustomerId = null; mEditTextForCustomer.setText(""); mButtonShowForCustomer.setEnabled(false); } private void showCustomerDetails(long customerId) { Intent myIntent = new Intent(me, CustomerDetailsActivity.class); myIntent.putExtra("customer-id", customerId); me.startActivity(myIntent); } private void chooseCustomerDialog(final boolean setFromCustomer) { final Dialog ad = new Dialog(me); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_list); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); if(ad.getWindow() != null) lp.copyFrom(ad.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.height = WindowManager.LayoutParams.MATCH_PARENT; final List<Customer> customers = mDb.getCustomers(null, false, false, null); final Button buttonOK = ad.findViewById(R.id.buttonOK); final ListView listView = ad.findViewById(R.id.listViewDialogList); listView.setAdapter(new CustomerAdapter(me, customers, null)); final EditText textBoxSearch = ad.findViewById(R.id.editTextDialogListSearch); textBoxSearch.addTextChangedListener(new TextWatcher() { // future search implementation @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { } }); buttonOK.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); if(listView.getCheckedItemPosition() < 0) return; Customer newCustomer = (Customer) listView.getAdapter().getItem(listView.getCheckedItemPosition()); if(setFromCustomer) { mButtonShowFromCustomer.setEnabled(true); mCurrentVoucher.mFromCustomerId = newCustomer.mId; mCurrentVoucher.mFromCustomer = ""; mEditTextFromCustomer.setText(newCustomer.getFullName(false)); } else { mButtonShowForCustomer.setEnabled(true); mCurrentVoucher.mForCustomerId = newCustomer.mId; mCurrentVoucher.mForCustomer = ""; mEditTextForCustomer.setText(newCustomer.getFullName(false)); } } }); ad.show(); ad.getWindow().setAttributes(lp); } }
13,622
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
CalendarAppointmentEditActivity.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/CalendarAppointmentEditActivity.java
package de.georgsieber.customerdb; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.Spinner; import android.widget.TimePicker; import androidx.activity.result.ActivityResult; import androidx.activity.result.ActivityResultCallback; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import com.google.zxing.BarcodeFormat; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import java.io.File; import java.text.ParseException; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Timer; import java.util.TimerTask; import de.georgsieber.customerdb.importexport.CalendarCsvBuilder; import de.georgsieber.customerdb.importexport.CalendarIcsBuilder; import de.georgsieber.customerdb.model.Customer; import de.georgsieber.customerdb.model.CustomerAppointment; import de.georgsieber.customerdb.model.CustomerCalendar; import de.georgsieber.customerdb.tools.ColorControl; import de.georgsieber.customerdb.tools.CommonDialog; import de.georgsieber.customerdb.tools.DateControl; import de.georgsieber.customerdb.tools.StorageControl; public class CalendarAppointmentEditActivity extends AppCompatActivity { private CalendarAppointmentEditActivity me; private long mCurrentAppointmentId = -1; private CustomerAppointment mCurrentAppointment; private SharedPreferences mSettings; private CustomerDatabase mDb; private Calendar mCalendar = Calendar.getInstance(); private List<CustomerCalendar> mCustomerCalendars; ImageButton mButtonShowCustomer; Spinner mSpinnerCalendar; EditText mEditTextTitle; EditText mEditTextCustomer; EditText mEditTextNotes; EditText mEditTextLocation; Button mButtonDay; TimePicker mTimePickerStart; TimePicker mTimePickerEnd; ImageView mImageViewQrCode; private ActivityResultLauncher<Intent> mResultHandlerExportMoveFile; private File mCurrentExportFile; @Override protected void onCreate(Bundle savedInstanceState) { // init settings mSettings = getSharedPreferences(MainActivity.PREFS_NAME, 0); // init database mDb = new CustomerDatabase(this); // init activity view super.onCreate(savedInstanceState); me = this; setContentView(R.layout.activity_calendar_appointment_edit); // init toolbar Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); if(getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); // init colors ColorControl.updateActionBarColor(this, mSettings); // find views mButtonShowCustomer = findViewById(R.id.buttonShowCustomer); mButtonShowCustomer.setEnabled(false); mImageViewQrCode = findViewById(R.id.imageViewQrCode); mSpinnerCalendar = findViewById(R.id.spinnerCalendar); mEditTextTitle = findViewById(R.id.editTextTitle); mEditTextNotes = findViewById(R.id.editTextNotes); mEditTextCustomer = findViewById(R.id.editTextCustomer); mEditTextLocation = findViewById(R.id.editTextLocation); mButtonDay = findViewById(R.id.buttonDay); mTimePickerStart = findViewById(R.id.timePickerStart); mTimePickerStart.setIs24HourView(true); mTimePickerEnd = findViewById(R.id.timePickerEnd); mTimePickerEnd.setIs24HourView(true); // init activity result handler mResultHandlerExportMoveFile = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() { @Override public void onActivityResult(ActivityResult result) { if(result.getResultCode() == RESULT_OK) { Uri uri = result.getData().getData(); if(uri != null) { try { StorageControl.moveFile(mCurrentExportFile, uri, me); } catch(Exception e) { CommonDialog.show(me, getString(R.string.error), e.getMessage(), CommonDialog.TYPE.FAIL, false); } } } } } ); // register events Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { refreshQrCode(); } }, 1000, 1000); // load calendars mCustomerCalendars = mDb.getCalendars(false); ArrayAdapter<CustomerCalendar> a = new ArrayAdapter<>(this, R.layout.item_list_simple, mCustomerCalendars); mSpinnerCalendar.setAdapter(a); // load default values mEditTextTitle.setText(mSettings.getString("default-appointment-title", "")); mEditTextLocation.setText(mSettings.getString("default-appointment-location", "")); // get extra from parent intent Intent intent = getIntent(); mCurrentAppointmentId = intent.getLongExtra("appointment-id", -1); mCurrentAppointment = mDb.getAppointmentById(mCurrentAppointmentId, false); if(mCurrentAppointment != null) { fillFields(mCurrentAppointment); getSupportActionBar().setTitle(getResources().getString(R.string.edit_appointment)); } else { mCurrentAppointment = new CustomerAppointment(); Object preselectDate = intent.getSerializableExtra("appointment-day"); if(preselectDate instanceof Calendar) mCalendar = (Calendar) preselectDate; // apply default length int defaultLength = mSettings.getInt("appointment-length", 30); Calendar tempCalendar = Calendar.getInstance(); tempCalendar.add(Calendar.MINUTE, defaultLength); if(Build.VERSION.SDK_INT < 23) { mTimePickerEnd.setCurrentHour(tempCalendar.get(Calendar.HOUR_OF_DAY)); mTimePickerEnd.setCurrentMinute(tempCalendar.get(Calendar.MINUTE)); } else { mTimePickerEnd.setHour(tempCalendar.get(Calendar.HOUR_OF_DAY)); mTimePickerEnd.setMinute(tempCalendar.get(Calendar.MINUTE)); } getSupportActionBar().setTitle(getResources().getString(R.string.new_appointment)); } refreshDisplayDate(); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_calendar_appointment_edit, menu); if(mCurrentAppointmentId == -1) { // hide id and remove button if we are about to create a new appointment menu.findItem(R.id.action_id).setVisible(false); menu.findItem(R.id.action_remove).setVisible(false); } else { menu.findItem(R.id.action_id).setVisible(true); menu.findItem(R.id.action_remove).setVisible(true); } if(mCurrentAppointment != null && mCurrentAppointment.mId != -1) // show id in menu menu.findItem(R.id.action_id).setTitle( "ID: " + mCurrentAppointment.mId ); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case android.R.id.home: finish(); return true; case R.id.action_remove: removeAndExit(); return true; case R.id.action_export: export(); return true; case R.id.action_edit_done: saveAndExit(); return true; default: return super.onOptionsItemSelected(item); } } private String mLastQrContent = ""; @SuppressWarnings("SuspiciousNameCombination") private void refreshQrCode() { int WIDTH = 1200; if(!updateAppointmentObjectByInputs()) return; String content = "BEGIN:VEVENT" + "\n" + "SUMMARY:" + mEditTextTitle.getText().toString() + "\n" + "DESCRIPTION:" + mEditTextNotes.getText().toString().replace("\n", "\\n") + "\n" + "LOCATION:" + mEditTextLocation.getText().toString() + "\n" + "DTSTART:" + CalendarIcsBuilder.dateFormatIcs.format(mCurrentAppointment.mTimeStart) + "\n" + "DTEND:" + CalendarIcsBuilder.dateFormatIcs.format(mCurrentAppointment.mTimeEnd) + "\n" + "END:VEVENT" + "\n"; if(mLastQrContent.equals(content)) return; mLastQrContent = content; try { QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, WIDTH, WIDTH); int w = bitMatrix.getWidth(); int h = bitMatrix.getHeight(); int[] pixels = new int[w * h]; for (int y = 0; y < h; y++) { int offset = y * w; for (int x = 0; x < w; x++) { pixels[offset + x] = bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE; } } final Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, WIDTH, 0, 0, w, h); runOnUiThread(new Runnable() { @Override public void run() { mImageViewQrCode.setImageDrawable(new BitmapDrawable(bitmap)); } }); } catch (WriterException ignored) { runOnUiThread(new Runnable() { @Override public void run() { mImageViewQrCode.setImageDrawable(new ColorDrawable(Color.WHITE)); } }); } } private void fillFields(CustomerAppointment a) { for(CustomerCalendar c : mCustomerCalendars) { if(c.mId == a.mCalendarId) { mSpinnerCalendar.setSelection(mCustomerCalendars.indexOf(c)); } } mEditTextTitle.setText(a.mTitle); mEditTextNotes.setText(a.mNotes); mEditTextLocation.setText(a.mLocation); if(a.mCustomerId != null) { Customer relatedCustomer = mDb.getCustomerById(a.mCustomerId, false, false); if(relatedCustomer != null) { mEditTextCustomer.setText(relatedCustomer.getFullName(false)); mButtonShowCustomer.setEnabled(true); } else { mEditTextCustomer.setText(getString(R.string.removed_placeholder)); } } else { mEditTextCustomer.setText(a.mCustomer); } mCalendar.setTime(a.mTimeEnd); if(Build.VERSION.SDK_INT < 23) { mTimePickerEnd.setCurrentHour(mCalendar.get(Calendar.HOUR_OF_DAY)); mTimePickerEnd.setCurrentMinute(mCalendar.get(Calendar.MINUTE)); } else { mTimePickerEnd.setHour(mCalendar.get(Calendar.HOUR_OF_DAY)); mTimePickerEnd.setMinute(mCalendar.get(Calendar.MINUTE)); } mCalendar.setTime(a.mTimeStart); if(Build.VERSION.SDK_INT < 23) { mTimePickerStart.setCurrentHour(mCalendar.get(Calendar.HOUR_OF_DAY)); mTimePickerStart.setCurrentMinute(mCalendar.get(Calendar.MINUTE)); } else { mTimePickerStart.setHour(mCalendar.get(Calendar.HOUR_OF_DAY)); mTimePickerStart.setMinute(mCalendar.get(Calendar.MINUTE)); } } @SuppressWarnings("BooleanMethodIsAlwaysInverted") private boolean updateAppointmentObjectByInputs() { CustomerCalendar calendar = (CustomerCalendar) (mSpinnerCalendar).getSelectedItem(); if(calendar == null) return false; mCurrentAppointment.mCalendarId = calendar.mId; mCurrentAppointment.mTitle = mEditTextTitle.getText().toString(); mCurrentAppointment.mNotes = mEditTextNotes.getText().toString(); mCurrentAppointment.mLocation = mEditTextLocation.getText().toString(); String dateString = CustomerDatabase.storageFormatWithoutTime.format(mCalendar.getTime()); String dateStringStart; String dateStringEnd; if(Build.VERSION.SDK_INT < 23) { dateStringStart = dateString + " " + mTimePickerStart.getCurrentHour() + ":" + mTimePickerStart.getCurrentMinute() + ":00"; dateStringEnd = dateString + " " + mTimePickerEnd.getCurrentHour() + ":" + mTimePickerEnd.getCurrentMinute() + ":00"; } else { dateStringStart = dateString + " " + mTimePickerStart.getHour() + ":" + mTimePickerStart.getMinute() + ":00"; dateStringEnd = dateString + " " + mTimePickerEnd.getHour() + ":" + mTimePickerEnd.getMinute() + ":00"; } try { mCurrentAppointment.mTimeStart = CustomerDatabase.parseDateRaw(dateStringStart); mCurrentAppointment.mTimeEnd = CustomerDatabase.parseDateRaw(dateStringEnd); } catch (ParseException e) { return false; } // save default length SharedPreferences.Editor editor = mSettings.edit(); editor.putInt("appointment-length", (int)((mCurrentAppointment.mTimeEnd.getTime() - mCurrentAppointment.mTimeStart.getTime()) / 1000 / 60)); editor.apply(); return true; } private boolean updateAndCheckAppointment() { CustomerCalendar calendar = (CustomerCalendar) (mSpinnerCalendar).getSelectedItem(); if(calendar == null) { CommonDialog.show(this, getString(R.string.error), getString(R.string.no_calendar_selected), CommonDialog.TYPE.WARN, false); return false; } if(!updateAppointmentObjectByInputs()) return false; if(mCurrentAppointment.mTimeStart.getTime() > mCurrentAppointment.mTimeEnd.getTime()) { CommonDialog.show(this, getString(R.string.error), getString(R.string.end_date_before_start_date), CommonDialog.TYPE.WARN, false); return false; } if(mCurrentAppointment.mTimeEnd.getTime() - mCurrentAppointment.mTimeStart.getTime() < 1000*60*5) { CommonDialog.show(this, getString(R.string.error), getString(R.string.appointment_too_short), CommonDialog.TYPE.WARN, false); return false; } return true; } private void saveAndExit() { if(updateAndCheckAppointment()) { if(mCurrentAppointmentId == -1) { // insert new mDb.addAppointment(mCurrentAppointment); } else { // update in database mCurrentAppointment.mLastModified = new Date(); mDb.updateAppointment(mCurrentAppointment); } MainActivity.setUnsyncedChanges(this); setResult(RESULT_OK); finish(); } } private void removeAndExit() { mDb.removeAppointment(mCurrentAppointment); MainActivity.setUnsyncedChanges(this); setResult(RESULT_OK); finish(); } public void onClickChangeDay(View v) { final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { mCalendar.set(Calendar.YEAR, year); mCalendar.set(Calendar.MONTH, monthOfYear); mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); refreshDisplayDate(); } }; new DatePickerDialog( this, date, mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH) ).show(); } private void refreshDisplayDate() { mButtonDay.setText(DateControl.birthdayDateFormat.format(mCalendar.getTime())); } private void export() { if(!updateAppointmentObjectByInputs()) return; final Dialog ad = new Dialog(this); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_export_single_appointment); ad.findViewById(R.id.buttonExportSingleCSV).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); if(new CalendarCsvBuilder(mCurrentAppointment).saveCsvFile(getStorageExportCSV(), mDb)) { mCurrentExportFile = getStorageExportCSV(); CommonDialog.exportFinishedDialog(me, getStorageExportCSV(), "text/csv", new String[]{}, "", "", mResultHandlerExportMoveFile ); } else { CommonDialog.show(me, getResources().getString(R.string.export_fail), getStorageExportCSV().getPath(), CommonDialog.TYPE.FAIL, false); } StorageControl.scanFile(getStorageExportCSV(), me); } }); ad.findViewById(R.id.buttonExportSingleICS).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); if(new CalendarIcsBuilder(mCurrentAppointment).saveIcsFile(getStorageExportICS())) { mCurrentExportFile = getStorageExportICS(); CommonDialog.exportFinishedDialog(me, getStorageExportICS(), "text/calendar", new String[]{}, "", "", mResultHandlerExportMoveFile ); } else { CommonDialog.show(me, getResources().getString(R.string.export_fail), getStorageExportICS().getPath(), CommonDialog.TYPE.FAIL, false); } StorageControl.scanFile(getStorageExportICS(), me); } }); ad.findViewById(R.id.buttonExportSingleCancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); } }); ad.show(); } private File getStorageExportCSV() { File exportDir = new File(getExternalFilesDir(null), "export"); exportDir.mkdirs(); return new File(exportDir, "export."+ mCurrentAppointment.mId +".csv"); } private File getStorageExportICS() { File exportDir = new File(getExternalFilesDir(null), "export"); exportDir.mkdirs(); return new File(exportDir, "export."+ mCurrentAppointment.mId +".ics"); } public void onClickShowCustomer(View v) { if(mCurrentAppointment.mCustomerId != null) { showCustomerDetails(mCurrentAppointment.mCustomerId); } } public void onClickAddCustomer(View v) { chooseCustomerDialog(); } public void onClickRemoveCustomer(View v) { mCurrentAppointment.mCustomer = ""; mCurrentAppointment.mCustomerId = null; mEditTextCustomer.setText(""); mButtonShowCustomer.setEnabled(false); } private void showCustomerDetails(long customerId) { Intent myIntent = new Intent(me, CustomerDetailsActivity.class); myIntent.putExtra("customer-id", customerId); me.startActivity(myIntent); } private void chooseCustomerDialog() { final Dialog ad = new Dialog(me); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_list); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); if(ad.getWindow() != null) lp.copyFrom(ad.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.height = WindowManager.LayoutParams.MATCH_PARENT; final List<Customer> customers = mDb.getCustomers(null, false, false, null); final Button buttonOK = ad.findViewById(R.id.buttonOK); final ListView listView = ad.findViewById(R.id.listViewDialogList); listView.setAdapter(new CustomerAdapter(me, customers, null)); final EditText textBoxSearch = ad.findViewById(R.id.editTextDialogListSearch); textBoxSearch.addTextChangedListener(new TextWatcher() { // future search implementation @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { } }); buttonOK.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); if(listView.getCheckedItemPosition() < 0) return; Customer newCustomer = (Customer) listView.getAdapter().getItem(listView.getCheckedItemPosition()); mButtonShowCustomer.setEnabled(true); mCurrentAppointment.mCustomerId = newCustomer.mId; mCurrentAppointment.mCustomer = ""; mEditTextCustomer.setText(newCustomer.getFullName(false)); } }); ad.show(); ad.getWindow().setAttributes(lp); } }
22,430
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
CustomerAdapterBirthday.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/CustomerAdapterBirthday.java
package de.georgsieber.customerdb; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.TextView; import java.util.List; import de.georgsieber.customerdb.model.Customer; public class CustomerAdapterBirthday extends BaseAdapter { private Context mContext; private List<Customer> mCustomers; CustomerAdapterBirthday(Context context, List<Customer> customers) { mContext = context; mCustomers = customers; } @Override public int getCount() { return mCustomers.size(); } @Override public Object getItem(int position) { return mCustomers.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null) { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.item_list_customer, null); } TextView tv1 = (convertView.findViewById(R.id.textViewCustomerListItem1)); TextView tv2 = (convertView.findViewById(R.id.textViewCustomerListItem2)); CheckBox cb = (convertView.findViewById(R.id.checkBoxCustomerListItem)); tv1.setText(mCustomers.get(position).getFirstLine()); tv2.setText(mCustomers.get(position).getBirthdayString(mContext.getResources().getString(R.string.birthdaytodaynote))); cb.setVisibility(View.GONE); return convertView; } }
1,713
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
VoucherAdapter.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/VoucherAdapter.java
package de.georgsieber.customerdb; import android.annotation.SuppressLint; import android.content.Context; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import de.georgsieber.customerdb.model.Voucher; public class VoucherAdapter extends BaseAdapter { private Context mContext; private List<Voucher> mVouchers; private String mCurrency; private LayoutInflater mInflater; private boolean mShowCheckbox = false; VoucherAdapter(Context context, List<Voucher> vouchers, String currency) { mContext = context; mVouchers = vouchers; mCurrency = currency; mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } VoucherAdapter(Context context, List<Voucher> vouchers, String currency, checkedChangedListener listener) { mContext = context; mVouchers = vouchers; mCurrency = currency; mListener = listener; mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return mVouchers.size(); } @Override public Object getItem(int position) { return mVouchers.get(position); } @Override public long getItemId(int position) { return 0; } @SuppressLint("SetTextI18n") @Override public View getView(int position, View convertView, ViewGroup parent) { Voucher v = mVouchers.get(position); if(convertView == null) { convertView = mInflater.inflate(R.layout.item_list_customer, null); } TextView tv1 = (convertView.findViewById(R.id.textViewCustomerListItem1)); TextView tv2 = (convertView.findViewById(R.id.textViewCustomerListItem2)); if(v.mCurrentValue != v.mOriginalValue) tv1.setText(v.getCurrentValueString()+" "+mCurrency + " ("+v.getOriginalValueString()+" "+mCurrency+")"); else tv1.setText(v.getCurrentValueString()+" "+mCurrency); tv2.setText(v.mVoucherNo.equals("") ? v.getIdString() : v.mVoucherNo); CheckBox currentListItemCheckBox = convertView.findViewById(R.id.checkBoxCustomerListItem); if(mShowCheckbox) { currentListItemCheckBox.setTag(position); currentListItemCheckBox.setChecked(mSparseBooleanArray.get(position)); currentListItemCheckBox.setOnCheckedChangeListener(mCheckedChangeListener); currentListItemCheckBox.setVisibility(View.VISIBLE); } else { currentListItemCheckBox.setVisibility(View.GONE); } return convertView; } boolean getShowCheckbox() { return mShowCheckbox; } void setShowCheckbox(boolean visible) { mShowCheckbox = visible; notifyDataSetChanged(); } private SparseBooleanArray mSparseBooleanArray = new SparseBooleanArray(); private CompoundButton.OnCheckedChangeListener mCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked); if(mListener != null) mListener.checkedChanged(getCheckedItems()); } }; void setAllChecked(boolean checked) { for(int i = 0; i< mVouchers.size(); i++) { mSparseBooleanArray.put(i, checked); } if(mListener != null) mListener.checkedChanged(getCheckedItems()); } ArrayList<Voucher> getCheckedItems() { ArrayList<Voucher> mTempArray = new ArrayList<>(); for(int i = 0; i< mVouchers.size(); i++) { if(mSparseBooleanArray.get(i)) { mTempArray.add(mVouchers.get(i)); } } return mTempArray; } private checkedChangedListener mListener = null; public interface checkedChangedListener { void checkedChanged(ArrayList<Voucher> checked); } void setCheckedChangedListener(checkedChangedListener listener) { this.mListener = listener; } }
4,389
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
ScanActivity.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/ScanActivity.java
package de.georgsieber.customerdb; import android.Manifest; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.os.VibrationEffect; import android.os.Vibrator; import android.text.TextUtils; import android.util.Log; import android.view.MenuItem; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import com.google.zxing.Result; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; import de.georgsieber.customerdb.importexport.CustomerVcfBuilder; import de.georgsieber.customerdb.model.Customer; import de.georgsieber.customerdb.tools.ColorControl; import me.dm7.barcodescanner.zxing.ZXingScannerView; public class ScanActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler { private ScanActivity me; private CustomerDatabase mDb; private SharedPreferences mSettings; private ZXingScannerView mScannerView; private int currentCameraId = 0; private final static int CAMERA_PERMISSION = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scan); me = this; // init toolbar Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); if(getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); // init settings mSettings = getSharedPreferences(MainActivity.PREFS_NAME, 0); // init database mDb = new CustomerDatabase(this); // init colors ColorControl.updateActionBarColor(this, mSettings); // init scanner mScannerView = findViewById(R.id.scannerView); mScannerView.setFlash(false); mScannerView.setAutoFocus(true); mScannerView.setAspectTolerance(0.5f); // request camera permission openCamera(); } private void openCamera() { if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION); } } @SuppressWarnings({"SwitchStatementWithTooFewBranches", "UnnecessaryReturnStatement"}) @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch(requestCode) { case CAMERA_PERMISSION: if(grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, getString(R.string.please_grant_camera_permission), Toast.LENGTH_LONG).show(); } return; } } @Override public boolean onOptionsItemSelected(MenuItem item) { //noinspection SwitchStatementWithTooFewBranches switch(item.getItemId()) { case android.R.id.home: finish(); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onResume() { super.onResume(); mScannerView.setResultHandler(this); mScannerView.startCamera(currentCameraId); } @Override public void onPause() { super.onPause(); mScannerView.stopCamera(); // Stop camera on pause } @SuppressWarnings("CharsetObjectCanBeUsed") @Override public void handleResult(Result rawResult) { vibrate(this); String code = rawResult.getText(); if(code == null) return; Log.i("SCAN", code); // check if code contains VCF formatted data try { InputStream stream = new ByteArrayInputStream(code.getBytes("UTF-8")); List<Customer> parsedCustomers = CustomerVcfBuilder.readVcfFile(new InputStreamReader(stream)); if(parsedCustomers.size() > 0) { askImport(parsedCustomers); return; } } catch(Exception ignored) { } // check if code contains MECARD formatted data (similar to VCF, used by Huawei contacts app) if(code.startsWith("MECARD:")) { String formatted = code.substring(7); formatted = "BEGIN:VCARD\n" + TextUtils.join("\n", formatted.split(";")) + "\nEND:VCARD"; try { InputStream stream = new ByteArrayInputStream(formatted.getBytes("UTF-8")); List<Customer> parsedCustomers = CustomerVcfBuilder.readVcfFile(new InputStreamReader(stream)); if(parsedCustomers.size() > 0) { askImport(parsedCustomers); return; } } catch(Exception ignored) { } } // no valid data found Toast.makeText(this, getString(R.string.invalid_code), Toast.LENGTH_LONG).show(); mScannerView.resumeCameraPreview(this); } private void askImport(final List<Customer> customers) { if(customers.size() == 0) { return; } // ask for import dialog String importDescription = ""; for(Customer c : customers) { importDescription += c.getFirstLine() + "\n"; } DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch(which) { case DialogInterface.BUTTON_POSITIVE: for(Customer c : customers) { mDb.addCustomer(c); } MainActivity.setUnsyncedChanges(me); me.setResult(1); me.finish(); break; case DialogInterface.BUTTON_NEGATIVE: mScannerView.resumeCameraPreview(me); break; } } }; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(getString(R.string.do_you_want_to_import_this_customer) + "\n\n" + importDescription) .setPositiveButton(getString(R.string.yes), dialogClickListener) .setNegativeButton(getString(R.string.no), dialogClickListener) .setCancelable(false) .show(); } static void vibrate(Context c) { Vibrator v = (Vibrator) c.getSystemService(Context.VIBRATOR_SERVICE); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (v != null) { v.vibrate(VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE)); } } else { //deprecated in API 26 if (v != null) { v.vibrate(100); } } } }
7,338
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
CustomerEditActivity.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/CustomerEditActivity.java
package de.georgsieber.customerdb; import android.Manifest; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.ContentResolver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.core.content.FileProvider; import android.provider.MediaStore; import android.provider.OpenableColumns; import android.text.InputType; import android.util.Base64; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Space; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Calendar; import java.util.Date; import java.util.List; import de.georgsieber.customerdb.model.CustomField; import de.georgsieber.customerdb.model.Customer; import de.georgsieber.customerdb.model.CustomerFile; import de.georgsieber.customerdb.tools.ColorControl; import de.georgsieber.customerdb.tools.CommonDialog; import de.georgsieber.customerdb.tools.DateControl; import de.georgsieber.customerdb.tools.NumTools; import de.georgsieber.customerdb.tools.StorageControl; @SuppressWarnings("TryFinallyCanBeTryWithResources") public class CustomerEditActivity extends AppCompatActivity { private CustomerEditActivity me; private CustomerDatabase mDb; private FeatureCheck mFc; private long mCurrentCustomerId = -1; private Customer mCurrentCustomer; private List<CustomField> mCustomFields; private boolean mIsInoutOnlyModeActive = false; private final static int CUSTOMER_IMAGE_PICK_REQUEST = 1; private final static int CUSTOMER_IMAGE_CAMERA_REQUEST = 2; private final static int ABOUT_REQUEST = 3; private final static int FILE_CAMERA_REQUEST = 4; private final static int FILE_PICK_REQUEST = 5; private final static int FILE_DRAW_REQUEST = 6; private final static int CAMERA_PERMISSION_REQUEST = 7; Calendar mBirthdayCalendar = null; EditText mEditTextTitle; EditText mEditTextFirstName; EditText mEditTextLastName; EditText mEditTextPhoneHome; EditText mEditTextPhoneMobile; EditText mEditTextPhoneWork; EditText mEditTextEmail; EditText mEditTextStreet; EditText mEditTextZipcode; EditText mEditTextCity; EditText mEditTextCountry; EditText mEditTextGroup; EditText mEditTextNotes; CheckBox mCheckBoxNewsletter; CheckBox mCheckBoxConsent; Button mButtonBirthday; @Override protected void onCreate(Bundle savedInstanceState) { // init settings SharedPreferences settings = getSharedPreferences(MainActivity.PREFS_NAME, 0); // init database mDb = new CustomerDatabase(this); // load in-app purchases mFc = new FeatureCheck(this); mFc.init(); // init activity view super.onCreate(savedInstanceState); me = this; setContentView(R.layout.activity_customer_edit); // init toolbar Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); if(getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); // init colors ColorControl.updateActionBarColor(this, settings); // find views mEditTextTitle = findViewById(R.id.editTextTitle); mEditTextFirstName = findViewById(R.id.editTextFirstName); mEditTextLastName = findViewById(R.id.editTextLastName); mEditTextPhoneHome = findViewById(R.id.editTextPhoneHome); mEditTextPhoneMobile = findViewById(R.id.editTextPhoneMobile); mEditTextPhoneWork = findViewById(R.id.editTextPhoneWork); mEditTextEmail = findViewById(R.id.editTextEmail); mEditTextStreet = findViewById(R.id.editTextStreet); mEditTextZipcode = findViewById(R.id.editTextZipcode); mEditTextCity = findViewById(R.id.editTextCity); mEditTextCountry = findViewById(R.id.editTextCountry); mEditTextGroup = findViewById(R.id.editTextGroup); mEditTextNotes = findViewById(R.id.editTextNotes); mCheckBoxNewsletter = findViewById(R.id.checkBoxEditNewsletter); mCheckBoxConsent = findViewById(R.id.checkBoxEditConsent); mButtonBirthday = findViewById(R.id.buttonBirthday); // apply settings settings = getSharedPreferences(MainActivity.PREFS_NAME, 0); if(settings.getBoolean("phone-allow-text", false)) { mEditTextPhoneHome.setInputType(InputType.TYPE_CLASS_TEXT); mEditTextPhoneMobile.setInputType(InputType.TYPE_CLASS_TEXT); mEditTextPhoneWork.setInputType(InputType.TYPE_CLASS_TEXT); } if(!settings.getBoolean("show-customer-picture", true)) { findViewById(R.id.linearLayoutCustomerImageEdit).setVisibility(View.GONE); } if(!settings.getBoolean("show-phone-field", true)) { mEditTextPhoneHome.setVisibility(View.GONE); mEditTextPhoneMobile.setVisibility(View.GONE); mEditTextPhoneWork.setVisibility(View.GONE); } if(!settings.getBoolean("show-email-field", true)) { mEditTextEmail.setVisibility(View.GONE); } if(!settings.getBoolean("show-phone-field", true) && !settings.getBoolean("show-email-field", true)) { findViewById(R.id.linearLayoutContact).setVisibility(View.GONE); } if(!settings.getBoolean("show-address-field", true)) { findViewById(R.id.linearLayoutAddress).setVisibility(View.GONE); } if(!settings.getBoolean("show-group-field", true)) { findViewById(R.id.linearLayoutGroup).setVisibility(View.GONE); } if(!settings.getBoolean("show-notes-field", true)) { findViewById(R.id.linearLayoutNotes).setVisibility(View.GONE); } if(!settings.getBoolean("show-newsletter-field", true)) { findViewById(R.id.linearLayoutNewsletter).setVisibility(View.GONE); } if(!settings.getBoolean("show-birthday-field", true)) { findViewById(R.id.linearLayoutBirthday).setVisibility(View.GONE); } if(!settings.getBoolean("show-files", true)) { findViewById(R.id.linearLayoutFilesContainer).setVisibility(View.GONE); } // load default values mEditTextTitle.setText(settings.getString("default-customer-title", "")); mEditTextCity.setText(settings.getString("default-customer-city", "")); mEditTextCountry.setText(settings.getString("default-customer-country", "")); mEditTextGroup.setText(settings.getString("default-customer-group", "")); // show consent checkbox if(settings.getBoolean("iom", false) && settings.getBoolean("show-consent-field", false)) { mIsInoutOnlyModeActive = true; findViewById(R.id.linearLayoutConsent).setVisibility(View.VISIBLE); } // get extra from parent intent Intent intent = getIntent(); mCurrentCustomerId = intent.getLongExtra("customer-id", -1); mCurrentCustomer = mDb.getCustomerById(mCurrentCustomerId, false, true); if(mCurrentCustomer != null) { fillFields(mCurrentCustomer); if(getSupportActionBar() != null) getSupportActionBar().setTitle(getResources().getString(R.string.edit_customer)); } else { mCurrentCustomer = new Customer(); if(getSupportActionBar() != null) getSupportActionBar().setTitle(getResources().getString(R.string.new_customer)); } // init custom fields LinearLayout linearLayout = findViewById(R.id.linearLayoutCustomFieldsEdit); linearLayout.removeAllViews(); mCustomFields = mDb.getCustomFields(); if(mCustomFields.size() > 0) linearLayout.setVisibility(View.VISIBLE); for(CustomField cf : mCustomFields) { TextView descriptionView = new TextView(this); descriptionView.setText(cf.mTitle); descriptionView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT)); String value = ""; if(mCurrentCustomer != null) { value = mCurrentCustomer.getCustomField(cf.mTitle); if(value == null) value = ""; } View valueView; if(cf.mType == 2) { valueView = new Spinner(this); cf.mEditViewReference = valueView; valueView.setBackgroundResource(R.drawable.background_spinner); reloadCustomFieldPresets((Spinner)valueView, cf.mId, value); } else { valueView = new EditText(this); cf.mEditViewReference = valueView; if(cf.mType == 1) { ((EditText)valueView).setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED); } else if(cf.mType == 3) { // open DatePickerDialog on click final EditText editTextValue = ((EditText)valueView); editTextValue.setInputType(InputType.TYPE_NULL); editTextValue.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean hasFocus) { if(hasFocus) { onCustomDateFieldClick(editTextValue); } } }); editTextValue.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onCustomDateFieldClick(editTextValue); } }); // try parse old value and show it in local format try { Date selectedDate = CustomerDatabase.parseDateRaw(value); value = DateControl.birthdayDateFormat.format(selectedDate); } catch(Exception ignored) {} } else if(cf.mType == 4) { ((EditText)valueView).setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_MULTI_LINE); } else { ((EditText)valueView).setInputType(InputType.TYPE_CLASS_TEXT); } ((EditText)valueView).setText(value); } View spaceView = new Space(this); spaceView.setLayoutParams(new LinearLayout.LayoutParams(0, NumTools.dpToPx(20, this))); linearLayout.addView(spaceView); valueView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); linearLayout.addView(descriptionView); linearLayout.addView(valueView); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_customer_edit, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case android.R.id.home: finish(); return true; case R.id.action_edit_done: saveAndExit(); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch(requestCode) { case(CUSTOMER_IMAGE_CAMERA_REQUEST) : { if(resultCode == RESULT_OK && data != null && data.getExtras() != null) { Bitmap photo = (Bitmap) data.getExtras().get("data"); mCurrentCustomer.mImage = compressToJpeg(photo, 50); refreshImage(); } break; } case(CUSTOMER_IMAGE_PICK_REQUEST) : { if(resultCode == RESULT_OK && data != null && data.getData() != null) { try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData()); mCurrentCustomer.mImage = compressToJpeg(resizeCompressToJpeg(bitmap, 400, 400), 50); } catch (IOException e) { CommonDialog.show(me, getString(R.string.error), e.getLocalizedMessage(), CommonDialog.TYPE.FAIL, false); } refreshImage(); } break; } case(FILE_CAMERA_REQUEST) : { if(resultCode == RESULT_OK) { try { //Bitmap photo = (Bitmap) data.getExtras().get("data"); // thumbnail Bitmap bitmap = BitmapFactory.decodeFile(StorageControl.getStorageImageTemp(this).getAbsolutePath()); byte[] jpegBytes = compressToJpeg(resizeCompressToJpeg(bitmap, 800, 600), 70); mCurrentCustomer.addFile(new CustomerFile(StorageControl.getNewPictureFilename(this), jpegBytes), this); } catch(Exception e) { CommonDialog.show(me, getString(R.string.error), e.getLocalizedMessage(), CommonDialog.TYPE.FAIL, false); } } refreshFiles(); break; } case(FILE_PICK_REQUEST) : { if(resultCode == RESULT_OK && data != null && data.getData() != null) { String filename = getFileName(data.getData()); ContentResolver cr = getContentResolver(); try { if(cr.getType(data.getData()).startsWith("image/")) { // try to compress the image Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData()); byte[] jpegBytes = compressToJpeg(resizeCompressToJpeg(bitmap, 800, 600), 70); mCurrentCustomer.addFile(new CustomerFile(filename, jpegBytes), this); } else { // save raw InputStream is = getContentResolver().openInputStream(data.getData()); byte[] dataBytes = getByteArrayFromInputStream(is); mCurrentCustomer.addFile(new CustomerFile(filename, dataBytes), this); } } catch(Exception e) { CommonDialog.show(me, getString(R.string.error), e.getLocalizedMessage(), CommonDialog.TYPE.FAIL, false); } } refreshFiles(); break; } case(FILE_DRAW_REQUEST) : { if(resultCode == RESULT_OK && data != null && data.getExtras() != null) { try { mCurrentCustomer.addFile(new CustomerFile(StorageControl.getNewDrawingFilename(this), Base64.decode(data.getExtras().getString("image"), Base64.DEFAULT)), this); } catch(Exception e) { CommonDialog.show(me, getString(R.string.error), e.getLocalizedMessage(), CommonDialog.TYPE.FAIL, false); } } refreshFiles(); break; } case(ABOUT_REQUEST) : { mFc.init(); break; } } } @SuppressWarnings("SameParameterValue") private static Bitmap resizeCompressToJpeg(Bitmap image, int maxWidth, int maxHeight) { if((image.getWidth() > maxWidth || image.getHeight() > maxHeight) && maxHeight > 0 && maxWidth > 0) { int width = image.getWidth(); int height = image.getHeight(); float ratioBitmap = (float) width / (float) height; float ratioMax = (float) maxWidth / (float) maxHeight; int finalWidth = maxWidth; int finalHeight = maxHeight; if(ratioMax > ratioBitmap) { finalWidth = (int) ((float)maxHeight * ratioBitmap); } else { finalHeight = (int) ((float)maxWidth / ratioBitmap); } image = Bitmap.createScaledBitmap(image, finalWidth, finalHeight, true); } return image; } private static byte[] compressToJpeg(Bitmap image, int compressRatio) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, compressRatio, stream); byte[] byteArray = stream.toByteArray(); image.recycle(); return byteArray; } public String getFileName(Uri uri) { String result = null; if(uri.getScheme().equals("content")) { Cursor cursor = getContentResolver().query(uri, null, null, null, null); try { if(cursor != null && cursor.moveToFirst()) { result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); } } finally { cursor.close(); } } if(result == null) { result = uri.getPath(); int cut = result.lastIndexOf('/'); if(cut != -1) { result = result.substring(cut + 1); } } return result; } private byte[] getByteArrayFromInputStream(InputStream is) { try { ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while((len = is.read(buffer)) != -1) { byteBuffer.write(buffer, 0, len); } return byteBuffer.toByteArray(); } catch (Exception e) { Log.e("FILE", "Error: " + e.toString()); } return null; } void onCustomDateFieldClick(final EditText editTextValue) { hideKeyboardFrom(me, editTextValue); Calendar selected = Calendar.getInstance(); try { selected.setTime( DateControl.birthdayDateFormat.parse(editTextValue.getText().toString()) ); } catch(Exception ignored) {} final DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, monthOfYear); cal.set(Calendar.DAY_OF_MONTH, dayOfMonth); editTextValue.setText(DateControl.birthdayDateFormat.format(cal.getTime())); } }; new DatePickerDialog( CustomerEditActivity.this, listener, selected.get(Calendar.YEAR), selected.get(Calendar.MONTH), selected.get(Calendar.DAY_OF_MONTH) ).show(); } static void hideKeyboardFrom(Context context, View view) { InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } private void dialogInApp(String title, String text) { AlertDialog.Builder ad = new AlertDialog.Builder(this); ad.setTitle(title); ad.setMessage(text); ad.setIcon(getResources().getDrawable(R.drawable.ic_warning_orange_24dp)); ad.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); ad.setNeutralButton(getResources().getString(R.string.more), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startActivityForResult(new Intent(me, AboutActivity.class), ABOUT_REQUEST); } }); ad.show(); } private void saveAndExit() { if(mEditTextTitle.getText().toString().equals("") && mEditTextFirstName.getText().toString().equals("") && mEditTextLastName.getText().toString().equals("")) { CommonDialog.show(this, getString(R.string.name_empty), getString(R.string.please_fill_name), CommonDialog.TYPE.WARN, false); return; } if(mCheckBoxNewsletter.isChecked() && mEditTextEmail.getText().toString().equals("")) { CommonDialog.show(this, getString(R.string.email_empty), getString(R.string.please_fill_email), CommonDialog.TYPE.WARN, false); return; } if(mIsInoutOnlyModeActive && !mCheckBoxConsent.isChecked()) { CommonDialog.show(this, getString(R.string.data_processing_consent), getString(R.string.please_accept_data_processing), CommonDialog.TYPE.WARN, false); return; } if(mDb.getCustomers(null, false, false, null).size() >= 500 && !mFc.unlockedLargeCompany) { dialogInApp(getResources().getString(R.string.feature_locked), getResources().getString(R.string.feature_locked_large_company_text)); return; } updateCustomerObjectByInputs(); if(mCurrentCustomer.mId == -1) { // insert new customer mDb.addCustomer(mCurrentCustomer); } else { // update in database mCurrentCustomer.mLastModified = new Date(); mDb.updateCustomer(mCurrentCustomer); } MainActivity.setUnsyncedChanges(this); setResult(RESULT_OK); finish(); } private void reloadCustomFieldPresets(Spinner spinner, int fieldId, String defaultValue) { List<CustomField> options = mDb.getCustomFieldPresets(fieldId); ArrayAdapter<CustomField> a = new ArrayAdapter<CustomField>(this, R.layout.item_list_simple, options); spinner.setAdapter(a); for(CustomField f : options) { if(f.mTitle.equals(defaultValue)) { Log.e("EQUALS", defaultValue); spinner.setSelection(options.indexOf(f)); } } } private void fillFields(Customer c) { mEditTextTitle.setText(c.mTitle); mEditTextFirstName.setText(c.mFirstName); mEditTextLastName.setText(c.mLastName); mEditTextPhoneHome.setText(c.mPhoneHome); mEditTextPhoneMobile.setText(c.mPhoneMobile); mEditTextPhoneWork.setText(c.mPhoneWork); mEditTextEmail.setText(c.mEmail); mEditTextStreet.setText(c.mStreet); mEditTextZipcode.setText(c.mZipcode); mEditTextCity.setText(c.mCity); mEditTextCountry.setText(c.mCountry); mEditTextNotes.setText(c.mNotes); mEditTextGroup.setText(c.mCustomerGroup); mCheckBoxNewsletter.setChecked(c.mNewsletter); if(c.mBirthday == null) { mBirthdayCalendar = null; } else { mBirthdayCalendar = Calendar.getInstance(); } if(mBirthdayCalendar == null) { mButtonBirthday.setText(getString(R.string.no_date_set)); } else { mBirthdayCalendar.setTime(c.mBirthday); mButtonBirthday.setText(DateControl.birthdayDateFormat.format(mBirthdayCalendar.getTime())); } refreshImage(); refreshFiles(); } private void refreshImage() { if(mCurrentCustomer.getImage().length != 0) { Bitmap bitmap = BitmapFactory.decodeByteArray(mCurrentCustomer.getImage(), 0, mCurrentCustomer.getImage().length); ((ImageView) findViewById(R.id.imageViewEditCustomerImage)).setImageBitmap(bitmap); } else { ((ImageView) findViewById(R.id.imageViewEditCustomerImage)).setImageDrawable(getResources().getDrawable(R.drawable.ic_person_black_96dp)); } } private void refreshFiles() { LinearLayout linearLayoutFilesView = findViewById(R.id.linearLayoutFilesView); linearLayoutFilesView.removeAllViews(); int counter = 0; for(final CustomerFile file : mCurrentCustomer.getFiles()) { final int count = counter; @SuppressLint("InflateParams") LinearLayout linearLayoutFile = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.item_file_edit, null); Button buttonFilename = linearLayoutFile.findViewById(R.id.buttonFile); buttonFilename.setText(file.mName); buttonFilename.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final Dialog ad = new Dialog(me); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_input_box); ((TextView) ad.findViewById(R.id.textViewInputBox)).setText(getResources().getString(R.string.enter_new_name)); ((EditText) ad.findViewById(R.id.editTextInputBox)).setText(file.mName); if(file.mName.contains(".")) { int lastIndex = file.mName.lastIndexOf("."); ((EditText) ad.findViewById(R.id.editTextInputBox)).setSelection(0, lastIndex); } if(ad.getWindow() != null) ad.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); ad.findViewById(R.id.buttonInputBoxOK).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); String newName = ((EditText) ad.findViewById(R.id.editTextInputBox)).getText().toString(); mCurrentCustomer.renameFile(count, newName); refreshFiles(); } }); ad.show(); } }); ImageButton buttonFileRemove = linearLayoutFile.findViewById(R.id.buttonFileRemove); buttonFileRemove.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mCurrentCustomer.removeFile(count); refreshFiles(); } }); linearLayoutFilesView.addView(linearLayoutFile); counter ++; } } private void updateCustomerObjectByInputs() { mCurrentCustomer.mTitle = mEditTextTitle.getText().toString(); mCurrentCustomer.mFirstName = mEditTextFirstName.getText().toString(); mCurrentCustomer.mLastName = mEditTextLastName.getText().toString(); mCurrentCustomer.mPhoneHome = mEditTextPhoneHome.getText().toString(); mCurrentCustomer.mPhoneMobile = mEditTextPhoneMobile.getText().toString(); mCurrentCustomer.mPhoneWork = mEditTextPhoneWork.getText().toString(); mCurrentCustomer.mEmail = mEditTextEmail.getText().toString().trim(); mCurrentCustomer.mStreet = mEditTextStreet.getText().toString(); mCurrentCustomer.mZipcode = mEditTextZipcode.getText().toString(); mCurrentCustomer.mCity = mEditTextCity.getText().toString(); mCurrentCustomer.mCountry = mEditTextCountry.getText().toString(); mCurrentCustomer.mBirthday = mBirthdayCalendar == null ? null : mBirthdayCalendar.getTime(); mCurrentCustomer.mLastModified = new Date(); mCurrentCustomer.mNotes = mEditTextNotes.getText().toString(); mCurrentCustomer.mCustomerGroup = mEditTextGroup.getText().toString(); mCurrentCustomer.mNewsletter = mCheckBoxNewsletter.isChecked(); for(CustomField cf : mCustomFields) { String newValue = ""; if(cf.mEditViewReference instanceof EditText) { newValue = ((EditText)cf.mEditViewReference).getText().toString(); if(cf.mType == 3) { try { // try parse date and save it in normalized format Date selectedDate = DateControl.birthdayDateFormat.parse(newValue); newValue = CustomerDatabase.dateToStringRaw(selectedDate); } catch(Exception ignored) {} } } else if(cf.mEditViewReference instanceof Spinner) { CustomField selectedItem = ((CustomField) ((Spinner)cf.mEditViewReference).getSelectedItem()); if(selectedItem != null) newValue = selectedItem.mTitle; } mCurrentCustomer.updateOrCreateCustomField(cf.mTitle, newValue); } } public void setCustomerBirthday(View v) { if(mBirthdayCalendar == null) { mBirthdayCalendar = Calendar.getInstance(); } final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { mBirthdayCalendar.set(Calendar.YEAR, year); mBirthdayCalendar.set(Calendar.MONTH, monthOfYear); mBirthdayCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); mButtonBirthday.setText(DateControl.birthdayDateFormat.format(mBirthdayCalendar.getTime())); } }; new DatePickerDialog( CustomerEditActivity.this, date, mBirthdayCalendar.get(Calendar.YEAR), mBirthdayCalendar.get(Calendar.MONTH), mBirthdayCalendar.get(Calendar.DAY_OF_MONTH) ).show(); } public void removeCustomerBirthday(View v) { mBirthdayCalendar = null; mButtonBirthday.setText(getString(R.string.no_date_set)); } public void setCustomerImage(View v) { final Dialog ad = new Dialog(this); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_customer_image); ad.findViewById(R.id.buttonConsentFromCamera).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(ContextCompat.checkSelfPermission(me, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(me, new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST); } else { Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); me.startActivityForResult(cameraIntent, CUSTOMER_IMAGE_CAMERA_REQUEST); } ad.dismiss(); } }); ad.findViewById(R.id.buttonConsentFromGallery).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, getString(R.string.choose_from_gallery)), CUSTOMER_IMAGE_PICK_REQUEST); } }); ad.findViewById(R.id.buttonConsentCancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); } }); ad.show(); } public void removeCustomerImage(View v) { mCurrentCustomer.mImage = new byte[0]; refreshImage(); } public void onClickAddFile(View v) { if(mFc == null || !mFc.unlockedFiles) { dialogInApp(getResources().getString(R.string.feature_locked), getResources().getString(R.string.feature_locked_text)); return; } final Dialog ad = new Dialog(this); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_file_add); ad.findViewById(R.id.buttonConsentFromCamera).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(ContextCompat.checkSelfPermission(me, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(me, new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST); } else { Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); Uri photoURI = FileProvider.getUriForFile(me, "de.georgsieber.customerdb.provider", StorageControl.getStorageImageTemp(me)); cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI); me.startActivityForResult(cameraIntent, FILE_CAMERA_REQUEST); } ad.dismiss(); } }); ad.findViewById(R.id.buttonConsentFromGallery).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); Intent intent = new Intent(); intent.setType("*/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, getString(R.string.choose_from_gallery)), FILE_PICK_REQUEST); } }); ad.findViewById(R.id.buttonConsentFromTouchscreen).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); Intent intent = new Intent(me, DrawActivity.class); startActivityForResult(intent, FILE_DRAW_REQUEST); } }); ad.findViewById(R.id.buttonConsentCancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); } }); ad.show(); } @SuppressWarnings({"SwitchStatementWithTooFewBranches", "UnnecessaryReturnStatement"}) @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch(requestCode) { case CAMERA_PERMISSION_REQUEST: if(grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, getString(R.string.please_grant_camera_permission), Toast.LENGTH_LONG).show(); } return; } } }
36,287
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
MainActivity.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/MainActivity.java
package de.georgsieber.customerdb; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.Dialog; import android.app.SearchManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.res.ColorStateList; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.print.PrintAttributes; import android.print.PrintManager; import androidx.activity.result.ActivityResult; import androidx.activity.result.ActivityResultCallback; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.NonNull; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.android.material.navigation.NavigationView; import com.google.android.material.snackbar.Snackbar; import androidx.appcompat.app.AppCompatActivity; import androidx.core.view.GravityCompat; import androidx.drawerlayout.widget.DrawerLayout; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.widget.Toolbar; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.RadioButton; import android.widget.SearchView; import android.widget.Spinner; import android.widget.TextView; import java.io.File; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.List; import de.georgsieber.customerdb.importexport.CalendarCsvBuilder; import de.georgsieber.customerdb.importexport.CalendarIcsBuilder; import de.georgsieber.customerdb.importexport.CustomerCsvBuilder; import de.georgsieber.customerdb.importexport.CustomerVcfBuilder; import de.georgsieber.customerdb.importexport.VoucherCsvBuilder; import de.georgsieber.customerdb.model.CustomField; import de.georgsieber.customerdb.model.Customer; import de.georgsieber.customerdb.model.CustomerAppointment; import de.georgsieber.customerdb.model.CustomerCalendar; import de.georgsieber.customerdb.model.Voucher; import de.georgsieber.customerdb.print.CustomerPrintDocumentAdapter; import de.georgsieber.customerdb.tools.ColorControl; import de.georgsieber.customerdb.tools.CommonDialog; import de.georgsieber.customerdb.tools.DateControl; import de.georgsieber.customerdb.tools.StorageControl; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { MainActivity me = this; ListView mListViewCustomers; ListView mListViewVouchers; Menu mOptionMenu; Menu mDrawerMenu; NavigationView mNavigationView; BottomNavigationView mBottomNavigationView; Button mButtonCalendarViewDay; CalendarFragment mCalendarFragment; Calendar mCalendarViewCalendar = Calendar.getInstance(); CustomerDatabase mDb; List<Customer> mCustomers = new ArrayList<>(); List<Voucher> mVouchers = new ArrayList<>(); private CustomerAdapter mCurrentCustomerAdapter; private VoucherAdapter mCurrentVoucherAdapter; private CustomerAdapter.checkedChangedListener mCustomerCheckedChangedListener; private VoucherAdapter.checkedChangedListener mVoucherCheckedChangedListener; private FeatureCheck mFc; private boolean isInputOnlyModeActive = false; private boolean isLockActive = false; int mRemoteDatabaseConnType = 0; String mRemoteDatabaseConnURL = ""; String mRemoteDatabaseConnUsername = ""; String mRemoteDatabaseConnPassword = ""; String mCurrency = "?"; String mIomPassword = ""; long mCurrentCalendarImportSelectedId = -1; public static final String PREFS_NAME = "CustomerDBprefs"; private SharedPreferences mSettings; private final static int NEW_CUSTOMER_REQUEST = 0; private final static int VIEW_CUSTOMER_REQUEST = 1; private final static int SETTINGS_REQUEST = 2; private final static int PICK_CUSTOMER_VCF_REQUEST = 4; private final static int PICK_CUSTOMER_CSV_REQUEST = 5; private final static int BIRTHDAY_REQUEST = 6; private final static int ABOUT_REQUEST = 7; private final static int NEW_VOUCHER_REQUEST = 8; private final static int VIEW_VOUCHER_REQUEST = 9; private final static int PICK_VOUCHER_CSV_REQUEST = 10; private final static int NEW_APPOINTMENT_REQUEST = 11; private final static int PICK_CALENDAR_ICS_REQUEST = 12; private final static int PICK_CALENDAR_CSV_REQUEST = 13; private final static int SCAN_REQUEST = 14; private ActivityResultLauncher<Intent> mResultHandlerExportMoveFile; private File mCurrentExportFile; @Override protected void onCreate(Bundle savedInstanceState) { // init settings mSettings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE); // init activity view super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // init toolbar Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); // init drawer menu DrawerLayout drawer = findViewById(R.id.drawerLayoutMain); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); mNavigationView = findViewById(R.id.navigationViewMain); mDrawerMenu = mNavigationView.getMenu(); mNavigationView.setNavigationItemSelectedListener(this); // init local database mDb = new CustomerDatabase(this); // init activity result handler mResultHandlerExportMoveFile = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() { @Override public void onActivityResult(ActivityResult result) { if(result.getResultCode() == RESULT_OK) { Uri uri = result.getData().getData(); if(uri != null) { try { StorageControl.moveFile(mCurrentExportFile, uri, me); } catch(Exception e) { CommonDialog.show(me, getString(R.string.error), e.getMessage(), CommonDialog.TYPE.FAIL, false); } } } } } ); // init bottom navigation mBottomNavigationView = findViewById(R.id.bottomNavigation); mBottomNavigationView.setOnNavigationItemSelectedListener( new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { refreshView(item.getItemId()); return true; } } ); refreshView(null); // load sync settings loadSettings(); // init views mListViewCustomers = findViewById(R.id.mainCustomerList); mListViewCustomers.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Customer customer = (Customer) mListViewCustomers.getItemAtPosition(position); Intent myIntent = new Intent(me, CustomerDetailsActivity.class); myIntent.putExtra("customer-id", customer.mId); me.startActivityForResult(myIntent, VIEW_CUSTOMER_REQUEST); } }); mListViewCustomers.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { mCurrentCustomerAdapter.setShowCheckbox(!mCurrentCustomerAdapter.getShowCheckbox()); if(!mCurrentCustomerAdapter.getShowCheckbox()) { mCurrentCustomerAdapter.setAllChecked(false); } return true; } }); mCalendarFragment = (CalendarFragment) getSupportFragmentManager().findFragmentById(R.id.fragmentCalendar); mButtonCalendarViewDay = findViewById(R.id.buttonCalendarChangeDay); mListViewVouchers = findViewById(R.id.mainVoucherList); mListViewVouchers.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Voucher voucher = (Voucher) mListViewVouchers.getItemAtPosition(position); Intent myIntent = new Intent(me, VoucherDetailsActivity.class); myIntent.putExtra("voucher-id", voucher.mId); me.startActivityForResult(myIntent, VIEW_VOUCHER_REQUEST); } }); mListViewVouchers.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { mCurrentVoucherAdapter.setShowCheckbox(!mCurrentVoucherAdapter.getShowCheckbox()); if(!mCurrentVoucherAdapter.getShowCheckbox()) { mCurrentVoucherAdapter.setAllChecked(false); } return true; } }); mCustomerCheckedChangedListener = new CustomerAdapter.checkedChangedListener() { @Override public void checkedChanged(ArrayList<Customer> checked) { refreshSelectedCountInfo(null); } }; mVoucherCheckedChangedListener = new VoucherAdapter.checkedChangedListener() { @Override public void checkedChanged(ArrayList<Voucher> checked) { refreshSelectedCountInfo(null); } }; refreshCustomersFromLocalDatabase(); refreshAppointmentsFromLocalDatabase(); refreshVouchersFromLocalDatabase(); // init add buttons (FloatingActionButtons) findViewById(R.id.fabAdd).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { switch(mBottomNavigationView.getSelectedItemId()) { case R.id.bottomnav_customers: me.startActivityForResult(new Intent(me, CustomerEditActivity.class), NEW_CUSTOMER_REQUEST); break; case R.id.bottomnav_calendar: Intent intent = new Intent(me, CalendarAppointmentEditActivity.class); intent.putExtra("appointment-day", mCalendarViewCalendar); me.startActivityForResult(intent, NEW_APPOINTMENT_REQUEST); break; case R.id.bottomnav_vouchers: me.startActivityForResult(new Intent(me, VoucherEditActivity.class), NEW_VOUCHER_REQUEST); break; } } }); findViewById(R.id.buttonAddCustomerInputOnlyMode).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { me.startActivityForResult(new Intent(me, CustomerEditActivity.class), NEW_CUSTOMER_REQUEST); } }); findViewById(R.id.buttonInputOnlyModeUnlock).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onToggleInputOnlyModeButtonClick(); } }); findViewById(R.id.buttonLockUnlock).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onToggleLockButtonClick(); } }); // show dialogs //dialogNews(); dialogEula(); } private void refreshView(Integer itemId) { if(itemId == null) itemId = mBottomNavigationView.getSelectedItemId(); findViewById(R.id.mainCustomerList).setVisibility(View.INVISIBLE); findViewById(R.id.mainCalendarView).setVisibility(View.INVISIBLE); findViewById(R.id.mainVoucherList).setVisibility(View.INVISIBLE); if(isLockActive || isInputOnlyModeActive) { return; } boolean state = true; switch(itemId) { case R.id.bottomnav_customers: findViewById(R.id.mainCustomerList).setVisibility(View.VISIBLE); state = true; break; case R.id.bottomnav_calendar: findViewById(R.id.mainCalendarView).setVisibility(View.VISIBLE); state = false; break; case R.id.bottomnav_vouchers: findViewById(R.id.mainVoucherList).setVisibility(View.VISIBLE); state = false; break; } if(mDrawerMenu != null) { mDrawerMenu.findItem(R.id.nav_input_only_mode).setEnabled(state); mDrawerMenu.findItem(R.id.nav_lock).setEnabled(state); mDrawerMenu.findItem(R.id.nav_filter).setEnabled(state); mDrawerMenu.findItem(R.id.nav_sort).setEnabled(state); mDrawerMenu.findItem(R.id.nav_newsletter).setEnabled(state); mDrawerMenu.findItem(R.id.nav_birthdays).setEnabled(state); } refreshSelectedCountInfo(itemId); } void refreshCustomersFromLocalDatabase() { refreshCustomersFromLocalDatabase(null); } private void refreshCustomersFromLocalDatabase(String search) { if(mCurrentGroup == null && mCurrentCity == null && mCurrentCountry == null) { mCustomers = mDb.getCustomers(search, false, false, null); resetActionBarTitle(); } else { List<Customer> newCustomerList = new ArrayList<>(); for(Customer c : mDb.getCustomers(search, false, false, null)) { if((mCurrentGroup == null || c.mCustomerGroup.equals(mCurrentGroup)) && (mCurrentCity == null || c.mCity.equals(mCurrentCity)) && (mCurrentCountry == null || c.mCountry.equals(mCurrentCountry)) ) { newCustomerList.add(c); } } mCustomers = newCustomerList; if(getSupportActionBar() != null) getSupportActionBar().setTitle( ((mCurrentGroup != null ? (mCurrentGroup.equals("") ? getString(R.string.empty) : mCurrentGroup) : "") + " " + (mCurrentCity != null ? (mCurrentCity.equals("") ? getString(R.string.empty) : mCurrentCity) : "") + " " + (mCurrentCountry != null ? (mCurrentCountry.equals("") ? getString(R.string.empty) : mCurrentCountry) : "")).trim() ); } mCurrentCustomerAdapter = new CustomerAdapter(this, mCustomers, mCustomerCheckedChangedListener); mListViewCustomers.setAdapter(mCurrentCustomerAdapter); refreshCount(); refreshSelectedCountInfo(null); } void refreshAppointmentsFromLocalDatabase() { mCalendarFragment.show(mDb.getCalendars(false), mCalendarViewCalendar.getTime()); mButtonCalendarViewDay.setText(DateControl.birthdayDateFormat.format(mCalendarViewCalendar.getTime())); } void refreshVouchersFromLocalDatabase() { refreshVouchersFromLocalDatabase(null); } private void refreshVouchersFromLocalDatabase(String search) { mVouchers = mDb.getVouchers(search, false, null); resetActionBarTitle(); mCurrentVoucherAdapter = new VoucherAdapter(this, mVouchers, mCurrency, mVoucherCheckedChangedListener); mListViewVouchers.setAdapter(mCurrentVoucherAdapter); refreshCount(); refreshSelectedCountInfo(null); } public void onClickChangeCalendarViewDay(View v) { final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { mCalendarViewCalendar.set(Calendar.YEAR, year); mCalendarViewCalendar.set(Calendar.MONTH, monthOfYear); mCalendarViewCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); refreshAppointmentsFromLocalDatabase(); } }; new DatePickerDialog( this, date, mCalendarViewCalendar.get(Calendar.YEAR), mCalendarViewCalendar.get(Calendar.MONTH), mCalendarViewCalendar.get(Calendar.DAY_OF_MONTH) ).show(); } public void onClickPrevCalendarViewDay(View v) { mCalendarViewCalendar.add(Calendar.DAY_OF_MONTH, -1); refreshAppointmentsFromLocalDatabase(); } public void onClickNextCalendarViewDay(View v) { mCalendarViewCalendar.add(Calendar.DAY_OF_MONTH, 1); refreshAppointmentsFromLocalDatabase(); } private void loadSettings() { // restore remote database connection preferences mRemoteDatabaseConnType = mSettings.getInt("webapi-type", 0); mRemoteDatabaseConnURL = mSettings.getString("webapi-url", ""); mRemoteDatabaseConnUsername = mSettings.getString("webapi-username", ""); mRemoteDatabaseConnPassword = mSettings.getString("webapi-password", ""); mCurrency = mSettings.getString("currency", "€"); mIomPassword = mSettings.getString("iom-password", ""); isInputOnlyModeActive = mSettings.getBoolean("iom", false); isLockActive = mSettings.getBoolean("locked", false); // migrate legacy API settings if(mRemoteDatabaseConnType == 0 && !mRemoteDatabaseConnURL.equals("") && !mRemoteDatabaseConnPassword.equals("") && mRemoteDatabaseConnUsername.equals("")) { SharedPreferences.Editor editor = mSettings.edit(); editor.putInt("webapi-type", 3); editor.apply(); mRemoteDatabaseConnType = 3; } // init colors ColorControl.updateActionBarColor(this, mSettings); ColorControl.updateAccentColor(findViewById(R.id.mainInputOnlyOverlay), mSettings); ColorControl.updateAccentColor(findViewById(R.id.mainLockOverlay), mSettings); ColorControl.updateAccentColor(findViewById(R.id.fabAdd), mSettings); ColorControl.updateAccentColor(findViewById(R.id.buttonCalendarChangeDay), mSettings); ColorStateList colorStates = new ColorStateList( new int[][] { new int[] {-android.R.attr.state_checked}, new int[] { android.R.attr.state_checked} }, new int[] { getResources().getColor(R.color.bottomNavigationViewInactiveColor), ColorControl.getColorFromSettings(mSettings) }); mBottomNavigationView.setItemTextColor(colorStates); mBottomNavigationView.setItemIconTintList(colorStates); View headerView = mNavigationView.getHeaderView(0); if(headerView != null) ColorControl.updateAccentColor(headerView.findViewById(R.id.linearLayoutDrawerNavHeader), mSettings); // refresh backup note if(headerView != null) { if(mRemoteDatabaseConnType == 0) { headerView.findViewById(R.id.linearLayoutDrawerBackupNote).setVisibility(View.VISIBLE); } else { headerView.findViewById(R.id.linearLayoutDrawerBackupNote).setVisibility(View.GONE); } } // load in-app purchases mFc = new FeatureCheck(this); mFc.setFeatureCheckReadyListener(new FeatureCheck.featureCheckReadyListener() { @Override public void featureCheckReady(boolean fetchSuccess) { if(mFc.unlockedCommercialUsage) { (findViewById(R.id.textViewInputOnlyModeNotLicensed)).setVisibility(View.GONE); } } }); mFc.init(); // init logo image File logo = StorageControl.getStorageLogo(this); ImageView backgroundLogo = findViewById(R.id.imageBackgroundLogo); if(logo.exists()) { try { Bitmap myBitmap = BitmapFactory.decodeFile(logo.getAbsolutePath()); ((ImageView) findViewById(R.id.imageViewInputOnlyModeLogo)).setImageBitmap(myBitmap); ((ImageView) findViewById(R.id.imageViewLockLogo)).setImageBitmap(myBitmap); backgroundLogo.setImageBitmap(myBitmap); backgroundLogo.setAlpha(0.2f); } catch(Exception e) { e.printStackTrace(); } } else { backgroundLogo.setImageResource(R.drawable.ic_customerdb_gray); backgroundLogo.setAlpha(0.05f); } } static void setUnsyncedChanges(Context c) { SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("unsynced-changes", true); editor.apply(); } static void setChangesSynced(Context c) { SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("unsynced-changes", false); editor.apply(); } void refreshSyncIcon() { if(mOptionMenu == null) return; if(mSettings.getBoolean("unsynced-changes", false)) { if(mRemoteDatabaseConnType == 1 || mRemoteDatabaseConnType == 2) { mOptionMenu.findItem(R.id.action_sync).setIcon(getResources().getDrawable(R.drawable.ic_sync_problem_white_24dp)); } } else { mOptionMenu.findItem(R.id.action_sync).setIcon(getResources().getDrawable(R.drawable.ic_sync_white_24dp)); } } @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { DrawerLayout drawer = findViewById(R.id.drawerLayoutMain); switch(item.getItemId()) { case R.id.nav_information: Intent aboutIntent = new Intent(me, AboutActivity.class); startActivityForResult(aboutIntent, ABOUT_REQUEST); break; case R.id.nav_settings: Intent settingsIntent = new Intent(me, SettingsActivity.class); startActivityForResult(settingsIntent, SETTINGS_REQUEST); break; case R.id.nav_input_only_mode: drawer.closeDrawer(GravityCompat.START); onToggleInputOnlyModeButtonClick(); break; case R.id.nav_lock: drawer.closeDrawer(GravityCompat.START); onToggleLockButtonClick(); break; case R.id.nav_filter: drawer.closeDrawer(GravityCompat.START); filterDialog(); break; case R.id.nav_sort: drawer.closeDrawer(GravityCompat.START); sortDialog(); break; case R.id.nav_newsletter: drawer.closeDrawer(GravityCompat.START); doNewsletter(); break; case R.id.nav_birthdays: drawer.closeDrawer(GravityCompat.START); openBirthdaysIntent(); break; case R.id.nav_import_export: drawer.closeDrawer(GravityCompat.START); if(mBottomNavigationView.getSelectedItemId() == R.id.bottomnav_customers) menuImportExportCustomer(); else if(mBottomNavigationView.getSelectedItemId() == R.id.bottomnav_vouchers) menuImportExportVoucher(); else if(mBottomNavigationView.getSelectedItemId() == R.id.bottomnav_calendar) menuImportExportCalendar(); break; case R.id.nav_remove_selected: drawer.closeDrawer(GravityCompat.START); removeSelectedDialog(); break; case R.id.nav_exit: mDb.close(); finish(); break; } return true; } @Override public void onBackPressed() { DrawerLayout drawer = findViewById(R.id.drawerLayoutMain); if(drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); mOptionMenu = menu; enableDisableInputOnlyMode(isInputOnlyModeActive); enableDisableLock(isLockActive); refreshSyncIcon(); SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); if(manager == null) return false; SearchView search = (SearchView) menu.findItem(R.id.action_search).getActionView(); search.setSearchableInfo(manager.getSearchableInfo(getComponentName())); search.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { refreshCustomersFromLocalDatabase(query); refreshVouchersFromLocalDatabase(query); resetActionBarTitle(); return false; } @Override public boolean onQueryTextChange(String query) { if(query == null || query.equals("")) { refreshCustomersFromLocalDatabase(query); refreshVouchersFromLocalDatabase(query); resetActionBarTitle(); } return true; } }); return true; } @SuppressWarnings("SwitchStatementWithTooFewBranches") @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.action_sync: doSync(); return true; } return super.onOptionsItemSelected(item); } @Override public void onResume() { super.onResume(); incrementStartedCounter(); refreshSyncIcon(); checkSnackbarMessage(); showAdOtherApps(); } @Override public void onDestroy() { super.onDestroy(); StorageControl.deleteTempFiles(this); } private void doSync() { if(mRemoteDatabaseConnType == 1 || mRemoteDatabaseConnType == 2) { if(isNetworkConnected()) { dialogSyncProgress(); CustomerDatabaseApi cda = null; if(mRemoteDatabaseConnType == 1) { cda = new CustomerDatabaseApi(this, mSettings.getString("sync-purchase-token", ""), mRemoteDatabaseConnUsername, mRemoteDatabaseConnPassword, mDb ); } else if(mRemoteDatabaseConnType == 2) { cda = new CustomerDatabaseApi(this, mSettings.getString("sync-purchase-token", ""), mRemoteDatabaseConnURL, mRemoteDatabaseConnUsername, mRemoteDatabaseConnPassword, mDb ); } cda.setReadyListener(new CustomerDatabaseApi.readyListener() { @Override public void ready(final Exception e) { runOnUiThread(new Runnable() { @Override public void run() { if(e == null) { mSettings.edit().putLong("last-successful-sync", new Date().getTime()).apply(); MainActivity.setChangesSynced(me); refreshCustomersFromLocalDatabase(); refreshVouchersFromLocalDatabase(); refreshAppointmentsFromLocalDatabase(); dialogSyncSuccess(); } else { dialogSyncFail(e.getMessage()); } refreshSyncIcon(); } }); } }); cda.sync(new Date(mSettings.getLong("last-successful-sync", 0))); } else { CommonDialog.show(this, getResources().getString(R.string.no_network_conn_title), getResources().getString(R.string.no_network_conn_text), CommonDialog.TYPE.WARN, false ); } } else { dialogSyncNotConfigured(); } } @SuppressLint("SourceLockedOrientationActivity") private void lockCurrentOrientation(boolean lock) { if(lock) { int currentOrientation = getResources().getConfiguration().orientation; if(currentOrientation == Configuration.ORIENTATION_LANDSCAPE) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE); } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT); } } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); } } private void removeSelectedDialog() { switch(mBottomNavigationView.getSelectedItemId()) { case R.id.bottomnav_customers: final ArrayList<Customer> selectedCustomers = mCurrentCustomerAdapter.getCheckedItems(); if(selectedCustomers.size() == 0) { CommonDialog.show(this, getResources().getString(R.string.nothing_selected), getResources().getString(R.string.select_at_least_one), CommonDialog.TYPE.WARN, false); } else { AlertDialog.Builder ad = new AlertDialog.Builder(me); ad.setPositiveButton(getResources().getString(R.string.delete), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { for(Customer c : selectedCustomers) { mDb.removeCustomer(c); } refreshCustomersFromLocalDatabase(); }}); ad.setNegativeButton(getResources().getString(R.string.abort), null); ad.setTitle(getResources().getString(R.string.reallydelete_title)); ad.setMessage( getResources().getQuantityString(R.plurals.delete_records, selectedCustomers.size(), selectedCustomers.size()) ); ad.setIcon(getResources().getDrawable(R.drawable.remove)); ad.show(); } break; case R.id.bottomnav_vouchers: final ArrayList<Voucher> selectedVouchers = mCurrentVoucherAdapter.getCheckedItems(); if(selectedVouchers.size() == 0) { CommonDialog.show(this, getResources().getString(R.string.nothing_selected), getResources().getString(R.string.select_at_least_one), CommonDialog.TYPE.WARN, false); } else { AlertDialog.Builder ad = new AlertDialog.Builder(me); ad.setPositiveButton(getResources().getString(R.string.delete), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { for(Voucher v : selectedVouchers) { mDb.removeVoucher(v); } refreshVouchersFromLocalDatabase(); }}); ad.setNegativeButton(getResources().getString(R.string.abort), null); ad.setTitle(getResources().getString(R.string.reallydelete_title)); ad.setMessage( getResources().getQuantityString(R.plurals.delete_records, selectedVouchers.size(), selectedVouchers.size()) ); ad.setIcon(getResources().getDrawable(R.drawable.remove)); ad.show(); } break; } } private void sortDialog() { List<CustomField> customFields = mDb.getCustomFields(); final Dialog ad = new Dialog(this); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_sort); ArrayAdapter<CustomField> a = new ArrayAdapter<>(this, R.layout.item_list_simple, customFields); Spinner s = ad.findViewById(R.id.spinnerSort); s.setAdapter(a); ad.show(); ad.findViewById(R.id.buttonSort).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { RadioButton radioButtonSortLastName = ad.findViewById(R.id.radioButtonSortLastName); RadioButton radioButtonSortFirstName = ad.findViewById(R.id.radioButtonSortFirstName); RadioButton radioButtonSortLastModified = ad.findViewById(R.id.radioButtonSortLastModified); RadioButton radioButtonSortCustomField = ad.findViewById(R.id.radioButtonSortCustomField); boolean sortAsc = ((RadioButton) ad.findViewById(R.id.radioButtonSortAsc)).isChecked(); if(radioButtonSortLastName.isChecked()) { sort(CustomerComparator.FIELD.LAST_NAME, sortAsc); } else if(radioButtonSortFirstName.isChecked()) { sort(CustomerComparator.FIELD.FIRST_NAME, sortAsc); } else if(radioButtonSortLastModified.isChecked()) { sort(CustomerComparator.FIELD.LAST_MODIFIED, sortAsc); } else if(radioButtonSortCustomField.isChecked()) { CustomField customField = (CustomField) ((Spinner) ad.findViewById(R.id.spinnerSort)).getSelectedItem(); if(customField != null) { String customFieldName = customField.toString(); sort(customFieldName, sortAsc); } } ad.dismiss(); } }); ad.findViewById(R.id.buttonSortCancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { refreshCustomersFromLocalDatabase(); ad.dismiss(); } }); } private void sort(String fieldTitle, boolean ascending) { mCustomers = mDb.getCustomers(null, false, false, null); Collections.sort(mCustomers, new CustomerComparator(fieldTitle, ascending)); mCurrentCustomerAdapter = new CustomerAdapter(this, mCustomers, mCustomerCheckedChangedListener); mListViewCustomers.setAdapter(mCurrentCustomerAdapter); } private void sort(CustomerComparator.FIELD field, boolean ascending) { mCustomers = mDb.getCustomers(null, false, false, null); Collections.sort(mCustomers, new CustomerComparator(field, ascending)); mCurrentCustomerAdapter = new CustomerAdapter(this, mCustomers, mCustomerCheckedChangedListener); mListViewCustomers.setAdapter(mCurrentCustomerAdapter); } private void onToggleLockButtonClick() { if(isLockActive) { // password check final Dialog ad = new Dialog(this); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_unlock_password); Button button = ad.findViewById(R.id.buttonInputOnlyModeUnlock); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String passwordInput = ((EditText) ad.findViewById(R.id.editTextInputOnlyModeUnlockPassword)).getText().toString(); if(passwordInput.equals(mIomPassword)) { ad.dismiss(); enableDisableLock(false); } else { ad.dismiss(); CommonDialog.show(me, getResources().getString(R.string.password_incorrect), "", CommonDialog.TYPE.FAIL, false); } } }); if(ad.getWindow() != null) ad.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); ad.show(); } else { if(mFc.unlockedInputOnlyMode) { if(mIomPassword.equals("")) { CommonDialog.show(this, "", getString(R.string.please_set_password_first), CommonDialog.TYPE.WARN, false); } else { enableDisableLock(true); } } else { dialogInApp(getResources().getString(R.string.feature_locked), getResources().getString(R.string.feature_locked_text)); } } } private void enableDisableLock(boolean state) { if(isInputOnlyModeActive) return; isLockActive = state; SharedPreferences.Editor editor = mSettings.edit(); editor.putBoolean("locked", state); editor.apply(); if(mOptionMenu != null) { mOptionMenu.findItem(R.id.action_search).setVisible(!state); } if(mDrawerMenu != null) { mDrawerMenu.findItem(R.id.nav_input_only_mode).setEnabled(!state); mDrawerMenu.findItem(R.id.nav_lock).setEnabled(!state); mDrawerMenu.findItem(R.id.nav_filter).setEnabled(!state); mDrawerMenu.findItem(R.id.nav_sort).setEnabled(!state); mDrawerMenu.findItem(R.id.nav_newsletter).setEnabled(!state); mDrawerMenu.findItem(R.id.nav_birthdays).setEnabled(!state); mDrawerMenu.findItem(R.id.nav_import_export).setEnabled(!state); mDrawerMenu.findItem(R.id.nav_settings).setEnabled(!state); mDrawerMenu.findItem(R.id.nav_remove_selected).setEnabled(!state); mDrawerMenu.findItem(R.id.nav_exit).setEnabled(!state); } final View overlay = findViewById(R.id.mainLockOverlay); if(state) { findViewById(R.id.fabAdd).setVisibility(View.GONE); mBottomNavigationView.setVisibility(View.GONE); overlay.setAlpha(0.0f); overlay.setVisibility(View.VISIBLE); overlay.animate().alpha(1f).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); overlay.setAlpha(1f); } }); } else { findViewById(R.id.fabAdd).setVisibility(View.VISIBLE); mBottomNavigationView.setVisibility(View.VISIBLE); overlay.animate().alpha(0.0f).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); overlay.setVisibility(View.GONE); } }); } refreshView(null); } private void onToggleInputOnlyModeButtonClick() { if(isInputOnlyModeActive) { // password check final Dialog ad = new Dialog(this); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_unlock_password); Button button = ad.findViewById(R.id.buttonInputOnlyModeUnlock); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String passwordInput = ((EditText) ad.findViewById(R.id.editTextInputOnlyModeUnlockPassword)).getText().toString(); if(passwordInput.equals(mIomPassword)) { ad.dismiss(); enableDisableInputOnlyMode(false); } else { ad.dismiss(); CommonDialog.show(me, getResources().getString(R.string.password_incorrect), "", CommonDialog.TYPE.FAIL, false); } } }); if(ad.getWindow() != null) ad.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); ad.show(); } else { if(mFc.unlockedInputOnlyMode) { if(mIomPassword.equals("")) { CommonDialog.show(this, "", getString(R.string.please_set_password_first), CommonDialog.TYPE.WARN, false); } else { enableDisableInputOnlyMode(true); if(!mSettings.getBoolean("input-only-mode-instructions-shown", false)) { CommonDialog.show(this, getString(R.string.input_only_mode), getString(R.string.input_only_mode_instructions), CommonDialog.TYPE.NONE, false); mSettings.edit().putBoolean("input-only-mode-instructions-shown", true).apply(); } } } else { dialogInApp(getResources().getString(R.string.feature_locked), getResources().getString(R.string.feature_locked_text)); } } } private void enableDisableInputOnlyMode(boolean state) { if(isLockActive) return; isInputOnlyModeActive = state; SharedPreferences.Editor editor = mSettings.edit(); editor.putBoolean("iom", state); editor.apply(); if(mOptionMenu != null) { mOptionMenu.findItem(R.id.action_search).setVisible(!state); } if(mDrawerMenu != null) { mDrawerMenu.findItem(R.id.nav_input_only_mode).setEnabled(!state); mDrawerMenu.findItem(R.id.nav_lock).setEnabled(!state); mDrawerMenu.findItem(R.id.nav_filter).setEnabled(!state); mDrawerMenu.findItem(R.id.nav_sort).setEnabled(!state); mDrawerMenu.findItem(R.id.nav_newsletter).setEnabled(!state); mDrawerMenu.findItem(R.id.nav_birthdays).setEnabled(!state); mDrawerMenu.findItem(R.id.nav_import_export).setEnabled(!state); mDrawerMenu.findItem(R.id.nav_settings).setEnabled(!state); mDrawerMenu.findItem(R.id.nav_remove_selected).setEnabled(!state); mDrawerMenu.findItem(R.id.nav_exit).setEnabled(!state); } final View overlay = findViewById(R.id.mainInputOnlyOverlay); if(state) { findViewById(R.id.fabAdd).setVisibility(View.GONE); mBottomNavigationView.setVisibility(View.GONE); overlay.setAlpha(0.0f); overlay.setVisibility(View.VISIBLE); overlay.animate().alpha(1f).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); overlay.setAlpha(1f); } }); } else { findViewById(R.id.fabAdd).setVisibility(View.VISIBLE); mBottomNavigationView.setVisibility(View.VISIBLE); overlay.animate().alpha(0.0f).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); overlay.setVisibility(View.GONE); } }); } refreshView(null); } private void openBirthdaysIntent() { int previewDays = BirthdayActivity.getBirthdayPreviewDays(mSettings); ArrayList<Customer> birthdays = BirthdayActivity.getSoonBirthdayCustomers(mCustomers, previewDays); if(birthdays.size() == 0) { CommonDialog.show(this, getResources().getQuantityString(R.plurals.nobirthdayssoon, previewDays, previewDays), "", CommonDialog.TYPE.WARN, false); return; } me.startActivityForResult(new Intent(me, BirthdayActivity.class), BIRTHDAY_REQUEST); } public void resetActionBarTitle() { if(getSupportActionBar() != null) getSupportActionBar().setTitle(getResources().getString(R.string.app_name)); } private boolean isNetworkConnected() { ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); if(connectivityManager == null) return true; NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } private void checkSnackbarMessage() { //Log.i("FEATURE", Integer.toString(mSettings.getInt("started", 0))); if((mSettings.getInt("started", 0) % 15) == 0) { if(mFc != null && mFc.isReady) { if(!mFc.unlockedCommercialUsage) { if(mRemoteDatabaseConnURL.equals("")) { showAdLicense(); } else { Log.i("FEATURE", "Licensing information hidden because connected with API."); checkBirthdays(); } } else { Log.i("FEATURE", "Licensing information hidden because commercial usage allowed."); checkBirthdays(); } } else { Log.i("FEATURE", "Licensing information hidden because feature check not ready yet."); checkBirthdays(); } } else { checkBirthdays(); } } private void checkBirthdays() { int previewDays = BirthdayActivity.getBirthdayPreviewDays(mSettings); ArrayList<Customer> birthdays = BirthdayActivity.getSoonBirthdayCustomers(mCustomers, previewDays); if(birthdays.size() > 0 && !isInputOnlyModeActive && !isLockActive) { Snackbar.make( findViewById(R.id.coordinatorLayoutInner), getResources().getQuantityString(R.plurals.birthdayssoon, birthdays.size(), birthdays.size()), Snackbar.LENGTH_LONG) .setAction(getResources().getString(R.string.view), new View.OnClickListener() { @Override public void onClick(View v) { openBirthdaysIntent(); } }) .show(); } } private Snackbar mCheckedCountInfoSnackbar; private void refreshSelectedCountInfo(Integer itemId) { if(mBottomNavigationView == null) return; if(itemId == null) itemId = mBottomNavigationView.getSelectedItemId(); BaseAdapter currentAdapter = null; switch(itemId) { case R.id.bottomnav_customers: currentAdapter = mCurrentCustomerAdapter; break; case R.id.bottomnav_vouchers: currentAdapter = mCurrentVoucherAdapter; break; } final BaseAdapter finalCurrentAdapter = currentAdapter; final Integer finalItemId = itemId; int count = 0; if(finalCurrentAdapter instanceof CustomerAdapter) { count = ((CustomerAdapter) finalCurrentAdapter).getCheckedItems().size(); } else if(finalCurrentAdapter instanceof VoucherAdapter) { count = ((VoucherAdapter) finalCurrentAdapter).getCheckedItems().size(); } final int finalCount = count; if(count == 0) { if(mCheckedCountInfoSnackbar != null) mCheckedCountInfoSnackbar.dismiss(); } else { if(mCheckedCountInfoSnackbar == null) mCheckedCountInfoSnackbar = Snackbar.make( findViewById(R.id.coordinatorLayoutInner), "", Snackbar.LENGTH_INDEFINITE ); mCheckedCountInfoSnackbar.setText(getResources().getQuantityString(R.plurals.selected_records, count, count)); mCheckedCountInfoSnackbar.setAction( (count == finalCurrentAdapter.getCount()) ? getResources().getString(R.string.deselect) : getResources().getString(R.string.select_all), new View.OnClickListener() { @Override public void onClick(View view) { boolean state = true; if(finalCount == finalCurrentAdapter.getCount()) { state = false; } if(finalCurrentAdapter instanceof CustomerAdapter) { ((CustomerAdapter) finalCurrentAdapter).setAllChecked(state); } else if(finalCurrentAdapter instanceof VoucherAdapter) { ((VoucherAdapter) finalCurrentAdapter).setAllChecked(state); } finalCurrentAdapter.notifyDataSetChanged(); // immediately show snackbar again new java.util.Timer().schedule( new java.util.TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { refreshSelectedCountInfo(finalItemId); } }); } }, 400 ); } }); mCheckedCountInfoSnackbar.show(); } } @SuppressLint("SetTextI18n") private void refreshCount() { if(mNavigationView != null) { int customersCount = mDb.getCustomers(null, false, false, null).size(); int vouchersCount = mDb.getVouchers(null,false, null).size(); String customerAmountString = getResources().getQuantityString(R.plurals.customersamount, customersCount, customersCount); String voucherAmountString = getResources().getQuantityString(R.plurals.vouchersamount, vouchersCount, vouchersCount); View headerView = mNavigationView.getHeaderView(0); ((TextView) headerView.findViewById(R.id.textViewDrawerCustomerCount)).setText( customerAmountString ); ((TextView) headerView.findViewById(R.id.textViewDrawerVoucherCount)).setText( voucherAmountString ); } } public Dialog dialogObjSyncProgress = null; public void dialogSyncProgress() { final Dialog ad = new Dialog(this); ad.setCancelable(false); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_syncprogress); ad.show(); dialogObjSyncProgress = ad; lockCurrentOrientation(true); } public void dialogSyncSuccess() { lockCurrentOrientation(false); if(dialogObjSyncProgress != null) dialogObjSyncProgress.dismiss(); CommonDialog.show(this, getResources().getString(R.string.syncsuccess), null, CommonDialog.TYPE.OK, false); } public void dialogSyncFail(String errorMessage) { lockCurrentOrientation(false); if(dialogObjSyncProgress != null) dialogObjSyncProgress.dismiss(); CommonDialog.show(this, getResources().getString(R.string.syncfail), errorMessage, CommonDialog.TYPE.FAIL, false); } public static boolean isValidEmail(CharSequence target) { return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches(); } private void doNewsletter() { final Dialog ad = new Dialog(this); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_send_newsletter); final Button buttonComposeNewsletter = ad.findViewById(R.id.buttonComposeNewsletter); buttonComposeNewsletter.setEnabled(false); final Spinner dropdown = ad.findViewById(R.id.spinnerGroup); final RadioButton radioButtonSelected = ad.findViewById(R.id.radioButtonNewsletterReceiverSelected); final RadioButton radioButtonGroup = ad.findViewById(R.id.radioButtonNewsletterReceiverGroup); if(mCurrentCustomerAdapter.getCheckedItems().size() == 0) radioButtonSelected.setEnabled(false); CompoundButton.OnCheckedChangeListener occl = new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { buttonComposeNewsletter.setEnabled(true); } }; radioButtonSelected.setOnCheckedChangeListener(occl); radioButtonGroup.setOnCheckedChangeListener(occl); ad.findViewById(R.id.buttonComposeNewsletter).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); List<String> receiversList = new ArrayList<>(); if(radioButtonGroup.isChecked()) { String group = dropdown.getSelectedItem().toString(); for(Customer c : mCustomers) { if(c.mNewsletter && c.mEmail != null && !c.mEmail.equals("") && isValidEmail(c.mEmail)) if(group.equals(getResources().getString(R.string.all)) || group.equals(c.mCustomerGroup)) receiversList.add(c.mEmail); } } else if(radioButtonSelected.isChecked()) { for(Customer c : mCurrentCustomerAdapter.getCheckedItems()) { if(c.mEmail != null && !c.mEmail.equals("") && isValidEmail(c.mEmail)) receiversList.add(c.mEmail); } } if(receiversList.size() == 0) { CommonDialog.show(me, getResources().getString(R.string.newsletter_no_customers_title), getResources().getString(R.string.newsletter_no_customers_text), CommonDialog.TYPE.WARN,false); return; } composeNewsletter(receiversList); } }); ad.findViewById(R.id.buttonComposeNewsletterCancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); } }); ad.show(); String[] items = getGroups(true); ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.item_list_simple, items); dropdown.setAdapter(adapter); } private void composeNewsletter(List<String> receiversList) { String[] receivers = new String[receiversList.size()]; receivers = receiversList.toArray(receivers); Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("message/rfc822"); intent.putExtra(Intent.EXTRA_EMAIL, new String[]{}); intent.putExtra(Intent.EXTRA_BCC, receivers); intent.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.newsletter)); intent.putExtra(Intent.EXTRA_TEXT, mSettings.getString("email-newsletter-template", getResources().getString(R.string.newsletter_text_template)) ); startActivity(Intent.createChooser(intent, getResources().getString(R.string.emailtocustomer))); } private void menuImportExportCustomer() { final Dialog ad = new Dialog(this); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_import_export_customer); if(mCurrentCustomerAdapter.getCheckedItems().size() == 0) ad.findViewById(R.id.checkBoxExportOnlySelected).setEnabled(false); ad.findViewById(R.id.buttonImportVCF).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); Intent intent = new Intent(); intent.setType("text/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select VCF file"), PICK_CUSTOMER_VCF_REQUEST); } }); ad.findViewById(R.id.buttonImportCSV).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); AlertDialog.Builder ad2 = new AlertDialog.Builder(me); ad2.setMessage(getResources().getString(R.string.import_csv_note)); ad2.setNegativeButton(getResources().getString(R.string.abort), null); ad2.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); Intent intent = new Intent(); intent.setType("text/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select CSV file"), PICK_CUSTOMER_CSV_REQUEST); } }); ad2.show(); } }); ad.findViewById(R.id.buttonImportCode).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); PackageManager pm = getPackageManager(); if(pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) { startActivityForResult(new Intent(me, ScanActivity.class), SCAN_REQUEST); } } }); ad.findViewById(R.id.buttonExportVCF).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); boolean onlySelected = ((CheckBox) ad.findViewById(R.id.checkBoxExportOnlySelected)).isChecked(); CustomerVcfBuilder content; if(onlySelected) { List<Customer> exportCustomers = new ArrayList<>(); for(Customer c : mCurrentCustomerAdapter.getCheckedItems()) { exportCustomers.add(mDb.getCustomerById(c.mId, false, true)); } content = new CustomerVcfBuilder(exportCustomers); } else { content = new CustomerVcfBuilder(mDb.getCustomers(null, false, true, null)); } File f = StorageControl.getStorageExportVcf(me); if(content.saveVcfFile(f)) { mCurrentExportFile = f; CommonDialog.exportFinishedDialog(me, f, "text/vcard", new String[]{}, "", "", mResultHandlerExportMoveFile); } else { CommonDialog.show(me, getResources().getString(R.string.export_fail), f.getPath(), CommonDialog.TYPE.FAIL, false); } StorageControl.scanFile(f, me); } }); ad.findViewById(R.id.buttonExportCSV).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); boolean onlySelected = ((CheckBox) ad.findViewById(R.id.checkBoxExportOnlySelected)).isChecked(); CustomerCsvBuilder content; if(onlySelected) content = new CustomerCsvBuilder(mCurrentCustomerAdapter.getCheckedItems(), mDb.getCustomFields()); else content = new CustomerCsvBuilder(mCustomers, mDb.getCustomFields()); File f = StorageControl.getStorageExportCsv(me); if(content.saveCsvFile(f)) { mCurrentExportFile = f; CommonDialog.exportFinishedDialog(me, f, "text/csv", new String[]{}, "", "", mResultHandlerExportMoveFile); } else { CommonDialog.show(me, getResources().getString(R.string.export_fail), f.getPath(), CommonDialog.TYPE.FAIL, false); } StorageControl.scanFile(f, me); } }); ad.findViewById(R.id.buttonExportPDF).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { boolean onlySelected = ((CheckBox) ad.findViewById(R.id.checkBoxExportOnlySelected)).isChecked(); List<Customer> printList = mCustomers; if(onlySelected) printList = mCurrentCustomerAdapter.getCheckedItems(); for(Customer c : printList) { print(c); } } else { CommonDialog.show(me, getResources().getString(R.string.not_supported), getResources().getString(R.string.not_supported_printing), CommonDialog.TYPE.FAIL, false); } } }); ad.findViewById(R.id.buttonExportCancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); } }); ad.show(); } private void menuImportExportVoucher() { final Dialog ad = new Dialog(this); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_import_export_voucher); if(mCurrentVoucherAdapter.getCheckedItems().size() == 0) ad.findViewById(R.id.checkBoxExportOnlySelected).setEnabled(false); ad.findViewById(R.id.buttonImportCSV).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); AlertDialog.Builder ad2 = new AlertDialog.Builder(me); ad2.setMessage(getResources().getString(R.string.import_csv_note_voucher)); ad2.setNegativeButton(getResources().getString(R.string.abort), null); ad2.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); Intent intent = new Intent(); intent.setType("text/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select CSV file"), PICK_VOUCHER_CSV_REQUEST); } }); ad2.show(); } }); ad.findViewById(R.id.buttonExportCSV).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); boolean onlySelected = ((CheckBox) ad.findViewById(R.id.checkBoxExportOnlySelected)).isChecked(); VoucherCsvBuilder content; if(onlySelected) content = new VoucherCsvBuilder(mCurrentVoucherAdapter.getCheckedItems()); else content = new VoucherCsvBuilder(mVouchers); File f = StorageControl.getStorageExportCsv(me); if(content.saveCsvFile(f, mDb)) { mCurrentExportFile = f; CommonDialog.exportFinishedDialog(me, f, "text/csv", new String[]{}, "", "", mResultHandlerExportMoveFile); } else { CommonDialog.show(me, getResources().getString(R.string.export_fail), f.getPath(), CommonDialog.TYPE.FAIL, false); } StorageControl.scanFile(f, me); } }); ad.findViewById(R.id.buttonExportCancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); } }); ad.show(); } private void menuImportExportCalendar() { final Dialog ad = new Dialog(this); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_import_export_calendar); // load calendars final Spinner spinnerCalendar = ad.findViewById(R.id.spinnerCalendar); ArrayAdapter<CustomerCalendar> a = new ArrayAdapter<>(this, R.layout.item_list_simple, mDb.getCalendars(false)); spinnerCalendar.setAdapter(a); ad.findViewById(R.id.buttonImportICS).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); CustomerCalendar calendar = (CustomerCalendar) spinnerCalendar.getSelectedItem(); if(calendar == null) { CommonDialog.show(me, getString(R.string.error), getString(R.string.no_calendar_selected), CommonDialog.TYPE.WARN, false); return; } mCurrentCalendarImportSelectedId = calendar.mId; Intent intent = new Intent(); intent.setType("text/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select ICS file"), PICK_CALENDAR_ICS_REQUEST); } }); ad.findViewById(R.id.buttonImportCSV).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); CustomerCalendar calendar = (CustomerCalendar) spinnerCalendar.getSelectedItem(); if(calendar == null) { CommonDialog.show(me, getString(R.string.error), getString(R.string.no_calendar_selected), CommonDialog.TYPE.WARN, false); return; } mCurrentCalendarImportSelectedId = calendar.mId; AlertDialog.Builder ad2 = new AlertDialog.Builder(me); ad2.setMessage(getResources().getString(R.string.import_csv_note)); ad2.setNegativeButton(getResources().getString(R.string.abort), null); ad2.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); Intent intent = new Intent(); intent.setType("text/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select CSV file"), PICK_CALENDAR_CSV_REQUEST); } }); ad2.show(); } }); ad.findViewById(R.id.buttonExportICS).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); CustomerCalendar calendar = (CustomerCalendar) spinnerCalendar.getSelectedItem(); if(calendar == null) { CommonDialog.show(me, getString(R.string.error), getString(R.string.no_calendar_selected), CommonDialog.TYPE.WARN, false); return; } CalendarIcsBuilder content = new CalendarIcsBuilder(mDb.getAppointments(calendar.mId, null, false, null)); File f = StorageControl.getStorageExportIcs(me); if(content.saveIcsFile(f)) { mCurrentExportFile = f; CommonDialog.exportFinishedDialog(me, f, "text/calendar", new String[]{}, "", "", mResultHandlerExportMoveFile); } else { CommonDialog.show(me, getResources().getString(R.string.export_fail), f.getPath(), CommonDialog.TYPE.FAIL, false); } StorageControl.scanFile(f, me); } }); ad.findViewById(R.id.buttonExportCSV).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); CustomerCalendar calendar = (CustomerCalendar) spinnerCalendar.getSelectedItem(); if(calendar == null) { CommonDialog.show(me, getString(R.string.error), getString(R.string.no_calendar_selected), CommonDialog.TYPE.WARN, false); return; } CalendarCsvBuilder content = new CalendarCsvBuilder(mDb.getAppointments(calendar.mId, null, false, null)); File f = StorageControl.getStorageExportCsv(me); if(content.saveCsvFile(f, mDb)) { mCurrentExportFile = f; CommonDialog.exportFinishedDialog(me, f, "text/csv", new String[]{}, "", "", mResultHandlerExportMoveFile); } else { CommonDialog.show(me, getResources().getString(R.string.export_fail), f.getPath(), CommonDialog.TYPE.FAIL, false); } StorageControl.scanFile(f, me); } }); ad.findViewById(R.id.buttonExportCancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); } }); ad.show(); } private void print(Customer currentCustomer) { if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { PrintManager printManager = (PrintManager) this.getSystemService(Context.PRINT_SERVICE); if(printManager != null) { String jobName = "Customer Database"; PrintAttributes pa = new PrintAttributes.Builder() .setColorMode(PrintAttributes.COLOR_MODE_COLOR) .setMediaSize(PrintAttributes.MediaSize.ISO_A4) .setResolution(new PrintAttributes.Resolution("customerdb", PRINT_SERVICE, 300, 300)) .setMinMargins(PrintAttributes.Margins.NO_MARGINS) .build(); printManager.print(jobName, new CustomerPrintDocumentAdapter(this,currentCustomer), pa); } } } private void dialogInApp(String title, String text) { AlertDialog.Builder ad = new AlertDialog.Builder(this); ad.setTitle(title); ad.setMessage(text); ad.setIcon(getResources().getDrawable(R.drawable.ic_warning_orange_24dp)); ad.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); ad.setNeutralButton(getResources().getString(R.string.more), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startActivityForResult(new Intent(me, AboutActivity.class), ABOUT_REQUEST); } }); ad.show(); } private void dialogSyncNotConfigured() { AlertDialog.Builder ad = new AlertDialog.Builder(this); ad.setTitle(getResources().getString(R.string.sync_not_configured_title)); ad.setMessage(getResources().getString(R.string.sync_not_configured_text)); ad.setIcon(getResources().getDrawable(R.drawable.ic_warning_orange_24dp)); ad.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); ad.setNeutralButton(getResources().getString(R.string.more), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startActivity(new Intent(me, InfoActivity.class)); } }); ad.show(); } public void dialogEula() { final SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); if(!settings.getBoolean("eulaok", false)) { final AlertDialog.Builder ad = new AlertDialog.Builder(me); ad.setPositiveButton(getResources().getString(R.string.eulaaccept), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("eulaok", true); editor.apply(); }}); ad.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { me.finish(); } }); ad.setTitle(getResources().getString(R.string.eula_title)); ad.setMessage(getResources().getString(R.string.eula)); ad.show(); } } public void dialogNews() { final String newsKey = "news-shown-3.2"; final SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); if(!settings.getBoolean(newsKey, false)) { final Dialog ad = new Dialog(this); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_news); Button button = ad.findViewById(R.id.buttonClose); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean(newsKey, true); editor.apply(); } }); ad.show(); } } private void showAdLicense() { Snackbar.make( findViewById(R.id.coordinatorLayoutInner), getResources().getString(R.string.not_licensed), Snackbar.LENGTH_LONG) .setAction(getResources().getString(R.string.fix), new View.OnClickListener() { @Override public void onClick(View v) { Intent aboutIntent = new Intent(me, AboutActivity.class); startActivity(aboutIntent); } }) .show(); } private void showAdOtherApps() { if(mSettings.getInt("started", 0) % 12 == 0 && mSettings.getInt("ad-other-apps-shown", 0) < 2) { // increment counter SharedPreferences.Editor editor = mSettings.edit(); editor.putInt("ad-other-apps-shown", mSettings.getInt("ad-other-apps-shown", 0)+1); editor.apply(); // show ad "other apps" final Dialog ad = new Dialog(this); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_otherapps); ad.setCancelable(true); ad.findViewById(R.id.buttonRateCustomerDB).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openPlayStore(me, getPackageName()); ad.hide(); } }); ad.findViewById(R.id.linearLayoutRateStars).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { openPlayStore(me, getPackageName()); ad.hide(); } }); ad.show(); } } static void openPlayStore(Activity activity, String appId) { try { activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appId))); } catch (android.content.ActivityNotFoundException ignored) { activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appId))); } } private void incrementStartedCounter() { final SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); int oldStartedValue = settings.getInt("started", 0); Log.i("STARTED",Integer.toString(oldStartedValue)); SharedPreferences.Editor editor = settings.edit(); editor.putInt("started", oldStartedValue+1); editor.apply(); } private String mCurrentGroup = null; private String mCurrentCity = null; private String mCurrentCountry = null; private void filterDialog() { final Dialog ad = new Dialog(this); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_filter); final Spinner dropdownCity = ad.findViewById(R.id.spinnerCity); final Spinner dropdownCountry = ad.findViewById(R.id.spinnerCountry); final Spinner dropdownGroup = ad.findViewById(R.id.spinnerGroup); ad.findViewById(R.id.buttonGroupSelect).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mCurrentGroup = dropdownGroup.getSelectedItem().toString(); mCurrentCity = dropdownCity.getSelectedItem().toString(); mCurrentCountry = dropdownCountry.getSelectedItem().toString(); if(mCurrentGroup.equals(getString(R.string.empty))) mCurrentGroup = ""; if(mCurrentCity.equals(getString(R.string.empty))) mCurrentCity = ""; if(mCurrentCountry.equals(getString(R.string.empty))) mCurrentCountry = ""; if(mCurrentGroup.equals(getString(R.string.all))) mCurrentGroup = null; if(mCurrentCity.equals(getString(R.string.all))) mCurrentCity = null; if(mCurrentCountry.equals(getString(R.string.all))) mCurrentCountry = null; ad.dismiss(); refreshCustomersFromLocalDatabase(); } }); ad.findViewById(R.id.buttonAllSelect).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mCurrentGroup = null; mCurrentCity = null; mCurrentCountry = null; ad.dismiss(); refreshCustomersFromLocalDatabase(); } }); ad.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { ad.dismiss(); } }); ad.show(); ArrayAdapter<String> adapterGroup = new ArrayAdapter<>(this, R.layout.item_list_simple, getGroups(true)); ArrayAdapter<String> adapterCity = new ArrayAdapter<>(this, R.layout.item_list_simple, getCities(true)); ArrayAdapter<String> adapterCountry = new ArrayAdapter<>(this, R.layout.item_list_simple, getCountries(true)); dropdownGroup.setAdapter(adapterGroup); dropdownCity.setAdapter(adapterCity); dropdownCountry.setAdapter(adapterCountry); } private String[] getGroups(boolean withAllEntry) { ArrayList<String> groups = new ArrayList<>(); if(withAllEntry) { groups.add(getResources().getString(R.string.all)); groups.add(getResources().getString(R.string.empty)); } for(Customer c : mDb.getCustomers(null, false, false, null)) { if(!groups.contains(c.mCustomerGroup) && !c.mCustomerGroup.equals("")) groups.add(c.mCustomerGroup); } String[] finalArray = new String[groups.size()]; groups.toArray(finalArray); return finalArray; } private String[] getCities(boolean withAllEntry) { ArrayList<String> groups = new ArrayList<>(); if(withAllEntry) { groups.add(getResources().getString(R.string.all)); groups.add(getResources().getString(R.string.empty)); } for(Customer c : mDb.getCustomers(null, false, false, null)) { if(!groups.contains(c.mCity) && !c.mCity.equals("")) groups.add(c.mCity); } String[] finalArray = new String[groups.size()]; groups.toArray(finalArray); return finalArray; } private String[] getCountries(boolean withAllEntry) { ArrayList<String> groups = new ArrayList<>(); if(withAllEntry) { groups.add(getResources().getString(R.string.all)); groups.add(getResources().getString(R.string.empty)); } for(Customer c : mDb.getCustomers(null, false, false, null)) { if(!groups.contains(c.mCountry) && !c.mCountry.equals("")) groups.add(c.mCountry); } String[] finalArray = new String[groups.size()]; groups.toArray(finalArray); return finalArray; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch(requestCode) { case(NEW_APPOINTMENT_REQUEST): { if(resultCode == Activity.RESULT_OK) { refreshAppointmentsFromLocalDatabase(); } break; } case(NEW_CUSTOMER_REQUEST): { if(resultCode == Activity.RESULT_OK) { refreshCustomersFromLocalDatabase(); } break; } case(NEW_VOUCHER_REQUEST): { if(resultCode == Activity.RESULT_OK) { refreshVouchersFromLocalDatabase(); } break; } case(BIRTHDAY_REQUEST): case(VIEW_CUSTOMER_REQUEST): { if(resultCode == Activity.RESULT_OK) { if(data.getStringExtra("action").equals("update")) { MainActivity.setUnsyncedChanges(this); refreshCustomersFromLocalDatabase(); } } break; } case(VIEW_VOUCHER_REQUEST): { if(resultCode == Activity.RESULT_OK) { if(data.getStringExtra("action").equals("update")) { MainActivity.setUnsyncedChanges(this); refreshVouchersFromLocalDatabase(); } } break; } case(PICK_CUSTOMER_VCF_REQUEST): { if(resultCode == Activity.RESULT_OK && data.getData() != null) { try { List<Customer> newCustomers = CustomerVcfBuilder.readVcfFile(new InputStreamReader(getContentResolver().openInputStream(data.getData()))); int counter = 0; for(Customer c : newCustomers) { c.mId = Customer.generateID(counter); if(mDb.addCustomer(c)) { counter ++; } } if(counter > 0) { refreshCustomersFromLocalDatabase(); CommonDialog.show(this, getResources().getString(R.string.import_ok),getResources().getQuantityString(R.plurals.imported, counter, counter), CommonDialog.TYPE.OK, false); MainActivity.setUnsyncedChanges(this); } else { CommonDialog.show(this, getResources().getString(R.string.import_fail),getResources().getString(R.string.import_fail_no_entries), CommonDialog.TYPE.FAIL, false); } } catch(Exception e) { CommonDialog.show(this, getResources().getString(R.string.import_fail),e.getMessage(), CommonDialog.TYPE.FAIL, false); e.printStackTrace(); } } break; } case(PICK_CUSTOMER_CSV_REQUEST): { if(resultCode == Activity.RESULT_OK && data.getData() != null) { try { List<Customer> newCustomers = CustomerCsvBuilder.readCsvFile(new InputStreamReader(getContentResolver().openInputStream(data.getData()))); int counter = 0; for(Customer c : newCustomers) { if(c.mId < 1 || mDb.getCustomerById(c.mId, true, false) != null) { c.mId = Customer.generateID(counter); } if(mDb.addCustomer(c)) { counter ++; } } if(counter > 0) { refreshCustomersFromLocalDatabase(); CommonDialog.show(this, getResources().getString(R.string.import_ok),getResources().getQuantityString(R.plurals.imported, counter, counter), CommonDialog.TYPE.OK, false); MainActivity.setUnsyncedChanges(this); } else { CommonDialog.show(this, getResources().getString(R.string.import_fail),getResources().getString(R.string.import_fail_no_entries), CommonDialog.TYPE.FAIL, false); } } catch(Exception e) { CommonDialog.show(this, getResources().getString(R.string.import_fail), e.getMessage(), CommonDialog.TYPE.FAIL, false); e.printStackTrace(); } } break; } case(PICK_VOUCHER_CSV_REQUEST): { if(resultCode == Activity.RESULT_OK && data.getData() != null) { try { List<Voucher> newVouchers = VoucherCsvBuilder.readCsvFile(new InputStreamReader(getContentResolver().openInputStream(data.getData()))); if(newVouchers.size() > 0) { int counter = 0; for(Voucher v : newVouchers) { if(v.mId < 1 || mDb.getVoucherById(v.mId, true) != null) { v.mId = Voucher.generateID(counter); } mDb.addVoucher(v); counter ++; } refreshVouchersFromLocalDatabase(); CommonDialog.show(this, getResources().getString(R.string.import_ok),getResources().getQuantityString(R.plurals.imported, newVouchers.size(), newVouchers.size()), CommonDialog.TYPE.OK, false); MainActivity.setUnsyncedChanges(this); } else CommonDialog.show(this, getResources().getString(R.string.import_fail),getResources().getString(R.string.import_fail_no_entries), CommonDialog.TYPE.FAIL, false); } catch(Exception e) { CommonDialog.show(this, getResources().getString(R.string.import_fail), e.getMessage(), CommonDialog.TYPE.FAIL, false); e.printStackTrace(); } } break; } case(PICK_CALENDAR_ICS_REQUEST): { if(resultCode == Activity.RESULT_OK && data.getData() != null) { try { List<CustomerAppointment> newAppointments = CalendarIcsBuilder.readIcsFile(new InputStreamReader(getContentResolver().openInputStream(data.getData()))); if(newAppointments.size() > 0) { int counter = 0; for(CustomerAppointment ca : newAppointments) { ca.mId = CustomerAppointment.generateID(counter); ca.mCalendarId = mCurrentCalendarImportSelectedId; mDb.addAppointment(ca); counter ++; } refreshAppointmentsFromLocalDatabase(); CommonDialog.show(this, getResources().getString(R.string.import_ok),getResources().getQuantityString(R.plurals.imported, newAppointments.size(), newAppointments.size()), CommonDialog.TYPE.OK, false); MainActivity.setUnsyncedChanges(this); } else CommonDialog.show(this, getResources().getString(R.string.import_fail),getResources().getString(R.string.import_fail_no_entries), CommonDialog.TYPE.FAIL, false); } catch(Exception e) { CommonDialog.show(this, getResources().getString(R.string.import_fail),e.getMessage(), CommonDialog.TYPE.FAIL, false); e.printStackTrace(); } } break; } case(PICK_CALENDAR_CSV_REQUEST): { if(resultCode == Activity.RESULT_OK && data.getData() != null) { try { List<CustomerAppointment> newAppointments = CalendarCsvBuilder.readCsvFile(new InputStreamReader(getContentResolver().openInputStream(data.getData()))); if(newAppointments.size() > 0) { int counter = 0; for(CustomerAppointment ca : newAppointments) { if(ca.mId < 1 || mDb.getAppointmentById(ca.mId, true) != null) { ca.mId = Customer.generateID(counter); } ca.mCalendarId = mCurrentCalendarImportSelectedId; mDb.addAppointment(ca); counter ++; } refreshAppointmentsFromLocalDatabase(); CommonDialog.show(this, getResources().getString(R.string.import_ok),getResources().getQuantityString(R.plurals.imported, newAppointments.size(), newAppointments.size()), CommonDialog.TYPE.OK, false); MainActivity.setUnsyncedChanges(this); } else CommonDialog.show(this, getResources().getString(R.string.import_fail),getResources().getString(R.string.import_fail_no_entries), CommonDialog.TYPE.FAIL, false); } catch(Exception e) { CommonDialog.show(this, getResources().getString(R.string.import_fail), e.getMessage(), CommonDialog.TYPE.FAIL, false); e.printStackTrace(); } } break; } case(ABOUT_REQUEST): case(SETTINGS_REQUEST): { //loadSettings(); recreate(); break; } case(SCAN_REQUEST): { if(resultCode == 1) { refreshCustomersFromLocalDatabase(); } break; } } } }
94,474
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
InfoActivity.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/InfoActivity.java
package de.georgsieber.customerdb; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.lang.ref.WeakReference; import java.net.HttpURLConnection; import java.net.URL; import java.util.Locale; import de.georgsieber.customerdb.tools.ColorControl; import de.georgsieber.customerdb.tools.CommonDialog; public class InfoActivity extends AppCompatActivity { InfoActivity me = this; FeatureCheck mFc; String mRegisteredUsername = ""; String mRegisteredPassword = ""; @Override protected void onCreate(Bundle savedInstanceState) { // init settings SharedPreferences settings = getSharedPreferences(MainActivity.PREFS_NAME, 0); // init activity view super.onCreate(savedInstanceState); setContentView(R.layout.activity_info); // init toolbar Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); if(getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); // init colors ColorControl.updateActionBarColor(this, settings); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case android.R.id.home: finish(); return true; default: return super.onOptionsItemSelected(item); } } public void onMoreInfoClick(View v) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().getString(R.string.help_website)))); } public void onOpenAboutClick(View v) { startActivity(new Intent(this, AboutActivity.class)); } Dialog mRegistrationDialog = null; public void onCreateAccountClick(View v) { mRegistrationDialog = new Dialog(this); mRegistrationDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); mRegistrationDialog.setContentView(R.layout.dialog_register); final Button buttonRegister = mRegistrationDialog.findViewById(R.id.buttonRegisterNow); final EditText editTextEmail = mRegistrationDialog.findViewById(R.id.editTextEmailAddress); final EditText editTextChoosePassword = mRegistrationDialog.findViewById(R.id.editTextChoosePassword); final EditText editTextConfirmPassword = mRegistrationDialog.findViewById(R.id.editTextConfirmPassword); final CheckBox checkBoxAcceptTerms = mRegistrationDialog.findViewById(R.id.checkBoxAcceptCloudTerms); final Button buttonCloudTerms = mRegistrationDialog.findViewById(R.id.buttonCloudTerms); buttonCloudTerms.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().getString(R.string.terms_website))); startActivity(browserIntent); } }); buttonRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(!checkBoxAcceptTerms.isChecked()) { CommonDialog.show(me, "", getString(R.string.please_accept_privacy_policy), CommonDialog.TYPE.WARN, false ); return; } if(!editTextChoosePassword.getText().toString().equals(editTextConfirmPassword.getText().toString())) { CommonDialog.show(me, getString(R.string.passwords_not_matching), "", CommonDialog.TYPE.WARN, false ); return; } mRegisteredUsername = editTextEmail.getText().toString(); mRegisteredPassword = editTextChoosePassword.getText().toString(); SharedPreferences settings = getSharedPreferences(MainActivity.PREFS_NAME, 0); if(settings.getInt("webapi-type", 0) == 2) { AccountApi aa = new AccountApi(me, settings.getString("webapi-url", ""), "account.register"); aa.execute(editTextEmail.getText().toString(), editTextChoosePassword.getText().toString()); } else { AccountApi aa = new AccountApi(me, "account.register"); aa.execute(editTextEmail.getText().toString(), editTextChoosePassword.getText().toString()); } buttonRegister.setEnabled(false); buttonRegister.setText(getString(R.string.please_wait)); } }); mRegistrationDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { mRegistrationDialog.dismiss(); } }); mRegistrationDialog.show(); } public void onResetPasswordClick(View v) { mRegistrationDialog = new Dialog(this); mRegistrationDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); mRegistrationDialog.setContentView(R.layout.dialog_reset_password); final Button buttonOK = mRegistrationDialog.findViewById(R.id.buttonOK); final EditText editTextEmail = mRegistrationDialog.findViewById(R.id.editTextEmailAddress); buttonOK.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SharedPreferences settings = getSharedPreferences(MainActivity.PREFS_NAME, 0); if(settings.getInt("webapi-type", 0) == 2) { AccountApi aa = new AccountApi(me, settings.getString("webapi-url", ""), "account.resetpwd"); aa.execute(editTextEmail.getText().toString()); } else { AccountApi aa = new AccountApi(me, "account.resetpwd"); aa.execute(editTextEmail.getText().toString()); } buttonOK.setEnabled(false); buttonOK.setText(getString(R.string.please_wait)); } }); mRegistrationDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { mRegistrationDialog.dismiss(); } }); mRegistrationDialog.show(); } public void onDeleteAccountClick(View v) { mRegistrationDialog = new Dialog(this); mRegistrationDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); mRegistrationDialog.setContentView(R.layout.dialog_delete_account); final Button buttonOK = mRegistrationDialog.findViewById(R.id.buttonOK); final EditText editTextEmail = mRegistrationDialog.findViewById(R.id.editTextEmailAddress); buttonOK.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SharedPreferences settings = getSharedPreferences(MainActivity.PREFS_NAME, 0); if(settings.getInt("webapi-type", 0) == 2) { AccountApi aa = new AccountApi(me, settings.getString("webapi-url", ""), "account.delete"); aa.execute(editTextEmail.getText().toString()); } else { AccountApi aa = new AccountApi(me, "account.delete"); aa.execute(editTextEmail.getText().toString()); } buttonOK.setEnabled(false); buttonOK.setText(getString(R.string.please_wait)); } }); mRegistrationDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { mRegistrationDialog.dismiss(); } }); mRegistrationDialog.show(); } public void onServerGithubClick(View v) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.server_repo_link))); startActivity(browserIntent); } void handleAccountCreationSuccess() { SharedPreferences settings = getSharedPreferences(MainActivity.PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putInt("webapi-type", settings.getInt("webapi-type", 0)==2 ? 2 : 1); editor.putString("webapi-username", mRegisteredUsername); editor.putString("webapi-password", mRegisteredPassword); editor.apply(); CommonDialog.show(this, getString(R.string.registration_succeeded), getString(R.string.registration_succeeded_text), CommonDialog.TYPE.OK, false ); if(mRegistrationDialog != null) mRegistrationDialog.dismiss(); } void handleAccountCreationError(String message) { CommonDialog.show(this, getString(R.string.registration_failed), message, CommonDialog.TYPE.FAIL, false ); if(mRegistrationDialog != null) { Button buttonRegister = mRegistrationDialog.findViewById(R.id.buttonRegisterNow); buttonRegister.setEnabled(true); buttonRegister.setText(getString(R.string.register_now2)); } } void handleAccountSuccess() { CommonDialog.show(this, getString(R.string.success), getString(R.string.please_check_inbox), CommonDialog.TYPE.OK, false ); if(mRegistrationDialog != null) mRegistrationDialog.dismiss(); } void handleAccountError(String message) { CommonDialog.show(this, getString(R.string.error), message, CommonDialog.TYPE.FAIL, false ); if(mRegistrationDialog != null) mRegistrationDialog.dismiss(); } public class AccountApi extends AsyncTask<String, Void, String> { private WeakReference<InfoActivity> mInfoActivityReference; private String mApiUrl; private String mMethod; AccountApi(InfoActivity context, String method) { mInfoActivityReference = new WeakReference<>(context); mApiUrl = CustomerDatabaseApi.MANAGED_API; mMethod = method; } AccountApi(InfoActivity context, String url, String method) { mInfoActivityReference = new WeakReference<>(context); mApiUrl = url; mMethod = method; } @Override protected String doInBackground(String... params) { try { if(mMethod.equals("account.register") && params.length == 2) { register(params[0], params[1]); return null; } else if(mMethod.equals("account.resetpwd") && params.length == 1) { resetPassword(params[0]); return null; } else if(mMethod.equals("account.delete") && params.length == 1) { delete(params[0]); return null; } else { throw new Error("Invalid Method or Missing Parameter"); } } catch(Exception e) { return e.getMessage(); } } private void register(String email, String password) throws Exception { try { JSONObject jaccparams = new JSONObject(); jaccparams.put("email", email); jaccparams.put("password", password); JSONObject jroot = new JSONObject(); jroot.put("jsonrpc", "2.0"); jroot.put("id", 1); jroot.put("method", "account.register"); jroot.put("params", jaccparams); //Log.e("API", jroot.toString()); String result = openConnection(jroot.toString()); //Log.e("API", result); try { JSONObject jresult = new JSONObject(result); if(jresult.isNull("result") || !jresult.getBoolean("result")) { throw new Exception(jresult.getString("error")); } } catch(JSONException e) { throw new Exception(result); } } catch(JSONException ex) { throw new Exception(ex.getMessage()); } } private void resetPassword(String email) throws Exception { try { JSONObject jaccparams = new JSONObject(); jaccparams.put("email", email); JSONObject jroot = new JSONObject(); jroot.put("jsonrpc", "2.0"); jroot.put("id", 1); jroot.put("method", "account.resetpwd"); jroot.put("params", jaccparams); //Log.e("API", jroot.toString()); String result = openConnection(jroot.toString()); //Log.e("API", result); try { JSONObject jresult = new JSONObject(result); if(jresult.isNull("result") || !jresult.getBoolean("result")) { throw new Exception(jresult.getString("error")); } } catch(JSONException e) { throw new Exception(result); } } catch(JSONException ex) { throw new Exception(ex.getMessage()); } } private void delete(String email) throws Exception { try { JSONObject jaccparams = new JSONObject(); jaccparams.put("email", email); JSONObject jroot = new JSONObject(); jroot.put("jsonrpc", "2.0"); jroot.put("id", 1); jroot.put("method", "account.delete"); jroot.put("params", jaccparams); //Log.e("API", jroot.toString()); String result = openConnection(jroot.toString()); //Log.e("API", result); try { JSONObject jresult = new JSONObject(result); if(jresult.isNull("result") || !jresult.getBoolean("result")) { throw new Exception(jresult.getString("error")); } } catch(JSONException e) { throw new Exception(result); } } catch(JSONException ex) { throw new Exception(ex.getMessage()); } } private String openConnection(String send) throws Exception { String text = ""; BufferedReader reader = null; try { URL url = new URL(mApiUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept-Language", Locale.getDefault().getLanguage()); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(send); wr.flush(); int statusCode = conn.getResponseCode(); if(statusCode == 200) reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); else reader = new BufferedReader(new InputStreamReader((conn).getErrorStream())); StringBuilder sb2 = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb2.append(line).append("\n"); } text = sb2.toString(); if(text.equals("")) text = statusCode + " " + conn.getResponseMessage(); } catch (Exception ex) { throw new Exception(ex.getMessage()); } finally { if(reader != null) try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } return text; } @Override protected void onPostExecute(String result) { // get a reference to the activity if it is still there InfoActivity activity = mInfoActivityReference.get(); if(activity == null) return; if(result == null) { if(mMethod.equals("account.register")) { activity.handleAccountCreationSuccess(); } else { activity.handleAccountSuccess(); } } else { if(mMethod.equals("account.register")) { activity.handleAccountCreationError(result); } else { activity.handleAccountError(result); } } } } }
17,789
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
CustomerDatabase.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/CustomerDatabase.java
package de.georgsieber.customerdb; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.telephony.PhoneNumberUtils; import android.util.Log; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteStatement; import java.io.File; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.TimeZone; import de.georgsieber.customerdb.model.CustomerAppointment; import de.georgsieber.customerdb.model.CustomerCalendar; import de.georgsieber.customerdb.model.CustomField; import de.georgsieber.customerdb.model.Customer; import de.georgsieber.customerdb.model.CustomerFile; import de.georgsieber.customerdb.model.Voucher; import static android.content.Context.MODE_PRIVATE; @SuppressWarnings("TryFinallyCanBeTryWithResources") public class CustomerDatabase { @SuppressLint("SimpleDateFormat") public static DateFormat storageFormatWithoutTime = new SimpleDateFormat("yyyy-MM-dd"); @SuppressLint("SimpleDateFormat") private static DateFormat storageFormatWithTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static String dateToString(Date d) { if(d == null) d = new Date(); storageFormatWithTime.setTimeZone(TimeZone.getTimeZone("UTC")); return storageFormatWithTime.format(d); } public static String dateToStringRaw(Date d) { if(d == null) d = new Date(); storageFormatWithTime.setTimeZone(TimeZone.getDefault()); return storageFormatWithTime.format(d); } public static Date parseDate(String s) throws ParseException { if(s == null) throw new ParseException("String is null", 0); storageFormatWithTime.setTimeZone(TimeZone.getTimeZone("UTC")); return storageFormatWithTime.parse(s); } public static Date parseDateRaw(String s) throws ParseException { if(s == null) throw new ParseException("String is null", 0); storageFormatWithTime.setTimeZone(TimeZone.getDefault()); return storageFormatWithTime.parse(s); } private SQLiteDatabase db; private Context context; public CustomerDatabase(Context context) { this.context = context; db = context.openOrCreateDatabase(getStorage().getPath(), MODE_PRIVATE, null); db.execSQL("CREATE TABLE IF NOT EXISTS customer (id INTEGER PRIMARY KEY AUTOINCREMENT, title VARCHAR, first_name VARCHAR, last_name VARCHAR, phone_home VARCHAR, phone_mobile VARCHAR, phone_work VARCHAR, email VARCHAR, street VARCHAR, zipcode VARCHAR, city VARCHAR, country VARCHAR, birthday DATETIME, last_modified DATETIME, notes VARCHAR, removed INTEGER DEFAULT 0);"); db.execSQL("CREATE TABLE IF NOT EXISTS voucher (id INTEGER PRIMARY KEY AUTOINCREMENT, current_value REAL, original_value REAL, from_customer VARCHAR, for_customer VARCHAR, issued DATETIME DEFAULT CURRENT_TIMESTAMP, valid_until DATETIME DEFAULT NULL, redeemed DATETIME DEFAULT NULL, last_modified DATETIME DEFAULT NULL, notes VARCHAR, removed INTEGER DEFAULT 0);"); upgradeDatabase(); scanFile(getStorage()); } public void close() { db.close(); } void beginTransaction() { db.beginTransaction(); } void endTransaction() { db.endTransaction(); } void commitTransaction() { db.setTransactionSuccessful(); } private File getStorage() { return new File(context.getExternalFilesDir(null), "customers.sqlite"); } private void scanFile(File f) { Uri uri = Uri.fromFile(f); Intent scanFileIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri); context.sendBroadcast(scanFileIntent); } private boolean columnNotExists(String table, String column) { Cursor cursor = db.rawQuery("PRAGMA table_info("+ table +")", null); if(cursor != null) { while(cursor.moveToNext()) { String name = cursor.getString(cursor.getColumnIndex("name")); if(column.equalsIgnoreCase(name)) { return false; } } } if(cursor != null) cursor.close(); return true; } private void upgradeDatabase() { if(columnNotExists("customer", "customer_group")) { db.execSQL("ALTER TABLE customer ADD COLUMN consent BLOB;"); db.execSQL("ALTER TABLE customer ADD COLUMN newsletter INTEGER default 0;"); db.execSQL("ALTER TABLE customer ADD COLUMN customer_group VARCHAR default '';"); } if(columnNotExists("customer", "custom_fields")) { db.execSQL("ALTER TABLE customer ADD COLUMN custom_fields VARCHAR default '';"); db.execSQL("CREATE TABLE IF NOT EXISTS customer_extra_fields (id INTEGER PRIMARY KEY AUTOINCREMENT, title VARCHAR, type INTEGER);"); db.execSQL("CREATE TABLE IF NOT EXISTS customer_extra_presets (id INTEGER PRIMARY KEY AUTOINCREMENT, title VARCHAR, extra_field_id INTEGER);"); } if(columnNotExists("customer", "image")) { db.execSQL("ALTER TABLE customer ADD COLUMN image BLOB;"); } if(columnNotExists("voucher", "voucher_no")) { db.execSQL("ALTER TABLE voucher ADD COLUMN voucher_no VARCHAR NOT NULL DEFAULT '';"); db.execSQL("UPDATE customer SET birthday = null WHERE birthday LIKE '%1800%';"); } if(columnNotExists("customer_file", "content")) { String currentDateString = dateToString(new Date()); beginTransaction(); db.execSQL("CREATE TABLE IF NOT EXISTS calendar (id INTEGER PRIMARY KEY AUTOINCREMENT, title VARCHAR NOT NULL, color VARCHAR NOT NULL, notes VARCHAR NOT NULL, last_modified DATETIME DEFAULT CURRENT_TIMESTAMP, removed INTEGER DEFAULT 0);"); db.execSQL("CREATE TABLE IF NOT EXISTS appointment (id INTEGER PRIMARY KEY AUTOINCREMENT, calendar_id INTEGER NOT NULL, title VARCHAR NOT NULL, notes VARCHAR NOT NULL, time_start DATETIME, time_end DATETIME, fullday INTEGER DEFAULT 0, customer VARCHAR NOT NULL, location VARCHAR NOT NULL, last_modified DATETIME DEFAULT CURRENT_TIMESTAMP, removed INTEGER DEFAULT 0);"); db.execSQL("CREATE TABLE IF NOT EXISTS customer_file (id INTEGER PRIMARY KEY AUTOINCREMENT, customer_id INTEGER NOT NULL, name VARCHAR NOT NULL, content BLOB NOT NULL);"); Cursor cursor = db.rawQuery("SELECT id, consent FROM customer", null); try { if(cursor.moveToFirst()) { do { if(!cursor.isNull(1) && cursor.getBlob(1).length > 0) { SQLiteStatement stmt = db.compileStatement("INSERT INTO customer_file (customer_id, name, content) VALUES (?, ?, ?)"); stmt.bindLong(1, cursor.getLong(0)); stmt.bindString(2, context.getString(R.string.consent)+".jpg"); stmt.bindBlob(3, cursor.getBlob(1)); stmt.execute(); } SQLiteStatement stmt = db.compileStatement("UPDATE customer SET consent = ?, last_modified = ? WHERE id = ?"); stmt.bindNull(1); stmt.bindString(2, currentDateString); stmt.bindLong(3, cursor.getLong(0)); stmt.execute(); } while (cursor.moveToNext()); } } catch (SQLiteException e) { Log.e("SQLite Error", e.getMessage()); System.exit(1); } finally { cursor.close(); } commitTransaction(); endTransaction(); } if(columnNotExists("appointment", "customer_id")) { db.beginTransaction(); db.execSQL("ALTER TABLE appointment ADD COLUMN customer_id INTEGER;"); db.execSQL("ALTER TABLE voucher ADD COLUMN from_customer_id INTEGER;"); db.execSQL("ALTER TABLE voucher ADD COLUMN for_customer_id INTEGER;"); // convert timestamps to UTC Cursor cursor = db.rawQuery("SELECT id, last_modified FROM customer", null); try { if(cursor.moveToFirst()) { do { Date oldDate; try { oldDate = parseDateRaw(cursor.getString(1)); } catch (ParseException e) { oldDate = new Date(); } String newDateString = dateToString(oldDate); SQLiteStatement stmt = db.compileStatement("UPDATE customer SET last_modified = ? WHERE id = ?"); stmt.bindString(1, newDateString); stmt.bindLong(2, cursor.getLong(0)); stmt.execute(); } while (cursor.moveToNext()); } } catch (SQLiteException e) { Log.e("Customer utc dce", e.getMessage()); System.exit(1); } finally { cursor.close(); } cursor = db.rawQuery("SELECT id, last_modified FROM appointment", null); try { if(cursor.moveToFirst()) { do { Date oldDate; try { oldDate = parseDateRaw(cursor.getString(1)); } catch (ParseException e) { oldDate = new Date(); } String newDateString = dateToString(oldDate); SQLiteStatement stmt = db.compileStatement("UPDATE appointment SET last_modified = ? WHERE id = ?"); stmt.bindString(1, newDateString); stmt.bindLong(2, cursor.getLong(0)); stmt.execute(); } while (cursor.moveToNext()); } } catch (SQLiteException e) { Log.e("Appointment utc dce", e.getMessage()); System.exit(1); } finally { cursor.close(); } cursor = db.rawQuery("SELECT id, issued, redeemed, valid_until, last_modified FROM voucher", null); try { if(cursor.moveToFirst()) { do { Date oldDate1; try { oldDate1 = parseDateRaw(cursor.getString(1)); } catch (ParseException e) { oldDate1 = new Date(); } String newDateString1 = dateToString(oldDate1); String newDateString2 = null; if(!cursor.isNull(2) && !cursor.getString(2).equals("")) { try { Date oldDate2 = parseDateRaw(cursor.getString(2)); newDateString2 = dateToString(oldDate2); } catch (ParseException e) { e.printStackTrace(); } } String newDateString3 = null; if(!cursor.isNull(3) && !cursor.getString(3).equals("")) { try { Date oldDate3 = parseDateRaw(cursor.getString(3)); newDateString3 = dateToString(oldDate3); } catch (ParseException e) { e.printStackTrace(); } } Date oldDate4; try { oldDate4 = parseDateRaw(cursor.getString(4)); } catch (ParseException e) { oldDate4 = new Date(); } String newDateString4 = dateToString(oldDate4); SQLiteStatement stmt = db.compileStatement("UPDATE voucher SET issued = ?, redeemed = ?, valid_until = ?, last_modified = ? WHERE id = ?"); stmt.bindString(1, newDateString1); if(newDateString2 == null) { stmt.bindNull(2); } else { stmt.bindString(2, newDateString2); } if(newDateString3 == null) { stmt.bindNull(3); } else { stmt.bindString(3, newDateString3); } stmt.bindString(4, newDateString4); stmt.bindLong(5, cursor.getLong(0)); stmt.execute(); } while (cursor.moveToNext()); } } catch (SQLiteException e) { Log.e("Voucher utc dce", e.getMessage()); System.exit(1); } finally { cursor.close(); } commitTransaction(); endTransaction(); } } CustomerCalendar getCalendarById(long id, boolean showRemoved) { List<CustomerCalendar> calendars = getCalendars(showRemoved); for(CustomerCalendar c : calendars) { if(c.mId == id) { return c; } } return null; } List<CustomerCalendar> getCalendars(boolean showRemoved) { String sql = "SELECT id, title, color, notes, last_modified, removed FROM calendar WHERE removed = 0"; if(showRemoved) sql = "SELECT id, title, color, notes, last_modified, removed FROM calendar"; Cursor cursor = db.rawQuery(sql, null); ArrayList<CustomerCalendar> cf = new ArrayList<>(); try { if(cursor.moveToFirst()) { do { Date lastModified = new Date(); try { if(cursor.getString(4) != null && (!cursor.getString(4).equals(""))) lastModified = parseDate(cursor.getString(4)); } catch (ParseException e) { e.printStackTrace(); } CustomerCalendar f = new CustomerCalendar( cursor.getLong(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), lastModified, cursor.getInt(5) ); cf.add(f); } while (cursor.moveToNext()); } } catch (SQLiteException e) { Log.e("SQLite Error", e.getMessage()); return null; } finally { cursor.close(); } return cf; } void addCalendar(CustomerCalendar c) { SQLiteStatement stmt = db.compileStatement("INSERT INTO calendar (id, title, color, notes, last_modified, removed) VALUES (?,?,?,?,?,?)"); if(c.mId == -1) c.mId = CustomerCalendar.generateID(); stmt.bindLong(1, c.mId); stmt.bindString(2, c.mTitle); stmt.bindString(3, c.mColor); stmt.bindString(4, c.mNotes); stmt.bindString(5, dateToString(c.mLastModified)); stmt.bindLong(6, c.mRemoved); stmt.execute(); } void updateCalendar(CustomerCalendar c) { SQLiteStatement stmt = db.compileStatement( "UPDATE calendar SET title = ?, color = ?, notes = ?, last_modified = ?, removed = ? WHERE id = ?" ); stmt.bindString(1, c.mTitle); stmt.bindString(2, c.mColor); stmt.bindString(3, c.mNotes); stmt.bindString(4, dateToString(c.mLastModified)); stmt.bindLong(5, c.mRemoved); stmt.bindLong(6, c.mId); stmt.execute(); } void removeCalendar(CustomerCalendar c) { String currentDateString = dateToString(new Date()); SQLiteStatement stmt = db.compileStatement("UPDATE calendar SET removed = 1, title = '', color = '', notes = '', last_modified = ? WHERE id = ?"); stmt.bindString(1, currentDateString); stmt.bindLong(2, c.mId); stmt.execute(); SQLiteStatement stmt2 = db.compileStatement("UPDATE appointment SET removed = 1, calendar_id = -1, title = '', notes = '', time_start = NULL, time_end = NULL, fullday = 0, customer = '', location = '', last_modified = ? WHERE calendar_id = ?"); stmt2.bindString(1, currentDateString); stmt2.bindLong(2, c.mId); stmt2.execute(); } CustomerAppointment getAppointmentById(long id, boolean showRemoved) { Cursor cursor = db.rawQuery( "SELECT id, calendar_id, title, notes, time_start, time_end, fullday, customer, customer_id, location, last_modified, removed FROM appointment WHERE id = ?", new String[]{ Long.toString(id) } ); try { if(cursor.moveToFirst()) { do { Date startTime = null; try { if(cursor.getString(4) != null && (!cursor.getString(4).equals(""))) startTime = parseDateRaw(cursor.getString(4)); } catch (ParseException e) { Log.e("CAL", e.getLocalizedMessage()); } Date endTime = null; try { if(cursor.getString(5) != null && (!cursor.getString(5).equals(""))) endTime = parseDateRaw(cursor.getString(5)); } catch (ParseException e) { Log.e("CAL", e.getLocalizedMessage()); } Date lastModified = new Date(); try { if(cursor.getString(10) != null && (!cursor.getString(10).equals(""))) lastModified = parseDate(cursor.getString(10)); } catch (ParseException ignored) {} CustomerAppointment appointment = new CustomerAppointment( cursor.getLong(0), cursor.getLong(1), cursor.getString(2), cursor.getString(3), startTime, endTime, cursor.getInt(6) > 0, cursor.getString(7), cursor.isNull(8) ? null : cursor.getLong(8), cursor.getString(9), lastModified, cursor.getInt(11) ); if(showRemoved || appointment.mRemoved == 0) return appointment; } while (cursor.moveToNext()); } } catch (SQLiteException e) { Log.e("SQLite Error", e.getMessage()); return null; } finally { cursor.close(); } return null; } List<CustomerAppointment> getAppointments(Long calendarId, Date day, boolean showRemoved, Date modifiedSince) { Cursor cursor; if(calendarId != null && day != null && !showRemoved) { @SuppressLint("SimpleDateFormat") SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); cursor = db.rawQuery( "SELECT id, calendar_id, title, notes, time_start, time_end, fullday, customer, customer_id, location, last_modified, removed FROM appointment WHERE calendar_id = ? AND strftime('%Y-%m-%d',time_start) = ? AND removed = 0", new String[]{Long.toString(calendarId), format.format(day)} ); } else if(calendarId != null && day == null && !showRemoved) { cursor = db.rawQuery( "SELECT id, calendar_id, title, notes, time_start, time_end, fullday, customer, customer_id, location, last_modified, removed FROM appointment WHERE calendar_id = ? AND removed = 0", new String[]{Long.toString(calendarId)} ); } else { String sql; if(showRemoved) { sql = "SELECT id, calendar_id, title, notes, time_start, time_end, fullday, customer, customer_id, location, last_modified, removed FROM appointment"; } else { sql = "SELECT id, calendar_id, title, notes, time_start, time_end, fullday, customer, customer_id, location, last_modified, removed FROM appointment WHERE removed = 0"; } cursor = db.rawQuery(sql, null); } ArrayList<CustomerAppointment> al = new ArrayList<>(); try { if(cursor.moveToFirst()) { do { Date startTime = null; try { if(cursor.getString(4) != null && (!cursor.getString(4).equals(""))) startTime = parseDateRaw(cursor.getString(4)); } catch(ParseException e) { Log.e("CAL", e.getLocalizedMessage()); } Date endTime = null; try { if(cursor.getString(5) != null && (!cursor.getString(5).equals(""))) endTime = parseDateRaw(cursor.getString(5)); } catch(ParseException e) { Log.e("CAL", e.getLocalizedMessage()); } Date lastModified = new Date(); try { if(cursor.getString(10) != null && (!cursor.getString(10).equals(""))) lastModified = parseDate(cursor.getString(10)); } catch(ParseException ignored) {} CustomerAppointment a = new CustomerAppointment( cursor.getLong(0), cursor.getLong(1), cursor.getString(2), cursor.getString(3), startTime, endTime, cursor.getInt(6) > 0, cursor.getString(7), cursor.isNull(8) ? null : cursor.getLong(8), cursor.getString(9), lastModified, cursor.getInt(11) ); if(modifiedSince == null || lastModified.after(modifiedSince)) al.add(a); } while(cursor.moveToNext()); } } catch(SQLiteException e) { Log.e("SQLite Error", e.getMessage()); return null; } finally { cursor.close(); } return al; } List<CustomerAppointment> getAppointmentsByCustomer(long customerId) { Cursor cursor = db.rawQuery( "SELECT id, calendar_id, title, notes, time_start, time_end, fullday, customer, customer_id, location, last_modified, removed FROM appointment WHERE customer_id = ? AND removed = 0 ORDER BY time_start ASC", new String[]{ Long.toString(customerId) } ); ArrayList<CustomerAppointment> al = new ArrayList<>(); try { if(cursor.moveToFirst()) { do { Date startTime = null; try { if(cursor.getString(4) != null && (!cursor.getString(4).equals(""))) startTime = parseDateRaw(cursor.getString(4)); } catch (ParseException e) { Log.e("CAL", e.getLocalizedMessage()); } Date endTime = null; try { if(cursor.getString(5) != null && (!cursor.getString(5).equals(""))) endTime = parseDateRaw(cursor.getString(5)); } catch (ParseException e) { Log.e("CAL", e.getLocalizedMessage()); } Date lastModified = new Date(); try { if(cursor.getString(10) != null && (!cursor.getString(10).equals(""))) lastModified = parseDate(cursor.getString(10)); } catch (ParseException ignored) {} CustomerAppointment a = new CustomerAppointment( cursor.getLong(0), cursor.getLong(1), cursor.getString(2), cursor.getString(3), startTime, endTime, cursor.getInt(6) > 0, cursor.getString(7), cursor.isNull(8) ? null : cursor.getLong(8), cursor.getString(9), lastModified, cursor.getInt(11) ); al.add(a); } while (cursor.moveToNext()); } } catch (SQLiteException e) { Log.e("SQLite Error", e.getMessage()); return null; } finally { cursor.close(); } return al; } void addAppointment(CustomerAppointment a) { SQLiteStatement stmt = db.compileStatement("INSERT INTO appointment (id, calendar_id, title, notes, time_start, time_end, fullday, customer, customer_id, location, last_modified, removed) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)"); if(a.mId == -1) a.mId = CustomerAppointment.generateID(); String timeStartString; if(a.mTimeStart != null) { timeStartString = dateToStringRaw(a.mTimeStart); } else { timeStartString = dateToStringRaw(new Date()); } String timeEndString; if(a.mTimeEnd != null) { timeEndString = dateToStringRaw(a.mTimeEnd); } else { timeEndString = dateToStringRaw(new Date()); } stmt.bindLong(1, a.mId); stmt.bindLong(2, a.mCalendarId); stmt.bindString(3, a.mTitle); stmt.bindString(4, a.mNotes); stmt.bindString(5, timeStartString); stmt.bindString(6, timeEndString); stmt.bindLong(7, a.mFullday ? 1 : 0); stmt.bindString(8, a.mCustomer); if(a.mCustomerId == null) { stmt.bindNull(9); } else { stmt.bindLong(9, a.mCustomerId); } stmt.bindString(10, a.mLocation); stmt.bindString(11, dateToString(a.mLastModified)); stmt.bindLong(12, a.mRemoved); stmt.execute(); } void updateAppointment(CustomerAppointment a) { SQLiteStatement stmt = db.compileStatement( "UPDATE appointment SET calendar_id = ?, title = ?, notes = ?, time_start = ?, time_end = ?, fullday = ?, customer = ?, customer_id = ?, location = ?, last_modified = ?, removed = ? WHERE id = ?" ); String timeStartString; if(a.mTimeStart != null) { timeStartString = dateToStringRaw(a.mTimeStart); } else { timeStartString = dateToStringRaw(new Date()); } String timeEndString; if(a.mTimeEnd != null) { timeEndString = dateToStringRaw(a.mTimeEnd); } else { timeEndString = dateToStringRaw(new Date()); } stmt.bindLong(1, a.mCalendarId); stmt.bindString(2, a.mTitle); stmt.bindString(3, a.mNotes); stmt.bindString(4, timeStartString); stmt.bindString(5, timeEndString); stmt.bindLong(6, a.mFullday ? 1 : 0); stmt.bindString(7, a.mCustomer); if(a.mCustomerId == null) { stmt.bindNull(8); } else { stmt.bindLong(8, a.mCustomerId); } stmt.bindString(9, a.mLocation); stmt.bindString(10, dateToString(a.mLastModified)); stmt.bindLong(11, a.mRemoved); stmt.bindLong(12, a.mId); stmt.execute(); } void removeAppointment(CustomerAppointment a) { String currentDateString = dateToString(new Date()); SQLiteStatement stmt = db.compileStatement("UPDATE appointment SET removed = 1, calendar_id = -1, title = '', notes = '', time_start = NULL, time_end = NULL, fullday = 0, customer = '', customer_id = NULL, location = '', last_modified = ? WHERE id = ?"); stmt.bindString(1, currentDateString); stmt.bindLong(2, a.mId); stmt.execute(); } List<CustomField> getCustomFields() { Cursor cursor = db.rawQuery("SELECT id, title, type FROM customer_extra_fields", null); ArrayList<CustomField> cf = new ArrayList<>(); try { if (cursor.moveToFirst()) { do { CustomField f = new CustomField( cursor.getInt(0), cursor.getString(1), cursor.getInt(2) ); cf.add(f); } while (cursor.moveToNext()); } } catch (SQLiteException e) { Log.e("SQLite Error", e.getMessage()); return null; } finally { cursor.close(); } return cf; } List<CustomField> getCustomFieldPresets(int customFieldId) { Cursor cursor = db.rawQuery("SELECT id, title FROM customer_extra_presets WHERE extra_field_id = ?", new String[]{Integer.toString(customFieldId)}); ArrayList<CustomField> presets = new ArrayList<>(); try { if (cursor.moveToFirst()) { do { presets.add(new CustomField(cursor.getInt(0), cursor.getString(1), -1)); } while (cursor.moveToNext()); } } catch (SQLiteException e) { Log.e("SQLite Error", e.getMessage()); return null; } finally { cursor.close(); } return presets; } void addCustomField(CustomField cf) { SQLiteStatement stmt = db.compileStatement("INSERT INTO customer_extra_fields (title, type) VALUES (?, ?)"); stmt.bindString(1, cf.mTitle); stmt.bindLong(2, cf.mType); stmt.execute(); } void addCustomFieldPreset(int fieldId, String preset) { SQLiteStatement stmt = db.compileStatement("INSERT INTO customer_extra_presets (title, extra_field_id) VALUES (?,?)"); stmt.bindString(1, preset); stmt.bindLong(2, fieldId); stmt.execute(); } void updateCustomField(CustomField cf) { SQLiteStatement stmt = db.compileStatement("UPDATE customer_extra_fields SET title = ?, type = ? WHERE id = ?"); stmt.bindString(1, cf.mTitle); stmt.bindLong(2, cf.mType); stmt.bindLong(3, cf.mId); stmt.execute(); } void removeCustomField(int id) { SQLiteStatement stmt = db.compileStatement("DELETE FROM customer_extra_fields WHERE id = ?"); stmt.bindLong(1, id); stmt.execute(); } void removeCustomFieldPreset(int id) { SQLiteStatement stmt = db.compileStatement("DELETE FROM customer_extra_presets WHERE id = ?"); stmt.bindLong(1, id); stmt.execute(); } List<Voucher> getVouchers(String search, boolean showRemoved, Date modifiedSince) { Cursor cursor; String selectQuery = "SELECT id, current_value, original_value, voucher_no, from_customer, from_customer_id, for_customer, for_customer_id, issued, valid_until, redeemed, last_modified, notes, removed FROM voucher ORDER BY issued DESC"; cursor = db.rawQuery(selectQuery, null); ArrayList<Voucher> vouchers = new ArrayList<>(); try { if(cursor.moveToFirst()) { do { Date issued = new Date(); try { if(cursor.getString(8) != null && (!cursor.getString(8).equals(""))) issued = parseDate(cursor.getString(8)); } catch(ParseException e) { e.printStackTrace(); } Date validUntil = null; try { if(cursor.getString(9) != null && (!cursor.getString(9).equals(""))) validUntil = parseDate(cursor.getString(9)); } catch(ParseException e) { e.printStackTrace(); } Date redeemed = null; try { if(cursor.getString(10) != null && (!cursor.getString(10).equals(""))) redeemed = parseDate(cursor.getString(10)); } catch(ParseException e) { e.printStackTrace(); } Date lastModified = new Date(); try { if(cursor.getString(11) != null && (!cursor.getString(11).equals(""))) lastModified = parseDate(cursor.getString(11)); } catch(ParseException e) { e.printStackTrace(); } Voucher v = new Voucher( cursor.getLong(0), cursor.getDouble(1), cursor.getDouble(2), cursor.getString(3), cursor.getString(4), cursor.isNull(5) ? null : cursor.getLong(5), cursor.getString(6), cursor.isNull(7) ? null : cursor.getLong(7), issued, validUntil, redeemed, lastModified, cursor.getString(12), cursor.getInt(13) ); if(cursor.getInt(13) == 0 || showRemoved) { if(search == null || search.equals("")) { if(modifiedSince == null || lastModified.after(modifiedSince)) vouchers.add(v); } else { // filter if(v.mNotes.toUpperCase().contains(search.toUpperCase()) || v.mVoucherNo.toUpperCase().contains(search.toUpperCase()) || v.mFromCustomer.toUpperCase().contains(search.toUpperCase()) || v.mForCustomer.toUpperCase().contains(search.toUpperCase())) { if(modifiedSince == null || lastModified.after(modifiedSince)) vouchers.add(v); } } } } while(cursor.moveToNext()); } } catch(SQLiteException e) { Log.e("SQLite Error", e.getMessage()); return null; } finally { cursor.close(); } return vouchers; } List<Voucher> getVouchersByCustomer(long customerId) { Cursor cursor; String selectQuery = "SELECT id, current_value, original_value, voucher_no, from_customer, from_customer_id, for_customer, for_customer_id, issued, valid_until, redeemed, last_modified, notes, removed FROM voucher WHERE (from_customer_id = ? OR for_customer_id = ?) AND removed = 0 ORDER BY issued DESC"; cursor = db.rawQuery(selectQuery, new String[]{ Long.toString(customerId), Long.toString(customerId) }); ArrayList<Voucher> vouchers = new ArrayList<>(); try { if(cursor.moveToFirst()) { do { Date issued = new Date(); try { if(cursor.getString(8) != null && (!cursor.getString(8).equals(""))) issued = parseDate(cursor.getString(8)); } catch (ParseException e) { e.printStackTrace(); } Date validUntil = null; try { if(cursor.getString(9) != null && (!cursor.getString(9).equals(""))) validUntil = parseDate(cursor.getString(9)); } catch (ParseException e) { e.printStackTrace(); } Date redeemed = null; try { if(cursor.getString(10) != null && (!cursor.getString(10).equals(""))) redeemed = parseDate(cursor.getString(10)); } catch (ParseException e) { e.printStackTrace(); } Date lastModified = new Date(); try { if(cursor.getString(11) != null && (!cursor.getString(11).equals(""))) lastModified = parseDate(cursor.getString(11)); } catch (ParseException e) { e.printStackTrace(); } Voucher v = new Voucher( cursor.getLong(0), cursor.getDouble(1), cursor.getDouble(2), cursor.getString(3), cursor.getString(4), cursor.isNull(5) ? null : cursor.getLong(5), cursor.getString(6), cursor.isNull(7) ? null : cursor.getLong(7), issued, validUntil, redeemed, lastModified, cursor.getString(12), cursor.getInt(13) ); vouchers.add(v); } while(cursor.moveToNext()); } } catch(SQLiteException e) { Log.e("SQLite Error", e.getMessage()); return null; } finally { cursor.close(); } return vouchers; } void addVoucher(Voucher v) { SQLiteStatement stmt = db.compileStatement( "INSERT INTO voucher (id, current_value, original_value, voucher_no, from_customer, from_customer_id, for_customer, for_customer_id, issued, valid_until, redeemed, last_modified, notes, removed) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" ); long id = v.mId; if(id == -1) id = Voucher.generateID(); String validUntilString = ""; if(v.mValidUntil != null) { validUntilString = dateToString(v.mValidUntil); } String redeemedString = ""; if(v.mRedeemed != null) { redeemedString = dateToString(v.mRedeemed); } stmt.bindLong(1, id); stmt.bindDouble(2, v.mCurrentValue); stmt.bindDouble(3, v.mOriginalValue); stmt.bindString(4, v.mVoucherNo); stmt.bindString(5, v.mFromCustomer); if(v.mFromCustomerId == null) { stmt.bindNull(6); } else { stmt.bindLong(6, v.mFromCustomerId); } stmt.bindString(7, v.mForCustomer); if(v.mForCustomerId == null) { stmt.bindNull(8); } else { stmt.bindLong(8, v.mForCustomerId); } stmt.bindString(9, dateToString(v.mIssued)); stmt.bindString(10, validUntilString); stmt.bindString(11, redeemedString); stmt.bindString(12, dateToString(v.mLastModified)); stmt.bindString(13, v.mNotes); stmt.bindLong(14, v.mRemoved); stmt.execute(); } void updateVoucher(Voucher v) { SQLiteStatement stmt = db.compileStatement( "UPDATE voucher SET current_value = ?, original_value = ?, voucher_no = ?, from_customer = ?, from_customer_id = ?, for_customer = ?, for_customer_id = ?, issued = ?, valid_until = ?, redeemed = ?, last_modified = ?, notes = ?, removed = ? WHERE id = ?" ); String validUntilString = ""; if(v.mValidUntil != null) { validUntilString = dateToString(v.mValidUntil); } String redeemedString = ""; if(v.mRedeemed != null) { redeemedString = dateToString(v.mRedeemed); } stmt.bindDouble(1, v.mCurrentValue); stmt.bindDouble(2, v.mOriginalValue); stmt.bindString(3, v.mVoucherNo); stmt.bindString(4, v.mFromCustomer); if(v.mFromCustomerId == null) { stmt.bindNull(5); } else { stmt.bindLong(5, v.mFromCustomerId); } stmt.bindString(6, v.mForCustomer); if(v.mForCustomerId == null) { stmt.bindNull(7); } else { stmt.bindLong(7, v.mForCustomerId); } stmt.bindString(8, dateToString(v.mIssued)); stmt.bindString(9, validUntilString); stmt.bindString(10, redeemedString); stmt.bindString(11, dateToString(v.mLastModified)); stmt.bindString(12, v.mNotes); stmt.bindLong(13, v.mRemoved); stmt.bindLong(14, v.mId); stmt.execute(); } List<Customer> getCustomers(String search, boolean showRemoved, boolean withFiles, Date modifiedSince) { Cursor cursor; String selectQuery; if(showRemoved) { selectQuery = "SELECT id, title, first_name, last_name, phone_home, phone_mobile, phone_work, email, street, zipcode, city, country, birthday, customer_group, newsletter, notes, custom_fields, last_modified, removed FROM customer ORDER BY last_name, first_name ASC"; } else { selectQuery = "SELECT id, title, first_name, last_name, phone_home, phone_mobile, phone_work, email, street, zipcode, city, country, birthday, customer_group, newsletter, notes, custom_fields, last_modified, removed FROM customer WHERE removed = 0 ORDER BY last_name, first_name ASC"; } cursor = db.rawQuery(selectQuery, null); ArrayList<Customer> customers = new ArrayList<>(); try { if(cursor.moveToFirst()) { do { Date birthday = null; try { if(cursor.getString(12) != null && (!cursor.getString(12).equals(""))) birthday = storageFormatWithoutTime.parse(cursor.getString(12)); } catch(ParseException e) { e.printStackTrace(); } Date lastModified = new Date(); try { if(cursor.getString(17) != null && (!cursor.getString(17).equals(""))) lastModified = parseDate(cursor.getString(17)); } catch(ParseException e) { e.printStackTrace(); } Customer c = new Customer( cursor.getLong(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7), cursor.getString(8), cursor.getString(9), cursor.getString(10), cursor.getString(11), birthday, cursor.getString(13), cursor.getInt(14) > 0, cursor.getString(15), cursor.getString(16), lastModified, cursor.getInt(18) ); if(search == null || search.equals("")) { if(modifiedSince == null || lastModified.after(modifiedSince)) customers.add(c); } else { // search in default fields String searchUpperCase = search.toUpperCase(); if(c.mTitle.toUpperCase().contains(searchUpperCase) || c.mFirstName.toUpperCase().contains(searchUpperCase) || c.mLastName.toUpperCase().contains(searchUpperCase) || c.mPhoneHome.toUpperCase().contains(searchUpperCase) || c.mPhoneMobile.toUpperCase().contains(searchUpperCase) || c.mPhoneWork.toUpperCase().contains(searchUpperCase) || c.mEmail.toUpperCase().contains(searchUpperCase) || c.mStreet.toUpperCase().contains(searchUpperCase) || c.mZipcode.toUpperCase().contains(searchUpperCase) || c.mCity.toUpperCase().contains(searchUpperCase) || c.mCustomerGroup.toUpperCase().contains(searchUpperCase) || c.mNotes.toUpperCase().contains(searchUpperCase) ) { if(modifiedSince == null || lastModified.after(modifiedSince)) customers.add(c); } else { // search in custom fields for(CustomField cf : c.getCustomFields()) { if(cf.mValue.toUpperCase().contains(searchUpperCase)) { if(modifiedSince == null || lastModified.after(modifiedSince)) customers.add(c); break; } } } } } while(cursor.moveToNext()); } } catch(SQLiteException e) { Log.e("SQLite Error", e.getMessage()); return null; } finally { cursor.close(); } if(withFiles) { ArrayList<Customer> customersWithFiles = new ArrayList<>(); for(Customer c : customers) { customersWithFiles.add(getCustomerFiles(c)); } return customersWithFiles; } return customers; } Customer getCustomerFiles(Customer c) { Cursor cursor = db.rawQuery("SELECT image FROM customer WHERE id = ?", new String[]{Long.toString(c.mId)}); try { if(cursor.moveToFirst()) { do { c.mImage = cursor.getBlob(0); } while(cursor.moveToNext()); } } catch(SQLiteException e) { Log.e("SQLite Error", e.getMessage()); } finally { cursor.close(); } c.mFiles = new ArrayList<>(); Cursor cursor2 = db.rawQuery("SELECT name, content FROM customer_file WHERE customer_id = ?", new String[]{Long.toString(c.mId)}); try { if(cursor2.moveToFirst()) { do { c.mFiles.add(new CustomerFile( cursor2.getString(0), cursor2.getBlob(1) )); } while(cursor2.moveToNext()); } } catch(SQLiteException e) { Log.e("SQLite Error", e.getMessage()); } finally { cursor2.close(); } return c; } public Customer getCustomerByNumber(String number) { List<Customer> allCustomers = getCustomers(null, false, false, null); List<Customer> results = new ArrayList<>(); for(Customer c : allCustomers) { if(PhoneNumberUtils.compare(c.mPhoneHome, number) || PhoneNumberUtils.compare(c.mPhoneMobile, number) || PhoneNumberUtils.compare(c.mPhoneWork, number)) { results.add(c); break; } for(CustomField cf : c.getCustomFields()) { if((!cf.mValue.trim().equals("")) && PhoneNumberUtils.compare(cf.mValue.trim(), number)) { results.add(c); } } } if(results.size() > 0) { // return with customer picture for (caller id) return this.getCustomerFiles(results.get(0)); } return null; } public Customer getCustomerById(long id, boolean showRemoved, boolean withFiles) { // Do not fetch files for all customers! We'll fetch files only for the one ID match! List<Customer> customers = getCustomers(null, showRemoved, false, null); for(Customer c : customers) { if(c.mId == id) { if(withFiles) { return getCustomerFiles(c); } return c; } } return null; } Voucher getVoucherById(long id) { return getVoucherById(id, false); } Voucher getVoucherById(long id, boolean showRemoved) { List<Voucher> vouchers = getVouchers(null, showRemoved, null); for(Voucher v : vouchers) { if(v.mId == id) { return v; } } return null; } boolean addCustomer(Customer c) { // do not add if name is empty if(c.mTitle.equals("") && c.mFirstName.equals("") && c.mLastName.equals("")) return false; SQLiteStatement stmt = db.compileStatement( "INSERT INTO customer (id, title, first_name, last_name, phone_home, phone_mobile, phone_work, email, street, zipcode, city, country, birthday, customer_group, newsletter, notes, custom_fields, image, last_modified, removed) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" ); long id = c.mId; if(id == -1) id = Customer.generateID(); String birthdayString = ""; if(c.mBirthday != null) { birthdayString = storageFormatWithoutTime.format(c.mBirthday); } stmt.bindLong(1, id); stmt.bindString(2, c.mTitle); stmt.bindString(3, c.mFirstName); stmt.bindString(4, c.mLastName); stmt.bindString(5, c.mPhoneHome); stmt.bindString(6, c.mPhoneMobile); stmt.bindString(7, c.mPhoneWork); stmt.bindString(8, c.mEmail); stmt.bindString(9, c.mStreet); stmt.bindString(10, c.mZipcode); stmt.bindString(11, c.mCity); stmt.bindString(12, c.mCountry); stmt.bindString(13, birthdayString); stmt.bindString(14, c.mCustomerGroup); stmt.bindLong(15, c.mNewsletter ? 1 : 0); stmt.bindString(16, c.mNotes); stmt.bindString(17, c.mCustomFields); stmt.bindBlob(18, c.getImage()); stmt.bindString(19, dateToString(c.mLastModified)); stmt.bindLong(20, c.mRemoved); stmt.execute(); if(c.mFiles != null) { for(CustomerFile file : c.mFiles) { SQLiteStatement stmt3 = db.compileStatement("INSERT INTO customer_file (customer_id, name, content) VALUES (?,?,?)"); stmt3.bindLong(1, id); stmt3.bindString(2, file.mName); stmt3.bindBlob(3, file.mContent); stmt3.execute(); } } return true; } void updateCustomer(Customer c) { SQLiteStatement stmt = db.compileStatement( "UPDATE customer SET title = ?, first_name = ?, last_name = ?, phone_home = ?, phone_mobile = ?, phone_work = ?, email = ?, street = ?, zipcode = ?, city = ?, country = ?, birthday = ?, customer_group = ?, newsletter = ?, notes = ?, image = ?, custom_fields = ?, last_modified = ?, removed = ? WHERE id = ?" ); String birthdayString = ""; if(c.mBirthday != null) { birthdayString = storageFormatWithoutTime.format(c.mBirthday); } stmt.bindString(1, c.mTitle); stmt.bindString(2, c.mFirstName); stmt.bindString(3, c.mLastName); stmt.bindString(4, c.mPhoneHome); stmt.bindString(5, c.mPhoneMobile); stmt.bindString(6, c.mPhoneWork); stmt.bindString(7, c.mEmail); stmt.bindString(8, c.mStreet); stmt.bindString(9, c.mZipcode); stmt.bindString(10, c.mCity); stmt.bindString(11, c.mCountry); stmt.bindString(12, birthdayString); stmt.bindString(13, c.mCustomerGroup); stmt.bindLong(14, c.mNewsletter ? 1 : 0); stmt.bindString(15, c.mNotes); stmt.bindBlob(16, c.getImage()); stmt.bindString(17, c.mCustomFields); stmt.bindString(18, dateToString(c.mLastModified)); stmt.bindLong(19, c.mRemoved); stmt.bindLong(20, c.mId); stmt.execute(); if(c.mFiles != null) { SQLiteStatement stmt2 = db.compileStatement("DELETE FROM customer_file WHERE customer_id = ?"); stmt2.bindLong(1, c.mId); stmt2.execute(); for(CustomerFile file : c.mFiles) { SQLiteStatement stmt3 = db.compileStatement("INSERT INTO customer_file (customer_id, name, content) VALUES (?,?,?)"); stmt3.bindLong(1, c.mId); stmt3.bindString(2, file.mName); stmt3.bindBlob(3, file.mContent); stmt3.execute(); } } } void removeCustomer(Customer c) { String currentDateString = dateToString(new Date()); SQLiteStatement stmt = db.compileStatement("UPDATE customer SET removed = 1, title = '', first_name = '', last_name = '', phone_home = '', phone_mobile = '', phone_work = '', email = '', street = '', city = '', country = '', notes = '', customer_group = '', custom_fields = '', image = '', consent = '', birthday = '', newsletter = 0, last_modified = ? WHERE id = ?"); stmt.bindString(1, currentDateString); stmt.bindLong(2, c.mId); stmt.execute(); SQLiteStatement stmt2 = db.compileStatement("DELETE FROM customer_file WHERE customer_id = ?"); stmt2.bindLong(1, c.mId); stmt2.execute(); } void removeVoucher(Voucher v) { String currentDateString = dateToString(new Date()); SQLiteStatement stmt = db.compileStatement("UPDATE voucher SET removed = 1, current_value = 0, original_value = 0, from_customer = '', from_customer_id = NULL, for_customer = '', for_customer_id = NULL, notes = '', last_modified = ? WHERE id = ?"); stmt.bindString(1, currentDateString); stmt.bindLong(2, v.mId); stmt.execute(); } void truncateCustomers() { SQLiteStatement stmt = db.compileStatement("DELETE FROM customer WHERE 1=1"); stmt.execute(); SQLiteStatement stmt2 = db.compileStatement("DELETE FROM customer_file WHERE 1=1"); stmt2.execute(); } void truncateVouchers() { SQLiteStatement stmt = db.compileStatement("DELETE FROM voucher WHERE 1=1"); stmt.execute(); } void truncateCalendars() { SQLiteStatement stmt = db.compileStatement("DELETE FROM calendar WHERE 1=1"); stmt.execute(); } void truncateAppointments() { SQLiteStatement stmt = db.compileStatement("DELETE FROM appointment WHERE 1=1"); stmt.execute(); } }
56,017
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
CustomerDetailsActivity.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/CustomerDetailsActivity.java
package de.georgsieber.customerdb; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.print.PrintAttributes; import android.print.PrintManager; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import androidx.activity.result.ActivityResult; import androidx.activity.result.ActivityResultCallback; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.NonNull; import androidx.core.content.FileProvider; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.text.SpannableString; import android.text.Spanned; import android.text.style.URLSpan; import android.util.TypedValue; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Space; import android.widget.TextView; import java.io.File; import java.io.FileOutputStream; import java.util.Date; import java.util.List; import de.georgsieber.customerdb.importexport.CustomerCsvBuilder; import de.georgsieber.customerdb.importexport.CustomerVcfBuilder; import de.georgsieber.customerdb.model.CustomField; import de.georgsieber.customerdb.model.Customer; import de.georgsieber.customerdb.model.CustomerAppointment; import de.georgsieber.customerdb.model.CustomerFile; import de.georgsieber.customerdb.model.Voucher; import de.georgsieber.customerdb.print.CustomerPrintDocumentAdapter; import de.georgsieber.customerdb.tools.ColorControl; import de.georgsieber.customerdb.tools.CommonDialog; import de.georgsieber.customerdb.tools.StorageControl; import de.georgsieber.customerdb.tools.DateControl; public class CustomerDetailsActivity extends AppCompatActivity { private CustomerDetailsActivity me; private CustomerDatabase mDb; private long mCurrentCustomerId = -1; private Customer mCurrentCustomer = null; private SharedPreferences mSettings; private boolean mChanged = false; private final static int EDIT_CUSTOMER_REQUEST = 2; private final static int VIEW_VOUCHER_REQUEST = 3; private final static int VIEW_APPOINTMENT_REQUEST = 4; TextView mTextViewName; TextView mTextViewPhoneHome; TextView mTextViewPhoneMobile; TextView mTextViewPhoneWork; TextView mTextViewEmail; TextView mTextViewAddress; TextView mTextViewGroup; TextView mTextViewNotes; TextView mTextViewNewsletter; TextView mTextViewBirthday; TextView mTextViewLastChanged; ImageButton mButtonPhoneHomeMore; ImageButton mButtonPhoneMobileMore; ImageButton mButtonPhoneWorkMore; ImageButton mButtonEmailMore; ImageButton mButtonAddressMore; ImageButton mButtonGroupMore; ImageButton mButtonNotesMore; private ActivityResultLauncher<Intent> mResultHandlerExportMoveFile; private File mCurrentExportFile; @Override protected void onCreate(Bundle savedInstanceState) { // init settings mSettings = getSharedPreferences(MainActivity.PREFS_NAME, 0); // init activity view super.onCreate(savedInstanceState); me = this; setContentView(R.layout.activity_customer_details); setSupportActionBar((Toolbar)findViewById(R.id.toolbarView)); if(getSupportActionBar() != null) { getSupportActionBar().setTitle(getResources().getString(R.string.detailview)); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } // local database init mDb = new CustomerDatabase(this); // init colors ColorControl.updateActionBarColor(this, mSettings); ColorControl.updateAccentColor(findViewById(R.id.fabEdit), mSettings); // find views mTextViewName = findViewById(R.id.textViewName); mTextViewPhoneHome = findViewById(R.id.textViewPhoneHome); mTextViewPhoneMobile = findViewById(R.id.textViewPhoneMobile); mTextViewPhoneWork = findViewById(R.id.textViewPhoneWork); mTextViewEmail = findViewById(R.id.textViewEmail); mTextViewAddress = findViewById(R.id.textViewAddress); mTextViewGroup = findViewById(R.id.textViewGroup); mTextViewNotes = findViewById(R.id.textViewNotes); mTextViewNewsletter = findViewById(R.id.textViewNewsletter); mTextViewBirthday = findViewById(R.id.textViewBirthday); mTextViewLastChanged = findViewById(R.id.textViewLastModified); mButtonPhoneHomeMore = findViewById(R.id.buttonPhoneHomeMore); mButtonPhoneMobileMore = findViewById(R.id.buttonPhoneMobileMore); mButtonPhoneWorkMore = findViewById(R.id.buttonPhoneWorkMore); mButtonEmailMore = findViewById(R.id.buttonEmailMore); mButtonAddressMore = findViewById(R.id.buttonAddressMore); mButtonGroupMore = findViewById(R.id.buttonGroupMore); mButtonNotesMore = findViewById(R.id.buttonNotesMore); // init activity result handler mResultHandlerExportMoveFile = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() { @Override public void onActivityResult(ActivityResult result) { if(result.getResultCode() == RESULT_OK) { Uri uri = result.getData().getData(); if(uri != null) { try { StorageControl.moveFile(mCurrentExportFile, uri, me); } catch(Exception e) { CommonDialog.show(me, getString(R.string.error), e.getMessage(), CommonDialog.TYPE.FAIL, false); } } } } } ); // init context menus View.OnClickListener contextMenuClickListener = new View.OnClickListener() { @Override public void onClick(View v) { v.showContextMenu(); } }; mButtonPhoneHomeMore.setOnClickListener(contextMenuClickListener); mButtonPhoneMobileMore.setOnClickListener(contextMenuClickListener); mButtonPhoneWorkMore.setOnClickListener(contextMenuClickListener); mButtonEmailMore.setOnClickListener(contextMenuClickListener); mButtonAddressMore.setOnClickListener(contextMenuClickListener); mButtonGroupMore.setOnClickListener(contextMenuClickListener); mButtonNotesMore.setOnClickListener(contextMenuClickListener); registerForContextMenu(mButtonPhoneHomeMore); registerForContextMenu(mButtonPhoneMobileMore); registerForContextMenu(mButtonPhoneWorkMore); registerForContextMenu(mButtonEmailMore); registerForContextMenu(mButtonAddressMore); registerForContextMenu(mButtonGroupMore); registerForContextMenu(mButtonNotesMore); // hide fields if(!mSettings.getBoolean("show-customer-picture", true)) { findViewById(R.id.imageViewCustomerImage).setVisibility(View.GONE); } if(!mSettings.getBoolean("show-phone-field", true)) { findViewById(R.id.linearLayoutPhone).setVisibility(View.GONE); } if(!mSettings.getBoolean("show-email-field", true)) { findViewById(R.id.linearLayoutEmail).setVisibility(View.GONE); } if(!mSettings.getBoolean("show-address-field", true)) { findViewById(R.id.linearLayoutAddress).setVisibility(View.GONE); } if(!mSettings.getBoolean("show-group-field", true)) { findViewById(R.id.linearLayoutGroup).setVisibility(View.GONE); } if(!mSettings.getBoolean("show-notes-field", true)) { findViewById(R.id.linearLayoutNotes).setVisibility(View.GONE); } if(!mSettings.getBoolean("show-newsletter-field", true)) { findViewById(R.id.linearLayoutNewsletter).setVisibility(View.GONE); } if(!mSettings.getBoolean("show-birthday-field", true)) { findViewById(R.id.linearLayoutBirthday).setVisibility(View.GONE); } if(!mSettings.getBoolean("show-files", true)) { findViewById(R.id.linearLayoutFilesContainer).setVisibility(View.GONE); } // init fab FloatingActionButton fab = findViewById(R.id.fabEdit); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent myIntent = new Intent(me, CustomerEditActivity.class); myIntent.putExtra("customer-id", mCurrentCustomerId); me.startActivityForResult(myIntent, EDIT_CUSTOMER_REQUEST); } }); // get current customer Intent intent = getIntent(); mCurrentCustomerId = intent.getLongExtra("customer-id", -1); loadCustomer(); } private void loadCustomer() { // load current values from database with images and files mCurrentCustomer = mDb.getCustomerById(mCurrentCustomerId, false, true); if(mCurrentCustomer == null) { finish(); } else { createListEntries(mCurrentCustomer); } } @Override public void onDestroy() { mDb.close(); super.onDestroy(); } @Override public void finish() { // report MainActivity to update customer list if(mChanged) { Intent output = new Intent(); output.putExtra("action", "update"); setResult(RESULT_OK, output); } super.finish(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch(requestCode) { case(EDIT_CUSTOMER_REQUEST): if(resultCode == Activity.RESULT_OK) { // update view mChanged = true; loadCustomer(); } break; case(VIEW_VOUCHER_REQUEST): case(VIEW_APPOINTMENT_REQUEST): if(resultCode == Activity.RESULT_OK) { // update view loadCustomer(); } break; } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_customer_details, menu); if(mCurrentCustomer != null && mCurrentCustomer.mId != -1) // show mId in menu menu.findItem(R.id.action_id).setTitle( "ID: " + mCurrentCustomer.mId ); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.action_remove: confirmRemove(); return true; case R.id.action_export: this.export(); return true; case R.id.action_print: print(); return true; case android.R.id.home: finish(); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean("changed", mChanged); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); mChanged = savedInstanceState.getBoolean("changed"); } private final static int CMI_PHOME_CALL = 1; private final static int CMI_PHOME_MSG = 2; private final static int CMI_PHOME_CPY = 3; private final static int CMI_PMOBILE_CALL = 4; private final static int CMI_PMOBILE_MSG = 5; private final static int CMI_PMOBILE_CPY = 6; private final static int CMI_PWORK_CALL = 7; private final static int CMI_PWORK_MSG = 8; private final static int CMI_PWORK_CPY = 9; private final static int CMI_EMAIL_MSG = 10; private final static int CMI_EMAIL_CPY = 11; private final static int CMI_ADDRESS_MAP = 12; private final static int CMI_ADDRESS_CPY = 13; private final static int CMI_POST_ADDRESS_CPY = 16; private final static int CMI_GROUP_CPY = 14; private final static int CMI_NOTES_CPY = 15; @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); if(v == mButtonPhoneHomeMore) { menu.setHeaderTitle(mCurrentCustomer.mPhoneHome); menu.add(0, CMI_PHOME_CALL, 0, getString(R.string.do_call)); menu.add(0, CMI_PHOME_MSG, 0, getString(R.string.send_message)); menu.add(0, CMI_PHOME_CPY, 0, getString(R.string.copy_to_clipboard)); } else if(v == mButtonPhoneMobileMore) { menu.setHeaderTitle(mCurrentCustomer.mPhoneMobile); menu.add(0, CMI_PMOBILE_CALL, 0, getString(R.string.do_call)); menu.add(0, CMI_PMOBILE_MSG, 0, getString(R.string.send_message)); menu.add(0, CMI_PMOBILE_CPY, 0, getString(R.string.copy_to_clipboard)); } else if(v == mButtonPhoneWorkMore) { menu.setHeaderTitle(mCurrentCustomer.mPhoneWork); menu.add(0, CMI_PWORK_CALL, 0, getString(R.string.do_call)); menu.add(0, CMI_PWORK_MSG, 0, getString(R.string.send_message)); menu.add(0, CMI_PWORK_CPY, 0, getString(R.string.copy_to_clipboard)); } else if(v == mButtonEmailMore) { menu.setHeaderTitle(mCurrentCustomer.mEmail); menu.add(0, CMI_EMAIL_MSG, 0, getString(R.string.send_message)); menu.add(0, CMI_EMAIL_CPY, 0, getString(R.string.copy_to_clipboard)); } else if(v == mButtonAddressMore) { menu.setHeaderTitle(mCurrentCustomer.getAddress()); menu.add(0, CMI_ADDRESS_MAP, 0, getString(R.string.show_on_map)); menu.add(0, CMI_ADDRESS_CPY, 0, getString(R.string.copy_to_clipboard)); menu.add(0, CMI_POST_ADDRESS_CPY, 0, getString(R.string.copy_postal_address)); } else if(v == mButtonGroupMore) { menu.setHeaderTitle(mCurrentCustomer.mCustomerGroup); menu.add(0, CMI_GROUP_CPY, 0, getString(R.string.copy_to_clipboard)); } else if(v == mButtonNotesMore) { menu.setHeaderTitle(mCurrentCustomer.mNotes); menu.add(0, CMI_NOTES_CPY, 0, getString(R.string.copy_to_clipboard)); } } @Override public boolean onContextItemSelected(MenuItem item) { switch(item.getItemId()) { case CMI_PHOME_CALL: startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + mCurrentCustomer.mPhoneHome.replaceAll("[^\\d]", "")))); return true; case CMI_PHOME_MSG: startActivity(new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", mCurrentCustomer.mPhoneHome, null))); return true; case CMI_PHOME_CPY: toClipboard(mCurrentCustomer.mPhoneHome); return true; case CMI_PMOBILE_CALL: startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + mCurrentCustomer.mPhoneMobile.replaceAll("[^\\d]", "")))); return true; case CMI_PMOBILE_MSG: startActivity(new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", mCurrentCustomer.mPhoneMobile, null))); return true; case CMI_PMOBILE_CPY: toClipboard(mCurrentCustomer.mPhoneMobile); return true; case CMI_PWORK_CALL: startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + mCurrentCustomer.mPhoneWork.replaceAll("[^\\d]", "")))); return true; case CMI_PWORK_MSG: startActivity(new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", mCurrentCustomer.mPhoneWork, null))); return true; case CMI_PWORK_CPY: toClipboard(mCurrentCustomer.mPhoneWork); return true; case CMI_EMAIL_MSG: onClickEmailLink(null); return true; case CMI_EMAIL_CPY: toClipboard(mCurrentCustomer.mEmail); return true; case CMI_ADDRESS_MAP: try { Uri gmmIntentUri = Uri.parse("geo:0,0?q="+ mCurrentCustomer.getAddress()); Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri); startActivity(mapIntent); } catch(Exception ignored) {} return true; case CMI_ADDRESS_CPY: toClipboard(mCurrentCustomer.getAddress()); return true; case CMI_POST_ADDRESS_CPY: toClipboard(mCurrentCustomer.getFullName(false) + "\n" + mCurrentCustomer.getAddress()); return true; case CMI_GROUP_CPY: toClipboard(mCurrentCustomer.mCustomerGroup); return true; case CMI_NOTES_CPY: toClipboard(mCurrentCustomer.mNotes); return true; } return false; } private void print() { if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { PrintManager printManager = (PrintManager) this.getSystemService(Context.PRINT_SERVICE); if(printManager != null) { String jobName = "Customer Database"; PrintAttributes pa = new PrintAttributes.Builder() .setColorMode(PrintAttributes.COLOR_MODE_COLOR) .setMediaSize(PrintAttributes.MediaSize.ISO_A4) .setResolution(new PrintAttributes.Resolution("customerdb", PRINT_SERVICE, 300, 300)) .setMinMargins(PrintAttributes.Margins.NO_MARGINS) .build(); printManager.print(jobName, new CustomerPrintDocumentAdapter(this, mCurrentCustomer), pa); } } else { CommonDialog.show(this,getResources().getString(R.string.not_supported), getResources().getString(R.string.not_supported_printing), CommonDialog.TYPE.FAIL, false); } } private void export() { final Dialog ad = new Dialog(this); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_export_single_customer); ad.findViewById(R.id.buttonExportSingleCSV).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); if(new CustomerCsvBuilder(mCurrentCustomer, mDb.getCustomFields()).saveCsvFile(getStorageExportCSV())) { mCurrentExportFile = getStorageExportCSV(); CommonDialog.exportFinishedDialog(me, getStorageExportCSV(), "text/csv", new String[]{mCurrentCustomer.mEmail}, mSettings.getString("email-export-subject", getResources().getString(R.string.email_export_subject_template)), mSettings.getString("email-export-template", getResources().getString(R.string.email_export_text_template)).replace("CUSTOMER", mCurrentCustomer.getFullName(false)) + "\n\n", mResultHandlerExportMoveFile ); } else { CommonDialog.show(me, getResources().getString(R.string.export_fail), getStorageExportCSV().getPath(), CommonDialog.TYPE.FAIL, false); } StorageControl.scanFile(getStorageExportCSV(), me); } }); ad.findViewById(R.id.buttonExportSingleVCF).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); if(new CustomerVcfBuilder(mCurrentCustomer).saveVcfFile(getStorageExportVCF())) { mCurrentExportFile = getStorageExportVCF(); CommonDialog.exportFinishedDialog(me, getStorageExportVCF(), "text/vcard", new String[]{mCurrentCustomer.mEmail}, mSettings.getString("email-export-subject", getResources().getString(R.string.email_export_subject_template)), mSettings.getString("email-export-template", getResources().getString(R.string.email_export_text_template)).replace("CUSTOMER", mCurrentCustomer.getFullName(false)) + "\n\n", mResultHandlerExportMoveFile ); } else { CommonDialog.show(me, getResources().getString(R.string.export_fail), getStorageExportVCF().getPath(), CommonDialog.TYPE.FAIL, false); } StorageControl.scanFile(getStorageExportVCF(), me); } }); ad.findViewById(R.id.buttonExportSingleCancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); } }); ad.show(); } private File getStorageExportCSV() { File exportDir = new File(getExternalFilesDir(null), "export"); exportDir.mkdirs(); return new File(exportDir, "export."+ mCurrentCustomer.mId+".csv"); } private File getStorageExportVCF() { File exportDir = new File(getExternalFilesDir(null), "export"); exportDir.mkdirs(); return new File(exportDir, "export."+ mCurrentCustomer.mId+".vcf"); } private void confirmRemove() { AlertDialog.Builder ad = new AlertDialog.Builder(me); ad.setPositiveButton(getResources().getString(R.string.delete), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mDb.removeCustomer(mCurrentCustomer); mChanged = false; Intent output = new Intent(); output.putExtra("action", "update"); setResult(RESULT_OK, output); finish(); }}); ad.setNegativeButton(getResources().getString(R.string.abort), null); ad.setTitle(getResources().getString(R.string.reallydelete_title)); ad.setMessage(getResources().getString(R.string.reallydelete)); ad.setIcon(getResources().getDrawable(R.drawable.remove)); ad.show(); } @SuppressLint("SetTextI18n") private void createListEntries(Customer c) { mTextViewName.setText( c.getFullName(false) ); mTextViewPhoneHome.setText( c.mPhoneHome ); mTextViewPhoneMobile.setText( c.mPhoneMobile ); mTextViewPhoneWork.setText( c.mPhoneWork ); mTextViewEmail.setText( c.mEmail ); mTextViewAddress.setText( c.getAddress() ); mTextViewBirthday.setText( c.getBirthdayString() ); mTextViewLastChanged.setText( DateControl.displayDateFormat.format(c.mLastModified) ); mTextViewNotes.setText( c.mNotes ); mTextViewGroup.setText( c.mCustomerGroup ); mTextViewNewsletter.setText( c.mNewsletter ? getResources().getString(R.string.yes) : getResources().getString(R.string.no)); if(c.mPhoneHome.equals("")) mButtonPhoneHomeMore.setEnabled(false); else mButtonPhoneHomeMore.setEnabled(true); if(c.mPhoneMobile.equals("")) mButtonPhoneMobileMore.setEnabled(false); else mButtonPhoneMobileMore.setEnabled(true); if(c.mPhoneWork.equals("")) mButtonPhoneWorkMore.setEnabled(false); else mButtonPhoneWorkMore.setEnabled(true); if(c.mEmail.equals("")) mButtonEmailMore.setEnabled(false); else mButtonEmailMore.setEnabled(true); if(c.getAddress().equals("")) mButtonAddressMore.setEnabled(false); else mButtonAddressMore.setEnabled(true); if(c.mCustomerGroup.equals("")) mButtonGroupMore.setEnabled(false); else mButtonGroupMore.setEnabled(true); if(c.mNotes.equals("")) mButtonNotesMore.setEnabled(false); else mButtonNotesMore.setEnabled(true); // fake link... we handle the email click event not with autolink, because this launches always the system email app on huawei devices :-( final CharSequence text = mTextViewEmail.getText(); final SpannableString spannableString = new SpannableString( text ); spannableString.setSpan(new URLSpan(""), 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); mTextViewEmail.setText(spannableString, TextView.BufferType.SPANNABLE); // custom fields final float scale = getResources().getDisplayMetrics().density; LinearLayout linearLayoutCustomFields = findViewById(R.id.linearLayoutCustomFieldsView); linearLayoutCustomFields.removeAllViews(); List<CustomField> customFields = mDb.getCustomFields(); if(customFields.size() > 0) linearLayoutCustomFields.setVisibility(View.VISIBLE); for(CustomField cf : customFields) { TextView descriptionView = new TextView(this); descriptionView.setText(cf.mTitle); descriptionView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT)); String value = c.getCustomField(cf.mTitle); TextView valueView = new TextView(this); valueView.setTextIsSelectable(true); if(value != null) { String displayValue = value; if(cf.mType == 3) { // try parse value from storage (normalized) format and show it in local format try { Date selectedDate = CustomerDatabase.parseDateRaw(value); displayValue = DateControl.birthdayDateFormat.format(selectedDate); } catch(Exception ignored) {} } valueView.setText(displayValue); } valueView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT)); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { valueView.setTextAppearance(R.style.TextAppearance_AppCompat); } valueView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18); View spaceView = new Space(this); spaceView.setLayoutParams(new LinearLayout.LayoutParams(0, (int)(20/*dp*/ * scale + 0.5f))); linearLayoutCustomFields.addView(spaceView); linearLayoutCustomFields.addView(descriptionView); linearLayoutCustomFields.addView(valueView); } // customer image if(mCurrentCustomer.getImage().length != 0) { Bitmap bitmap = BitmapFactory.decodeByteArray(mCurrentCustomer.getImage(), 0, mCurrentCustomer.getImage().length); ((ImageView) findViewById(R.id.imageViewCustomerImage)).setImageBitmap(bitmap); } else { ((ImageView) findViewById(R.id.imageViewCustomerImage)).setImageDrawable(getResources().getDrawable(R.drawable.ic_person_black_96dp)); } // files LinearLayout linearLayoutFilesView = findViewById(R.id.linearLayoutFilesView); linearLayoutFilesView.removeAllViews(); for(final CustomerFile file : mCurrentCustomer.getFiles()) { @SuppressLint("InflateParams") LinearLayout linearLayoutFile = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.item_file_list, null); Button buttonFilename = linearLayoutFile.findViewById(R.id.buttonFile); buttonFilename.setText(file.mName); buttonFilename.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { File f = StorageControl.getStorageFileTemp(me, file.mName); try { FileOutputStream stream = new FileOutputStream(f); stream.write(file.mContent); stream.flush(); stream.close(); Uri openUri = FileProvider.getUriForFile(me, "de.georgsieber.customerdb.provider", f); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(openUri); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); startActivity(intent); } catch(Exception e) { CommonDialog.show(me, getString(R.string.error), e.getLocalizedMessage(), CommonDialog.TYPE.FAIL, false); } StorageControl.scanFile(f, me); } }); linearLayoutFilesView.addView(linearLayoutFile); } // vouchers final String currency = mSettings.getString("currency", ""); LinearLayout linearLayoutVouchersView = findViewById(R.id.linearLayoutAssignedVouchersView); linearLayoutVouchersView.removeAllViews(); for(final Voucher voucher : mDb.getVouchersByCustomer(mCurrentCustomer.mId)) { @SuppressLint("InflateParams") LinearLayout linearLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.item_simple_button, null); Button button = linearLayout.findViewById(R.id.buttonSimple); if(!voucher.mVoucherNo.equals("")) { button.setText("#"+voucher.mVoucherNo+" ("+voucher.getCurrentValueString()+" "+currency+")"); } else { button.setText("#"+Long.toString(voucher.mId)+" ("+voucher.getCurrentValueString()+" "+currency+")"); } button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent myIntent = new Intent(me, VoucherDetailsActivity.class); myIntent.putExtra("voucher-id", voucher.mId); me.startActivityForResult(myIntent, VIEW_VOUCHER_REQUEST); } }); linearLayoutVouchersView.addView(linearLayout); } // appointments LinearLayout linearLayoutAppointmentsView = findViewById(R.id.linearLayoutAssignedAppointmentsView); linearLayoutAppointmentsView.removeAllViews(); for(final CustomerAppointment appointment : mDb.getAppointmentsByCustomer(mCurrentCustomer.mId)) { @SuppressLint("InflateParams") LinearLayout linearLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.item_simple_button, null); Button button = linearLayout.findViewById(R.id.buttonSimple); button.setText(DateControl.displayDateFormat.format(appointment.mTimeStart)+" - "+appointment.mTitle); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent myIntent = new Intent(me, CalendarAppointmentEditActivity.class); myIntent.putExtra("appointment-id", appointment.mId); me.startActivityForResult(myIntent, VIEW_APPOINTMENT_REQUEST); } }); linearLayoutAppointmentsView.addView(linearLayout); } } public void onClickEmailLink(View v) { // this opens app chooser instead of system mEmail app Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("message/rfc822"); intent.putExtra(Intent.EXTRA_EMAIL, new String[]{mCurrentCustomer.mEmail}); intent.putExtra(Intent.EXTRA_SUBJECT, mSettings.getString("email-subject", getResources().getString(R.string.email_subject_template))); intent.putExtra(Intent.EXTRA_TEXT, mSettings.getString("email-template", getResources().getString(R.string.email_text_template)) .replace("CUSTOMER", mCurrentCustomer.getFullName(false)) + "\n\n" ); startActivity(Intent.createChooser(intent, getResources().getString(R.string.emailtocustomer))); } private void toClipboard(String text) { ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("phone", text); if (clipboard != null) { clipboard.setPrimaryClip(clip); } Snackbar.make(findViewById(R.id.fabEdit), getResources().getString(R.string.copied_to_clipboard), Snackbar.LENGTH_SHORT) .setAction("Action", null) .show(); } }
33,822
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
DrawActivity.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/DrawActivity.java
package de.georgsieber.customerdb; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Color; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.os.Bundle; import android.util.Base64; import android.view.Menu; import android.view.MenuItem; import android.view.View; import java.io.ByteArrayOutputStream; public class DrawActivity extends AppCompatActivity { private DrawingView dv; @Override protected void onCreate(Bundle savedInstanceState) { // init activity view super.onCreate(savedInstanceState); setContentView(R.layout.activity_draw); dv = findViewById(R.id.drawingView); // init toolbar Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); if(getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_draw, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case android.R.id.home: finish(); break; case R.id.action_done: Intent data = new Intent(); data.putExtra("image", bitmapToBase64(bitmapFromView(dv))); setResult(RESULT_OK, data); finish(); break; case R.id.action_abort: setResult(-1); finish(); break; case R.id.action_clear: dv.mCanvas.drawColor(Color.WHITE); dv.invalidate(); break; } return true; } private String bitmapToBase64(Bitmap b) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); b.compress(Bitmap.CompressFormat.JPEG, 90, byteArrayOutputStream); byte[] byteArray = byteArrayOutputStream.toByteArray(); return Base64.encodeToString(byteArray, Base64.NO_WRAP); } public Bitmap bitmapFromView(View v) { Bitmap bitmap; v.setDrawingCacheEnabled(true); bitmap = Bitmap.createBitmap(v.getDrawingCache()); v.setDrawingCacheEnabled(false); return bitmap; } }
2,408
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
VoucherDetailsActivity.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/VoucherDetailsActivity.java
package de.georgsieber.customerdb; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.print.PrintAttributes; import android.print.PrintManager; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.EditText; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import com.google.android.material.floatingactionbutton.FloatingActionButton; import java.util.Date; import de.georgsieber.customerdb.model.Customer; import de.georgsieber.customerdb.model.Voucher; import de.georgsieber.customerdb.print.VoucherPrintDocumentAdapter; import de.georgsieber.customerdb.tools.ColorControl; import de.georgsieber.customerdb.tools.CommonDialog; import de.georgsieber.customerdb.tools.NumTools; public class VoucherDetailsActivity extends AppCompatActivity { private VoucherDetailsActivity me; private CustomerDatabase mDb; private long mCurrentVoucherId = -1; private Voucher mCurrentVoucher = null; private SharedPreferences mSettings; private String currency = "?"; private boolean mChanged = false; TextView mTextViewCurrentValue; TextView mTextViewOriginalValue; TextView mTextViewVoucherNo; TextView mTextViewFromCustomer; TextView mTextViewForCustomer; TextView mTextViewNotes; TextView mTextViewIssued; TextView mTextViewValidUntil; TextView mTextViewRedeemed; TextView mTextViewLastModified; private final static int EDIT_VOUCHER_REQUEST = 1; @Override protected void onCreate(Bundle savedInstanceState) { // init settings mSettings = getSharedPreferences(MainActivity.PREFS_NAME, 0); currency = mSettings.getString("currency", "€"); // init activity view super.onCreate(savedInstanceState); me = this; setContentView(R.layout.activity_voucher_details); setSupportActionBar((Toolbar)findViewById(R.id.toolbarView)); if(getSupportActionBar() != null) { getSupportActionBar().setTitle(getResources().getString(R.string.detailview)); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } // local database init mDb = new CustomerDatabase(this); // init colors ColorControl.updateActionBarColor(this, mSettings); ColorControl.updateAccentColor(findViewById(R.id.fabEdit), mSettings); // find views mTextViewCurrentValue = findViewById(R.id.textViewCurrentValue); mTextViewOriginalValue = findViewById(R.id.textViewOriginalValue); mTextViewVoucherNo = findViewById(R.id.textViewVoucherNo); mTextViewFromCustomer = findViewById(R.id.textViewFromCustomer); mTextViewForCustomer = findViewById(R.id.textViewForCustomer); mTextViewNotes = findViewById(R.id.textViewNotes); mTextViewIssued = findViewById(R.id.textViewIssued); mTextViewValidUntil = findViewById(R.id.textViewValidUntil); mTextViewRedeemed = findViewById(R.id.textViewRedeemed); mTextViewLastModified = findViewById(R.id.textViewLastModified); // init fab FloatingActionButton fab = findViewById(R.id.fabEdit); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent myIntent = new Intent(me, VoucherEditActivity.class); myIntent.putExtra("voucher-id", mCurrentVoucher.mId); me.startActivityForResult(myIntent, EDIT_VOUCHER_REQUEST); } }); // get current voucher Intent intent = getIntent(); mCurrentVoucherId = intent.getLongExtra("voucher-id", -1); loadVoucher(); } private void loadVoucher() { // load current values from database mCurrentVoucher = mDb.getVoucherById(mCurrentVoucherId, false); if(mCurrentVoucher == null) { finish(); } else { createListEntries(mCurrentVoucher); } } @Override public void onDestroy() { mDb.close(); super.onDestroy(); } @Override public void finish() { // report MainActivity to update customer list if(mChanged) { Intent output = new Intent(); output.putExtra("action", "update"); setResult(RESULT_OK, output); } super.finish(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch(requestCode) { case(EDIT_VOUCHER_REQUEST) : { if(resultCode == Activity.RESULT_OK) { mChanged = true; loadVoucher(); } break; } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_voucher_details, menu); if(mCurrentVoucher != null && mCurrentVoucher.mId != -1) // show mId in menu menu.findItem(R.id.action_id).setTitle( "ID: " + mCurrentVoucher.mId ); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.action_redeem: showRedeemVoucher(mCurrentVoucher); return true; case R.id.action_remove: confirmRemove(); return true; //case R.mId.action_export: // not implemented yet // this.export(); // return true; case R.id.action_print: print(mCurrentVoucher); return true; case android.R.id.home: finish(); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean("changed", mChanged); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); mChanged = savedInstanceState.getBoolean("changed"); } private void confirmRemove() { AlertDialog.Builder ad = new AlertDialog.Builder(me); ad.setPositiveButton(getResources().getString(R.string.delete), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mDb.removeVoucher(mCurrentVoucher); mChanged = false; Intent output = new Intent(); output.putExtra("action", "update"); setResult(RESULT_OK, output); finish(); }}); ad.setNegativeButton(getResources().getString(R.string.abort), null); ad.setTitle(getResources().getString(R.string.reallydelete_title)); ad.setMessage(getResources().getString(R.string.reallydelete_voucher)); ad.setIcon(getResources().getDrawable(R.drawable.remove)); ad.show(); } @SuppressLint("SetTextI18n") private void createListEntries(Voucher v) { mTextViewCurrentValue.setText( v.getCurrentValueString()+" "+currency ); mTextViewOriginalValue.setText( v.getOriginalValueString()+" "+currency ); mTextViewVoucherNo.setText( v.mVoucherNo ); mTextViewNotes.setText( v.mNotes ); mTextViewIssued.setText( v.getIssuedString() ); mTextViewValidUntil.setText( v.getValidUntilString() ); mTextViewRedeemed.setText( v.getRedeemedString() ); mTextViewLastModified.setText( v.getLastModifiedString() ); if(v.mFromCustomerId != null) { Customer relatedCustomer = mDb.getCustomerById(v.mFromCustomerId, false, false); if(relatedCustomer != null) { mTextViewFromCustomer.setText(relatedCustomer.getFullName(false)); } else { mTextViewFromCustomer.setText(getString(R.string.removed_placeholder)); } } else { mTextViewFromCustomer.setText(v.mFromCustomer); } if(v.mForCustomerId != null) { Customer relatedCustomer = mDb.getCustomerById(v.mForCustomerId, false, false); if(relatedCustomer != null) { mTextViewForCustomer.setText(relatedCustomer.getFullName(false)); } else { mTextViewForCustomer.setText(getString(R.string.removed_placeholder)); } } else { mTextViewForCustomer.setText(v.mFromCustomer); } } public void showRedeemVoucher(final Voucher vo) { final Dialog ad = new Dialog(this); ad.requestWindowFeature(Window.FEATURE_NO_TITLE); ad.setContentView(R.layout.dialog_voucher_redeem); ad.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); final EditText editTextVoucherNotes = ad.findViewById(R.id.editTextVoucherNewNotes); final EditText editTextValueRedeem = ad.findViewById(R.id.editTextVoucherValueRedeem); editTextVoucherNotes.setText(vo.mNotes); editTextValueRedeem.setText(vo.getCurrentValueString()); editTextValueRedeem.selectAll(); ad.findViewById(R.id.buttonVoucherRedeemOK).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); String subtractValueString = editTextValueRedeem.getText().toString(); Double subtractValue = NumTools.tryParseDouble(subtractValueString); if(subtractValue == null) { CommonDialog.show(me, getResources().getString(R.string.invalid_number), getResources().getString(R.string.invalid_number_text), CommonDialog.TYPE.FAIL, false); } else { vo.mCurrentValue -= subtractValue; vo.mNotes = editTextVoucherNotes.getText().toString(); vo.mRedeemed = new Date(); vo.mLastModified = new Date(); mDb.updateVoucher(vo); mChanged = true; MainActivity.setUnsyncedChanges(me); loadVoucher(); } } }); ad.findViewById(R.id.buttonVoucherRedeemClose).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ad.dismiss(); } }); ad.show(); } private void print(Voucher v) { if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { PrintManager printManager = (PrintManager) this.getSystemService(Context.PRINT_SERVICE); if(printManager != null) { PrintAttributes.MediaSize ms = PrintAttributes.MediaSize.ISO_A5; String jobName = "Customer Database Voucher"; PrintAttributes pa = new PrintAttributes.Builder() .setColorMode(PrintAttributes.COLOR_MODE_COLOR) .setMediaSize(ms.asLandscape()) .setResolution(new PrintAttributes.Resolution("customerdb", PRINT_SERVICE, 300, 300)) .setMinMargins(PrintAttributes.Margins.NO_MARGINS) .build(); printManager.print(jobName, new VoucherPrintDocumentAdapter(this, v, currency), pa); } } else { CommonDialog.show(this, getResources().getString(R.string.not_supported), getResources().getString(R.string.not_supported_printing), CommonDialog.TYPE.FAIL, false); } } }
12,252
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
CustomerDatabaseApp.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/CustomerDatabaseApp.java
package de.georgsieber.customerdb; import android.app.Application; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Configuration; import androidx.appcompat.app.AppCompatDelegate; public class CustomerDatabaseApp extends Application { @Override public void onCreate() { setAppTheme(getAppTheme(getApplicationContext())); super.onCreate(); } public static void setAppTheme(int setting) { AppCompatDelegate.setDefaultNightMode(setting); } public static int getAppTheme(Context context) { SharedPreferences prefs = context.getSharedPreferences(MainActivity.PREFS_NAME, 0); return prefs.getInt("dark-mode-native", AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM); } public static boolean isDarkThemeActive(Context context, int setting) { if(setting == AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) { return isDarkThemeActive(context); } else { return setting == AppCompatDelegate.MODE_NIGHT_YES; } } public static boolean isDarkThemeActive(Context context) { int uiMode = context.getResources().getConfiguration().uiMode; return (uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES; } }
1,311
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
CustomerDatabaseApi.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/CustomerDatabaseApi.java
package de.georgsieber.customerdb; import android.util.Base64; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.lang.ref.WeakReference; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.Locale; import de.georgsieber.customerdb.model.Customer; import de.georgsieber.customerdb.model.CustomerAppointment; import de.georgsieber.customerdb.model.CustomerCalendar; import de.georgsieber.customerdb.model.CustomerFile; import de.georgsieber.customerdb.model.Voucher; public class CustomerDatabaseApi { static String MANAGED_API = "https://customerdb.sieber.systems/api.php"; private WeakReference<MainActivity> mMainActivityReference; private String mPurchaseToken; private String mApiUrl; private String mUsername; private String mPassword; private CustomerDatabase mDb; CustomerDatabaseApi(MainActivity context, String purchaseToken, String username, String password, CustomerDatabase db) { mMainActivityReference = new WeakReference<>(context); mPurchaseToken = purchaseToken; mApiUrl = MANAGED_API; mUsername = username; mPassword = password; mDb = db; } CustomerDatabaseApi(MainActivity context, String purchaseToken, String url, String username, String password, CustomerDatabase db) { mMainActivityReference = new WeakReference<>(context); mPurchaseToken = purchaseToken; mApiUrl = url; mUsername = username; mPassword = password; mDb = db; } private readyListener mReadyListener = null; public interface readyListener { void ready(Exception e); } void setReadyListener(readyListener listener) { this.mReadyListener = listener; } protected void sync(final Date diffSince) { new Thread(new Runnable() { @Override public void run() { try { putCustomers(diffSince); readCustomers(diffSince); if(mReadyListener != null) mReadyListener.ready(null); } catch(Exception e) { if(mReadyListener != null) mReadyListener.ready(e); } } }).start(); } private void putCustomers(Date diffSince) throws Exception { try { JSONArray jarrayCustomers = new JSONArray(); for(Customer c : mDb.getCustomers(null, true, true, diffSince)) { JSONArray jsonFiles = new JSONArray(); for(CustomerFile file : c.getFiles()) { JSONObject jsonFile = new JSONObject(); jsonFile.put("name", file.mName); jsonFile.put("content", Base64.encodeToString(file.mContent, Base64.NO_WRAP)); jsonFiles.put(jsonFile); } JSONObject jc = new JSONObject(); jc.put("id", c.mId); jc.put("title", c.mTitle); jc.put("first_name", c.mFirstName); jc.put("last_name", c.mLastName); jc.put("phone_home", c.mPhoneHome); jc.put("phone_mobile", c.mPhoneMobile); jc.put("phone_work", c.mPhoneWork); jc.put("email", c.mEmail); jc.put("street", c.mStreet); jc.put("zipcode", c.mZipcode); jc.put("city", c.mCity); jc.put("country", c.mCountry); jc.put("birthday", c.mBirthday == null ? JSONObject.NULL : CustomerDatabase.dateToStringRaw(c.mBirthday)); jc.put("customer_group", c.mCustomerGroup); jc.put("newsletter", c.mNewsletter ? 1 : 0); jc.put("notes", c.mNotes); jc.put("image", (c.mImage==null ? JSONObject.NULL : Base64.encodeToString(c.mImage, Base64.NO_WRAP))); jc.put("consent", JSONObject.NULL); jc.put("files", (jsonFiles.length()==0 ? JSONObject.NULL : jsonFiles.toString())); jc.put("custom_fields", c.mCustomFields); jc.put("last_modified", CustomerDatabase.dateToString(c.mLastModified)); jc.put("removed", c.mRemoved); jarrayCustomers.put(jc); } JSONArray jarrayCalendars = new JSONArray(); for(CustomerCalendar c : mDb.getCalendars(true)) { JSONObject jc = new JSONObject(); jc.put("id", c.mId); jc.put("title", c.mTitle); jc.put("color", c.mColor); jc.put("notes", c.mNotes); jc.put("last_modified", CustomerDatabase.dateToString(c.mLastModified)); jc.put("removed", c.mRemoved); jarrayCalendars.put(jc); } JSONArray jarrayAppointments = new JSONArray(); for(CustomerAppointment a : mDb.getAppointments(null,null, true, diffSince)) { JSONObject jc = new JSONObject(); jc.put("id", a.mId); jc.put("calendar_id", a.mCalendarId); jc.put("title", a.mTitle); jc.put("notes", a.mNotes); jc.put("time_start", a.mTimeStart == null ? JSONObject.NULL : CustomerDatabase.dateToStringRaw(a.mTimeStart)); jc.put("time_end", a.mTimeEnd == null ? JSONObject.NULL : CustomerDatabase.dateToStringRaw(a.mTimeEnd)); jc.put("fullday", a.mFullday); jc.put("customer", a.mCustomer); jc.put("customer_id", a.mCustomerId == null ? JSONObject.NULL : a.mCustomerId); jc.put("location", a.mLocation); jc.put("last_modified", CustomerDatabase.dateToString(a.mLastModified)); jc.put("removed", a.mRemoved); jarrayAppointments.put(jc); } JSONArray jarrayVouchers = new JSONArray(); for(Voucher v : mDb.getVouchers(null,true, diffSince)) { JSONObject jc = new JSONObject(); jc.put("id", v.mId); jc.put("original_value", v.mOriginalValue); jc.put("current_value", v.mCurrentValue); jc.put("voucher_no", v.mVoucherNo); jc.put("from_customer", v.mFromCustomer); jc.put("from_customer_id", v.mFromCustomerId == null ? JSONObject.NULL : v.mFromCustomerId); jc.put("for_customer", v.mForCustomer); jc.put("for_customer_id", v.mForCustomerId == null ? JSONObject.NULL : v.mForCustomerId); jc.put("issued", CustomerDatabase.dateToString(v.mIssued)); jc.put("valid_until", v.mValidUntil == null ? JSONObject.NULL : CustomerDatabase.dateToString(v.mValidUntil)); jc.put("redeemed", v.mRedeemed == null ? JSONObject.NULL : CustomerDatabase.dateToString(v.mRedeemed)); jc.put("notes", v.mNotes); jc.put("last_modified", CustomerDatabase.dateToString(v.mLastModified)); jc.put("removed", v.mRemoved); jarrayVouchers.put(jc); } JSONObject jparams = new JSONObject(); jparams.put("playstore_token", mPurchaseToken); jparams.put("username", mUsername); jparams.put("password", mPassword); jparams.put("customers", jarrayCustomers); jparams.put("vouchers", jarrayVouchers); jparams.put("calendars", jarrayCalendars); jparams.put("appointments", jarrayAppointments); JSONObject jroot = new JSONObject(); jroot.put("jsonrpc", "2.0"); jroot.put("id", 1); jroot.put("method", "customerdb.put"); jroot.put("params", jparams); String result = openConnection(jroot.toString()); //Log.e("API", result); try { JSONObject jresult = new JSONObject(result); if(jresult.isNull("result") || !jresult.getBoolean("result")) { throw new Exception(jresult.getString("error")); } } catch(JSONException e) { throw new Exception(result); } } catch(JSONException ex) { throw new Exception(ex.getMessage()); } } private void readCustomers(Date diffSince) throws Exception { MainActivity activity = mMainActivityReference.get(); try { JSONObject jparams = new JSONObject(); jparams.put("diff_since", CustomerDatabase.dateToString(diffSince)); jparams.put("files", false); jparams.put("playstore_token", mPurchaseToken); jparams.put("username", mUsername); jparams.put("password", mPassword); JSONObject jroot = new JSONObject(); jroot.put("jsonrpc", "2.0"); jroot.put("id", 1); jroot.put("method", "customerdb.read"); jroot.put("params", jparams); String result = openConnection(jroot.toString()); //Log.e("API", jroot.toString()); //Log.e("API", result); try { JSONObject jresult = new JSONObject(result); if(jresult.isNull("result") || !jresult.isNull("error")) { throw new Exception(jresult.getString("error")); } } catch(JSONException e) { throw new Exception(result); } try { JSONObject jresult = new JSONObject(result); JSONObject jresults = jresult.getJSONObject("result"); JSONArray jcustomers = jresults.getJSONArray("customers"); JSONArray jvouchers = jresults.getJSONArray("vouchers"); JSONArray jcalendars = jresults.getJSONArray("calendars"); JSONArray jappointments = jresults.getJSONArray("appointments"); activity.mDb.beginTransaction(); for(int i = 0; i < jcustomers.length(); i++) { JSONObject jo = jcustomers.getJSONObject(i); Customer c = new Customer(); c.mFiles = new ArrayList<>(); Iterator<String> iter = jo.keys(); while(iter.hasNext()) { String key = iter.next(); if(jo.isNull(key)) continue; String value = jo.getString(key); c.putCustomerAttribute(key, value); } if(c.mId <= 0) continue; if(activity.mDb.getCustomerById(c.mId, true, false) == null) { activity.mDb.addCustomer(c); } else { activity.mDb.updateCustomer(c); } if(!jo.isNull("files")) { readCustomer(c.mId); } } for(int i = 0; i < jcalendars.length(); i++) { JSONObject jo = jcalendars.getJSONObject(i); CustomerCalendar c = new CustomerCalendar(); Iterator<String> iter = jo.keys(); while(iter.hasNext()) { String key = iter.next(); if(jo.isNull(key)) continue; String value = jo.getString(key); c.putAttribute(key, value); } if(c.mId <= 0) continue; if(activity.mDb.getCalendarById(c.mId, true) == null) { activity.mDb.addCalendar(c); } else { activity.mDb.updateCalendar(c); } } for(int i = 0; i < jappointments.length(); i++) { JSONObject jo = jappointments.getJSONObject(i); CustomerAppointment a = new CustomerAppointment(); Iterator<String> iter = jo.keys(); while(iter.hasNext()) { String key = iter.next(); if(jo.isNull(key)) continue; String value = jo.getString(key); a.putAttribute(key, value); } if(a.mId <= 0) continue; if(activity.mDb.getAppointmentById(a.mId, true) == null) { activity.mDb.addAppointment(a); } else { activity.mDb.updateAppointment(a); } } for(int i = 0; i < jvouchers.length(); i++) { JSONObject jo = jvouchers.getJSONObject(i); Voucher v = new Voucher(); Iterator<String> iter = jo.keys(); while(iter.hasNext()) { String key = iter.next(); if(jo.isNull(key)) continue; String value = jo.getString(key); v.putVoucherAttribute(key, value); } if(v.mId <= 0) continue; if(activity.mDb.getVoucherById(v.mId, true) == null) { activity.mDb.addVoucher(v); } else { activity.mDb.updateVoucher(v); } } activity.mDb.commitTransaction(); activity.mDb.endTransaction(); } catch(Exception e) { activity.mDb.endTransaction(); try { JSONObject jresult = new JSONObject(result); throw new Exception("Get Values Failed ("+e.getMessage()+") - "+jresult.getString("error")); } catch(JSONException e2) { throw new Exception("Get Values Failed ("+e.getMessage()+") - "+result); } } } catch(JSONException ex) { throw new Exception(ex.getMessage()); } } private void readCustomer(long customerId) throws Exception { MainActivity activity = mMainActivityReference.get(); JSONObject jparams = new JSONObject(); jparams.put("customer_id", customerId); jparams.put("playstore_token", mPurchaseToken); jparams.put("username", mUsername); jparams.put("password", mPassword); JSONObject jroot = new JSONObject(); jroot.put("jsonrpc", "2.0"); jroot.put("id", 1); jroot.put("method", "customerdb.read.customer"); jroot.put("params", jparams); String result = openConnection(jroot.toString()); //Log.e("API", jroot.toString()); //Log.e("API", result); try { JSONObject jresult = new JSONObject(result); if(jresult.isNull("result") || !jresult.isNull("error")) { throw new Exception(jresult.getString("error")); } } catch(JSONException e) { throw new Exception(result); } JSONObject jresult = new JSONObject(result); JSONObject jo = jresult.getJSONObject("result"); Customer c = new Customer(); Iterator<String> iter = jo.keys(); while(iter.hasNext()) { String key = iter.next(); if(jo.isNull(key)) continue; String value = jo.getString(key); c.putCustomerAttribute(key, value); } activity.mDb.updateCustomer(c); } private String openConnection(String send) throws Exception { String text = ""; BufferedReader reader = null; try { URL url = new URL(mApiUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept-Language", Locale.getDefault().getLanguage()); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(send); wr.flush(); int statusCode = conn.getResponseCode(); if(statusCode == 200) reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); else reader = new BufferedReader(new InputStreamReader((conn).getErrorStream())); StringBuilder sb2 = new StringBuilder(); String line; while((line = reader.readLine()) != null) { sb2.append(line).append("\n"); } text = sb2.toString(); if(text.equals("")) text = statusCode + " " + conn.getResponseMessage(); } catch(Exception ex) { throw new Exception(ex.getMessage()); } finally { if(reader != null) try { reader.close(); } catch(IOException e) { e.printStackTrace(); } } return text; } }
17,393
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
CustomerComparator.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/CustomerComparator.java
package de.georgsieber.customerdb; import java.util.Comparator; import java.util.List; import de.georgsieber.customerdb.model.CustomField; import de.georgsieber.customerdb.model.Customer; public class CustomerComparator implements Comparator<Customer> { private FIELD mSortField; private String mSortCustomField; private boolean mAscending; enum FIELD { TITLE, FIRST_NAME, LAST_NAME, LAST_MODIFIED } CustomerComparator(String customFieldTitleForSort, boolean ascending) { this.mSortCustomField = customFieldTitleForSort; this.mAscending = ascending; } CustomerComparator(FIELD field, boolean ascending) { this.mSortField = field; this.mAscending = ascending; } @Override public int compare(Customer c1, Customer c2) { String fieldValue_1 = ""; String fieldValue_2 = ""; if(mSortCustomField != null) { List<CustomField> cf_1 = c1.getCustomFields(); List<CustomField> cf_2 = c2.getCustomFields(); for(CustomField cf : cf_1) { if(cf.mTitle.equals(mSortCustomField)) fieldValue_1 = cf.mValue; } for(CustomField cf : cf_2) { if(cf.mTitle.equals(mSortCustomField)) fieldValue_2 = cf.mValue; } } else if(mSortField != null) { if(mSortField == FIELD.TITLE) { fieldValue_1 = c1.mTitle; fieldValue_2 = c2.mTitle; } else if(mSortField == FIELD.FIRST_NAME) { fieldValue_1 = c1.mFirstName; fieldValue_2 = c2.mFirstName; } else if(mSortField == FIELD.LAST_NAME) { fieldValue_1 = c1.mLastName; fieldValue_2 = c2.mLastName; } else if(mSortField == FIELD.LAST_MODIFIED) { fieldValue_1 = CustomerDatabase.dateToString(c1.mLastModified); fieldValue_2 = CustomerDatabase.dateToString(c2.mLastModified); } } if(mAscending) return fieldValue_1.compareTo(fieldValue_2); else return fieldValue_2.compareTo(fieldValue_1); } }
2,255
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
TextViewActivity.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/TextViewActivity.java
package de.georgsieber.customerdb; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import com.google.android.material.snackbar.Snackbar; import androidx.appcompat.widget.Toolbar; import androidx.core.content.FileProvider; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import de.georgsieber.customerdb.tools.ColorControl; public class TextViewActivity extends AppCompatActivity { String mTitle = ""; String mContent = ""; @Override protected void onCreate(Bundle savedInstanceState) { // init settings SharedPreferences settings = getSharedPreferences(MainActivity.PREFS_NAME, 0); // init activity view super.onCreate(savedInstanceState); setContentView(R.layout.activity_text_view); // init toolbar Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); if(getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); // init colors ColorControl.updateActionBarColor(this, settings); // load text mTitle = getIntent().getStringExtra("title"); if(mTitle != null) this.setTitle(mTitle); mContent = getIntent().getStringExtra("content"); if(mContent != null) ((TextView) findViewById(R.id.textViewScript)).setText(mContent); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_text_view, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case android.R.id.home: finish(); return true; case R.id.action_send_via_email: if(mContent == null) break; sendViaEmail(mContent); break; case R.id.action_copy_to_clipboard: if(mContent == null) break; toClipboard(mContent); break; } return super.onOptionsItemSelected(item); } private File getStorageScript() { File exportDir = new File(getExternalFilesDir(null), "tmp"); exportDir.mkdirs(); return new File(exportDir, "email.txt"); } private void scanFile(File f) { Uri uri = Uri.fromFile(f); Intent scanFileIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri); sendBroadcast(scanFileIntent); } public void sendViaEmail(String text) { File f = getStorageScript(); try { FileOutputStream stream = new FileOutputStream(f); stream.write(text.getBytes()); stream.close(); } catch(IOException e) { e.printStackTrace(); } scanFile(f); Uri attachmentUri = FileProvider.getUriForFile( this, "de.georgsieber.customerdb.provider", f ); // this opens app chooser instead of system email app Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("message/rfc822"); intent.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.app_name)); intent.putExtra(Intent.EXTRA_TEXT, ""); intent.putExtra(Intent.EXTRA_STREAM, attachmentUri); startActivity(Intent.createChooser(intent, getResources().getString(R.string.email))); } private void toClipboard(String text) { ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("phone", text); clipboard.setPrimaryClip(clip); Snackbar.make(findViewById(R.id.linearLayoutScriptActivityMainView), getResources().getString(R.string.copied_to_clipboard), Snackbar.LENGTH_LONG) .setAction("Action", null) .show(); } }
4,291
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
DateControl.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/tools/DateControl.java
package de.georgsieber.customerdb.tools; import java.text.DateFormat; import java.util.Date; import java.util.Locale; public class DateControl { public static DateFormat birthdayDateFormat = DateFormat.getDateInstance(DateFormat.LONG, Locale.getDefault()); public static DateFormat displayDateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault()); public static DateFormat displayTimeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault()); }
521
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
HttpRequest.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/tools/HttpRequest.java
package de.georgsieber.customerdb.tools; import android.os.AsyncTask; import android.util.Log; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.security.KeyStore; import java.security.SecureRandom; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.List; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManagerFactory; public class HttpRequest extends AsyncTask<Void, Void, String> { public static class KeyValueItem { private String key = ""; private String value = ""; private boolean useValueAsInteger = false; public KeyValueItem(String _key, String _value) { key = _key; value = _value; } public KeyValueItem(String _key, String _value, boolean _useValueAsInteger) { key = _key; value = _value; useValueAsInteger = _useValueAsInteger; } public String getKey() { return key; } public String getValue() { return value; } public boolean isInteger() { return useValueAsInteger; } } private File fileCert; private List<KeyValueItem> requestParameter; private List<KeyValueItem> requestHeader; private String requestBody = null; private String urlString; private int statusCode = 0; private static final String POST_PARAM_KEYVALUE_SEPARATOR = "="; private static final String POST_PARAM_SEPARATOR = "&"; private static final String POST_ENCODING = "UTF-8"; public HttpRequest(String url, File fileCert) { this.fileCert = fileCert; this.urlString = url; } public void setRequestParameter(List<KeyValueItem> parameter) { this.requestParameter = parameter; } public void setRequestBody(String body) { this.requestBody = body; } public void setRequestHeaders(List<KeyValueItem> headers) { this.requestHeader = headers; } private readyListener listener = null; public interface readyListener { void ready(int statusCode, String responseBody); } public void setReadyListener(readyListener listener) { this.listener = listener; } @Override protected String doInBackground(Void... params) { return openConnection(); } private String openConnection() { StringBuilder sb = new StringBuilder(); if(this.requestBody != null) { sb.append((this.requestBody)); } else if(this.requestParameter != null) { try { for(KeyValueItem kvi : this.requestParameter) { sb.append(URLEncoder.encode(kvi.getKey(), POST_ENCODING)); sb.append(POST_PARAM_KEYVALUE_SEPARATOR); sb.append(URLEncoder.encode(kvi.getValue(), POST_ENCODING)); sb.append(POST_PARAM_SEPARATOR); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } String responseText = ""; BufferedReader reader = null; try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); if(conn instanceof HttpsURLConnection) { SSLSocketFactory ssf = getCustomSSLSocketFactory(); if(ssf != null) { ((HttpsURLConnection)conn).setSSLSocketFactory(ssf); } } if(this.requestHeader != null) { for(KeyValueItem kv : this.requestHeader) { conn.setRequestProperty(kv.getKey(), kv.getValue()); } } conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(sb.toString()); wr.flush(); this.statusCode = ((HttpURLConnection)conn).getResponseCode(); if(this.statusCode == 200) reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); else reader = new BufferedReader(new InputStreamReader(((HttpURLConnection) conn).getErrorStream())); StringBuilder sb2 = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb2.append(line).append("\n"); } responseText = sb2.toString(); reader.close(); } catch (Exception ex) { //StringWriter sw = new StringWriter(); //PrintWriter pw = new PrintWriter(sw); //ex.printStackTrace(pw); //Log.e("HTTP", sw.toString()); responseText = ex.getLocalizedMessage(); } finally { if (reader != null) try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } return responseText; } @Override protected void onPostExecute(String result) { if(listener != null) listener.ready(this.statusCode, result); } private SSLSocketFactory getCustomSSLSocketFactory() { if(fileCert == null || !fileCert.exists() || fileCert.isDirectory()) { return null; } try { // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); CertificateFactory cf = CertificateFactory.getInstance("X509"); InputStream caInput = new FileInputStream(fileCert); Certificate ca; try { ca = cf.generateCertificate(caInput); Log.i("CERT", "CA certificate [" + ((X509Certificate) ca).getSubjectDN() + "] added to truststore."); } finally { caInput.close(); } keyStore.setCertificateEntry(fileCert.getName(), ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), new SecureRandom()); return sslContext.getSocketFactory(); } catch (Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); Log.e("CERT", sw.toString()); return null; } } }
7,329
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
CommonDialog.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/tools/CommonDialog.java
package de.georgsieber.customerdb.tools; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Build; import androidx.activity.result.ActivityResultLauncher; import androidx.appcompat.app.AppCompatActivity; import androidx.core.content.FileProvider; import java.io.File; import de.georgsieber.customerdb.R; public class CommonDialog { public enum TYPE { OK, WARN, FAIL, NONE } public static void show(final AppCompatActivity context, String title, String text, TYPE icon, final boolean finish) { if(context == null || context.isFinishing()) return; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { if(context.isDestroyed()) return; } AlertDialog ad = new AlertDialog.Builder(context).create(); ad.setCancelable(!finish); if(title != null && !title.equals("")) ad.setTitle(title); if(icon == TYPE.OK) { if(text != null && (!text.equals(""))) ad.setMessage(text); ad.setIcon(context.getResources().getDrawable(R.drawable.ic_tick_green_24dp)); } else if(icon == TYPE.WARN) { if(text != null && (!text.equals(""))) ad.setMessage(text); ad.setIcon(context.getResources().getDrawable(R.drawable.ic_warning_orange_24dp)); } else if(icon == TYPE.FAIL) { if(text != null && (!text.equals(""))) ad.setMessage(text); ad.setIcon(context.getResources().getDrawable(R.drawable.ic_fail_red_36dp)); } else { ad.setMessage(text); } ad.setButton(context.getResources().getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if(finish) context.finish(); } }); ad.show(); } public static void exportFinishedDialog(final AppCompatActivity context, File f, String mimeType, String[] emailRecipients, String emailSubject, String emailText, ActivityResultLauncher<Intent> resultHandlerExportMoveFile) { AlertDialog ad = new AlertDialog.Builder(context).create(); ad.setTitle(context.getResources().getString(R.string.export_ok)); ad.setMessage(f.getPath()); ad.setIcon(context.getResources().getDrawable(R.drawable.ic_tick_green_24dp)); ad.setButton(DialogInterface.BUTTON_POSITIVE, context.getResources().getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); ad.setButton(DialogInterface.BUTTON_NEUTRAL, context.getResources().getString(R.string.email), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); // this opens app chooser instead of system email app Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("message/rfc822"); intent.putExtra(Intent.EXTRA_EMAIL, emailRecipients); intent.putExtra(Intent.EXTRA_SUBJECT, emailSubject); intent.putExtra(Intent.EXTRA_TEXT, emailText); if(f != null) { intent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(context, "de.georgsieber.customerdb.provider", f)); } context.startActivity(Intent.createChooser(intent, context.getResources().getString(R.string.emailtocustomer))); } }); if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) { ad.setButton(DialogInterface.BUTTON_NEGATIVE, context.getResources().getString(R.string.move), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT); intent.setType(mimeType); intent.putExtra(Intent.EXTRA_TITLE, f.getName()); resultHandlerExportMoveFile.launch(intent); } }); } ad.show(); } }
4,426
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
BitmapCompressor.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/tools/BitmapCompressor.java
package de.georgsieber.customerdb.tools; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; import java.io.File; public class BitmapCompressor { private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of mImage int height = options.outHeight; int width = options.outWidth; int inSampleSize = 1; while ((width/inSampleSize) > reqWidth || (height/inSampleSize) > reqHeight) { inSampleSize += 1; } Log.i("BitmapCompressor", Integer.toString(inSampleSize)); return inSampleSize; } public static Bitmap getSmallBitmap(File file) { long originalSize = file.length(); Log.i("BitmapCompressor", "Original mImage size is: " + originalSize + " bytes."); final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(file.getAbsolutePath(), options); // Calculate inSampleSize based on a preset ratio options.inSampleSize = calculateInSampleSize(options, 850, 700); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; Bitmap compressedImage = BitmapFactory.decodeFile(file.getAbsolutePath(), options); Log.i("BitmapCompressor", "Compressed mImage size is " + compressedImage.getByteCount() + " bytes"); return compressedImage; } }
1,527
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
NumTools.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/tools/NumTools.java
package de.georgsieber.customerdb.tools; import android.content.Context; import java.text.NumberFormat; import java.util.Locale; public class NumTools { public static Long tryParseNullableLong(String value, Long defaultVal) { try { return Long.parseLong(value); } catch (NumberFormatException e) { return defaultVal; } } public static long tryParseLong(String value, long defaultVal) { try { return Long.parseLong(value); } catch (NumberFormatException e) { return defaultVal; } } public static Double tryParseDouble(String str) { try { NumberFormat format = NumberFormat.getInstance(Locale.getDefault()); Number number = format.parse(str); return number.doubleValue(); //return Double.parseDouble(str); } catch(Exception e) { return null; } } public static Integer tryParseInt(String str) { try { return Integer.parseInt(str); } catch(Exception e) { return null; } } @SuppressWarnings("SameParameterValue") public static int dpToPx(int dp, Context c) { return (int)(dp * c.getResources().getDisplayMetrics().density); } }
1,323
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
StorageControl.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/tools/StorageControl.java
package de.georgsieber.customerdb.tools; import android.content.Context; import android.content.Intent; import android.net.Uri; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.Date; import de.georgsieber.customerdb.R; public class StorageControl { private static String DIR_TEMP = "tmp"; private static String DIR_EXPORT = "export"; public static File getStorageLogo(Context c) { File exportDir = c.getExternalFilesDir(null); return new File(exportDir, "logo.png"); } public static File getStorageExportCsv(Context c) { return getFile(DIR_EXPORT, "export.csv", c); } public static File getStorageExportVcf(Context c) { return getFile(DIR_EXPORT, "export.vcf", c); } public static File getStorageExportIcs(Context c) { return getFile(DIR_EXPORT, "export.ics", c); } public static File getStorageImageTemp(Context c) { return getFile(DIR_TEMP, "image.tmp.jpg", c); } public static File getStorageFileTemp(Context c, String filename) { return getFile(DIR_TEMP, filename, c); } private static File getFile(String dir, String filename, Context c) { File exportDir = new File(c.getExternalFilesDir(null), dir); exportDir.mkdirs(); return new File(exportDir, filename); } public static void scanFile(File f, Context c) { Uri uri = Uri.fromFile(f); Intent scanFileIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri); c.sendBroadcast(scanFileIntent); } public static String getNewPictureFilename(Context c) { return (c.getString(R.string.picture) + " " + DateControl.displayDateFormat.format(new Date())).replaceAll("[^A-Za-z0-9 ]", "_") + ".jpg"; } public static String getNewDrawingFilename(Context c) { return (c.getString(R.string.drawing) + " " + DateControl.displayDateFormat.format(new Date())).replaceAll("[^A-Za-z0-9 ]", "_") + ".jpg"; } public static void deleteTempFiles(Context c) { try { deleteFilesInDirectory(new File(c.getExternalFilesDir(null), DIR_TEMP), c); } catch(Exception ignored) {} } public static boolean deleteFilesInDirectory(File fileOrDirectory, Context c) { if(!fileOrDirectory.isDirectory()) return false; for(File child : fileOrDirectory.listFiles()) { if(!child.isDirectory()) { if(!child.delete()) return false; scanFile(child, c); // otherwise file still appears via MTP... } } return true; } public static void moveFile(File sourceFile, Uri destinationUri, Context c) throws Exception { InputStream in = new FileInputStream(sourceFile); OutputStream out = c.getContentResolver().openOutputStream(destinationUri); byte[] buffer = new byte[1024]; int read; while((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); // write the output file out.flush(); out.close(); // delete the original file sourceFile.delete(); } }
3,233
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
CallerIdProvider.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/tools/CallerIdProvider.java
package de.georgsieber.customerdb.tools; import android.annotation.SuppressLint; import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.content.UriMatcher; import android.content.res.AssetFileDescriptor; import android.database.Cursor; import android.database.MatrixCursor; import android.net.Uri; import android.os.ParcelFileDescriptor; import android.provider.ContactsContract; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import de.georgsieber.customerdb.CustomerDatabase; import de.georgsieber.customerdb.MainActivity; import de.georgsieber.customerdb.R; import de.georgsieber.customerdb.model.Customer; public class CallerIdProvider extends ContentProvider { private final static int DIRECTORIES = 1; private final static int PHONE_LOOKUP = 2; private final static int PRIMARY_PHOTO = 3; private final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); private Uri authorityUri; private CustomerDatabase mDb; private SharedPreferences mSettings; @Override public boolean onCreate() { String authority = getContext().getString(R.string.callerid_authority); authorityUri = Uri.parse("content://"+authority); uriMatcher.addURI(authority, "directories", DIRECTORIES); uriMatcher.addURI(authority, "phone_lookup/*", PHONE_LOOKUP); uriMatcher.addURI(authority, "photo/primary_photo/*", PRIMARY_PHOTO); mSettings = getContext().getSharedPreferences(MainActivity.PREFS_NAME, 0); try { mDb = new CustomerDatabase(getContext()); } catch(Exception ex) { return false; } return true; } @Nullable @Override public Cursor query(@NonNull Uri uri, @Nullable String[] strings, @Nullable String s, @Nullable String[] strings1, @Nullable String s1) { MatrixCursor cursor = new MatrixCursor(strings); ArrayList<Object> values = new ArrayList<>(); switch(uriMatcher.match(uri)) { case(DIRECTORIES): for(String c : strings) { switch(c) { //case(ContactsContract.Directory.PHOTO_SUPPORT): // values.add(ContactsContract.Directory.PHOTO_SUPPORT_FULL); break; case(ContactsContract.Directory.ACCOUNT_NAME): case(ContactsContract.Directory.ACCOUNT_TYPE): case(ContactsContract.Directory.DISPLAY_NAME): values.add(getContext().getString(R.string.app_name)); break; case(ContactsContract.Directory.TYPE_RESOURCE_ID): values.add(R.string.app_name); break; case(ContactsContract.Directory.EXPORT_SUPPORT): values.add(ContactsContract.Directory.EXPORT_SUPPORT_SAME_ACCOUNT_ONLY); break; case(ContactsContract.Directory.SHORTCUT_SUPPORT): values.add(ContactsContract.Directory.SHORTCUT_SUPPORT_NONE); break; default: values.add(null); } } cursor.addRow(values.toArray()); return cursor; case(PHONE_LOOKUP): // check caller package - we only allow native android phone app String callerPackage = uri.getQueryParameter("callerPackage"); if(callerPackage == null) return cursor; // as of 2022, I only know the Google dialer app which supports this phone lookup feature // so, we deny requests from other apps - feel free to open a pull request to add another compatible dialer app if(!callerPackage.equals("com.android.dialer") && !callerPackage.equals("com.google.android.dialer")) return cursor; // prevent bulk queries // this seems not to work anymore with recent Google dialer versions // they now do multiple lookups for one call for whatever reason // since we restricted the packages which can query the information, I can switch this check off with a clear conscience int currentTime = (int)(System.currentTimeMillis() / 1000L); //int lastLookup = mSettings.getInt("last-caller-id-lookup", 0); //if(currentTime - lastLookup < 1) return cursor; mSettings.edit().putInt("last-caller-id-lookup", currentTime).apply(); // do the lookup if(mDb == null) return cursor; String incomingNumber = uri.getPathSegments().get(1); Customer customer = mDb.getCustomerByNumber(incomingNumber); if(customer != null) { saveLastCallInfo(getContext(), incomingNumber, customer.getFullName(false)); for(String c : strings) { switch(c) { case(ContactsContract.PhoneLookup._ID): values.add(customer.mId); break; case(ContactsContract.PhoneLookup.DISPLAY_NAME): values.add(customer.getFullName(false)); break; case(ContactsContract.PhoneLookup.LABEL): values.add(customer.mCustomerGroup); break; case(ContactsContract.PhoneLookup.PHOTO_THUMBNAIL_URI): case(ContactsContract.PhoneLookup.PHOTO_URI): values.add( Uri.withAppendedPath( Uri.withAppendedPath( Uri.withAppendedPath( authorityUri, "photo" ), "primary_photo" ), incomingNumber ) ); break; default: values.add(null); } } cursor.addRow(values.toArray()); } else { saveLastCallInfo(getContext(), incomingNumber, null); } return cursor; } return null; } @Override public AssetFileDescriptor openAssetFile(@NonNull Uri uri, @NonNull String mode) { if(uriMatcher.match(uri) == PRIMARY_PHOTO && mDb != null) { String incomingNumber = uri.getPathSegments().get(2); Customer customer = mDb.getCustomerByNumber(incomingNumber); if(customer != null && customer.getImage().length > 0) { // image from database return bytesToAssetFileDescriptor(customer.getImage()); } else { // fallback image from resources return getContext().getResources().openRawResourceFd(R.drawable.logo_customerdb_raw); } } return null; } private AssetFileDescriptor bytesToAssetFileDescriptor(byte[] data) { try { ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe(); InputStream inputStream = new ByteArrayInputStream(data); ParcelFileDescriptor.AutoCloseOutputStream outputStream = new ParcelFileDescriptor.AutoCloseOutputStream(pipe[1]); int len; while((len = inputStream.read()) >= 0) { outputStream.write(len); } inputStream.close(); outputStream.flush(); outputStream.close(); return new AssetFileDescriptor(pipe[0], 0, AssetFileDescriptor.UNKNOWN_LENGTH); } catch(IOException ignored) { return null; } } private void saveLastCallInfo(Context c, String number, String customer) { @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); String callInfo = sdf.format(new Date()) +" via ContentProvider: "+ number +" ("+ (customer == null ? c.getResources().getString(R.string.no_customer_found) : customer) +")"; SharedPreferences.Editor editor = mSettings.edit(); editor.putString("last-call-received", callInfo); editor.apply(); } @Nullable @Override public String getType(@NonNull Uri uri) { return null; } @Nullable @Override public Uri insert(@NonNull Uri uri, @Nullable ContentValues contentValues) { throw new UnsupportedOperationException(); } @Override public int delete(@NonNull Uri uri, @Nullable String s, @Nullable String[] strings) { throw new UnsupportedOperationException(); } @Override public int update(@NonNull Uri uri, @Nullable ContentValues contentValues, @Nullable String s, @Nullable String[] strings) { throw new UnsupportedOperationException(); } }
9,591
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
ColorControl.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/tools/ColorControl.java
package de.georgsieber.customerdb.tools; import android.content.SharedPreferences; import android.content.res.ColorStateList; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Build; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import android.view.View; public class ColorControl { public final static int DEFAULT_COLOR_R = 15; public final static int DEFAULT_COLOR_G = 124; public final static int DEFAULT_COLOR_B = 157; public static int getColorFromSettings(SharedPreferences settings) { int r = settings.getInt("design-red", DEFAULT_COLOR_R); int g = settings.getInt("design-green", DEFAULT_COLOR_G); int b = settings.getInt("design-blue", DEFAULT_COLOR_B); return Color.argb(0xff,r,g,b); } public static void updateActionBarColor(AppCompatActivity a, SharedPreferences settings) { int color = getColorFromSettings(settings); ActionBar ab = a.getSupportActionBar(); if(ab != null) ab.setBackgroundDrawable(new ColorDrawable(color)); if(Build.VERSION.SDK_INT >= 21) { a.getWindow().setStatusBarColor(color); } } public static void updateAccentColor(View v, SharedPreferences settings) { int color = getColorFromSettings(settings); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { v.setBackgroundTintList(ColorStateList.valueOf(color)); } else { v.setBackgroundDrawable(new ColorDrawable(color)); } } public static boolean isColorDark(int color) { double darkness = 1-(0.299*Color.red(color) + 0.587*Color.green(color) + 0.114*Color.blue(color))/255; return !(darkness < 0.5); } public static String getHexColor(int color) { return String.format("#%06X", (0xFFFFFF & color)); } }
1,908
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
VoucherPrintDocumentAdapter.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/print/VoucherPrintDocumentAdapter.java
package de.georgsieber.customerdb.print; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.pdf.PdfDocument; import android.os.Bundle; import android.os.CancellationSignal; import android.os.ParcelFileDescriptor; import android.print.PageRange; import android.print.PrintAttributes; import android.print.PrintDocumentAdapter; import android.print.PrintDocumentInfo; import android.print.pdf.PrintedPdfDocument; import java.io.FileOutputStream; import java.io.IOException; import de.georgsieber.customerdb.R; import de.georgsieber.customerdb.tools.DateControl; import de.georgsieber.customerdb.model.Voucher; public class VoucherPrintDocumentAdapter extends PrintDocumentAdapter { private Voucher mCurrentVoucher; private Context mCurrentContext; private PrintedPdfDocument mPdfDocument; private String mCurrency; public VoucherPrintDocumentAdapter(Context context, Voucher voucher, String currency) { mCurrentVoucher = voucher; mCurrentContext = context; mCurrency = currency; } @Override public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras) { if(cancellationSignal.isCanceled() ) { callback.onLayoutCancelled(); return; } mPdfDocument = new PrintedPdfDocument(mCurrentContext, newAttributes); if(cancellationSignal.isCanceled() ) { callback.onLayoutCancelled(); return; } PrintDocumentInfo info = new PrintDocumentInfo .Builder("printvoucher.tmp.pdf") .setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT) .setPageCount(1) .build(); callback.onLayoutFinished(info, true); } @Override public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback) { PdfDocument.Page page = mPdfDocument.startPage(1); // Draw page content for printing drawPage(page); // Rendering is complete, so page can be finalized. mPdfDocument.finishPage(page); // Write PDF document to file try { mPdfDocument.writeTo(new FileOutputStream( destination.getFileDescriptor())); } catch (IOException e) { callback.onWriteFailed(e.toString()); return; } finally { mPdfDocument.close(); mPdfDocument = null; } PageRange[] pr = new PageRange[1]; pr[0] = PageRange.ALL_PAGES; callback.onWriteFinished(pr); } private void drawPage(PdfDocument.Page page) { Canvas c = page.getCanvas(); int fontSize = page.getInfo().getPageWidth()/15; int lineHeight = Math.round(fontSize/1.55f); int x0 = 15; int x1 = Math.round(page.getInfo().getPageWidth()/2.8f); int y = lineHeight*2; int charsPerLine = Math.round((page.getInfo().getPageWidth() - 10) / (fontSize/4)); Paint p = new Paint(); Paint p_gray = new Paint(); p.setColor(Color.BLACK); p_gray.setColor(Color.GRAY); p.setTextSize(fontSize); c.drawText(mCurrentVoucher.getCurrentValueString()+mCurrency, x0, y, p); p.setTextSize(fontSize/2); p_gray.setTextSize(fontSize/2); y += lineHeight*2; if(!mCurrentVoucher.mVoucherNo.equals("")) { c.drawText(mCurrentContext.getResources().getString(R.string.voucher_number)+": "+mCurrentVoucher.mVoucherNo, x0, y, p_gray); y += lineHeight*1.25f; } c.drawText(mCurrentContext.getResources().getString(R.string.id)+": "+mCurrentVoucher.getIdString(), x0, y, p_gray); if(mCurrentVoucher.mCurrentValue != mCurrentVoucher.mOriginalValue) { y += lineHeight*1.25f; c.drawText(mCurrentContext.getResources().getString(R.string.original_value), x0, y, p_gray); y += lineHeight; c.drawText(mCurrentVoucher.getOriginalValueString()+mCurrency, x0, y, p); } if(mCurrentVoucher.mIssued != null) { y += lineHeight*1.25f; c.drawText(mCurrentContext.getResources().getString(R.string.issued), x0, y, p_gray); y += lineHeight; c.drawText(DateControl.displayDateFormat.format(mCurrentVoucher.mIssued), x0, y, p); } if(mCurrentVoucher.mValidUntil != null) { y += lineHeight*1.25f; c.drawText(mCurrentContext.getResources().getString(R.string.valid_until), x0, y, p_gray); y += lineHeight; c.drawText(DateControl.displayDateFormat.format(mCurrentVoucher.mValidUntil), x0, y, p); } if(mCurrentVoucher.mRedeemed != null) { y += lineHeight*1.25f; c.drawText(mCurrentContext.getResources().getString(R.string.redeemed), x0, y, p_gray); y += lineHeight; c.drawText(DateControl.displayDateFormat.format(mCurrentVoucher.mRedeemed), x0, y, p); } if(!mCurrentVoucher.mFromCustomer.equals("")) { y += lineHeight*1.25f; c.drawText(mCurrentContext.getResources().getString(R.string.from_customer), x0, y, p_gray); y += lineHeight; c.drawText(mCurrentVoucher.mFromCustomer, x0, y, p); } if(!mCurrentVoucher.mForCustomer.equals("")) { y += lineHeight*1.25f; c.drawText(mCurrentContext.getResources().getString(R.string.for_customer), x0, y, p_gray); y += lineHeight; c.drawText(mCurrentVoucher.mForCustomer, x0, y, p); } if(!mCurrentVoucher.mNotes.equals("")) { y += lineHeight*1.25f; c.drawText(mCurrentContext.getResources().getString(R.string.notes), x0, y, p_gray); for(String s : PrintTools.wordWrap(mCurrentVoucher.mNotes, charsPerLine).split("\n")) { y += lineHeight; c.drawText(s, x0, y, p); } } } }
6,229
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
PrintTools.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/print/PrintTools.java
package de.georgsieber.customerdb.print; public class PrintTools { static String wordWrap(final String input, final int length) { if(input == null || length < 1) { throw new IllegalArgumentException("Invalid input args"); } final String text = input.trim(); if(text.length() > length && text.contains(" ")) { final String line = text.substring(0, length); final int lineBreakIndex = line.indexOf("\n"); final int lineLastSpaceIndex = line.lastIndexOf(" "); final int inputFirstSpaceIndex = text.indexOf(" "); final int breakIndex = lineBreakIndex > -1 ? lineBreakIndex : (lineLastSpaceIndex > -1 ? lineLastSpaceIndex : inputFirstSpaceIndex); return text.substring(0, breakIndex) + "\n" + wordWrap(text.substring(breakIndex + 1), length); } else { return text; } } }
939
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
CustomerPrintDocumentAdapter.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/print/CustomerPrintDocumentAdapter.java
package de.georgsieber.customerdb.print; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.pdf.PdfDocument; import android.os.Bundle; import android.os.CancellationSignal; import android.os.ParcelFileDescriptor; import android.print.PageRange; import android.print.PrintAttributes; import android.print.PrintDocumentAdapter; import android.print.PrintDocumentInfo; import android.print.pdf.PrintedPdfDocument; import java.io.FileOutputStream; import java.io.IOException; import de.georgsieber.customerdb.R; import de.georgsieber.customerdb.model.CustomerFile; import de.georgsieber.customerdb.tools.DateControl; import de.georgsieber.customerdb.model.CustomField; import de.georgsieber.customerdb.model.Customer; public class CustomerPrintDocumentAdapter extends PrintDocumentAdapter { private Customer mCurrentCustomer; private Context mCurrentContext; private PrintedPdfDocument mPdfDocument; public CustomerPrintDocumentAdapter(Context context, Customer customer) { mCurrentCustomer = customer; mCurrentContext = context; } @Override public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras) { if(cancellationSignal.isCanceled() ) { callback.onLayoutCancelled(); return; } mPdfDocument = new PrintedPdfDocument(mCurrentContext, newAttributes); if(cancellationSignal.isCanceled() ) { callback.onLayoutCancelled(); return; } PrintDocumentInfo info = new PrintDocumentInfo .Builder("printcustomer.tmp.pdf") .setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT) .setPageCount(1) .build(); callback.onLayoutFinished(info, true); } @Override public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback) { PdfDocument.Page page = mPdfDocument.startPage(1); // Draw page content for printing drawPage(page); // Rendering is complete, so page can be finalized. mPdfDocument.finishPage(page); // Write PDF document to file try { mPdfDocument.writeTo(new FileOutputStream( destination.getFileDescriptor())); } catch (IOException e) { callback.onWriteFailed(e.toString()); return; } finally { mPdfDocument.close(); mPdfDocument = null; } PageRange[] pr = new PageRange[1]; pr[0] = PageRange.ALL_PAGES; callback.onWriteFinished(pr); } private void drawPage(PdfDocument.Page page) { Canvas c = page.getCanvas(); int fontSize = page.getInfo().getPageWidth()/14; int lineHeight = Math.round(fontSize/1.55f); int x0 = 15; int x1 = Math.round(page.getInfo().getPageWidth()/2.8f); int y = lineHeight*2; int charsPerLine = Math.round((page.getInfo().getPageWidth() - x1 - 10) / (fontSize/4)); if(mCurrentCustomer.getImage().length != 0) { Bitmap bitmap = BitmapFactory.decodeByteArray(mCurrentCustomer.getImage(), 0, mCurrentCustomer.getImage().length); int width = (int) (fontSize*1.5); Rect dstRect = new Rect(c.getWidth()-width-x0, x0, c.getWidth()-x0, x0+width); c.drawBitmap(bitmap, null, dstRect, null); } Paint p = new Paint(); Paint p_gray = new Paint(); p.setColor(Color.BLACK); p_gray.setColor(Color.GRAY); p.setTextSize(fontSize); c.drawText(mCurrentCustomer.getFullName(false), x0, y, p); p.setTextSize(fontSize/2); p_gray.setTextSize(fontSize/2); y += lineHeight*2; c.drawText(mCurrentContext.getResources().getString(R.string.phonehome), x0, y, p_gray); c.drawText(mCurrentCustomer.mPhoneHome, x1, y, p); y += lineHeight; c.drawText(mCurrentContext.getResources().getString(R.string.phonemobile), x0, y, p_gray); c.drawText(mCurrentCustomer.mPhoneMobile, x1, y, p); y += lineHeight; c.drawText(mCurrentContext.getResources().getString(R.string.phonework), x0, y, p_gray); c.drawText(mCurrentCustomer.mPhoneWork, x1, y, p); y += lineHeight; c.drawText(mCurrentContext.getResources().getString(R.string.email), x0, y, p_gray); c.drawText(mCurrentCustomer.mEmail, x1, y, p); y += lineHeight; c.drawText(mCurrentContext.getResources().getString(R.string.address), x0, y, p_gray); for(String s : mCurrentCustomer.getAddress().split("\n")) { c.drawText(s, x1, y, p); y += lineHeight; } y += lineHeight; c.drawText(mCurrentContext.getResources().getString(R.string.group), x0, y, p_gray); c.drawText(mCurrentCustomer.mCustomerGroup, x1, y, p); y += lineHeight; for(CustomField cf : mCurrentCustomer.getCustomFields()) { c.drawText(cf.mTitle, x0, y, p_gray); c.drawText(cf.mValue, x1, y, p); y += lineHeight; } y += lineHeight; c.drawText(mCurrentContext.getResources().getString(R.string.birthday), x0, y, p_gray); c.drawText(mCurrentCustomer.getBirthdayString(), x1, y, p); if(mCurrentCustomer.mBirthday != null) { y += lineHeight; c.drawText(mCurrentContext.getResources().getString(R.string.lastchanged), x0, y, p_gray); c.drawText(DateControl.birthdayDateFormat.format(mCurrentCustomer.mBirthday), x1, y, p); } y += lineHeight; y += lineHeight; c.drawText(mCurrentContext.getResources().getString(R.string.notes), x0, y, p_gray); for(String s : PrintTools.wordWrap(mCurrentCustomer.mNotes, charsPerLine).split("\n")) { c.drawText(s, x1, y, p); y += lineHeight; } y += lineHeight; y += lineHeight; c.drawText(mCurrentContext.getResources().getString(R.string.files), x0, y, p_gray); for(CustomerFile file : mCurrentCustomer.getFiles()) { c.drawText(file.mName, x1, y, p); y += lineHeight; } } @SuppressWarnings("SameParameterValue") private static Bitmap resize(Bitmap image, int maxWidth, int maxHeight) { if(maxHeight > 0 && maxWidth > 0) { int width = image.getWidth(); int height = image.getHeight(); float ratioBitmap = (float) width / (float) height; float ratioMax = (float) maxWidth / (float) maxHeight; int finalWidth = maxWidth; int finalHeight = maxHeight; if (ratioMax > ratioBitmap) { finalWidth = (int) ((float)maxHeight * ratioBitmap); } else { finalHeight = (int) ((float)maxWidth / ratioBitmap); } image = Bitmap.createScaledBitmap(image, finalWidth, finalHeight, true); return image; } else { return image; } } }
7,389
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
VoucherCsvBuilder.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/importexport/VoucherCsvBuilder.java
package de.georgsieber.customerdb.importexport; import android.util.Log; import com.opencsv.CSVReader; import com.opencsv.CSVWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import de.georgsieber.customerdb.CustomerDatabase; import de.georgsieber.customerdb.model.Customer; import de.georgsieber.customerdb.model.Voucher; public class VoucherCsvBuilder { private List<Voucher> mVouchers = new ArrayList<>(); public VoucherCsvBuilder(List<Voucher> _vouchers) { mVouchers = _vouchers; } public VoucherCsvBuilder(Voucher _voucher) { mVouchers.add(_voucher); } private String buildCsvContent(CustomerDatabase db) { StringWriter content = new StringWriter(); CSVWriter csvWriter = new CSVWriter(content); List<String> headers = new ArrayList<>(Arrays.asList( "id", "voucher_no", "original_value", "current_value", "from_customer", "from_customer_id", "for_customer", "for_customer_id", "issued", "valid_until", "redeemed", "last_modified", "notes" )); csvWriter.writeNext(headers.toArray(new String[0])); for(Voucher currentVoucher : mVouchers) { String fromCustomerText = ""; if(currentVoucher.mFromCustomerId != null) { Customer relatedCustomer = db.getCustomerById(currentVoucher.mFromCustomerId, false, false); if(relatedCustomer != null) { fromCustomerText = relatedCustomer.getFullName(false); } } else { fromCustomerText = currentVoucher.mFromCustomer; } String forCustomerText = ""; if(currentVoucher.mForCustomerId != null) { Customer relatedCustomer = db.getCustomerById(currentVoucher.mForCustomerId, false, false); if(relatedCustomer != null) { forCustomerText = relatedCustomer.getFullName(false); } } else { forCustomerText = currentVoucher.mForCustomer; } List<String> values = new ArrayList<>(Arrays.asList( Long.toString(currentVoucher.mId), currentVoucher.mVoucherNo, Double.toString(currentVoucher.mOriginalValue), Double.toString(currentVoucher.mCurrentValue), fromCustomerText, currentVoucher.mFromCustomerId==null ? "" : Long.toString(currentVoucher.mFromCustomerId), forCustomerText, currentVoucher.mForCustomerId==null ? "" : Long.toString(currentVoucher.mForCustomerId), currentVoucher.mIssued==null ? "" : CustomerDatabase.dateToString(currentVoucher.mIssued), currentVoucher.mValidUntil==null ? "" : CustomerDatabase.dateToString(currentVoucher.mValidUntil), currentVoucher.mRedeemed==null ? "" : CustomerDatabase.dateToString(currentVoucher.mRedeemed), currentVoucher.mLastModified==null ? "" : CustomerDatabase.dateToString(currentVoucher.mLastModified), currentVoucher.mNotes )); csvWriter.writeNext(values.toArray(new String[0])); } return content.toString(); } public boolean saveCsvFile(File f, CustomerDatabase db) { try { FileOutputStream stream = new FileOutputStream(f); stream.write(buildCsvContent(db).getBytes()); stream.close(); return true; } catch (IOException e) { Log.e("Exception", "File write failed: " + e.toString()); } return false; } public static List<Voucher> readCsvFile(InputStreamReader isr) throws Exception { List<Voucher> newVouchers = new ArrayList<>(); CSVReader reader = new CSVReader(isr); String[] headers = new String[]{}; String[] line; int counter = 0; while((line = reader.readNext()) != null) { try { if(counter == 0) { headers = line; } else { Voucher newVoucher = new Voucher(); int counter2 = 0; for(String field : line) { //Log.e("CSV", headers[counter2] + " -> "+ field); newVoucher.putVoucherAttribute(headers[counter2], field); counter2 ++; } newVouchers.add(newVoucher); } } catch(Exception ignored) {} counter ++; } return newVouchers; } }
4,889
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
CustomerVcfBuilder.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/importexport/CustomerVcfBuilder.java
package de.georgsieber.customerdb.importexport; import android.annotation.SuppressLint; import android.util.Base64; import android.util.Log; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import de.georgsieber.customerdb.model.Customer; public class CustomerVcfBuilder { static class VcfEntry { ArrayList<VcfField> mFields = new ArrayList<>(); VcfEntry() { super(); } } static class VcfField { String[] mOptions; String[] mValues; VcfField(String[] options, String[] values) { mOptions = options; mValues = values; } } private List<Customer> mCustomers = new ArrayList<>(); public CustomerVcfBuilder(List<Customer> _customers) { mCustomers = _customers; } public CustomerVcfBuilder(Customer _customer) { mCustomers.add(_customer); } @SuppressLint("SimpleDateFormat") final private static DateFormat formatWithoutDashes = new SimpleDateFormat("yyyyMMdd"); // vCard 4.0 @SuppressLint("SimpleDateFormat") final private static DateFormat formatWithDashes = new SimpleDateFormat("yyyy-MM-dd"); // vCard 2.1, 3.0, 4.0 private String buildVcfContent() { StringBuilder content = new StringBuilder(); for(Customer currentCustomer : mCustomers) { content.append("BEGIN:VCARD\n"); content.append("VERSION:2.1\n"); content.append("FN;ENCODING=QUOTED-PRINTABLE:").append(QuotedPrintable.encode(currentCustomer.mTitle)).append(" ").append(QuotedPrintable.encode(currentCustomer.mFirstName)).append(" ").append(QuotedPrintable.encode(currentCustomer.mLastName)).append("\n"); content.append("N;ENCODING=QUOTED-PRINTABLE:").append(QuotedPrintable.encode(currentCustomer.mLastName)).append(";").append(QuotedPrintable.encode(currentCustomer.mFirstName)).append(";;").append(QuotedPrintable.encode(currentCustomer.mTitle)).append(";\n"); if(!currentCustomer.mPhoneHome.equals("")) content.append("TEL;HOME:").append(escapeVcfValue(currentCustomer.mPhoneHome)).append("\n"); if(!currentCustomer.mPhoneMobile.equals("")) content.append("TEL;CELL:").append(escapeVcfValue(currentCustomer.mPhoneMobile)).append("\n"); if(!currentCustomer.mPhoneWork.equals("")) content.append("TEL;WORK:").append(escapeVcfValue(currentCustomer.mPhoneWork)).append("\n"); if(!currentCustomer.mEmail.equals("")) content.append("EMAIL;INTERNET:").append(currentCustomer.mEmail).append("\n"); if(!currentCustomer.getAddress().equals("")) content.append("ADR;TYPE=HOME:" + ";;").append(escapeVcfValue(currentCustomer.mStreet)).append(";").append(escapeVcfValue(currentCustomer.mCity)).append(";;").append(escapeVcfValue(currentCustomer.mZipcode)).append(";").append(escapeVcfValue(currentCustomer.mCountry)).append("\n"); if(!currentCustomer.mCustomerGroup.equals("")) content.append("ORG:").append(escapeVcfValue(currentCustomer.mCustomerGroup)).append("\n"); if(currentCustomer.mBirthday != null) content.append("BDAY:").append(formatWithoutDashes.format(currentCustomer.mBirthday)).append("\n"); if(!currentCustomer.mNotes.equals("")) content.append("NOTE;ENCODING=QUOTED-PRINTABLE:").append(QuotedPrintable.encode(currentCustomer.mNotes)).append("\n"); if(!currentCustomer.mCustomFields.equals("")) content.append("X-CUSTOM-FIELDS:").append(escapeVcfValue(currentCustomer.mCustomFields)).append("\n"); if(currentCustomer.mImage != null && currentCustomer.mImage.length > 0) { String base64String = Base64.encodeToString(currentCustomer.mImage, Base64.DEFAULT); base64String = base64String.replace("\n", "\n ").trim(); content.append("PHOTO;ENCODING=BASE64;JPEG:").append(base64String).append("\n"); } content.append("END:VCARD\n\n"); } return content.toString(); } private String escapeVcfValue(String value) { return value.replace("\n", "\\n"); } public boolean saveVcfFile(File f) { try { FileOutputStream stream = new FileOutputStream(f); stream.write(buildVcfContent().getBytes()); stream.close(); return true; } catch(IOException e) { Log.e("Exception", "File write failed: " + e.toString()); } return false; } private static String[] VCF_FIELDS = { // thanks, Wikipedia "ADR", "AGENT", "ANNIVERSARY", "BDAY", "BEGIN", "BIRTHPLACE", "CALADRURI", "CALURI", "CATEGORIES", "CLASS", "CLIENTPIDMAP", "DEATHDATE", "DEATHPLACE", "EMAIL", "END", "EXPERTISE", "FBURL", "FN", "GENDER", "GEO", "HOBBY", "IMPP", "INTEREST", "KEY", "KIND", "LABEL", "LANG", "LOGO", "MAILER", "MEMBER", "N", "NAME", "NICKNAME", "NOTE", "ORG", "ORG-DIRECTORY", "PHOTO", "PROID", "PROFILE", "RELATED", "REV", "ROLE", "SORT-STRING", "SOUND", "SOURCE", "TEL", "TITLE", "TZ", "UID", "URL", "VERSION", "XML" }; private static boolean isVcfField(String text) { String upperText = text.toUpperCase(); String[] keyValue = upperText.split(":"); if(keyValue.length >= 1) { String[] subKeys = keyValue[0].split(";"); if(subKeys[0].startsWith("X-")) { return true; } for(String field : VCF_FIELDS) { if(subKeys[0].startsWith(field)) { return true; } } } return false; } @SuppressWarnings("StringConcatenationInLoop") public static List<Customer> readVcfFile(InputStreamReader isr) throws IOException { // STEP 0 : a vcf field can be broken up into multiple lines // we concatenate them here into a single line again BufferedReader br = new BufferedReader(isr); ArrayList<String> vcfFields = new ArrayList<>(); String currFieldValue = ""; String line0; while((line0 = br.readLine()) != null) { if(isVcfField(line0)) { if(!currFieldValue.trim().equals("")) { vcfFields.add(currFieldValue); //Log.e("VCF FIELD", currFieldValue); } currFieldValue = line0.trim(); } else { String append = line0.trim(); // avoid the double equal sign hell if(append.startsWith("=") && currFieldValue.endsWith("=")) { append = append.substring(1); } currFieldValue += append; } } if(!currFieldValue.trim().equals("")) { vcfFields.add(currFieldValue); //Log.e("VCF FIELD", currFieldValue); } // STEP 1 : parse VCF string into structured data VcfEntry tempVcfEntry = null; ArrayList<VcfEntry> tempVcfEntries = new ArrayList<>(); for(String line : vcfFields) { String upperLine = line.toUpperCase(); if(upperLine.startsWith("BEGIN:VCARD")) { tempVcfEntry = new VcfEntry(); } if(upperLine.startsWith("END:VCARD")) { if(tempVcfEntry != null) { tempVcfEntries.add(tempVcfEntry); } tempVcfEntry = null; } if(tempVcfEntry != null) { String[] keyValue = line.split(":", 2); if(keyValue.length != 2) continue; String[] options = keyValue[0].split(";"); String[] values = keyValue[1].split(";"); if(QuotedPrintable.isVcfFieldQuotedPrintableEncoded(options)) { // decode quoted printable encoded fields ArrayList<String> decodedValuesList = new ArrayList<>(); for(String v : values) { decodedValuesList.add(QuotedPrintable.decode(v)); } tempVcfEntry.mFields.add(new VcfField(options, decodedValuesList.toArray(new String[0]))); } else { tempVcfEntry.mFields.add(new VcfField(options, values)); } } } // STEP 2 : create customers from VCF data List<Customer> newCustomers = new ArrayList<>(); for(VcfEntry e : tempVcfEntries) { String fullNameTemp = ""; Customer newCustomer = new Customer(); // apply all VCF fields for(VcfField f : e.mFields) { switch(f.mOptions[0].toUpperCase()) { case "FN": if(f.mValues.length >= 1) fullNameTemp = f.mValues[0]; break; case "N": if(f.mValues.length >= 1) newCustomer.mLastName = f.mValues[0]; if(f.mValues.length >= 2) newCustomer.mFirstName = f.mValues[1]; if(f.mValues.length >= 4) newCustomer.mTitle = f.mValues[3]; break; case "EMAIL": if(f.mValues.length >= 1) newCustomer.mEmail = f.mValues[0]; break; case "ADR": String street = ""; String zipcode = ""; String city = ""; String country = ""; if(f.mValues.length > 2) street = f.mValues[2]; if(f.mValues.length > 3) city = f.mValues[3]; if(f.mValues.length > 5) zipcode = f.mValues[5]; if(f.mValues.length > 6) country = f.mValues[6]; if(newCustomer.mStreet.trim().equals("") && newCustomer.mZipcode.trim().equals("") && newCustomer.mCity.trim().equals("") && newCustomer.mCountry.trim().equals("")) { newCustomer.mStreet = street; newCustomer.mZipcode = zipcode; newCustomer.mCity = city; newCustomer.mCountry = country; } else { addAdditionalInfoToDescription(newCustomer, street + "\n" + zipcode + " " + city + "\n" + country); } break; case "TITLE": case "URL": case "NOTE": addAdditionalInfoToDescription(newCustomer, f.mValues[0]); break; case "X-CUSTOM-FIELDS": newCustomer.mCustomFields = f.mValues[0]; break; case "TEL": String telParam = ""; if(f.mOptions.length > 1) telParam = f.mOptions[1].trim(); addTelephoneNumber(newCustomer, telParam, f.mValues[0]); break; case "ORG": newCustomer.mCustomerGroup = f.mValues[0]; break; case "BDAY": if(f.mValues[0].trim().length() == 10) { try { newCustomer.mBirthday = formatWithDashes.parse(f.mValues[0]); } catch(Exception ignored) { } } else { try { newCustomer.mBirthday = formatWithoutDashes.parse(f.mValues[0]); } catch(Exception ignored) { } } break; case "PHOTO": newCustomer.putCustomerAttribute("image", f.mValues[0]); break; } } // apply name fallback if name is empty if(newCustomer.mFirstName.equals("") && newCustomer.mLastName.equals("")) { newCustomer.mLastName = fullNameTemp; } // only add if name is not empty if(!(newCustomer.mFirstName.equals("") && newCustomer.mLastName.equals("") && newCustomer.mTitle.equals(""))) { newCustomers.add(newCustomer); } } return newCustomers; } private static void addTelephoneNumber(Customer currentCustomer, String telParam, String telValue) { String telParamUpper = telParam.toUpperCase(); if(telParamUpper.startsWith("HOME")) { if(currentCustomer.mPhoneHome.trim().equals("")) currentCustomer.mPhoneHome = telValue; else addTelephoneNumberAlternative(currentCustomer, telParam, telValue); } else if(telParamUpper.startsWith("CELL")) { if(currentCustomer.mPhoneMobile.trim().equals("")) currentCustomer.mPhoneMobile = telValue; else addTelephoneNumberAlternative(currentCustomer, telParam, telValue); } else if(telParamUpper.startsWith("WORK")) { if(currentCustomer.mPhoneWork.trim().equals("")) currentCustomer.mPhoneWork = telValue; else addTelephoneNumberAlternative(currentCustomer, telParam, telValue); } else { if(currentCustomer.mPhoneHome.equals("")) { currentCustomer.mPhoneHome = telValue; } else if(currentCustomer.mPhoneMobile.equals("")) { currentCustomer.mPhoneMobile = telValue; } else if(currentCustomer.mPhoneWork.equals("")) { currentCustomer.mPhoneWork = telValue; } else { addTelephoneNumberAlternative(currentCustomer, telParam, telValue); } } } private static void addTelephoneNumberAlternative(Customer currentCustomer, String telParam, String telValue) { addAdditionalInfoToDescription(currentCustomer, telParam + ": " + telValue); } private static void addAdditionalInfoToDescription(Customer currentCustomer, String info) { currentCustomer.mNotes = (currentCustomer.mNotes + "\n\n" + info).trim(); } }
15,023
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
QuotedPrintable.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/importexport/QuotedPrintable.java
package de.georgsieber.customerdb.importexport; import java.io.UnsupportedEncodingException; import java.util.ArrayList; class QuotedPrintable { static String ASCII_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 "; @SuppressWarnings("CharsetObjectCanBeUsed") static String decode(String str) { ArrayList<Byte> bytes = new ArrayList<>(); for(int i = 0; i < str.length(); i++) { char currentChar = str.charAt(i); try { if(currentChar == '=' && i+2 <= str.length()-1) { char nextChar1 = str.charAt(i+1); char nextChar2 = str.charAt(i+2); int val = Integer.parseInt(String.valueOf(nextChar1)+String.valueOf(nextChar2), 16); bytes.add((byte) val); i += 2; continue; } } catch(Exception ignored) {} bytes.add((byte) currentChar); } try { return new String(toByteArray(bytes), "UTF-8"); } catch(UnsupportedEncodingException ignored) { return str; } } @SuppressWarnings("CharsetObjectCanBeUsed") static String encode(String str) { StringBuilder encoded = new StringBuilder(); try { for(String s : splitToCodePoints(str)) { if(ASCII_CHARS.contains(s)) { // append standard ASCII chars directly (should be human readable) encoded.append(s); } else { // append all bytes of char quoted-printable encoded for(byte b : s.getBytes("UTF-8")) { encoded.append("=").append(String.format("%02X", b)); } } } } catch(UnsupportedEncodingException ignored) {} return encoded.toString(); } private static ArrayList<String> splitToCodePoints(String str) { ArrayList<String> list = new ArrayList<>(); int count = 0; while(count < str.length()) { int cp = str.codePointAt(count); list.add(new String(Character.toChars(cp))); count += Character.charCount(cp); } return list; } private static byte[] toByteArray(ArrayList<Byte> in) { final int n = in.size(); byte[] ret = new byte[n]; for (int i = 0; i < n; i++) { ret[i] = in.get(i); } return ret; } static boolean isVcfFieldQuotedPrintableEncoded(String[] fieldOptions) { for(String option : fieldOptions) { if(option.toUpperCase().equals("ENCODING=QUOTED-PRINTABLE")) { return true; } } return false; } }
2,808
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
CalendarCsvBuilder.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/importexport/CalendarCsvBuilder.java
package de.georgsieber.customerdb.importexport; import android.util.Log; import com.opencsv.CSVReader; import com.opencsv.CSVWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import de.georgsieber.customerdb.CustomerDatabase; import de.georgsieber.customerdb.model.Customer; import de.georgsieber.customerdb.model.CustomerAppointment; public class CalendarCsvBuilder { private List<CustomerAppointment> mAppointments = new ArrayList<>(); public CalendarCsvBuilder(List<CustomerAppointment> _appointments) { mAppointments = _appointments; } public CalendarCsvBuilder(CustomerAppointment _appointment) { mAppointments.add(_appointment); } private String buildCsvContent(CustomerDatabase db) { StringWriter content = new StringWriter(); CSVWriter csvWriter = new CSVWriter(content); List<String> headers = new ArrayList<>(Arrays.asList( "id", "title", "notes", "time_start", "time_end", "fullday", "customer", "customer_id", "location", "last_modified" )); csvWriter.writeNext(headers.toArray(new String[0])); for(CustomerAppointment ca : mAppointments) { String customerText = ""; if(ca.mCustomerId != null) { Customer relatedCustomer = db.getCustomerById(ca.mCustomerId, false, false); if(relatedCustomer != null) { customerText = relatedCustomer.getFullName(false); } } else { customerText = ca.mCustomer; } List<String> values = new ArrayList<>(Arrays.asList( Long.toString(ca.mId), ca.mTitle, ca.mNotes, ca.mTimeStart==null ? "" : CustomerDatabase.dateToStringRaw(ca.mTimeStart), ca.mTimeEnd==null ? "" : CustomerDatabase.dateToStringRaw(ca.mTimeEnd), ca.mFullday ? "1" : "0", customerText, ca.mCustomerId==null ? "" : Long.toString(ca.mCustomerId), ca.mLocation, ca.mLastModified==null ? "" : CustomerDatabase.dateToString(ca.mLastModified) )); csvWriter.writeNext(values.toArray(new String[0])); } return content.toString(); } public boolean saveCsvFile(File f, CustomerDatabase db) { try { FileOutputStream stream = new FileOutputStream(f); stream.write(buildCsvContent(db).getBytes()); stream.close(); return true; } catch (IOException e) { Log.e("Exception", "File write failed: " + e.toString()); } return false; } public static List<CustomerAppointment> readCsvFile(InputStreamReader isr) throws Exception { List<CustomerAppointment> newAppointments = new ArrayList<>(); CSVReader reader = new CSVReader(isr); String[] headers = new String[]{}; String[] line; int counter = 0; while((line = reader.readNext()) != null) { try { if(counter == 0) { headers = line; } else { CustomerAppointment newAppointment = new CustomerAppointment(); int counter2 = 0; for(String field : line) { //Log.e("CSV", headers[counter2] + " -> "+ field); newAppointment.putAttribute(headers[counter2], field); counter2 ++; } newAppointments.add(newAppointment); } } catch(Exception ignored) {} counter ++; } return newAppointments; } }
3,955
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
CustomerCsvBuilder.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/importexport/CustomerCsvBuilder.java
package de.georgsieber.customerdb.importexport; import android.util.Log; import com.opencsv.CSVReader; import com.opencsv.CSVWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import de.georgsieber.customerdb.CustomerDatabase; import de.georgsieber.customerdb.model.CustomField; import de.georgsieber.customerdb.model.Customer; public class CustomerCsvBuilder { private List<Customer> mCustomers = new ArrayList<>(); private List<CustomField> mAllCustomFields; public CustomerCsvBuilder(List<Customer> _customers, List<CustomField> _allCustomFields) { mCustomers = _customers; mAllCustomFields = _allCustomFields; } public CustomerCsvBuilder(Customer _customer, List<CustomField> _allCustomFields) { mCustomers.add(_customer); mAllCustomFields = _allCustomFields; } private String buildCsvContent() { StringWriter content = new StringWriter(); CSVWriter csvWriter = new CSVWriter(content); List<String> headers = new ArrayList<>(Arrays.asList( "id", "title", "first_name", "last_name", "phone_home", "phone_mobile", "phone_work", "email", "street", "zipcode", "city", "country", "customer_group", "newsletter", "birthday", "last_modified", "notes" )); for(CustomField cf : mAllCustomFields) { //Log.e("CSV", "add cf: "+cf.mTitle); headers.add(cf.mTitle); } csvWriter.writeNext(headers.toArray(new String[0])); for(Customer currentCustomer : mCustomers) { List<String> values = new ArrayList<>(Arrays.asList( Long.toString(currentCustomer.mId), currentCustomer.mTitle, currentCustomer.mFirstName, currentCustomer.mLastName, currentCustomer.mPhoneHome, currentCustomer.mPhoneMobile, currentCustomer.mPhoneWork, currentCustomer.mEmail, currentCustomer.mStreet, currentCustomer.mZipcode, currentCustomer.mCity, currentCustomer.mCountry, currentCustomer.mCustomerGroup, currentCustomer.mNewsletter ? "1" : "0", currentCustomer.mBirthday==null ? "" : CustomerDatabase.dateToStringRaw(currentCustomer.mBirthday), currentCustomer.mLastModified==null ? "" : CustomerDatabase.dateToString(currentCustomer.mLastModified), currentCustomer.mNotes )); for(CustomField cf : mAllCustomFields) { values.add(currentCustomer.getCustomField(cf.mTitle)); } csvWriter.writeNext(values.toArray(new String[0])); } return content.toString(); } public boolean saveCsvFile(File f) { try { FileOutputStream stream = new FileOutputStream(f); stream.write(buildCsvContent().getBytes()); stream.close(); return true; } catch (IOException e) { Log.e("Exception", "File write failed: " + e.toString()); } return false; } public static List<Customer> readCsvFile(InputStreamReader isr) throws Exception { List<Customer> newCustomers = new ArrayList<>(); CSVReader reader = new CSVReader(isr); String[] headers = new String[]{}; String[] line; int counter = 0; while((line = reader.readNext()) != null) { try { if(counter == 0) { headers = line; } else { Customer newCustomer = new Customer(); int counter2 = 0; for(String field : line) { //Log.e("CSV", headers[counter2] + " -> "+ field); newCustomer.putCustomerAttribute(headers[counter2], field); counter2 ++; } newCustomers.add(newCustomer); } } catch(Exception ignored) {} counter ++; } return newCustomers; } }
4,421
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
CalendarIcsBuilder.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/importexport/CalendarIcsBuilder.java
package de.georgsieber.customerdb.importexport; import android.annotation.SuppressLint; import android.util.Log; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import de.georgsieber.customerdb.model.Customer; import de.georgsieber.customerdb.model.CustomerAppointment; public class CalendarIcsBuilder { static class IcsEntry { ArrayList<IcsField> mFields = new ArrayList<>(); IcsEntry() { super(); } } static class IcsField { String[] mOptions; String[] mValues; IcsField(String[] options, String[] values) { mOptions = options; mValues = values; } } private List<CustomerAppointment> mAppointments = new ArrayList<>(); public CalendarIcsBuilder(List<CustomerAppointment> _appointments) { mAppointments = _appointments; } public CalendarIcsBuilder(CustomerAppointment _appointment) { mAppointments.add(_appointment); } @SuppressLint("SimpleDateFormat") public static DateFormat dateFormatIcs = new SimpleDateFormat("yyyyMMdd'T'HHmmss"); private String buildIcsContent() { StringBuilder content = new StringBuilder(); content.append("BEGIN:VCALENDAR\n"); content.append("VERSION:2.0\n"); for(CustomerAppointment ca : mAppointments) { content.append("BEGIN:VEVENT\n"); content.append("SUMMARY:").append(ca.mTitle).append("\n"); content.append("DESCRIPTION:").append(escapeIcsValue(ca.mNotes)).append("\n"); content.append("LOCATION:").append(ca.mLocation).append("\n"); content.append("DTSTART:").append(dateFormatIcs.format(ca.mTimeStart)).append("\n"); content.append("DTEND:").append(dateFormatIcs.format(ca.mTimeEnd)).append("\n"); content.append("END:VEVENT\n\n"); } content.append("END:VCALENDAR\n"); return content.toString(); } private String escapeIcsValue(String value) { return value.replace("\n", "\\n"); } public boolean saveIcsFile(File f) { try { FileOutputStream stream = new FileOutputStream(f); stream.write(buildIcsContent().getBytes()); stream.close(); return true; } catch (IOException e) { Log.e("Exception", "File write failed: " + e.toString()); } return false; } private static String[] ICS_FIELDS = { "PRODID", "METHOD", "BEGIN", "TZID", "DTSTART", "DTEND", "DTSTAMP", "RRULE", "TZOFFSETFROM", "TZOFFSETTO", "END", "UID", "ORGANIZER", "LOCATION", "GEO", "SUMMARY", "DESCRIPTION", "CLASS", "VERSION", }; private static boolean isIcsField(String text) { String upperText = text.toUpperCase(); String[] keyValue = upperText.split(":"); if(keyValue.length >= 1) { String[] subKeys = keyValue[0].split(";"); if(subKeys[0].startsWith("X-")) { return true; } for(String field : ICS_FIELDS) { if(subKeys[0].startsWith(field)) { return true; } } } return false; } @SuppressWarnings("StringConcatenationInLoop") public static List<CustomerAppointment> readIcsFile(InputStreamReader isr) throws IOException { // STEP 0 : a ics field can be broken up into multiple lines // we concatenate them here into a single line again BufferedReader br = new BufferedReader(isr); ArrayList<String> icsFields = new ArrayList<>(); String currFieldValue = ""; String line0; while((line0 = br.readLine()) != null) { if(isIcsField(line0)) { if(!currFieldValue.trim().equals("")) { icsFields.add(currFieldValue); } currFieldValue = line0.trim(); } else { String append = line0.trim(); // avoid the double equal sign hell if(append.startsWith("=") && currFieldValue.endsWith("=")) { append = append.substring(1); } currFieldValue += append; } } if(!currFieldValue.trim().equals("")) { icsFields.add(currFieldValue); } // STEP 1 : parse ICS string into structured data IcsEntry tempIcsEntry = null; ArrayList<IcsEntry> tempIcsEntries = new ArrayList<>(); for(String line : icsFields) { String upperLine = line.toUpperCase(); if(upperLine.startsWith("BEGIN:VEVENT")) { tempIcsEntry = new IcsEntry(); } if(upperLine.startsWith("END:VEVENT")) { if(tempIcsEntry != null) { tempIcsEntries.add(tempIcsEntry); } tempIcsEntry = null; } if(tempIcsEntry != null) { String[] keyValue = line.split(":", 2); if(keyValue.length != 2) continue; String[] options = keyValue[0].split(";"); String[] values = keyValue[1].split(";"); if(QuotedPrintable.isVcfFieldQuotedPrintableEncoded(options)) { // decode quoted printable encoded fields ArrayList<String> decodedValuesList = new ArrayList<>(); for(String v : values) { decodedValuesList.add(QuotedPrintable.decode(v)); } tempIcsEntry.mFields.add(new IcsField(options, decodedValuesList.toArray(new String[0]))); } else { tempIcsEntry.mFields.add(new IcsField(options, values)); } } } // STEP 2 : create customers from ICS data List<CustomerAppointment> newAppointments = new ArrayList<>(); for(IcsEntry e : tempIcsEntries) { CustomerAppointment newAppointment = new CustomerAppointment(); // apply all ICS fields for(IcsField f : e.mFields) { switch(f.mOptions[0].toUpperCase()) { case "SUMMARY": if(f.mValues.length >= 1) newAppointment.mTitle = f.mValues[0]; break; case "DESCRIPTION": if(f.mValues.length >= 1) newAppointment.mNotes = f.mValues[0]; break; case "LOCATION": newAppointment.mLocation = f.mValues[0]; break; case "DTSTART": try { newAppointment.mTimeStart = dateFormatIcs.parse(f.mValues[0]); } catch (Exception ignored) {} break; case "DTEND": try { newAppointment.mTimeEnd = dateFormatIcs.parse(f.mValues[0]); } catch (Exception ignored) {} break; } } // only add if name is not empty if(!newAppointment.mTitle.equals("")) { newAppointments.add(newAppointment); } } return newAppointments; } }
7,600
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
CustomerAppointment.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/model/CustomerAppointment.java
package de.georgsieber.customerdb.model; import android.annotation.SuppressLint; import androidx.annotation.NonNull; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.concurrent.ThreadLocalRandom; import de.georgsieber.customerdb.CustomerDatabase; import de.georgsieber.customerdb.tools.NumTools; public class CustomerAppointment { public long mId = -1; public long mCalendarId = -1; public String mTitle = ""; public String mNotes = ""; public Date mTimeStart = null; public Date mTimeEnd = null; public boolean mFullday = false; public String mCustomer = ""; public Long mCustomerId = null; public String mLocation = ""; public Date mLastModified = new Date(); public int mRemoved = 0; public String mColor = ""; public CustomerAppointment() { super(); } public CustomerAppointment(long _id, long _calendarId, String _title, String _notes, Date _timeStart, Date _timeEnd, boolean _fullday, String _customer, Long _customerId, String _location, Date _lastModified, int _removed) { mId = _id; mCalendarId = _calendarId; mTitle = _title; mNotes = _notes; mTimeStart = _timeStart; mTimeEnd = _timeEnd; mFullday = _fullday; mCustomer = _customer; mCustomerId = _customerId; mLocation = _location; mLastModified = _lastModified; mRemoved = _removed; } @NonNull @Override public String toString() { return mTitle; } @Override public boolean equals(Object o) { if(this == o) return true; if(o == null || getClass() != o.getClass()) return false; CustomerAppointment event = (CustomerAppointment) o; return mId == event.mId; } public static long generateID() { /* This function generates an unique mId for a new record. * Required in order to get unique ids over multiple devices, * which are not in sync with the central mysql server */ @SuppressLint("SimpleDateFormat") DateFormat idFormat = new SimpleDateFormat("yyyyMMddkkmmss"); String random; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { random = String.valueOf(ThreadLocalRandom.current().nextInt(1, 100)); } else { random = "10"; } return Long.parseLong(idFormat.format(new Date())+random); } public static long generateID(int suffix) { /* specific suffix for bulk import */ @SuppressLint("SimpleDateFormat") DateFormat idFormat = new SimpleDateFormat("yyyyMMddkkmmss"); return Long.parseLong(idFormat.format(new Date())+suffix); } public void putAttribute(String key, String value) { switch(key) { case "id": mId = NumTools.tryParseLong(value, mId); break; case "calendar_id": mCalendarId = NumTools.tryParseLong(value, mCalendarId); break; case "title": mTitle = value; break; case "notes": mNotes = value; break; case "time_start": try { mTimeStart = CustomerDatabase.parseDateRaw(value); } catch (ParseException e) { e.printStackTrace(); } break; case "time_end": try { mTimeEnd = CustomerDatabase.parseDateRaw(value); } catch (ParseException e) { e.printStackTrace(); } break; case "fullday": Integer parsed = NumTools.tryParseInt(value); mFullday = (parsed==null ? 0 : parsed) > 0; break; case "customer": mCustomer = value; break; case "customer_id": mCustomerId = NumTools.tryParseNullableLong(value, mCustomerId); break; case "location": mLocation = value; break; case "last_modified": try { mLastModified = CustomerDatabase.parseDate(value); } catch (ParseException e) { e.printStackTrace(); } break; case "removed": mRemoved = Integer.parseInt(value); break; } } Calendar mCalendar = Calendar.getInstance(); public int getStartTimeInMinutes() { mCalendar.setTime(mTimeStart); int hour = mCalendar.get(Calendar.HOUR_OF_DAY); int min = mCalendar.get(Calendar.MINUTE); return (int)(hour * 60) + min; } public int getEndTimeInMinutes() { mCalendar.setTime(mTimeEnd); int hour = mCalendar.get(Calendar.HOUR_OF_DAY); int min = mCalendar.get(Calendar.MINUTE); return (int)(hour * 60) + min; } }
5,162
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
CustomerCalendar.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/model/CustomerCalendar.java
package de.georgsieber.customerdb.model; import android.annotation.SuppressLint; import androidx.annotation.NonNull; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.ThreadLocalRandom; import de.georgsieber.customerdb.CustomerDatabase; import de.georgsieber.customerdb.tools.NumTools; public class CustomerCalendar { public long mId = -1; public String mTitle = ""; public String mColor = ""; public String mNotes = ""; public Date mLastModified = new Date(); public int mRemoved = 0; public CustomerCalendar() { super(); } public CustomerCalendar(long _id, String _title, String _color, String _notes, Date _lastModified, int _removed) { mId = _id; mTitle = _title; mColor = _color; mNotes = _notes; mLastModified = _lastModified; mRemoved = _removed; } @NonNull @Override public String toString() { return mTitle; } public static long generateID() { /* This function generates an unique mId for a new record. * Required in order to get unique ids over multiple devices, * which are not in sync with the central mysql server */ @SuppressLint("SimpleDateFormat") DateFormat idFormat = new SimpleDateFormat("yyyyMMddkkmmss"); String random; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { random = String.valueOf(ThreadLocalRandom.current().nextInt(1, 100)); } else { random = "10"; } return Long.parseLong(idFormat.format(new Date())+random); } public void putAttribute(String key, String value) { switch(key) { case "id": mId = NumTools.tryParseLong(value, mId); break; case "title": mTitle = value; break; case "color": mColor = value; break; case "notes": mNotes = value; break; case "last_modified": try { mLastModified = CustomerDatabase.parseDate(value); } catch (ParseException e) { e.printStackTrace(); } break; case "removed": mRemoved = Integer.parseInt(value); break; } } }
2,508
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
CustomField.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/model/CustomField.java
package de.georgsieber.customerdb.model; import android.view.View; public class CustomField { public int mId = -1; public String mTitle = ""; public int mType = -1; public String mValue; public View mEditViewReference; public CustomField(String title, int type) { this.mTitle = title; this.mType = type; } public CustomField(int id, String title, int type) { this.mId = id; this.mTitle = title; this.mType = type; } public CustomField(String title, String value) { this.mTitle = title; this.mValue = value; } @Override public String toString() { return mTitle; } }
691
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
Voucher.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/model/Voucher.java
package de.georgsieber.customerdb.model; import android.annotation.SuppressLint; import android.os.Parcel; import android.os.Parcelable; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.concurrent.ThreadLocalRandom; import de.georgsieber.customerdb.CustomerDatabase; import de.georgsieber.customerdb.tools.DateControl; import de.georgsieber.customerdb.tools.NumTools; public class Voucher implements Parcelable { public long mId = -1; public double mOriginalValue = 0; public double mCurrentValue = 0; public String mVoucherNo = ""; public String mFromCustomer = ""; public Long mFromCustomerId = null; public String mForCustomer = ""; public Long mForCustomerId = null; public String mNotes = ""; public Date mIssued = new Date(); public Date mValidUntil; public Date mRedeemed; public Date mLastModified; public int mRemoved = 0; public Voucher() {} public Voucher( long _id, double _currentValue, double _originalValue, String _voucherNo, String _fromCustomer, Long _fromCustomerId, String _forCustomer, Long _forCustomerId, Date _issued, Date _validUntil, Date _redeemed, Date _lastModified, String _notes, int _removed ) { mId = _id; mOriginalValue = _originalValue; mCurrentValue = _currentValue; mVoucherNo = _voucherNo; mFromCustomer = _fromCustomer; mFromCustomerId = _fromCustomerId; mForCustomer = _forCustomer; mForCustomerId = _forCustomerId; mIssued = _issued; mValidUntil = _validUntil; mRedeemed = _redeemed; mNotes = _notes; mRemoved = _removed; mLastModified = _lastModified; } public static long generateID() { /* This function generates an unique mId for a new record. * Required in order to get unique ids over multiple devices, * which are not in sync with the central mysql server */ @SuppressLint("SimpleDateFormat") DateFormat idFormat = new SimpleDateFormat("yyMMddkkmmss"); String random; if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { random = String.valueOf(ThreadLocalRandom.current().nextInt(1, 100)); } else { random = "10"; } return Long.parseLong(idFormat.format(new Date())+random); } public static long generateID(int suffix) { /* specific suffix for bulk import */ @SuppressLint("SimpleDateFormat") DateFormat idFormat = new SimpleDateFormat("yyyyMMddkkmmss"); return Long.parseLong(idFormat.format(new Date())+suffix); } public void putVoucherAttribute(String key, String value) { switch(key) { case "id": mId = NumTools.tryParseLong(value, mId); break; case "current_value": mCurrentValue = Float.parseFloat(value); break; case "original_value": mOriginalValue = Float.parseFloat(value); break; case "voucher_no": mVoucherNo = value; break; case "from_customer": mFromCustomer = value; break; case "from_customer_id": mFromCustomerId = NumTools.tryParseNullableLong(value, mFromCustomerId); break; case "for_customer": mForCustomer = value; break; case "for_customer_id": mForCustomerId = NumTools.tryParseNullableLong(value, mForCustomerId); break; case "notes": mNotes = value; break; case "removed": mRemoved = Integer.parseInt(value); break; case "issued": try { mIssued = CustomerDatabase.parseDate(value); } catch (ParseException e) { e.printStackTrace(); } break; case "redeemed": try { mRedeemed = CustomerDatabase.parseDate(value); } catch (ParseException e) { e.printStackTrace(); } break; case "valid_until": try { mValidUntil = CustomerDatabase.parseDate(value); } catch (ParseException e) { e.printStackTrace(); } break; case "last_modified": try { mLastModified = CustomerDatabase.parseDate(value); } catch (ParseException e) { e.printStackTrace(); } break; } } public String getIdString() { return Long.toString(mId); } public String getCurrentValueString() { return String.format(Locale.getDefault(), "%.2f", mCurrentValue); } public String getOriginalValueString() { return String.format(Locale.getDefault(), "%.2f", mOriginalValue); } public String getIssuedString() { if(mIssued == null) return ""; return DateControl.displayDateFormat.format(mIssued); } public String getValidUntilString() { if(mValidUntil == null) return ""; return DateControl.displayDateFormat.format(mValidUntil); } public String getRedeemedString() { if(mRedeemed == null) return ""; return DateControl.displayDateFormat.format(mRedeemed); } public String getLastModifiedString() { if(mLastModified == null) return ""; return DateControl.displayDateFormat.format(mLastModified); } public void remove() { mCurrentValue = 0; mOriginalValue = 0; mVoucherNo = ""; mFromCustomer = ""; mForCustomer = ""; mNotes = ""; mLastModified = new Date(); mRemoved = 1; } /* everything below here is for implementing Parcelable */ @Override public int describeContents() { return 0; } // write your object's data to the passed-in Parcel @Override public void writeToParcel(Parcel out, int flags) { out.writeLong(mId); out.writeDouble(mOriginalValue); out.writeDouble(mCurrentValue); out.writeString(mVoucherNo); out.writeString(mFromCustomer); out.writeLong(mFromCustomerId == null ? 0 : mFromCustomerId); out.writeString(mForCustomer); out.writeLong(mForCustomerId == null ? 0 : mForCustomerId); out.writeString(mNotes); out.writeLong(mIssued == null ? 0 : mIssued.getTime()); out.writeLong(mValidUntil == null ? 0 : mValidUntil.getTime()); out.writeLong(mRedeemed == null ? 0 : mRedeemed.getTime()); out.writeLong(mLastModified.getTime()); } // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods public static final Parcelable.Creator<Voucher> CREATOR = new Parcelable.Creator<Voucher>() { public Voucher createFromParcel(Parcel in) { return new Voucher(in); } public Voucher[] newArray(int size) { return new Voucher[size]; } }; // example constructor that takes a Parcel and gives you an object populated with it's values private Voucher(Parcel in) { mId = in.readLong(); mOriginalValue = in.readDouble(); mCurrentValue = in.readDouble(); mVoucherNo = in.readString(); mFromCustomer = in.readString(); long fromCustomerId = in.readLong(); mFromCustomerId = fromCustomerId == 0 ? null : fromCustomerId; mForCustomer = in.readString(); long forCustomerId = in.readLong(); mForCustomerId = forCustomerId == 0 ? null : forCustomerId; mNotes = in.readString(); long issued = in.readLong(); mIssued = issued == 0 ? null : new Date(issued); long validUntil = in.readLong(); mValidUntil = validUntil == 0 ? null : new Date(validUntil); long redeemed = in.readLong(); mRedeemed = redeemed == 0 ? null : new Date(redeemed); mLastModified = new Date(in.readLong()); } }
8,420
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
Customer.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/model/Customer.java
package de.georgsieber.customerdb.model; import android.annotation.SuppressLint; import android.content.Context; import android.os.Build; import android.util.Base64; import androidx.annotation.NonNull; import org.json.JSONArray; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.Period; import java.time.ZoneId; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import de.georgsieber.customerdb.CustomerDatabase; import de.georgsieber.customerdb.R; import de.georgsieber.customerdb.tools.DateControl; import de.georgsieber.customerdb.tools.NumTools; public class Customer { public long mId = -1; public String mTitle = ""; public String mFirstName = ""; public String mLastName = ""; public String mPhoneHome = ""; public String mPhoneMobile = ""; public String mPhoneWork = ""; public String mEmail = ""; public String mStreet = ""; public String mZipcode = ""; public String mCity = ""; public String mCountry = ""; public Date mBirthday; public String mCustomerGroup = ""; public boolean mNewsletter = false; public String mNotes = ""; public byte[] mImage = new byte[0]; public ArrayList<CustomerFile> mFiles = null; public String mCustomFields = ""; public Date mLastModified = new Date(); public int mRemoved = 0; public Customer() { super(); } public Customer(long _id, String _title, String _firstName, String _lastName, String _phoneHome, String _phoneMobile, String _phoneWork, String _email, String _street, String _zipcode, String _city, String _country, Date _birthday, String _group, boolean _newsletter, String _notes, String _customFields, Date _lastModified) { mId = _id; mTitle = _title; mFirstName = _firstName; mLastName = _lastName; mPhoneHome = _phoneHome; mPhoneMobile = _phoneMobile; mPhoneWork = _phoneWork; mEmail = _email; mStreet = _street; mZipcode = _zipcode; mCity = _city; mCountry = _country; mBirthday = _birthday; mCustomerGroup = _group; mNewsletter = _newsletter; mNotes = _notes; mCustomFields = _customFields; mLastModified = _lastModified; } public Customer(long _id, String _title, String _firstName, String _lastName, String _phoneHome, String _phoneMobile, String _phoneWork, String _email, String _street, String _zipcode, String _city, String _country, Date _birthday, String _group, boolean _newsletter, String _notes, String _customFields, Date _lastModified, int _removed) { mId = _id; mTitle = _title; mFirstName = _firstName; mLastName = _lastName; mPhoneHome = _phoneHome; mPhoneMobile = _phoneMobile; mPhoneWork = _phoneWork; mEmail = _email; mStreet = _street; mZipcode = _zipcode; mCity = _city; mCountry = _country; mBirthday = _birthday; mCustomerGroup = _group; mNewsletter = _newsletter; mNotes = _notes; mCustomFields = _customFields; mLastModified = _lastModified; mRemoved = _removed; } public static long generateID() { /* This function generates an unique mId for a new record. * Required in order to get unique ids over multiple devices, * which are not in sync with the central mysql server */ @SuppressLint("SimpleDateFormat") DateFormat idFormat = new SimpleDateFormat("yyyyMMddkkmmss"); String random; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { random = String.valueOf(ThreadLocalRandom.current().nextInt(1, 100)); } else { random = "10"; } return Long.parseLong(idFormat.format(new Date())+random); } public static long generateID(int suffix) { /* specific suffix for bulk import */ @SuppressLint("SimpleDateFormat") DateFormat idFormat = new SimpleDateFormat("yyyyMMddkkmmss"); return Long.parseLong(idFormat.format(new Date())+suffix); } public void putCustomerAttribute(String key, String value) { switch(key) { case "id": mId = NumTools.tryParseLong(value, mId); break; case "title": mTitle = value; break; case "first_name": mFirstName = value; break; case "last_name": mLastName = value; break; case "phone_home": mPhoneHome = value; break; case "phone_mobile": mPhoneMobile = value; break; case "phone_work": mPhoneWork = value; break; case "email": mEmail = value; break; case "street": mStreet = value; break; case "zipcode": mZipcode = value; break; case "city": mCity = value; break; case "country": mCountry = value; break; case "birthday": if(value.contains("1800")) { mBirthday = null; } else { try { mBirthday = CustomerDatabase.parseDateRaw(value); } catch (ParseException e) { e.printStackTrace(); } } break; case "last_modified": try { mLastModified = CustomerDatabase.parseDate(value); } catch (ParseException e) { e.printStackTrace(); } break; case "notes": mNotes = value; break; case "customer_group": mCustomerGroup = value; break; case "newsletter": mNewsletter = (value.equals("1")); break; case "consent": // deprecated break; case "image": try { mImage = Base64.decode(value, Base64.NO_WRAP); } catch(Exception ignored) {} break; case "files": try { JSONArray jsonFiles = new JSONArray(value); for(int i=0; i < jsonFiles.length(); i++) { JSONObject jsonFile = jsonFiles.getJSONObject(i); addFile(new CustomerFile(jsonFile.getString("name"), Base64.decode(jsonFile.getString("content"), Base64.NO_WRAP)), null); } } catch(Exception ignored) {} break; case "custom_fields": mCustomFields = value; break; case "removed": mRemoved = Integer.parseInt(value); break; default: updateOrCreateCustomField(key, value); } } public void addFile(CustomerFile file, Context context) throws Exception { if(mFiles == null) mFiles = new ArrayList<>(); if(file.mContent.length > 1024 * 1024) { throw new Exception( context==null ? "File too big!" : context.getString(R.string.file_too_big) ); } if(mFiles.size() >= 20) { throw new Exception( context==null ? "File limit reached!" : context.getString(R.string.file_limit_reached) ); } mFiles.add(file); } public void renameFile(int fileIndex, String newName) { if(mFiles == null || newName.equals("")) return; mFiles.get(fileIndex).mName = newName; } public void removeFile(int fileIndex) { if(mFiles == null) return; mFiles.remove(fileIndex); } public ArrayList<CustomerFile> getFiles() { if(mFiles == null) mFiles = new ArrayList<>(); return mFiles; } public byte[] getImage() { if(this.mImage == null) return new byte[0]; else return this.mImage; } @NonNull @Override public String toString() { return this.mLastName + ", " + this.mFirstName; } public String getFullName(boolean lastNameFirst) { String final_title = ""; if(!this.mTitle.equals("")) final_title = this.mTitle +" "; String final_name; if(this.mLastName.equals("")) final_name = this.mFirstName; else if(this.mFirstName.equals("")) final_name = this.mLastName; else if(lastNameFirst) final_name = this.mLastName + ", " + this.mFirstName; else final_name = this.mFirstName + " " + this.mLastName; return final_title + final_name; } public String getAddress() { if(this.mStreet == null || this.mZipcode == null || this.mCity == null || this.mCountry == null) return ""; else return (this.mStreet + "\n" + this.mZipcode + " " + this.mCity + "\n" + this.mCountry).trim(); } private static boolean isSameDay(Date date1, Date date2) { if(date1 == null || date2 == null) { throw new IllegalArgumentException("The dates must not be null"); } Calendar cal1 = Calendar.getInstance(); cal1.setTime(date1); Calendar cal2 = Calendar.getInstance(); cal2.setTime(date2); return isSameDay(cal1, cal2); } private static boolean isSameDay(Calendar cal1, Calendar cal2) { if(cal1 == null || cal2 == null) { throw new IllegalArgumentException("The dates must not be null"); } return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR)); } private static boolean isToday(Date date) { return isSameDay(date, Calendar.getInstance().getTime()); } public String getBirthdayString() { return getBirthdayString(""); } public String getBirthdayString(String todayNote) { // 1900 = birthday without year // 1800 = no birthday if(mBirthday == null) return ""; String years = ""; if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { int diff = Period.between(mBirthday.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(), LocalDate.now()).getYears(); if(diff < 120) years = " (" + diff + ")"; } String finalString = DateControl.birthdayDateFormat.format(mBirthday) + years; if(!todayNote.equals("") && isToday(getNextBirthday())) finalString += " " + todayNote; return finalString; } public Date getNextBirthday() { if(mBirthday == null) return null; try { Calendar current = Calendar.getInstance(); Calendar cal = Calendar.getInstance(); cal.setTime(mBirthday); cal.set(Calendar.YEAR, current.get(Calendar.YEAR)); if(cal.get(Calendar.DAY_OF_MONTH) != current.get(Calendar.DAY_OF_MONTH) || cal.get(Calendar.MONTH) != current.get(Calendar.MONTH)) { // birthday is today - this is ok if(cal.getTimeInMillis() < current.getTimeInMillis()) { // birthday this year is already in the past - go to next year cal.set(Calendar.YEAR, current.get(Calendar.YEAR) + 1); } } return cal.getTime(); } catch(Exception ignored) { return null; } } public String getFirstLine() { return this.getFullName(true); } public String getSecondLine() { if(!mPhoneHome.equals("")) return mPhoneHome; else if(!mPhoneMobile.equals("")) return mPhoneMobile; else if(!mPhoneWork.equals("")) return mPhoneWork; else if(!mEmail.equals("")) return mEmail; else return getFirstNotEmptyCustomFieldString(); } /* parsing custom fields string */ public List<CustomField> getCustomFields() { List<CustomField> fields = new ArrayList<>(); for(String kv : mCustomFields.split("&")) { String[] kv_split = kv.split("="); if(kv_split.length == 2) { try { fields.add(new CustomField( URLDecoder.decode(kv_split[0], "UTF-8"), URLDecoder.decode(kv_split[1], "UTF-8") )); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } return fields; } private String getFirstNotEmptyCustomFieldString() { for(CustomField field : getCustomFields()) { if(!field.mValue.equals("")) { return field.mValue; } } return ""; } public String getCustomField(String key) { for(CustomField cf : getCustomFields()) { if(cf.mTitle.equals(key)) { return cf.mValue; } } return null; } public void setCustomFields(List<CustomField> fields) { StringBuilder sb = new StringBuilder(); for(CustomField cf : fields) { try { sb.append(URLEncoder.encode(cf.mTitle, "UTF-8")); sb.append("="); sb.append(URLEncoder.encode(cf.mValue, "UTF-8")); sb.append("&"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } mCustomFields = sb.toString(); } public void updateOrCreateCustomField(String title, String value) { List<CustomField> fields = getCustomFields(); for(CustomField cf : fields) { if(cf.mTitle.equals(title)) { cf.mValue = value; setCustomFields(fields); return; } } fields.add(new CustomField(title, value)); setCustomFields(fields); } /* everything below here is for implementing Parcelable @Override public int describeContents() { return 0; } // write your object's data to the passed-in Parcel @Override public void writeToParcel(Parcel out, int flags) { out.writeLong(mId); out.writeString(mTitle); out.writeString(mFirstName); out.writeString(mLastName); out.writeString(mPhoneHome); out.writeString(mPhoneMobile); out.writeString(mPhoneWork); out.writeString(mEmail); out.writeString(mStreet); out.writeString(mZipcode); out.writeString(mCity); out.writeString(mCountry); out.writeLong(mBirthday == null ? 0 : mBirthday.getTime()); out.writeString(mCustomerGroup); out.writeString(mNotes); out.writeInt(mNewsletter ? 1 : 0); out.writeString(mCustomFields); out.writeLong(mLastModified.getTime()); out.writeString(mFilesJson); out.writeInt(mImage == null ? 0 : mImage.length); out.writeByteArray(mImage == null ? new byte[0] : mImage); } // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods public static final Parcelable.Creator<Customer> CREATOR = new Parcelable.Creator<Customer>() { public Customer createFromParcel(Parcel in) { return new Customer(in); } public Customer[] newArray(int size) { return new Customer[size]; } }; // example constructor that takes a Parcel and gives you an object populated with it's values private Customer(Parcel in) { mId = in.readLong(); mTitle = in.readString(); mFirstName = in.readString(); mLastName = in.readString(); mPhoneHome = in.readString(); mPhoneMobile = in.readString(); mPhoneWork = in.readString(); mEmail = in.readString(); mStreet = in.readString(); mZipcode = in.readString(); mCity = in.readString(); mCountry = in.readString(); long birthday = in.readLong(); mBirthday = birthday == 0 ? null : new Date(birthday); mCustomerGroup = in.readString(); mNotes = in.readString(); mNewsletter = in.readInt() == 1; mCustomFields = in.readString(); mLastModified = new Date(in.readLong()); mFilesJson = in.readString(); mImage = new byte[in.readInt()]; in.readByteArray(mImage); }*/ }
17,558
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
CustomerFile.java
/FileExtraction/Java_unseen/schorschii_CustomerDB-Android/app/src/main/java/de/georgsieber/customerdb/model/CustomerFile.java
package de.georgsieber.customerdb.model; public class CustomerFile { public String mName; public byte[] mContent; public CustomerFile(String _name, byte[] _content) { mName = _name; mContent = _content; } }
241
Java
.java
schorschii/CustomerDB-Android
12
3
0
2020-01-19T14:30:58Z
2024-03-11T12:41:57Z
GenFeign.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-core/src/main/java/io/qifan/infrastructure/generator/core/GenFeign.java
package io.qifan.infrastructure.generator.core; public @interface GenFeign { String moduleName() default ""; String sourcePath() default ""; String suffix() default "FeignClient"; String packageName() default "feign"; }
239
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
GenField.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-core/src/main/java/io/qifan/infrastructure/generator/core/GenField.java
package io.qifan.infrastructure.generator.core; import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Inherited @Target({ElementType.FIELD}) public @interface GenField { String description() default ""; String dtoType() default ""; boolean association() default false; boolean ignoreRequest() default false; boolean ignoreResponse() default false; }
391
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
GenController.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-core/src/main/java/io/qifan/infrastructure/generator/core/GenController.java
package io.qifan.infrastructure.generator.core; public @interface GenController { String sourcePath() default ""; String suffix() default "Controller"; String packageName() default "controller"; }
212
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
GenResponse.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-core/src/main/java/io/qifan/infrastructure/generator/core/GenResponse.java
package io.qifan.infrastructure.generator.core; public @interface GenResponse { String sourcePath() default ""; String suffix() default "Response"; String packageName() default "dto.response"; String[] ignoreFields() default {}; }
251
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
GenRepository.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-core/src/main/java/io/qifan/infrastructure/generator/core/GenRepository.java
package io.qifan.infrastructure.generator.core; public @interface GenRepository { String sourcePath() default ""; String packageName() default "repository"; String suffix() default "Repository"; }
213
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
DtoType.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-core/src/main/java/io/qifan/infrastructure/generator/core/DtoType.java
package io.qifan.infrastructure.generator.core; import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Inherited @Target({ElementType.FIELD}) public @interface DtoType { String type() default "java.lang.String"; boolean association() default false; }
275
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
GenType.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-core/src/main/java/io/qifan/infrastructure/generator/core/GenType.java
package io.qifan.infrastructure.generator.core; public enum GenType { CONTROLLER, SERVICE, REPOSITORY, MAPPER, DTO_RESPONSE, DTO_CREATE, DTO_UPDATE, DTO_QUERY, FEIGN, TYPING, API }
226
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
GenService.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-core/src/main/java/io/qifan/infrastructure/generator/core/GenService.java
package io.qifan.infrastructure.generator.core; public @interface GenService { String sourcePath() default ""; String packageName() default "service"; String suffix() default "Service"; }
203
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
GenMapper.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-core/src/main/java/io/qifan/infrastructure/generator/core/GenMapper.java
package io.qifan.infrastructure.generator.core; public @interface GenMapper { String sourcePath() default ""; String packageName() default "mapper"; String suffix() default "Mapper"; }
202
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
GenEntity.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-core/src/main/java/io/qifan/infrastructure/generator/core/GenEntity.java
package io.qifan.infrastructure.generator.core; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.CLASS) public @interface GenEntity { String sourcePath() default "src/main/java"; String requestSourcePath() default "src/main/java"; String responseSourcePath() default "src/main/java"; GenType[] genTypeList() default {GenType.DTO_QUERY, GenType.DTO_CREATE, GenType.DTO_UPDATE, GenType.DTO_RESPONSE, GenType.MAPPER, GenType.REPOSITORY, GenType.SERVICE, GenType.CONTROLLER, GenType.TYPING, GenType.FEIGN, GenType.API}; GenController genController() default @GenController; GenService genService() default @GenService; GenMapper genMapper() default @GenMapper; GenRepository genRepository() default @GenRepository; GenRequest[] genRequest() default { @GenRequest(suffix = "CreateRequest"), @GenRequest(suffix = "UpdateRequest"), @GenRequest(suffix = "QueryRequest")}; GenResponse[] genResponse() default { @GenResponse(suffix = "CommonResponse") }; GenFeign genFeign()default @GenFeign; }
1,677
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
GenRequest.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-core/src/main/java/io/qifan/infrastructure/generator/core/GenRequest.java
package io.qifan.infrastructure.generator.core; public @interface GenRequest { String sourcePath() default ""; String suffix() default "Request"; String packageName() default "dto.request"; String[] ignoreFields() default {}; }
248
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
QiFanProcessor.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/QiFanProcessor.java
package io.qifan.infrastructure.generator.processor; import io.qifan.infrastructure.generator.processor.processor.DefaultModelElementProcessorContext; import io.qifan.infrastructure.generator.processor.processor.EntityCreateProcessor; import io.qifan.infrastructure.generator.processor.processor.ModelElementProcessor; import io.qifan.infrastructure.generator.processor.processor.TemplateRenderingProcessor; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.TypeElement; import javax.lang.model.util.ElementFilter; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; @SupportedAnnotationTypes("io.qifan.infrastructure.generator.core.GenEntity") public class QiFanProcessor extends AbstractProcessor { Set<ModelElementProcessor<?, ?>> processors; @Override public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); processors = new TreeSet<>((o1, o2) -> o2.getPriority() - o1.getPriority()); processors.add(new TemplateRenderingProcessor()); processors.add(new EntityCreateProcessor()); } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { Set<TypeElement> entities = getEntities(annotations, roundEnv); processEntityElements(entities); return false; } public Set<TypeElement> getEntities(Set<? extends TypeElement> annotations, RoundEnvironment roundEnvironment) { Set<TypeElement> entityTypes = new HashSet<>(); for (TypeElement annotation : annotations) { if (annotation.getKind() != ElementKind.ANNOTATION_TYPE) { continue; } Set<? extends Element> elementsAnnotatedWith = roundEnvironment.getElementsAnnotatedWith(annotation); Set<TypeElement> typeElements = ElementFilter.typesIn(elementsAnnotatedWith); entityTypes.addAll(typeElements); } return entityTypes; } public void processEntityElements(Set<TypeElement> typeElements) { for (TypeElement typeElement : typeElements) { DefaultModelElementProcessorContext defaultModelElementProcessorContext = new DefaultModelElementProcessorContext( this.processingEnv, typeElement); processEntityTypeElement(defaultModelElementProcessorContext); } } private void processEntityTypeElement(ModelElementProcessor.ProcessorContext context) { Object model = null; for (ModelElementProcessor<?, ?> processor : processors) { model = process(context, processor, model); } } private <P, R> R process(ModelElementProcessor.ProcessorContext context, ModelElementProcessor<P, R> processor, Object modelElement) { @SuppressWarnings("unchecked") P sourceElement = (P) modelElement; return processor.process(context, sourceElement); } }
3,315
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
FreeMarkerWritable.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/writer/FreeMarkerWritable.java
package io.qifan.infrastructure.generator.processor.writer; import freemarker.template.TemplateException; import java.io.IOException; import java.io.Writer; public abstract class FreeMarkerWritable implements Writable { @Override public void write(Context context, Writer writer) { try { new FreeMarkerModelElementWriter().write(this, context, writer); } catch (IOException | TemplateException e) { throw new RuntimeException(e); } } protected String getTemplateName() { return getTemplateNameForClass(getClass()); } protected String getTemplateNameForClass(Class<?> clazz) { return clazz.getName().replace('.', '/') + ".ftl"; } }
729
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
Writable.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/writer/Writable.java
package io.qifan.infrastructure.generator.processor.writer; import java.io.Writer; public interface Writable { void write(Context context, Writer writer); interface Context { <T> T get(Class<T> type); } }
228
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
ModelWriter.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/writer/ModelWriter.java
package io.qifan.infrastructure.generator.processor.writer; import freemarker.cache.StrongCacheStorage; import freemarker.cache.TemplateLoader; import freemarker.log.Logger; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import io.qifan.infrastructure.generator.processor.model.common.Type; import io.qifan.infrastructure.generator.processor.model.front.FrontModel; import java.io.*; import java.net.URL; import java.net.URLConnection; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; public class ModelWriter { private static final Configuration CONFIGURATION; static { try { Logger.selectLoggerLibrary(Logger.LIBRARY_NONE); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } CONFIGURATION = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); CONFIGURATION.setTemplateLoader(new SimpleClasspathLoader()); CONFIGURATION.setObjectWrapper(new DefaultObjectWrapper(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS)); CONFIGURATION.setSharedVariable( "includeModel", new ModelIncludeDirective(CONFIGURATION) ); // do not refresh/gc the cached templates, as we never change them at runtime CONFIGURATION.setCacheStorage(new StrongCacheStorage()); CONFIGURATION.setTemplateUpdateDelay(Integer.MAX_VALUE); CONFIGURATION.setLocalizedLookup(false); } public void writeModel(FrontModel model, Boolean append) { File dir = Paths.get("src/main/resources/front").toFile(); if (!dir.exists()) { dir.mkdirs(); } File file = Paths.get("src/main/resources/front", model.getFileName()).toFile(); if (!append & file.exists()) { return; } writeModel(file, model, append); } public void writeModel(File file, Writable model, Boolean append) { try (FileWriter writer = new FileWriter(file, append)) { Map<Class<?>, Object> values = new HashMap<>(); values.put(Configuration.class, CONFIGURATION); model.write(new DefaultModelElementWriterContext(values), writer); writer.flush(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } } public void writeModel(String sourcePath, Type type, Writable model) { File packageDir = Paths.get(sourcePath, type.getPackageDir()).toFile(); if (!packageDir.exists()) { packageDir.mkdirs(); } File javaFile = Paths.get(sourcePath, type.getPackageDir(), type.getFileName()).toFile(); if (javaFile.exists()) { return; } writeModel(javaFile, model, false); } private static final class SimpleClasspathLoader implements TemplateLoader { @Override public Reader getReader(Object name, String encoding) throws IOException { URL url = getClass().getClassLoader().getResource(String.valueOf(name)); if (url == null) { throw new IllegalStateException(name + " not found on classpath"); } URLConnection connection = url.openConnection(); // don't use jar-file caching, as it caused occasionally closed input streams [at least under JDK 1.8.0_25] connection.setUseCaches(false); InputStream is = connection.getInputStream(); return new InputStreamReader(is, StandardCharsets.UTF_8); } @Override public long getLastModified(Object templateSource) { return 0; } @Override public Object findTemplateSource(String name) throws IOException { return name; } @Override public void closeTemplateSource(Object templateSource) throws IOException { } } static class DefaultModelElementWriterContext implements Writable.Context { private final Map<Class<?>, Object> values; DefaultModelElementWriterContext(Map<Class<?>, Object> values) { this.values = new HashMap<>(values); } @Override @SuppressWarnings("unchecked") public <T> T get(Class<T> type) { return (T) values.get(type); } } }
4,471
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
ModelIncludeDirective.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/writer/ModelIncludeDirective.java
package io.qifan.infrastructure.generator.processor.writer; import freemarker.core.Environment; import freemarker.ext.beans.BeanModel; import freemarker.template.Configuration; import freemarker.template.TemplateDirectiveBody; import freemarker.template.TemplateDirectiveModel; import freemarker.template.TemplateModel; import java.util.HashMap; import java.util.Map; public class ModelIncludeDirective implements TemplateDirectiveModel { private final Configuration configuration; public ModelIncludeDirective(Configuration configuration) { this.configuration = configuration; } @Override public void execute(Environment env, @SuppressWarnings("rawtypes") Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) { Writable modelElement = getModelElement(params); ModelWriter.DefaultModelElementWriterContext context = createContext(params); if (modelElement != null) { modelElement.write(context, env.getOut()); } } @SuppressWarnings("rawtypes") private Writable getModelElement(Map params) { if (!params.containsKey("object")) { throw new IllegalArgumentException( "Object to be included must be passed to this directive via the 'object' parameter" ); } BeanModel objectModel = (BeanModel) params.get("object"); if (objectModel == null) { return null; } if (!(objectModel.getWrappedObject() instanceof Writable)) { throw new IllegalArgumentException("Given object isn't a Writable:" + objectModel.getWrappedObject()); } return (Writable) objectModel.getWrappedObject(); } /** * Creates a writer context providing access to the FreeMarker * {@link Configuration} and a map with any additional parameters passed to * the directive. * * @param params The parameter map passed to this directive. * @return A writer context. */ @SuppressWarnings({"rawtypes", "unchecked"}) private ModelWriter.DefaultModelElementWriterContext createContext(Map params) { Map<String, Object> ext = new HashMap<String, Object>(params); ext.remove("object"); Map<Class<?>, Object> values = new HashMap<>(); values.put(Configuration.class, configuration); values.put(Map.class, ext); return new ModelWriter.DefaultModelElementWriterContext(values); } }
2,496
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
FreeMarkerModelElementWriter.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/writer/FreeMarkerModelElementWriter.java
package io.qifan.infrastructure.generator.processor.writer; import freemarker.ext.beans.BeanModel; import freemarker.ext.beans.BeansWrapper; import freemarker.ext.beans.SimpleMapModel; import freemarker.template.*; import java.io.IOException; import java.io.Writer; import java.util.Map; public class FreeMarkerModelElementWriter { public void write(FreeMarkerWritable writable, Writable.Context context, Writer writer) throws IOException, TemplateException { Configuration configuration = context.get(Configuration.class); Template template = configuration.getTemplate(writable.getTemplateName()); template.process(new ExternalParamsTemplateModel(new BeanModel(writable, BeansWrapper.getDefaultInstance()), new SimpleMapModel(context.get( Map.class), BeansWrapper.getDefaultInstance())), writer); } private record ExternalParamsTemplateModel(BeanModel object, SimpleMapModel extParams) implements TemplateHashModel { @Override public TemplateModel get(String key) throws TemplateModelException { if (key.equals("ext")) { return extParams; } else { return object.get(key); } } @Override public boolean isEmpty() throws TemplateModelException { return object.isEmpty() && extParams.isEmpty(); } } }
1,543
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
AnnotationProcessorContext.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/utils/AnnotationProcessorContext.java
package io.qifan.infrastructure.generator.processor.utils; import javax.annotation.processing.Messager; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; public record AnnotationProcessorContext(Elements elementUtils, Types typeUtils, Messager messager) { }
286
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
GenEntityUtils.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/utils/GenEntityUtils.java
package io.qifan.infrastructure.generator.processor.utils; import io.qifan.infrastructure.generator.core.*; import java.util.Arrays; import java.util.List; public class GenEntityUtils { private final GenEntity genEntity; public GenEntityUtils(GenEntity genEntity) { this.genEntity = genEntity; } public GenController getController() { return genEntity.genController(); } public GenMapper getMapper() { return genEntity.genMapper(); } public GenService getService() { return genEntity.genService(); } public GenRepository getRepository() { return genEntity.genRepository(); } public List<GenResponse> getResponses() { return List.of(genEntity.genResponse()); } public List<GenRequest> getRequests() { return List.of(genEntity.genRequest()); } public GenFeign getFeign() { return genEntity.genFeign(); } public String getSourcePath() { return genEntity.sourcePath(); } public String getRequestSourcePath() { return genEntity.requestSourcePath(); } public String getResponseSourcePath() { return genEntity.responseSourcePath(); } public boolean hasTyping() { return matchGenType(GenType.TYPING); } public boolean hasApi() { return matchGenType(GenType.API); } public boolean hasController() { return matchGenType(GenType.CONTROLLER); } public boolean hasService() { return matchGenType(GenType.SERVICE); } public boolean hasRepository() { return matchGenType(GenType.REPOSITORY); } public boolean hasMapper() { return matchGenType(GenType.MAPPER); } public boolean hasCreateDTO() { return matchGenType(GenType.DTO_CREATE); } public boolean hasUpdateDTO() { return matchGenType(GenType.DTO_UPDATE); } public boolean hasQueryDTO() { return matchGenType(GenType.DTO_QUERY); } public boolean hashResponseDTO() { return matchGenType(GenType.DTO_RESPONSE); } public boolean matchGenType(GenType genType) { return Arrays.asList(genEntity.genTypeList()).contains(genType); } }
2,347
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
FieldUtils.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/utils/FieldUtils.java
package io.qifan.infrastructure.generator.processor.utils; import io.qifan.infrastructure.generator.core.GenField; import io.qifan.infrastructure.generator.processor.model.common.Field; import io.qifan.infrastructure.generator.processor.model.common.Type; import org.springframework.util.StringUtils; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.util.ElementFilter; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; public class FieldUtils { public static List<Field> getFields(TypeElement typeElement) { List<? extends Element> enclosedElements = typeElement.getEnclosedElements(); List<VariableElement> variableElements = ElementFilter.fieldsIn(enclosedElements); return variableElements.stream() .map(variableElement -> { String typeString = variableElement.asType().toString(); // 包含了注解和类型 String[] annotationsAndType = typeString.split(" "); String typePath = annotationsAndType[annotationsAndType.length - 1]; Type type = TypeUtils.getType(typePath); Optional<GenField> genFieldOptional = Optional.ofNullable(variableElement.getAnnotation(GenField.class)); if (isParameterType(typePath)) { type = TypeUtils.getParameterType(typePath); } return Field.builder() .type(type) .description(genFieldOptional.map(GenField::description).orElse("")) .fieldName(variableElement.getSimpleName() .toString()) .build(); }).toList(); } public static List<Field> getFieldsForRequest(TypeElement typeElement, String[] ignoreFields, String packageName, String suffix) { return getFields(typeElement, ignoreFields, packageName, suffix, genField -> { // 过滤条件,忽略为true则返回的为false,这样filter才可以过滤。 return !Optional.ofNullable(genField).map(GenField::ignoreRequest).orElse(false); }); } public static List<Field> getFieldsForResponse(TypeElement typeElement, String[] ignoreFields, String packageName, String suffix) { return getFields(typeElement, ignoreFields, packageName, suffix, genField -> { // 过滤条件,忽略为true则返回的为false,这样filter才可以过滤。 return !Optional.ofNullable(genField).map(GenField::ignoreResponse).orElse(false); }); } public static List<Field> getFields(TypeElement typeElement, String[] ignoreFields, String packageName, String suffix, Predicate<GenField> predicate) { List<? extends Element> enclosedElements = typeElement.getEnclosedElements(); List<VariableElement> variableElements = ElementFilter.fieldsIn(enclosedElements); return variableElements.stream() // 过滤掉ignore的属性 .filter(variableElement -> { GenField annotation = variableElement.getAnnotation(GenField.class); return !Arrays.asList(ignoreFields) .contains( variableElement.getSimpleName().toString()) && predicate.test( annotation); }) .map(variableElement -> { String typeString = variableElement.asType().toString(); // 包含了注解和类型 String[] annotationsAndType = typeString.split(" "); String typePath = annotationsAndType[annotationsAndType.length - 1]; Type type = TypeUtils.getType(typePath); if (isParameterType(typePath)) { type = TypeUtils.getParameterType(typePath); } if (isAssociation(variableElement)) { if (isParameterType(typePath)) { Matcher matcher = Pattern.compile("<([a-zA-Z.]*)>") .matcher(typePath); if (matcher.find()) { String entityTypePath = matcher.group(1); String[] split = entityTypePath.split("\\."); String entityTypeName = split[split.length - 1]; String dtoTypePath = entityTypePath.replace(entityTypeName, packageName + "." + entityTypeName + suffix); type = TypeUtils.getParameterType(typePath.replace(entityTypePath, dtoTypePath)); } } else { String[] split = typePath.split("\\."); String entityTypeName = split[split.length - 1]; String dtoTypePath = typePath.replace(entityTypeName, packageName + "." + entityTypeName + suffix); type = TypeUtils.getType(dtoTypePath); } } Optional<GenField> genFieldOptional = Optional.ofNullable(variableElement.getAnnotation(GenField.class)); if (genFieldOptional.map(field -> StringUtils.hasText(field.dtoType())) .orElse(false)) { type = TypeUtils.getType(variableElement, genFieldOptional.orElse(null)); } return Field.builder() .description(genFieldOptional.map(GenField::description).orElse("")) .fieldName(variableElement.getSimpleName() .toString()) .type(type) .build(); }).toList(); } public static boolean isAssociation(VariableElement variableElement) { return Optional.ofNullable(variableElement.getAnnotation(GenField.class)) .map(GenField::association) .orElse(false); } public static boolean isParameterType(String typePath) { return typePath.contains("<"); } }
8,430
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
TypeUtils.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/utils/TypeUtils.java
package io.qifan.infrastructure.generator.processor.utils; import io.qifan.infrastructure.generator.core.GenField; import io.qifan.infrastructure.generator.processor.model.common.ParameterType; import io.qifan.infrastructure.generator.processor.model.common.Type; import org.springframework.util.StringUtils; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import java.util.Optional; public class TypeUtils { public static ParameterType getParameterType(String typePath) { int start = typePath.length(); int end = typePath.length(); for (int i = 0; i < typePath.length(); i++) { if (typePath.charAt(i) == '<') { start = i; break; } } for (int i = typePath.length() - 1; i > 0; i--) { if (typePath.charAt(i) == '>') { end = i; break; } } ParameterType parameterType = null; if (start < end) { parameterType = getParameterType(typePath.substring(start + 1, end)); } return new ParameterType(TypeUtils.getType(typePath.substring(0, start)), parameterType); } public static Type getType(TypeElement entityType, String packageName, String suffix) { String typeName = entityType.getSimpleName() + suffix; String packagePath = entityType.getQualifiedName() .toString() .replace(entityType.getSimpleName(), "") + packageName; return Type.builder() .typeName(typeName) .packagePath(packagePath) .build(); } public static Type getType(TypeElement entityType) { return getType(entityType.getQualifiedName().toString()); } public static Type getType(VariableElement variableElement, GenField genField) { String typePath = Optional.ofNullable(genField) .map(field -> StringUtils.hasText(field.dtoType()) ? field.dtoType() : null) .orElse(variableElement.asType().toString()); return getType(typePath); } public static Type getType(String typePath) { String[] splits = typePath.split("\\."); String typeName = splits[splits.length - 1]; String packagePath = typePath.replace("." + splits[splits.length - 1], ""); return getType(typeName, packagePath); } public static Type getType(String typeName, String packagePath) { return Type.builder() .typeName(typeName) .packagePath(packagePath) .build(); } public static Type getType(Class<?> clazz) { return getType(clazz.getSimpleName(), clazz.getPackageName()); } }
2,868
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
ModelElementProcessor.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/processor/ModelElementProcessor.java
package io.qifan.infrastructure.generator.processor.processor; import javax.annotation.processing.Filer; import javax.lang.model.element.TypeElement; public interface ModelElementProcessor<P, R> { R process(ProcessorContext context, P sourceModel); int getPriority(); interface ProcessorContext { Filer getFiler(); TypeElement getTypeElement(); } }
390
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
TemplateRenderingProcessor.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/processor/TemplateRenderingProcessor.java
package io.qifan.infrastructure.generator.processor.processor; import io.qifan.infrastructure.generator.processor.model.Entity; import io.qifan.infrastructure.generator.processor.model.controller.Controller; import io.qifan.infrastructure.generator.processor.model.dto.Request; import io.qifan.infrastructure.generator.processor.model.dto.Response; import io.qifan.infrastructure.generator.processor.model.feign.Feign; import io.qifan.infrastructure.generator.processor.model.front.Api; import io.qifan.infrastructure.generator.processor.model.front.Typing; import io.qifan.infrastructure.generator.processor.model.mapper.Mapper; import io.qifan.infrastructure.generator.processor.model.repository.Repository; import io.qifan.infrastructure.generator.processor.model.service.Service; import io.qifan.infrastructure.generator.processor.writer.ModelWriter; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import java.util.List; @Slf4j public class TemplateRenderingProcessor implements ModelElementProcessor<Entity, Entity> { @Override public Entity process(ProcessorContext processorContext, Entity entity) { ModelWriter modelWriter = new ModelWriter(); if (entity.hasController()) { writeController(modelWriter, entity.getController()); } if (entity.hasRequests()) { writeRequests(modelWriter, entity.getRequests()); } if (entity.hasResponse()) { writeResponse(modelWriter, entity.getResponses()); } if (entity.hasMapper()) { writeMapper(modelWriter, entity.getMapper()); } if (entity.hasRepository()) { writeRepository(modelWriter, entity.getRepository()); } if (entity.hasService()) { writeService(modelWriter, entity.getService()); } if (entity.hasFeign()) { writeFeign(modelWriter, entity.getFeign()); } if (entity.hasTyping()) { writeTyping(modelWriter, entity.getTyping()); } if (entity.hasApi()) { writeApi(modelWriter, entity.getApi()); } return entity; } private void writeApi(ModelWriter modelWriter, Api api) { modelWriter.writeModel(api, false); } private void writeTyping(ModelWriter modelWriter, Typing typing) { modelWriter.writeModel(typing, true); } @SneakyThrows public void writeController(ModelWriter modelWriter, Controller controller) { modelWriter.writeModel(controller.getSourcePath(), controller.getType(), controller); } public void writeService(ModelWriter modelWriter, Service service) { modelWriter.writeModel(service.getSourcePath(), service.getType(), service); } public void writeRepository(ModelWriter modelWriter, Repository repository) { modelWriter.writeModel(repository.getSourcePath(), repository.getType(), repository); } public void writeMapper(ModelWriter modelWriter, Mapper mapper) { modelWriter.writeModel(mapper.getSourcePath(), mapper.getType(), mapper); } public void writeRequests(ModelWriter modelWriter, List<Request> requests) { requests.forEach(request -> { modelWriter.writeModel(request.getSourcePath(), request.getType(), request); }); } public void writeResponse(ModelWriter modelWriter, List<Response> responses) { responses.forEach(response -> { modelWriter.writeModel(response.getSourcePath(), response.getType(), response); }); } public void writeFeign(ModelWriter modelWriter, Feign feign) { modelWriter.writeModel(feign.getSourcePath(), feign.getType(), feign); } @Override public int getPriority() { return 0; } }
3,827
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
EntityCreateProcessor.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/processor/EntityCreateProcessor.java
package io.qifan.infrastructure.generator.processor.processor; import io.qifan.infrastructure.generator.core.*; import io.qifan.infrastructure.generator.processor.model.Entity; import io.qifan.infrastructure.generator.processor.model.common.Field; import io.qifan.infrastructure.generator.processor.model.controller.Controller; import io.qifan.infrastructure.generator.processor.model.dto.Request; import io.qifan.infrastructure.generator.processor.model.dto.Response; import io.qifan.infrastructure.generator.processor.model.feign.Feign; import io.qifan.infrastructure.generator.processor.model.front.Api; import io.qifan.infrastructure.generator.processor.model.front.Typing; import io.qifan.infrastructure.generator.processor.model.front.TypingField; import io.qifan.infrastructure.generator.processor.model.mapper.Mapper; import io.qifan.infrastructure.generator.processor.model.repository.Repository; import io.qifan.infrastructure.generator.processor.model.service.Service; import io.qifan.infrastructure.generator.processor.processor.front.mapping.*; import io.qifan.infrastructure.generator.processor.utils.FieldUtils; import io.qifan.infrastructure.generator.processor.utils.GenEntityUtils; import io.qifan.infrastructure.generator.processor.utils.TypeUtils; import org.springframework.util.StringUtils; import javax.lang.model.element.TypeElement; import java.util.List; public class EntityCreateProcessor implements ModelElementProcessor<Void, Entity> { private static final List<TypeMapping> typeMappings; static { typeMappings = List.of(new ArrayMapping(), new BooleanMapping(), new NumberMapping(), new StringMapping(), new ValidStatusMapping(), new ObjectMapping()); } private TypeElement typeElement; private GenEntityUtils genEntityUtils; @Override public Entity process(ProcessorContext processorContext, Void sourceModel) { typeElement = processorContext.getTypeElement(); genEntityUtils = new GenEntityUtils(typeElement.getAnnotation(GenEntity.class)); return Entity.builder() .type(TypeUtils.getType(typeElement)) .fields(FieldUtils.getFields(typeElement)) .requests(createRequest()) .responses(createResponse()) .mapper(createMapper()) .repository(createRepository()) .service(createService()) .controller(createController()) .feign(createFeign()) .typing(typing()) .api(api()) .build(); } private Service createService() { if (!genEntityUtils.hasService()) { return null; } GenService service = genEntityUtils.getService(); return Service.builder() .sourcePath(StringUtils.hasText( service.sourcePath()) ? service.sourcePath() : genEntityUtils.getSourcePath()) .type(TypeUtils.getType(typeElement, service.packageName(), service.suffix())) .entityType(TypeUtils.getType(typeElement)) .build(); } private Controller createController() { if (!genEntityUtils.hasController()) { return null; } GenController controller = genEntityUtils.getController(); return Controller.builder() .sourcePath(StringUtils.hasText( controller.sourcePath()) ? controller.sourcePath() : genEntityUtils.getSourcePath()) .type(TypeUtils.getType(typeElement, controller.packageName(), controller.suffix())) .entityType(TypeUtils.getType(typeElement)) .build(); } private Repository createRepository() { if (!genEntityUtils.hasRepository()) { return null; } GenRepository repository = genEntityUtils.getRepository(); return Repository.builder() .sourcePath(StringUtils.hasText( repository.sourcePath()) ? repository.sourcePath() : genEntityUtils.getSourcePath()) .type(TypeUtils.getType(typeElement, repository.packageName(), repository.suffix())) .entityType(TypeUtils.getType(typeElement)) .build(); } private Mapper createMapper() { if (!genEntityUtils.hasMapper()) { return null; } GenMapper mapper = genEntityUtils.getMapper(); return Mapper.builder() .sourcePath(StringUtils.hasText( mapper.sourcePath()) ? mapper.sourcePath() : genEntityUtils.getSourcePath()) .entityType(TypeUtils.getType(typeElement)) .type(TypeUtils.getType(typeElement, mapper.packageName(), mapper.suffix())) .build(); } private List<Response> createResponse() { List<GenResponse> responses = genEntityUtils.getResponses(); return responses.stream().map(response -> Response.builder() .sourcePath(StringUtils.hasText( response.sourcePath()) ? response.sourcePath() : genEntityUtils.getResponseSourcePath()) .type(TypeUtils.getType(typeElement, response.packageName(), response.suffix())) .entityType(TypeUtils.getType(typeElement)) .fields(FieldUtils.getFieldsForResponse(typeElement, response.ignoreFields(), response.packageName(), response.suffix())) .build()).toList(); } private List<Request> createRequest() { List<GenRequest> requests = genEntityUtils.getRequests(); return requests.stream().map(request -> Request.builder() .sourcePath(StringUtils.hasText( request.sourcePath()) ? request.sourcePath() : genEntityUtils.getRequestSourcePath()) .type(TypeUtils.getType(typeElement, request.packageName(), request.suffix())) .entityType(TypeUtils.getType(typeElement)) .fields(FieldUtils.getFieldsForRequest(typeElement, request.ignoreFields(), request.packageName(), request.suffix())) .build()).toList(); } private Feign createFeign() { GenFeign feign = genEntityUtils.getFeign(); if (!StringUtils.hasText(feign.moduleName())) return null; return Feign.builder() .sourcePath(StringUtils.hasText( feign.sourcePath()) ? feign.sourcePath() : genEntityUtils.getSourcePath()) .moduleName(feign.moduleName()) .type(TypeUtils.getType(typeElement, feign.packageName(), feign.suffix())) .entityType(TypeUtils.getType(typeElement)) .build(); } private Typing typing() { if (!genEntityUtils.hasTyping()) return null; List<Field> fields = FieldUtils.getFields(typeElement); List<TypingField> typingFields = fields.stream().map(field -> { for (TypeMapping typeMapping : typeMappings) { String convert = typeMapping.convert(field); if (convert != null) { // 字段名称+ts类型 return new TypingField(field.getFieldName(), convert); } } return null; }).toList(); return Typing.builder() .entityType(TypeUtils.getType(typeElement)) .typingFields(typingFields).build(); } private Api api() { if (!genEntityUtils.hasApi()) return null; return Api.builder().entityType(TypeUtils.getType(typeElement)).build(); } @Override public int getPriority() { return 1; } }
9,538
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
DefaultModelElementProcessorContext.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/processor/DefaultModelElementProcessorContext.java
package io.qifan.infrastructure.generator.processor.processor; import javax.annotation.processing.Filer; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.TypeElement; public class DefaultModelElementProcessorContext implements ModelElementProcessor.ProcessorContext { private final ProcessingEnvironment processingEnvironment; private final TypeElement typeElement; public DefaultModelElementProcessorContext(ProcessingEnvironment processingEnvironment, TypeElement typeElement) { this.processingEnvironment = processingEnvironment; this.typeElement = typeElement; } @Override public Filer getFiler() { return processingEnvironment.getFiler(); } @Override public TypeElement getTypeElement() { return typeElement; } }
836
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
NumberMapping.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/processor/front/mapping/NumberMapping.java
package io.qifan.infrastructure.generator.processor.processor.front.mapping; import io.qifan.infrastructure.generator.processor.model.common.Field; import lombok.SneakyThrows; import java.util.List; public class NumberMapping implements TypeMapping { @SneakyThrows @Override public String convert(Field field) { List<String> types = List.of("byte", "Byte", "short", "Short", "int", "Integer", "long", "Long", "float", "Float", "double", "Double", "BigDecimal", "BigInteger"); return types.contains(field.getType().getTypeName()) ? "number" : null; } }
697
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
TypeMapping.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/processor/front/mapping/TypeMapping.java
package io.qifan.infrastructure.generator.processor.processor.front.mapping; import io.qifan.infrastructure.generator.processor.model.common.Field; public interface TypeMapping { String convert(Field field); }
217
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
StringMapping.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/processor/front/mapping/StringMapping.java
package io.qifan.infrastructure.generator.processor.processor.front.mapping; import io.qifan.infrastructure.generator.processor.model.common.Field; import lombok.SneakyThrows; import java.util.List; public class StringMapping implements TypeMapping { @SneakyThrows @Override public String convert(Field field) { List<String> types = List.of("char", "Character", "String", "LocalDateTime", "Date", "UUID"); return types.contains(field.getType().getTypeName()) ? "string" : null; } }
555
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
ObjectMapping.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/processor/front/mapping/ObjectMapping.java
package io.qifan.infrastructure.generator.processor.processor.front.mapping; import io.qifan.infrastructure.generator.processor.model.common.Field; public class ObjectMapping implements TypeMapping { @Override public String convert(Field field) { return field.getType().getTypeName(); } }
312
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
ValidStatusMapping.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/processor/front/mapping/ValidStatusMapping.java
package io.qifan.infrastructure.generator.processor.processor.front.mapping; import io.qifan.infrastructure.generator.processor.model.common.Field; public class ValidStatusMapping implements TypeMapping { @Override public String convert(Field field) { if (!field.getType().getTypeName().equals("ValidStatus")) return null; return "'VALID' | 'INVALID'"; } }
388
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
BooleanMapping.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/processor/front/mapping/BooleanMapping.java
package io.qifan.infrastructure.generator.processor.processor.front.mapping; import io.qifan.infrastructure.generator.processor.model.common.Field; import lombok.SneakyThrows; import java.util.List; public class BooleanMapping implements TypeMapping { @SneakyThrows @Override public String convert(Field field) { List<String> types = List.of("boolean", "Boolean"); return types.contains(field.getType().getTypeName()) ? "boolean" : null; } }
477
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
ArrayMapping.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/processor/front/mapping/ArrayMapping.java
package io.qifan.infrastructure.generator.processor.processor.front.mapping; import io.qifan.infrastructure.generator.processor.model.common.Field; import io.qifan.infrastructure.generator.processor.model.common.ParameterType; import lombok.SneakyThrows; import java.util.List; public class ArrayMapping implements TypeMapping { @SneakyThrows @Override public String convert(Field field) { List<String> types = List.of( "Set", "List", "Map", "SortedSet", "SortedMap", "HashSet", "TreeSet", "ArrayList", "LinkedList", "Vector", "Collections", "Arrays", "AbstractCollection"); boolean anyMatch = types.stream().anyMatch(type -> field.getType().getTypeName().contains(type)); if (!anyMatch) return null; if (field.getType() instanceof ParameterType type) { ParameterType parameterType = type; return parameterType.getParameterType().getCurrentTypeName() + "[]"; } return "any[]"; } }
1,181
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
Entity.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/model/Entity.java
package io.qifan.infrastructure.generator.processor.model; import io.qifan.infrastructure.generator.processor.model.common.Field; import io.qifan.infrastructure.generator.processor.model.common.ModelElement; import io.qifan.infrastructure.generator.processor.model.common.Type; import io.qifan.infrastructure.generator.processor.model.controller.Controller; import io.qifan.infrastructure.generator.processor.model.dto.Request; import io.qifan.infrastructure.generator.processor.model.dto.Response; import io.qifan.infrastructure.generator.processor.model.feign.Feign; import io.qifan.infrastructure.generator.processor.model.front.Api; import io.qifan.infrastructure.generator.processor.model.front.Typing; import io.qifan.infrastructure.generator.processor.model.mapper.Mapper; import io.qifan.infrastructure.generator.processor.model.repository.Repository; import io.qifan.infrastructure.generator.processor.model.service.Service; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import org.springframework.util.CollectionUtils; import java.util.List; import java.util.Set; @EqualsAndHashCode(callSuper = true) @Data @Builder public class Entity extends ModelElement { private Type type; private List<Field> fields; private Controller controller; private List<Request> requests; private List<Response> responses; private Mapper mapper; private Repository repository; private Service service; private Feign feign; private Typing typing; private Api api; public boolean hasApi() { return api != null; } public boolean hasTyping() { return typing != null; } public boolean hasService() { return service != null; } public boolean hasRepository() { return repository != null; } public boolean hasRequests() { return !CollectionUtils.isEmpty(requests); } public boolean hasResponse() { return !CollectionUtils.isEmpty(responses); } public boolean hasController() { return controller != null; } public boolean hasMapper() { return mapper != null; } public boolean hasFeign() { return feign != null; } @Override public Set<Type> getImportTypes() { return null; } }
2,309
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
Mapper.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/model/mapper/Mapper.java
package io.qifan.infrastructure.generator.processor.model.mapper; import io.qifan.infrastructure.generator.processor.model.common.ModelElement; import io.qifan.infrastructure.generator.processor.model.common.Type; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.Set; @EqualsAndHashCode(callSuper = true) @Data @Builder public class Mapper extends ModelElement { private String sourcePath; private Type type; private Type entityType; @Override public Set<Type> getImportTypes() { return Set.of(entityType); } }
593
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
Feign.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/model/feign/Feign.java
package io.qifan.infrastructure.generator.processor.model.feign; import io.qifan.infrastructure.generator.processor.model.common.ModelElement; import io.qifan.infrastructure.generator.processor.model.common.Type; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.Set; @EqualsAndHashCode(callSuper = true) @Data @Builder public class Feign extends ModelElement { private String moduleName; private String sourcePath; private Type type; private Type entityType; @Override public Set<Type> getImportTypes() { return Set.of(entityType); } }
621
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
Response.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/model/dto/Response.java
package io.qifan.infrastructure.generator.processor.model.dto; import io.qifan.infrastructure.generator.processor.model.common.Field; import io.qifan.infrastructure.generator.processor.model.common.ModelElement; import io.qifan.infrastructure.generator.processor.model.common.Type; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.HashSet; import java.util.List; import java.util.Set; @EqualsAndHashCode(callSuper = true) @Data @Builder public class Response extends ModelElement { private String sourcePath; private Type type; private Type entityType; private List<Field> fields; @Override public Set<Type> getImportTypes() { HashSet<Type> types = new HashSet<>(); fields.forEach(field -> { types.addAll(field.getImportTypes()); }); // types.add(entityType); return types; } }
906
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
Request.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/model/dto/Request.java
package io.qifan.infrastructure.generator.processor.model.dto; import io.qifan.infrastructure.generator.processor.model.common.Field; import io.qifan.infrastructure.generator.processor.model.common.ModelElement; import io.qifan.infrastructure.generator.processor.model.common.Type; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.HashSet; import java.util.List; import java.util.Set; @EqualsAndHashCode(callSuper = true) @Data @Builder public class Request extends ModelElement { private String sourcePath; private Type type; private Type entityType; private List<Field> fields; @Override public Set<Type> getImportTypes() { HashSet<Type> types = new HashSet<>(); fields.forEach(field -> { types.addAll(field.getImportTypes()); }); // types.add(entityType); return types; } }
938
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
ModelElement.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/model/common/ModelElement.java
package io.qifan.infrastructure.generator.processor.model.common; import io.qifan.infrastructure.generator.processor.writer.FreeMarkerWritable; import java.util.Set; public abstract class ModelElement extends FreeMarkerWritable { public abstract Set<Type> getImportTypes(); }
284
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
Field.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/model/common/Field.java
package io.qifan.infrastructure.generator.processor.model.common; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.Set; @EqualsAndHashCode(callSuper = true) @Data @Builder public class Field extends ModelElement { private Type type; private String fieldName; private String description; @Override public Set<Type> getImportTypes() { return type.getImportTypes(); } }
447
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
ParameterType.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/model/common/ParameterType.java
package io.qifan.infrastructure.generator.processor.model.common; import lombok.Getter; import lombok.Setter; import java.util.HashSet; import java.util.Set; @Getter @Setter public class ParameterType extends Type { private ParameterType parameterType; public ParameterType(Type type, ParameterType parameterType) { super(type.getTypeName(), type.getPackagePath()); this.parameterType = parameterType; } public String getCurrentTypeName() { return typeName; } @Override public String getTypeName() { String typeName = super.typeName; if (parameterType != null) { typeName = typeName + "<" + parameterType.getTypeName() + ">"; } return typeName; } @Override public Set<Type> getImportTypes() { HashSet<Type> types = new HashSet<>(super.getImportTypes()); if (parameterType != null) { types.addAll(parameterType.getImportTypes()); } return types; } }
1,012
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
Parameter.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/model/common/Parameter.java
package io.qifan.infrastructure.generator.processor.model.common; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.Set; @EqualsAndHashCode(callSuper = true) @Data @Builder public class Parameter extends ModelElement { private Type type; private String variableName; @Override public Set<Type> getImportTypes() { return Set.of(type); } }
413
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
Type.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/model/common/Type.java
package io.qifan.infrastructure.generator.processor.model.common; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import org.springframework.util.StringUtils; import java.util.Set; @EqualsAndHashCode(callSuper = true) @Data @Builder public class Type extends ModelElement { protected String typeName; protected String packagePath; public String getTypePath() { return packagePath + "." + typeName; } public String getPackageDir() { return packagePath.replace(".", "/"); } public String getFileName() { return typeName + ".java"; } public String getUncapitalizeTypeName() { return StringUtils.uncapitalize(typeName); } @Override public Set<Type> getImportTypes() { return Set.of(this); } }
817
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
Repository.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/model/repository/Repository.java
package io.qifan.infrastructure.generator.processor.model.repository; import io.qifan.infrastructure.generator.processor.model.common.ModelElement; import io.qifan.infrastructure.generator.processor.model.common.Type; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.Set; @EqualsAndHashCode(callSuper = true) @Data @Builder public class Repository extends ModelElement { private String sourcePath; private Type type; private Type entityType; @Override public Set<Type> getImportTypes() { return Set.of(entityType); } }
600
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
Controller.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/model/controller/Controller.java
package io.qifan.infrastructure.generator.processor.model.controller; import io.qifan.infrastructure.generator.processor.model.common.ModelElement; import io.qifan.infrastructure.generator.processor.model.common.Type; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.Set; @EqualsAndHashCode(callSuper = true) @Data @Builder public class Controller extends ModelElement { private String sourcePath; private Type type; private Type entityType; @Override public Set<Type> getImportTypes() { return Set.of(entityType); } }
602
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
Service.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/model/service/Service.java
package io.qifan.infrastructure.generator.processor.model.service; import io.qifan.infrastructure.generator.processor.model.common.ModelElement; import io.qifan.infrastructure.generator.processor.model.common.Type; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.Set; @EqualsAndHashCode(callSuper = true) @Data @Builder public class Service extends ModelElement { private String sourcePath; private Type type; private Type entityType; @Override public Set<Type> getImportTypes() { return Set.of(entityType); } }
594
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
Api.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/model/front/Api.java
package io.qifan.infrastructure.generator.processor.model.front; import io.qifan.infrastructure.generator.processor.model.common.Type; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import org.springframework.util.StringUtils; import java.util.Set; @EqualsAndHashCode(callSuper = true) @Data @Builder public class Api extends FrontModel { private Type entityType; @Override public Set<Type> getImportTypes() { return null; } @Override public String getFileName() { String[] split = entityType.getTypeName() .split("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])"); String joinString = StringUtils.arrayToDelimitedString(split, "-"); return joinString.toLowerCase() + ".ts"; } }
805
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
Typing.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/model/front/Typing.java
package io.qifan.infrastructure.generator.processor.model.front; import io.qifan.infrastructure.generator.processor.model.common.Type; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.HashSet; import java.util.List; import java.util.Set; @EqualsAndHashCode(callSuper = true) @Data @Builder public class Typing extends FrontModel { private Type entityType; private List<TypingField> typingFields; @Override public Set<Type> getImportTypes() { return new HashSet<>(); } @Override public String getFileName() { return "index.d.ts"; } }
630
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
FrontModel.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/model/front/FrontModel.java
package io.qifan.infrastructure.generator.processor.model.front; import io.qifan.infrastructure.generator.processor.model.common.ModelElement; public abstract class FrontModel extends ModelElement { public abstract String getFileName(); }
246
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
TypingField.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-generator/generator-processor/src/main/java/io/qifan/infrastructure/generator/processor/model/front/TypingField.java
package io.qifan.infrastructure.generator.processor.model.front; public record TypingField(String fieldName, String typeName) { }
132
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
SecurityProperties.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-security/src/main/java/io/qifan/chatgpt/infrastructure/security/SecurityProperties.java
package io.qifan.chatgpt.infrastructure.security; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "security") @Data public class SecurityProperties { private Boolean enabled = true; }
272
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z
AuthAutoConfiguration.java
/FileExtraction/Java_unseen/qifan777_chatgpt-assistant/infrastructure/infrastructure-security/src/main/java/io/qifan/chatgpt/infrastructure/security/AuthAutoConfiguration.java
package io.qifan.chatgpt.infrastructure.security; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Configuration @ConditionalOnProperty(prefix = "security", name = "enabled", havingValue = "true") public class AuthAutoConfiguration { @Configuration @Import(WebConfig.class) public static class SecurityConfig { } }
480
Java
.java
qifan777/chatgpt-assistant
39
8
0
2023-05-31T05:33:12Z
2024-03-19T14:14:35Z