#StackBounty: #java #android #gradle #kotlin Gradle build failed with message: TaskDependencyResolveException: Could not determine the …

Bounty: 50

I have updated Android Studio to 3.3 and now I can’t build one of my existing project, I have tried invalidate/restart, also checked gradle-wrapper.propertieswhere gradle version is latest update:

distributionUrl=https://services.gradle.org/distributions/gradle-4.10.1-all.zip

Here is my build.gradle

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'realm-android'
apply plugin: 'kotlin-kapt'

buildscript {
    ext.kotlin_version = '1.3.11'
    repositories {
        google()
        jcenter()
        mavenCentral()
        maven {
            url 'https://maven.google.com'
        }
    }

dependencies {
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    classpath 'com.android.tools.build:gradle:3.3.0'
    classpath 'com.google.gms:google-services:4.2.0'
    classpath "io.realm:realm-gradle-plugin:3.1.3"
    }
}

repositories {
    google()
    jcenter()
    mavenCentral()
    maven { url "https://jitpack.io" }
    maven {
        url 'https://maven.google.com'
    }

}


androidExtensions {
    experimental = true
}

android {
    compileSdkVersion 22
    buildToolsVersion '28.0.3'
    defaultConfig {
        applicationId "my.package.name"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 1
        versionName "1.0.0"
        multiDexEnabled true
        vectorDrawables.useSupportLibrary = true
        ndk {
            abiFilters "armeabi-v7a", "x86", "armeabi", "mips"
        }
    }

    lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            ....
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
            jniLibs.srcDir 'libs'   
        }

        androidTest.setRoot('tests')

        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')
    }
    buildTypes {
    }
}

ext {
    supportLibraryVersion = '22.2.0'
    googleServicesVersion = '17.3.4'
    retrofitVersion = '2.3.0'
}

dependencies {
    implementation fileTree(include: '*.jar', dir: 'libs')
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    [
            'cardview-v7', 'design'
    ].each {
        implementation "com.android.support:$it:$supportLibraryVersion"
    }

    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"


    implementation 'org.jetbrains.anko:anko-sdk23:0.9.1'
    implementation 'com.google.code.gson:gson:2.8.5'
    implementation 'com.android.support:multidex:1.0.3'
    implementation 'com.squareup:otto:1.3.8'
    implementation "com.squareup.retrofit2:retrofit:$retrofitVersion"
    implementation "com.squareup.retrofit2:converter-gson:$retrofitVersion"
    implementation 'com.squareup.okhttp3:okhttp:3.11.0'
    implementation 'com.squareup.picasso:picasso:2.71828'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.8.1'
    implementation "com.google.firebase:firebase-messaging:$googleServicesVersion"
}

apply plugin: 'com.google.gms.google-services'

When I’m trying to build project preDebugBuild error appears

org.gradle.api.UncheckedIOException: Failed to capture fingerprint of input files for task ':preDebugBuild' property 'compileManifests' during up-to-date check.

and Java compiler: (1 error)

Caused by: java.lang.ArrayIndexOutOfBoundsException: 1

If I run assembleDebug

* Exception is:
org.gradle.api.internal.tasks.TaskDependencyResolveException: 
Could not determine the dependencies of task ':compileDebugKotlin.' 
...
Caused by: java.lang.ArrayIndexOutOfBoundsException: 1 

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0.
Use '--warning-mode all' to show the individual deprecation warnings.

Also if run ./gradlew build -Dorg.gradle.warning.mode=all

The project name 'myapp-android production' contains at least one of the following characters:
[ , /, , :, <, >, ", ?, *, |]. This has been deprecated and is scheduled to be removed in Gradle 5.0. 
Set the 'rootProject.name' or adjust the 'include' statement
 (see https://docs.gradle.org/4.10.1/dsl/org.gradle.api.initialization.Settings.html#org.gradle.api.initialization.Settings:include(java.lang.String[])
 for more details)

Could not resolve compiler classpath. 
Check if Kotlin Gradle plugin repository is configured in root project 'myapp-android production'
FAILURE: Build failed with an exception.

* What went wrong:
Could not determine the dependencies of task ':compileReleaseKotlin'.

How can I resolve this issue? This happened after Android Studio update.


Get this bounty!!!

#StackBounty: #java #c# #android #visual-studio #xamarin Release Mode and Debug Mode in VS

Bounty: 50

I currently work on an Android application, and I messed around a bit with the VS.

I was wandering, what are the real differences between the two modes? I did some research, but I didn’t completely get the real differences and the advantages of each one, as well as when to use a specific mode.

During my research, I came across those questions 1, 2 and 3, talking about the differences between the two.

  1. Why debug mode runs slower than release mode?
  2. When releasing an application to Google Play, which mode should I use and why?
  3. Can I create my own mode?

My app seems to be built fine in Debug mode, yet in Release mode I get a lot of warnings about “no debug symbols file was found”.

  1. What are those debug symbols?
  2. What is the “81” folder in the obj/Debug or obj/Release?
  3. I also noticed that sometimes, when switching from Debug to Release, some Resource.Id are not found, and I need to recreate the axml file for the layouts plus cleaning the sln. How can I prevent it?

As I understood, debug mode uses some files that release mode doesn’t need in order to run, I assume that the missing files are those “debug symbols”?. Maybe it’s a problem with Xamarin or with VS?
These are the warnings I get:

Warning     Directory objRelease81android/assets contains Xamarin.Android.Support.v7.AppCompat.dll but no debug symbols file was found.          0   
Warning     Directory objRelease81android/assets contains Java.Interop.dll but no debug symbols file was found.          0   
Warning     Directory objRelease81android/assets contains Xamarin.Android.Arch.Core.Common.dll but no debug symbols file was found.          0   
Warning     Directory objRelease81android/assets contains Xamarin.Android.Arch.Lifecycle.Common.dll but no debug symbols file was found.         0   
Warning     Directory objRelease81android/assets contains Xamarin.Android.Arch.Lifecycle.Runtime.dll but no debug symbols file was found.            0   
Warning     Directory objRelease81android/assets contains Xamarin.Android.Support.Animated.Vector.Drawable.dll but no debug symbols file was found.          0   
Warning     Directory objRelease81android/assets contains Xamarin.Android.Support.Annotations.dll but no debug symbols file was found.           0   
Warning     Directory objRelease81android/assets contains Xamarin.Android.Support.Compat.dll but no debug symbols file was found.            0   
Warning     Directory objRelease81android/assets contains Xamarin.Android.Support.Core.UI.dll but no debug symbols file was found.           0   
Warning     Directory objRelease81android/assets contains Xamarin.Android.Support.Core.Utils.dll but no debug symbols file was found.            0   
Warning     Directory objRelease81android/assets contains Xamarin.Android.Support.Design.dll but no debug symbols file was found.            0   
Warning     Directory objRelease81android/assets contains Xamarin.Android.Support.Fragment.dll but no debug symbols file was found.          0   
Warning     Directory objRelease81android/assets contains Xamarin.Android.Support.Media.Compat.dll but no debug symbols file was found.          0   
Warning     Directory objRelease81android/assets contains Xamarin.Android.Support.Transition.dll but no debug symbols file was found.            0   
Warning     Directory objRelease81android/assets contains Xamarin.Android.Support.v4.dll but no debug symbols file was found.            0   
Warning     Directory objRelease81android/assets contains Xamarin.Android.Support.v7.RecyclerView.dll but no debug symbols file was found.           0   
Warning     Directory objRelease81android/assets contains Xamarin.Android.Support.Vector.Drawable.dll but no debug symbols file was found.           0   
Warning     Directory objRelease81android/assets contains Xamarin.GooglePlayServices.Base.dll but no debug symbols file was found.           0   
Warning     Directory objRelease81android/assets contains Xamarin.GooglePlayServices.Basement.dll but no debug symbols file was found.           0   
Warning     Directory objRelease81android/assets contains Xamarin.GooglePlayServices.Maps.dll but no debug symbols file was found.           0   
Warning     Directory objRelease81android/assets contains Xamarin.GooglePlayServices.Tasks.dll but no debug symbols file was found.          0   
  1. Are those warning really something I need to worry about when releasing an app? Can they cause any further bugs?

I already tried:

  1. Deleting those files.

  2. Cleaning the solution and the whole project.
    • I hope you could help me with all the questions I asked and provide a fully detailed answer.


Get this bounty!!!

#StackBounty: #amazon-web-services #java #command-line-interface AWS MTurk Command Line Tools – A JNI error has occurred

Bounty: 50

I’m trying to install and use Amazon Mechanical Turk Command Line Tools, which I just downloaded from https://requester.mturk.com/developer/tools/clt

I’m trying to run them from a Administrator Command Prompt in Windows 10.

When I try the getBalance script, I get the following error:

c:mypathaws-mturk-cltaws-mturk-clt-1.3.4>bingetBalance
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: com/amazonaws/mturk/filter/Filter
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
        at java.lang.Class.privateGetMethodRecursive(Unknown Source)
        at java.lang.Class.getMethod0(Unknown Source)
        at java.lang.Class.getMethod(Unknown Source)
        at sun.launcher.LauncherHelper.validateMainClass(Unknown Source)
        at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: com.amazonaws.mturk.filter.Filter
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 7 more

The error message tells me to check my installation, but there was really nothing to install.


Get this bounty!!!

#StackBounty: #java #multithreading #error-handling #api #http HTTP multithreaded connections with retry and session update

Bounty: 50

I have a task to make a multithreaded HTTP method. This method is my entry point (as mine is a library) for a bigger project which is a library.

The flow is like this:

ProjectA —> My Entry point Lib —-> HttpLibrary

The main features of this method are:

  • Accept multiple requests
  • Check for HTTP status codes and act appropriately
  • If the session fails, try updating session once and retry main API call

Here is what I have come up with so far:

 private JsonHttpResult execJsonHttpMethod(final int requestId, BaseRequest request, int maxRequestCount) throws BaseApiException, NullPointerException {
        if (maxRequestCount <= 0) {
            maxRequestCount = REQUESTS_ATTEMPTS_COUNT;
        }
        int timeToWaitBeforeNextRequestIncaseError = 500;
        HttpRetryManager httpRetryManager = new HttpRetryManager(maxRequestCount, timeToWaitBeforeNextRequestIncaseError); // Instance created for each thread

        int count = 0; // Only for logging purpose - thread safe | thread local variable
        JsonHttpResult result = null;
        while (httpRetryManager.canRetry()) {
            count++;
            try {
                reloginLock.readLock().lock();
                final HttpMethod httpMethod = compileHttpMethod(request);
                printRequestLog(request, "execJsonHttpMethod[request]: requestId=" + requestId + ", count=" + count + ", url=" + httpMethod.getURI(), false);
                result = mTransportProvider.execJsonHttpMethod(httpMethod);


                boolean isResEmpty = errorIfResponseEmpty(result);
                if (isResEmpty) {
                    try {
                        httpRetryManager.onErrorUpdateCountAndSleep(new HttpStatusException(result.getHttpStatus(), "Unexpected empty response body"));
                    } catch (HttpStatusException responseEmpty) {
                        responseEmpty.printStackTrace();
                        throw responseEmpty;
                    }
                }

                boolean isSessionInvalid = errorIfResponseUnAuthorized(result);
                if (isSessionInvalid) {
                    if (updateSessionIncaseApiGot401()) {
                        try {
                            //In-case session does not update, logout the user by escalating 401 to 403 ( InvalidSessionException() ---> InvalidUserException())
                            httpRetryManager.onErrorUpdateCountAndSleep(new InvalidUserException());
                            continue; //Start next iteration - no need to check for the rest of the conditions
                        } catch (InvalidUserException exceptionSessEsclatedToInvalidUser) {
                            exceptionSessEsclatedToInvalidUser.printStackTrace();
                            throw exceptionSessEsclatedToInvalidUser;
                        }
                    } else {
                        throw new InvalidUserException(); // WILL TRY ONLY ONCE - IF UPDATE FAILS LOGOUT - 403
                    }
                }

                //Logout user incase API threw 403 - Pops up the stack, no retry action required
                if (errorIfResponseForbidden(result)) {
                    throw new InvalidUserException();
                }

                boolean isHttpErrCodeNotOk = errorIfHttpStatusNotOk(result);
                if (!isHttpErrCodeNotOk) {
                    if (result.getHttpStatus() != HttpStatus.SC_OK && result.getHttpStatus() != HttpStatus.SC_CREATED
                            && result.getHttpStatus() != HttpStatus.SC_NO_CONTENT) {
                        if (result.httpError != null) {
                            throw new HttpStatusDetailedException(result.getHttpStatus(), "Unexpected HTTP(S) result: " + result.toString(), result.httpError);
                        } else {
                            throw new HttpStatusException(result.getHttpStatus(), "Unexpected HTTP(S) result: " + result.toString());
                        }
                    }
                }
                //Success
                HttpUUIDController.getInstance().handleSuccessRequest(request);
                break;
            } catch (TransportLevelException ex) {
                printRequestLog(request, "execJsonHttpMethod[error]: request failed, requestId=" + requestId + ", count=" + count + ", ex=" + ex, false);
                try {
                    httpRetryManager.onErrorUpdateCountAndSleep(ex);
                } catch (Exception transportException) {
                    transportException.printStackTrace();
                    throw transportException;
                }
            } catch (URIException ex) {
                printRequestLog(request, "execJsonHttpMethod[error]: request failed, ex=" + ex.getMessage(), false);
                throw new InvalidUrlException();
            } finally {
                printRequestLog(request, "execJsonHttpMethod[result]: finished, requestId=" + requestId + ", count=" + count + ", result=" + result, false);
                reloginLock.readLock().unlock();
            }
        }
        simpleLog("Loop has been exited, Iterations: " + count);
        return result;
    }

These are my helper methods:

 private boolean errorIfResponseEmpty(HttpResult result) {
        if (result.getHttpStatus() == HttpStatus.SC_OK && result.getHttpResponse() == null) {
            printResponseLog(result.getHttpStatus() + " Unexpected empty response body", true);
            return true;
        }
        return false;
    }

    private boolean errorIfResponseUnAuthorized(HttpResult result) {
        if (result.getHttpStatus() == HttpStatus.SC_UNAUTHORIZED) {
            printResponseLog(result.getHttpStatus() + " Session Failed", true);
            return true;
        }
        return false;

    }

    private boolean errorIfHttpStatusNotOk(HttpResult result) {
        if (result.getHttpStatus() != HttpStatus.SC_OK && result.getHttpStatus() != HttpStatus.SC_CREATED && result.getHttpStatus() != HttpStatus.SC_NO_CONTENT) {
            if (result.httpError != null) {
                printResponseLog(result.getHttpStatus() + " Unexpected HTTP(S) result: " + result.toString() + " " + result.httpError, true);
            } else {
                printResponseLog(result.getHttpStatus() + " Unexpected HTTP(S) result: " + result.toString(), true);
            }
            return false;
        }
        return true;
    }


    private boolean errorIfResponseForbidden(HttpResult result) {
        return (result.getHttpStatus() == HttpStatus.SC_FORBIDDEN);

    }

And finally my HttpRetryManager:

import com.api.Constants;
import com.api.http.exception.BaseApiException;

public class HttpRetryManager {

    private int leftRetries;
    private long timeToWait;
    private static final boolean LOG = Constants.LOG;
    private static final String TAG = HttpRetryManager.class.getCanonicalName();

    public HttpRetryManager(int retries, long timeToWait) {
        this.timeToWait = timeToWait;
        leftRetries = retries;
        printDebugLog("Init: HttpRetryManager, this thread will retry " + leftRetries + " times");
    }

    public boolean canRetry() {
        return leftRetries > 0;
    }

    public void onErrorUpdateCountAndSleep(BaseApiException ex) throws BaseApiException {
        leftRetries--;
        printDebugLog("onErrorUpdateCountAndSleep: RetriesLeft: " + leftRetries);
        if (!canRetry()) {
            throw ex;
        }
        waitUntilNextTry();
    }

    private long getTimeToWait() {
        return timeToWait;
    }

    private void waitUntilNextTry() {
        try {
            Thread.sleep(getTimeToWait());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void printDebugLog(String message) {
        if (LOG) {
            ApiLogger.d(TAG, message);
        }
    }
}


Get this bounty!!!

#StackBounty: #java #mysql #spring-boot #jpa Spring JPA OneToOne FK as PK Cascade.Remove

Bounty: 50

I’ve got two tables, b and a:

  • they have a one-to-one bidirectional relationship
  • a has a foreign key to b that defines this relationship
  • this foreign key is also considered as a primary key for a, and a JPA @ID
  • I want a cascade removal that deletes the related b when a is deleted
  • in MySQL, a‘s b_id is NOT NULL

The problem is that when I delete my A object with JPA repository, I get a ConstraintViolationException on its foreign key.
I would expect that both a and b rows are deleted (cleverly starting with a‘s one).

How could I work around this knowing that I want to keep:

  • my DB schema the same
  • the cascade removal from a to b
  • the b id being the JPA @Id for a
CREATE TABLE `b` (
  `dbid` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`dbid`),
);

CREATE TABLE `a` (
  `b_id` int(11) NOT NULL,
  KEY `b_fk` (`b_id`),
  CONSTRAINT `b_fk` FOREIGN KEY (`b_id`) REFERENCES `b` (`dbid`),
);

@Entity
@Table(name = "a")
public class A {

    @Id
    @Column(name = "b_id")
    @GeneratedValue(generator = "gen")
    @GenericGenerator(name = "gen", strategy = "foreign", parameters = @Parameter(name="property", value="b"))
    private Integer bId;

    @OneToOne(cascade = CascadeType.REMOVE)
    @PrimaryKeyJoinColumn
    private B b;
}
@Entity
@Table(name = "b")
public class B {

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Column(name = "dbid")
    private Integer id;

    @OneToOne(mappedBy = "b")
    private A a;
}


Get this bounty!!!

#StackBounty: #java #hibernate #spring-boot #multi-tenant Springboot Multi-tenant with MultiTenantConnectionProvider always throw org.a…

Bounty: 50

I have started converted my exiting Spring Boot(1.5.4.RELEASE) application to work with multi-tenant features.it is a schema based multi-tenant solution and based on mysql.
As hibernate document suggested below

https://docs.jboss.org/hibernate/orm/4.2/devguide/en-US/html/ch16.html

i have implemented both MultiTenantConnectionProvider and CurrentTenantIdentifierResolver interfaces and it works fine.

package com.ifi.aws.tenant.config.hibernate;

import org.hibernate.HibernateException;
import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ifi.aws.tenant.entity.TenantContext;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

@Component
public class MultiTenantConnectionProviderImpl implements MultiTenantConnectionProvider {

  private static final long serialVersionUID = 6246085840652870138L;

  @Autowired
  private DataSource dataSource;

@Override
public Connection getAnyConnection() throws SQLException {
  return dataSource.getConnection();
}

@Override
public void releaseAnyConnection(Connection connection) throws SQLException {
  connection.close();
}

@Override
public Connection getConnection(String tenantIdentifier) throws SQLException {
  final Connection connection = getAnyConnection();
  try {
    connection.createStatement().execute( "USE " + tenantIdentifier );
  }
  catch ( SQLException e ) {
    throw new HibernateException(
        "Could not alter JDBC connection to specified schema [" + tenantIdentifier + "]",
      e
      );
  }
  return connection;
}

@Override
public void releaseConnection(String tenantIdentifier, Connection connection) throws SQLException {
  try {
    connection.createStatement().execute( "USE " + TenantContext.DEFAULT_TENANT );
  }
  catch ( SQLException e ) {
    throw new HibernateException(
        "Could not alter JDBC connection to specified schema [" + tenantIdentifier + "]",
      e
      );
  }
  connection.close();
}

@SuppressWarnings("rawtypes")
@Override
public boolean isUnwrappableAs(Class unwrapType) {
  return false;
}

@Override
public <T> T unwrap(Class<T> unwrapType) {
  return null;
}

@Override
public boolean supportsAggressiveRelease() {
  return true;
}

}

package com.ifi.aws.tenant.config.hibernate;

import org.hibernate.context.spi.CurrentTenantIdentifierResolver;
import org.springframework.context.annotation.Configuration;

import com.ifi.aws.tenant.entity.TenantContext;

@Configuration
public class TenantIdentifierResolver implements CurrentTenantIdentifierResolver {

  @Override
  public String resolveCurrentTenantIdentifier() {


     String tenantId = TenantContext.getTenantSchema();

    //System.out.println("------------------ resolveCurrentTenantIdentifier = " + tenantId);
    if (tenantId != null) {
        return tenantId;
    }
    return TenantContext.DEFAULT_TENANT;
}
@Override
public boolean validateExistingCurrentSessions() {
    return true;
}
}

and then below is my hibernate configuration

package com.ifi.aws.tenant.config.hibernate;

import org.hibernate.MultiTenancyStrategy;
import org.hibernate.cfg.Environment;
import org.hibernate.context.spi.CurrentTenantIdentifierResolver;
import 
org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;

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

import javax.sql.DataSource;

@Configuration
public class HibernateConfig {

  @Autowired
  private JpaProperties jpaProperties;

  @Bean
  public JpaVendorAdapter jpaVendorAdapter() {
    return new HibernateJpaVendorAdapter();
  }

  @Bean
  public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource,
  MultiTenantConnectionProvider multiTenantConnectionProviderImpl,
  CurrentTenantIdentifierResolver currentTenantIdentifierResolverImpl) {
    Map<String, Object> properties = new HashMap<>();
    properties.putAll(jpaProperties.getHibernateProperties(dataSource));
    properties.put(Environment.MULTI_TENANT, MultiTenancyStrategy.SCHEMA);
    properties.put(Environment.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProviderImpl);
    properties.put(Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, currentTenantIdentifierResolverImpl);

    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(dataSource);
    em.setPackagesToScan("com.ifi.aws");
    em.setJpaVendorAdapter(jpaVendorAdapter());
    em.setJpaPropertyMap(properties);
   return em;
  }
}

however time to time system crashes with below error

Springboot Multi-tenant with MultiTenantConnectionProvider always throw org.apache.tomcat.jdbc.pool.PoolExhaustedException: [http-nio-8086-exec-2] Timeout: Pool empty. Unable to fetch a connection in 30 seconds, none available[size:100; busy:100; idle:0; lastwait:30000].

i Did some reading on this site and found exact same issue in below questions.

Spring Boot: Apache derby pool empty. Unable to fetch a connection in 30 seconds
Tomcat Connection Pool Exhasuted

One of the fixes they suggested was to to add below configurations

spring.datasource.tomcat.max-active=100
spring.datasource.tomcat.max-idle=8
spring.datasource.tomcat.min-idle=8

But still i am getting the same error and i debug the code and found that it closes the connection after each execution of the database call. Do you guys have any idea?

Thanks,
Kelum


Get this bounty!!!

#HackerEarth: #BattleOfBots 9: Taunt

Problem

Taunt is a two player board game which is played on a 10X4 grid of cells and is played on opposite sides of the game-board. Each player has an allocated color, Orange ( First Player ) or Green ( Second Player ) being conventional. Each player has nine piece in total. The players move their pieces towards to his / her opponent’s area by moving their pieces strategically. Each piece has a different moving feature and is one of the 3 types of pieces.

Piece 1: It can move to horizontally or vertically adjacent cell, if the cell doesn’t contain a piece of same color.

enter image description here

Piece 2: It can move to horizontally adjacent cell or can move two steps forward, if the cell doesn’t contain a piece of same color (except the piece itself).

enter image description here

This type of piece can move to its own position if its in the second last row of the grid and going downward or if its in the second row of the grid and going upward.

enter image description here

Piece 3: It can move two step diagonally in the forward direction, if the cell doesn’t contain a piece of same color (except the piece itself).

enter image description here enter image description here

This type of piece can move to its own position if its in the second last row of the grid and going downward or if its in the second row of the grid and going upward.

enter image description here

Players take turns involving moves of pieces as mentioned above and can captures opponent’s piece by jumping on or over opponent’s pieces.

Note: Forward direction for first player is downward and for second player is upward.

If a piece (except piece 1) is moving downward and touches the last row, its direction will change i.e. now it will move upward. Similarly, once if a piece (except piece 1) is moving upward and touches the first row, its direction will change i.e. now it will move downward.

Rules:

  • Player can only move according to the moves mentioned above.
  • A player may not move an opponent’s piece.
  • A player can captures opponent’s piece by jumping on or over opponent pieces.

The game will end after 100 moves ( 50 moves for each player ) or when any of the players don’t have any move left. At the end of the game the player with majority of pieces will win.

We will play it on an 10X4 grid. The top left of the grid is [0,0] and the bottom right is [9,3].

Input:
The input will be a 10X4 matrix consisting only of 0,1or2. Next line will contain an integer denoting the total number of moves till the current state of the board. Next line contains an integer – 1 or 2 which is your player id.

In the given matrix, top-left is [0,0] and bottom-right is [9,3]. The y-coordinate increases from left to right, and x-coordinate increases from top to bottom.

A cell is represented by 3 integers.

First integer denotes the player id (1 or 2).
Second integer denotes the type of piece (1, 2 or 3).
Third integer denotes the direction of the piece (0 (upward) or 1 (downward)). When the piece is of first type, direction doesn’t matter as the piece is free to move to horizontally or vertically adjacent cell, if the cell doesn’t contain a piece of same color.

Empty cell is represented by 000.

Output:
In the first line print the coordinates of the cell separated by space, the piece you want to move.
In second line print the coordinates of the cell in which the piece will jump.
You must take care that you don’t print invalid coordinates. For example, [1,1] might be a valid coordinate in the game play if the piece is able to jump to [1,1], but [9,10] will never be. Also if you play an invalid move or your code exceeds the time/memory limit while determining the move, you lose the game.

Starting state
The starting state of the game is the state of the board before the game starts.

131 131 131 121
121 121 111 111
111 000 000 000
000 000 000 000
000 000 000 000
000 000 000 000
000 000 000 000
000 000 000 210
210 210 220 220
220 230 230 230

First Input
This is the input give to the first player at the start of the game.

131 131 131 121
121 121 111 111
111 000 000 000
000 000 000 000
000 000 000 000
000 000 000 000
000 000 000 000
000 000 000 210
210 210 220 220
220 230 230 230
0
1

 

SAMPLE INPUT
000 000 000 000
000 000 000 111
000 000 111 130
000 000 000 000
000 000 000 000
000 220 000 000
131 000 000 000
121 000 210 000
000 210 131 000
000 210 000 000
58
1
SAMPLE OUTPUT
8 2
8 0

Explanation

This is player 1’s turn, and the player will move the piece at [8,2] and will take two steps diagonally in downward direction and will be at [8,0]
After his/her move the state of game becomes:

000 000 000 000
000 000 000 111
000 000 111 130
000 000 000 000
000 000 000 000
000 220 000 000
131 000 000 000
121 000 210 000
130 210 000 000
000 000 000 000
59
2

Note: Direction of the piece is also changed from 1 to 0 as the piece was moving downward and touches the last row. This state will be fed as input to program of player 2.

Here is the code of the default bot.

Time Limit:1.0 sec(s) for each input file.
Memory Limit:256 MB
Source Limit:1024 KB

Sample Game

Installing Apache UserGrid on linux

About the Project

Apache Usergrid is an open-source Backend-as-a-Service (BaaS or mBaaS) composed of an integrated distributed NoSQL database, application layer and client tier with SDKs for developers looking to rapidly build web and/or mobile applications. It provides elementary services and retrieval features like:

  • User Registration & Management
  • Data Storage
  • File Storage
  • Queues
  • Full Text Search
  • Geolocation Search
  • Joins

It is a multi-tenant system designed for deployment to public cloud environments (such as Amazon Web Services, Rackspace, etc.) or to run on traditional server infrastructures so that anyone can run their own private BaaS deployment.

For architects and back-end teams, it aims to provide a distributed, easily extendable, operationally predictable and highly scalable solution. For front-end developers, it aims to simplify the development process by enabling them to rapidly build and operate mobile and web applications without requiring backend expertise.

Usergrid 2.1.0 Deployment Guide

Though the Usergrid Deployment guide seems to be simple enough, I faced certain hiccups and it took me about 4 days to figure out what I was doing wrong.

This document explains how to deploy the Usergrid v2.1.0 Backend-as-a-Service (BaaS), which comprises the Usergrid Stack, a Java web application, and the Usergrid Portal, which is an HTML5/JavaScript application.

Prerequsites

Below are the software requirements for Usergrid 2.1.0 Stack and Portal. You can install them all on one computer for development purposes, and for deployment you can deploy them separately using clustering.

Linux or a UNIX-like system (Usergrid may run on Windows, but we haven’t tried it)

Download the Apache Usergrid 2.1.0 binary release from the official Usergrid releases page:

After untarring the files that you need for deploying Usergrid Stack and Portal are ROOT.war and usergrid-portal.tar.

Stack STEP #1: Setup Cassandra

As mentioned in prerequisites, follow the installation guide given in link

Usergrid uses Cassandra’s Thrift protocol
Before starting cassandra, on Cassandra 2.x releases you MUST enable Thrift by setting start_rpc in your cassandra.yaml file:

    #Whether to start the thrift rpc server.
    start_rpc: true

Note:DataStax no longer supports the DataStax Community version of Apache Cassandra or the DataStax Distribution of Apache Cassandra. It is best to follow the Apache Documentation

Once you are up and running make a note of these things:

  • The name of the Cassandra cluster
  • Hostname or IP address of each Cassandra node
    • in case of same machine as Usergrid, then localhost. Usergrid would then be running on single machine embedded mode.
  • Port number used for Cassandra RPC (the default is 9160)
  • Replication factor of Cassandra cluster

Stack STEP #2: Setup ElasticSearch

Usergrid also needs access to at least one ElasticSearch node. As with Cassandra, you can setup single ElasticSearch node on your computer, and you should run a cluster in production.

Steps:

  • Download and unzip Elasticsearch
  • Run bin/elasticsearch (or bin\elasticsearch -d on Linux as Background Process) (or bin\elasticsearch.bat on Windows)
  • Run curl http://localhost:9200/

Once you are up and running make a note of these things:

  • The name of the ElasticSearch cluster
  • Hostname or IP address of each ElasticSearch node
    • in case of same machine as Usergrid, then localhost. Usergrid would then be running on single machine embedded mode.
  • Port number used for ElasticSearch protocol (the default is 9200)

Stack STEP #3: Setup Tomcat

The Usergrid Stack is contained in a file named ROOT.war, a standard Java EE WAR ready for deployment to Tomcat. On each machine that will run the Usergrid Stack you must install the Java SE 8 JDK and Tomcat 7+.

Stack STEP #4: Configure Usergrid Stack

You must create a Usergrid properties file called usergrid-deployment.properties. The properties in this file tell Usergrid how to communicate with Cassandra and ElasticSearch, and how to form URLs using the hostname you wish to use for Usegrid. There are many properties that you can set to configure Usergrid.

Once you have created your Usergrid properties file, place it in the Tomcat lib directory. On a Linux system, that directory is probably located at /path/to/tomcat7/lib/

The Default Usergrid Properties File

You should review the defaults in the above file. To get you started, let’s look at a minimal example properties file that you can edit and use as your own.

Please note that if you are installing Usergrid on the same machine as Cassandra Server, then set the following property to true

   #Tell Usergrid that Cassandra is not embedded.
   cassandra.embedded=true

Stack STEP #5: Deploy ROOT.war to Tomcat

The next step is to deploy the Usergrid Stack software to Tomcat. There are a variety of ways of doing this and the simplest is probably to place the Usergrid Stack ROOT.war file into the Tomcat webapps directory, then restart Tomcat.

Look for messages like this, which indicate that the ROOT.war file was deployed:

INFO: Starting service Catalina
Jan 29, 2016 1:00:32 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.59
Jan 29, 2016 1:00:32 PM org.apache.catalina.startup.HostConfig deployWAR
INFO: Deploying web application archive /usr/share/tomcat7/webapps/ROOT.war

Does it work?

you can use curl:

curl http://localhost:8080/status

If you get a JSON file of status data, then you’re ready to move to the next step. You should see a response that begins like this:

{
“timestamp” : 1454090178953,
“duration” : 10,
“status” : {
“started” : 1453957327516,
“uptime” : 132851437,
“version” : “201601240200-595955dff9ee4a706de9d97b86c5f0636fe24b43”,
“cassandraAvailable” : true,
“cassandraStatus” : “GREEN”,
“managementAppIndexStatus” : “GREEN”,
“queueDepth” : 0,
“org.apache.usergrid.count.AbstractBatcher” : {
“add_invocation” : {
“type” : “timer”,
“unit” : “microseconds”,
… etc. …

Initialize the Usergrid Database

Next, you must initialize the Usergrid database, index and query systems.

To do this you must issue a series of HTTP operations using the superuser credentials. You can only do this if Usergrid is configured to allow superused login via this property usergrid.sysadmin.login.allowed=true and if you used the above example properties file, it is allowed.

The three operation you must perform are expressed by the curl commands below and, of course, you will have ot change the password test to match the superuser password that you set in your Usergrid properties file.

curl -X PUT http://localhost:8080/system/database/setup -u superuser:test
curl -X PUT http://localhost:8080/system/database/bootstrap -u superuser:test
curl -X GET http://localhost:8080/system/superuser/setup -u superuser:test

When you issue each of those curl commands, you should see a success message like this:

{
“action” : “cassandra setup”,
“status” : “ok”,
“timestamp” : 1454100922067,
“duration” : 374
}

Now that you’ve gotten Usergrid up and running, you’re ready to deploy the Usergrid Portal.

Deploying the Usergrid Portal

The Usergrid Portal is an HTML5/JavaScript application, a bunch of static files that can be deployed to any web server, e.g. Apache HTTPD or Tomcat.

To deploy the Portal to a web server, you will un-tar the usergrid-portal.tar file into directory that serves as the root directory of your web pages.

Once you have done that there is one more step. You need to configure the portal so that it can find the Usergrid stack. You do that by editing the portal/config.js and changing this line:

Usergrid.overrideUrl = ’http://localhost:8080/‘;

To set the hostname that you will be using for your Usergrid installation.

I have deployed a sample instance and tested the same. You can find the system ready configurations in TechUtils repository

LDAP Connector

Below is a sample code to perform LDAP Queries. Just modify the configuration information and then provide any valid query to get the search results.

You can also modify the code to get custom business logic as required.