Methods of second class on DBus not callable - dbus

I created Dbus service with Vala language. It creates interface to add devices with different paths. Device must scan dir and bind methods on subpath.
Then i call su.example.Phone.AddBySyspath(/sys/bus/usb/devices/2-2.4), it returns "/su/example/phone/2_2d4" as expected. But calling Reset on this path causes "Unable to find method Reset on path /su/example/phone/2_2d4 in interface su.example.Phone".
I have code:
using Gee;
[DBus (name = "su.example.Phone")]
public class Phone : Object {
Regex ttyregex;
string path;
string manufacturer;
public Phone(string path){
this.path = path;
this.ttyregex = new Regex ("tty[A-Z0-9]+");
this.manufacturer = "Unknown";
load();
}
private async void load(){
string[3] ttys = {"", "", ""};
var dir = File.new_for_path (path);
stderr.printf ("path %s\n", path);
FindTTY(dir,0,ttys);
stdout.printf ("done\n");
}
private void FindTTY(File dir, int sub, string[] ttys){
sub++;
FileEnumerator enumerator = dir.enumerate_children(
"standard::*",
FileQueryInfoFlags.NONE
);
FileInfo info = null;
while
((info = enumerator.next_file ()) != null)
{
var name = info.get_name ();
if (name == "manufacturer") {
File f = dir.resolve_relative_path (info.get_name ());
var dis = new DataInputStream (f.read ());
manufacturer = dis.read_line (null);
}
stdout.printf ("%s\n", info.get_name ());
stdout.printf ("%d\n", info.get_file_type ());
}
}
public string reset() throws Error {
stdout.printf ("ATZ\n");
return "OK";
}
}
[DBus (name = "su.example.Phone")]
public class PhoneServer : Object {
Regex dotregex;
Regex nonalpharegex;
private DBusConnection conn;
private HashMap<string, Phone> map;
public PhoneServer(DBusConnection conn) {
this.conn = conn;
this.map = new HashMap<string, Phone> ();
this.dotregex = new Regex ("[.]+");
this.nonalpharegex = new Regex ("\\W+");
}
public string add_by_syspath(string path, GLib.BusName sender) throws Error {
// path = /sys/bus/usb/devices/2-2.4
var pathv = path.split("/");
string name = pathv[pathv.length-1];
name = dotregex.replace(name,name.length,0, "d");
name = nonalpharegex.replace(name,name.length,0, "_");
stderr.printf ("name %s\n", name);
var buspath = "/su/example/phone/%s".printf(name);
if (map.has_key(name)) {
} else {
var phone = new Phone (path);
map.set(name,phone);
try {
conn.register_object ("/su/example/phone/%s".printf(name), phone);
} catch (IOError e) {
stderr.printf ("Could not register service\n");
}
}
return buspath;
}
}
[DBus (name = "su.example.PhoneError")]
public errordomain PhoneError
{
SOME_ERROR
}
void on_bus_aquired (DBusConnection conn) {
try {
conn.register_object ("/su/example/phone", new PhoneServer (conn));
} catch (IOError e) {
stderr.printf ("Could not register service\n");
}
}
void main (string[] args) {
Bus.own_name (BusType.SYSTEM, "su.example.Phone", BusNameOwnerFlags.NONE,
on_bus_aquired,
() => {},
() => stderr.printf ("Could not aquire name\n"));
new MainLoop ().run ();
}

While writing question i solved this.
I need to use different DBus names for handler classes:
[DBus (name = "su.eerie.PhoneManager.Phone")]
public class Phone : Object {
...
[DBus (name = "su.eerie.PhoneManager")]
public class PhoneServer : Object {
...

Related

Codename one FacebookConnect

I'm currently trying out Codename One for a cross-platform mobile app development and the app requires a social login. I am trying to introduce facebook login but it doesn't work. What may I be doing wrong?
Below is my code which throughs an error:
public class MyApplication {
private Form current;
private Resources theme;
private String tokenPrefix;
private String fullName;
private String uniqueId;
private String imageURL;
private static EncodedImage userPlaceholder;
private EncodedImage roundPlaceholder;
public void start() {
if (current != null) {
current.show();
return;
}
Form facebook = new Form(new BorderLayout(BorderLayout.CENTER_BEHAVIOR_CENTER));
facebook.getTitleArea().setUIID("Container");
Button connect = new Button("Login with facebook");
Container c = BoxLayout.encloseY(connect);
facebook.add(BorderLayout.CENTER, c);
connect.addActionListener((evt) -> {
/* tokenPrefix = "facebook";
Login fb = FacebookConnect.getInstance();
fb.setClientId("XXXXXXXXXXXXXXXXX");
fb.setRedirectURI("http://localhost/callback");
fb.setClientSecret("xxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
doLogin(fb, new FacebookData(), false); */
String clientId = "XXXXXXXXXXXXXXXXX";
String redirectURI = "http://www.codenameone.com/";
String clientSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
Login fb = FacebookConnect.getInstance();
fb.setClientId(clientId);
fb.setRedirectURI(redirectURI);
fb.setClientSecret(clientSecret);
Log.p("login event triggered");
doLogin(fb, new FacebookData(), false);
/* if(!fb.isUserLoggedIn()){
doLogin(fb, new FacebookData(),false);
}else{
//get the token and now you can query the facebook API
String token = fb.getAccessToken().getToken();
} */
});
facebook.show();
}
void doLogin(Login lg, UserData data, boolean forceLogin) {
if (!forceLogin) {
if (lg.isUserLoggedIn()) {
Log.p("Fetching data......");
showContactsForm();
return;
}
String t = Preferences.get(tokenPrefix + "token", (String) null);
if (t != null) {
long tokenExpires = Preferences.get(tokenPrefix + "tokenExpires", (long) -1);
if (tokenExpires < 0 || tokenExpires > System.currentTimeMillis()) {
//we are still logged in
Log.p("Fetching data......");
showContactsForm();
return;
}
}
}
lg.setCallback(new LoginCallback() {
public void loginFailed(String errorMessage) {
Log.p("Error occured");
Dialog.show("Error Logging in", "There was an error logging in:" + errorMessage, "OK", null);
}
public void loginSuccessful() {
Log.p("doLogin started");
// when login is successful we fetch the full data
data.fetchData(lg.getAccessToken().getToken(), () -> {
// we store the values of result into local variables
String uniqueId = data.getId();
String fullName = data.getName();
String imageURL = data.getImage();
// we then store the data into local cached storage so they will be around when we run the app next time
Preferences.set("fullName", fullName);
Preferences.set("uniqueId", uniqueId);
Preferences.set("imageURL", imageURL);
Preferences.set(tokenPrefix + "token", lg.getAccessToken().getToken());
// token expiration is in seconds from the current time, we convert it to a System.currentTimeMillis value so we can
// reference it in the future to check expiration
Preferences.set(tokenPrefix + "tokenExpires", tokenExpirationInMillis(lg.getAccessToken()));
showContactsForm();
Log.p("information fetched" + fullName + "_" + uniqueId + "_");
});
}
});
lg.doLogin();
}
long tokenExpirationInMillis(AccessToken token) {
String expires = token.getExpires();
if (expires != null && expires.length() > 0) {
try {
// when it will expire in seconds
long l = (long) (Float.parseFloat(expires) * 1000);
return System.currentTimeMillis() + l;
} catch (NumberFormatException err) {
// ignore invalid input
}
}
return -1;
}
static interface UserData {
public String getName();
public String getId();
public String getImage();
public void fetchData(String token, Runnable callback);
// public ContactData[] getContacts();
}
class FacebookData implements UserData {
String name;
String id;
String token;
#Override
public String getName() {
return name;
}
#Override
public String getId() {
return id;
}
#Override
public String getImage() {
return "http://graph.facebook.com/v2.8/" + id + "/picture";
}
#Override
public void fetchData(String token, Runnable callback) {
this.token = token;
ConnectionRequest req = new ConnectionRequest() {
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser parser = new JSONParser();
Map<String, Object> parsed = parser.parseJSON(new InputStreamReader(input, "UTF-8"));
name = (String) parsed.get("name");
id = (String) parsed.get("id");
}
#Override
protected void postResponse() {
callback.run();
}
#Override
protected void handleErrorResponseCode(int code, String message) {
//access token not valid anymore
if (code >= 400 && code <= 410) {
Log.p("error occured");
doLogin(FacebookConnect.getInstance(), FacebookData.this, true);
return;
}
super.handleErrorResponseCode(code, message);
}
};
req.setPost(false);
req.setUrl("https://graph.facebook.com/v2.8/me");
req.addArgumentNoEncoding("access_token", token);
NetworkManager.getInstance().addToQueue(req);
}
}
void showContactsForm() {
Form result = new Form(new BorderLayout(BorderLayout.CENTER_BEHAVIOR_CENTER_ABSOLUTE));
Label fname = new Label("Hello");
Label id = new Label("Facebook");
Container c = BoxLayout.encloseY(fname, id);
fname.setText(Preferences.get("fullName", fullName));
id.setText(Preferences.get("uniqueId", uniqueId));
result.add(BorderLayout.CENTER, c);
result.show();
}
}
Firstly, make sure your Facebook login is setup properly on Facebook Developers Console.
Here is how you get all information you need:
Take note of this line req.addArgumentNoEncoding("fields", "id,email,name,first_name,last_name,gender,age_range,picture.width(512).height(512),locale,link,timezone,updated_time");, That's where we tell Facebook what informations we need
I used Dialog to check output in processFacebookLogin() for debugging purpose instead of showContact()
void doLogin(Login lg, UserData data, boolean forceLogin) {
if (!forceLogin) {
if (lg.isUserLoggedIn()) {
processFacebookLogin(data);
return;
}
// if the user already logged in previously and we have a token
String token = Preferences.get(tokenPrefix + "token", (String) null);
if (getToolbar() != null) {
// we check the expiration of the token which we previously stored as System time
long tokenExpires = Preferences.get(tokenPrefix + "tokenExpires", (long) -1);
if (tokenExpires < 0 || tokenExpires > System.currentTimeMillis()) {
data.fetchData(token, () -> {
processFacebookLogin(data);
});
return;
}
}
}
lg.setCallback(new LoginCallback() {
#Override
public void loginFailed(String errorMessage) {
Dialog.show("Error Logging In", "There was an error logging in with Facebook: " + errorMessage, "Ok", null);
}
#Override
public void loginSuccessful() {
data.fetchData(lg.getAccessToken().getToken(), () -> {
Preferences.set(tokenPrefix + "token", lg.getAccessToken().getToken());
Preferences.set(tokenPrefix + "tokenExpires", tokenExpirationInMillis(lg.getAccessToken()));
processFacebookLogin(data);
});
}
});
lg.doLogin();
}
long tokenExpirationInMillis(AccessToken token) {
String expires = token.getExpires();
if (expires != null && expires.length() > 0) {
try {
// when it will expire in seconds
long l = (long) (Float.parseFloat(expires) * 1000);
return System.currentTimeMillis() + l;
} catch (NumberFormatException err) {
// ignore invalid input
}
}
return -1;
}
class FacebookData implements UserData {
String id;
String email;
String name;
String first_name;
String last_name;
String image;
String link;
String gender;
String locale;
Double timezone;
String updated_time;
String verified;
#Override
public String getId() {
return id;
}
#Override
public String getEmail() {
return email;
}
#Override
public String getFullName() {
return name;
}
#Override
public String getFirstName() {
return first_name;
}
#Override
public String getLastName() {
return last_name;
}
#Override
public String getGender() {
return gender;
}
#Override
public String getLink() {
return link;
}
#Override
public String getLocale() {
return locale;
}
#Override
public Double getTimezone() {
return timezone;
}
#Override
public String getUpdatedTime() {
return updated_time;
}
#Override
public String getImage() {
return image;
}
#Override
public void fetchData(String token, Runnable callback) {
ConnectionRequest req = new ConnectionRequest() {
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser parser = new JSONParser();
Map<String, Object> parsed = parser.parseJSON(new InputStreamReader(input, "UTF-8"));
id = (String) parsed.get("id");
email = (String) parsed.get("email");
name = (String) parsed.get("name");
first_name = (String) parsed.get("first_name");
last_name = (String) parsed.get("last_name");
link = (String) parsed.get("link");
gender = (String) parsed.get("gender");
locale = (String) parsed.get("locale");
timezone = (Double) parsed.get("timezone");
updated_time = (String) parsed.get("updated_time;");
verified = (String) parsed.get("verified");
image = (String) ((Map) ((Map) parsed.get("picture")).get("data")).get("url").toString();
}
#Override
protected void postResponse() {
callback.run();
}
#Override
protected void handleErrorResponseCode(int code, String message) {
//access token not valid anymore
if (code >= 400 && code <= 410) {
doLogin(FacebookConnect.getInstance(), FacebookData.this, true);
return;
}
super.handleErrorResponseCode(code, message);
}
};
req.setPost(false);
req.setUrl("https://graph.facebook.com/v2.8/me");
req.addArgumentNoEncoding("access_token", token);
req.addArgumentNoEncoding("fields", "id,email,name,first_name,last_name,gender,age_range,picture.width(512).height(512),locale,link,timezone,updated_time");
NetworkManager.getInstance().addToQueue(req);
}
}

.net c# WebChannelFactory keepAliveEnabled=false with webHttpBehavior

I create WebChannelFactory. I need set KeepAlive=false.
I found only one solution use CustomBinding. and set property keepAliveEnabled to false.
I use custom behavior for my factory also.
Code:
static CustomBinding GetBinding(MySettings serviceSettings = null)
{
var customBinding = new CustomBinding();
HttpTransportBindingElement transportBindingElement = new HttpTransportBindingElement();
transportBindingElement.KeepAliveEnabled = false;
transportBindingElement.MaxBufferSize = 0x07000000;
transportBindingElement.MaxReceivedMessageSize = 0x07000000;
if (serviceSettings != null)
{
customBinding.SendTimeout = serviceSettings.SendTimeout;
}
customBinding.Elements.Add(transportBindingElement);
return customBinding;
}
var customBinding = GetBinding(serviceSettings);
WebChannelFactory<TChannel> factory = new WebChannelFactory<TChannel>(customBinding, new Uri(url));
factory.Endpoint.Behaviors.Add(new MyWebHttpBehavior(userId));
class MyWebHttpBehavior : IEndpointBehavior
{
private int _userId;
public MyWebHttpBehavior(int userId)
{
_userId = userId;
}
public void AddBindingParameters(ServiceEndpoint serviceEndpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{ }
public void ApplyClientBehavior(ServiceEndpoint serviceEndpoint, System.ServiceModel.Dispatcher.ClientRuntime behavior)
{
behavior.MessageInspectors.Add(new MyClientMessageInspector(_userId));
}
public void ApplyDispatchBehavior(ServiceEndpoint serviceEndpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
{ }
public void Validate(ServiceEndpoint serviceEndpoint)
{ }
}
In current situation i get error "does not have a Binding with the None MessageVersion".

how to check if file exist in a folder on ftp in c#

i want to check if some files exists in a folder on ftp then do specific task
i have the following methos for files check
public static bool CheckFileExistOnFTP(string ServerUri, string FTPUserName, string FTPPassword)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ServerUri);
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential(FTPUserName, FTPPassword);
//request.Method = WebRequestMethods.Ftp.GetFileSize;
// request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
try
{
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
return true;
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
return false;
}
}
return true;
}
and i call that method on formload
if (FTPUtility.CheckFileExistOnFTP("ftp://ip address/Requests/", "edexcrawler", "edexcrawler123"))
{
btnUploadRequest.Visible = true;
btnUploadRequest.BackColor = System.Drawing.Color.LightGreen;
btnUploadRequest.ForeColor = System.Drawing.Color.Blue;
}
Based on your other question to get a list of files from ftp, you can check if the file you want to check is in that list:
Var fileNameToCkeck = "myfile.txt";
var utility= new FtpUtility();
utility.UserName = "...";
utility.Password = "...";
utility.Path = "...";
If (utility.ListFiles().Contains(fileNameToCkeck))
{
//The file exists
}
Or if you want to know if that path has any file:
If (utility.ListFiles().Count() > 0)
{
//The folder contains files
}
And here is the code for FtpUtility
public class FtpUtility
{
public string UserName { get; set; }
public string Password { get; set; }
public string Path { get; set; }
public List<string> ListFiles()
{
var request = (FtpWebRequest)WebRequest.Create(Path);
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential(UserName, Password);
List<string> files = new List<string>();
using (var response = (FtpWebResponse)request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (string.IsNullOrWhiteSpace(line) == false)
{
var fileName = line.Split(new[] { ' ', '\t' }).Last();
if (!fileName.StartsWith("."))
files.Add(fileName);
}
}
return files;
}
}
}
}

Enum switch in Java

I have this Java class where I am writing the code for applying the overrides. I want to know if using ENUM is appropriate or if I need to use the switch case, how can I use it? Also, I have the for loop that I need to use as a common block of code for each override type. Apart from that, I do have few separate fields that I need to code for each override type.
public class EWFMService
{
private WorkbrainSystemAccessService wsa = new WorkbrainSystemAccessService();
private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(EWFMService.class);
private final static String ovrCalcGrp = "ovrCalcGrp";
private DBConnection conn = null;
private int empId;
private Date ovrDate;
private String ovrTime;
private String ovrAction;
public List<EWFMServiceData> getProcessEWFMOverrides(String userName, String password, List<EWFMServiceInputData> inputData)
throws WSApplicationException{
logger.debug("EWFM Service");
wsa.logOn(userName, password);
List<EWFMServiceData> returnList = new ArrayList<EWFMServiceData> ();
logger.debug("userName = " + userName);
DBConnection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
conn = new DBConnection(ConnectionManager.getConnection());
for (int i = 0; i < inputData.size(); i++)
{
Here I want to retrieve the emp_id from the database, store the value in a variable and be able to use the variable in the rest of my program. How do I do it? To retrieve the emp_id, I am using the following query.
conn = new DBConnection(ConnectionManager.getConnection());
String sql = "SELECT EMP_ID FROM EMPLOYEE_HISTORY"
+ " WHERE EMP_VAL2 = **This is where I want to use the variable in which the values of emp_id will be stored. There can be more than 100 emp_ids**"
+ " AND SYSDATE BETWEEN EMPHIST_START_DATE AND EMPHIST_END_DATE";
EWFMServiceInputData inData = (EWFMServiceInputData) inputData.get(i);
OverrideType ot = OverrideType.getOverrideType(inData.getRecordType());
logger.debug("override type = " + ot.toString());
logger.debug("inputData ["+i+"] = " + inData.toString());
OverrideAccess oa = new OverrideAccess(conn);
OverrideData ovr = new OverrideData();
ovr.setOvrUdf4(inData.getReferenceId().toString());
if (ovrAction.equals("APPLY")) {
ovr.setOvrStatus(OverrideData.PENDING);
Here I want to determine the Action. If it is Apply, then I need to find out the recordType. So basically branch it out for each recordType using if else statements or enum as I believe switch doesn't support Java 1.5 which is what I am using. Then for each recordType, I branch out and write the appropriate code corresponding to that recordType. If Action is CANCEL, then I just write the following code.
} else if (ovrAction.equals("CANCEL")) {
String sql = "SELECT * FROM OVERRIDE"
+ " WHERE OVR_UDF4 = ?"
+ " AND OVRTYP_ID = ?";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()); {
ovr.assignByName(rs);
ovr.setUpdated(false);
ovr.setRetrieved(true);
ovr.setOvrStatus(OverrideData.CANCEL);
oa.save(ovr);
}
}
ovr.setEmpId(empId);
String strOvrDate = inData.getOvrStartDate();
ovr.setOvrStartDate(DateHelper.parseDate(strOvrDate, "MM/dd/yyyy"));
if (ovrStartTime != null) {
ovr.setOvrStartTime(ovrTime);
}
Object ovrEndDate;
if (ovrEndDate != null) {
ovr.setOvrEndDate(ovrDate);
}
Object ovrEndTime;
if (ovrEndTime!= null) {
ovr.setOvrEndTime(ovrTime);
}
ovr.setOvrComment(inData.getOvrComments());
ovr.setWbuName(inData.getWbuName());
ovr.setWbuNameActual(inData.getWbuNameActual());
ovr.setOvrNewValue("VAC");
ovr.setOvrCreateDate(new Date());
ovr.setOvrtypId(103);
oa.insert(ovr);
RuleEngine.runCalcGroup(conn,
empId,
ovrDate,
ovrDate);
//COMMON BLOCK ENDS HERE
EWFMServiceData outData = new EWFMServiceData();
outData.setReferenceId(inData.getReferenceId());
String [] status = {"SUCCESS", "ERROR", "LOCKED", "EXCEPTION"};
Random ran = new Random();
String gen = status[ran.nextInt(status.length)];
logger.debug("Status is" + status );
outData.setStatus(gen);
if (gen.equals("SUCCESS")){
outData.setErrorDetails("");
} else if (gen.equals("ERROR")) {
outData.setErrorDetails("Usage of time code VAC is not allowed; balance is insufficient." + " error");
} else if (gen.equals("LOCKED")) {
outData.setErrorDetails("Timesheet cannot be edited because it is locked for payroll close." + "locked");
} else if (gen.equals("EXCEPTION")) {
outData.setErrorDetails("{ML}QR_INCORRECT_CONDITION_PARAMETER{/ML}Error in condition AWA Is Self Override Condition: java.lang.NullPointerException{ARGS}AWA Is Self Override Conditionjava.lang.NullPointerException{/ARGS" + "exception");
}
returnList.add(outData);
}
}catch (Exception e){
logger.error("Error occured",e);
throw new WSApplicationException("Error retrieved",e);
}finally{
SQLUtil.cleanUp(conn, ps, rs);
}
wsa.logOff();
logger.debug("inputData+ ");
return returnList;
}
// I need to know if writing enum is okay or can I just write a switch case above in the for loop and branch each override type and declare their individual variables there? What's the best way? Can someone help me with the code?
public enum OverrideType {
WORKDETAIL,
WORKPREMIUM,
EMPLOYEESCHEDULE,
EMPLOYEE;
public static OverrideType getOverrideType(String recordType) {
if(recordType == null) {
throw new IllegalArgumentException("Record Type cannot be null");
}
if(recordType.equals("Work Detail")) {
return WORKDETAIL;
} else if (recordType.equals("Work Premium")) {
return WORKPREMIUM;
} else if (recordType.equals("Schedule")) {
return EMPLOYEESCHEDULE;
} else if (recordType.equals("Shift Pattern")) {
return EMPLOYEE;
} else {
throw new IllegalArgumentException("Record Type cannot be" + recordType);
}
}
}
}
THE OTHER FIELDS I NEED TO INCLUDE ARE AS FOLLOWS:
FOR WORKDETAIL, I NEED TO USE TIMECODE OF FORMAT THAT IS SENT BY THE CLIENT.
FOR WORK PREMIUM, I NEED TO USE TIMECODE OF FORMAT THAT IS SENT BY THE CLIENT AND ANOTHER FIELD IS MINUTES THAT GIVES THE NUMBER OF MINUTES WHICH IS ALSO SENT BY THE CLIENT.
Generally, using enums is appropriate, especially if you have a defined set of possible types.
You can also add behavior to the enums, which could make your enum a little bit more sophisticated:
public enum OverrideType {
WORKDETAIL("Work Detail"),
WORKPREMIUM("Work Premium"),
EMPLOYEESCHEDULE("Schedule"),
EMPLOYEE("Shift Pattern");
private String identifier;
private OverrideType(String identifier){
this.identifier = identifier;
}
public static OverrideType getOverrideType(String recordType) {
if(recordType == null) {
throw new IllegalArgumentException("Record Type cannot be null");
}
for (OverrideType ot : OverrideType.values()) {
if (recordType.equals(ot.identifier)) {
return ot;
}
}
return null;
}
}
The following example shows how to use an interface in enums or an abstract method definition:
public enum OverrideType implements OverrideTypeIF {
WORKDETAIL("Work Detail") {
public int getKey() {
return 0;
}
},
WORKPREMIUM("Work Premium") {
public int getKey() {
return 0;
}
},
EMPLOYEESCHEDULE("Schedule") {
public int getKey() {
return 0;
}
},
EMPLOYEE("Shift Pattern") {
public int getKey() {
return 0;
}
public void myInterfaceMethod() {
// do type specific behavior
}
};
private String identifier;
private OverrideType(String identifier){
this.identifier = identifier;
}
public abstract int getKey();
public void myInterfaceMethod() {
// do default behavior
}
public static OverrideType getOverrideType(String recordType) {
if(recordType == null) {
throw new IllegalArgumentException("Record Type cannot be null");
}
for (OverrideType ot : OverrideType.values()) {
if (recordType.equals(ot.identifier)) {
return ot;
}
}
return null;
}
}
public interface OverrideTypeIF {
void myInterfaceMethod();
}

data/data/com.package/databases folder isn't showed

I made an android dictionary application. I have created a database named "kamusJawa.sqlite" and copied it to the assets folder. I tried the code in this link Own Database in Assets Folder on Android Eclipse Project
This is my database manager class:
package com.kamusJI;
public class DBHelper extends SQLiteOpenHelper{
private static String DBPATH = "/data/data/com.kamusJI/databases/";
private static String DBNAME = "kamusJawa.sqlite";
private SQLiteDatabase DBSQ;
private final Context KJICtx;
public DBHelper(Context context) throws IOException {
super(context, DBNAME, null, 1);
this.KJICtx = context;
// TODO Auto-generated constructor stub
boolean dbexist = cekDB();
if (dbexist) {
//System.out.println("Database exists");
openDB();
} else {
System.out.println("Database doesn't exist");
createDB();
}
}
public void createDB() throws IOException{
boolean dbExist = cekDB();
if(!dbExist){
this.getReadableDatabase();
try{
salinDB();
}catch (IOException e){
throw new Error("Gagal menyalin database");
}
}
}
boolean cekDB() {
//SQLiteDatabase cekDatabase = null;
boolean cekdb = false;
try{
String path = DBPATH + DBNAME;
File dbfile = new File(path);
//cekDatabase = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
cekdb = dbfile.exists();
}catch(SQLException e){
System.out.println("Database tidak ada");
}
return cekdb;
//return cekDatabase !=null ? true : false;
}
private void salinDB() throws IOException{
AssetManager AM = KJICtx.getAssets();
File DbFile = new File(DBPATH+DBNAME);
InputStream in = KJICtx.getAssets().open(DBNAME);
//OutputStream out = new FileOutputStream(DbFile);
OutputStream out = new FileOutputStream("/data/data/com.kamusJI/databases/kamusJawa.sqlite");
DbFile.createNewFile();
byte[] b = new byte[1024];
int i, r;
String[] Files = AM.list("");
Arrays.sort(Files);
i= 1;
String fdb = String.format("kamusJawa.db.00%d", i);
while(Arrays.binarySearch(Files, fdb)>=0){
//InputStream in = AM.open(fdb);
while(( r = in.read(b))>0)
out.write(b,0,r);
in.close();
i++;
fdb = String.format("kamusJawa.db.00%d", i);
}
out.flush();
out.close();
}
public void openDB() throws SQLException{
String path = DBPATH+DBNAME;
DBSQ = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
}
public synchronized void close(){
if(DBSQ !=null)
DBSQ.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
}
and this is my main class:
package com.kamusJI;
public class KJI extends ListActivity {
private KJI this_class = this;
String[] Menu = {"Basa Jawa", "Bahasa Indonesia", "Tambah Data"};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(this, R.layout.row, R.id.Cari, Menu));
ListView lv = getListView();
lv.setTextFilterEnabled(false);
/* Defines On Item Click callback method */
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent action = null;
switch(position) {
case 0:
case 1:
action = new Intent(getApplicationContext(), Cari.class);
action.putExtra("MODE", position);
break;
case 2:
action = new Intent(getApplicationContext(), Tambah.class);
action.putExtra("MODE", position);
break;
case 3:
finish();
return;
}
startActivity(action);
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
public void InitDatabase() {
AsyncTask<String, Void, String> InitDB = new AsyncTask<String, Void, String>() {
Dialog progress = null;
String msg;
DBHelper dbhelper;
#Override
protected void onPreExecute() {
try {
dbhelper = new DBHelper(this_class);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (!dbhelper.cekDB())
progress = ProgressDialog.show(this_class, "", "Installing Database.\nPlease wait.");
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
dbhelper.createDB();
msg = "Database successfully installed.";
} catch (IOException ioe) {
msg = "Database installation failed.";
}
return msg;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (progress!=null) {
progress.dismiss();
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
}
}
};
InitDB.execute(new String());
}
}
When I run my application, then I go to file explorer, I can't find the data/data/com.kamusJI/databases. How it can be like that?
change your database name extension to .db
You need special permissions like root access to read the path:
/data/data/com.package/databases

Resources