Categories
discuss

Remove unnecessary linebreaks on template output?

Using Play 2 I am realising a simple REST API, the output is plain text. My template looks like this:

@(items: Map[String,String]) 
@for((key, value) <- items) {
@value
@key
}

In the controller:

return ok(views.html.bla.render(itemsMap)).as("text/plain");

This gives the following output:

(empty line)
(empty line)
value
key
(empty line)
value
key

I want to get rid of the first 2 empty lines – is that possible?

Putting the for in the first line removes one of the empty lines at the top, however one still remains and for in the first line makes the template hard to read ): Thanks for any hint!

Answer

First off, if you use plain text, you should use txt templates (bla.scala.txt). They also automatically set text/plain; charset=utf-8 content type.

To trim the content, you can return the rendered content directly:

return ok(views.txt.bla.render(itemsMap).body().trim());

In case you want to render HTML content you’d need to change this manually:

return ok(views.html.ble.render().body().trim()).as("text/html; charset=utf-8");
Categories
discuss

What is most appropriate way to read all data from a text file in one go?

I have a text file and I want to read the entire contents of it into a String variable. The file is being opened as an InputStream as I am using Android’s assetManager.open() method.

What is the best practise way to read the entire contents into a String? I am currently wrapping the InputStream with an InputStreamReader and then a BufferedReader and using a while loop I read in the text line by line with the readLine() method.

Is there a better way of reading in this text considering I there is no requirement to read it in line by line, I’d like to get it all in one go if possible

Answer

One normally should not reinvent the wheel, so use the apache commons library, if the overhead is bearable on Android. Use org.apache.commons.io.IOUtils.toString.

InputStream in = new FileInputStream(new File("a.txt"));
String s = IOUtils.toString(in, "UTF-8");
Categories
discuss

How to prevent SQL Injection with JPA and Hibernate?

I am developing an application using hibernate. When I try to create a Login page, The problem of Sql Injection arises. I have the following code:

@Component
@Transactional(propagation = Propagation.SUPPORTS)
public class LoginInfoDAOImpl implements LoginInfoDAO{

@Autowired
private SessionFactory sessionFactory;      
@Override
public LoginInfo getLoginInfo(String userName,String password){
    List<LoginInfo> loginList = sessionFactory.getCurrentSession().createQuery("from LoginInfo where userName='"+userName+"' and password='"+password+"'").list();
    if(loginList!=null )
        return loginList.get(0);
    else return null;   
          }
      }

How will i prevent Sql Injection in this scenario ?The create table syntax of loginInfo table is as follows:

create table login_info
  (user_name varchar(16) not null primary key,
  pass_word varchar(16) not null); 

Answer

Query q = sessionFactory.getCurrentSession().createQuery("from LoginInfo where userName = :name");
q.setParameter("name", userName);
List<LoginInfo> loginList = q.list();

You have other options too, see this nice article from mkyong.

Categories
discuss

How do you get a contact photo through the contact provider in android 2.3.6?

I have this version that works for android 4 (String email is a gmail address):

private Uri getPhotoUriFromEmail(String email) {
    Uri u = null;
    String[] projection = { ContactsContract.CommonDataKinds.Email.PHOTO_URI };
    String photoUri;
    ContentResolver cr = context.getContentResolver();
    Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, projection,
            ContactsContract.CommonDataKinds.Email.ADDRESS + " = ?", 
            new String[]{email}, null);
    if (emailCur.moveToNext()) { 
        photoUri = emailCur.getString(
                emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.PHOTO_URI));
        u = Uri.parse(photoUri);
    }
    return u;
}

What is its 2.3.6 version? (Also shouldn’t the android SDK warn me about using API 11 when I set API 8 as my minimal API support? Because it didn’t…)

Answer

You can get the contact photo uri without using ContactsContract.CommonDataKinds.Email.PHOTO_URI this way:

private Uri getPhotoUriFromEmail(String email) {
    Uri u = null;
    String[] projection = { ContactsContract.CommonDataKinds.Photo.CONTACT_ID };
    String photoUri;
    ContentResolver cr = getContentResolver();
    Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, 
            projection,
            ContactsContract.CommonDataKinds.Email.ADDRESS + " = ?",
            new String[]{email}, null);
    if (emailCur.moveToNext()) {
        int columnIndex = emailCur.getColumnIndex(
                              ContactsContract.CommonDataKinds.Photo.CONTACT_ID);
        long contactId = emailCur.getLong(columnIndex);

        u = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, 
                                       contactId);
        u = Uri.withAppendedPath(u, 
                                ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
    }
    return u;
}

Alternatively, you can get the photo stream utilizing method ContactsContract.Contacts .openContactPhotoInputStream(ContentResolver, Uri) this way:

private InputStream getPhotoInputStreamFromEmail(String email) {
    Uri u = null;
    String[] projection = { ContactsContract.CommonDataKinds.Photo.CONTACT_ID };
    String photoUri;
    ContentResolver cr = getContentResolver();
    Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
            projection,
            ContactsContract.CommonDataKinds.Email.ADDRESS + " = ?",
            new String[]{email}, null);
    if (emailCur.moveToNext()) {
        int columnIndex = emailCur.getColumnIndex(
                ContactsContract.CommonDataKinds.Photo.CONTACT_ID);
        long contactId = emailCur.getLong(columnIndex);

        u = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,
                contactId);
        return ContactsContract.Contacts.openContactPhotoInputStream(cr, u);
    }
    return null;
}
Categories
discuss

Why is BigDecimal.equals specified to compare both value and scale individually?

This is not a question about how to compare two BigDecimal objects – I know that you can use compareTo instead of equals to do that, since equals is documented as:

Unlike compareTo, this method considers two BigDecimal objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).

The question is: why has the equals been specified in this seemingly counter-intuitive manner? That is, why is it important to be able to distinguish between 2.0 and 2.00?

It seems likely that there must be a reason for this, since the Comparable documentation, which specifies the compareTo method, states:

It is strongly recommended (though not required) that natural orderings be consistent with equals

I imagine there must be a good reason for ignoring this recommendation.

Answer

Because in some situations, an indication of precision (i.e. the margin of error) may be important.

For example, if you’re storing measurements made by two physical sensors, perhaps one is 10x more precise than the other. It may be important to represent this fact.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..