how to arrange a panel with GridLayout in java swing

Hi I’m doing a snakes and ladders game, you can see the picure that I have a problem in the left panel which is not well-arranged .
I used GridLayout to make everything of image , jlable and jbotton be in one column and many rows , I don’t know if there is better way to make it more better .

enter image description here

my code for left panel

    // -----------------left panel------------------------------

    JPanel leftPanel = new JPanel(new GridLayout(8, 1));

    leftPanel.setSize(1, 177);

    JPanel panel1 = new JPanel();

    ImageIcon image = new ImageIcon("logo1.jpg");
    JLabel label = new JLabel("", image, JLabel.CENTER);
    panel1.add(label);

    JPanel panel2 = new JPanel();
    JLabel player1text = new JLabel("Player 1");
    panel2.add(player1text);

    JPanel panel3 = new JPanel();
    dice1 = new JButton("", new ImageIcon(GameProject.class.getResource("pictures/Dice.png")));

    dice1.addActionListener(this);
    panel3.add(dice1);

    JPanel panel4 = new JPanel();
    JLabel player2text = new JLabel("Player 2");
    panel4.add(player2text);

    JPanel panel5 = new JPanel();
    dice2 = new JButton("", new ImageIcon(GameProject.class.getResource("pictures/Dice.png")));

    dice2.addActionListener(this);
    panel5.add(dice2);

     leftPanel.add(panel1);
    leftPanel.add(panel2);
    leftPanel.add(panel3);
    leftPanel.add(panel4);
    leftPanel.add(panel5);

    add(leftPanel, BorderLayout.WEST);

    // -----------------------------------------------------

springboot how to dynamically switch different datasource

I have the requirement like to switch the datasource at runtime. The different database configuration data(it may be mysql, oracle, mongodb ..) is persisted in DB. Because I need to add datasource at any time, so I do that. Now, when I use the datasource, I will get database configuration data in the DB and create a new sqlSessionFactory again.

How can I give it to Spring IOC container to deal with?

Role base authentication and redirecting request on different pages

I am trying to achieve spring security role based authentication and redirect the user on different pages based on their role. If the user in admin redirect them to admin/index.html and if user is developer redirect them to developer/index.html.

For that I tried below code. I am not facing any exception, but not sure where is the problem. Any help is appreciated !

WebContent/admin/index.html

This is admin landing page

WebContent/developer/index.html

This is developer landing page

pom.xml

http://maven.apache.org/maven-v4_0_0.xsd”>
4.0.0

<groupId>com.provm</groupId>
<artifactId>aws-vm-pro</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>aws-vm-pro</name>
<url>http://maven.apache.org</url>

<dependencies>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.2.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>4.0.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>4.0.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>net.bull.javamelody</groupId>
        <artifactId>javamelody-core</artifactId>
        <version>1.60.0</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.2</version>
    </dependency>
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
                <warSourceDirectory>WebContent</warSourceDirectory>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-maven-plugin</artifactId>
            <version>9.0.6.v20130930</version>
            <configuration>
                <webAppSourceDirectory>WebContent</webAppSourceDirectory>
                <httpConnector>
                    <port>8088</port>
                    <host>localhost</host>
                </httpConnector>
                <scanIntervalSeconds>10</scanIntervalSeconds>
            </configuration>
        </plugin>
    </plugins>
</build>

SecurityWebApplicationInitializer.java

package com.my.app;

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {

    public SecurityWebApplicationInitializer() {
        super(MvcConfig.class, SecurityConfig.class);
    }

}

MvcConfig.java

package com.my.app;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan(basePackages = "com.my.app")
public class MvcConfig {

    @Bean
    public CustomSuccessHandler getCustomSuccessHandler() {
        return new CustomSuccessHandler();
    }

    @Bean
    public MyUserDetailsService getMyUserDetailsService() {
        return new MyUserDetailsService();
    }

}

SecurityConfig.java

package com.my.app;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    CustomSuccessHandler customSuccessHandler;
    @Autowired
    MyUserDetailsService myUserDetailsService;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").hasAnyRole("ADMIN", "DEVELOPER").antMatchers("/admin/**")
                .hasRole("ADMIN").antMatchers("/developer/**").hasRole("DEVELOPER").and().formLogin()
                .successHandler(customSuccessHandler).and().logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll();
        http.csrf().disable();
    }

}

CustomSuccessHandler.java

package com.my.app;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

@Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException {
        String targetUrl = determineTargetUrl(authentication);
        if (response.isCommitted()) {
            System.out.println("Can't redirect");
            return;
        }
        redirectStrategy.sendRedirect(request, response, targetUrl);
    }

    protected String determineTargetUrl(Authentication authentication) {
        String url = "";
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        List<String> roles = new ArrayList<String>();
        for (GrantedAuthority a : authorities) {
            roles.add(a.getAuthority());
        }
        if (isAdmin(roles)) {
            url = "/admin/index.html";
        } else if (isDeveloper(roles)) {
            url = "/developer/index.html";
        }
        return url;
    }

    private boolean isAdmin(List<String> roles) {
        if (roles.contains("ROLE_ADMIN")) {
            return true;
        }
        return false;
    }

    private boolean isDeveloper(List<String> roles) {
        if (roles.contains("ROLE_DEVELOPER")) {
            return true;
        }
        return false;
    }

    public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
        this.redirectStrategy = redirectStrategy;
    }

    protected RedirectStrategy getRedirectStrategy() {
        return redirectStrategy;
    }

}

MyUserDetailsService.java

package com.my.app;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component
public class MyUserDetailsService implements UserDetailsService {

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String password = null;
        String[] authorities = new String[1];
        String admin = "admin";
        String developer = "developer";
        if (username.equals(admin)) {
            password = "admin";
            authorities[0] = "ADMIN";
        }
        if (username.equals(developer)) {
            password = "developer";
            authorities[1] = "DEVELOPER";
        }
        System.out.println(username + "=" + password + "=" + authorities);
        return new MyUserDetails(username, password, authorities);
    }

}

MyUserDetails.java

package com.my.app;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.List;

public class MyUserDetails implements UserDetails {
    private String username;
    private String password;
    private List<GrantedAuthority> grantedAuthorities;

    public MyUserDetails(String username, String password, String[] authorities) {
        this.username = username;
        this.password = password;
        this.grantedAuthorities = AuthorityUtils.createAuthorityList(authorities);
    }

    public Collection<? extends GrantedAuthority> getAuthorities() {
        return grantedAuthorities;
    }

    public String getPassword() {
        return password;
    }

    public String getUsername() {
        return username;
    }

    public boolean isAccountNonExpired() {
        return true;
    }

    public boolean isAccountNonLocked() {
        return true;
    }

    public boolean isCredentialsNonExpired() {
        return true;
    }

    public boolean isEnabled() {
        return true;
    }

}

error: can someone help me with the code

I made an ascending array sorting but it gives error all the time.
here is the code:

    import java.util.*;
public class algo {
public static void main(String[] args) {
    Scanner tara = new Scanner(System.in);
    System.out.print("sayı girin");
    int n=tara.nextInt();
    int a[]=new int [n];
    int x,y,entry=0;
    System.out.print(n+"eleman girin");
    for(x=0;x<n;x++) {
        a[x]=tara.nextInt();
    }
    System.out.print("elemanlar  :");
    for(x=0;x<n;x++) {
        System.out.print("     "+a[x]);
    }
            for(x=0;x<n;x++);{
                for(y=1;y<n;y++) {
                    if(a[x]>a[y]) {
                        entry=a[x];
                        a[y]=a[x];
                        a[y]=entry;
                    }
                }
            }
            System.out.print("artan sırada   :");
            for(x=0;x<n;x++) {
                System.out.print("     "+a[x]);
            }
}
}

I couldn’t under stand the

for(x=0;x<n;x++);{
                    for(y=1;y<n;y++) {
                        if(a[x]>a[y]) {
                            entry=a[x];
                            a[y]=a[x];
                            a[y]=entry;
                        }

part can somebody please explain?

And it also gives the following error:

 12Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
    at algo.main(algo.java:19) 

And it also says the scanner is never closed

Get annotation value dynamically, not hard coding the class/method name to get the annotation value

I have some tests running on testNG, which will have test data type annotated on the test method, i am using a common a method to read the test data based on the annotation value in test methods. Problem here is, i can not specify the class or method name to read the annotation as there will be different/multiple test methods from different classes that will be reading the test data. So i am looking for a way to read the annotation dynamically from this common method, based on which test method is seeking for the test data.

Please have a look on the below code snippet for more clarity.

public class MyClass1 {

    @Test
    @testDataParam(testDataType="excel")
    public void test1() {

        DataTable dataTable = new DataTable();
        dataTable.getValue();
        //Some test that reads from specified test data type
    }

}

public class MyClass2 {

    @Test
    @testDataParam(testDataType="json")
    public void test2() {

        DataTable dataTable = new DataTable();
        dataTable.getValue();
        //Some test that reads from specified test data type
    }

}

public class GetTestData {

    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface testDataParam {
        String testDataType();
    }

}

public class DataTable {

    public void setDataTable() {

        // get annotation from test methods, test methods will be different for
        // different test, so i can not mention specific class or method here to read
        // annotation.

        // if test data type is excel, read data from excel
        // if test data type is json, read data from json
    }

    public String getValue() {

        // return value from specified data type excel/json
        return "";
    }
}

How can I implement Observer pattern with broadcastreceiver and Main UI in Android to start a thread

I want to do some multithreading stuff… When the broadcastreceiver is triggered, I’d like it to set a value in a Observable. Then, I’d like the Main UI thread to be notified of that change. Upon that, the main UI thread will start another thread for some work… Below is the architecture of what I have got so far but it’s not working

My Observable Object Class

public class MyObservableObject extends Observable{
    String value;

    public MyObservableObject(){}

    public setValue(String value){
        this.value = value;
        setChanged();
        notifyObservers(value);
    }
}

**My Main UI class **

public class MainActivity extends AppCompatActivity implements Observer{

    private MyObservableObject myObservableObject;

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

        myObservableObject = new MyObservableObject();

    }

    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
        MainActivity.this.registerReceiver(myReceiver, filter);
        sendBroadcast(new Intent("android.provider.Telephony.SMS_RECEIVED"));
    }

    @Override
    protected void onStop() {
        MainActivity.this.unregisterReceiver(myReceiver);
        super.onStop();
    }

    BroadcastReceiver myReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().
                    equals("android.provider.Telephony.SMS_RECEIVED")) {
                StringBuilder sb = new StringBuilder();
                Bundle bundle = intent.getExtras();
                if (bundle != null) {
                    Object[] pdus = (Object[])
                            bundle.get("pdus");
                    for (Object pdu : pdus) {
                        SmsMessage smsMessage =
                                SmsMessage.createFromPdu
                                        ((byte[]) pdu);
                        sb.append("body - " + smsMessage.
                                getDisplayMessageBody());
                    }

                    this.myObservableObject.setValue(sb.toString());
                }
            }
        }
    };


    @Override
    public void update(Observable o, Object arg) {
        try {
            new Thread(
                    new SocketServerReplyThread((String)arg)
            ).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private class SocketServerReplyThread  extends Thread {

        private Socket hostThreadSocket;
        private String sms;
        SocketServerReplyThread(String sms) {
            hostThreadSocket = new ServerSocket(5555);
            hostThreadSocket.accept();
            this.sms = sms;
        }

        @Override
        public void run() {
            try{

                OutputStream os = hostThreadSocket.getOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(os);

                DonneesDeTransfert dt2 = new DonneesDeTransfert();
                dt2.setSmsResultat(sms);
                oos.writeObject(dt2);
                hostThreadSocket.close();

            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
}

Converting AESCryptography Cs code into Java Code

namespace AESTestSample.Helpers
{
public class AESTest
{
#region Configured Values
private static string saltValue = ConfigurationManager.AppSettings[“Salt”]; //Salt value used along with passphrase to generate password. Salt can be any string. In this example we assume that salt is an ASCII string.
private static int passwordIterations = Convert.ToInt32(ConfigurationManager.AppSettings[“PasswordIterations”]);//Number of iterations used to generate password. One or two iterations should be enough.
private static string initVector = ConfigurationManager.AppSettings[“InitVector”];//Initialization vector (or IV). This value is required to encrypt the first block of plaintext data. For RijndaelManaged class IV must be exactly 16 ASCII characters long.
private static string hashAlgorithm = ConfigurationManager.AppSettings[“HashAlgorithm”];//Hash algorithm used to generate password. Allowed values are: “MD5” and “SHA1”. SHA1 hashes are a bit slower, but more secure than MD5 hashes.
private static int keySize = Convert.ToInt32(ConfigurationManager.AppSettings[“Keysize”]);//Size of encryption key in bits. Allowed values are: 128, 192, and 256. Longer keys are more secure than shorter keys.
private static string passPhrase = ConfigurationManager.AppSettings[“Key”];// Passphrase from which a pseudo-random password will be derived. The derived password will be used to generate the encryption key. Passphrase can be any string.
#endregion

    #region Encryption
    /// <summary>
    /// Encrypts specified plaintext using Rijndael symmetric key algorithm
    /// and returns a base64-encoded result.
    /// </summary>
    /// <param name="plainText">
    /// Plaintext value to be encrypted.
    /// </param>
    /// <returns>
    /// Encrypted value formatted as a base64-encoded string.
    /// </returns>
    public static string Encrypt(string plainText)
    {
        // Convert strings into byte arrays.
        // Let us assume that strings only contain ASCII codes.
        // If strings include Unicode characters, use Unicode, UTF7, or UTF8 
        // encoding.
        byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
        byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);

        // Convert our plaintext into a byte array.
        // Let us assume that plaintext contains UTF8-encoded characters.
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

        // First, we must create a password, from which the key will be derived.
        // This password will be generated from the specified passphrase and 
        // salt value. The password will be created using the specified hash 
        // algorithm. Password creation can be done in several iterations.
        PasswordDeriveBytes password = new PasswordDeriveBytes
        (
            passPhrase,
            saltValueBytes,
            hashAlgorithm,
            passwordIterations
        );

        // Use the password to generate pseudo-random bytes for the encryption
        // key. Specify the size of the key in bytes (instead of bits).
        byte[] keyBytes = password.GetBytes(keySize / 8);

        // Create uninitialized Rijndael encryption object.
        RijndaelManaged symmetricKey = new RijndaelManaged();

        // It is reasonable to set encryption mode to Cipher Block Chaining
        // (CBC). Use default options for other symmetric key parameters.
        symmetricKey.Mode = CipherMode.CBC;

        // Generate encryptor from the existing key bytes and initialization 
        // vector. Key size will be defined based on the number of the key 
        // bytes.
        ICryptoTransform encryptor = symmetricKey.CreateEncryptor
        (
            keyBytes,
            initVectorBytes
        );

        // Define memory stream which will be used to hold encrypted data.
        MemoryStream memoryStream = new MemoryStream();

        // Define cryptographic stream (always use Write mode for encryption).
        CryptoStream cryptoStream = new CryptoStream
        (
            memoryStream,
            encryptor,
            CryptoStreamMode.Write
        );

        // Start encrypting.
        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);

        // Finish encrypting.
        cryptoStream.FlushFinalBlock();

        // Convert our encrypted data from a memory stream into a byte array.
        byte[] cipherTextBytes = memoryStream.ToArray();

        // Close both streams.
        memoryStream.Close();
        cryptoStream.Close();

        // Convert encrypted data into a base64-encoded string.
        string cipherText = Convert.ToBase64String(cipherTextBytes);

        // Return encrypted string.
        return cipherText;
    }
    #endregion

    #region Decryption

    /// <summary>
    /// Decrypts specified ciphertext using Rijndael symmetric key algorithm.
    /// </summary>
    /// <param name="cipherText">
    /// Base64-formatted ciphertext value.
    /// </param>
    /// <returns>
    /// Decrypted string value.
    /// </returns>
    /// <remarks>
    /// Most of the logic in this function is similar to the Encrypt
    /// logic. In order for decryption to work, all parameters of this function
    /// - except cipherText value - must match the corresponding parameters of
    /// the Encrypt function which was called to generate the
    /// ciphertext.
    /// </remarks>
    public static string Decrypt(string cipherText)
    {
        // Convert strings defining encryption key characteristics into byte
        // arrays. Let us assume that strings only contain ASCII codes.
        // If strings include Unicode characters, use Unicode, UTF7, or UTF8
        // encoding.
        byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
        byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);

        // Convert our ciphertext into a byte array.
        byte[] cipherTextBytes = Convert.FromBase64String(cipherText);

        try { 
            // First, we must create a password, from which the key will be 
            // derived. This password will be generated from the specified 
            // passphrase and salt value. The password will be created using
            // the specified hash algorithm. Password creation can be done in
            // several iterations.
            PasswordDeriveBytes password = new PasswordDeriveBytes
            (
                passPhrase,
                saltValueBytes,
                hashAlgorithm,
                passwordIterations
            );

            // Use the password to generate pseudo-random bytes for the encryption
            // key. Specify the size of the key in bytes (instead of bits).
            byte[] keyBytes = password.GetBytes(keySize / 8);

            // Create uninitialized Rijndael encryption object.
            RijndaelManaged symmetricKey = new RijndaelManaged();

            // It is reasonable to set encryption mode to Cipher Block Chaining
            // (CBC). Use default options for other symmetric key parameters.
            symmetricKey.Mode = CipherMode.CBC;

            // Generate decryptor from the existing key bytes and initialization 
            // vector. Key size will be defined based on the number of the key 
            // bytes.
            ICryptoTransform decryptor = symmetricKey.CreateDecryptor
            (
                keyBytes,
                initVectorBytes
            );

            // Define memory stream which will be used to hold encrypted data.
            MemoryStream memoryStream = new MemoryStream(cipherTextBytes);

            // Define cryptographic stream (always use Read mode for encryption).
            CryptoStream cryptoStream = new CryptoStream
            (
                memoryStream,
                decryptor,
                CryptoStreamMode.Read
            );

            // Since at this point we don't know what the size of decrypted data
            // will be, allocate the buffer long enough to hold ciphertext;
            // plaintext is never longer than ciphertext.
            byte[] plainTextBytes = new byte[cipherTextBytes.Length];

            // Start decrypting.
            int decryptedByteCount = cryptoStream.Read
            (
                plainTextBytes,
                0,
                plainTextBytes.Length
            );

            // Close both streams.
            memoryStream.Close();
            cryptoStream.Close();
            // Convert decrypted data into a string. 
            // Let us assume that the original plaintext string was UTF8-encoded.
            string plainText = Encoding.UTF8.GetString
                (
                    plainTextBytes,
                    0,
                    decryptedByteCount
                );

            // Return decrypted string.   
            return plainText;
        }
        catch(Exception ex){
            throw ex;
        }            
    } 
    #endregion
}

}