Convert AnyObject to NSString to Swift String - string

I am trying to understand why I cannot get a swift String from my dictionary type of AnyObject. If I do a println(fileCreationDate) it works, but I need an actual string of some kind to work with. So when I try to convert it to an NSString (because it is an object unlike String, a struct) it is nil.
Here is what I have:
if let atts = fileManager.attributesOfItemAtPath(fileLocation.path!, error:&err) as? Dictionary<String, AnyObject> {
println(atts)
if let fileCreationDate:AnyObject = atts["NSFileCreationDate"] {
println(fileCreationDate) //prints a date
var mystring:NSString! = fileCreationDate as? NSString
println(mystring) //prints nil
}
Thanks!

You have to use if let and a conditional cast to NSDate to convert your anyObject to NSDate and them you can format your date as you wish.
if let atts = NSFileManager.defaultManager().attributesOfItemAtPath(myUrl.path!, error:nil) as? Dictionary<String, AnyObject> {
if let fileCreationDate = atts["NSFileCreationDate"] as? NSDate {
println(fileCreationDate)
let mystring = fileCreationDate.description
println(mystring)
}
}
extension String {
var fileExists: Bool {
return NSFileManager.defaultManager().fileExistsAtPath(self)
}
var fileAttributes: [String:AnyObject] {
return fileExists ? NSFileManager.defaultManager().attributesOfItemAtPath(self, error:nil) as Dictionary<String, AnyObject> : [:]
}
var fileCreationDate:NSDate {
return fileAttributes["NSFileCreationDate"] as NSDate
}
var fileGroupOwnerAccountName:String{
return fileAttributes["NSFileGroupOwnerAccountName"] as String
}
var fileType: String {
return fileAttributes["NSFileType"] as String
}
var fileHFSTypeCode: Int {
return fileAttributes["NSFileHFSTypeCode"] as Int
}
var fileExtendedAttributes:[String:AnyObject] {
return fileAttributes["NSFileExtendedAttributes"] as [String:AnyObject]
}
var fileSystemNumber: Int {
return fileAttributes["NSFileSystemNumber"] as Int
}
var fileOwnerAccountName: String {
return fileAttributes["NSFileOwnerAccountName"] as String
}
var fileReferenceCount: Int {
return fileAttributes["NSFileReferenceCount"] as Int
}
var fileModificationDate: NSDate {
return fileAttributes["NSFileModificationDate"] as NSDate
}
var fileExtensionHidden: Bool {
return fileAttributes["NSFileExtensionHidden"] as Bool
}
var fileSize: Int {
return fileAttributes["NSFileSize"] as Int
}
var fileGroupOwnerAccountID: Int {
return fileAttributes["NSFileGroupOwnerAccountID"] as Int
}
var fileOwnerAccountID: Int {
return fileAttributes["NSFileOwnerAccountID"] as Int
}
var filePosixPermissions: Int {
return fileAttributes["NSFilePosixPermissions"] as Int
}
var fileHFSCreatorCode: Int {
return fileAttributes["NSFileHFSCreatorCode"] as Int
}
var fileSystemFileNumber: Int {
return fileAttributes["NSFileSystemFileNumber"] as Int
}
}

Related

Get posted file over HTTP Listener in c#

I have make a simple http server using c#. And I know how to get posted data and output them. Here is my c# code
public static void start(){
HttpListener listener = new HttpListener();
listener.Prefixes.Add(new Uri("http://localhost:8080").ToString());
istener.Start();
while(true){
HttpListenerContext con = listener.GetContext();
showPostedData(con.Request);
con.Response.StatusCode = (int)HttpStatusCode.NotFound;
string data = "Uploaded successful";
byte[] output = Encoding.ASCII.GetBytes(data);
con.Response.ContentType = "text/html";
con.Response.ContentLength64 = output.Length;
con.Response.OutputStream.Write(output , 0, output.Length );
}
}
public static void showPostedData(HttpListenerRequest request){
if (!request.HasEntityBody)
{
return;
}
System.IO.Stream body = request.InputStream;
System.Text.Encoding encoding = request.ContentEncoding;
System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
string text;
if (request.ContentType != null)
{
text = reader.ReadToEnd();
}
Console.WriteLine( text );
}
My client html form has input box named file: <input type="file" name"file">
In the console output is like that :
file='Path of Choosed file not a file'
So How i get POSTED files and copy them to upload directory..?
Sorry for my english and thanks in advance...
public static void start(){
HttpListener listener = new HttpListener();
listener.Prefixes.Add(new Uri("http://localhost:80").ToString());
istener.Start();
while(true){
HttpListenerContext con = listener.GetContext();
var values = new HttpNameValueCollection(ref con);
try
{
Console.WriteLine(values.Files["file"].FileName);
File.WriteAllText(values.Files["file"].FileName, values.Files["file"].FileData, Encoding.Default);
}
catch (Exception tr)
{
}
}
}
class HTTPFormData
{
public class File
{
private string _fileName;
public string FileName { get { return _fileName ?? (_fileName = ""); } set { _fileName = value; } }
private string _fileData;
public string FileData { get { return _fileData ?? (_fileName = ""); } set { _fileData = value; } }
private string _contentType;
public string ContentType { get { return _contentType ?? (_contentType = ""); } set { _contentType = value; } }
}
private NameValueCollection _post;
private Dictionary<string, File> _files;
private readonly HttpListenerContext _ctx;
public NameValueCollection Post { get { return _post ?? (_post = new NameValueCollection()); } set { _post = value; } }
public NameValueCollection Get { get { return _ctx.Request.QueryString; } }
public Dictionary<string, File> Files { get { return _files ?? (_files = new Dictionary<string, File>()); } set { _files = value; } }
private void PopulatePostMultiPart(string post_string)
{
var boundary_index = _ctx.Request.ContentType.IndexOf("boundary=") + 9;
var boundary = _ctx.Request.ContentType.Substring(boundary_index, _ctx.Request.ContentType.Length - boundary_index);
var upper_bound = post_string.Length - 4;
if (post_string.Substring(2, boundary.Length) != boundary)
throw (new InvalidDataException());
var current_string = new StringBuilder();
for (var x = 4 + boundary.Length; x < upper_bound; ++x)
{
if (post_string.Substring(x, boundary.Length) == boundary)
{
x += boundary.Length + 1;
var post_variable_string = current_string.Remove(current_string.Length - 4, 4).ToString();
var end_of_header = post_variable_string.IndexOf("\r\n\r\n");
if (end_of_header == -1) throw (new InvalidDataException());
var filename_index = post_variable_string.IndexOf("filename=\"", 0, end_of_header);
var filename_starts = filename_index + 10;
var content_type_starts = post_variable_string.IndexOf("Content-Type: ", 0, end_of_header) + 14;
var name_starts = post_variable_string.IndexOf("name=\"") + 6;
var data_starts = end_of_header + 4;
if (filename_index != -1)
{
var filename = post_variable_string.Substring(filename_starts, post_variable_string.IndexOf("\"", filename_starts) - filename_starts);
var content_type = post_variable_string.Substring(content_type_starts, post_variable_string.IndexOf("\r\n", content_type_starts) - content_type_starts);
var file_data = post_variable_string.Substring(data_starts, post_variable_string.Length - data_starts);
var name = post_variable_string.Substring(name_starts, post_variable_string.IndexOf("\"", name_starts) - name_starts);
Files.Add(name, new File() { FileName = filename, ContentType = content_type, FileData = file_data });
}
else
{
var name = post_variable_string.Substring(name_starts, post_variable_string.IndexOf("\"", name_starts) - name_starts);
var value = post_variable_string.Substring(data_starts, post_variable_string.Length - data_starts);
Post.Add(name, value);
}
current_string.Clear();
continue;
}
current_string.Append(post_string[x]);
}
}
private void PopulatePost()
{
if (_ctx.Request.HttpMethod != "POST" || _ctx.Request.ContentType == null) return;
var post_string = new StreamReader(_ctx.Request.InputStream, _ctx.Request.ContentEncoding).ReadToEnd();
if (_ctx.Request.ContentType.StartsWith("multipart/form-data"))
PopulatePostMultiPart(post_string);
}
public HTTPFormData(ref HttpListenerContext ctx)
{
_ctx = ctx;
PopulatePost();
}
}

logically false fetch request

I am doing a fetch request with a predicate mentioned in the block quote below, but I seem to get "logically false fetch request". What does this message mean and what step should I take to find the problem and resolve it?
annotation: logically false fetch request (entity: Country; predicate: ("alpha3Code" == "KOR"); sortDescriptors: ((null)); type: NSManagedObjectResultType; ) short circuits.
Here is the code that I get the error from
let record = Currency.fetch(id: currency)[0] as! Currency
where Currency class is as follows. "fetch" is implemented in NSManagedObjectProtocol trait
public class Currency: NSManagedObject, NSManagedObjectProtocol, XMLImporterDelegate {
private static let attributes = ["name", "currency", "decimalUnit", "isUsed"]
private static let xmlRecordTag = "CcyNtry"
private static let xmlAttributeTags = ["CcyNm": attributes[0],
"Ccy": attributes[1],
"CcyMnrUnts": attributes[2]]
static func setValue(managedObject: NSManagedObjectProtocol, object: Dictionary<String, Any>) {
let currency = managedObject as! Currency
currency.name = getString(from: object, withKeyValue: attributes[0])
currency.currency = getString(from: object, withKeyValue: attributes[1])
currency.decimalUnit = getInt16(from: object, withKeyValue: attributes[2])
currency.isUsed = getBool(from: object, withKeyValue: attributes[3])
return
}
static func getPredicates(forID id: Dictionary<String, Any>) -> [NSPredicate] {
var predicates: [NSPredicate] = []
predicates.append(NSPredicate.init(format: "%# = %#", attributes[1], getString(from: id, withKeyValue: attributes[1])))
return predicates
}
func isEqual(object: NSManagedObjectProtocol) -> Bool {
if let object = object as? Currency {
if object.currency == self.currency { return false }
return true
} else {
return false
}
}
static func recordTag() -> String {
return xmlRecordTag
}
static func attribute(byTag tag: String) -> String? {
return xmlAttributeTags[tag]
}
static func getUsed() -> [Any]?{
var predicates: [NSPredicate] = []
predicates.append(NSPredicate.init(format: "%# = %#", attributes[3], NSNumber(booleanLiteral: false)))
return fetch(predicates: predicates)
}
}
NSManagedObjectProtocol has following trait
extension NSManagedObjectProtocol {
public static func add(from objectValue: Dictionary<String, Any>) -> NSManagedObjectProtocol? {
let exists = fetch(id: objectValue)
if exists.count > 0 {
NSLog("Object already exists in CoreData : %#", objectValue.description)
return nil
} else {
return newObject(object: objectValue)
}
}
public static func addOrChange(from object: Dictionary<String, Any>) -> NSManagedObjectProtocol {
let exists = fetch(id: object)
if exists.count > 0 {
// TODO: confirm if data needs to be changed rather than delete and insert
}
delete(id: object)
return add(from: object)!
}
public static func getString(from object: Dictionary<String, Any>, withKeyValue key: String) -> String {
return object[key] as! String
}
public static func getInt16(from object: Dictionary<String, Any>, withKeyValue key: String) -> Int16 {
if let stringValue = object[key] as? String {
if let intValue = Int(stringValue) {
return Int16(intValue)
} else {
return 0
}
} else if let intValue = object[key] as? Int {
return Int16(intValue)
} else {
return 0
}
}
public static func getBool(from object: Dictionary<String, Any>, withKeyValue key: String) -> Bool {
if let boolValue = object[key] as? Bool {
return boolValue
} else {
return false
}
}
public static func fetch(predicates: [NSPredicate] = [], sortDescriptors: [NSSortDescriptor] = []) -> [Any] {
let request = Self.request(predicates: predicates)
do {
return try CoreDataHelper.getCoreDataHelper().context.fetch(request)
} catch {
return []
}
}
public static func fetch(id: Dictionary<String, Any>) -> [Any] {
return Self.fetch(predicates: Self.getPredicates(forID: id))
}
public static func delete(predicates: [NSPredicate] = []) {
let context = CoreDataHelper.getContext()
let fetchRequest = request(predicates: predicates)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try context.execute(deleteRequest)
CoreDataHelper.getCoreDataHelper().saveContext()
} catch {
NSLog("Delete request failed")
return
}
}
public static func delete(id: Dictionary<String, Any>) {
delete(predicates: getPredicates(forID: id))
}
// MARK: - Private API
private static func newObject(object: Dictionary<String, Any>) -> NSManagedObjectProtocol {
let entityName = String(describing: self)
let context = CoreDataHelper.getContext()
let managedObject = NSEntityDescription.insertNewObject(forEntityName: entityName, into: context) as! NSManagedObjectProtocol
setValue(managedObject: managedObject, object: object)
CoreDataHelper.getCoreDataHelper().saveContext()
return managedObject
}
private static func request(predicates: [NSPredicate] = [], sortDescriptors: [NSSortDescriptor] = []) -> NSFetchRequest<NSFetchRequestResult> {
// Prepare a request
let entityName = String(describing: self)
let classObject: AnyClass! = NSClassFromString(entityName)
let objectType: NSManagedObject.Type = classObject as! NSManagedObject.Type!
let request: NSFetchRequest<NSFetchRequestResult> = objectType.fetchRequest()
// Add predicates
if predicates.count > 0 {
request.predicate = NSCompoundPredicate.init(andPredicateWithSubpredicates: predicates)
}
// Add sortDescriptors
if sortDescriptors.count > 0 {
request.sortDescriptors = sortDescriptors
}
return request
}
}
Finally this is how the CoreDataHelper looks like.
class CoreDataHelper: NSObject {
var context: NSManagedObjectContext!
var model: NSManagedObjectModel!
var coordinator: NSPersistentStoreCoordinator!
var store: NSPersistentStore!
let storeFilename = "Accounting.sqlite"
func setupCoreData() {
self.loadStore()
}
func saveContext() {
if (self.context.hasChanges) {
do {
try context.save()
} catch {
}
}
}
func applicationDocumentDictionary() -> String {
let directory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!
NSLog("SQLite Directory : %#", directory)
return directory
}
func applicationStoresDirectory() -> URL {
let storesDirectory = URL.init(fileURLWithPath: self.applicationDocumentDictionary()).appendingPathComponent("Stores")
let fileManager = FileManager.default
if (!fileManager.fileExists(atPath: storesDirectory.path)) {
do {
try fileManager.createDirectory(at: storesDirectory,
withIntermediateDirectories: true,
attributes: nil)
} catch {
}
}
return storesDirectory
}
func storesURL() -> URL {
return self.applicationStoresDirectory().appendingPathComponent(storeFilename)
}
override init() {
super.init()
model = NSManagedObjectModel.mergedModel(from: nil)
coordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
context.persistentStoreCoordinator = coordinator
}
func loadStore() {
if (store != nil) {
return
} else {
do {
try store = coordinator.addPersistentStore(ofType: NSSQLiteStoreType,
configurationName: nil,
at: self.storesURL(),
options: nil)
} catch {
}
}
}
static func getCoreDataHelper() -> CoreDataHelper {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.coreDataHelper
}
static func getContext() -> NSManagedObjectContext {
return getCoreDataHelper().context
}
}
Just to let you know that Country class has alpha3Code.
extension Country {
#nonobjc public class func fetchRequest() -> NSFetchRequest<Country> {
return NSFetchRequest<Country>(entityName: "Country");
}
#NSManaged public var englishName: String?
#NSManaged public var frenchName: String?
#NSManaged public var alpha2Code: String?
#NSManaged public var alpha3Code: String?
#NSManaged public var countryNumber: Int16
}
Use the recommended format specifier %K for a key(path) rather than %# as described in the Predicate Documentation
predicates.append(NSPredicate.init(format: "%K = %#", attributes[1], getString(from: id, withKeyValue: attributes[1])))

Using functions as map keys in Haxe

I want to use functions as keys in a Map like this:
var timers : Map<Void->Void, snow.api.Timer>;
But Haxe won't compile:
Abstract Map has no #:to function that accepts IMap<Void -> Void, snow.api.Timer>
Is there a way to do this ?
It's easy to write a custom implementation:
import haxe.Constraints;
class FunctionMap<K:Function,V> implements IMap<K,V> {
private var _keys : Array<K>;
private var _values : Array<V>;
public function new () {
_keys = [];
_values = [];
}
public function get(k:K):Null<V> {
var keyIndex = index(k);
if (keyIndex < 0) {
return null;
} else {
return _values[keyIndex];
}
}
public function set(k:K, v:V):Void {
var keyIndex = index(k);
if (keyIndex < 0) {
_keys.push(k);
_values.push(v);
} else {
_values[keyIndex] = v;
}
}
public function exists(k:K):Bool {
return index(k) >= 0;
}
public function remove(k:K):Bool {
var keyIndex = index(k);
if (keyIndex < 0) {
return false;
} else {
_keys.splice(keyIndex, 1);
_values.splice(keyIndex, 1);
return true;
}
}
public function keys():Iterator<K> {
return _keys.iterator();
}
public function iterator():Iterator<V> {
return _values
.iterator();
}
public function toString():String {
var s = new StringBuf();
s.add("{");
for( i in 0..._keys.length ) {
s.add('<function>');
s.add(" => ");
s.add(Std.string(_values[i]));
if( i < _keys.length - 1 )
s.add(", ");
}
s.add("}");
return s.toString();
}
private function index(key:K) : Int {
for (i in 0..._keys.length) {
if (Reflect.compareMethods(key, _keys[i])) {
return i;
}
}
return -1;
}}
http://try.haxe.org/#DdF31
I just tried this in try.haxe.org, and the compiler doesn't seem to like it, so I'm guessing the answer is "no."
You could get around this with some cleverness:
class Test {
static function main() {
var map:Map<VoidVoid,String>;
map = new Map<VoidVoid,String>();
var thing = {func:foo};
map.set(thing,"bar");
trace(map.get({func:foo})); //fails
trace(map.get(thing)); //succeeds;
}
static function foo():Void
{
}
}
typedef VoidVoid = {
var func:Void->Void;
}
But that's not an ideal solution because wrapping it in a typedef like that will make it fail if it's not the exact same instance, even if the value inside is the same.
I also tried making a Map<Dynamic,String> since you can stuff function references in those, but that didn't work either.
At this point I should ask, what problem are you trying to solve this way? Perhaps it could be better solved some other way.

XPages: How to acces an application scope bean from a session scope bean

I need a value from my application scope managed bean in my session scope managed bean. Not sure how to get this done. Saw a poste here: https://guedebyte.wordpress.com/2012/05/19/accessing-beans-from-java-code-in-xpages-learned-by-reading-the-sourcecode-of-the-extensionlibrary/ But I get a bunch of errors... I also found this: JSF 2.0 Accessing Application Scope bean from another Bean so IM thinking maybe I need to redefine my application bean??? Totally clueless...
How can I make that happen?
Here is the application scope bean's code:
public class AppConfig implements Serializable {
private static final long serialVersionUID = 2768250939591274442L;
public AppConfig() {
initDefaults();
initFromConfigDoc();
}
// Control the number of entries displayed in the widgets
private int nbWidgetFavorites = 0;
private int nbWidgetMostPopular = 0;
private int nbWidgetToolbox = 0;
// Control the number of entries to display in the What's new view
private int nbWhatsNew = 0;
private String showDetailsWhatsNew = "no";
//controls various search options
private int nbSearchResults = 0;
private int nbMaxSearchResults = 0;
//the home page to use for each language
private String homePageUNID_FR = "";
private String homePageUNID_EN = "";
//application email address to use (webmaster)
// DEV ADDRESS
private String appEmailAddress = "DEVTEAMTEST/DEV#DEVELOPMENTCORP";
// UAT ADDRESS
// PROD ADDRESS
//path to the stats DB
private String statsDB = "";
//application message, if needed
private String systemMessageFR = "";
private String systemMessageEN = "";
//default lang (defined here as session bean will read from the App bean first to
// see if there's a value stored there)
private String defaultLang = "";
//default prov
private String defaultProv = "";
// show Province drop down?
private String showProv = "no";
//various text for "share this link" emails
private String senderEmail = "";
private String senderName = "";
private String appURL = "";
private String emailText = "";
private String clickLinkText = "";
private String emailFooter = "";
private String messageIntro = "";
private String allowRatingModification = "";
/*****************************************************************************/
private void initDefaults() {
// Control the number of entries displayed in the widgets
nbWidgetFavorites = 10;
nbWidgetMostPopular = 10;
nbWidgetToolbox = 10;
nbWhatsNew = 15;
showDetailsWhatsNew = "no";
nbSearchResults = 25;
nbMaxSearchResults = 100;
homePageUNID_FR = "";
homePageUNID_EN = "";
appEmailAddress = "DEVTEAMTEST/DEV#DEVELOPMENTCORP";
statsDB = "belair\\xBiblioStats.nsf";
systemMessageFR = "";
systemMessageEN = "";
defaultLang = "FR";
defaultProv = "QC";
showProv = "no";
allowRatingModification = "1";
}
/*****************************************************************************/
public boolean persistToConfigDoc() {
//write content of sessionScope vars to config doc
try {
Database db = ExtLibUtil.getCurrentSession().getCurrentDatabase();
View view = db.getView("AppConfig");
Document doc = view.getFirstDocument();
if(doc == null) {
doc = db.createDocument();
doc.replaceItemValue("form", "AppConfig");
}
doc.replaceItemValue("nbWidgetFavorites", this.nbWidgetFavorites);
doc.replaceItemValue("nbWidgetMostPopular", this.nbWidgetMostPopular);
doc.replaceItemValue("nbWidgetToolbox", this.nbWidgetToolbox);
doc.replaceItemValue("nbWidgetToolbox", this.nbWidgetToolbox);
doc.replaceItemValue("nbWhatsNew", this.nbWhatsNew);
doc.replaceItemValue("showDetailsWhatsNew", this.showDetailsWhatsNew);
doc.replaceItemValue("nbSearchResults", this.nbSearchResults);
doc.replaceItemValue("nbMaxSearchResults", this.nbMaxSearchResults);
doc.replaceItemValue("homePageUNID_FR", this.homePageUNID_FR);
doc.replaceItemValue("homePageUNID_EN", this.homePageUNID_EN);
doc.replaceItemValue("appEmailAddress", this.appEmailAddress);
doc.replaceItemValue("statsDB", this.statsDB);
doc.replaceItemValue("systemMessageFR", this.systemMessageFR);
doc.replaceItemValue("systemMessageEN", this.systemMessageEN);
doc.replaceItemValue("defaultLang", this.defaultLang);
doc.replaceItemValue("defaultProv", this.defaultProv);
doc.replaceItemValue("showProv", this.showProv);
doc.replaceItemValue("senderEmail", this.senderEmail);
doc.replaceItemValue("senderName", this.senderName);
doc.replaceItemValue("appURL", this.appURL);
doc.replaceItemValue("emailText", this.emailText);
doc.replaceItemValue("clickLinkText", this.clickLinkText);
doc.replaceItemValue("emailFooter", this.emailFooter);
doc.replaceItemValue("messageIntro", this.messageIntro);
doc.replaceItemValue("allowRatingModification", this.allowRatingModification);
doc.save();
return true;
} catch (NotesException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
/*****************************************************************************/
public void initFromConfigDoc() {
try {
Database db = ExtLibUtil.getCurrentSession().getCurrentDatabase();
View view = db.getView("AppConfig");
Document doc = view.getFirstDocument();
if(doc != null) {
//load default values
if(doc.hasItem("nbWidgetFavorites")) {
int tmp = doc.getItemValueInteger("nbWidgetFavorites");
if(tmp > 0) {
this.nbWidgetFavorites = tmp;
}
}
if(doc.hasItem("nbWidgetMostPopular")) {
int tmp = doc.getItemValueInteger("nbWidgetMostPopular");
if(tmp > 0) {
this.nbWidgetMostPopular = tmp;
}
}
if(doc.hasItem("nbWidgetToolbox")) {
int tmp = doc.getItemValueInteger("nbWidgetToolbox");
if(tmp > 0) {
this.nbWidgetToolbox = tmp;
}
}
if(doc.hasItem("nbWhatsNew")) {
int tmp = doc.getItemValueInteger("nbWhatsNew");
if(tmp > 0) {
this.nbWhatsNew = tmp;
}
}
if(doc.hasItem("showDetailsWhatsNew")) {
String tmp = doc.getItemValueString("showDetailsWhatsNew");
this.showDetailsWhatsNew = tmp;
}
if(doc.hasItem("nbSearchResults")) {
int tmp = doc.getItemValueInteger("nbSearchResults");
if(tmp > 0) {
this.nbSearchResults = tmp;
}
}
if(doc.hasItem("nbMaxSearchResults")) {
int tmp = doc.getItemValueInteger("nbMaxSearchResults");
if(tmp > 0) {
this.nbMaxSearchResults = tmp;
}
}
if(doc.hasItem("homePageUNID_FR")) {
String tmp = doc.getItemValueString("homePageUNID_FR");
if(!"".equals(tmp)) {
this.homePageUNID_FR = tmp;
}
}
if(doc.hasItem("homePageUNID_EN")) {
String tmp = doc.getItemValueString("homePageUNID_EN");
if(!"".equals(tmp)) {
this.homePageUNID_EN = tmp;
}
}
if(doc.hasItem("appEmailAddress")) {
String tmp = doc.getItemValueString("appEmailAddress");
if(!"".equals(tmp)) {
this.appEmailAddress = tmp;
}
}
if(doc.hasItem("statsDB")) {
String tmp = doc.getItemValueString("statsDB");
if(!"".equals(tmp)) {
this.statsDB = tmp;
}
}
if(doc.hasItem("systemMessageFR")) {
String tmp = doc.getItemValueString("systemMessageFR");
if(!"".equals(tmp)) {
this.systemMessageFR = tmp;
}
}
if(doc.hasItem("systemMessageEN")) {
String tmp = doc.getItemValueString("systemMessageEN");
if(!"".equals(tmp)) {
this.systemMessageEN = tmp;
}
}
if(doc.hasItem("defaultLang")) {
String tmp = doc.getItemValueString("defaultLang");
if(!"".equals(tmp)) {
this.defaultLang = tmp;
}
}
if(doc.hasItem("defaultProv")) {
String tmp = doc.getItemValueString("defaultProv");
if(!"".equals(tmp)) {
this.defaultProv = tmp;
}
}
if(doc.hasItem("showProv")) {
String tmp = doc.getItemValueString("showProv");
if(!"".equals(tmp)) {
this.showProv = tmp;
}
}
if(doc.hasItem("senderEmail")) {
String tmp = doc.getItemValueString("senderEmail");
if(!"".equals(tmp)) {
this.senderEmail = tmp;
}
}
if(doc.hasItem("senderName")) {
String tmp = doc.getItemValueString("senderName");
if(!"".equals(tmp)) {
this.senderName = tmp;
}
}
if(doc.hasItem("appURL")) {
String tmp = doc.getItemValueString("appURL");
if(!"".equals(tmp)) {
this.appURL = tmp;
}
}
if(doc.hasItem("emailText")) {
String tmp = doc.getItemValueString("emailText");
if(!"".equals(tmp)) {
this.emailText = tmp;
}
}
if(doc.hasItem("clickLinkText")) {
String tmp = doc.getItemValueString("clickLinkText");
if(!"".equals(tmp)) {
this.clickLinkText = tmp;
}
}
if(doc.hasItem("emailFooter")) {
String tmp = doc.getItemValueString("emailFooter");
if(!"".equals(tmp)) {
this.emailFooter = tmp;
}
}
if(doc.hasItem("messageIntro")) {
String tmp = doc.getItemValueString("messageIntro");
if(!"".equals(tmp)) {
this.messageIntro = tmp;
}
}
//allowRatingModification
if(doc.hasItem("allowRatingModification")) {
String tmp = doc.getItemValueString("allowRatingModification");
if(!"".equals(tmp)) {
this.allowRatingModification = tmp;
}
}
}
} catch (NotesException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*****************************************************************************/
public int getNbWidgetFavorites() {
return nbWidgetFavorites;
}
public void setNbWidgetFavorites(int nbWidgetFavorites) {
this.nbWidgetFavorites = nbWidgetFavorites;
}
public int getNbWidgetMostPopular() {
return nbWidgetMostPopular;
}
public void setNbWidgetMostPopular(int nbWidgetMostPopular) {
this.nbWidgetMostPopular = nbWidgetMostPopular;
}
public int getNbWidgetToolbox() {
return nbWidgetToolbox;
}
public void setNbWidgetToolbox(int nbWidgetToolbox) {
this.nbWidgetToolbox = nbWidgetToolbox;
}
public void setNbWhatsNew(int nbWhatsNew) {
this.nbWhatsNew = nbWhatsNew;
}
public int getNbWhatsNew() {
return nbWhatsNew;
}
public void setShowDetailsWhatsNew(String showDetailsWhatsNew) {
this.showDetailsWhatsNew = showDetailsWhatsNew;
}
public String getShowDetailsWhatsNew() {
return showDetailsWhatsNew;
}
public int getNbSearchResults() {
return nbSearchResults;
}
public void setNbSearchResults(int nbSearchResults) {
this.nbSearchResults = nbSearchResults;
}
public int getNbMaxSearchResults() {
return nbMaxSearchResults;
}
public void setNbMaxSearchResults(int nbMaxSearchResults) {
this.nbMaxSearchResults = nbMaxSearchResults;
}
public String getHomePageUNID_FR() {
return homePageUNID_FR;
}
public void setHomePageUNID_FR(String homePageUNID_FR) {
this.homePageUNID_FR = homePageUNID_FR;
}
public String getHomePageUNID_EN() {
return homePageUNID_EN;
}
public void setHomePageUNID_EN(String homePageUNID_EN) {
this.homePageUNID_EN = homePageUNID_EN;
}
public String getAppEmailAddress() {
return appEmailAddress;
}
public void setAppEmailAddress(String appEmailAddress) {
this.appEmailAddress = appEmailAddress;
}
public String getSystemMessageFR() {
return systemMessageFR;
}
public void setSystemMessageFR(String systemMessageFR) {
this.systemMessageFR = systemMessageFR;
}
public String getSystemMessageEN() {
return systemMessageEN;
}
public void setSystemMessageEN(String systemMessageEN) {
this.systemMessageEN = systemMessageEN;
}
public void setStatsDB(String statsDB) {
this.statsDB = statsDB;
}
public String getStatsDB() {
return statsDB;
}
public void setDefaultLang(String defaultLang) {
this.defaultLang = defaultLang;
}
public String getDefaultProv() {
return defaultProv;
}
public void setDefaultProv(String defaultPRov) {
this.defaultProv = defaultPRov;
}
public void setShowProv(String showProv) {
this.showProv = showProv;
}
public String getShowProv() {
return showProv;
}
public String getDefaultLang() {
return defaultLang;
}
public String getMessageIntro() {
return messageIntro;
}
public void setMessageIntro(String messageIntro) {
this.messageIntro = messageIntro;
}
public String getSenderEmail() {
return senderEmail;
}
public void setSenderEmail(String senderEmail) {
this.senderEmail = senderEmail;
}
public String getSenderName() {
return senderName;
}
public void setSenderName(String senderName) {
this.senderName = senderName;
}
public String getAppURL() {
return appURL;
}
public void setAppURL(String appURL) {
this.appURL = appURL;
}
public String getEmailText() {
return emailText;
}
public void setEmailText(String emailText) {
this.emailText = emailText;
}
public String getClickLinkText() {
return clickLinkText;
}
public void setClickLinkText(String clickLinkText) {
this.clickLinkText = clickLinkText;
}
public String getEmailFooter() {
return emailFooter;
}
public void setEmailFooter(String emailFooter) {
this.emailFooter = emailFooter;
}
//allowRatingModification
public String getAllowRatingModification() {
return allowRatingModification;
}
public void setAllowRatingModification(String allowRatingModification) {
this.allowRatingModification = allowRatingModification;
}
}
The VariableResolver goes through all implicit variables (e.g. session, database) as well as scoped variables (e.g. applicationScope.myVar). Your bean is also accessed from SSJS via the VariableResolver.
So you can use:
ExtLibUtil.resolveVariable(FacesContext.getCurrentInstance(), "myAppScopeBean");
This is not a direct answer to your question...
An alternative would be to set the value you want in applicationScope and then access it this way from your bean. To access the entire bean directly is a different answer.
You use this code get a handle to your applicationScope.
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
Map<String, Object> applicationScope = externalContext.getApplicationMap();
Then to use this you have code like this:
String agentLogDB = (String) applicationScope.get("LOGDB");

Swift extract an Int, Float or Double value from a String (type-conversion)

Please could you help me here? I need to understand how to convert a String into an Int, Float or Double! This problem occurs when I'm trying to get the value from an UITextField and need this type of conversion!
I used to do it like this:
var myValue : Float = myTextField.text.bridgeToObjectiveC().floatValue
but since Xcode 6 beta 6 it doesn't seem to work anymore!
I've tried also like this:
var str = "3.14"
// Conversion from StringValue to an Int
var intValue : Int = str.toInt()!
// Other converstion from StringValue to an Int
var intOtherValue : Int = Int(str)
// Converstion from StringValue to a Float
var floatValue : Float = str.bridgeToObjectiveC().floatValue
// Converstion from StringValue to a Double
var doubleValue : Double = Double(str)
Please help me or tell me where I can find the answer! Many thanks!
Convert String to NSString and Use convenience methods:
var str = "3.1"
To Int
var intValue : Int = NSString(string: str).integerValue // 3
To Float
var floatValue : Float = NSString(string: str).floatValue // 3.09999990463257
To Double
var doubleValue : Double = NSString(string: str).doubleValue // 3.1
Reference
var doubleValue: Double { get }
var floatValue: Float { get }
var intValue: Int32 { get }
#availability(OSX, introduced=10.5)
var integerValue: Int { get }
#availability(OSX, introduced=10.5)
var longLongValue: Int64 { get }
#availability(OSX, introduced=10.5)
Use:
Int(string:String)
Double(string:String)
Float(string:String)
Which return an optional which is nil if it fails to parse the string.
For example:
var num = 0.0
if let unwrappedNum = Double("5.0") {
num = unwrappedNum
} else {
print("Error converting to Double")
}
Of course you can force unwrap if you are sure:
var foo = Double("5.0")!
Extending String
If you are doing this in more than a few places, and want error handling to be handled the same everywhere then you may want to extend String with conversion methods:
For example:
extension String {
func toDouble() -> Double {
if let unwrappedNum = Double(self) {
return unwrappedNum
} else {
// Handle a bad number
print("Error converting \"" + self + "\" to Double")
return 0.0
}
}
}
and then to use it:
let str = "4.9"
var num = str.toDouble()
public extension String {
public func toFloat() -> Float? {
return Float.init(self)
}
public func toDouble() -> Double? {
return Double.init(self)
}
}
var holdTextFieldToStringValue = myTextField.text
//convert from string to Int
var holdIntValue = holdTextFieldToStringValue.toInt()!
//convert from string to Double
var holdDoubleValue = Double((holdTextFieldToStringValue as NSString).doubleValue)
let strValue = "14.03"
let result = (strValue as NSString).floatValue

Resources