/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package foam.nanos.boot;

import foam.core.*;
import foam.dao.*;
import foam.nanos.*;

public class Boot {
  protected DAO serviceDAO_;
  protected X   root_ = new ProxyX();

  public Boot() {
    serviceDAO_ = new MapDAO();
    ((MapDAO) serviceDAO_).setOf(NSpec.getOwnClassInfo());
    ((MapDAO) serviceDAO_).setX(root_);
    loadTestData();

    ((AbstractDAO) serviceDAO_).select(new AbstractSink() {
      public void put(FObject obj, Detachable sub) {
        NSpec sp = (NSpec) obj;
        System.out.println("NSpec: " + sp.getName());

        try {
          // NanoService ns = sp.createService();

          // ((ContextAwareSupport) ns).setX(root_);
          // ns.start();

          root_.putFactory(sp.getName(), new SingletonFactory(new NSpecFactory(sp)));
        } catch (ClassNotFoundException e) {
           e.printStackTrace();
        } catch (InstantiationException e) {
           e.printStackTrace();
        } catch (IllegalAccessException e) {
           e.printStackTrace();
        }
      }
    });
  }

  protected void loadTestData() {
    NSpec s = new NSpec();
    s.setName("http");
    s.setServiceClass("foam.nanos.http.NanoHttpServer");
    serviceDAO_.put(s);
  }

  public static void main (String[] args) throws Exception {
    new Boot();
  }

}

/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package foam.nanos.boot;

import foam.core.*;
import foam.dao.*;
import foam.nanos.*;

public class Boot {
  protected DAO serviceDAO_;
  protected X   root_ = new ProxyX();

  public Boot() {
    serviceDAO_ = new MapDAO();
    ((MapDAO) serviceDAO_).setOf(NSpec.getOwnClassInfo());
    ((MapDAO) serviceDAO_).setX(root_);
    loadTestData();

    ((AbstractDAO) serviceDAO_).select(new AbstractSink() {
      public void put(FObject obj, Detachable sub) {
        NSpec sp = (NSpec) obj;
        System.out.println("NSpec: " + sp.getName());

        root_.putFactory(sp.getName(), new SingletonFactory(new NSpecFactory(sp)));
      }
    });
  }

  protected void loadTestData() {
    NSpec s = new NSpec();
    s.setName("http");
    s.setServiceClass("foam.nanos.http.NanoHttpServer");
    serviceDAO_.put(s);
  }

  public static void main (String[] args) throws Exception {
    new Boot();
  }

}

Remove try/catch statement from boot constructor


package com.ljs.scratch.ootp.rating;

import com.fasterxml.jackson.annotation.JsonTypeInfo;

/**
 *
 * @author lstephen
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
public interface Scale<T> {

    Rating<T, ? extends Scale<T>> ratingOf(T value);

    Rating<T, ? extends Scale<T>> parse(String s);

    Rating<Integer, OneToOneHundred> normalize(T value);

}

package com.ljs.scratch.ootp.rating;

import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.ljs.scratch.ootp.ootp5.site.ZeroToTen;

/**
 *
 * @author lstephen
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
@JsonSubTypes({
    @Type(ZeroToTen.class)
})
public interface Scale<T> {

    Rating<T, ? extends Scale<T>> ratingOf(T value);

    Rating<T, ? extends Scale<T>> parse(String s);

    Rating<Integer, OneToOneHundred> normalize(T value);

}

Fix error in draft pool deserialization


/*
 * Parse command-line options and run the SNPrank algorithm.
 * Authors:  Brett McKinney and Nick Davis
 * Email:  brett.mckinney@gmail.com, nick@nickdavis.name
 */
public class snprank {
	public static void main(String[] args) {

		if(args.length != 3) {
			System.out.println("Usage: java snprank matrix.txt gamma output.txt");
			System.exit(1);
		}

		SNPrank full_data = new SNPrank(args[0]);
		full_data.snprank(full_data.getHeader(), full_data.getData(), args[1], args[2]);
	}
}

/*
 * Parse command-line options and run the SNPrank algorithm.
 * Authors:  Brett McKinney and Nick Davis
 * Email:  brett.mckinney@gmail.com, nick@nickdavis.name
 */
public class snprank {
	public static void main(String[] args) {

		if(args.length != 3) {
			System.out.println("Usage: java snprank matrix.txt gamma output.txt");
			System.exit(1);
		}

		SNPrankData full_data = new SNPrankData(args[0]);
		full_data.snprank(full_data.getHeader(), full_data.getData(), args[1], args[2]);
	}
}

Update SNPrank -> SNPrankData in main class


package se.hyperlab.tigcm;

import android.content.Intent;
import android.app.Activity;
import android.os.Bundle;
import org.appcelerator.kroll.common.Log;

import org.appcelerator.titanium.TiApplication;

import java.util.HashMap;

public class NotificationActivity extends Activity {

    private static final String TAG = "NotificationActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        HashMap<String, Object> data = (HashMap)intent.getSerializableExtra(TiGCMModule.NTF_KEY_DATA);

        TiGCMModule module = TiGCMModule.getInstance();
        TiApplication instance = TiApplication.getInstance();

        if(module != null) {
            module.fireMessage(data, false);
        } else {
            TiApplication.getInstance().getAppProperties().setString(TiGCMModule.PROPERTY_PENDING_DATA, data.toString());
            Log.d(TAG, "Saving data in props: " + data.toString());
        }

        String pkg = instance.getApplicationContext().getPackageName();
        Intent launcherIntent = instance.getApplicationContext().getPackageManager().getLaunchIntentForPackage(pkg);

        startActivity(launcherIntent);
        finish();
    }
}

package se.hyperlab.tigcm;

import android.content.Intent;
import android.app.Activity;
import android.os.Bundle;
import org.appcelerator.kroll.common.Log;

import org.appcelerator.titanium.TiApplication;
import org.appcelerator.kroll.KrollDict;

import java.util.HashMap;

public class NotificationActivity extends Activity {

    private static final String TAG = "NotificationActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        HashMap<String, Object> data = (HashMap)intent.getSerializableExtra(TiGCMModule.NTF_KEY_DATA);

        TiGCMModule module = TiGCMModule.getInstance();
        TiApplication instance = TiApplication.getInstance();

        if(module != null) {
            module.fireMessage(data, false);
        } else {
            KrollDict kdata = new KrollDict(data);

            TiApplication.getInstance().getAppProperties().setString(TiGCMModule.PROPERTY_PENDING_DATA, kdata.toString());
            Log.d(TAG, "Saving data in props: " + kdata.toString());
        }

        String pkg = instance.getApplicationContext().getPackageName();
        Intent launcherIntent = instance.getApplicationContext().getPackageManager().getLaunchIntentForPackage(pkg);

        startActivity(launcherIntent);
        finish();
    }
}

Fix data serialization causing app not to receive data when launched from notification


package br.com.bloder.blorm;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;

import br.com.bloder.blormlib.Blorm;

import static br.com.bloder.blormlib.validation.Validations.*;

public class MainActivity extends AppCompatActivity {

  private EditText editTextFilled;
  private Button submit;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    editTextFilled = (EditText) findViewById(R.id.edit_text_filled);
    submit = (Button) findViewById(R.id.submit);

    new Blorm.Builder().field(editTextFilled).is(filled).onSubmit(submit);
  }
}

package br.com.bloder.blorm;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;

import br.com.bloder.blormlib.Blorm;
import br.com.bloder.blormlib.validation.Validate;

import static br.com.bloder.blormlib.validation.Validations.*;

public class MainActivity extends AppCompatActivity {

  private EditText editTextFilled;
  private Button submit;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    editTextFilled = (EditText) findViewById(R.id.edit_text_filled);
    submit = (Button) findViewById(R.id.submit);

    new Blorm.Builder().field(editTextFilled).is(filled).onSubmit(submit);

    new Blorm.Builder().field(editTextFilled).is(new Validate() {
      @Override
      public boolean validate() {
        return false;
      }

      @Override
      public void onError() {

      }
    }).onSubmit(submit);
  }
}

Add custom on error example in main activity


package org.concord.otrunk.user;

import org.concord.framework.otrunk.OTObjectInterface;
import org.concord.framework.otrunk.OTObjectList;
import org.concord.otrunk.view.OTClassMember;
import org.concord.otrunk.view.document.OTDocument;

public interface OTWorkgroupMemberChooser
    extends OTObjectInterface
{
	/**
	 * The current user
	 * @return
	 */
	public void setLeadMember(OTClassMember member);
	public OTClassMember getLeadMember();

	/**
	 * A List of OTClassMember objects, all of which are copied from the OTClassListManager
	 * @return
	 */
	public OTObjectList getOtherWorkgroupMembers();

	/**
	 * A List of OTClassMember objects, all of which were dynamically created on the fly by the current user
	 * @return
	 */
	public OTObjectList getCustomWorkgroupMembers();

	public static final boolean DEFAULT_usePopup = true;
	public boolean getUsePopup();

	/**
	 * This Document is a template for the header text in the view. The text will be run through a simple substitution engine prior to being rendered.
	 * Valid substitution variables are:
	 *   #{user_name}
	 * @return
	 */
	public OTDocument getTextTemplate();
}

package org.concord.otrunk.user;

import org.concord.framework.otrunk.OTObject;
import org.concord.framework.otrunk.OTObjectInterface;
import org.concord.framework.otrunk.OTObjectList;
import org.concord.otrunk.view.OTClassMember;

public interface OTWorkgroupMemberChooser
    extends OTObjectInterface
{
	/**
	 * The current user
	 * @return
	 */
	public void setLeadMember(OTClassMember member);
	public OTClassMember getLeadMember();

	/**
	 * A List of OTClassMember objects, all of which are copied from the OTClassListManager
	 * @return
	 */
	public OTObjectList getOtherWorkgroupMembers();

	/**
	 * A List of OTClassMember objects, all of which were dynamically created on the fly by the current user
	 * @return
	 */
	public OTObjectList getCustomWorkgroupMembers();

	public static final boolean DEFAULT_usePopup = true;
	public boolean getUsePopup();

	/**
	 * This Document is a template for the header text in the view. The text will be run through a simple substitution engine prior to being rendered.
	 * Valid substitution variables are:
	 *   #{user_name}
	 * The type of this object is set to OTObject to remove its dependency on OTDocument which
	 * is no longer in the OTrunk project.  The view now casts this to OTDocument.
	 * This class should probably be moved to another package/project.
	 * @return
	 */
	public OTObject getTextTemplate();
}

Change the workgroupmemberchooser so it doesn't directly depend on OTDocument. This change is to facilitate moving OTDocument out of the otrunk project.


package org.asteriskjava.manager.event;

import static org.junit.Assert.assertEquals;

import java.util.TimeZone;

import org.junit.Before;
import org.junit.Test;

public class CdrEventTest
{
    CdrEvent cdrEvent;
    TimeZone defaultTimeZone;

    @Before
    public void setUp()
    {
        cdrEvent = new CdrEvent(this);
        cdrEvent.setStartTime("2006-05-19 11:54:48");
        defaultTimeZone = TimeZone.getDefault();
        TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
    }

    @Before
    public void tearDown()
    {
        TimeZone.setDefault(defaultTimeZone);
    }

    @Test
    public void testGetStartTimeAsDate()
    {
        assertEquals(1148039688000L, cdrEvent.getStartTimeAsDate().getTime());
    }

    @Test
    public void testGetStartTimeAsDateWithTimeZone()
    {
        TimeZone tz = TimeZone.getTimeZone("GMT+2");
        assertEquals(1148032488000L, cdrEvent.getStartTimeAsDate(tz).getTime());
    }

    @Test
    public void testBug()
    {
        TimeZone.setDefault(TimeZone.getTimeZone("Europe/Monaco"));

        cdrEvent.setStartTime("2006-05-29 13:17:21");
        assertEquals("Mon May 29 13:17:21 CEST 2006", cdrEvent.getStartTimeAsDate().toString());
    }
}

package org.asteriskjava.manager.event;

import static org.junit.Assert.assertEquals;

import java.util.TimeZone;

import org.junit.Before;
import org.junit.After;
import org.junit.Test;

public class CdrEventTest
{
    CdrEvent cdrEvent;
    TimeZone defaultTimeZone;

    @Before
    public void setUp()
    {
        cdrEvent = new CdrEvent(this);
        cdrEvent.setStartTime("2006-05-19 11:54:48");
        defaultTimeZone = TimeZone.getDefault();
        TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
    }

    @After
    public void tearDown()
    {
        TimeZone.setDefault(defaultTimeZone);
    }

    @Test
    public void testGetStartTimeAsDate()
    {
        assertEquals(1148039688000L, cdrEvent.getStartTimeAsDate().getTime());
    }

    @Test
    public void testGetStartTimeAsDateWithTimeZone()
    {
        TimeZone tz = TimeZone.getTimeZone("GMT+2");
        assertEquals(1148032488000L, cdrEvent.getStartTimeAsDate(tz).getTime());
    }

    @Test
    public void testBug()
    {
        TimeZone.setDefault(TimeZone.getTimeZone("Europe/Monaco"));

        cdrEvent.setStartTime("2006-05-29 13:17:21");
        assertEquals("Mon May 29 13:17:21 CEST 2006", cdrEvent.getStartTimeAsDate().toString());
    }
}

Fix cdr timezone test issue


public class LazyInit {
	static Object foo;

	// This should be reported
	public static Object getFoo() {
		if (foo == null)
			foo = new Object();
		return foo;
	}

	// This should not be reported
	public synchronized static Object sgetFoo() {
		if (foo == null)
			foo = new Object();
		return foo;
	}
}

public class LazyInit {
	static Object foo;
	static volatile Object bar;

	// This should be reported
	public static Object getFoo() {
		if (foo == null)
			foo = new Object();
		return foo;
	}
	// This should be reported
	public static Object getBar() {
		if (bar == null)
			bar = new Object();
		return bar;
	}

	// This should not be reported
	public synchronized static Object sgetFoo() {
		if (foo == null)
			foo = new Object();
		return foo;
	}
}

Check that volatile statics don't get flagged


package org.jgrades.rest;

import org.joda.time.DateTime;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class RestDocsConfig {
    @Bean
    public Docket jGradesRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                .pathMapping("/")
                .directModelSubstitute(DateTime.class, Long.class)
                .enableUrlTemplating(true);
    }

}

package org.jgrades.rest;

import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.LocalTime;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class RestDocsConfig {
    @Bean
    public Docket jGradesRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                .pathMapping("/")
                .directModelSubstitute(DateTime.class, Long.class)
                .directModelSubstitute(LocalDate.class, String.class)
                .directModelSubstitute(LocalTime.class, String.class)
                .enableUrlTemplating(true);
    }

}

Improve joda objects model in rest


package in.twizmwaz.cardinal.module.modules.filter.type.old;

import in.twizmwaz.cardinal.module.ModuleCollection;
import in.twizmwaz.cardinal.module.modules.filter.FilterModule;
import in.twizmwaz.cardinal.module.modules.filter.FilterState;
import in.twizmwaz.cardinal.module.modules.filter.parsers.ChildrenFilterParser;

import static in.twizmwaz.cardinal.module.modules.filter.FilterState.*;

public class AllowFilter extends FilterModule {

    private final ModuleCollection<FilterModule> children;

    public AllowFilter(final ChildrenFilterParser parser) {
        super(parser.getName());
        this.children = parser.getChildren();
    }

    @Override
    public FilterState evaluate(final Object... objects) {
        for (FilterModule child : children) {
            if (child.evaluate(objects).equals(DENY)) return DENY;
            if (child.evaluate(objects).equals(ALLOW)) return ALLOW;
        }
        return ABSTAIN;
    }

}

package in.twizmwaz.cardinal.module.modules.filter.type.old;

import in.twizmwaz.cardinal.module.ModuleCollection;
import in.twizmwaz.cardinal.module.modules.filter.FilterModule;
import in.twizmwaz.cardinal.module.modules.filter.FilterState;
import in.twizmwaz.cardinal.module.modules.filter.parsers.ChildrenFilterParser;

import static in.twizmwaz.cardinal.module.modules.filter.FilterState.*;

public class AllowFilter extends FilterModule {

    private final ModuleCollection<FilterModule> children;

    public AllowFilter(final ChildrenFilterParser parser) {
        super(parser.getName());
        this.children = parser.getChildren();
    }

    @Override
    public FilterState evaluate(final Object... objects) {
        boolean abstain = true;
        for (FilterModule child : children) {
            if (child.evaluate(objects).equals(DENY)) return DENY;
            if (!child.evaluate(objects).equals(ABSTAIN)) abstain = false;
        }
        if (abstain) return ABSTAIN;
        return ALLOW;
    }

}

Add abstination back to allow filters


/*
 * Copyright 2015 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

package com.skia;

import org.libsdl.app.SDLActivity;

import android.content.Intent;

public class VisualBenchActivity extends SDLActivity {
  protected String[] getArguments() {
    // intent get intent extras if triggered from the command line
    Intent intent = this.getIntent();
    String flags = intent.getStringExtra("cmdLineFlags");

    return flags.split("\\s+");
  }
}

/*
 * Copyright 2015 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

package com.skia;

import org.libsdl.app.SDLActivity;

import android.content.Intent;

public class VisualBenchActivity extends SDLActivity {
  protected String[] getArguments() {
    String flags = this.getIntent().getStringExtra("cmdLineFlags");
    if (flags != null && !flags.isEmpty()) {
	return flags.split("\\s+");
    }
    return new String[0];
  }
}

Make the Android SDL app start without cmdline arguments


package fr.neamar.kiss;

import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.preference.PreferenceManager;
import android.view.Window;
import android.view.WindowManager;

/**
 * Created by neamar on 19/03/17.
 */

public class UiTweaks {
    static void updateThemePrimaryColor(Activity activity) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
        String primaryColorOverride = prefs.getString("primary-color", "");

        // Circuit breaker, keep default behavior.
        if (primaryColorOverride.isEmpty()) {
            return;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            int mainColor = Color.parseColor(primaryColorOverride);
            Window window = activity.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

            // Update status bar color
            window.setStatusBarColor(mainColor);

        }
    }
}

package fr.neamar.kiss;

import android.app.ActionBar;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.preference.PreferenceManager;
import android.view.Window;
import android.view.WindowManager;

/**
 * Created by neamar on 19/03/17.
 */

public class UiTweaks {
    static void updateThemePrimaryColor(Activity activity) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
        String primaryColorOverride = prefs.getString("primary-color", "");

        // Circuit breaker, keep default behavior.
        if (primaryColorOverride.isEmpty()) {
            return;
        }

        int primaryColor = Color.parseColor(primaryColorOverride);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = activity.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

            // Update status bar color
            window.setStatusBarColor(primaryColor);
        }

        ActionBar actionBar = activity.getActionBar();
        if(actionBar != null) {
            actionBar.setBackgroundDrawable(new ColorDrawable(primaryColor));
        }
    }
}

Update actionbar color in settings


package fixtures.jaxb;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;

@Path("/jaxb")
public class JaxbResource {
    @GET
    public ResponseModel get() {
        return new ResponseModel();
    }

    @POST
    public javax.xml.ws.Response create(PayloadModel payload) {
        return new ResponseModel();
    }
}

package fixtures.jaxb;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;

@Path("/jaxb")
public class JaxbResource {
    @GET
    public ResponseModel get() {
        return new ResponseModel();
    }

    @POST
    public Response create(PayloadModel payload) {
        return Response.ok().build();
    }
}

Fix compile error because of bad response type.


package easylog.jee;

import javax.interceptor.InterceptorBinding;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Inherited
@InterceptorBinding
@Retention(RUNTIME)
@Target(TYPE)
public @interface Easylog {
}

package easylog.jee;

import javax.interceptor.InterceptorBinding;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Inherited
@InterceptorBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Easylog {
}

Allow interceptor annotation to be placed on methods.


package com.sequenceiq.cloudbreak.service.upgrade.ccm;

import static com.sequenceiq.cloudbreak.core.flow2.cluster.ccm.upgrade.CcmUpgradeEvent.CCM_UPGRADE_EVENT;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.sequenceiq.cloudbreak.api.endpoint.v4.dto.NameOrCrn;
import com.sequenceiq.cloudbreak.core.flow2.service.ReactorNotifier;
import com.sequenceiq.cloudbreak.domain.stack.Stack;
import com.sequenceiq.cloudbreak.logger.MDCBuilder;
import com.sequenceiq.cloudbreak.reactor.api.event.StackEvent;
import com.sequenceiq.cloudbreak.service.stack.StackService;
import com.sequenceiq.cloudbreak.structuredevent.CloudbreakRestRequestThreadLocalService;
import com.sequenceiq.flow.api.model.FlowIdentifier;

@Service
public class StackCcmUpgradeService {

    private static final Logger LOGGER = LoggerFactory.getLogger(StackCcmUpgradeService.class);

    @Inject
    private CloudbreakRestRequestThreadLocalService restRequestThreadLocalService;

    @Inject
    private StackService stackService;

    @Inject
    private ReactorNotifier reactorNotifier;

    public FlowIdentifier upgradeCcm(NameOrCrn nameOrCrn) {
        Long workspaceId = restRequestThreadLocalService.getRequestedWorkspaceId();
        Stack stack = stackService.getByNameOrCrnInWorkspace(nameOrCrn, workspaceId);
        MDCBuilder.buildMdcContext(stack);
        LOGGER.debug("Ccm upgrade has been initiated for stack {}", nameOrCrn.getNameOrCrn());
        String selector = CCM_UPGRADE_EVENT.event();
        return reactorNotifier.notify(stack.getId(), selector, new StackEvent(selector, stack.getId()));
    }
}

package com.sequenceiq.cloudbreak.service.upgrade.ccm;

import org.springframework.stereotype.Service;

import com.sequenceiq.cloudbreak.api.endpoint.v4.dto.NameOrCrn;
import com.sequenceiq.flow.api.model.FlowIdentifier;

@Service
public class StackCcmUpgradeService {
    public FlowIdentifier upgradeCcm(NameOrCrn nameOrCrn) {
        return null;
    }
}

Revert "CB-14584 triggering ccm upgrade flow through internal call"


package com.codicesoftware.plugins.hudson.util;

import hudson.Util;
import hudson.model.ParameterValue;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SelectorParametersResolver {

    public static String resolve(String text, List<ParameterValue> parameters) {
        if (parameters == null) {
            return text;
        }

        Map<String, String> parametersMap = new HashMap<>();
        for (ParameterValue parameter : parameters) {
            if ((parameter != null) && (parameter.getName() != null) && (parameter.getValue() != null)) {
                parametersMap.put(parameter.getName(), parameter.getValue().toString());
            }
        }

        return Util.replaceMacro(text, parametersMap);
    }
}

package com.codicesoftware.plugins.hudson.util;

import hudson.Util;
import hudson.model.ParameterValue;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SelectorParametersResolver {

    public static String resolve(String text, List<ParameterValue> parameters) {
        if (parameters == null) {
            return text;
        }

        Map<String, String> parametersMap = new HashMap<>();
        for (ParameterValue parameter : parameters) {
            if ((parameter != null) && (parameter.getName() != null) && (parameter.getValue() != null)) {
                parametersMap.put(parameter.getName(), parameter.getValue().toString());
            }
        }

        return Util.replaceMacro(
            resolveLegacyFormat(text, parametersMap), parametersMap);
    }

    static String resolveLegacyFormat(String text, Map<String, String> parametersMap) {
        String result = text;
        for (Map.Entry<String, String> entry : parametersMap.entrySet()) {
            result = result.replaceAll("%" + entry.getKey() + "%", entry.getValue());
        }
        return result;
    }
}

Make parameter resolution backwards compatible


package io.xchris6041x.devin.playerdata.request;

import java.util.UUID;

import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;

/**
 * @author Christopher Bishop
 */
public abstract class PlayerRequest {

	private UUID from;
	private UUID to;

	public PlayerRequest(Player from, OfflinePlayer to) {
		this.from = from.getUniqueId();
		this.to = to.getUniqueId();
	}

	public abstract String getDescription();

	/**
	 * @return the unique id of
	 */
	public UUID getFromUniqueId() {
		return from;
	}

	/**
	 * @return the uinque id of the player who was sent the request.
	 */
	public UUID getToUniqueId() {
		return to;
	}

}

package io.xchris6041x.devin.playerdata.request;

import java.util.UUID;

import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;

/**
 * @author Christopher Bishop
 */
public abstract class PlayerRequest {

	private UUID sender;
	private UUID receiver;

	public PlayerRequest(Player sender, OfflinePlayer receiver) {
		this.sender = sender.getUniqueId();
		this.receiver = receiver.getUniqueId();
	}

	public abstract String getDescription();

	/**
	 * @return the unique id of the player who sent the request.
	 */
	public UUID getSenderUniqueId() {
		return sender;
	}

	/**
	 * @return the uinque id of the player who received the request.
	 */
	public UUID getReceiverUniqueId() {
		return receiver;
	}

}

Change the name "from" and "to" to "sender" and "receiver".


package io.airlift.http.client.jetty;

import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.HttpClientTransport;
import org.eclipse.jetty.client.HttpRequest;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.util.ssl.SslContextFactory;

import java.net.URI;

import static org.eclipse.jetty.http.HttpHeader.AUTHORIZATION;

class AuthorizationPreservingHttpClient
        extends HttpClient
{
    private static final String PRESERVE_AUTHORIZATION_KEY = "airlift_preserve_authorization";

    public AuthorizationPreservingHttpClient(HttpClientTransport transport, SslContextFactory sslContextFactory)
    {
        super(transport, sslContextFactory);
    }

    @Override
    protected Request copyRequest(HttpRequest oldRequest, URI newUri)
    {
        Request newRequest = super.copyRequest(oldRequest, newUri);

        if (isPreserveAuthorization(oldRequest)) {
            setPreserveAuthorization(newRequest, true);
            for (HttpField field : oldRequest.getHeaders()) {
                if (field.getHeader() == AUTHORIZATION) {
                    newRequest.header(field.getName(), field.getValue());
                }
            }
        }

        return newRequest;
    }

    public static void setPreserveAuthorization(Request request, boolean preserveAuthorization)
    {
        request.attribute(PRESERVE_AUTHORIZATION_KEY, preserveAuthorization);
    }

    private static boolean isPreserveAuthorization(Request request)
    {
        return (boolean) request.getAttributes().get(PRESERVE_AUTHORIZATION_KEY);
    }
}

package io.airlift.http.client.jetty;

import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.HttpClientTransport;
import org.eclipse.jetty.client.HttpRequest;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.util.ssl.SslContextFactory;

import java.net.URI;

import static java.lang.Boolean.TRUE;
import static org.eclipse.jetty.http.HttpHeader.AUTHORIZATION;

class AuthorizationPreservingHttpClient
        extends HttpClient
{
    private static final String PRESERVE_AUTHORIZATION_KEY = "airlift_preserve_authorization";

    public AuthorizationPreservingHttpClient(HttpClientTransport transport, SslContextFactory sslContextFactory)
    {
        super(transport, sslContextFactory);
    }

    @Override
    protected Request copyRequest(HttpRequest oldRequest, URI newUri)
    {
        Request newRequest = super.copyRequest(oldRequest, newUri);

        if (isPreserveAuthorization(oldRequest)) {
            setPreserveAuthorization(newRequest, true);
            for (HttpField field : oldRequest.getHeaders()) {
                if (field.getHeader() == AUTHORIZATION) {
                    newRequest.header(field.getName(), field.getValue());
                }
            }
        }

        return newRequest;
    }

    public static void setPreserveAuthorization(Request request, boolean preserveAuthorization)
    {
        request.attribute(PRESERVE_AUTHORIZATION_KEY, preserveAuthorization);
    }

    private static boolean isPreserveAuthorization(Request request)
    {
        return TRUE.equals(request.getAttributes().get(PRESERVE_AUTHORIZATION_KEY));
    }
}

Allow HTTP client PRESERVE_AUTHORIZATION_KEY to be unset


package cpw.mods.fml.common.event;

import cpw.mods.fml.common.LoaderState.ModState;

public class FMLPostInitializationEvent extends FMLStateEvent
{
    public FMLPostInitializationEvent(Object... data)
    {
        super(data);
    }

    @Override
    public ModState getModState()
    {
        return ModState.POSTINITIALIZED;
    }

}

package cpw.mods.fml.common.event;

import com.google.common.base.Throwables;

import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.LoaderState.ModState;

public class FMLPostInitializationEvent extends FMLStateEvent
{
    public FMLPostInitializationEvent(Object... data)
    {
        super(data);
    }

    @Override
    public ModState getModState()
    {
        return ModState.POSTINITIALIZED;
    }

    public Object buildSoftDependProxy(String modId, String className)
    {
        if (Loader.isModLoaded(modId))
        {
            try
            {
                Class<?> clz = Class.forName(className,true,Loader.instance().getModClassLoader());
                return clz.newInstance();
            }
            catch (Exception e)
            {
                Throwables.propagateIfPossible(e);
                return null;
            }
        }
        return null;
    }
}

Add in a convenience method for getting a class instance based on existence of another Mod. Useful for soft dependencies.


package com.lazerycode.jmeter.configuration;

/**
 * Enum containing the log levels supported by JMeter
 */
public enum LogLevel {
	FATAL_ERROR,
	ERROR,
	WARN,
	INFO,
	DEBUG;

	@Override
	public String toString() {
		return super.toString().toUpperCase();
	}
}

package com.lazerycode.jmeter.configuration;

/**
 * Enum containing the log levels supported by JMeter
 */
public enum LogLevel {
	ERROR,
	WARN,
	INFO,
	DEBUG;

	@Override
	public String toString() {
		return super.toString().toUpperCase();
	}
}

Upgrade to JMeter 3.2 FATAL_ERROR does not exist anymore after migration of JMeter to slf4j


package cs437.som.neighborhood;

import cs437.som.NeightborhoodWidthFunction;

/**
 * Neighborhood width strategy for self-organizing maps that decays the width
 * linearly as the iterations progress.
 *
 * The exact behavior follows the formula:
 *      w_i * (1 - (-t / t_max))
 *  where
 *      w_i   is the initial width of the neighborhood
 *      e     is the base of the natural logarithm
 *      t     is the current iteration
 *      t_max is the maximum expected iteration
 */
public class LinearDecayNeighborhoodWidthFunction implements NeightborhoodWidthFunction {
    private final double initialNeighborhoodWidth;
    private double expectedIterations = 0.0;

    public LinearDecayNeighborhoodWidthFunction(double initialWidth) {
        initialNeighborhoodWidth = initialWidth;
    }

    public void setExpectedIterations(int expectedIterations) {
        this.expectedIterations = expectedIterations;
    }

    public double neighborhoodWidth(int iteration) {
        return initialNeighborhoodWidth * (1.0 - (iteration / expectedIterations));
    }

    @Override
    public String toString() {
        return "LinearDecayNeighborhoodWidthFunction";
    }
}

package cs437.som.neighborhood;

import cs437.som.NeightborhoodWidthFunction;

/**
 * Neighborhood width strategy for self-organizing maps that decays the width
 * linearly as the iterations progress.
 *
 * The exact behavior follows the formula:
 *      w_i * (1 - (-t / t_max))
 *  where
 *      w_i   is the initial width of the neighborhood
 *      t     is the current iteration
 *      t_max is the maximum expected iteration
 */
public class LinearDecayNeighborhoodWidthFunction implements NeightborhoodWidthFunction {
    private final double initialNeighborhoodWidth;
    private double expectedIterations = 0.0;

    public LinearDecayNeighborhoodWidthFunction(double initialWidth) {
        initialNeighborhoodWidth = initialWidth;
    }

    public void setExpectedIterations(int expectedIterations) {
        this.expectedIterations = expectedIterations;
    }

    public double neighborhoodWidth(int iteration) {
        return initialNeighborhoodWidth * (1.0 - (iteration / expectedIterations));
    }

    @Override
    public String toString() {
        return "LinearDecayNeighborhoodWidthFunction";
    }
}

Fix lin. decay NW comment.


/*++

NASM Assembly Language Plugin
Copyright (c) 2017-2018 Aidan Khoury. All rights reserved.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

--*/

package com.nasmlanguage.psi;

import com.intellij.psi.PsiNameIdentifierOwner;

public interface NASMNamedElement extends PsiNameIdentifierOwner {
}

/*++

NASM Assembly Language Plugin
Copyright (c) 2017-2018 Aidan Khoury

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

--*/

package com.nasmlanguage.psi;

import com.intellij.psi.PsiNameIdentifierOwner;

public interface NASMNamedElement extends PsiNameIdentifierOwner {
}

Update copyright notice with MIT license


// Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org)

package org.xbill.DNS;

import java.io.*;

/**
 * An exception thrown when a DNS message is invalid.
 *
 * @author Brian Wellington
 */

public class WireParseException extends IOException {

public
WireParseException() {
	super();
}

public
WireParseException(String s) {
	super(s);
}

}

// Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org)

package org.xbill.DNS;

import java.io.*;

/**
 * An exception thrown when a DNS message is invalid.
 *
 * @author Brian Wellington
 */

public class WireParseException extends IOException {

public
WireParseException() {
	super();
}

public
WireParseException(String s) {
	super(s);
}

public
WireParseException(String s, Throwable cause) {
	super(s, cause);
}

}

Add a constructor that takes a cause Exception.


package org.apereo.cas.web.report;

import org.springframework.cloud.bus.BusProperties;
import org.springframework.cloud.config.server.config.ConfigServerProperties;

import java.util.Map;

/**
 * This is {@link ControllerUtils}.
 *
 * @author Misagh Moayyed
 * @since 5.1.0
 */
public final class ControllerUtils {
    private ControllerUtils() {
    }

    /**
     * Configure model map for config server cloud bus endpoints.
     *
     * @param busProperties          the bus properties
     * @param configServerProperties the config server properties
     * @param path                   the path
     * @param model                  the model
     */
    public static void configureModelMapForConfigServerCloudBusEndpoints(final BusProperties busProperties,
                                                                         final ConfigServerProperties configServerProperties,
                                                                         final String path,
                                                                         final Map model) {
        if (busProperties != null && busProperties.isEnabled()) {
            model.put("refreshEndpoint", path + configServerProperties.getPrefix() + "/cas/bus/refresh");
            model.put("refreshMethod", "GET");
        } else {
            model.put("refreshEndpoint", path + "/status/refresh");
            model.put("refreshMethod", "POST");
        }
    }
}

package org.apereo.cas.web.report;

import org.springframework.cloud.bus.BusProperties;
import org.springframework.cloud.config.server.config.ConfigServerProperties;

import java.util.Map;

/**
 * This is {@link ControllerUtils}.
 *
 * @author Misagh Moayyed
 * @since 5.1.0
 */
final class ControllerUtils {
    private ControllerUtils() {
    }

    /**
     * Configure model map for config server cloud bus endpoints.
     *
     * @param busProperties          the bus properties
     * @param configServerProperties the config server properties
     * @param path                   the path
     * @param model                  the model
     */
    public static void configureModelMapForConfigServerCloudBusEndpoints(final BusProperties busProperties,
                                                                         final ConfigServerProperties configServerProperties,
                                                                         final String path,
                                                                         final Map model) {
        if (busProperties != null && busProperties.isEnabled()) {
            model.put("refreshEndpoint", path + configServerProperties.getPrefix() + "/cas/bus/refresh");
            model.put("refreshMethod", "GET");
        } else {
            model.put("refreshEndpoint", path + "/status/refresh");
            model.put("refreshMethod", "POST");
        }
    }
}

Clean up duplicate code in controllers


/*
 * oxTrust is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
 *
 * Copyright (c) 2014, Gluu
 */

/**
 *
 */
package org.gluu.oxtrust.model;

import java.util.List;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

/**
 * @author "Oleksiy Tataryn"
 *
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class RegistrationConfiguration {

	private List<String> additionalAttributes;

	private boolean isCaptchaDisabled;

    public List<String> getAdditionalAttributes() {
        return additionalAttributes;
    }

    public void setAdditionalAttributes(List<String> additionalAttributes) {
        this.additionalAttributes = additionalAttributes;
    }

    public boolean isCaptchaDisabled() {
        return isCaptchaDisabled;
    }

    public void setCaptchaDisabled(boolean captchaDisabled) {
        isCaptchaDisabled = captchaDisabled;
    }

}

/*
 * oxTrust is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
 *
 * Copyright (c) 2014, Gluu
 */

/**
 *
 */
package org.gluu.oxtrust.model;

import java.io.Serializable;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

/**
 * @author "Oleksiy Tataryn"
 *
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class RegistrationConfiguration implements Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = -7310064771467874959L;

	/**
	 *
	 */

	private List<String> additionalAttributes;

	private boolean isCaptchaDisabled;

    public List<String> getAdditionalAttributes() {
        return additionalAttributes;
    }

    public void setAdditionalAttributes(List<String> additionalAttributes) {
        this.additionalAttributes = additionalAttributes;
    }

    public boolean isCaptchaDisabled() {
        return isCaptchaDisabled;
    }

    public void setCaptchaDisabled(boolean captchaDisabled) {
        isCaptchaDisabled = captchaDisabled;
    }

}

Fix serialization issue for oxRegistration class


package alien4cloud.webconfiguration;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class StaticResourcesConfiguration extends WebMvcConfigurerAdapter {
    @Value("file:///${directories.alien}/${directories.csar_repository}/")
    private String toscaRepo;
    @Value("file:///${directories.alien}/work/plugins/ui/")
    private String pluginsUi;

    public final static String PLUGIN_STATIC_ENDPOINT = "/static/plugins/";

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/tosca/**").addResourceLocations(toscaRepo);
        registry.addResourceHandler(PLUGIN_STATIC_ENDPOINT + "**").addResourceLocations(pluginsUi);
    }
}

package alien4cloud.webconfiguration;

import java.nio.file.Paths;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Slf4j
@Configuration
public class StaticResourcesConfiguration extends WebMvcConfigurerAdapter {
    @Value("${directories.alien}/${directories.csar_repository}/")
    private String toscaRepo;
    @Value("${directories.alien}/work/plugins/ui/")
    private String pluginsUi;

    public final static String PLUGIN_STATIC_ENDPOINT = "/static/plugins/";

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String prefix = "file:///";
        // resource locations must be full path and not relatives
        String absToscaRepo = prefix.concat(Paths.get(toscaRepo).toAbsolutePath().toString()).concat("/");
        String absPluginUi = prefix.concat(Paths.get(pluginsUi).toAbsolutePath().toString()).concat("/");
        log.info("Serving {} as tosca repo content.", absToscaRepo);
        log.info("Serving {} as plugin ui content.", absPluginUi);
        registry.addResourceHandler("/static/tosca/**").addResourceLocations(absToscaRepo);
        registry.addResourceHandler(PLUGIN_STATIC_ENDPOINT + "**").addResourceLocations(absPluginUi);
    }
}

Fix an issue causing alien4cloud static resources (csar and plugin) to be unavailable when main directory was expressed using relative paths.


package com.hypirion.smallex;

import java.io.Reader;
import java.util.Iterator;

import com.hypirion.smallex.Item;

public class SMLXLexer implements Iterator<Item> {
    private Reader reader;

    public SMLXLexer(Reader reader) {
        this.reader = reader;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }

    @Override
    public Item next() {
        return null;
    }

    @Override
    public boolean hasNext() {
        return false;
    }
}

Add in package header to lexer.


package org.jenkinsci.plugins.github.status.sources;

import hudson.model.Run;
import hudson.model.TaskListener;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.runners.MockitoJUnitRunner;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.when;

/**
 * @author pupssman (Kalinin Ivan)
 */
@RunWith(MockitoJUnitRunner.class)
public class BuildRefBackrefSourceTest {

    @Rule
    public MockitoRule mockitoRule = MockitoJUnit.rule();

    @Mock(answer = Answers.RETURNS_MOCKS)
    private Run run;

    @Mock(answer = Answers.RETURNS_MOCKS)
    private TaskListener listener;

    @Test
    public void shouldReturnRunAbsoluteUrl() throws Exception {
        when(run.getAbsoluteUrl()).thenReturn("ABSOLUTE_URL");

        String result = new BuildRefBackrefSource().get(run, listener);
        assertThat("state", result, is("ABSOLUTE_URL"));
    }

}

package org.jenkinsci.plugins.github.status.sources;

import hudson.model.FreeStyleProject;
import hudson.model.Run;
import hudson.model.TaskListener;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.jvnet.hudson.test.JenkinsRule;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.mockito.runners.MockitoJUnitRunner;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.when;

/**
 * @author pupssman (Kalinin Ivan)
 */
@RunWith(MockitoJUnitRunner.class)
public class BuildRefBackrefSourceTest {

    @Rule
    public JenkinsRule jenkinsRule = new JenkinsRule();

    @Mock(answer = Answers.RETURNS_MOCKS)
    private TaskListener listener;

    @Test
    /**
     * Should've used mocked Run, but getAbsoluteUrl is final.
     *
     * @throws Exception
     */
    public void shouldReturnRunAbsoluteUrl() throws Exception {
        Run<?, ?> run = jenkinsRule.buildAndAssertSuccess(jenkinsRule.createFreeStyleProject());

        String result = new BuildRefBackrefSource().get(run, listener);
        assertThat("state", result, is(run.getAbsoluteUrl()));
    }

}

Change test to using JenkinsRule


/**
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.devtools.cdbg.debuglets.java;

/**
 * Defines the version of the Java Cloud Debugger agent.
 */
public final class GcpDebugletVersion {
  /**
   * Major version of the debugger.

   * All agents of the same major version are compatible with each other. In other words an
   * application can mix different agents with the same major version within the same debuggee.
   */
  public static final int MAJOR_VERSION = 2;

  /**
   * Minor version of the agent.
   */
  public static final int MINOR_VERSION = 14;

  /**
   * Debugger agent version string in the format of MAJOR.MINOR.
   */
  public static final String VERSION = String.format("%d.%d", MAJOR_VERSION, MINOR_VERSION);

  /**
   * Main function to print the version string.
   */
  public static void main(String[] args) {
    System.out.println(VERSION);
  }
}

/**
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.devtools.cdbg.debuglets.java;

/**
 * Defines the version of the Java Cloud Debugger agent.
 */
public final class GcpDebugletVersion {
  /**
   * Major version of the debugger.

   * All agents of the same major version are compatible with each other. In other words an
   * application can mix different agents with the same major version within the same debuggee.
   */
  public static final int MAJOR_VERSION = 2;

  /**
   * Minor version of the agent.
   */
  public static final int MINOR_VERSION = 15;

  /**
   * Debugger agent version string in the format of MAJOR.MINOR.
   */
  public static final String VERSION = String.format("%d.%d", MAJOR_VERSION, MINOR_VERSION);

  /**
   * Main function to print the version string.
   */
  public static void main(String[] args) {
    System.out.println(VERSION);
  }
}

Increment minor version to 2.15 to prepare for a new release.


package com.stacktoheap.go.docker.Commands.BuildCommands;

import com.stacktoheap.go.docker.Commands.DockerCommand;
import com.stacktoheap.go.docker.Config;
import com.stacktoheap.go.docker.Context;
import org.apache.commons.io.FilenameUtils;

public class DockerBuildCommand extends DockerCommand {

    public DockerBuildCommand(Context taskContext, Config taskConfig) {
        super(taskContext, taskConfig);
    }

    @Override
    public void buildCommand(Context taskContext, Config taskConfig) {
        command.add("docker");
        command.add("build");

        command.add("-t");
        command.add(getTemporaryImageTag(taskContext));

        String dockerFilePath = FilenameUtils.concat(taskContext.getWorkingDir(), taskConfig.dockerFile);
        command.add(dockerFilePath);
    }

    @Override
    protected boolean shouldRun(Context taskContext, Config taskConfig) {
        return taskConfig.isDockerBuild;
    }
}

package com.stacktoheap.go.docker.Commands.BuildCommands;

import com.stacktoheap.go.docker.Commands.DockerCommand;
import com.stacktoheap.go.docker.Config;
import com.stacktoheap.go.docker.Context;
import org.apache.commons.io.FilenameUtils;

public class DockerBuildCommand extends DockerCommand {

    public DockerBuildCommand(Context taskContext, Config taskConfig) {
        super(taskContext, taskConfig);
    }

    @Override
    public void buildCommand(Context taskContext, Config taskConfig) {
        command.add("build");

        command.add("-t");
        command.add(getTemporaryImageTag(taskContext));

        String dockerFilePath = FilenameUtils.concat(taskContext.getWorkingDir(), taskConfig.dockerFile);
        command.add(dockerFilePath);
    }

    @Override
    protected boolean shouldRun(Context taskContext, Config taskConfig) {
        return taskConfig.isDockerBuild;
    }
}

Remove redundant "docker" string in the command


/**
 *
 */
package com.trendrr.oss.concurrent;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Simple threadsafe lazy init object.
 *
 * usage:
 *
 * LazyInit<MyObject> obj = new LazyInit<MyObject>() {
 * 	@Override
 * 	public MyObject init() {
 * 		return new MyObject();
 * 	}
 * }
 *
 *
 * MyObject my = obj.get();
 *
 * @author Dustin Norlander
 * @created Aug 31, 2011
 *
 */
public abstract class LazyInitObject<T> {

	protected Log log = LogFactory.getLog(LazyInitObject.class);

	T object;
	LazyInit lock = new LazyInit();

	public abstract T init();

	public T get() {
		if (lock.start()) {
			try {
				this.object = this.init();
			} finally {
				lock.end();
			}
		}
		return object;
	}

	/**
	 * will reset this object to initialize again (on the next get() method call)
	 */
	public void reset() {
		lock.reset();
	}
}

/**
 *
 */
package com.trendrr.oss.concurrent;

import java.util.concurrent.atomic.AtomicReference;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Simple threadsafe lazy init object.
 *
 * usage:
 *
 * LazyInit<MyObject> obj = new LazyInit<MyObject>() {
 * 	@Override
 * 	public MyObject init() {
 * 		return new MyObject();
 * 	}
 * }
 *
 *
 * MyObject my = obj.get();
 *
 * @author Dustin Norlander
 * @created Aug 31, 2011
 *
 */
public abstract class LazyInitObject<T> {

	protected Log log = LogFactory.getLog(LazyInitObject.class);

	AtomicReference<T> object;
	LazyInit lock = new LazyInit();

	public abstract T init();

	public T get() {
		if (lock.start()) {
			try {
				this.object.set(this.init());
			} finally {
				lock.end();
			}
		}
		return object.get();
	}

	/**
	 * will reset this object to initialize again (on the next get() method call)
	 */
	public void reset() {
		lock.reset();
	}

	/**
	 * atomically sets the reference and sets the init to not run.
	 * @param object
	 */
	public void set(T object) {
		lock.start();
		try {
			this.object.set(object);
		} finally {
			lock.end();
		}
	}
}

Add set to lazy init object, to bypass init code if needed


package com.anprosit.android.dagger.factory;

import android.content.Context;
import android.media.MediaPlayer;

/**
 * Created by Hirofumi Nakagawa on 13/09/06.
 */
public class MediaPlayerFactory {
	public MediaPlayer create(Context context, int resId) {
		return MediaPlayer.create(context, resId);
	}

	public MediaPlayer create() {
		return new MediaPlayer();
	}
}

package com.anprosit.android.dagger.factory;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;

/**
 * @author hnakagawa
 */
public class MediaPlayerFactory {
	public MediaPlayer create(Context context, int resId) {
		return MediaPlayer.create(context, resId);
	}

	public MediaPlayer create(Context context, Uri uri) {
		return MediaPlayer.create(context, uri);
	}

	public MediaPlayer create() {
		return new MediaPlayer();
	}
}

Add factory method for media player


package reborncore.common;

import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import reborncore.RebornCore;

public abstract class BaseTileBlock extends Block implements ITileEntityProvider
{
	protected BaseTileBlock(Material materialIn)
	{
		super(materialIn);
		RebornCore.jsonDestroyer.registerObject(this);
	}

	public int getRenderType()
	{
		return 3;
	}

	@Override
	public void breakBlock(World worldIn, BlockPos pos, IBlockState state)
	{
		super.breakBlock(worldIn, pos, state);
		worldIn.removeTileEntity(pos);
	}
}

package reborncore.common;

import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import reborncore.RebornCore;

public abstract class BaseTileBlock extends Block implements ITileEntityProvider
{
	protected BaseTileBlock(Material materialIn)
	{
		super(materialIn);
		RebornCore.jsonDestroyer.registerObject(this);
		setHardness(1F);
	}

	public int getRenderType()
	{
		return 3;
	}

	@Override
	public void breakBlock(World worldIn, BlockPos pos, IBlockState state)
	{
		super.breakBlock(worldIn, pos, state);
		worldIn.removeTileEntity(pos);
	}
}

Add a hardness to the base block


package utask.model.util;

import utask.commons.exceptions.IllegalValueException;
import utask.model.ReadOnlyUTask;
import utask.model.UTask;
import utask.model.tag.UniqueTagList;
import utask.model.task.Deadline;
import utask.model.task.EventTask;
import utask.model.task.Frequency;
import utask.model.task.Name;
import utask.model.task.Task;
import utask.model.task.Timestamp;
import utask.model.task.UniqueTaskList.DuplicateTaskException;

public class SampleDataUtil {
    public static Task[] getSamplePersons() {
        try {
            return new Task[] {
                new EventTask(new Name("My first task"), new Deadline("010117"), new Timestamp("0900 to 1000"),
                new Frequency("-"),
                new UniqueTagList("important"))
            };
        } catch (IllegalValueException e) {
            throw new AssertionError("sample data cannot be invalid", e);
        }
    }

    public static ReadOnlyUTask getSampleAddressBook() {
        try {
            UTask sampleAB = new UTask();
            for (Task sampleTask : getSamplePersons()) {
                sampleAB.addTask(sampleTask);
            }
            return sampleAB;
        } catch (DuplicateTaskException e) {
            throw new AssertionError("sample data cannot contain duplicate persons", e);
        }
    }
}

package utask.model.util;

import utask.commons.exceptions.IllegalValueException;
import utask.model.ReadOnlyUTask;
import utask.model.UTask;
import utask.model.tag.UniqueTagList;
import utask.model.task.Deadline;
import utask.model.task.EventTask;
import utask.model.task.Frequency;
import utask.model.task.IsCompleted;
import utask.model.task.Name;
import utask.model.task.Task;
import utask.model.task.Timestamp;
import utask.model.task.UniqueTaskList.DuplicateTaskException;

public class SampleDataUtil {
    public static Task[] getSamplePersons() {
        try {
            return new Task[] {
                new EventTask(new Name("My first task"), new Deadline("010117"), new Timestamp("0900 to 1000"),
                new Frequency("-"),
                new UniqueTagList("important"),
                new IsCompleted("no"))
            };
        } catch (IllegalValueException e) {
            throw new AssertionError("sample data cannot be invalid", e);
        }
    }

    public static ReadOnlyUTask getSampleAddressBook() {
        try {
            UTask sampleAB = new UTask();
            for (Task sampleTask : getSamplePersons()) {
                sampleAB.addTask(sampleTask);
            }
            return sampleAB;
        } catch (DuplicateTaskException e) {
            throw new AssertionError("sample data cannot contain duplicate persons", e);
        }
    }
}

Update SampleDateUtil to include isCompleted during Task creation


/*
 * Copyright 2014 Danilo Reinert
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.reinert.requestor.impl.gdeferred;

import io.reinert.requestor.Response;

/**
 * DoneCallback with optional access to the response.
 *
 * @param <T> Type of the response payload
 */
public abstract class DoneCallback<T> implements io.reinert.gdeferred.DoneCallback<T> {

    @Override
    public void onDone(T result) {
    }

    public void onDone(Response<T> response) {
        onDone(response.getPayload());
    }
}

/*
 * Copyright 2014 Danilo Reinert
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.reinert.requestor.impl.gdeferred;

import io.reinert.requestor.RawResponseImpl;
import io.reinert.requestor.Response;

/**
 * DoneCallback with optional access to the response.
 *
 * @param <T> Type of the response payload
 */
public abstract class DoneCallback<T> implements io.reinert.gdeferred.DoneCallback<T> {

    @Override
    public void onDone(T result) {
    }

    /**
     * If you want to access the Response attributes, then override this method.
     *
     * @param response  the HTTP Response returned from the Request.
     */
    @SuppressWarnings("unchecked")
    public void onDone(Response<T> response) {
        if (response instanceof RawResponseImpl) {
            onDone((T) response);
            return;
        }

        onDone(response.getPayload());
    }
}

Fix callback cast of SerializeResponse


package org.skyve.metadata.view;

import javax.xml.bind.annotation.XmlType;

import org.skyve.impl.util.XMLMetaData;

public interface TextOutput {
	Boolean getEscape();

	@XmlType(namespace = XMLMetaData.VIEW_NAMESPACE)
	public static enum Sanitisation {
		// Note the values are ordered from least restrictive to most restrictive so we can compare the ordinals

		// No sanitisation applied
		none,
		// CSS too
		relaxed,
		// Formatting tags, structural tags, links and images
		basic,
		// Formatting tags only
		simple,
		// Only Text - no HTML
		text
	}

	Sanitisation getSanitise();
}

package org.skyve.metadata.view;

import javax.xml.bind.annotation.XmlType;

import org.skyve.impl.util.XMLMetaData;

public interface TextOutput {
	Boolean getEscape();

	@XmlType(namespace = XMLMetaData.VIEW_NAMESPACE)
	public static enum Sanitisation {
		// Note the values are ordered from least restrictive to most restrictive so we can compare the ordinals

		// No sanitisation applied
		none,
		// Formatting tags, structural tags, links and images and CSS too
		relaxed,
		// Formatting tags, structural tags, links and images
		basic,
		// Formatting tags only
		simple,
		// Only Text - no HTML
		text
	}

	Sanitisation getSanitise();
}

Change comment on Sanitisation enum to be more clearer.


/**
 * Project RSA Algorithm.
 * Copyright Michał Szczygieł.
 * Created at Feb 24, 2014.
 */

/**
 * TODO COMMENTS MISSING!
 *
 * @author Michał Szczygieł <michal.szczygiel@wp.pl>
 *
 */
public interface Encryption {

}

import java.math.BigInteger;

/**
 * Project RSA Algorithm.
 * Copyright Michał Szczygieł.
 * Created at Feb 24, 2014.
 */

/**
 * This interface describe the basic operation with encryption algorithm.
 *
 * @author Michał Szczygieł <michal.szczygiel@wp.pl>
 *
 */
public interface Encryption {

    /**
     * This method makes operation to achieve decrypted message.
     *
     * @param valueToDecrypt
     *            The value of which will be performed the decryption process.
     * @return Decrypted value.
     */
    public BigInteger decrypt(BigInteger valueToDecrypt);

    /**
     * This method makes operation to create encrypted message.
     *
     * @param valueToEncrypt
     *            The value of which will be performed the encryption process
     * @return Encrypted value.
     */
    public BigInteger encrypt(BigInteger valueToEncrypt);

}

Define interface for encryption operations


// BSD License (http://lemurproject.org/galago-license)
package org.lemurproject.galago.core.index;

import org.lemurproject.galago.core.retrieval.iterator.BaseIterator;

import java.io.IOException;

/**
 * Each iterator from an index has an extra two methods,
 * getValueString() and nextKey(), that allows the data from
 * the index to be easily printed.  DumpIndex uses this functionality
 * to dump the contents of any Galago index.
 *
 * (2/22/2011, irmarc): Refactored into the index package to indicate this is functionality
 *                      that a disk-based iterator should have.
 *
 * @author trevor, irmarc
 */
public interface KeyIterator extends Comparable<KeyIterator> {

  // moves iterator to some particular key
  public boolean findKey(byte[] key) throws IOException;

  // moves iterator to a particular key (forward direction only)
  public boolean skipToKey(byte[] key) throws IOException;

  // moves iterator to the next key
  public boolean nextKey() throws IOException;

  // true if the iterator has moved past the last key
  public boolean isDone();

  // resets iterator to the first key
  public void reset() throws IOException;

  // Access to key data
  public byte[] getKey() throws IOException;
  public String getKeyString() throws IOException;

  // Access to the key's value. (Not all may be implemented)
  public byte[] getValueBytes() throws IOException;
  public String getValueString() throws IOException;
  public BaseIterator getValueIterator() throws IOException;
}

// BSD License (http://lemurproject.org/galago-license)
package org.lemurproject.galago.core.index;

import org.lemurproject.galago.core.retrieval.iterator.BaseIterator;
import org.lemurproject.galago.utility.ByteUtil;

import java.io.IOException;

/**
 * Each iterator from an index has an extra two methods,
 * getValueString() and nextKey(), that allows the data from
 * the index to be easily printed.  DumpIndex uses this functionality
 * to dump the contents of any Galago index.
 *
 * (2/22/2011, irmarc): Refactored into the index package to indicate this is functionality
 *                      that a disk-based iterator should have.
 *
 * @author trevor, irmarc
 */
public interface KeyIterator extends Comparable<KeyIterator> {

  // moves iterator to some particular key
  public boolean findKey(byte[] key) throws IOException;

  default boolean findKey(String key) throws IOException {
    return findKey(ByteUtil.fromString(key));
  }

  // moves iterator to a particular key (forward direction only)
  public boolean skipToKey(byte[] key) throws IOException;

  // moves iterator to the next key
  public boolean nextKey() throws IOException;

  // true if the iterator has moved past the last key
  public boolean isDone();

  // resets iterator to the first key
  public void reset() throws IOException;

  // Access to key data
  public byte[] getKey() throws IOException;
  public String getKeyString() throws IOException;

  // Access to the key's value. (Not all may be implemented)
  public byte[] getValueBytes() throws IOException;
  public String getValueString() throws IOException;
  public BaseIterator getValueIterator() throws IOException;
}

Add default method for finding strings rather than byte[]


import org.fluentlenium.adapter.FluentTest;
import org.junit.ClassRule;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

import static org.assertj.core.api.Assertions.assertThat;

public class IntegrationTest extends FluentTest {
  public WebDriver webDriver = new HtmlUnitDriver();

  @Override
  public WebDriver getDefaultDriver() {
    return webDriver;
  }

  @ClassRule
  public static ServerRule server = new ServerRule();

  @Test
  public void rootTest() {
    goTo("http://localhost:4567/");
    assertThat(pageSource()).contains("Shipping Calculator");
  }

  @Test
  public void resultsTest_returnsCostCorrectly() {
    goTo("http://localhost:4567/");
    fill("#length").with("10");
    fill("#width").with("10");
    fill("#height").with("10");
    fill("#weight").with("5");
    fill("#distance").with("100");
    submit(".btn");
    assertThat(pageSource()).contains("Cost to Ship: 5000");
  }

}

import org.fluentlenium.adapter.FluentTest;
import org.junit.ClassRule;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

import static org.assertj.core.api.Assertions.assertThat;

public class IntegrationTest extends FluentTest {
  public WebDriver webDriver = new HtmlUnitDriver();

  @Override
  public WebDriver getDefaultDriver() {
    return webDriver;
  }

  @ClassRule
  public static ServerRule server = new ServerRule();

  @Test
  public void rootTest() {
    goTo("http://localhost:4567/");
    assertThat(pageSource()).contains("Shipping Calculator");
  }

  @Test
  public void resultsTest_returnsCostCorrectly() {
    goTo("http://localhost:4567/");
    fill("#length").with("10");
    fill("#width").with("10");
    fill("#height").with("10");
    fill("#weight").with("5");
    fill("#distance").with("100");
    submit(".btn");
    assertThat(pageSource()).contains("Base Shipping Cost: $50.00");
  }

}

Correct expected output for integration test


package uk.ac.ebi.quickgo.annotation.service.converter;

import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocument;
import uk.ac.ebi.quickgo.annotation.model.Annotation;

/**
 * @author Tony Wardell
 * Date: 26/04/2016
 * Time: 16:47
 * Created with IntelliJ IDEA.
 */
public interface AnnotationDocConverter {

    /**
     * Convert an Annotation Document into a model to be returned to the user
     * @param annotationDocument  A document retrieved from the Annotation data source
     * @return an Annotation model
     */
    Annotation convert(AnnotationDocument annotationDocument);
}

package uk.ac.ebi.quickgo.annotation.service.converter;

import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocument;
import uk.ac.ebi.quickgo.annotation.model.Annotation;

/**
 * Converts an {@link AnnotationDocument} into an instance of {@link Annotation}.
 *
 * @author Tony Wardell
 * Date: 26/04/2016
 * Time: 16:47
 */
public interface AnnotationDocConverter {

    /**
     * Convert an Annotation Document into a model to be returned to the user
     * @param annotationDocument  A document retrieved from the Annotation data source
     * @return an Annotation model
     */
    Annotation convert(AnnotationDocument annotationDocument);
}

Improve more JavaDoc to interface.


/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.camel;

/**
 * A processor is used to implement the
 *  Event Driven Consumer
 * and  Message Translator
 * patterns and to process message exchanges.
 *
 * @version
 */
public interface Processor {

    /**
     * Processes the message exchange
     *
     * @param exchange the message exchange
     * @throws Exception if an internal processing error has occurred.
     */
    void process(Exchange exchange) throws Exception;
}

/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.camel;

/**
 * A processor is used to implement the
 *  Event Driven Consumer
 * and  Message Translator
 * patterns and to process message exchanges.
 *

 * Notice if you use a {@link Processor} in a Camel route, then make sure to write the {@link Processor}
 * in a thread-safe way, as the Camel routes can potentially be executed by concurrent threads, and therefore
 * multiple threads can call the same {@link Processor} instance.
 *
 * @version
 */
public interface Processor {

    /**
     * Processes the message exchange
     *
     * @param exchange the message exchange
     * @throws Exception if an internal processing error has occurred.
     */
    void process(Exchange exchange) throws Exception;
}

Add to javadoc about thread safety in a processor in a route


// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.sdk.internal.wip.protocol.input;

import java.util.List;

import org.chromium.sdk.internal.protocolparser.JsonOptionalField;
import org.chromium.sdk.internal.protocolparser.JsonProtocolParseException;
import org.chromium.sdk.internal.protocolparser.JsonSubtypeCasting;
import org.chromium.sdk.internal.protocolparser.JsonType;

@JsonType(subtypesChosenManually=true)
public interface WipTabList {
  @JsonSubtypeCasting List<TabDescription> asTabList() throws JsonProtocolParseException;

  @JsonType interface TabDescription {
    String id();
    String faviconUrl();
    String title();
    String url();

    String thumbnailUrl();

    // TODO: consider adding enum here
    String type();

    @JsonOptionalField
    String devtoolsFrontendUrl();

    @JsonOptionalField
    String webSocketDebuggerUrl();
  }
}

// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.sdk.internal.wip.protocol.input;

import java.util.List;

import org.chromium.sdk.internal.protocolparser.JsonOptionalField;
import org.chromium.sdk.internal.protocolparser.JsonProtocolParseException;
import org.chromium.sdk.internal.protocolparser.JsonSubtypeCasting;
import org.chromium.sdk.internal.protocolparser.JsonType;

@JsonType(subtypesChosenManually=true)
public interface WipTabList {
  @JsonSubtypeCasting List<TabDescription> asTabList() throws JsonProtocolParseException;

  @JsonType interface TabDescription {
    String id();
    String faviconUrl();
    String title();
    String url();

    String thumbnailUrl();

    // TODO: consider adding enum here
    String type();

    @JsonOptionalField
    String description();

    @JsonOptionalField
    String devtoolsFrontendUrl();

    @JsonOptionalField
    String webSocketDebuggerUrl();
  }
}

Add new tab JSON field


package com.vaguehope.onosendai.update;

import android.content.Intent;

import com.vaguehope.onosendai.images.HybridBitmapCache;
import com.vaguehope.onosendai.storage.AttachmentStorage;
import com.vaguehope.onosendai.storage.DbBindingService;
import com.vaguehope.onosendai.util.LogWrapper;

/*
 * TODO move this class?
 */
public class CleanupService extends DbBindingService {

	protected static final LogWrapper LOG = new LogWrapper("CS");

	public CleanupService () {
		super("OnosendaiCleanupService", LOG);
	}

	@Override
	protected void doWork (final Intent i) {
		try {
			AttachmentStorage.cleanTempOutputDir(this); // FIXME what if attachment in use in Outbox?
			HybridBitmapCache.cleanCacheDir(this);
			if (!waitForDbReady()) return;
			getDb().vacuum();
			LOG.i("Clean up complete.");
		}
		catch (final Exception e) { // NOSONAR want to log all errors.
			LOG.e("Clean up failed.", e);
		}
	}

}

package com.vaguehope.onosendai.update;

import android.content.Intent;

import com.vaguehope.onosendai.images.HybridBitmapCache;
import com.vaguehope.onosendai.storage.AttachmentStorage;
import com.vaguehope.onosendai.storage.DbBindingService;
import com.vaguehope.onosendai.util.LogWrapper;

/*
 * TODO move this class?
 */
public class CleanupService extends DbBindingService {

	protected static final LogWrapper LOG = new LogWrapper("CS");

	public CleanupService () {
		super("OnosendaiCleanupService", LOG);
	}

	@Override
	protected void doWork (final Intent i) {
		try {
			AttachmentStorage.cleanTempOutputDir(this); // FIXME what if attachment in use in Outbox?
			HybridBitmapCache.cleanCacheDir(this);
			if (!waitForDbReady()) return;
//			getDb().vacuum();
			LOG.i("Clean up complete.");
		}
		catch (final Exception e) { // NOSONAR want to log all errors.
			LOG.e("Clean up failed.", e);
		}
	}

}

Disable DB vacuum cleanup step and it was not the root cause of the problem.


package net.sf.jabref.model.metadata;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

public class ContentSelectors {

    private HashMap<String, List<String>> contentSelectors;

    public ContentSelectors() {
        contentSelectors = new HashMap<>();
    }

    public void addContentSelector(String fieldName, List<String> selectors) {
        Objects.requireNonNull(fieldName);
        Objects.requireNonNull(selectors);

        this.contentSelectors.put(fieldName, selectors);
    }

    public List<String> getSelectorsForField(String fieldName) {
        List<String> result = contentSelectors.get(fieldName);

        if(result == null){
            result = Collections.emptyList();
        }

        return result;
    }

    public void removeSelector(String fieldName) {
        contentSelectors.remove(fieldName);
    }

    public static ContentSelectors parse(List<String> selectors) {
        //fixme: do the actual parsing

        return null;
    }

    public List<String> getAsStringList() {
        // fixme: do the actual serialization

        return null;
    }

    public HashMap<String, List<String>> getSelectorData() {
        return contentSelectors;
    }
}

package net.sf.jabref.model.metadata;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class ContentSelectors {

    private final Map<String, List<String>> contentSelectors;

    public ContentSelectors() {
        contentSelectors = new HashMap<>();
    }

    public void addContentSelector(String fieldName, List<String> selectors) {
        Objects.requireNonNull(fieldName);
        Objects.requireNonNull(selectors);

        this.contentSelectors.put(fieldName, selectors);
    }

    public List<String> getSelectorsForField(String fieldName) {
        List<String> result = contentSelectors.get(fieldName);

        if (result == null) {
            result = Collections.emptyList();
        }

        return result;
    }

    public void removeSelector(String fieldName) {
        contentSelectors.remove(fieldName);
    }

    public static ContentSelectors parse(List<String> selectors) {
        //fixme: do the actual parsing

        return null;
    }

    public List<String> getAsStringList() {
        // fixme: do the actual serialization

        return null;
    }

    public Map<String, List<String>> getSelectorData() {
        return contentSelectors;
    }
}

Fix codacy, use Interface instead of concrete type


/**
 * Copyright (C) 2009-2017 Simonsoft Nordic AB
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package se.simonsoft.cms.item.command;

import se.simonsoft.cms.item.CmsItemId;

public class ExternalCommand {

	private CmsItemId itemId;
	private String action;
	private String jsonargs = null;

	public ExternalCommand(CmsItemId itemId, String action, String jsonArgs) {
		this.itemId = itemId;
		this.action = action;
		this.jsonargs = jsonArgs;
	}

	public String getAction() {
		return action;
	}

	public CmsItemId getItemId() {
		return itemId;
	}

	public <T> T getArgs(Class<T> argumentsWrapperClass) {

		// TODO: Parse jsonargs into the requested type.
		return null;
	}
}

/**
 * Copyright (C) 2009-2017 Simonsoft Nordic AB
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package se.simonsoft.cms.item.command;

import se.simonsoft.cms.item.CmsItemId;

public class ExternalCommand {

	protected CmsItemId itemId;
	protected String action;
	protected String jsonargs = null;

	public ExternalCommand(CmsItemId itemId, String action, String jsonArgs) {
		this.itemId = itemId;
		this.action = action;
		this.jsonargs = jsonArgs;
	}

	public String getAction() {
		return action;
	}

	public CmsItemId getItemId() {
		return itemId;
	}

	public <T> T getArgs(Class<T> argumentsWrapperClass) {

		// TODO: Parse jsonargs into the requested type.
		return null;
	}
}

Enable extending classes to access fields.


package groovy.io;

import groovy.text.SimpleTemplateEngine;
import groovy.text.Template;
import junit.framework.TestCase;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

public class PlatformLineWriterTest extends TestCase {

    public void testPlatformLineWriter() throws IOException, ClassNotFoundException {
        String LS = System.getProperty("line.separator");
        Map binding = new HashMap();
        binding.put("first", "Tom");
        binding.put("last", "Adams");
        Template template = new SimpleTemplateEngine().createTemplate("<%= first %>\n<% println last %>");
        StringWriter stringWriter = new StringWriter();
        Writer platformWriter = new PlatformLineWriter(stringWriter);
        template.make(binding).writeTo(platformWriter);
        assertEquals("Tom" + LS + "Adams" + LS, stringWriter.toString());
    }
}

package groovy.io;

import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import junit.framework.TestCase;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

public class PlatformLineWriterTest extends TestCase {

    public void testPlatformLineWriter() throws IOException, ClassNotFoundException {
        String LS = System.getProperty("line.separator");
        Binding binding = new Binding();
        binding.setVariable("first", "Tom");
        binding.setVariable("last", "Adams");
        StringWriter stringWriter = new StringWriter();
        Writer platformWriter = new PlatformLineWriter(stringWriter);
        GroovyShell shell = new GroovyShell(binding);
        platformWriter.write(shell.evaluate("\"$first\\n$last\\n\"").toString());
        assertEquals("Tom" + LS + "Adams" + LS, stringWriter.toString());
        stringWriter = new StringWriter();
        platformWriter = new PlatformLineWriter(stringWriter);
        platformWriter.write(shell.evaluate("\"$first\\r\\n$last\\r\\n\"").toString());
        assertEquals("Tom" + LS + "Adams" + LS, stringWriter.toString());
    }
}

Remove dependency on templating module


package uk.ac.ebi.quickgo.client.service.loader.presets.ff;

/**
 * Represents the column indices required to create a {@link RawNamedPreset} instance.
 *
 * Created 13/09/16
 * @author Edd
 */
interface RawNamedPresetColumns {
    int getIdPosition();

    int getNamePosition();

    int getDescriptionPosition();

    int getRelevancyPosition();

    int getURLPosition();

    int getMaxRequiredColumnCount();

    int getAssociationPosition();

    int getGoEvidencePosition();
}

package uk.ac.ebi.quickgo.client.service.loader.presets.ff;

/**
 * Represents the column indices required to create a {@link RawNamedPreset} instance.
 *
 * Created 13/09/16
 * @author Edd
 */
public interface RawNamedPresetColumns {
    int getIdPosition();

    int getNamePosition();

    int getDescriptionPosition();

    int getRelevancyPosition();

    int getURLPosition();

    int getMaxRequiredColumnCount();

    int getAssociationPosition();
}

Make the interface public so it can be used more widely, remove getGoEvidencePosition()


package hu.advancedweb.scott.runtime;

import org.junit.runner.Description;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;

/**
 * An alternative way to produce the detailed failure reports is to register this JUnit listener.
 *
 * @see ScottReportingRule
 * @author David Csakvari
 */
public class ScottRunListener extends RunListener {

	private Description description;

	@Override
	public void testStarted(Description description) throws Exception {
		this.description = description;
		super.testStarted(description);
	}

	@Override
	public void testFailure(Failure failure) throws Exception {
		// TODO: the simple System.out.println really not fits nicely into the test reports.
		// try changing the original exception's message with reflection. See issue #8.

		System.out.println(failure.getTestHeader() + " FAILED!");
		System.out.println(FailureRenderer.render(description, failure.getException()));
		super.testFailure(failure);
	}
}

package hu.advancedweb.scott.runtime;

import java.lang.reflect.Field;

import org.junit.runner.Description;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;

/**
 * An alternative way to produce the detailed failure reports is to register this JUnit listener.
 *
 * @see ScottReportingRule
 * @author David Csakvari
 */
public class ScottRunListener extends RunListener {

	private Description description;

	@Override
	public void testStarted(Description description) throws Exception {
		this.description = description;
		super.testStarted(description);
	}

	@Override
	public void testFailure(Failure failure) throws Exception {
		String scottReport = FailureRenderer.render(description, failure.getException());
		setExceptionMessage(failure.getException(), scottReport);
		super.testFailure(failure);
	}

	private void setExceptionMessage(Object object, Object fieldValue) {
	    final String fieldName = "detailMessage";
		Class<?> clazz = object.getClass();
	    while (clazz != null) {
	        try {
	            Field field = clazz.getDeclaredField(fieldName);
	            field.setAccessible(true);
	            field.set(object, fieldValue);
	            return;
	        } catch (NoSuchFieldException e) {
	            clazz = clazz.getSuperclass();
	        } catch (Exception e) {
	            throw new IllegalStateException(e);
	        }
	    }
	}
}

Update exception message in run listener rather than just sysoutting the report.


package com.socgen.finit.easymargin;

import com.socgen.finit.easymargin.converter.TradeFileHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.orm.hibernate4.HibernateExceptionTranslator;
import java.util.Arrays;

@Slf4j
@SpringBootApplication
@Import(DefaultConfig.class)
public class Application {

    @Autowired
    TradeFileHandler tradeFileHandler;

    public static void main(String[] args) {

        ApplicationContext ctx = SpringApplication.run(Application.class, args);

        log.info("Let's inspect the beans provided by Spring Boot:");

        String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        for (String beanName : beanNames) {
            log.info(beanName);
        }
    }

    @Bean
    public HibernateExceptionTranslator hibernateExceptionTranslator() {
        return new HibernateExceptionTranslator();
    }
}

package com.socgen.finit.easymargin;

import com.socgen.finit.easymargin.converter.TradeFileHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.orm.hibernate4.HibernateExceptionTranslator;

import java.util.Arrays;

@Slf4j
@SpringBootApplication
@Import(DefaultConfig.class)
public class Application {

    @Autowired
    TradeFileHandler tradeFileHandler;

    public static void main(String[] args) {

        ApplicationContext ctx = SpringApplication.run(Application.class, args);

        log.info("Let's inspect the beans provided by Spring Boot:");

        String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        for (String beanName : beanNames) {
            log.info(beanName);
        }

        log.info("Server started - URL : http//localhost:" +
                ctx.getEnvironment().getProperty("server.port"));
    }

    @Bean
    public HibernateExceptionTranslator hibernateExceptionTranslator() {
        return new HibernateExceptionTranslator();
    }
}

Add automatic launch with maven test phase


package de.hfu.studiportal.data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class ExamCategory implements Serializable {

	private static final long serialVersionUID = -5178814560848378523L;
	private List<Exam> examList;
	private String categoryName;

	public ExamCategory(String categoryName) {
		this.setCategoryName(categoryName);
		this.examList = new ArrayList<>();

	}

	public String getCategoryName() {
		return this.categoryName;

	}

	public void setCategoryName(String newName) {
		this.categoryName = newName.replace(":", "").replace("*", "");

	}

	public void addExam(Exam e) {
		this.examList.add(e);

	}

	public void removeExam(Exam e) {
		this.examList.remove(e);

	}

	public void removeExam(int index) {
		this.examList.remove(index);

	}

	public int getExamCount() {
		return this.examList.size();

	}

	public Exam getExam(int index) {
		return this.examList.get(index);

	}

	public List<Exam> getAllExams() {
		return new ArrayList<>(this.examList);

	}
}

package de.hfu.studiportal.data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class ExamCategory implements Serializable {

	private static final long serialVersionUID = -5178814560848378523L;
	private List<Exam> examList;
	private String categoryName;

	public ExamCategory(String categoryName) {
		this.setCategoryName(categoryName);
		this.examList = new ArrayList<>();

	}

	public String getCategoryName() {
		return this.categoryName;

	}

	public void setCategoryName(String newName) {
		//Replace long terms with short ones to keep the titles short.
		//Replacing only parts of the title will reserve the meaning (even with unknown titles)
		this.categoryName = newName.replace(":", "").replace("*", "")
				.replace("Module/Teilmodule", "Module").replace("(ECTS) ", "")
				.replace("Bestandene Module", "Bestanden").trim();

	}

	public void addExam(Exam e) {
		this.examList.add(e);

	}

	public void removeExam(Exam e) {
		this.examList.remove(e);

	}

	public void removeExam(int index) {
		this.examList.remove(index);

	}

	public int getExamCount() {
		return this.examList.size();

	}

	public Exam getExam(int index) {
		return this.examList.get(index);

	}

	public List<Exam> getAllExams() {
		return new ArrayList<>(this.examList);

	}
}

Optimize category titles through replacing


package io.cattle.platform.agent.instance.service.impl;

import static io.cattle.platform.core.model.tables.NicTable.*;
import io.cattle.platform.agent.instance.service.InstanceNicLookup;
import io.cattle.platform.core.dao.GenericMapDao;
import io.cattle.platform.core.model.Instance;
import io.cattle.platform.core.model.Nic;
import io.cattle.platform.object.ObjectManager;

import java.util.List;

import javax.inject.Inject;

/**
 * This class is invoked on instance healthcheck changes
 *
 *
 */
public class ContainerNicLookup extends NicPerVnetNicLookup implements InstanceNicLookup {
    @Inject
    ObjectManager objectManager;

    @Inject
    GenericMapDao mapDao;

    @Override
    public List<? extends Nic> getNics(Object obj) {
        if (!(obj instanceof Instance)) {
            return null;
        }
        Instance container = (Instance) obj;
        return create().selectFrom(NIC)
                .where(NIC.INSTANCE_ID.eq(container.getId())
                        .and(NIC.REMOVED.isNull()))
                .fetch();
    }
}

package io.cattle.platform.agent.instance.service.impl;

import static io.cattle.platform.core.model.tables.NicTable.*;
import io.cattle.platform.agent.instance.service.InstanceNicLookup;
import io.cattle.platform.core.dao.GenericMapDao;
import io.cattle.platform.core.model.Instance;
import io.cattle.platform.core.model.Nic;
import io.cattle.platform.object.ObjectManager;

import java.util.List;

import javax.inject.Inject;

/**
 * This class is invoked on instance healthcheck changes
 *
 *
 */
public class ContainerNicLookup extends NicPerVnetNicLookup implements InstanceNicLookup {
    @Inject
    ObjectManager objectManager;

    @Inject
    GenericMapDao mapDao;

    @Override
    public List<? extends Nic> getNics(Object obj) {
        if (!(obj instanceof Instance)) {
            return null;
        }
        Instance container = (Instance) obj;
        return create().selectFrom(NIC)
                .where(NIC.INSTANCE_ID.eq(container.getId()))
                .fetch();
    }
}

Fix metadata update on instance.remove