How to return String from Optional<String>? - javafx

I have the following function.
public String getSomething(){
TextInputDialog dialog = new TextInputDialog();
dialog.setHeaderText("X");
dialog.setTitle("Y");
Optional<String> result = dialog.showAndWait();
return result;
}
Obviously, the returned value is not of String type. How could I return a String when result's type is Optional<String>?

Try doing result.get() should return a string.

I would do something like this to make sure you are protecting from null
if(a. isPresent()) {a.get()}

I'd use orElse which provides a default value in case the actual value is absent:
public String getSomething(){
TextInputDialog dialog = new TextInputDialog();
dialog.setHeaderText("X");
dialog.setTitle("Y");
return dialog.showAndWait().orElse("n/a");
}

Use String.valueOf(optionalString);
Optional<String> s1 =Optional.of("Hello");
// s1 will print - Optional["Hello"]
String s1 = String.valueOf(optionalObj.get());
// now s1 will print "Hello"
this would extract the exact string literal from the optional object.

Related

aop.AopInvocationException: Null return value from

here is the repository:
#Query(value = "select u.balance from User u where u.name=:name")
float toGetBalance(#Param("name") String name);
and here is the DAO interface:
boolean checkBalance(String userName, float totalPrice);
and here is the service
#Transactional(readOnly = true)
#Override
public boolean checkBalance(String userName, float totalPrice) {
if (userRepository.toGetBalance(userName) < totalPrice) {
return false;
} else {
return true;
}
}
and here is the error info:
org.springframework.aop.AopInvocationException: Null return value from advice does not match primitive return type for: public abstract float com.repository.UserRepository.toGetBalance(java.lang.String)
and the type of balance is float!
what's wrong?
Change the signature of your repository to
#Query(value = "select u.balance from User u where u.name=:name")
Float toGetBalance(#Param("name") String name);
And it will simply return null if there is no such user in database with given name
#Query(value = "select u.balance from User u where u.name=:name")'
'Float toGetBalance(#Param("name") String name);
This exception arise because name not exist OR balance = NULL fpr the selected record in the table
So the query results no output. Spring JPA not able to bind the result with Return type Float.
Null return value from advice does not match primitive return type for: public abstract float com.repository.UserRepository.toGetBalance(java.lang.String)

How to get value of a variable in a long delimited string

In a db table I have a string, such as...
Var1=0;CosType=1;DefaultType=US_Pass;DateYear=1;DateRange=1;ReportFormat=0
I want to create a VB.NET function that has 1 input var, the string (above) and the "token" to get the value for. (The return value is the value of the token.) For example, if I call it (LongString is the string above)....
txtValue.text = MyFunction(LongString,"DefaultType")
So, "US_Pass" would be returned.
What is the most efficient way to code MyFunction?
I've tried something like this...
return LongString.Substring(LongString.IndexOf(input_token) + 12)
I feel I'm close, but so far away.
Thanks!
This works as long as you know the key exists in your string:
public string MyFunction(string longString, string key)
{
return
longString
.Split(';')
.Select(x => x.Split('='))
.ToDictionary(x => x[0], x => x[1])[key];
}
With this code:
string longString = "Var1=0;CosType=1;DefaultType=US_Pass;DateYear=1;DateRange=1;ReportFormat=0";
Console.WriteLine(MyFunction(longString, "DefaultType"));
I get:
US_Pass
As VB.NET:
Public Function MyFunction(longString As String, key As String) As String
Return longString.Split(";"c).Select(Function(x) x.Split("="c)).ToDictionary(Function(x) x(0), Function(x) x(1))(key)
End Function
Split the string into parts at the semi-colons.
Dim parts As String() = LongString.Split(";")
Loop over the parts in a ForEach loop.
Find the part that StartsWith the the token value.
Find the equal sign (IndexOf) and take everything to the right of it (Substring).
That should give you enough to figure it out.
It's probably not a great idea to store data like this in your database. Hopefully you won't need to query these attributes from SQL.
In your case I would create a class to encapsulate the attributes. You pass in the string as a constructor parameter and let the class manage it.
Here's an example in C# that shouldn't be too hard to convert to VB:
public class AttributeCollection
{
private readonly Dictionary<string, string> _attrs;
public AttributeCollection(string values)
{
_attrs = (from v in values.Split(new[] {';'})
select v.Split(new[] {'='})).ToDictionary(i => i[0], i => i[1]);
}
public string this[string name]
{
get { return _attrs[name]; }
set { _attrs[name] = value; }
}
public override string ToString()
{
return string.Join(";", (from a in _attrs select a.Key + "=" + a.Value).ToArray());
}
}

how can i use sqlite rawQuery?

when I call select in other function, there is problem in line number 3.
Is it wrong?
public String[] select(int n){
db = helper.getReadableDatabase();
Cursor c = db.rawQuery("SELECT * FROM info WHERE number='" + n + "'", null);
}
The rawQuery() looks good, though usually you wouldn't quote integers as 'string literal'.
However, a non-void method must return a value and your method doesn't return anything. Add return null; to make it compile; implement a loop that builds a string array to return a non-null value.

NameValueCollection to URL Query?

I know i can do this
var nv = HttpUtility.ParseQueryString(req.RawUrl);
But is there a way to convert this back to a url?
var newUrl = HttpUtility.Something("/page", nv);
Simply calling ToString() on the NameValueCollection will return the name value pairs in a name1=value1&name2=value2 querystring ready format. Note that NameValueCollection types don't actually support this and it's misleading to suggest this, but the behavior works here due to the internal type that's actually returned, as explained below.
Thanks to #mjwills for pointing out that the HttpUtility.ParseQueryString method actually returns an internal HttpValueCollection object rather than a regular NameValueCollection (despite the documentation specifying NameValueCollection). The HttpValueCollection automatically encodes the querystring when using ToString(), so there's no need to write a routine that loops through the collection and uses the UrlEncode method. The desired result is already returned.
With the result in hand, you can then append it to the URL and redirect:
var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
string url = Request.Url.AbsolutePath + "?" + nameValues.ToString();
Response.Redirect(url);
Currently the only way to use a HttpValueCollection is by using the ParseQueryString method shown above (other than reflection, of course). It looks like this won't change since the Connect issue requesting this class be made public has been closed with a status of "won't fix."
As an aside, you can call the Add, Set, and Remove methods on nameValues to modify any of the querystring items before appending it. If you're interested in that see my response to another question.
string q = String.Join("&",
nvc.AllKeys.Select(a => a + "=" + HttpUtility.UrlEncode(nvc[a])));
Make an extension method that uses a couple of loops. I prefer this solution because it's readable (no linq), doesn't require System.Web.HttpUtility, and it supports duplicate keys.
public static string ToQueryString(this NameValueCollection nvc)
{
if (nvc == null) return string.Empty;
StringBuilder sb = new StringBuilder();
foreach (string key in nvc.Keys)
{
if (string.IsNullOrWhiteSpace(key)) continue;
string[] values = nvc.GetValues(key);
if (values == null) continue;
foreach (string value in values)
{
sb.Append(sb.Length == 0 ? "?" : "&");
sb.AppendFormat("{0}={1}", Uri.EscapeDataString(key), Uri.EscapeDataString(value));
}
}
return sb.ToString();
}
Example
var queryParams = new NameValueCollection()
{
{ "order_id", "0000" },
{ "item_id", "1111" },
{ "item_id", "2222" },
{ null, "skip entry with null key" },
{ "needs escaping", "special chars ? = &" },
{ "skip entry with null value", null }
};
Console.WriteLine(queryParams.ToQueryString());
Output
?order_id=0000&item_id=1111&item_id=2222&needs%20escaping=special%20chars%20%3F%20%3D%20%26
This should work without too much code:
NameValueCollection nameValues = HttpUtility.ParseQueryString(String.Empty);
nameValues.Add(Request.QueryString);
// modify nameValues if desired
var newUrl = "/page?" + nameValues;
The idea is to use HttpUtility.ParseQueryString to generate an empty collection of type HttpValueCollection. This class is a subclass of NameValueCollection that is marked as internal so that your code cannot easily create an instance of it.
The nice thing about HttpValueCollection is that the ToString method takes care of the encoding for you. By leveraging the NameValueCollection.Add(NameValueCollection) method, you can add the existing query string parameters to your newly created object without having to first convert the Request.QueryString collection into a url-encoded string, then parsing it back into a collection.
This technique can be exposed as an extension method as well:
public static string ToQueryString(this NameValueCollection nameValueCollection)
{
NameValueCollection httpValueCollection = HttpUtility.ParseQueryString(String.Empty);
httpValueCollection.Add(nameValueCollection);
return httpValueCollection.ToString();
}
Actually, you should encode the key too, not just value.
string q = String.Join("&",
nvc.AllKeys.Select(a => $"{HttpUtility.UrlEncode(a)}={HttpUtility.UrlEncode(nvc[a])}"));
Because a NameValueCollection can have multiple values for the same key, if you are concerned with the format of the querystring (since it will be returned as comma-separated values rather than "array notation") you may consider the following.
Example
var nvc = new NameValueCollection();
nvc.Add("key1", "val1");
nvc.Add("key2", "val2");
nvc.Add("empty", null);
nvc.Add("key2", "val2b");
Turn into: key1=val1&key2[]=val2&empty&key2[]=val2b rather than key1=val1&key2=val2,val2b&empty.
Code
string qs = string.Join("&",
// "loop" the keys
nvc.AllKeys.SelectMany(k => {
// "loop" the values
var values = nvc.GetValues(k);
if(values == null) return new[]{ k };
return nvc.GetValues(k).Select( (v,i) =>
// 'gracefully' handle formatting
// when there's 1 or more values
string.Format(
values.Length > 1
// pick your array format: k[i]=v or k[]=v, etc
? "{0}[]={1}"
: "{0}={1}"
, k, HttpUtility.UrlEncode(v), i)
);
})
);
or if you don't like Linq so much...
string qs = nvc.ToQueryString(); // using...
public static class UrlExtensions {
public static string ToQueryString(this NameValueCollection nvc) {
return string.Join("&", nvc.GetUrlList());
}
public static IEnumerable<string> GetUrlList(this NameValueCollection nvc) {
foreach(var k in nvc.AllKeys) {
var values = nvc.GetValues(k);
if(values == null) { yield return k; continue; }
for(int i = 0; i < values.Length; i++) {
yield return
// 'gracefully' handle formatting
// when there's 1 or more values
string.Format(
values.Length > 1
// pick your array format: k[i]=v or k[]=v, etc
? "{0}[]={1}"
: "{0}={1}"
, k, HttpUtility.UrlEncode(values[i]), i);
}
}
}
}
As has been pointed out in comments already, with the exception of this answer most of the other answers address the scenario (Request.QueryString is an HttpValueCollection, "not" a NameValueCollection) rather than the literal question.
Update: addressed null value issue from comment.
The short answer is to use .ToString() on the NameValueCollection and combine it with the original url.
However, I'd like to point out a few things:
You cant use HttpUtility.ParseQueryString on Request.RawUrl. The ParseQueryString() method is looking for a value like this: ?var=value&var2=value2.
If you want to get a NameValueCollection of the QueryString parameters just use Request.QueryString().
var nv = Request.QueryString;
To rebuild the URL just use nv.ToString().
string url = String.Format("{0}?{1}", Request.Path, nv.ToString());
If you are trying to parse a url string instead of using the Request object use Uri and the HttpUtility.ParseQueryString method.
Uri uri = new Uri("<THE URL>");
var nv = HttpUtility.ParseQueryString(uri.Query);
string url = String.Format("{0}?{1}", uri.AbsolutePath, nv.ToString());
I always use UriBuilder to convert an url with a querystring back to a valid and properly encoded url.
var url = "http://my-link.com?foo=bar";
var uriBuilder = new UriBuilder(url);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
query.Add("yep", "foo&bar");
uriBuilder.Query = query.ToString();
var result = uriBuilder.ToString();
// http://my-link.com:80/?foo=bar&yep=foo%26bar
In AspNet Core 2.0 you can use QueryHelpers AddQueryString method.
As #Atchitutchuk suggested, you can use QueryHelpers.AddQueryString in ASP.NET Core:
public string FormatParameters(NameValueCollection parameters)
{
var queryString = "";
foreach (var key in parameters.AllKeys)
{
foreach (var value in parameters.GetValues(key))
{
queryString = QueryHelpers.AddQueryString(queryString, key, value);
}
};
return queryString.TrimStart('?');
}
This did the trick for me:
public ActionResult SetLanguage(string language = "fr_FR")
{
Request.UrlReferrer.TryReadQueryAs(out RouteValueDictionary parameters);
parameters["language"] = language;
return RedirectToAction("Index", parameters);
}
You can use.
var ur = new Uri("/page",UriKind.Relative);
if this nv is of type string you can append to the uri first parameter.
Like
var ur2 = new Uri("/page?"+nv.ToString(),UriKind.Relative);

Code practice to handle empty result set in Linq to custom list

My Question is how do I handle a null set returned from a linq query if I am loading it into a custom class.
example
queryResults = queryResults.Select(p => new specialItems(p.ID, p.SECTION, p.PROGRAM, p.EVENT).ToList<specialItems>();
...
public class specialItems
{
public string Id { get; set; }
public string Section { get; set; }
public string Program { get; set; }
public string Event { get; set; }
public courseItems(string id, string section, string program, string event)
{
this.Id = id;
this.Section = section;
this.Program = program;
this.Event = event;
}
}
Currently this query works great until the result set is empty, then I get:
"Object reference not set to an instance of an object."
I need the query to return an empty List if the result set is empty.
UPDATE - Asided from the invalid redeclaration of a variable (fixed) I did find that the issue was higher up in the initial construction of the linq query. This became apparent when I received several good suggestions and removed the error. Once I fixed the original query things worked swimmingly.
Use the null coalescing operator (??).
List<specialItems> queryResults = queryResults.Select(p => new specialItems(p.ID, p.SECTION, p.PROGRAM, p.EVENT).ToList<specialItems>() ?? new List<specialItems>();
EDIT: Yeah, looking at what you have there a little closer, it's the ToList that's blowing up when this happens. You might have to split it up a bit.
var temp = queryResults.Select(p => new specialItems(p.ID, p.SECTION, p.PROGRAM, p.EVENT);
List<specialItems> results = temp == null ? new List<specialItems>() : temp.ToList<SpecialItems>();
Have to do it this way, because there's no good spot to put the null coalescing operator in this case.
Robaticus is mostly right, use the null coalescing operator (??). Howerver, since you didn't include the stack trace, I assume your code is throwing because queryResults is initially null. By the time you get to the ?? operator, you've already thrown the exception, because you tried to dereference queryResults.
Also, the code you have doesn't make a ton of sense, because queryResults is already defined within that scope by the time you get to that line. You can't redefine a variable that has already been declared locally in that scope.
List<SpecialItems> queryResults = GetSomeResults();
queryResults = (queryResults ?? new List<SpecialItems>())
.Select(p => new SpecialItems(p.ID, p.SECTION, p.PROGRAM, p.EVENT))
.ToList<SpecialItems>();
If you can get the function or line that spits out the original version of queryResults to return an empty list instead of null, then try to do that, or coalesce the results on that line. That's probably better than having all that code on the query line :)
List<SpecialItems> queryResults = GetSomeResults() ?? new List<SpecialItems>();
queryResults = queryResults
.Select(p => new SpecialItems(p.ID, p.SECTION, p.PROGRAM, p.EVENT))
.ToList<SpecialItems>();
Linq returns an empty list if there are no results, never null. Therefore, the problem is certainly not that queryResults.Select() returns null.
What is probably going on is that we're looking at a lazily evaluated linq-to-objects 'query'. ToList() triggers the evaluation of it, and probably the nullreference exception occurs in a lambda expression higher up the chain.
Neither Enumerable.Select, nor Queryable.Select, nor Enumerable.ToList return null.
The query is not realized until ToList enumerates it. During that enumeration, a null reference exception is occuring due to code you have not posted in the question.
Consider this code with and without the commented line:
List<int> source = Enumerable.Range(1, 10).ToList();
IEnumerable<int> query = null;
try
{
query = source.Where(i => 1 / i > 0);
}
catch(Exception ex)
{
Console.WriteLine("Exception was caught {0}", ex.Message);
}
// source.Add(0);
List<int> result = query.ToList();
Consider this code with and without the commented line:
DataContext myDC = new DataContext();
string name = null;
IQueryable<Person> query = myDC.Persons.Where(p => p.Name.StartsWith(name));
// name = "Zz";
List<Person> result = query.ToList();

Resources