Tuesday, March 10, 2015

Setup static web site on AWS EC2

Allow HTTP 80 port redirection from public IP to your private server, by default only 22 port is setup:


sudo yum install mc


desable SElinux
/etc/selinux/config
SELINUX=disabled


restart SERVER:
reboot


vi /etc/sysconfig/iptables
-A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
service iptables restart


http://dev.antoinesolutions.com/apache-server

How to install Apache Server on CentOS, RedHat, Linux

Install Apache HTTP Server
yum install httpd
Note: This is typically installed with CentOS by default

How to configure Apache Server on CentOS, RedHat, Linux

Set the apache service to start on boot
chkconfig --levels 235 httpd on
Enable name-based virtual hosting on port 80
Open the httpd configuration file located at /etc/httpd/conf/httpd.conf

ErrorLog /www/logs/error_log
CustomLog /www/logs/access_log combined
ServerName 54.164.21.75:80
DocumentRoot "/www"

Save the file
Restart the Apache HTTP Server daemon
service httpd restart



 In Browser :
http://54.164.21.75/ should show apapche welcome page


To make Authentication for one user by password:
http://www.cyberciti.biz/faq/howto-setup-apache-password-protect-directory-with-htaccess-file/
http://weavervsworld.com/docs/other/passprotect.html

What is better inversion in method names of inversion operator in usage ?

What is better inversion in method names of in usage ? What criteria we could use measure that ?

For private methods it might be not a problem, but mostly affects API and public methods

@Override
public void visitToken(DetailAST aAst) {
DetailAST conditionExpressionAst = aAst.findFirstToken(TokenTypes.EXPR);
switch (aAst.getType()) {
case TokenTypes.LITERAL_RETURN:
if (isNonEmptyReturn(aAst)) {
DetailAST inversionAst = getInversion(conditionExpressionAst);
if (isAvoidableInversion(inversionAst)) {
log(inversionAst);
}
}
break;
case TokenTypes.LITERAL_WHILE:
case TokenTypes.LITERAL_DO:
case TokenTypes.LITERAL_IF:
DetailAST inversionAst = getInversion(conditionExpressionAst);
if (isAvoidableInversion(inversionAst)) {
log(inversionAst);
}
break;
case TokenTypes.FOR_CONDITION:
if (isNonEmptyForCondition(aAst)) {
inversionAst = getInversion(conditionExpressionAst);
if (isAvoidableInversion(inversionAst)) {
log(inversionAst);
}
}
break;
default:
final String exceptionMsg = "Unexpected Token Type - "
+ TokenTypes.getTokenName(aAst.getType());
throw new IllegalStateException(exceptionMsg);
}
}
code:
/**
* Checks if return statement is not empty
* @param aReturnAst
*/
private static boolean isNonEmptyReturn(DetailAST aReturnAst) {
return aReturnAst.findFirstToken(TokenTypes.EXPR) != null;
}
/**
* Checks if condition in for-loop is not empty
* @param aForConditionAst
*/
private static boolean isNonEmptyForCondition(DetailAST aForConditionAst) {
return aForConditionAst.getFirstChild() != null;
}

Some code could not be written without "NOT"/"NON" , Example:

Syntactically parallel elements in indentation


Why it is matter ?

https://google-styleguide.googlecode.com/svn-history/r130/trunk/javaguide.html#s4.5.1-line-wrapping-where-to-break
"The prime directive of line-wrapping is: prefer to break at a higher syntactic level."

https://google-styleguide.googlecode.com/svn-history/r130/trunk/javaguide.html#s4.5.2-line-wrapping-indent
"When there are multiple continuation lines, indentation may be varied beyond +4 as desired. In general, two continuation lines use the same indentation level if and only if they begin with syntactically parallel elements."

Cases from real code with bad indentation:
1)

 if ((rcurly != null) && !level.accept(rcurlyPos)
           && (rcurlyMustStart() || startsLine(rcurly))
      && !areOnSameLine(rcurly, lcurly))


2)
details.append("Focused : ").append(file.getPath())
.append(", start date :")
.append(", end date : ");

3)
if (toVisitAst != null
&& (toVisitAst.getParent().getParent().getNextSibling() == null
|| toVisitAst.getParent().getParent().getNextSibling().getType()
== TokenTypes.RCURLY)
&& toVisitAst.getType() == TokenTypes.LITERAL_RETURN
&& toVisitAst.getParent().getNextSibling()== null) { }


===========================


resulted in https://github.com/checkstyle/checkstyle/issues/270

Static Import Check for Checkstyle

Static import: http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html

Command to catch code:
 grep --include=*.java --exclude={*Test.java,Test*.java,*IT.java} -rw -m 1 . -e "import static"

we can not forbid static import usage at all, it is useful, we need to limit it, So we will forbid all static imports that are not applying to following options:

1) allow in target member is used more then X times.
see example in point "3)" and imagine there is a lot of such code blocks, that option could allow static import for "psvBuilder".

2) allow in Class of target member could brake Line-limit more then X times.
 that it is not required as will hide too much code that should be formatted appropriately

3) Allow in complicated statements with a lot of inner methods calls in arguments.

import static com.commons.domain.DsvFileDefinition.psvBuilder;
import static com.commons.domain.FeedDefinition.feedBuilder;
import static com.commons.domain.ZipFileDefinition.zipBuilder;

private static FeedDefinition getFeedDefinition() {
return feedBuilder("Premium", "/datafeeds/", "NAME", "NAME1").addFile(
zipBuilder("premium").addFiles(of(
psvBuilder("address").build(),
psvBuilder("entity").build(),public enum BetPosition {
    // ...
    STRAIGHT_32(96, ...),
    STRAIGHT_33(142, ...),
    STRAIGHT_34(52, ...),
    BET_1_2(53, ...),
    BET_4_5(55, ...),
    // ... long list of enum values

psvBuilder("entity_changes").build(),
psvBuilder("entity_identifiers").build(),
psvBuilder("entity_names").build(),
psvBuilder("entity_profiles").build(),
psvBuilder("entity_relationships").build(),
psvBuilder("entity_structure").build(),
psvBuilder("entity_map").build(),
psvBuilder("listing_map").build())).build()
).build();


4) Ignore list of classes/methods that team presume distinctive and whole team know.
"com.google.common.base.Strings,com.google.common.base.XXXXXXX"

import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.base.Strings.nullToEmpty;

this.schemaName = nullToEmpty(schemaName);
if (isNullOrEmpty(tableName)) {
throw new IllegalArgumentException("tableName could not be empty");
}
this.tableName = tableName;

5)
Invalid usage:
import static com.google.common.collect.Iterables.getFirst;
....

TreeSet<Name> names = Sets.newTreeSet(new ILifeCycleEntityComparator());
if (names.isEmpty()) {
// do smth 
} else {
Name firstName = getFirst(tradenames, null);public enum BetPosition {
    // ...
    STRAIGHT_32(96, ...),
    STRAIGHT_33(142, ...),
    STRAIGHT_34(52, ...),
    BET_1_2(53, ...),
    BET_4_5(55, ...),
    // ... long list of enum values

// do smth else
}

6)
Here looks like static import allow to keep lines short.

import static com.revere.det.core.domain.validation.ValidationUtils.formatPeriod;

details.append("Focused sector: ").append(focusSector.getPath())
.append(", start date of focus: ").append(formatPeriod(focus.getStartDate()))
.append(", end date of focus: ").append(formatPeriod(focus.getEndDate()))
.append(NEW_LINE);

7)
Inappropriate - used only one time in whole file.

import static org.joda.time.LocalDateTime.now;

public class Builder extends DataBuilder {

private static final java.sql.Date THREE_YEARS_AGO = new java.sql.Date(now().minusYears(3).toDate().getTime());

=======================

https://code.google.com/p/guava-libraries/wiki/FunctionalExplained

Even using static imports, even if the Function and the Predicate declarations are moved to a different file, the first implementation is less concise, less readable, and less efficient.   

=================

Here's a shortened version of a class where static import is suitable:

===============================
import static com.some.company.BetPosition.*;

public class NumberMapping {

    private final BetPosition[][] numberToPositions = new BetPosition[][] {
            /* 0 number */{ STRAIGHT_0, BET_0_1, BET_0_2, BET_0_3, BET_0_1_2, BET_0_2_3, BET_0_1_2_3 },                 
            // ... 1-35 ...
            /* 36 number */{ STRAIGHT_36, BET_35_36, BET_33_36, BET_34_35_36, BET_32_33_35_36, BET_31_32_33_34_35_36,
                    TOP_2_TO_1, DOZEN_3_RD_12, HIGH_19_TO_36, RED, EVEN } };

    public BetPosition[] getPositions(int number) {
        BetPosition[] positions = numberToPositions[number];
        // some logic
        return positions;
    }
}


Where BetPosition is an enum with such a content:

public enum BetPosition {
    // ...
    STRAIGHT_32(96, ...),
    STRAIGHT_33(142, ...),
    STRAIGHT_34(52, ...),
    BET_1_2(53, ...),
    BET_4_5(55, ...),
    // ... long list of enum values

====================================

TODO..... investigate Guava code to have be sure that their code could follow that Check.

Issue is registered:
https://github.com/sevntu-checkstyle/sevntu.checkstyle/issues/453 

Wrong link generation by maven javadoc plugin for org.xml.sax.helpers.DefaultHandler

Friday, March 6, 2015

Reason of checkstyle ideas rejection for GSoC 2015

Conversation between GSoC administration and Checkstyle :

<gsocbot> carols: Next in line is checkstyle with notice: checkstyle checkstyle https://github.com/checkstyle/checkstyle/wiki/Checkstyle-GSoC-2015-Project-Ideas
* kblin gives voice to checkstyle
* scorche|sh gives voice to checkstyle
<checkstyle> Hi Carol, please share your thoughts about our ideas page
<carols> actually, just looking it over, i think it looks great.
<carols> your application looks good too.
<checkstyle> Do you have any preference of size (number of sentences) of one idea description ? We had a challange to describe clearly and be not too wordy. 
<carols> unfortunately this was another numbers thing. :-(
<carols> i’m sorry that i don’t have a more satisfying answer than that
<carols> checkstyle: yes, my preference is always for more information over less
<carols> i would rather see you over-describe a topic than under-describe
<checkstyle> So we just unlucky this year , right ?
<carols> it helps the students
<carols> yes, unfortunately so :-(
<checkstyle> ok, thanks a lot !
<carols> i hope you’ll try again next year
<carols> you’re welcome



Some reason why many other organizations are failed to pass to GSoC 20015:
<carols> we got a lot of applications in a few specific topic areas where we had to reject a lot of orgs, and we also tried to make space for new organizations who have never participated before over accepting organizations who have been with us for a long time.
<carols> it’s always difficult, and unfortunately some orgs had wonderful ideas pages and applications and still didn’t make the cut.
<carols> yeah, ideas page looks good to me, and it looks like we just made a bunch of hard decisions this year.

Full log of IRC feedback meeting for rejected organizations for Google Summer of Code 2015. #gsoc on freenode.net.

Monday, March 2, 2015

Logback config to suppress event by stacktrace element

Log event in file:
[2015-03-02 09:03:14,418] [server] [user] [ajp-bio-8009-exec-33] [Session][] [ERROR] - An exception has been thrown while processing following requests: '[Request[oid=2021,name=updateSelection,args=[ [ [ 2, 3 ], [ 6, 6 ], [ 11, 11 ] ] ]], Request[oid=2019,name=handleEvent,args=[ popupBeforeOpen, beforePopupOpen, [  ] ]]]'.
java.lang.NullPointerException: null
at com.company.View.fillContextMenu(View.java:444) 
at com.company.View.access$500(View.java:107)
at com.company.View$2.beforePopupOpen(View.java:303)
at sun.reflect.GeneratedMethodAccessor791.invoke(Unknown Source) ~[na:na]


to suppress that event following logback configuration for ch.qos.logback.classic.boolex.JaninoEventEvaluator is required:
<included>

   <property name="common.log.date.format" value="{MM/dd HH:mm:ss:SSS}" />
   <property name="common.log.conversionpattern" value="[%d${common.log.date.format}] [%X{username}] [%c{0}] [%marker] [%p]: %m%n" />

   <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
      <target>System.out</target>
      <encoder>
         <pattern>${common.log.conversionpattern}</pattern>
      </encoder>
<!-- perform more precise filtering, you can suppress particular messages here -->
<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
<evaluator>
<expression><![CDATA[
// suppress ERRORs from legacy code
if (level == ERROR
&& logger.contains("Session")
&& message.contains("handleEvent,args=[ popupBeforeOpen, beforePopupOpen, [  ] ]")
&& message.contains("updateSelection")
       && message.contains("An exception has been thrown while processing following requests")
        && throwableProxy != null && "java.lang.NullPointerException".equals(throwableProxy.getClassName())
&& throwableProxy.getStackTraceElementProxyArray()[0].getSTEAsString().contains("com.mycompany.View.fillContextMenu")
) {
return false;
}

return true;
]]></expression>
</evaluator>
<OnMatch>NEUTRAL</OnMatch>
<OnMismatch>DENY</OnMismatch>
</filter>
   </appender>

   <root level="INFO">
      <appender-ref ref="STDOUT" />
   </root>

</included>