Author Archives: michael laffargue

About michael laffargue

I'm a Software Architect specialised in Java/J2EE.

VSCode: Make vscode-tslint analyze multiple files in a project

vscode-tslint allows you to get Tslint warnings/errors in the problems view.

Minimal Versions:

  • visualcode-tslint : 0.5.38
  • gulp-tslint : 6.1.1

Note that I use typescript@next and tslint@next.

The only problem is installing this extension will only show the problems of a file once you open it.
Here is how to get it work on your whole project and get problems for every files you want to analyze.

First you’ll need a task runner like Gulp or Grunt with a task that’ll run tslint on your project.
Here is an example for Gulp :

var gulp = require('gulp'),
    gulptslint = require("gulp-tslint");
 
gulp.task("tslint", function() {
    const options = { summarizeFailureOutput: true };
 
    return gulp.src("src/**/*.ts", { base: '.' })
        .pipe(gulptslint({"formatter": "vso"}))
        .pipe(gulptslint.report(options));
});

Running this task will give you an output like this :

 ##vso[task.logissue type=warning;sourcepath=data/model/whatever.ts;linenumber=24;columnnumber=5;code=member-access;]The class method 'serialize' must be marked either 'private', 'public', or 'protected'
 ##vso[task.logissue type=warning;sourcepath=data/model/whatever.ts;linenumber=42;columnnumber=9;code=one-line;]misplaced 'else'

Now to link this analyze with vscode-tslint you’ll need to create configure the task in vscode. This can be done by modifying in your workspace the file .vscode/tasks.json.
If this file doesn’t exist just launch (Ctrl+Shift+P) Tasks: Configure Task Runner.

Then you need to configure the tslint task it like this :

    {
      "taskName": "tslint",
      "args": [],
      "isBuildCommand": true,
      "isWatching": false,
      "problemMatcher": {
        "owner": "tslint",
        "fileLocation": [
          "relative",
          "${workspaceRoot}"
        ],
        "severity": "warning",
        "pattern": {
          "regexp": "^##vso\\[.+type=(.+);sourcepath=(.+);linenumber=(\\d+);columnnumber=(\\d+);.*\\](.+)$",
          "severity": 1,
          "file": 2,
          "line": 3,
          "column": 4,
          "message": 5
        }
      }
    }

Information:

  • owner should have value “tslint” so vscode-tslint can merge the task problem with it’s own analyze on file edition

AngularJS2: Send HTTP Post request with parameters to PHP

After some troubles trying to reach an old PHP server (Using $_POST to retrieve parameters) with a new Ionic2 project (so using AngularJS2 Http).
Here is what worked :

var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
 
var params = 'email=email@example.com&pwd=xxxxxx';
 
this.http.post('http://mysite.com/api', params , {headers: headers})
  .subscribe(
    data => console.log('Received:' + data),
    err => console.log(err),
    () => console.log('Call Complete')
  );

The important parts are :

  • The Content-Type (By default: plain/text which won’t work on PHP server side) set to application/x-www-form-urlencoded
  • Parameters should be passed as a Query String
  • Don’t forget the imports (Forgetting Headers won’t crash but you’ll send plain/text)
    import {Http, Headers} from 'angular2/http';

Windows: Bypass proxy max size limit using cURL

Bypass proxy max size limit using cURL


Your entreprise/college proxy forbid you to download large file ? Here might be the solution.

cURL

First you need to download cURL
Go to the download page and choose your file, I personally used : “Win64 ia64.zip” from Don Luchini

Chunk file evaluation

Evaluate your proxy limit (We take 150M for this example) –> 150*1024*1024 = 157286400

Evaluate the number of chunk you’ll need : FileSize/ProxyLimit
* For a 400M file would be : 400/150 = 2,667 –> 3

So we’ll use 3 chunks:

  1. 0-157286400
  2. 157286400+1 – 157286400*2
  3. (157286400*2)+1-end

So we’ll need 3 commands :

curl --range 0-<strong>157286400</strong> <em>FILENAME</em> --output 1.ext
curl --range 157286401-314572800 <em>FILENAME</em> --output 2.ext
curl --range 314572801- <em>FILENAME</em> --output 3.ext

Merge chunks

Open a command prompt and merge the files :

copy /B 1.ext+2.ext+3.ext <em>REAL_FILENAME.REAL_EXTENSION</em>

And here you go.

Note that if you want to use a proxy with cURL simply add :

--proxy [protocol://][user:password@]proxyhost[:port]

JAD: Recursive Java decompilation command

Recursive JAD decompilation

To decompile all the classes of a jar file, unzip the jar in a folder.

Then use this command:

jad -d . -s java -r **/*.class
 
  -d <dir> - directory for output files 
  -s       - output file extension (default: .jad) 
  -r       - restore package directory structure

JAD can be found here

JAVA 8 : Lambda Expressions. Tutorial, example

Lambda Expressions

Introduction

JAVA 8 introduces a new language : Lambda Expressions

It’s meant to simplify the syntax when one use an anonymous class containing only one method. These interfaces are known as function interfaces.

 

Use case

Suppose you have a list of Person (age, last-name, first-name) and you’re asked to create a method that filters and then prints that list from different criteria.

 

Pre java 8 approach

The idea is to create a method that will filter a list of Person depending on specific attributes.
To avoid having one method per export (exportAdults, exportChildren…) we’ll introduce an interface PersonFilter with one method :
boolean filter(Person p) that will return true if the given person is part of the export we want.

Let’s go:

private static void exportSpecificPopulation(String category, Collection&lt;Person&gt; persons, PersonFilter filter) {
  for (Person p : persons) {
    if (filter.filter(p)) {
      System.out.println(category + ": "+p.getLastname() + " "+ p.getFirstname() + " " + p.getAge());
    }
  }
}

The code to call this method would be:

// Export Adults
exportSpecificPopulation("adults", persons, 
  new PersonFilter {
    @Override
    public boolean filter(Person person) {
      return p.getAge()>=ADULT_LEGAL_AGE;
    }
  }
// Export Children
exportSpecificPopulation("children", persons, 
  new PersonFilter {
    @Override
    public boolean filter(Person person) {
      return p.getAge()<ADULT_LEGAL_AGE;
    }
  }

Not that readable huh! and only to get adults and children.

Java 8 approach

In Java 8 we keep the main export method and the interface. But since the interface only has one method Lambda Reflections can be used.

The example in Java 8


Here is how we use the Lambda Expressions in our example (See Lambda Expressions syntax below) :

exportPopulation("adults", persons, p -> p.getAge()>=ADULT_LEGAL_AGE);
exportPopulation("children", persons, p -> p.getAge()<ADULT_LEGAL_AGE);

Note that it’s equivalent to :

exportPopulation("adults", persons, (Person p) -> {return  p.getAge()>=ADULT_LEGAL_AGE;});
exportPopulation("children", persons, (Person p) -> {return  p.getAge()<ADULT_LEGAL_AGE;});

Lambda expression syntax

(from oracle)

A lambda expression consists of the following:

  • A comma-separated list of formal parameters enclosed in parentheses.

    Note: You can omit the data type of the parameters in a lambda expression. In addition, you can omit the parentheses if there is only one parameter.

  • The arrow token, ->
  • A body, which consists of a single expression or a statement block. This example uses the following expression:

    If you specify a single expression, then the Java runtime evaluates the expression and then returns its value.

    A return statement is not an expression; in a lambda expression, you must enclose statements in braces ({}). However, you do not have to enclose a void method invocation in braces. For example, the following is a valid lambda expression:

    email -> System.out.println(email)

Note that a lambda expression looks a lot like a method declaration; you can consider lambda expressions as anonymous methods—methods without a name.

Install Package Control from behind a proxy (SublimeText3)

The default install script is given by “Package Control” website :

The simplest method of installation is through the Sublime Text console. The console is accessed via the ctrl+` shortcut or the View > Show Console menu. Once open, paste the code into the console.

import urllib.request,os,hashlib; h = '7183a2d3e96f11eeadd761d777e62404e330c659d4bb41d3bdf022e94cab3cd0'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); by = urllib.request.urlopen( 'http://sublime.wbond.net/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); print('Error validating download (got %s instead of %s), please try manual install' % (dh, h)) if dh != h else open(os.path.join( ipp, pf), 'wb' ).write(by)

However if you’re behind a proxy you’ll have to add the proxy infos in the urllib.request.ProxyHandler() object creation like this :

urllib.request.ProxyHandler(
  {"http":"http://[proxy_user]:[proxy_password]@[proxy_IP]:[proxy_port]"}
)

Here is the online code you should modify (Replace [proxy_*] by their value):

import urllib.request,os,hashlib; h = '7183a2d3e96f11eeadd761d777e62404e330c659d4bb41d3bdf022e94cab3cd0'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler({"http":"http://[proxy_username]:[proxy_password]@[proxy_IP_or_host]:[proxy_port]"})) ); by = urllib.request.urlopen( 'http://sublime.wbond.net/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); print('Error validating download (got %s instead of %s), please try manual install' % (dh, h)) if dh != h else open(os.path.join( ipp, pf), 'wb' ).write(by);

___
You haven’t finished yet since you now should configure the proxy in Package Control configuration so it’ll be able to access internet :
Go to Preferences > Package Settings > Package Control > Settings – User
On first install it should be empty, just add these lines (Replace [proxy_*] by their value):

{
    "proxy_username":"[proxy_password]",
    "proxy_password":"[proxy_username]",
    "http_proxy":"[proxy_IP_or_host]:[proxy_port]",
    "https_proxy":"[proxy_IP_or_host]:[proxy_port]",
}

GWT “CssResource.style” possible values for class names

How to modify GWT generated class names

Use this configuration tag in the .gwt.xml file :

<set-configuration-property name="CssResource.style" value="pretty" />

CssResource.style


For those like me looking for all possible values, here is where to find them (at least in GWT 2.5.0) :
com.google.gwt.resources.rg.CssObfuscationStyle

pretty –> VERBOSE (true, false, true, true),
stable –> STABLE_FULL_CLASSNAME (true, true, true, true),
stable-shorttype –> STABLE_SHORT_CLASSNAME (true, true, true, false),
stable-notype –> STABLE_NO_CLASSNAME (true, true, false, false),
[default] –> OBFUSCATED (false, false, false, false);

The CssResource.style argument values

XXXXXXXX (isPretty, isStable, showClassName, showPackageName)

The rules

If you set isPretty to false, other values won’t be read and OBFUSCATED name will be used.
If you set showClassName to false, showPackageName won’t be used.
If you set isStable to false, then the generated class name will have the obfuscated name prepended.

play framework 2.0 error : Connection timed out

Problem:
When trying to launch the play framework you get errors about connection timed out trying to retrieve “ivy.xml”

D:\frameworks\play\play-2.0\todolist>play
[info] Loading project definition from D:\frameworks\play\play-2.0\todolist\project
[error] Server access Error: Connection timed out: connect url=http://repo.typesafe.com/typesafe/ivy-releases/org.hibernate/hibernate-validator/4.2.0.Final/ivys/ivy.xml
[error] Server access Error: Connection timed out: connect url=http://repo.typesafe.com/typesafe/ivy-releases/javax.validation/validation-api/1.0.0.GA/ivys/ivy.xml
[error] Server access Error: Connection timed out: connect url=http://repo.typesafe.com/typesafe/ivy-releases/org.springframework/spring-context/3.0.7.RELEASE/ivys/ivy.xml
[error] Server access Error: Connection timed out: connect url=http://repo.typesafe.com/typesafe/ivy-releases/org.springframework/spring-core/3.0.7.RELEASE/ivys/ivy.xml
...

Solution

  1. Ensure your firewall isn’t blocking the requests
  2. You’re certainly behind a proxy and you need to configure it

Modify the last line of the build.bat file, adding those options to the java command.
Modifying the variables :MyProxyAccount,MyProxyPwd,MyProxyIp,MyProxyPort to suit your needs

-Dhttp.proxyUser=<MyProxyAccount>
-Dhttp.proxyPassword=<MyProxyPwd>
-Dhttp.proxyHost=<MyProxyIp>
-Dhttp.proxyPort=<MyProxyPort>

WordPress: Blank page with only one word : “error”

So you were happily using your WordPress website (certainly using the login interface, or trying to test some URL) and now all you’ve got is a blank page with a word : “error”.

I’m sure you want to panic and cry but don’t. There’s certainly a solution!

I’m pretty sure you’re using the “Better WP Security” plugin and didn’t really look at it in details.
Well here are some facts:

  • By default, if in a period of 5 minutes you try 5 times to connect from the same host and fail you’ll be “blocked” for 15 minutes
  • By default, if in a period of 5 minutes you try 10 times to connect as the same user and fail you’ll be “blocked” for 15 minutes
  • By default, if in a period of 5 minutes you try 20 times to get an invalid page (Error 404) you’ll be “blocked” for 15 minutes

Note that by default you’ll be banned definitely if you get “blocked” 3 times for the same action (login or 404)