Grails greek encoding for 1 field - database

The problem is that when i to save the data(in greek) on the server the title field data look's like this ??????????? but it must be Καλώς ορίσατε.
ControllerCode
#Secured(['ROLE_EDITOR'])
def saveArticle = {
def member = springSecurityService.currentUser
if(request.post){
params.member = member
def post = new Post(params)
if(post.save())
{
redirect(action: "page",id: post.id)
}
else
{
return post.errors
}
}
else
{
redirect(action: "addArticle")
}
}
Post domain class
class Post {
String title
String body
Members member
Date created_at = new Date()
static constraints = {}
}
the strange is that the field body returns correctly greek language and not like title.

the answer is jdbc:mysql://localhost/dev?useUnicode=yes&characterEncoding=UTF-8
the ?useUnicode=yes&characterEncoding=UTF-8 in the connection string..

Related

How to select date from Telerik (kendo) date picker

I am having problem selecting a specific day in the pickDay() method. When I specify 4, it keeps selecting 1. When println date[DAY_OF_MONTH] it prints out 4.
I'm calling it with this keyword :-
CustomKeywords.'custom.keywords.RadDatePicker.pickDate'('Object
Repository/Telerik/RadDateLightWeightPage/img_CalendarPopupButton',
'06/04/2019')
class RadDatePicker {
Date date;
String obj;
RadDatePicker() {
}
RadDatePicker(String object, String input_date) {
this.obj = object;
date = new Date().parse("MM/dd/yyyy", input_date)
}
def openCalendar() {...}
def displayMonth() {...}
def displayYear() {...}
def displayDate() {
return new Date().parse("MMM/yyyy", displayMonth() + "/" + displayYear())
}
def pickYear(){...}
def pickMonth(){...}
def pickDay() {
println date[DAY_OF_MONTH]
WebUI.click(findTestObject('Object Repository/Telerik/RadDateLightWeightPage/a_dayPicker', [('day') : date[DAY_OF_MONTH]]))
}
def pickDate() {
pickYear()
pickMonth()
pickDay()
}
#Keyword
def pickDate(String obj, String date) {
def pick = new RadDatePicker(obj, date)
pick.openCalendar()
pick.pickDate()
}
}
Here is the calendar and the HTML
calendar
html
I found a way around it by implementing WebDriver and looking for the specific xpath that contained the day I was looking for, here's the code
def pickDay() {
WebDriver driver = DriverFactory.getWebDriver();;
WebElement datepicker = driver.findElement(By.xpath("//*[#id='ctl00_cphContent_RadDatePicker1_calendar_Top']"));
datepicker.findElement(By.xpath("//*[(text()=" + date[DAY_OF_MONTH] + ")]")).click();
}

NHibernate Convert query to async query

I'm looking at async-ifying some of our existing code. Unfortunately my experience with NHibernate is lacking. Most of the NHibernate stuff has been easy, considering NHibernate 5 has a lot of support for async. I am, however, stuck.
Originally, we do something like this using our Dependency Injection:
private readonly IRepository repository;
public MovieRepository(IRepository repository)
{
this.repository = repository;
}
public Movie Get(int id)
{
return (from movie in repository.Query<Movie>()
select new Movie
{
ID = movie.ID,
Title = movie.Title,
Genre = new Genre
{
ID = movie.Genre.ID,
Name = movie.Genre.Name,
},
MaleLead = movie.MaleLead,
FemaleLead = movie.FemaleLead,
}).FirstOrDefault();
}
//Repository Query method in Repository.cs
public IQueryable<TEntity> Query<TEntity>() where TEntity : OurEntity
{
session = session.OpenSession();
return from entity in session.Query<TEntity>() select entity;
}
This works great for our current uses. We write things this way to maintain control over our queries, especially related to more complex objects, ensuring we get back exactly what we need.
I've tried a few things, like making the Query method return a Task< List< TEntity>> and using the ToListAsync() method, however because I am returning it as that kind of list I cannot query on it.
I'm sure I've missed something. If anyone can help me out, I would appreciate it.
You need to use FirstOrDefaultAsync in this case.
public async Task<Movie> Get(int id)
{
return await (from movie in repository.Query<Movie>()
select new Movie
{
ID = movie.ID,
Title = movie.Title,
Genre = new Genre
{
ID = movie.Genre.ID,
Name = movie.Genre.Name,
},
MaleLead = movie.MaleLead,
FemaleLead = movie.FemaleLead,
}).FirstOrDefaultAsync();
}
Add this using statement to your file
using NHibernate.Linq;
Then you can change your method to
public async Task<Movie> Get(int id)
{
return await (from movie in repository.Query<Movie>()
select new Movie
{
ID = movie.ID,
Title = movie.Title,
Genre = new Genre
{
ID = movie.Genre.ID,
Name = movie.Genre.Name,
},
MaleLead = movie.MaleLead,
FemaleLead = movie.FemaleLead,
}).FirstOrDefaultAsync();
}
NB: This is only available from NHibernate 5
Addendum:
The code you have in Repository.cs can be simplified to something like this:
//Repository Query method in Repository.cs
public IQueryable<TEntity> Query<TEntity>() where TEntity : OurEntity
{
//session = session.OpenSession(); //this is obviously wrong, but it's beside the point
var session = sessionFactory.OpenSession();
return session.Query<TEntity>(); //the fix
}

AngularJs, how to set empty string in URL

In the controller I have below function:
#RequestMapping(value = "administrator/listAuthor/{authorName}/{pageNo}", method = { RequestMethod.GET,
RequestMethod.POST }, produces = "application/json")
public List<Author> listAuthors(#PathVariable(value = "authorName") String authorName,
#PathVariable(value = "pageNo") Integer pageNo) {
try {
if (authorName == null) {
authorName = "";
}
if (pageNo == null) {
pageNo = 1;
}
return adminService.listAuthor(authorName, pageNo);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
This function fetches and returns data from mysql database based on "authorName" and "pageNo". For example, when "authorName = a" and "pageNo = 1" I have:
Data I get when "authorName = a" and "pageNo = 1"
Now I want to set "authorName" as ""(empty string), so that I can fetch all the data from mysql database (because the SQL statement "%+""+%" in backend will return all the data).
What can I do if I want to set authorName = empty string?
http://localhost:8080/spring/administrator/listAuthor/{empty string}/1
Thanks in advance!
I don't think that you can encode empty sting to url, what I suggest you to do is to declare some constant that will be your code to empty string - such as null.
Example:
administrator/listAuthor/null/90
Afterwards , on server side, check if authorName is null and set local parameter with empty stirng accordingly.

read zip attachment in visualforce page

Hi all I am developing an app on salesforce.
I want to read the content of the file which is inside the zip attachment in visualforce page but without extracting the zip file.
How can I achieve this? Is there any way to do this?
Update for modified question:
Have a look at Handling Office Files and Zip Files in Apex – Part 2 by Andrew Fawcett.
There is a basic Knowledge Article on how to do this with an image that is stored in an Attachment. See How can I Display Base64 Data on page layout?
In this example the AttachmentID is passed via a query string paramemter, but you could look it up however works best for your requirement.
Visualforce page:
<apex:page controller="ViewImage" cache="true">
<img src="data:{!att.ContentType};base64,{!image}" />
</apex:page>
Controller:
public class ViewImage {
public Attachment att {
get {
if (att == null) {
String id = ApexPages.currentPage().getParameters().get('AttachmentID');
att = [SELECT Body, ContentType, Name FROM Attachment WHERE ID = :id];
}
return att;
}
private set;
}
public String image {
get {
return EncodingUtil.Base64Encode(att.body);
}
}
}
Hi all I have achieved this using JSzip library here is my code --
In apex page I have written javascript function --
function viewContent(){
var zip = null;
var zipFileName = null;
var zipFileNames = null;
data = "{!contentAsText}";
zip = new JSZip(data, {base64:true});
zipFileName = 'files.zip';
zipFileNames = [];
for(var zipfileName in zip.files){
zipFileNames.push(zipfileName);
if(zipfileName == 'index.html'){
var file = zip.files[zipfileName];
var data = file.data;
document.getElementById('contentdiv').innerHTML = data;
//var data = JSZipBase64.encode(file.data);
}
}
In controller --
public String contentAsText {get;set;}
List<Attachment> atts = [Select Id, Body from Attachment where name='files.zip' limit 1];
contentAsText = EncodingUtil.base64Encode(atts[0].Body);
This link will help you --
http://andyinthecloud.com/2012/12/09/handling-office-files-and-zip-files-in-apex-part-2/

The given key was not present in the dictionary solrnet

Please note: I know for the question SolrNet - The given key was not present in the dictionary and I have initialized solr object just like Mauricio suggests.
I am using solr 4.6.0 and solrnet build #173, .net framework 4.0 and VS2012 for development. For some unknown reason I am receiving error 'The given key was not present in the dictionary'. I have a document with that id in solr, I've checked via browser. It's a document like any other document. Why is error popping up? My code (I've made a comment on the place where the error happens):
//establishes connection with solr
private void ConnectToSolr()
{
try
{
if (_solr != null) return;
Startup.Init<Register>(SolrAddress);
_solr = ServiceLocator.Current.GetInstance<ISolrOperations<Register>>();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
//Returns snippets from solr as BindingSource
public BindingSource GetSnippets(string searchTerm, DateTime? startDate = null, DateTime? endDate = null)
{
ConnectToSolr();
string dateQuery = startDate == null
? ""
: endDate == null
? "savedate:\"" + convertDateToSolrFormat(startDate) + "\"" //only start date
: "savedate:[" + convertDateToSolrFormat(startDate) + " TO " +
convertDateToSolrFormat(endDate) + "]";//range between start and end date
string textQuery = string.IsNullOrEmpty(searchTerm) ? "text:*" : "text:*" + searchTerm + "*";
List<Register> list = new List<Register>();
SolrQueryResults<Register> results;
string currentId = "";
try
{
results = _solr.Query(textQuery,
new QueryOptions
{
Highlight = new HighlightingParameters
{
Fields = new[] { "*" },
},
ExtraParams = new Dictionary<string, string>
{
{"fq", dateQuery},
{"sort", "savedate desc"}
}
});
for (int i = 0; i < results.Highlights.Count; i++)
{
currentId = results[i].Id;
var h = results.Highlights[currentId];
if (h.Snippets.Count > 0)
{
list.Add(new Register//here the error "the given key was not present in the dictionary pops up
{
Id = currentId,
ContentLiteral = h.Snippets["content"].ToArray()[0].Trim(new[]{' ', '\n'}),
SaveDateLiteral = results[i].SaveDate.ToShortDateString()
});
}
}
BindingList<Register> bindingList = new BindingList<Register>(list);
BindingSource bindingSource = new BindingSource();
bindingSource.DataSource = bindingList;
return bindingSource;
}
catch(Exception e)
{
MessageBox.Show(string.Format("{0}\nId:{1}", e.Message, currentId), "Solr error");
return null;
}
}
I've found out what's causing the problem: saving empty documents into solr. If I make an empty query (with text:*) through solrnet (usually I do this if I want to see all saved documents) and empty document is one of saved docs, then 'The given key is not present in dictionary pops up'. If all of the documents have text in them, this error doesn't pop up.
If you document contains fields with types other than string and you index null value to a double or integer field you will get the same error.
solr query return the null field as:
<null name="fieldname"/>
should be
<double name="fieldname">0.0</double>
or
<double name="fieldname"/>

Resources