/*
 * Copyright 2017 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.samples.apps.iosched.server.schedule.reservations.model;

/**
 * Representation of a Reservation object in RTDB.
 */
public class Reservation implements Comparable<Reservation> {

  public long last_status_changed;
  public String status;

  @Override
  public int compareTo(Reservation reservation) {
    if (last_status_changed < reservation.last_status_changed) {
      return -1;
    } else if (last_status_changed > reservation.last_status_changed) {
      return 1;
    }
    return 0;
  }
}

/*
 * Copyright 2017 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.samples.apps.iosched.server.schedule.reservations.model;

import java.util.Map;

/**
 * Representation of a Reservation object in RTDB.
 */
public class Reservation implements Comparable<Reservation> {

  public long last_status_changed;
  public String status;
  public Map<String, String> results;

  @Override
  public int compareTo(Reservation reservation) {
    if (last_status_changed < reservation.last_status_changed) {
      return -1;
    } else if (last_status_changed > reservation.last_status_changed) {
      return 1;
    }
    return 0;
  }
}

Add results to LoadSessionServlet model.

Each reservation may contain many results. Since clients may
be depending on these results we will want to keep them
constant when loading sessions from the CMS. This means that
results must be included in the model that is used to update
the reservation.

Change-Id: I8318b3866573b71a4e02dbd43541021f78a57f34


package fi.nls.oskari.spring.security.database;

import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.spring.security.OskariUserHelper;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Hooks in OskariUserHelper.onAuthenticationSuccess(). Extends different Spring class than the similar class
 * in SAML package.
 */
public class OskariAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    private Logger log = LogFactory.getLogger(OskariAuthenticationSuccessHandler.class);
    private OskariUserHelper helper = new OskariUserHelper();

    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, javax.servlet.ServletException {
        log.debug("Database based login successful:", authentication.getPrincipal());
        super.onAuthenticationSuccess(request, response, authentication);
        helper.onAuthenticationSuccess(request, response, authentication);
    }
}

package fi.nls.oskari.spring.security.database;

import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.spring.security.OskariUserHelper;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Hooks in OskariUserHelper.onAuthenticationSuccess(). Extends different Spring class than the similar class
 * in SAML package.
 */
public class OskariAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    private Logger log = LogFactory.getLogger(OskariAuthenticationSuccessHandler.class);
    private OskariUserHelper helper = new OskariUserHelper();
    public OskariAuthenticationSuccessHandler() {
        super();
        setUseReferer(true);
    }

    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, javax.servlet.ServletException {
        log.debug("Database based login successful:", authentication.getPrincipal());
        super.onAuthenticationSuccess(request, response, authentication);
        helper.onAuthenticationSuccess(request, response, authentication);
    }
}

Use referer to detect where to take the user after login


package com.opcoach.training.e4.codesamples;

import javax.inject.Inject;

import org.eclipse.e4.core.contexts.ContextInjectionFactory;
import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.jface.wizard.Wizard;

public class SampleWizard extends Wizard
{
	private SampleWizardPage firstPage = null;

	private IEclipseContext context;

    @Inject
	public SampleWizard(IEclipseContext ctx)
	{
		setWindowTitle("New Wizard");
		context = ctx;
	}

	@Override
	public void addPages()
	{
		firstPage = ContextInjectionFactory.make(SampleWizardPage.class, context);
		addPage(firstPage);
	}

	@Override
	public boolean performFinish()
	{
		// Do your stuff here by asking the pages...
		return true;
	}

}

package com.opcoach.training.e4.codesamples;

import javax.inject.Inject;

import org.eclipse.e4.core.contexts.ContextInjectionFactory;
import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.jface.wizard.Wizard;

public class SampleWizard extends Wizard
{
	private SampleWizardPage firstPage = null;
	private IEclipseContext context;

    @Inject
	public SampleWizard(IEclipseContext ctx)
	{
		setWindowTitle("New Wizard");
		context = ctx;
	}

	@Override
	public void addPages()
	{
		firstPage = ContextInjectionFactory.make(SampleWizardPage.class, context);
		addPage(firstPage);
	}

	@Override
	public void dispose()
	{
		// Don't forget to uninject pages created with make !
		ContextInjectionFactory.uninject(firstPage, context);
		super.dispose();
	}

	@Override
	public boolean performFinish()
	{
		// Do your stuff here by asking the pages...
		// Use an AntRunner to create projects structures or to manipulate files !
		return true;
	}
}

Add an uninject in the wizard dispose

Add an uninject in the wizard dispose

(Fix https://opcoach.atlassian.net/browse/FOR-127)

Change-Id: I6494b5646a52bee20c12a2656aa9c7189a90b0ec
Signed-off-by: Olivier Prouvost <922fcad8957c9a47efb13ab034b8bf0240ed7092@opcoach.com>


package ir_course;

/**
 * Created by martin on 4/9/14.
 */
public class SearchSuite {

    public static final String corpusPath = "corpus_part2.xml";
    private static String[] defaults = {corpusPath};
    public static final String BM25 = "bm25";
    private static String[] bm25Standard = {corpusPath, BM25};
    public static final String PORTER = "PORTER";
    private static String[] bm25Porter = {corpusPath, BM25, PORTER};
    private static String[] vsmPorter = {corpusPath, PORTER};
    public static final String SIMPLE = "SIMPLE";
    private static String[] vsmSimple = {corpusPath, SIMPLE};
    private static String[] bm25Simple = {corpusPath, BM25, SIMPLE};
    public static void main(String[] args) {
        LuceneSearchApp app = new LuceneSearchApp();
        app.main(defaults);
        app.main(bm25Standard);
        app.main(bm25Porter);
        app.main(bm25Simple);
        app.main(vsmSimple);
        app.main(vsmPorter);
    }
}

package ir_course;

/**
 * Created by martin on 4/9/14.
 */
public class SearchSuite {

    public static final String corpusPath = "corpus_part2.xml";
    private static String[] defaults = {corpusPath};
    public static final String BM25 = "bm25";
    private static String[] bm25Standard = {corpusPath, BM25};
    public static final String PORTER = "PORTER";
    private static String[] bm25Porter = {corpusPath, BM25, PORTER};
    private static String[] vsmPorter = {corpusPath, PORTER};
    public static final String SIMPLE = "SIMPLE";
    private static String[] vsmSimple = {corpusPath, SIMPLE};
    private static String[] bm25Simple = {corpusPath, BM25, SIMPLE};
    public static void main(String[] args) {
        LuceneSearchApp app = new LuceneSearchApp();
        app.main(defaults);
        app.main(bm25Standard);
        app.main(bm25Porter);
        app.main(bm25Simple);
        app.main(vsmSimple);
        app.main(vsmPorter);

        runCombination(app, "BM25", defaults, bm25Standard, bm25Porter, bm25Simple, vsmSimple, vsmPorter);
    }

    public static void runCombination(LuceneSearchApp app, String label, String[]... tests) {
    	for( String[] test : tests) {
    		// TODO: print label here
    		app.main(test);
    	}
    }
}

Add combination code to runner

Add combination code to runner


/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the "License"). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.master.journal.noop;

import alluxio.master.journal.Journal;
import alluxio.proto.journal.Journal.JournalEntry;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * Implementation of {@link Journal} that does nothing.
 */
public class NoopJournal implements Journal {

  /**
   * Creates a new instance of {@link NoopJournal}.
   */
  public NoopJournal() {}

  @Override
  public URI getLocation() {
    try {
      return new URI("/noop");
    } catch (URISyntaxException e) {
      throw new RuntimeException(e);
    }
  }

  @Override
  public void write(JournalEntry entry) throws IOException {}

  @Override
  public void flush() throws IOException {}

  @Override
  public void close() throws IOException {}
}

/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the "License"). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.master.journal.noop;

import alluxio.master.journal.Journal;
import alluxio.master.journal.JournalContext;
import alluxio.master.journal.NoopJournalContext;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * Implementation of {@link Journal} that does nothing.
 */
public class NoopJournal implements Journal {

  /**
   * Creates a new instance of {@link NoopJournal}.
   */
  public NoopJournal() {}

  @Override
  public URI getLocation() {
    try {
      return new URI("/noop");
    } catch (URISyntaxException e) {
      throw new RuntimeException(e);
    }
  }

  @Override
  public JournalContext createJournalContext() {
    return new NoopJournalContext();
  }

  @Override
  public void close() throws IOException {}
}

Update noop journal to use JournalContext


package org.ds.chronos.aws;

import org.ds.chronos.api.Chronicle;
import org.ds.chronos.api.PartitionPeriod;
import org.ds.chronos.api.PartitionedChronicle;

import com.amazonaws.services.s3.AmazonS3Client;

public class S3ParitionedChronicle extends PartitionedChronicle {

	final AmazonS3Client client;
	final String bucket;

	public S3ParitionedChronicle(AmazonS3Client client, String bucket, String keyPrefix, PartitionPeriod period) {
		super(keyPrefix, period);
		this.client = client;
		this.bucket = bucket;
	}

	@Override
  protected Chronicle getPartition(String key) {
	  return new S3Chronicle(client, bucket, key);
  }

}

package org.ds.chronos.aws;

import org.ds.chronos.api.Chronicle;
import org.ds.chronos.api.PartitionPeriod;
import org.ds.chronos.api.PartitionedChronicle;

import com.amazonaws.services.s3.AmazonS3Client;

public class S3ParitionedChronicle extends PartitionedChronicle {

	final AmazonS3Client client;
	final String bucket;
	final boolean gzip;

	public S3ParitionedChronicle(AmazonS3Client client, String bucket, String keyPrefix, PartitionPeriod period) {
		this(client, bucket, keyPrefix, period, false);
	}

	public S3ParitionedChronicle(AmazonS3Client client, String bucket, String keyPrefix, PartitionPeriod period,
	    boolean gzip) {
		super(keyPrefix, period);
		this.client = client;
		this.bucket = bucket;
		this.gzip = gzip;
	}

	@Override
	protected Chronicle getPartition(String key) {
		return new S3Chronicle(client, bucket, key, gzip);
	}

}

Add gzip constructor arg to partitioned s3 chronicle


package internal.org.springframework.content.rest.utils;

import org.springframework.data.mapping.PersistentEntity;
import org.springframework.data.mapping.PersistentProperty;
import org.springframework.data.repository.support.Repositories;

import internal.org.springframework.content.rest.controllers.ResourceNotFoundException;

public final class PersistentEntityUtils {

	private PersistentEntityUtils() {}

	public static PersistentEntity<?,?> findPersistentEntity(Repositories repositories,
													  Class<?> domainType) {

		PersistentEntity<?, ?> persistentEntity = repositories.getPersistentEntity(domainType);
		return persistentEntity;
	}

	public static PersistentProperty<?> getPersistentProperty(PersistentEntity<?,?> entity, String propertyName) {

		PersistentProperty<?> prop = entity.getPersistentProperty(propertyName);
		if (null == prop)
			throw new ResourceNotFoundException();

		return prop;
	}

	public static boolean isPropertyMultiValued(PersistentProperty<?> prop) {
		return (prop.isArray() || prop.isCollectionLike());
	}
}

package internal.org.springframework.content.rest.utils;

import org.springframework.data.mapping.PersistentProperty;

public final class PersistentEntityUtils {

	private PersistentEntityUtils() {}

	public static boolean isPropertyMultiValued(PersistentProperty<?> prop) {
		return (prop.isArray() || prop.isCollectionLike());
	}
}

Remove unused persistententity utils code


package fi.nls.oskari.mybatis;

import fi.nls.oskari.service.ServiceRuntimeException;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;

public class MyBatisHelper {

    public static SqlSessionFactory initMyBatis(DataSource ds, Class<?>... mappers) {
        return build(getConfig(ds, mappers));
    }

    public static Configuration getConfig(DataSource ds, Class<?>... mappers) {
        if(ds == null) {
            throw new ServiceRuntimeException("Tried initializing MyBatis without a datasource");
        }
        final TransactionFactory transactionFactory = new JdbcTransactionFactory();
        final Environment environment = new Environment("development", transactionFactory, ds);
        final Configuration configuration = new Configuration(environment);
        configuration.setLazyLoadingEnabled(true);
        addMappers(configuration, mappers);
        return configuration;
    }

    public static void addAliases(Configuration config, Class<?>... aliases) {
        for (Class<?> alias : aliases) {
            config.getTypeAliasRegistry().registerAlias(alias);
        }
    }

    public static void addMappers(Configuration config, Class<?>... mappers) {
        for (Class<?> mapper : mappers) {
            config.addMapper(mapper);
        }
    }

    public static SqlSessionFactory build(Configuration config) {
        return new SqlSessionFactoryBuilder().build(config);
    }
}

package fi.nls.oskari.mybatis;

import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import javax.sql.DataSource;

public class MyBatisHelper {

    public static SqlSessionFactory initMyBatis(DataSource ds, Class<?>... mappers) {
        return build(getConfig(ds, mappers));
    }

    public static Configuration getConfig(DataSource ds, Class<?>... mappers) {
        if (ds == null) {
            throw new NullPointerException("Tried initializing MyBatis without a datasource");
        }
        final TransactionFactory transactionFactory = new JdbcTransactionFactory();
        final Environment environment = new Environment("development", transactionFactory, ds);
        final Configuration configuration = new Configuration(environment);
        configuration.setLazyLoadingEnabled(true);
        addMappers(configuration, mappers);
        return configuration;
    }

    public static void addAliases(Configuration config, Class<?>... aliases) {
        for (Class<?> alias : aliases) {
            config.getTypeAliasRegistry().registerAlias(alias);
        }
    }

    public static void addMappers(Configuration config, Class<?>... mappers) {
        for (Class<?> mapper : mappers) {
            config.addMapper(mapper);
        }
    }

    public static SqlSessionFactory build(Configuration config) {
        return new SqlSessionFactoryBuilder().build(config);
    }
}

Throw NPE instead of ServiceRuntimeException, more fitting


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

import java.util.List;

/**
 * A source of {@link RequiredStatistics} instances.
 *
 * @author Tony Wardell
 * Date: 19/12/2017
 * Time: 11:04
 * Created with IntelliJ IDEA.
 */
public class RequiredStatisticsProvider {

    private final RequiredStatistics standardUsage;
    private final RequiredStatistics downloadUsage;
    private final RequiredStatistics standardUsageWithGeneProductFiltering;
    private final RequiredStatistics downloadUsageWithGeneProductFiltering;

    public RequiredStatisticsProvider(StatisticsTypeConfigurer standardConfiguration, StatisticsTypeConfigurer
            downloadConfiguration) {
        standardUsage = new RequiredStatistics(standardConfiguration);
        downloadUsage = new RequiredStatistics(downloadConfiguration);
        standardUsageWithGeneProductFiltering = new RequiredStatisticsWithGeneProduct(standardConfiguration);
        downloadUsageWithGeneProductFiltering = new RequiredStatisticsWithGeneProduct(downloadConfiguration);
    }

    public List<RequiredStatistic> getStandardUsage() {
        return standardUsage.getRequiredStatistics();
    }

    public List<RequiredStatistic> getDownloadUsage() {
        return downloadUsage.getRequiredStatistics();
    }

    public List<RequiredStatistic> getStandardUsageWithGeneProductFiltering() {
        return standardUsageWithGeneProductFiltering.getRequiredStatistics();
    }

    public List<RequiredStatistic> getDownloadUsageWithGeneProductFiltering() {
        return downloadUsageWithGeneProductFiltering.getRequiredStatistics();
    }
}

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

import java.util.List;
import java.util.Objects;

import static com.google.common.base.Preconditions.checkArgument;

/**
 * A source of {@link RequiredStatistics} instances.
 *
 * @author Tony Wardell
 * Date: 19/12/2017
 * Time: 11:04
 * Created with IntelliJ IDEA.
 */
public class RequiredStatisticsProvider {

    private final RequiredStatistics standardUsage;
    private final RequiredStatistics downloadUsage;
    private final RequiredStatistics standardUsageWithGeneProductFiltering;
    private final RequiredStatistics downloadUsageWithGeneProductFiltering;

    public RequiredStatisticsProvider(StatisticsTypeConfigurer standardConfiguration, StatisticsTypeConfigurer
            downloadConfiguration) {
        checkArgument(Objects.nonNull(standardConfiguration), "The standard StatisticsTypeConfigurer instance cannot" +
                " be null");
        checkArgument(Objects.nonNull(standardConfiguration), "The download StatisticsTypeConfigurer instance cannot" +
                " be null");
        standardUsage = new RequiredStatistics(standardConfiguration);
        downloadUsage = new RequiredStatistics(downloadConfiguration);
        standardUsageWithGeneProductFiltering = new RequiredStatisticsWithGeneProduct(standardConfiguration);
        downloadUsageWithGeneProductFiltering = new RequiredStatisticsWithGeneProduct(downloadConfiguration);
    }

    public List<RequiredStatistic> getStandardUsage() {
        return standardUsage.getRequiredStatistics();
    }

    public List<RequiredStatistic> getDownloadUsage() {
        return downloadUsage.getRequiredStatistics();
    }

    public List<RequiredStatistic> getStandardUsageWithGeneProductFiltering() {
        return standardUsageWithGeneProductFiltering.getRequiredStatistics();
    }

    public List<RequiredStatistic> getDownloadUsageWithGeneProductFiltering() {
        return downloadUsageWithGeneProductFiltering.getRequiredStatistics();
    }
}

Check configuration objects passed to the constructor are not null.


package org.realityforge.replicant.client;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * An event indicating that an imitation has changed.
 */
public final class EntityChangeEvent
{
  private final EntityChangeType _type;
  private final Object _object;
  private final String _name;
  private final Object _value;

  public EntityChangeEvent( @Nonnull final EntityChangeType type, @Nonnull final Object object )
  {
    this( type, object, null, null );
  }

  @SuppressWarnings( { "ConstantConditions" } )
  public EntityChangeEvent( @Nonnull final EntityChangeType type,
                            @Nonnull final Object object,
                            @Nullable final String name,
                            @Nullable final Object value )
  {
    if ( null == type )
    {
      throw new NullPointerException( "type" );
    }
    if ( null == object )
    {
      throw new NullPointerException( "object" );
    }
    _type = type;
    _object = object;
    _name = name;
    _value = value;
  }

  @Nonnull
  public final EntityChangeType getType()
  {
    return _type;
  }

  @Nonnull
  public final Object getObject()
  {
    return _object;
  }

  @Nullable
  public final String getName()
  {
    return _name;
  }

  @Nullable
  public final Object getValue()
  {
    return _value;
  }

  public final String toString()
  {
    final StringBuilder sb = new StringBuilder();
    sb.append( "EntityChange[type=" );
    sb.append( getType().name() );
    sb.append( ",name=" );
    sb.append( getName() );
    sb.append( ",value=" );
    sb.append( getValue() );
    sb.append( ",object=" );
    sb.append( getObject() );
    sb.append( "]" );
    return sb.toString();
  }
}

package org.realityforge.replicant.client;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * An event indicating that an imitation has changed.
 */
public final class EntityChangeEvent
{
  private final EntityChangeType _type;
  private final Object _object;
  private final String _name;
  private final Object _value;

  protected EntityChangeEvent( @Nonnull final EntityChangeType type,
                               @Nonnull final Object object,
                               @Nullable final String name,
                               @Nullable final Object value )
  {
    _type = type;
    _object = object;
    _name = name;
    _value = value;
  }

  @Nonnull
  public final EntityChangeType getType()
  {
    return _type;
  }

  @Nonnull
  public final Object getObject()
  {
    return _object;
  }

  @Nullable
  public final String getName()
  {
    return _name;
  }

  @Nullable
  public final Object getValue()
  {
    return _value;
  }

  /**
   * {@inheritDoc}
   */
  public final String toString()
  {
    final StringBuilder sb = new StringBuilder();
    sb.append( "EntityChange[type=" );
    sb.append( getType().name() );
    sb.append( ",name=" );
    sb.append( getName() );
    sb.append( ",value=" );
    sb.append( getValue() );
    sb.append( ",object=" );
    sb.append( getObject() );
    sb.append( "]" );
    return sb.toString();
  }
}

Simplify the construction of change events and make them protected


/*
 * Copyright 2010 the original author or authors.
 *
 * 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 org.gradle.groovy.scripts;

import org.gradle.internal.service.ServiceRegistry;
import org.gradle.logging.StandardOutputCapture;

/**
 * The base class for all scripts executed by Gradle.
 */
public abstract class Script extends groovy.lang.Script {
    private ScriptSource source;
    private ClassLoader contextClassloader;

    public ScriptSource getScriptSource() {
        return source;
    }

    public void setScriptSource(ScriptSource source) {
        this.source = source;
    }

    public void setContextClassloader(ClassLoader contextClassloader) {
        this.contextClassloader = contextClassloader;
    }

    public ClassLoader getContextClassloader() {
        return contextClassloader;
    }

    public abstract void init(Object target, ServiceRegistry services);

    public abstract StandardOutputCapture getStandardOutputCapture();
}

/*
 * Copyright 2010 the original author or authors.
 *
 * 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 org.gradle.groovy.scripts;

import org.gradle.internal.service.ServiceRegistry;
import org.gradle.logging.StandardOutputCapture;

/**
 * The base class for all scripts executed by Gradle.
 */
public abstract class Script extends groovy.lang.Script {
    private ScriptSource source;
    private ClassLoader contextClassloader;

    public ScriptSource getScriptSource() {
        return source;
    }

    public void setScriptSource(ScriptSource source) {
        this.source = source;
    }

    public void setContextClassloader(ClassLoader contextClassloader) {
        this.contextClassloader = contextClassloader;
    }

    public ClassLoader getContextClassloader() {
        return contextClassloader;
    }

    public abstract void init(Object target, ServiceRegistry services);

    public abstract StandardOutputCapture getStandardOutputCapture();

    @Override
    public Object getProperty(String property) {
        // Refactoring of groovy.lang.Script.getProperty logic
        // to avoid unnecessary MissingPropertyException in binding variable lookup
        if (getBinding().hasVariable(property)) {
            return super.getProperty(property);
        } else {
            return getMetaClass().getProperty(this, property);
        }
    }
}

Reduce MissingPropertyExceptions in Groovy script execution

- Refactoring of groovy.lang.Script.getProperty logic in Gradle's
  Groovy Script subclass to avoid unnecessary MissingPropertyException
  in binding variable lookup.

+review REVIEW-5778


package com.arondor.common.reflection.bean.config;

import java.util.Map;

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Transient;

import com.arondor.common.reflection.model.config.ElementConfiguration;
import com.arondor.common.reflection.model.config.MapConfiguration;

@Entity
@DiscriminatorValue("MAP")
public class MapConfigurationBean extends ElementConfigurationBean implements MapConfiguration
{
    /**
     *
     */
    private static final long serialVersionUID = 2968136864852828441L;

    public ElementConfigurationType getFieldConfigurationType()
    {
        return ElementConfigurationType.Map;
    }

    public MapConfigurationBean()
    {

    }

    // @ManyToMany(cascade = CascadeType.ALL)
    // , targetEntity = ElementConfigurationBean.class
    @Transient
    private Map<ElementConfiguration, ElementConfiguration> mapConfiguration;

    public Map<ElementConfiguration, ElementConfiguration> getMapConfiguration()
    {
        return mapConfiguration;
    }

    public void setMapConfiguration(Map<ElementConfiguration, ElementConfiguration> mapConfiguration)
    {
        this.mapConfiguration = mapConfiguration;
    }

}

package com.arondor.common.reflection.bean.config;

import java.util.Map;

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Transient;

import com.arondor.common.reflection.model.config.ElementConfiguration;
import com.arondor.common.reflection.model.config.MapConfiguration;

@Entity
@DiscriminatorValue("MAP")
public class MapConfigurationBean extends ElementConfigurationBean implements MapConfiguration
{
    /**
     *
     */
    private static final long serialVersionUID = 2968136864852828441L;

    public ElementConfigurationType getFieldConfigurationType()
    {
        return ElementConfigurationType.Map;
    }

    public MapConfigurationBean()
    {

    }

    // @ManyToMany(cascade = CascadeType.ALL)
    // , targetEntity = ElementConfigurationBean.class
    @Transient
    private Map<ElementConfiguration, ElementConfiguration> mapConfiguration;

    public Map<ElementConfiguration, ElementConfiguration> getMapConfiguration()
    {
        return mapConfiguration;
    }

    public void setMapConfiguration(Map<ElementConfiguration, ElementConfiguration> mapConfiguration)
    {
        this.mapConfiguration = mapConfiguration;
    }

    public String toString()
    {
        return "MapConfigurationBean[" + mapConfiguration.entrySet() + "]";
    }
}

Add a correct toString() method

Add a correct toString() method

git-svn-id: 7e8def7d4256e953abb468098d8cb9b4faff0c63@5801 12255794-1b5b-4525-b599-b0510597569d


package com.redhat.ceylon.eclipse.core.debug;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext;
import org.eclipse.jdt.debug.core.IJavaVariable;

public class CeylonContentProviderFilter {
    public static Object[] filterVariables(Object[] variables, IPresentationContext context) throws DebugException {
        List<Object> keep = new ArrayList<Object>(variables.length);
        for (int i = 0; i < variables.length; i++) {
            boolean filter = false;
            if (variables[i] instanceof IJavaVariable){
                IJavaVariable var = (IJavaVariable)variables[i];
                if (var.getName().contains("$")){
                    filter = true;
                }
            }
            if (!filter){
                keep.add(variables[i]);
            }
        }
        return keep.toArray(new Object[keep.size()]);
    }

}

package com.redhat.ceylon.eclipse.core.debug;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext;
import org.eclipse.jdt.debug.core.IJavaVariable;

import com.redhat.ceylon.compiler.java.codegen.Naming;

public class CeylonContentProviderFilter {
    public static Object[] filterVariables(Object[] variables, IPresentationContext context) throws DebugException {
        List<Object> keep = new ArrayList<Object>(variables.length);
        for (int i = 0; i < variables.length; i++) {
            boolean filter = false;
            if (variables[i] instanceof IJavaVariable){
                String name = ((IJavaVariable)variables[i]).getName();
                if (name.charAt(0) == '$') {
                    if (Naming.isJavaKeyword(name, 1, name.length())) {
                        name = name.substring(1);
                    }
                }
                if (name.contains("$")){
                    filter = true;
                }
            }
            if (!filter){
                keep.add(variables[i]);
            }
        }
        return keep.toArray(new Object[keep.size()]);
    }

}

Manage quoted variables (because having the name of a Java keyword)


package com.minelittlepony.client.render;

import net.minecraft.client.render.RenderLayer;
import net.minecraft.client.render.RenderPhase;
import net.minecraft.client.render.VertexFormats;

public class MagicGlow extends RenderPhase {

    public MagicGlow(String name, Runnable beginAction, Runnable endAction) {
        super(name, beginAction, endAction);
    }

    public static RenderLayer getRenderLayer() {
        return RenderLayer.method_24048("mlp_magic_glow", VertexFormats.POSITION_COLOR_TEXTURE_LIGHT_NORMAL, 7, 256, RenderLayer.MultiPhaseData.builder()
                .texture(NO_TEXTURE)
                .transparency(TRANSLUCENT_TRANSPARENCY)
                .lightmap(DISABLE_LIGHTMAP)
                .cull(DISABLE_CULLING)
                .build(false));
    }
}

package com.minelittlepony.client.render;

import net.minecraft.client.render.RenderLayer;
import net.minecraft.client.render.RenderPhase;
import net.minecraft.client.render.VertexFormats;

public class MagicGlow extends RenderPhase {
    private MagicGlow(String name, Runnable beginAction, Runnable endAction) {
        super(name, beginAction, endAction);
    }

    static final RenderLayer MAGIC = RenderLayer.method_24048("mlp_magic_glow", VertexFormats.POSITION_COLOR_TEXTURE_LIGHT_NORMAL, 7, 256, RenderLayer.MultiPhaseData.builder()
            .texture(NO_TEXTURE)
            .transparency(TRANSLUCENT_TRANSPARENCY)
            .lightmap(DISABLE_LIGHTMAP)
            .cull(DISABLE_CULLING)
            .build(false));

    public static RenderLayer getRenderLayer() {
        return MAGIC;
    }
}

Tidy up the magic glow layer

Tidy up the magic glow layer


/*
 * Copyright 2007-2009 Sun Microsystems, Inc.
 * This source code is available under the MIT license.
 * See the file LICENSE.txt for details.
 */

package org.jruby.rack;

import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jruby.rack.servlet.DefaultServletDispatcher;
import org.jruby.rack.servlet.ServletDispatcher;
import org.jruby.rack.servlet.ServletRackContext;

/**
 *
 * @author nicksieger
 */
public class RackServlet extends HttpServlet {
    private ServletDispatcher dispatcher;

    /** Default ctor, used by servlet container */
    public RackServlet() {
    }

    /** dependency injection ctor, used by unit tests */
    public RackServlet(ServletDispatcher dispatcher) {
        this.dispatcher = dispatcher;
    }

    @Override
    public void init(ServletConfig config) {
        this.dispatcher = new DefaultServletDispatcher(new ServletRackContext(config.getServletContext()));
    }

    @Override
    public void service(ServletRequest request, ServletResponse response)
        throws ServletException, IOException {
        dispatcher.process((HttpServletRequest) request, (HttpServletResponse) response);
    }

}

/*
 * Copyright 2007-2009 Sun Microsystems, Inc.
 * This source code is available under the MIT license.
 * See the file LICENSE.txt for details.
 */

package org.jruby.rack;

import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jruby.rack.servlet.DefaultServletDispatcher;
import org.jruby.rack.servlet.ServletDispatcher;
import org.jruby.rack.servlet.ServletRackContext;

/**
 *
 * @author nicksieger
 */
public class RackServlet extends HttpServlet {
    private ServletDispatcher dispatcher;

    /** Default ctor, used by servlet container */
    public RackServlet() {
    }

    /** dependency injection ctor, used by unit tests */
    public RackServlet(ServletDispatcher dispatcher) {
        this.dispatcher = dispatcher;
    }

    @Override
    public void init(ServletConfig config) {
        this.dispatcher = new DefaultServletDispatcher(new ServletRackContext(config.getServletContext()));
    }

    @Override
    public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        dispatcher.process(request, response);
    }

    @Override
    public void service(ServletRequest request, ServletResponse response)
        throws ServletException, IOException {
        service((HttpServletRequest) request, (HttpServletResponse) response);
    }
}

JRUBY_RACK-14: Add override for both Servlet and HttpServlet service methods (Michael Pitman)


/*
 * Copyright 2016 SEARCH-The National Consortium for Justice Information and Statistics
 *
 * 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 org.search.nibrs.stagingdata.repository;

import org.search.nibrs.stagingdata.model.UcrOffenseCodeType;
import org.springframework.data.repository.CrudRepository;

public interface UcrOffenseCodeTypeRepository extends CrudRepository<UcrOffenseCodeType, Integer>{
	public UcrOffenseCodeType findFirstByStateCode( String stateCode );
	public Iterable<UcrOffenseCodeType> findByOrderByStateDescription();
}

/*
 * Copyright 2016 SEARCH-The National Consortium for Justice Information and Statistics
 *
 * 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 org.search.nibrs.stagingdata.repository;

import org.search.nibrs.stagingdata.model.UcrOffenseCodeType;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UcrOffenseCodeTypeRepository extends JpaRepository<UcrOffenseCodeType, Integer>{
	public UcrOffenseCodeType findFirstByStateCode( String stateCode );
}

Use JpaRepository instead of CrudRepository.


// ========================================================================
// Copyright 2010 NEXCOM Systems
// ------------------------------------------------------------------------
// 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 org.cipango.diameter.router;

import java.util.Hashtable;
import java.util.Map;

import org.cipango.diameter.node.DiameterRequest;
import org.cipango.diameter.node.Node;
import org.cipango.diameter.node.Peer;

public class DefaultRouter implements DiameterRouter
{

	private Map<String, Peer> _peers = new Hashtable<String, Peer>();

	public Peer getRoute(DiameterRequest request)
	{
		return _peers.get(request.getDestinationHost());
	}

	public void peerAdded(Peer peer)
	{
		_peers.put(peer.getHost(), peer);
	}

	public void peerRemoved(Peer peer)
	{
		_peers.remove(peer.getHost());
	}

}

// ========================================================================
// Copyright 2010 NEXCOM Systems
// ------------------------------------------------------------------------
// 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 org.cipango.diameter.router;

import java.util.Hashtable;
import java.util.Map;

import org.cipango.diameter.node.DiameterRequest;
import org.cipango.diameter.node.Peer;

public class DefaultRouter implements DiameterRouter
{

	private Map<String, Peer> _peers = new Hashtable<String, Peer>();

	public Peer getRoute(DiameterRequest request)
	{
		if (request.getDestinationHost() == null)
			return null;
		return _peers.get(request.getDestinationHost());
	}

	public void peerAdded(Peer peer)
	{
		_peers.put(peer.getHost(), peer);
	}

	public void peerRemoved(Peer peer)
	{
		_peers.remove(peer.getHost());
	}

}

Fix CIPANGO-99: Creating a DiameterServletRequest without specifying the destinationhost field leads to a null pointer exception when sending a the request


package leetcode;

/**
 * https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
 */
public class Problem153 {
    public int findMin(int[] nums) {
        int min = nums[0];
        for (int n : nums) {
            if (n < min) {
                min = Math.min(n, min);
            }
        }
        return min;
    }
}

package leetcode;

/**
 * https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
 */
public class Problem153 {
    public int findMin(int[] nums) {
        return findMin(nums, 0, nums.length-1);
    }

    private int findMin(int[] nums, int left, int right) {
        if (left >= right) {
            return nums[left];
        }
        int mid = (left + right) / 2;
        int minLeft = nums[left];
        if (mid-1 >= 0) {
            minLeft = Math.min(minLeft, nums[mid-1]);
        }
        int minRight = nums[right];
        if (mid+1 < nums.length) {
            minRight = Math.min(minRight, nums[mid+1]);
        }
        int min = Math.min(minLeft, Math.min(nums[mid], minRight));
        if (min == nums[mid]) {
            return nums[mid];
        }
        if (minLeft < minRight) {
            return findMin(nums, left, mid-1);
        } else {
            return findMin(nums, mid+1, right);
        }
    }
}

Solve problem 153 (log n)

Solve problem 153 (log n)


package leetcode;

/**
 * https://leetcode.com/problems/insert-into-a-binary-search-tree/
 */
public class Problem701 {
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public TreeNode insertIntoBST(TreeNode root, int val) {
        // TODO
        return null;
    }

    public static void main(String[] args) {
        Problem701 prob = new Problem701();
    }
}

package leetcode;

/**
 * https://leetcode.com/problems/insert-into-a-binary-search-tree/
 */
public class Problem701 {
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) {
            return new TreeNode(val);
        }
        if (root.val > val) {
            root.left = insertIntoBST(root.left, val);
        } else {
            root.right = insertIntoBST(root.right, val);
        }
        return root;
    }
}

Solve problem 701 (my 600th problem :)

Solve problem 701 (my 600th problem :)


package edu.javacourse.threads;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Artem Pronchakov | email/xmpp: artem.pronchakov@calisto.email
 */
public class ExecutorServiceExample {

    public static void main(String[] args) {

        Thread worker1 = new Thread(new Worker("worker1"));
        Thread worker2 = new Thread(new Worker("worker2"));
        Thread worker3 = new Thread(new Worker("worker3"));
        Thread worker4 = new Thread(new Worker("worker4"));
        Thread worker5 = new Thread(new Worker("worker5"));

//        ExecutorService executorService = Executors.newSingleThreadExecutor();
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        executorService.execute(worker1);
        executorService.execute(worker2);
        executorService.execute(worker3);
        executorService.execute(worker4);
        executorService.execute(worker5);

        executorService.shutdown();

    }

}

package edu.javacourse.threads;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Artem Pronchakov | email/xmpp: artem.pronchakov@calisto.email
 */
public class ExecutorServiceExample {

    public static void main(String[] args) {

        Worker worker1 = new Worker("worker1");
        Worker worker2 = new Worker("worker2");
        Worker worker3 = new Worker("worker3");
        Worker worker4 = new Worker("worker4");
        Worker worker5 = new Worker("worker5");

//        ExecutorService executorService = Executors.newSingleThreadExecutor();
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        executorService.execute(worker1);
        executorService.execute(worker2);
        executorService.execute(worker3);
        executorService.execute(worker4);
        executorService.execute(worker5);

        executorService.shutdown();

    }

}

Remove unnecessary Thread objects creation in ExecutorService


package com.splicemachine.derby.impl.sql;

import java.sql.SQLException;
import java.util.Properties;

import com.splicemachine.backup.BackupManager;
import com.splicemachine.db.authentication.UserAuthenticator;
import com.splicemachine.db.impl.jdbc.authentication.AuthenticationServiceBase;
import com.splicemachine.management.Manager;

/**
 * Fake manager impl for mem db
 */
public class NoOpManager implements Manager {
    private static NoOpManager ourInstance=new NoOpManager();

    public static NoOpManager getInstance(){
        return ourInstance;
    }

    private NoOpManager(){ }

    @Override
    public void enableEnterprise(char[] value) throws SQLException {
        // no-op
    }

    @Override
    public BackupManager getBackupManager() throws SQLException {
        return NoOpBackupManager.getInstance();
    }

    @Override
    public UserAuthenticator getAuthenticationManager(AuthenticationServiceBase svc, Properties properties) throws SQLException {
        return null;
    }
}

package com.splicemachine.derby.impl.sql;

import java.sql.SQLException;
import java.util.Properties;

import com.splicemachine.backup.BackupManager;
import com.splicemachine.colperms.ColPermsManager;
import com.splicemachine.db.authentication.UserAuthenticator;
import com.splicemachine.db.impl.jdbc.authentication.AuthenticationServiceBase;
import com.splicemachine.management.Manager;

/**
 * Fake manager impl for mem db
 */
public class NoOpManager implements Manager {
    private static NoOpManager ourInstance=new NoOpManager();

    public static NoOpManager getInstance(){
        return ourInstance;
    }

    private NoOpManager(){ }

    @Override
    public void enableEnterprise(char[] value) throws SQLException {
        // no-op
    }

    @Override
    public BackupManager getBackupManager() throws SQLException {
        return NoOpBackupManager.getInstance();
    }

    @Override
    public UserAuthenticator getAuthenticationManager(AuthenticationServiceBase svc, Properties properties) throws SQLException {
        return null;
    }

    @Override
    public ColPermsManager getColPermsManager() throws SQLException {
        return null;
    }
}

Fix mem build - implement no-op method.

Fix mem build - implement no-op method.


/*
 * Copyright 2017, TeamDev Ltd. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.spine3.protobuf.error;

import com.google.protobuf.Message;

/**
 * Exception that is thrown when no descriptor for a message class can be found.
 *
 * @author Mikhail Mikhaylov
 */
public class MissingDescriptorException extends RuntimeException {

    private static final long serialVersionUID = 0L;

    public MissingDescriptorException(Class<? extends Message> clazz, Throwable cause) {
        super("Could not get descriptor for class: " + clazz.getName() + ", cause: " + cause.getMessage(), cause);
    }
}

/*
 * Copyright 2017, TeamDev Ltd. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.spine3.protobuf.error;

import com.google.protobuf.Message;

import static java.lang.String.format;

/**
 * Exception that is thrown when no descriptor for a message class can be found.
 *
 * @author Mikhail Mikhaylov
 */
public class MissingDescriptorException extends RuntimeException {

    private static final long serialVersionUID = 0L;

    public MissingDescriptorException(Class<? extends Message> cls, Throwable cause) {
        super(makeMessage(cls, cause), cause);
    }

    private static String makeMessage(Class<? extends Message> clazz, Throwable cause) {
        final String result = format("Could not get descriptor for class: %s, cause: %s",
                                     clazz.getName(),
                                     cause.getMessage());
        return result;
    }
}

Improve forming of exception message

Improve forming of exception message


/*
 * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */
package org.opendaylight.protocol.concepts;

import javax.annotation.concurrent.ThreadSafe;

@ThreadSafe
public class HandlerRegistry<CLASS, PARSER, SERIALIZER> {
	private final MultiRegistry<Class<? extends CLASS>, SERIALIZER> serializers = new MultiRegistry<>();
	private final MultiRegistry<Integer, PARSER> parsers = new MultiRegistry<>();

	public AbstractRegistration registerParser(final int type, final PARSER parser) {
		return parsers.register(type, parser);
	}

	public PARSER getParser(final int type) {
		return parsers.get(type);
	}

	public AbstractRegistration registerSerializer(final Class<? extends CLASS> clazz, final SERIALIZER serializer) {
		return serializers.register(clazz, serializer);
	}

	public SERIALIZER getSerializer(final Class<? extends CLASS> clazz) {
		return serializers.get(clazz);
	}
}

/*
 * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */
package org.opendaylight.protocol.concepts;

import javax.annotation.concurrent.ThreadSafe;

@ThreadSafe
public class HandlerRegistry<C, P, S> {
	private final MultiRegistry<Class<? extends C>, S> serializers = new MultiRegistry<>();
	private final MultiRegistry<Integer, P> parsers = new MultiRegistry<>();

	public AbstractRegistration registerParser(final int type, final P parser) {
		return parsers.register(type, parser);
	}

	public P getParser(final int type) {
		return parsers.get(type);
	}

	public AbstractRegistration registerSerializer(final Class<? extends C> clazz, final S serializer) {
		return serializers.register(clazz, serializer);
	}

	public S getSerializer(final Class<? extends C> clazz) {
		return serializers.get(clazz);
	}
}

Rename generic arguments to silence sonar

Change-Id: Ie578bbfb3a82e7c33cdd4c9abd4d8d43d2e0d35e
Signed-off-by: Robert Varga <b8bd3df785fdc0ff42dd1710c5d91998513c57ef@cisco.com>


package org.headsupdev.agile.storage.resource;

/**
 * A simple class representing a velocity of time done over a number of days
 * <p/>
 * Created: 14/03/2013
 *
 * @author Andrew Williams
 * @since 1.0
 */
public class Velocity
{
    public static Velocity INVALID = new Velocity( 0.0, 0.0 )
    {
        @Override
        public Double getVelocity()
        {
            return Double.NaN;
        }
    };

    private Double estimatedHours;
    private Double daysWorked;
    private Double velocity;

    public Velocity( Double estimatedHours, Double daysWorked )
    {
        this.estimatedHours = estimatedHours;
        this.daysWorked = daysWorked;
        this.velocity = ( estimatedHours / daysWorked );
    }

    public Double getEstimatedHours()
    {
        return estimatedHours;
    }

    public Double getDaysWorked()
    {
        return daysWorked;
    }

    public Double getVelocity()
    {
        return velocity;
    }

    @Override
    public String toString()
    {
        return "Velocity " + velocity + " (based on " + estimatedHours + " over " + daysWorked + " days)";
    }
}

package org.headsupdev.agile.storage.resource;

/**
 * A simple class representing a velocity of time done over a number of days
 * <p/>
 * Created: 14/03/2013
 *
 * @author Andrew Williams
 * @since 1.0
 */
public class Velocity
{
    public static Velocity INVALID = new Velocity( 0.0, 0.0 )
    {
        @Override
        public Double getVelocity()
        {
            return Double.NaN;
        }
    };

    private Double estimatedHours;
    private Double daysWorked;
    private Double velocity;

    public Velocity( Double estimatedHours, Double daysWorked )
    {
        this.estimatedHours = estimatedHours;
        this.daysWorked = daysWorked;
        this.velocity = ( estimatedHours / daysWorked );
    }

    public Double getEstimatedHours()
    {
        return estimatedHours;
    }

    public Double getDaysWorked()
    {
        return daysWorked;
    }

    public Double getVelocity()
    {
        return velocity;
    }

    @Override
    public boolean equals( Object o )
    {
        return o instanceof Velocity && equals( (Velocity) o );
    }

    public boolean equals( Velocity v )
    {
        return getVelocity().equals( v.getVelocity() );
    }

    @Override
    public String toString()
    {
        return "Velocity " + velocity + " (based on " + estimatedHours + " over " + daysWorked + " days)";
    }
}

Fix velocity equality so our INVALID checks work correctly


package cafe.test;

import java.io.IOException;

import cafe.image.png.IDATBuilder;
import cafe.image.png.IDATReader;
import cafe.string.StringUtils;

public class TestIDATReader {

	public TestIDATReader() { }

	public static void main(String[] args) throws IOException {
		IDATReader reader = new IDATReader();
		reader.addChunk(new IDATBuilder().data(new byte[] {1,2,3}).data(new byte[] {4,5,6}).build());
		System.out.println(StringUtils.byteArrayToHexString(reader.getData()));
	}
}

package cafe.test;

import java.io.IOException;

import cafe.image.png.IDATBuilder;
import cafe.image.png.IDATReader;
import cafe.string.StringUtils;

public class TestIDATReader {

	public TestIDATReader() { }

	public static void main(String[] args) throws IOException {
		IDATReader reader = new IDATReader();
		IDATBuilder builder = new IDATBuilder().data(new byte[] {1,2,3}).data(new byte[] {4,5,6});
		builder.setFinish(true);
		reader.addChunk(builder.build());
		System.out.println(StringUtils.byteArrayToHexString(reader.getData()));
	}
}

Revise to work with changes with IDATBuilder


package ua.in.directdemocracy.service.application.standalone.authentication;

import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import ua.in.directdemocracy.service.api.rest.authentication.PasswordAuthenticationREST;
import ua.in.directdemocracy.service.web.authentication.AuthenticationService;

@Configuration
public class JerseyConfiguration {

    @Autowired
    PasswordAuthenticationREST passwordAuthenticationService;

    @Bean
    public ResourceConfig config() {
        return new ResourceConfig().register(AuthenticationService.class);
    }

}

package ua.in.directdemocracy.service.application.standalone.authentication;

import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import ua.in.directdemocracy.service.api.rest.authentication.PasswordAuthenticationREST;
import ua.in.directdemocracy.service.web.authentication.AuthenticationService;

@Configuration
public class JerseyConfiguration {

    @Autowired
    PasswordAuthenticationREST passwordAuthenticationService;

    @Bean
    public ResourceConfig config() {
        return new ResourceConfig().register(passwordAuthenticationService);
    }

}

Use bean instead of class when registering REST


package io.requery.test;

import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import io.requery.android.sqlite.DatabaseSource;
import io.requery.meta.EntityModel;
import io.requery.sql.EntityDataStore;
import io.requery.test.model.Models;
import org.junit.runner.RunWith;

import java.sql.SQLException;

/**
 * Reuses the core functional tests from the test project
 */
@RunWith(AndroidJUnit4.class)
public class AndroidFunctionalTest extends FunctionalTest {

    @Override
    public void setup() throws SQLException {
        Context context = InstrumentationRegistry.getContext();
        final String dbName = "test.db";
        context.deleteDatabase(dbName);
        EntityModel model = Models.DEFAULT;
        DatabaseSource dataSource = new DatabaseSource(context, model, dbName, 1);
        dataSource.setLoggingEnabled(true);
        data = new EntityDataStore<>(dataSource.getConfiguration());
    }
}

package io.requery.test;

import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import io.requery.android.sqlite.DatabaseSource;
import io.requery.meta.EntityModel;
import io.requery.sql.EntityDataStore;
import io.requery.test.model.Models;
import org.junit.runner.RunWith;

import java.sql.SQLException;

/**
 * Reuses the core functional tests from the test project
 */
@RunWith(AndroidJUnit4.class)
public class AndroidFunctionalTest extends FunctionalTest {

    private DatabaseSource dataSource;

    @Override
    public void setup() throws SQLException {
        Context context = InstrumentationRegistry.getContext();
        final String dbName = "test.db";
        context.deleteDatabase(dbName);
        EntityModel model = Models.DEFAULT;
        dataSource = new DatabaseSource(context, model, dbName, 1);
        dataSource.setLoggingEnabled(true);
        data = new EntityDataStore<>(dataSource.getConfiguration());
    }

    @Override
    public void teardown() {
        super.teardown();
        if (dataSource != null) {
            dataSource.close();
        }
    }
}

Fix SQLiteDiskIOException while running tests


package com.alexstyl.specialdates.events.namedays.calendar.resource;

import com.alexstyl.specialdates.events.namedays.NamedayLocale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

class NamedayJSONResourceProvider {

    private final NamedayJSONResourceLoader loader;

    NamedayJSONResourceProvider(NamedayJSONResourceLoader loader) {
        this.loader = loader;
    }

    NamedayJSON getNamedayJSONFor(NamedayLocale locale) throws JSONException {
        JSONObject json = loader.loadJSON(locale);
        JSONArray data = json.getJSONArray("data");
        JSONArray special = json.getJSONArray("special");
        return new NamedayJSON(data, special);
    }

}

package com.alexstyl.specialdates.events.namedays.calendar.resource;

import com.alexstyl.specialdates.events.namedays.NamedayLocale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

class NamedayJSONResourceProvider {

    private final NamedayJSONResourceLoader loader;
    private final JSONArray jsonArray = new JSONArray();

    NamedayJSONResourceProvider(NamedayJSONResourceLoader loader) {
        this.loader = loader;
    }

    NamedayJSON getNamedayJSONFor(NamedayLocale locale) throws JSONException {
        JSONObject json = loader.loadJSON(locale);
        JSONArray data = json.getJSONArray("data");
        JSONArray special = getSpecialOf(json);
        return new NamedayJSON(data, special);
    }

    private JSONArray getSpecialOf(JSONObject json) throws JSONException {
        if (json.has("special")) {
            return json.getJSONArray("special");
        }
        return jsonArray;
    }

}

Return empty JSONArray if no Special is found


package nxt.db;

import nxt.Nxt;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public abstract class DerivedDbTable {

    protected final String table;

    protected DerivedDbTable(String table) {
        this.table = table;
        Nxt.getBlockchainProcessor().registerDerivedTable(this);
    }

    public void rollback(int height) {
        if (!Db.isInTransaction()) {
            throw new IllegalStateException("Not in transaction");
        }
        try (Connection con = Db.getConnection();
             PreparedStatement pstmtDelete = con.prepareStatement("DELETE FROM " + table + " WHERE height > ?")) {
            pstmtDelete.setInt(1, height);
            pstmtDelete.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e.toString(), e);
        }
    }

    public void truncate() {
        if (!Db.isInTransaction()) {
            throw new IllegalStateException("Not in transaction");
        }
        try (Connection con = Db.getConnection();
             Statement stmt = con.createStatement()) {
            stmt.executeUpdate("TRUNCATE TABLE " + table);
        } catch (SQLException e) {
            throw new RuntimeException(e.toString(), e);
        }
    }

    public void trim(int height) {
        //nothing to trim
    }

    public void finish() {

    }

}

package nxt.db;

import nxt.Nxt;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public abstract class DerivedDbTable {

    protected final String table;

    protected DerivedDbTable(String table) {
        this.table = table;
        Nxt.getBlockchainProcessor().registerDerivedTable(this);
    }

    public void rollback(int height) {
        if (!Db.isInTransaction()) {
            throw new IllegalStateException("Not in transaction");
        }
        try (Connection con = Db.getConnection();
             PreparedStatement pstmtDelete = con.prepareStatement("DELETE FROM " + table + " WHERE height > ?")) {
            pstmtDelete.setInt(1, height);
            pstmtDelete.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e.toString(), e);
        }
    }

    public void truncate() {
        if (!Db.isInTransaction()) {
            throw new IllegalStateException("Not in transaction");
        }
        try (Connection con = Db.getConnection();
             Statement stmt = con.createStatement()) {
            stmt.executeUpdate("DELETE FROM " + table);
        } catch (SQLException e) {
            throw new RuntimeException(e.toString(), e);
        }
    }

    public void trim(int height) {
        //nothing to trim
    }

    public void finish() {

    }

}

Change truncate to delete from in db abstraction. Truncate is not getting rolled back in the new h2 db version, leaving things in a dirty state after failed block application.


/*
 * This Java source file was generated by the Gradle 'init' task.
 */
import org.junit.Test;
import static org.junit.Assert.*;

public class LibraryTest {
    @Test public void testSomeLibraryMethod() {
        Library classUnderTest = new Library();
        assertFalse("someLibraryMethod should return 'true'", classUnderTest.someLibraryMethod());
    }
}

/*
 * This Java source file was generated by the Gradle 'init' task.
 */
import org.junit.Test;
import static org.junit.Assert.*;

public class LibraryTest {
    @Test public void testSomeLibraryMethod() {
        Library classUnderTest = new Library();
        assertTrue("someLibraryMethod should return 'true'", classUnderTest.someLibraryMethod());
    }
}

Revert "Make test fail to test Travis"

Revert "Make test fail to test Travis"

This reverts commit 2edaf89d9e9faa0d2f4b38d0d733ace14739d091.


package com.lassekoskela.maven;

import org.apache.maven.AbstractMavenLifecycleParticipant;
import org.apache.maven.MavenExecutionException;
import org.apache.maven.execution.ExecutionListener;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.rtinfo.RuntimeInformation;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.logging.Logger;

import com.lassekoskela.maven.buildevents.BuildEventListener;
import com.lassekoskela.maven.buildevents.BuildEventLog;
import com.lassekoskela.maven.buildevents.ExecutionListenerChain;

@Component(role = AbstractMavenLifecycleParticipant.class, hint = "buildevents")
public class BuildEventsExtension extends AbstractMavenLifecycleParticipant {

	@Requirement
	private Logger logger;

	@Requirement
	RuntimeInformation runtime;

	@Override
	public void afterProjectsRead(MavenSession session)
			throws MavenExecutionException {
		ExecutionListener original = session.getRequest()
				.getExecutionListener();
		BuildEventLog log = new BuildEventLog(logger);
		ExecutionListener injected = new BuildEventListener(log);
		ExecutionListener chain = new ExecutionListenerChain(original, injected);
		session.getRequest().setExecutionListener(chain);
	}

	void log(CharSequence message) {
		logger.info(message.toString());
	}
}

package com.lassekoskela.maven;

import org.apache.maven.AbstractMavenLifecycleParticipant;
import org.apache.maven.MavenExecutionException;
import org.apache.maven.execution.ExecutionListener;
import org.apache.maven.execution.MavenSession;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.logging.Logger;

import com.lassekoskela.maven.buildevents.BuildEventListener;
import com.lassekoskela.maven.buildevents.BuildEventLog;
import com.lassekoskela.maven.buildevents.ExecutionListenerChain;

@Component(role = AbstractMavenLifecycleParticipant.class, hint = "buildevents")
public class BuildEventsExtension extends AbstractMavenLifecycleParticipant {

	@Requirement
	private Logger logger;

	@Override
	public void afterProjectsRead(MavenSession session)
			throws MavenExecutionException {
		ExecutionListener original = session.getRequest()
				.getExecutionListener();
		BuildEventLog log = new BuildEventLog(logger);
		ExecutionListener injected = new BuildEventListener(log);
		ExecutionListener chain = new ExecutionListenerChain(original, injected);
		session.getRequest().setExecutionListener(chain);
	}

	void log(CharSequence message) {
		logger.info(message.toString());
	}
}

Drop @Requirement RuntimeInformation because we don't need it


package stream.flarebot.flarebot.util;

import net.dv8tion.jda.core.entities.TextChannel;
import stream.flarebot.flarebot.FlareBot;

import java.util.regex.Matcher;

public class HelpFormatter {
    public static String on(TextChannel channel, String description) {
        return description.replaceAll("(?<!\\\\)%p", Matcher.quoteReplacement(String.valueOf(get(channel))));
    }

    private static char get(TextChannel channel) {
        if (channel.getGuild() != null) {
            return FlareBot.getPrefixes().get(channel.getGuild().getId());
        }
        return FlareBot.getPrefixes().get(null);
    }

    public static String formatCommandUsage(TextChannel channel, String usage) {
        String prefix = String.valueOf(get(channel));
        return usage.replace("{%}", prefix);
    }
}

package stream.flarebot.flarebot.util;

import net.dv8tion.jda.core.entities.TextChannel;
import stream.flarebot.flarebot.FlareBot;

import java.util.regex.Matcher;

public class HelpFormatter {

    private static char get(TextChannel channel) {
        if (channel.getGuild() != null) {
            return FlareBot.getPrefixes().get(channel.getGuild().getId());
        }
        return FlareBot.getPrefixes().get(null);
    }

    public static String formatCommandPrefix(TextChannel channel, String usage) {
        String prefix = String.valueOf(get(channel));
        return usage.replaceAll("\\{%\\}", prefix);
    }
}

Make prefix placeholder "{%}" for everything


package org.gradle.sample.integtest.app;

import org.junit.jupiter.api.Test;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import org.gradle.sample.app.Main;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class MainIntegrationTest {
    @Test
    public void testMain() {
        PrintStream savedOut = System.out;
        try {
            ByteArrayOutputStream outStreamForTesting = new ByteArrayOutputStream();
            System.setOut(new PrintStream(outStreamForTesting));

            Main.main(new String[0]);

            assertEquals("Hello, World!\n", outStreamForTesting.toString());
        } finally {
            System.setOut(savedOut);
        }
    }
}

package org.gradle.sample.integtest.app;

import org.junit.jupiter.api.Test;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;

import org.gradle.sample.app.Main;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class MainIntegrationTest {
    @Test
    public void testMain() {
        PrintStream savedOut = System.out;
        try {
            ByteArrayOutputStream outStreamForTesting = new ByteArrayOutputStream();
            System.setOut(new PrintStream(outStreamForTesting));

            Main.main(new String[0]);

            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            pw.println("Hello, World!");
            pw.close();

            assertEquals(sw.toString(), outStreamForTesting.toString());
        } finally {
            System.setOut(savedOut);
        }
    }
}

Fix java modules sample on Windows

Fix java modules sample on Windows


package com.bq.oss.corbel.resources.rem.util;

import java.util.Optional;

import javax.ws.rs.core.MultivaluedMap;

import com.bq.oss.corbel.resources.rem.request.*;
import com.bq.oss.lib.queries.request.Pagination;

public class ImageRemUtil {

    public RequestParameters<CollectionParameters> getCollectionParametersWithPrefix(String prefix,
            RequestParameters<ResourceParameters> requestParameters) {

        MultivaluedMap<String, String> newParameters = requestParameters.getParams();
        newParameters.putSingle("prefix", "cachedImage." + prefix);

        return new RequestParametersImpl<>(new CollectionParametersImpl(new Pagination(1, 10), Optional.empty(), Optional.empty(),
                Optional.empty(), Optional.empty(), Optional.empty()), requestParameters.getTokenInfo(),
                requestParameters.getAcceptedMediaTypes(), requestParameters.getContentLength(), newParameters,
                requestParameters.getHeaders());

    }

}

package com.bq.oss.corbel.resources.rem.util;

import java.util.Optional;

import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;

import com.bq.oss.corbel.resources.rem.request.*;
import com.bq.oss.lib.queries.request.Pagination;

public class ImageRemUtil {

    public RequestParameters<CollectionParameters> getCollectionParametersWithPrefix(String prefix,
            RequestParameters<ResourceParameters> requestParameters) {

        MultivaluedMap<String, String> newParameters = new MultivaluedHashMap<String, String>(requestParameters.getParams());
        newParameters.putSingle("prefix", "cachedImage." + prefix);

        return new RequestParametersImpl<>(new CollectionParametersImpl(new Pagination(1, 10), Optional.empty(), Optional.empty(),
                Optional.empty(), Optional.empty(), Optional.empty()), requestParameters.getTokenInfo(),
                requestParameters.getAcceptedMediaTypes(), requestParameters.getContentLength(), newParameters,
                requestParameters.getHeaders());

    }

}

Resolve bug with immutable map in rem-image.

Change-Id: Icb28f94059f3d577124984503020fd62f54e0c7a


package org.ocpsoft.rewrite.transform.minify;

import java.nio.charset.Charset;

import org.ocpsoft.rewrite.transform.Transformer;

/**
 * A {@link Transformer} implementation that can perform various minification tasks.
 *
 * @author Lincoln Baxter, III
 */
public abstract class Minify implements Transformer
{
   private Charset charset;

   /**
    * Specify the {@link Charset} to be used during minification.
    *
    * @param charset the {@link Charset} to be used.
    */
   public Minify usingCharset(Charset charset)
   {
      this.charset = charset;
      return this;
   }

   public static JsMinify js()
   {
      return new JsMinify();
   }

   public static CssMinify css()
   {
      return new CssMinify();
   }

   /**
    * Get the {@link Charset} to be used during minification.
    */
   protected Charset getCharset()
   {
      return charset;
   }
}

package org.ocpsoft.rewrite.transform.minify;

import java.nio.charset.Charset;

import org.ocpsoft.rewrite.transform.Transformer;

/**
 * A {@link Transformer} implementation that can perform various minification tasks.
 *
 * @author Lincoln Baxter, III
 */
public abstract class Minify implements Transformer
{
   private Charset charset = Charset.forName("UTF-8");

   /**
    * Specify the {@link Charset} to be used during minification.
    *
    * @param charset the {@link Charset} to be used.
    */
   public Minify usingCharset(Charset charset)
   {
      this.charset = charset;
      return this;
   }

   public static JsMinify js()
   {
      return new JsMinify();
   }

   public static CssMinify css()
   {
      return new CssMinify();
   }

   /**
    * Get the {@link Charset} to be used during minification.
    */
   protected Charset getCharset()
   {
      return charset;
   }
}

Fix null Charset encoding that was breaking tests :)


package io.github.shark_app.shark;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class ShareActivity extends AppCompatActivity {

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

package io.github.shark_app.shark;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class ShareActivity extends AppCompatActivity {
    public static final String PREFS_NAME = "SHARK_PREFS";
    public static final String PREFS_USER_EXISTS_KEY = "userExists";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share);
        boolean userExists = checkIfUserExists();
        if (!userExists) {
            Intent intent = new Intent(this, RegisterActivity.class);
            startActivity(intent);
        }
    }

    private boolean checkIfUserExists(){
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        boolean userExists = settings.getBoolean(PREFS_USER_EXISTS_KEY, false);
        return userExists;
    }
}

Add userExists check, start registration if fail


package com.example.profbola.bakingtime.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.os.Parcelable;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by prof.BOLA on 7/6/2017.
 */

public class RecipeUtils {

    public static int getResourceIdFromName(Context context, String name) {
        return context.getResources().getIdentifier(name, "drawable", context.getPackageName());
    }

    public static CharSequence formatServings(int servings) {
        return String.format("Served: %d", servings);
    }

    public interface IsPersistable<T> {

        List<T> consumeCusor(Cursor cursor);

    }
}

package com.example.profbola.bakingtime.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.os.Parcelable;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by prof.BOLA on 7/6/2017.
 */

public class RecipeUtils {

    public static int getResourceIdFromName(Context context, String name) {
        String imageUrl = name.replaceAll("\\s", "_").toLowerCase();
        return context.getResources().getIdentifier(imageUrl, "drawable", context.getPackageName());
    }

    public static CharSequence formatServings(int servings) {
        return String.format("Served: %d", servings);
    }

    public interface IsPersistable<T> {

        List<T> consumeCusor(Cursor cursor);

    }
}

Move local image logic to helper method

Move local image logic to helper method


package fi.nls.oskari.spring.session;

import fi.nls.oskari.util.PropertyUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

// TODO: Check if maxInactiveIntervalInSeconds can be configured
@Configuration
@Profile(RedisSessionConfig.PROFILE)
@EnableRedisHttpSession(maxInactiveIntervalInSeconds=7200)
public class RedisSessionConfig extends WebMvcConfigurerAdapter {

    public static final String PROFILE ="redis-session";

    @Bean
    public JedisConnectionFactory connectionFactory() {
        JedisConnectionFactory jedis = new JedisConnectionFactory();
        jedis.setHostName(PropertyUtil.get("redis.hostname", "127.0.0.1"));
        jedis.setPort(PropertyUtil.getOptional("redis.port", 6379));
        jedis.setUsePool(true);
        return jedis;
    }
}

package fi.nls.oskari.spring.session;

import fi.nls.oskari.util.PropertyUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

// TODO: Check if maxInactiveIntervalInSeconds can be configured
@Configuration
@Profile(RedisSessionConfig.PROFILE)
@EnableRedisHttpSession(maxInactiveIntervalInSeconds=7200)
public class RedisSessionConfig extends WebMvcConfigurerAdapter {

    public static final String PROFILE ="redis-session";

    @Bean
    public JedisConnectionFactory connectionFactory() {
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(
                PropertyUtil.get("redis.hostname", "127.0.0.1"),
                PropertyUtil.getOptional("redis.port", 6379));
        JedisConnectionFactory jedis = new JedisConnectionFactory(config);
        return jedis;
    }
}

Update redis config from deprecated - pooling enabled by default


package net.stickycode.bootstrap.spring3;

import net.stickycode.stereotype.StickyComponent;
import net.stickycode.stereotype.StickyPlugin;

import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.type.filter.AnnotationTypeFilter;

public class StickySpringBootstrap {

  private GenericApplicationContext context;

  public StickySpringBootstrap(GenericApplicationContext context) {
    this.context = context;
  }

  public void scan(String... paths) {
    ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, false);
    scanner.setScopeMetadataResolver(new StickyScopeMetadataResolver());
    scanner.addIncludeFilter(new AnnotationTypeFilter(StickyComponent.class));
    scanner.addIncludeFilter(new AnnotationTypeFilter(StickyPlugin.class));
    scanner.scan(paths);
  }

}

package net.stickycode.bootstrap.spring3;

import net.stickycode.stereotype.StickyComponent;
import net.stickycode.stereotype.StickyPlugin;

import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Component;

public class StickySpringBootstrap {

  private GenericApplicationContext context;

  public StickySpringBootstrap(GenericApplicationContext context) {
    this.context = context;
  }

  public void scan(String... paths) {
    ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(context, false);
    scanner.setScopeMetadataResolver(new StickyScopeMetadataResolver());
    scanner.addIncludeFilter(new AnnotationTypeFilter(StickyComponent.class));
    scanner.addIncludeFilter(new AnnotationTypeFilter(StickyPlugin.class));
    scanner.addIncludeFilter(new AnnotationTypeFilter(Component.class));
    scanner.scan(paths);
  }

}

Use the spring component as well to allow for migrations


package es.craftmanship.toledo.katangapp.utils;

/**
 * Created by cristobal on 3/2/16.
 */
public class GPSTracker {

}

package es.craftmanship.toledo.katangapp.utils;

import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;

/**
 * Created by cristobal on 3/2/16.
 */
public class GPSTracker extends Service implements LocationListener {

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

Add methods extended from android.app.Service and LocationListener


package org.perfcake.pc4idea.configuration;

import com.intellij.execution.actions.ConfigurationContext;
import com.intellij.execution.actions.RunConfigurationProducer;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.PsiElement;
import org.perfcake.pc4idea.editor.PerfCakeEditorProvider;

/**
 * Created with IntelliJ IDEA.
 * User: Stanislav Kaleta
 * Date: 5.12.2014
 */
public class PCRunConfigurationProducer extends RunConfigurationProducer<PCRunConfiguration> {

    public PCRunConfigurationProducer(){
        super(PCConfigurationType.getInstance());
    }

    @Override
    protected boolean setupConfigurationFromContext(PCRunConfiguration pcRunConfig, ConfigurationContext configContext, Ref<PsiElement> psiElementRef) {
        if ((configContext.getLocation() != null) && (configContext.getLocation().getVirtualFile() != null) &&
                new PerfCakeEditorProvider().accept(configContext.getProject(), configContext.getLocation().getVirtualFile())){
            if (!pcRunConfig.isInitialized()) {
                String fileName = configContext.getLocation().getVirtualFile().getName();
                pcRunConfig.setScenarioName(fileName);
                pcRunConfig.setName(fileName);
            }
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean isConfigurationFromContext(PCRunConfiguration pcRunConfig, ConfigurationContext configContext) {
        if ((configContext.getLocation() != null) && (configContext.getLocation().getVirtualFile() != null)){
            String fileName = configContext.getLocation().getVirtualFile().getName();
            return fileName.equals(pcRunConfig.getScenarioName()) && pcRunConfig.isInitialized();
        } else {
            return false;
        }
    }
}

package org.perfcake.pc4idea.configuration;

import com.intellij.execution.actions.ConfigurationContext;
import com.intellij.execution.actions.RunConfigurationProducer;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.PsiElement;
import org.perfcake.pc4idea.editor.PerfCakeEditorProvider;

/**
 * Created with IntelliJ IDEA.
 * User: Stanislav Kaleta
 * Date: 5.12.2014
 */
public class PCRunConfigurationProducer extends RunConfigurationProducer<PCRunConfiguration> {
    public PCRunConfigurationProducer(){
        super(PCConfigurationType.getInstance());
    }

    @Override
    protected boolean setupConfigurationFromContext(PCRunConfiguration pcRunConfig, ConfigurationContext configContext, Ref<PsiElement> psiElementRef) {
        return (configContext.getLocation() != null) && (configContext.getLocation().getVirtualFile() != null) &&
                new PerfCakeEditorProvider().accept(configContext.getProject(), configContext.getLocation().getVirtualFile());
    }

    @Override
    public boolean isConfigurationFromContext(PCRunConfiguration pcRunConfig, ConfigurationContext configContext) {
        if ((configContext.getLocation() != null) && (configContext.getLocation().getVirtualFile() != null)){
            String fileName = configContext.getLocation().getVirtualFile().getName();
        }
        /*TODO if exists such a config - true = hide config setup*/
        return true;
    }
}

Revert "added ability to create default config on scenario click"

This reverts commit a00819be4a76bb766e4ff57f61e06f4c7ac1c1f8.


package main.java.org.wikidata.analyzer.Processor;

import org.wikidata.wdtk.datamodel.interfaces.*;

/**
 * This processor simply outputs status lines to the console.
 *
 * @author Addshore
 */
public class NoisyProcessor implements EntityDocumentProcessor {

    private int itemCount = 0;
    private int propertyCount = 0;

    @Override
    public void processItemDocument(ItemDocument item) {
        this.itemCount++;
        //Output a line ever 250,000 items
        if (this.itemCount % 250000 == 0) {
            System.out.println("Processed " + this.itemCount + " items " + Runtime.getRuntime().totalMemory() / 1024 / 1024 + "MB mem used");
        }
    }

    @Override
    public void processPropertyDocument(PropertyDocument property) {
        this.propertyCount++;
        //Output a line ever 100 properties
        if (this.propertyCount % 100 == 0) {
            System.out.println("Processed " + this.itemCount + " properties " + Runtime.getRuntime().totalMemory() / 1024 / 1024 + "MB mem used");
        }
    }

}

package main.java.org.wikidata.analyzer.Processor;

import org.wikidata.wdtk.datamodel.interfaces.*;

/**
 * This processor simply outputs status lines to the console.
 *
 * @author Addshore
 */
public class NoisyProcessor implements EntityDocumentProcessor {

    private int itemCount = 0;
    private int propertyCount = 0;

    @Override
    public void processItemDocument(ItemDocument item) {
        this.itemCount++;
        //Output a line ever 250,000 items
        if (this.itemCount % 250000 == 0) {
            System.out.println("Processed " + this.itemCount + " items " + Runtime.getRuntime().totalMemory() / 1024 / 1024 + "MB mem used");
        }
    }

    @Override
    public void processPropertyDocument(PropertyDocument property) {
        this.propertyCount++;
        //Output a line ever 100 properties
        if (this.propertyCount % 100 == 0) {
            System.out.println("Processed " + this.propertyCount + " properties " + Runtime.getRuntime().totalMemory() / 1024 / 1024 + "MB mem used");
        }
    }

}

Fix noisy processor propertycount output


// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.build.events;

import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;

/**
 * @author Vladislav.Soroka
 */
@ApiStatus.Experimental
public interface MessageEventResult extends EventResult {
  MessageEvent.Kind getKind();

  @Nullable
  String getDetails();
}

// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.build.events;

import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;

/**
 * @author Vladislav.Soroka
 */
@ApiStatus.Experimental
public interface MessageEventResult extends EventResult {
  MessageEvent.Kind getKind();

  @Nullable
  default String getDetails() { return null; }
}

Build view: fix api breaking change

Build view: fix api breaking change


package org.openlmis.stock.repository.mapper;

import org.apache.ibatis.annotations.Select;
import org.openlmis.stock.domain.Manufacturer;
import org.openlmis.stock.domain.VaccinePackaging;

/**
 * Created by Morley on 6/20/2015.
 */
public interface HasVaccinePackaging {

    @Select("SELECT * FROM vaccine_packaging WHERE id = #{packagingId}")
    VaccinePackaging getVaccinePackagingById(Long packagingId);
}

package org.openlmis.stock.repository.mapper;

import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.openlmis.stock.domain.Manufacturer;
import org.openlmis.stock.domain.Vaccine;
import org.openlmis.stock.domain.VaccinePackaging;

/**
 * Created by Morley on 6/20/2015.
 */
public interface HasVaccinePackaging extends HasVaccineMapper{

    @Select("SELECT * FROM vaccine_packaging WHERE id = #{packagingId}")
    @Results(value = {
            @Result(property = "vaccine", javaType = Vaccine.class, column = "vaccine_id",
                    one = @One(select = "getVaccineById")),
            @Result(property = "manufacturer", javaType = Manufacturer.class, column = "manufacturer_id",
                    one = @One(select = "getManufacturerById"))
    })
    VaccinePackaging getVaccinePackagingById(Long packagingId);

    @Select("SELECT * FROM manufacturers WHERE id = #{manufacturerId}")
    Manufacturer getManufacturerById(Long manufacturerId);
}

Add vaccine to every vaccine package

Add vaccine to every vaccine package


package ee.tuleva.onboarding;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class AcmeChallengeController {

	@RequestMapping(value = "/.well-known/acme-challenge/ImI3Zo4v6MLlQcnQDhTYn1ojxtwALQzOaoGTDZFANhk")
	@ResponseBody
	public String challenge() {
		return "ImI3Zo4v6MLlQcnQDhTYn1ojxtwALQzOaoGTDZFANhk.EMEBBxvSam3n_ien1J0z4dXeTuc2JuR3HqfAP6teLjE";
	}

}

package ee.tuleva.onboarding;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class AcmeChallengeController {

	@RequestMapping(value = "/.well-known/acme-challenge/hiPzrb01y82bTVL1T2XfyFuXDVH0d7Qi7VcD25CE8zo")
	@ResponseBody
	public String challenge() {
		return "hiPzrb01y82bTVL1T2XfyFuXDVH0d7Qi7VcD25CE8zo.EMEBBxvSam3n_ien1J0z4dXeTuc2JuR3HqfAP6teLjE";
	}

}

Sort target funds alphabetically & show all of them in the dropdown list.