How to use regex in groovy map - collections

i have a map similar to this.
xxx-10.name ='welcome'
xxx-10.age ='12'
xxx-10.std ='2nd'
xxx-12.name ='welcome'
xxx-12.age ='12'
xxx-12.std ='2nd'
yyy-10.name ='welcome'
yyy-10.age ='12'
yyy-10.std ='2nd'
yyy-12.name ='welcome'
yyy-12.age ='12'
yyy-12.std ='2nd'
wen user gives xxx i have to return the submap with all xxx entries, irrespective of the number associated with it. Is there any way to achieve this using regex ? or with out iterating over the keys?
SubMap i can get using the utility..

There is a filter function for collections in groovy. See API
def result = [a:1, b:2, c:4, d:5].findAll { it.value % 2 == 0 }
assert result.every { it instanceof Map.Entry }
assert result*.key == ["b", "c"]
assert result*.value == [2, 4]
In your case when searching for yourSearchString using String.startsWith():
map.findAll { it.key.startsWith(yourSearchString) }

This should do what you want.
def fileContents = '''xxx-10.name ='welcome'
|xxx-10.age ='12'
|xxx-10.std ='2nd'
|xxx-12.name ='welcome'
|xxx-12.age ='12'
|xxx-12.std ='2nd'
|yyy-10.name ='welcome'
|yyy-10.age ='12'
|yyy-10.std ='2nd'
|yyy-12.name ='welcome'
|yyy-12.age ='12'
|yyy-12.std ='2nd'''.stripMargin()
// Get a Reader for the String (this could be a File.withReader)
Map map = new StringReader( fileContents ).with {
// Create a new Properties object
new Properties().with { p ->
// Load the properties from the reader
load( it )
// Then for each name, inject into a map
propertyNames().collectEntries {
// Strip quotes off the values
[ (it): p[ it ][ 1..-2 ] ]
}
}
}
findByPrefix = { pref ->
map.findAll { k, v ->
k.startsWith( pref )
}
}
findByPrefix( 'xxx' )
Fingers crossed you don't delete this question ;-)

Related

Reflection and typeChecking for optionals

Playing with reflections in swift 2.0 i'm trying to type check a child value.
The problem: each element of the children array in the Mirror of Any item is not optional, but his type can be optional... What happens is that of course i have the child value even if the value is nil
Maybe it is not clear so i put here some code to explain better.
For convenience i defined a subscript in a Mirror extension that fetches the child object with a given label
extension Mirror {
public subscript(key: String)->Child?{
var child = children.filter {
var valid = false
if let label = $0.label {
valid = label == key
}
return valid
}.last
if child == nil,
let superMirror = superclassMirror() {
child = superMirror[key]
}
return child
}
}
perfect, now let's say i have this class
class Rule: NSObject, AProtocol {
var hello: String?
var subRule: Rule?
}
Ok, now the problem
let aRule = Rule()
let mirroredRule = Mirror(reflecting:aRule)
if let child = mirroredRule["subRule"] {
//child.value always exists
//i can't do child.value is AProtocol? because child.value is not optional
//child.value is AProtocol of course returns false
//child.dynamicType is Optional(Rule)
if let unwrapped = unwrap(child.value) where unwrapped is AProtocol {
//This of course works only if child.value is not nil
//so the unwrap function returns an unwrapped value
//this is not a definitive solution
}
}
child.value has not been initialized so it is nil, and i can't check his type using the unwrap function. I'm writing a deserializer so i need to check the var also if it is nil because in the dictionary that will be used for the deserialization it could be defined.
private func unwrap(subject: Any) -> Any? {
var value: Any?
let mirrored = Mirror(reflecting:subject)
if mirrored.displayStyle != .Optional {
value = subject
} else if let firstChild = mirrored.children.first {
value = firstChild.value
}
return value
}
I hope the problem is clear. Any suggestions?
Based on this answer, I recommend using if case Optional<Any>.some(_).
I did something recently to make sure I have at least one optional set on my struct. You can paste into playgrounds:
struct ErrorResponse: Codable {
let message: String?
let authorizationException: [String: String]?
let validationException: String?
let generalException: String?
var isValid: Bool {
var hasAtLeastOneNonNilErrorValue = false
Mirror(reflecting: self).children.forEach {
if case Optional<Any>.some(_) = $0.value {
hasAtLeastOneNonNilErrorValue = true
}
}
return hasAtLeastOneNonNilErrorValue
}
}
let errorTest = ErrorResponse(message: "some message", authorizationException: nil, validationException: nil, generalException: nil)
let errorTest2 = ErrorResponse(message: nil, authorizationException: nil, validationException: nil, generalException: nil)
print("is valid: \(errorTest.isValid)") //is valid: true
print("is valid: \(errorTest2.isValid)") //is valid: false

How can I use a Swift enum as a Dictionary key? (Conforming to Equatable)

I've defined an enum to represent a selection of a "station"; stations are defined by a unique positive integer, so I've created the following enum to allow negative values to represent special selections:
enum StationSelector : Printable {
case Nearest
case LastShown
case List
case Specific(Int)
func toInt() -> Int {
switch self {
case .Nearest:
return -1
case .LastShown:
return -2
case .List:
return -3
case .Specific(let stationNum):
return stationNum
}
}
static func fromInt(value:Int) -> StationSelector? {
if value > 0 {
return StationSelector.Specific(value)
}
switch value {
case -1:
return StationSelector.Nearest
case -2:
return StationSelector.LastShown
case -3:
return StationSelector.List
default:
return nil
}
}
var description: String {
get {
switch self {
case .Nearest:
return "Nearest Station"
case .LastShown:
return "Last Displayed Station"
case .List:
return "Station List"
case .Specific(let stationNumber):
return "Station #\(stationNumber)"
}
}
}
}
I'd like to use these values as keys in a dictionary. Declaring a Dictionary yields the expected error that StationSelector doesn't conform to Hashable. Conforming to Hashable is easy with a simple hash function:
var hashValue: Int {
get {
return self.toInt()
}
}
However, Hashable requires conformance to Equatable, and I can't seem to define the equals operator on my enum to satisfy the compiler.
func == (lhs: StationSelector, rhs: StationSelector) -> Bool {
return lhs.toInt() == rhs.toInt()
}
The compiler complains that this is two declarations on a single line and wants to put a ; after func, which doesn't make sense, either.
Any thoughts?
Info on Enumerations as dictionary keys:
From the Swift book:
Enumeration member values without associated values (as described in
Enumerations) are also hashable by default.
However, your Enumeration does have a member value with an associated value, so Hashable conformance has to be added manually by you.
Solution
The problem with your implementation, is that operator declarations in Swift must be at a global scope.
Just move:
func == (lhs: StationSelector, rhs: StationSelector) -> Bool {
return lhs.toInt() == rhs.toInt()
}
outside the enum definition and it will work.
Check the docs for more on that.
I struggled for a little trying to make an enum with associated values conform to Hashable.
Here's I made my enum with associated values conform to Hashable so it could be sorted or used as a Dictionary key, or do anything else that Hashable can do.
You have to make your associated values enum conform to Hashable because associated values enums cannot have a raw type.
public enum Components: Hashable {
case None
case Year(Int?)
case Month(Int?)
case Week(Int?)
case Day(Int?)
case Hour(Int?)
case Minute(Int?)
case Second(Int?)
///The hashValue of the `Component` so we can conform to `Hashable` and be sorted.
public var hashValue : Int {
return self.toInt()
}
/// Return an 'Int' value for each `Component` type so `Component` can conform to `Hashable`
private func toInt() -> Int {
switch self {
case .None:
return -1
case .Year:
return 0
case .Month:
return 1
case .Week:
return 2
case .Day:
return 3
case .Hour:
return 4
case .Minute:
return 5
case .Second:
return 6
}
}
}
Also need to override the equality operator:
/// Override equality operator so Components Enum conforms to Hashable
public func == (lhs: Components, rhs: Components) -> Bool {
return lhs.toInt() == rhs.toInt()
}
For more readability, let's reimplement StationSelector with Swift 3:
enum StationSelector {
case nearest, lastShown, list, specific(Int)
}
extension StationSelector: RawRepresentable {
typealias RawValue = Int
init?(rawValue: RawValue) {
switch rawValue {
case -1: self = .nearest
case -2: self = .lastShown
case -3: self = .list
case (let value) where value >= 0: self = .specific(value)
default: return nil
}
}
var rawValue: RawValue {
switch self {
case .nearest: return -1
case .lastShown: return -2
case .list: return -3
case .specific(let value) where value >= 0: return value
default: fatalError("StationSelector is not valid")
}
}
}
The Apple developer API Reference states about Hashable protocol:
When you define an enumeration without associated values, it gains Hashable conformance automatically, and you can add Hashable conformance to your other custom types by adding a single hashValue property.
Therefore, because StationSelector implements associated values, you must make StationSelector conform to Hashable protocol manually.
The first step is to implement == operator and make StationSelector conform to Equatable protocol:
extension StationSelector: Equatable {
static func == (lhs: StationSelector, rhs: StationSelector) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
Usage:
let nearest = StationSelector.nearest
let lastShown = StationSelector.lastShown
let specific0 = StationSelector.specific(0)
// Requires == operator
print(nearest == lastShown) // prints false
print(nearest == specific0) // prints false
// Requires Equatable protocol conformance
let array = [nearest, lastShown, specific0]
print(array.contains(nearest)) // prints true
Once Equatable protocol is implemented, you can make StationSelector conform to Hashable protocol:
extension StationSelector: Hashable {
var hashValue: Int {
return self.rawValue.hashValue
}
}
Usage:
// Requires Hashable protocol conformance
let dictionnary = [StationSelector.nearest: 5, StationSelector.lastShown: 10]
The following code shows the required implementation for StationSelector to make it conform to Hashable protocol using Swift 3:
enum StationSelector: RawRepresentable, Hashable {
case nearest, lastShown, list, specific(Int)
typealias RawValue = Int
init?(rawValue: RawValue) {
switch rawValue {
case -1: self = .nearest
case -2: self = .lastShown
case -3: self = .list
case (let value) where value >= 0: self = .specific(value)
default: return nil
}
}
var rawValue: RawValue {
switch self {
case .nearest: return -1
case .lastShown: return -2
case .list: return -3
case .specific(let value) where value >= 0: return value
default: fatalError("StationSelector is not valid")
}
}
static func == (lhs: StationSelector, rhs: StationSelector) -> Bool {
return lhs.rawValue == rhs.rawValue
}
var hashValue: Int {
return self.rawValue.hashValue
}
}
As of Swift 5.5 you can just write enum StationSelector: Hashable {}. Automatic conformance will be synthesized.
Just for emphasising what Cezar said before. If you can avoid having a member variable, you don't need to implement the equals operator to make enums hashable – just give them a type!
enum StationSelector : Int {
case Nearest = 1, LastShown, List, Specific
// automatically assigned to 1, 2, 3, 4
}
That's all you need. Now you can also initiate them with the rawValue or retrieve it later.
let a: StationSelector? = StationSelector(rawValue: 2) // LastShown
let b: StationSelector = .LastShown
if(a == b)
{
print("Selectors are equal with value \(a?.rawValue)")
}
For further information, check the documentation.

How to get just one value from querystrig

I'm write this function:
public static String QueryString(string queryStringKey)
{
if (HttpContext.Current.Request.QueryString[queryStringKey] != null)
{
if (HttpContext.Current.Request.QueryString[queryStringKey].ToString() != string.Empty)
return HttpContext.Current.Request.QueryString.GetValues(1).ToString();
}
return "NAQ";
}
And i want to get just one value from querystring parameter.
for example i send "page" to my function and url is: "sth.com/?page=1&page=2"
and function return to me: "1,2" ; but i want first value: "1", How?
GetValues returns a string[] if the key exists. An array is zero based, so you get the first element by using array[0], you are using GetValues(1) in your code, i assume that you wanted the first.
You could also use the Enumerable.First extension method:
Request.QueryString.GetValues("page").First();
Since GetValues returns not an empty array but null if the key was not present you need to check that explicitely (FirstOrDefault doesn't work):
public static String QueryString(string queryStringKey)
{
if (HttpContext.Current != null && HttpContext.Current.Request != null)
{
string[] values = HttpContext.Current.Request.QueryString.GetValues("queryStringKey");
if (values != null) return values.First();
}
return "NAQ";
}
A better approach would be -
public static String QueryString(string queryStringKey)
{
if (HttpContext.Current!=null && HttpContext.Current.Request!=null && !string.IsNullOrEmpty(HttpContext.Current.Request.QueryString[queryStringKey])
{
return HttpContext.Current.Request.QueryString.GetValues(queryStringKey).First();
}
return "NAQ";
}

Flex/AS3 - calling a function dynamically using a String?

Is it possible to call a function in AS3 using a string value as the function name e.g.
var functionName:String = "getDetails";
var instance1:MyObject = new MyObject();
instance1.functionName(); // I know this is so wrong, but it gets the point accross:)
UPDATE
The answer from #Taskinoor on accessing a function is correct:
instance1[functionName]();
And to access a property we would use:
instance1[propertyName]
instance1[functionName]();
Check this for some details.
You may use function.apply() or function.call() methods instead in the case when you dont know whether object has such method for instance.
var functionName:String = "getDetails";
var instance1:MyObject = new MyObject();
var function:Function = instance1[functionName]
if (function)
function.call(instance1, yourArguments)
I have created the following wrappers for calling a function. You can call it by its name or by the actual function. I tried to make these as error-prone as possible.
The following function converts a function name to the corresponding function given the scope.
public static function parseFunc(func:*, scope:Object):Function {
if (func is String && scope && scope.hasOwnProperty(funcName)) {
func = scope[func] as Function;
}
return func is Function ? func : null;
}
Call
Signature: call(func:*,scope:Object,...args):*
public static function call(func:*, scope:Object, ...args):* {
func = parseFunc(func, scope);
if (func) {
switch (args.length) {
case 0:
return func.call(scope);
case 1:
return func.call(scope, args[0]);
case 2:
return func.call(scope, args[0], args[1]);
case 3:
return func.call(scope, args[0], args[1], args[2]);
// Continue...
}
}
return null;
}
Apply
Signature: apply(func:*,scope:Object,argArray:*=null):*
public static function apply(func:*, scope:Object, argArray:*=null):* {
func = parseFunc(func, scope);
return func != null ? func.apply(scope, argArray) : null;
}
Notes
Call
The switch is needed, because both ...args and arguments.slice(2) are Arrays. You need to call Function.call() with variable arguments.
Apply
The built-in function (apply(thisArg:*, argArray:*):*) uses a non-typed argument for the argArray. I am just piggy-backing off of this.

Dynamically implement interface in Groovy using invokeMethod

Groovy offers some really neat language features for dealing with and implementing Java interfaces, but I seem kind of stuck.
I want to dynamically implement an Interface on a Groovy class and intercept all method calls on that interface using GroovyInterceptable.invokeMethod. Here what I tried so far:
public interface TestInterface
{
public void doBla();
public String hello(String world);
}
import groovy.lang.GroovyInterceptable;
class GormInterfaceDispatcher implements GroovyInterceptable
{
def invokeMethod(String name, args) {
System.out.println ("Beginning $name with $args")
def metaMethod = metaClass.getMetaMethod(name, args)
def result = null
if(!metaMethod)
{
// Do something cool here with the method call
}
else
result = metaMethod.invoke(this, args)
System.out.println ("Completed $name")
return result
}
TestInterface getFromClosure()
{
// This works, but how do I get the method name from here?
// I find that even more elegant than using invokeMethod
return { Object[] args -> System.out.println "An unknown method called with $args" }.asType(TestInterface.class)
}
TestInterface getThisAsInterface()
{
// I'm using asType because I won't know the interfaces
// This returns null
return this.asType(TestInterface.class)
}
public static void main(String[] args)
{
def gid = new GormInterfaceDispatcher()
TestInterface ti = gid.getFromClosure()
assert ti != null
ti.doBla() // Works
TestInterface ti2 = gid.getThisAsInterface()
assert ti2 != null // Assertion failed
ti2.doBla()
}
}
Returning the Closure works fine, but I couldn't figure a way to find out the name of the method being called there.
Trying to make a Proxy to the this reference itself (so that method calls will call invokeMethod) returns null.
You could use the Map coercion feature of Groovy to dynamically generate a Map that represents the given interface:
TestInterface getMapAsInterface() {
def map = [:]
TestInterface.class.methods.each() { method ->
map."$method.name" = { Object[] args->
println "Called method ${method.name} with ${args}"
}
}
return map.asType(TestInterface.class)
}
To complete the response of Christoph, as stated by this page, you can implement an interface with a closure. For example:
def map = [doBla: { println 'Bla!'}, hello: {world -> "Hello $world".toString()}] as TestInterface
map.hello 'Groovy' // returns 'Hello Groovy'

Resources