Categories
discuss

Regular expression to match non-ASCII characters?

What is the easiest way to match non-ASCII characters in a regex? I would like to match all words individually in an input string, but the language may not be English, so I will need to match things like ü, ö, ß, and ñ. Also, this is in Javascript/jQuery, so any solution will need to apply to that.

Answer

This should do it:

[^x00-x7F]+

It matches any character which is not contained in the ASCII character set (0-127, i.e. 0x0 to 0x7F).

You can do the same thing with Unicode:

[^u0000-u007F]+

For unicode you can look at this 2 resources:

Categories
discuss

Creating non-reverse-engineerable Java programs

Is there a way to deploy a Java program in a format that is not reverse-engineerable?

I know how to convert my application into an executable JAR file, but I want to make sure that the code cannot be reverse engineered, or at least, not easily.

Obfuscation of the source code doesn’t count… it makes it harder to understand the code, but does not hide it.

A related question is How to lock compiled Java classes to prevent decompilation?


Once I’ve completed the program, I would still have access to the original source, so maintaining the application would not be the problem. If the application is distributed, I would not want any of the users to be able to decompile it. Obfuscation does not achieve this as the users would still be able to decompile it, and while they would have difficulty following the action flows, they would be able to see the code, and potentially take information out of it.

What I’m concerned about is if there is any information in the code relating to remote access. There is a host to which the application connects using a user-id and password provided by the user. Is there a way to hide the host’s address from the user, if that address is located inside the source code?

Answer

You could obfuscate your JAR file with YGuard. It doesn’t obfuscate your source code, but the compiled classes, so there is no problem about maintaining the code later.

If you want to hide some string, you could encrypt it, making it harder to get it through looking at the source code (it is even better if you obfuscate the JAR file).

Categories
discuss

annotation based Spring bean validation

I’m investigating an annotation-based approach to validating Spring beans using spring modules. In this tutorial, the following bean (getters and setters omitted) is used as an example:

public final class User {  

  @NotBlank  
  @Length(max = 80)  
  private String name;  

  @NotBlank  
  @Email  
  @Length(max = 80)  
  private String email;  

  @NotBlank  
  @Length(max = 4000)  
  private String text;  
}

The error message that is used if a particular validation rule is disobeyed should follow this format:

bean-class.bean-propery[validation-rule]=Validation Error message

Examples for the class shown above include:

User.email[not.blank]=Please enter your e-mail address.  
User.email[email]=Please enter a valid e-mail address.  
User.email[length]=Please enter no more than {2} characters.

The fact that the message keys contain the class name presents a couple of problems:

  1. If the class is renamed, the message keys also need to be changed
  2. If I have another class (e.g. Person) with an email property that is validated identically to User.email, I need to duplicate the messages, e.g.

    Person.email[not.blank]=Please enter your e-mail address.
    Person.email[email]=Please enter a valid e-mail address.
    Person.email[length]=Please enter no more than {2} characters.

In fact, the documentation claims that is possible to configure a default message for a particular rule (e.g. @Email) like this:

email=email address is invalid

This default message should be used if a bean-specific message for the rule cannot be found. However, my experience is that this simply does not work.

An alternative mechanism for avoiding duplicate messages is to pass the key of the error message to the rule annotation. For example, assume I have defined the following default error message for the @Email rule

badEmail=Email address is invalid

This message should be used if I annotate the relevant property like this:

@Email(errorCode="badEmail")
private String email;

However I tried this, out and again, it just doesn’t seem to work. Has anyone found a way to avoid duplicating error messages when using this validation framework?

Answer

I took a quick look at the BeanValidator API, and it looks like you might want to try the errorCodeConverter property.

You would need to implement your own ErrorCodeConverter, or use one of the provided implementations?

....
<bean id="validator" class="org.springmodules.validation.bean.BeanValidator"
    p:configurationLoader-ref="configurationLoader"
    p:errorCodeConverter-ref="errorCodeConverter" />

<bean id="errorCodeConverter" class="contact.MyErrorCodeConverter" />
....

Note: configurationLoader is another bean defined in the config XML used in the tutorial

Example converter:

package contact;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springmodules.validation.bean.converter.ErrorCodeConverter;

public class MyErrorCodeConverter implements ErrorCodeConverter {

    private Log log = LogFactory.getLog(MyErrorCodeConverter.class);

    @Override
    public String convertPropertyErrorCode(String errorCode, Class clazz, String property) {
        log.error(String.format("Property %s %s %s", errorCode, clazz.getClass().getName(), property));
        return errorCode;  // <------ use the errorCode only
    }

    @Override
    public String convertGlobalErrorCode(String errorCode, Class clazz) {
        log.error(String.format("Global %s %s", errorCode, clazz.getClass().getName()));
        return errorCode;
    }
}

Now the properties should work:

MyEmailErrorCode=Bad email

class Foo {
    @Email(errorCode="MyEmailErrorCode")
    String email
}
Categories
discuss

Loading animated gif from JAR file into ImageIcon

I’m trying to create a ImageIcon from a animated gif stored in a jar file.

ImageIcon imageIcon = new ImageIcon(ImageIO.read(MyClass.class.getClassLoader().getResourceAsStream("animated.gif")));

The image loads, but only the first frame of the animated gif. The animation does not play.

If I load the animated gif from a file on the filesystem, everything works as expected. The animation plays through all the of frames. So this works:

ImageIcon imageIcon = new ImageIcon("/path/on/filesystem/animated.gif");

How can I load an animated gif into an ImageIcon from a jar file?

EDIT: Here is a complete test case, why doesn’t this display the animation?

import javax.imageio.ImageIO;
import javax.swing.*;

public class AnimationTest extends JFrame {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                AnimationTest test = new AnimationTest();
                test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                test.setVisible(true);
            }
        });
    }

    public AnimationTest() {
        super();
        try {
            JLabel label = new JLabel();
            ImageIcon imageIcon = new ImageIcon(ImageIO.read(AnimationTest.class.getClassLoader().getResourceAsStream("animated.gif")));
            label.setIcon(imageIcon);
            imageIcon.setImageObserver(label);
            add(label);
            pack();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Answer

This reads gif animation from inputStream

InputStream in = ...;
Image image = Toolkit.getDefaultToolkit().createImage(org.apache.commons.io.IOUtils.toByteArray(in));
Categories
discuss

Accessing constant values from an Apache Velocity template?

Is it possible to access a constant value (i.e. a public static final variable defined in a Java class) from a Velocity template?

I would like to be able to write something like this:

#if ($a lt Long.MAX_VALUE)

but this is apparently not the right syntax.

Answer

There are a number of ways.

1) You can put the values directly in the context.

2) You can use the FieldMethodizer to make all public static fields in a class available.

3) You can use a custom Uberspect implementation that includes public static fields in the lookup order.

4) You can use the FieldTool from VelocityTools.

I recommend 1 for a few values, 2 for a few classes, 3 for lots of classes and values, and 4 if you are already using VelocityTools and would otherwise use 1 or 2.

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..