Categories
discuss

SonarQube Leak Period between Branches or Projects

I am currently introducing SonarQube into a large legacy project. This means that there are already hundreds of warnings, in the first step I would like to ensure that there are no new warnings coming from our feature branches.

To achieve this, I want to have the Sonar analysis run on every feature branch, compare it to the main branch and alert the committer in case new warnings have been introduced.

Assume the following situation:

MyProject 1.0-SNAPSHOT is the name and version of the project on SonarQube. It has 100 warnings. It represents the develop branch. The leak period is the analysis from 1 day ago. This works very well, I can see which new warnings have been introduced since yesterday.

Developers are working on feature/somefeature branches. When they open a pull request, I want a Sonar analysis to run on that branch. This works fine, but I can’t set the leak version to MyProject 1.0-SNAPSHOT from yesterday, because this branch is seen as a completely separate project by SonarQube, even though I set the sonar.projectKey to the same name and I have also tried playing around with the sonar.branch property.

The desired outcome is:

  1. develop -> 100 warnings

  2. feature/somefeature -> 102 warnings

  3. On the SonarQube dashboard of feature/somefature display “2 new warnings”.

Can it be done with sonar itself, or do I need to write my own program using the Sonar REST API?

Answer

You should use Branch Plugin in order to analyse branches for only new issues. This plugin has a corresponding Quality Gate:

For short-lived branches, there is a kind of hard-coded quality gate focusing only on new issues.

It will create Issues only if there are new bugs or vulnerabilities.

As per the plugin documentation all your feature branches should be identified as short-lived branches.

NOTE: Branch Plugin is licensed under SonarSource and is available in nonfree Developer Edition

Categories
discuss

NullpointerException for console appender for Log4j2

My application logging crashes during maven build in the tests. This is the log4j2.xml what I have in the src/test/resources:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
    <Appenders>
        <Console name="stdout" target="SYSTEM_OUT">
            <PatternLayout pattern="MyApp: %d{yyyy-MM-dd HH:mm:ss,SSS} %5p [%t] %c{1.} - %m%n" />
        </Console>
    </Appenders>

    <Loggers>
        <Logger name="com.my.app" level="info" additivity="false">
            <Appender-ref ref="stdout"/>
        </Logger>
        <Root level="error">
            <Appender-ref ref="stdout"/>
        </Root>
    </Loggers>
</Configuration>

And I get this exception during test during build:

2017-11-23 15:12:28,371 main ERROR An exception occurred processing Appender stdout java.lang.NullPointerException
    at org.apache.logging.log4j.core.impl.ThrowableProxy.toExtendedStackTrace(ThrowableProxy.java:671)
    at org.apache.logging.log4j.core.impl.ThrowableProxy.<init>(ThrowableProxy.java:138)
    at org.apache.logging.log4j.core.impl.ThrowableProxy.<init>(ThrowableProxy.java:122)
    at org.apache.logging.log4j.core.impl.Log4jLogEvent.getThrownProxy(Log4jLogEvent.java:566)
    at org.apache.logging.log4j.core.pattern.ExtendedThrowablePatternConverter.format(ExtendedThrowablePatternConverter.java:64)
    at org.apache.logging.log4j.core.pattern.PatternFormatter.format(PatternFormatter.java:38)
    at org.apache.logging.log4j.core.layout.PatternLayout$PatternSerializer.toSerializable(PatternLayout.java:333)
    at org.apache.logging.log4j.core.layout.PatternLayout.toText(PatternLayout.java:232)
    at org.apache.logging.log4j.core.layout.PatternLayout.encode(PatternLayout.java:217)
    at org.apache.logging.log4j.core.layout.PatternLayout.encode(PatternLayout.java:57)
    at org.apache.logging.log4j.core.appender.AbstractOutputStreamAppender.directEncodeEvent(AbstractOutputStreamAppender.java:177)
    at org.apache.logging.log4j.core.appender.AbstractOutputStreamAppender.tryAppend(AbstractOutputStreamAppender.java:170)
    at org.apache.logging.log4j.core.appender.AbstractOutputStreamAppender.append(AbstractOutputStreamAppender.java:161)
    at org.apache.logging.log4j.core.config.AppenderControl.tryCallAppender(AppenderControl.java:156)
    at org.apache.logging.log4j.core.config.AppenderControl.callAppender0(AppenderControl.java:129)
    at org.apache.logging.log4j.core.config.AppenderControl.callAppenderPreventRecursion(AppenderControl.java:120)
    at org.apache.logging.log4j.core.config.AppenderControl.callAppender(AppenderControl.java:84)
    at org.apache.logging.log4j.core.config.LoggerConfig.callAppenders(LoggerConfig.java:448)
    at org.apache.logging.log4j.core.config.LoggerConfig.processLogEvent(LoggerConfig.java:433)
    at org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:417)
    at org.apache.logging.log4j.core.config.LoggerConfig.logParent(LoggerConfig.java:439)
    at org.apache.logging.log4j.core.config.LoggerConfig.processLogEvent(LoggerConfig.java:434)
    at org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:417)
    at org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:403)
    at org.apache.logging.log4j.core.config.AwaitCompletionReliabilityStrategy.log(AwaitCompletionReliabilityStrategy.java:63)
    at org.apache.logging.log4j.core.Logger.logMessage(Logger.java:146)
    at org.apache.logging.log4j.spi.AbstractLogger.tryLogMessage(AbstractLogger.java:2116)
    at org.apache.logging.log4j.spi.AbstractLogger.logMessageSafely(AbstractLogger.java:2100)
    at org.apache.logging.log4j.spi.AbstractLogger.logMessage(AbstractLogger.java:1994)
    at org.apache.logging.log4j.spi.AbstractLogger.logIfEnabled(AbstractLogger.java:1966)
    at org.apache.logging.slf4j.Log4jLogger.error(Log4jLogger.java:319)
    at com.my.app.MyTest.testingMyApp(MyTest.java:89)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:19)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
    at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:283)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:173)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:128)
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:203)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:155)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)

This is my pom:

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-web</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-slf4j-impl</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-jul</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-jcl</artifactId>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
    <groupId>org.dblock.log4jna</groupId>
    <artifactId>log4jna-api</artifactId>
</dependency>

The version of log4j is 2.9.1

And the funny thing, that it logs to the console, for example when the spring application starting, then there I can see the logs which are coming from the MyApplication.java which has the @SpringBootApplication annotation.

And MyTest.java:89 is:

logger.error("error occured",e);

And the logger is coming from:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

So it looks like it crashes during error log, but there is no problem if I log a normal info.

So what is this nullpointer?

Answer

Ok, I figured it out: it is because in the test class I have a mock exception. If I change it to creating a new object from the exception, it works fine.

It is a good candidate for reporting a bug I guess.

Categories
discuss

Can I use @Requestparam annotation for a Post request?

I have this controller method:

@PostMapping(
        value = "/createleave",
        params = {"start","end","hours","username"})
public void createLeave(@RequestParam(value = "start") String start,
                        @RequestParam(value = "end") String end,
                        @RequestParam(value = "hours") String hours,
                        @RequestParam(value = "username") String username){
    System.out.println("Entering createLeave " + start + " " + end + " " + hours + " " + username);
    LeaveQuery newLeaveQuery = new LeaveQuery();
    Account account = accountRepository.findByUsername(username);
    newLeaveQuery.setAccount(account);
    newLeaveQuery.setStartDate(new Date(Long.parseLong(start)));
    newLeaveQuery.setEndDate(new Date(Long.parseLong(end)));
    newLeaveQuery.setTotalHours(Integer.parseInt(hours));
    leaveQueryRepository.save(newLeaveQuery);
}

However when I send a post request to this endpoint I get the following

"{"timestamp":1511444885321,"status":400,"error":"Bad Request","exception":"org.springframework.web.bind.UnsatisfiedServletRequestParameterException","message":"Parameter conditions "start, end, hours, username" not met for actual request parameters: ","path":"/api/createleave"}"

When I remove the params argument from the @PostMapping annotation I get a more general error, it will say that it cannot find the first required parameter (start), while it really is being send together with the parameters end, hours and username.

how to get param in method post spring mvc?

I’ve read in this post that @RequestParam can only be used for get methods, but if I remove @RequestParam and stick with the params argument of the @PostMapping annotation it still doesn’t work. I know I can use @RequestBody but I do not want to make a class just for those 4 parameters. Can anyone tell me how I can make this work?

Thank you

EDIT: I’m reading here https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html#params– that the argument params isn’t exactly what I thought it was. It seems to be used as a condition. If a set of parameters match a value then the endpoint controller method will be activated.

Answer

What you are asking for is fundamentally wrong. POST requests sends data in a body payload, which is mapped via @RequestBody. @RequestParam is used to map data through the URL parameters such as /url?start=foo. What you are trying to do is use @RequestParam to do the job of @RequestBody.

Alternative solutions for REST controllers

  • Introduce a DTO class. It is the most preferred and clean method.
  • If you really want to avoid creating a class, you can use @RequestBody Map<String, String> payload. Be sure to include 'Content-Type': 'application/json' in your request header.
  • If you really want to use @RequestParam, use a GET request instead and send your data via URL parameters.

Alternative solutions for MVC controllers

  • Introduce a DTO class and use it with annotation @ModelAttribute.
  • If you transform the form data into JSON, you can use @RequestBody Map<String, String> payload. To do this, please see this answer.

It is not possible to map form data encoded data directly to a Map<String, String>.

Categories
discuss

Register User Through Passport Js

i want to add new user from signup page through help of passport.js Signup form is following

<form id="Signup-form" name="SignupForm" action="/signup" method="post"/>
<input type="text" id="firstname" name="Firstname" >
<input type="text" id="lastname" name="Lastname"/>
<input type="email" name="email" />
<input type="text" id="rollno" name="rollno"/>
<input type="password" name="password" id="password"/>
<input type="password" name="confirm" id="confirm-password"/>
<input type="radio" name='Gender' value="Male" />
<input type="radio" name='Gender' value="FeMale" />
</form>

my passport is initialized in app.js as

required

var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

after db setting

require('./config/passport');

intialized as

app.use(passport.initialize());
app.use(passport.session());

post sign up route

router.post('/signup', passport.authenticate('local.signup' , {
successRedirect : '/home',
failuerRedirect : '/signup',
failuerFlash: true
}));

my user model

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs')

const UserSchema = new Schema({
First_Name : String,
Last_Name : String,
email : String,
Roll_No : String,
Gender : String,
password : String
},{collection : 'Users'});

UserSchema.methods.encryptPassword = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(5), null);
};

UserSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.password);
}
var User = mongoose.model('User' , UserSchema); 
module.exports = User;

now my passport.js file in config dir is

var passport = require('passport');
var User = require('../models/user');
var LocalStrategy = require('passport-local').Strategy;
passport.serializeUser(function (user, done) {
done(null, user.id);
});

passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
done(err, user);
 });
});

my main questions how to write strategy for this route with all fields

passport.use('local.signup', new LocalStrategy({
//strategy code here
}));

Answer

Here is a good example Easy Node Authentication: Setup and Local

passport.use('local-signup', new LocalStrategy({
        // by default, local strategy uses username and password, we will override with email
        usernameField : 'email',
        passwordField : 'password',
        passReqToCallback : true // allows us to pass back the entire request to the callback
    },
    function(req, email, password, done) {

        // find a user whose email is the same as the forms email
        // we are checking to see if the user trying to login already exists
        User.findOne({ 'local.email' :  email }, function(err, user) {
            // if there are any errors, return the error
            if (err)
                return done(err);

            // check to see if theres already a user with that email
            if (user) {
                return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
            } else {

                // if there is no user with that email
                // create the user
                var newUser            = new User();

                // set the user's local credentials
                newUser.local.email    = email;
                newUser.local.password = newUser.generateHash(password);

                // save the user
                newUser.save(function(err) {
                    if (err)
                        throw err;
                    return done(null, newUser);
                });
            }

    }));
Categories
discuss

RecyclerView adapter show only first item

I know that this question has been asked many times, but the answers doesn’t work for me. I am trying to use Horizontal placement. Here is my code:

public class CalendarDaysAdapter extends RecyclerView.Adapter<CalendarDaysAdapter.MyViewHolder> {

    private ArrayList<String> list;

    public CalendarDaysAdapter(ArrayList<String> list)
    {
        this.list = list;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.fragment_calendar_days_item, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {

        String day = list.get(position);
        holder.daystxt.setText(day);
    }

    @Override
    public int getItemCount() {
        return list.size();
    }


    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView daystxt;

        public MyViewHolder(View view) {
            super(view);
            daystxt = (TextView) view.findViewById(R.id.daystxt);
        }
    }

}

fragment_calendar_days_item xml:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:gravity="center">

        <TextView
            android:id="@+id/daystxt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="MON"
            android:textSize="20sp"/>

    </RelativeLayout>


</LinearLayout>

I tried every combination of wrap_content – match_parent, also on the RecyclerView xml in parent Activity, but only the first item is showing. I have used breakpoints to see if the data of the list are there, and they are.

So what I am missing ?

Answer

Change your fragment_calendar_days_item height and width to android:layout_height="wrap_content" and android:layout_width="wrap_content"

it will solve your issue

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:gravity="center">

        <TextView
            android:id="@+id/daystxt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="MON"
            android:textSize="20sp"/>

    </RelativeLayout>


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