Recursive add stars between Characters

I am trying to write a recursive method to add stars between characters in a character arraylist. I am also trying to avoid hard coding in the method. Here is my attempt with the test code and desired output. I am trying to use a list iterator but I am wondering if there is a better way?

public static String addStars(List<Character> str) {
    if (str.isEmpty()) {
        return "";
    }

    else {

        char hold = '*';

        str.listIterator(1).add(hold);

        str.listIterator(3).add(hold);

    }

    return str.get(0) + addStars(str.subList(2, str.size()));
}

 public static void main(String[] args) {

ArrayList<Character> example = new ArrayList<>(Arrays.asList('a', 'b',  'c'));
    System.out.println(example); // [a, b, c]
    System.out.println(addStars(example)); // a*b*c
    System.out.println(example); // [a, *, b, *, c]
}

}

How to start ODBC tracing without using Data Source Administrator?

we are working on a java 8 standalone project, and we need to extract a query log from another application (an .exe), we were using the ODBC tracing to get the logs (manually for each run), but now we need to get them automatically (the other application querys variates depending of a .txt that we edit during the execution).

We need to know if there is a way to start the odbc tracing using java code, or with Runtime code (with cmd). What kind of alternatives we have?.

How do I hide and display a WebView located inside a snippet by using a button?

this is the java code of the fragment, I am currently working on a Tabbed Activity with action bar, in which there are three fragment and I want to put different WebView in each of the fragments and display them independently using buttons.

package com.example.facien.apliacionfacien;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Button;


public class FInformatica1 extends Fragment {

Button btn1;
WebView wView;

public FInformatica1() {
    // Required empty public constructor
}

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



}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_finformatica1, container, false);

    String url = "file:///android_asset/denominacionInformatica.html";
    WebView view = (WebView) rootView.findViewById(R.id.wView);



    view.getSettings().setJavaScriptEnabled(true);
    view.loadUrl(url);


    return rootView;
}
}

this is the fragment code

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.facien.apliacionfacien.FInformatica1">

<!-- TODO: Update blank fragment layout -->


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">



    <WebView
        android:id="@+id/wView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </WebView>

</LinearLayout>

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView" />
</FrameLayout>

this is the activity codestrong text

package com.example.facien.apliacionfacien;

import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;

public class InformaticaActivity extends AppCompatActivity implements ActionBar.TabListener, ViewPager.OnPageChangeListener{

Button btn1;
WebView wView;

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

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




    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);



        }

// Métodos de la interfaz ActionBar.TabListener
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
    mViewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {

}

@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {

}

// Métodos de la interfaz ViewPager.OnPageChangeListener
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

}

@Override
public void onPageSelected(int position) {
    getSupportActionBar().setSelectedNavigationItem(position);
}

@Override
public void onPageScrollStateChanged(int state) {

}

/**
 * A placeholder fragment containing a simple view.

 public static class PlaceholderFragment extends Fragment {
 /**
 * The fragment argument representing the section number for this
 * fragment.

 private static final String ARG_SECTION_NUMBER = "section_number";

 public PlaceholderFragment() {
 }

 /**
 * Returns a new instance of this fragment for the given section
 * number.
 */
/**
 public static PlaceholderFragment newInstance(int sectionNumber) {
 PlaceholderFragment fragment = new PlaceholderFragment();
 Bundle args = new Bundle();
 args.putInt(ARG_SECTION_NUMBER, sectionNumber);
 fragment.setArguments(args);
 return fragment;
 }

 }
 */

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */



public class SectionsPagerAdapter extends FragmentPagerAdapter {



    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {

        Fragment tabFragment = null;

        switch (position){
            case 0:
                tabFragment = new FInformatica1();
                break;
            case 1:
                tabFragment = new Finformatica2();
                break;
            case 2:
                tabFragment = new Finforamtica3();
                break;
        }
        return tabFragment;
    }

    @Override
    public int getCount() {
        // Show 2 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {

        String section = null;

        switch (position) {
            case 0:
                section = "SECTION 1";
                break;
            case 1:
                section = "SECTION 2";
                break;
            case 2:
                section = "SECTION 3";
                break;
        }
        return section;
    }
}
}

To assign Country in Country List one by one to Player in PlayerList

I am implementing RISK/Conquer game in JAVA. During the start-up phase of the game, I have to assign countries to each and every player. Just like distributing of cards from deck one by one to each player in the round-robin fashion.

The relation between Country and Player :

One Country has One Player (One to One)

One Player has Many Country (One to Many)

So far, this is my code:

Player.java

public class Player {

    public String name;
    public int totalArmies;
    public List<Country> assignedCountries;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }


    public int getTotalArmies() {
        return totalArmies;
    }

    public void setTotalArmies(int totalArmies) {
        this.totalArmies = totalArmies;
    }

    public List<Country> getAssignedCountries() {
        return assignedCountries;
    }

    public void setAssignedCountries(List<Country> assignedCountries) {
        this.assignedCountries = assignedCountries;
    }


    public Player(String name) {
        super();
        this.name = name;
    }

startup.java

 public class startup {
        HashMap<Country, List<Country>> graphMap = new HashMap<>();
    List<Country> neigNodesList = new ArrayList<>();
    List<Country> neigNodesList1 = new ArrayList<>();
        static List<Country> listofCountrytoAssignPlayers = new ArrayList<>();
        static List<Player> player = new ArrayList<>();
    public  void startup() {

            Country neig1 = new Country("ABC", 13, 14, "Asia");
            neigNodesList.add(neig1);
            Country neig2 = new Country("XYZ", 13, 14, "Asia");
            neigNodesList.add(neig2);

            Country country1 = new Country("MNP", 10, 11, "NorthAmerica");
            Country country2 = new Country("QWERTY", 10, 11, "NorthAmerica");
            Country country3 = new Country("IJK", 10, 11, "NorthAmerica");



            graphMap.put(country1, neigNodesList);
            graphMap.put(country2, neigNodesList1);
            graphMap.put(country3, neigNodesList);


            Iterator it = graphMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry pair = (Map.Entry) it.next();
                Country keyCountry = (Country) pair.getKey();
                listofCountrytoAssignPlayers.add(keyCountry);
                List<Country> neiCountryList = (List<Country>) pair.getValue();
                System.out.println("Country -->" + keyCountry.getCountryName());
                System.out.print("------Neigh List--------");
                System.out.println(graphMap.size());

                for (Country county : neiCountryList) {
                    System.out.println(county.getCountryName());
                }
                System.out.println("-----------");


            }// avoids a ConcurrentModificationException
        }

        public static void main(String args[]) {
            startup s1= new startup();
            s1.startup();
            System.out.println("Enter number of players:  ");
            Scanner scanner = new Scanner(System.in);
            int totalPlayers = scanner.nextInt();
            List<Player> playerList = new ArrayList<Player>();
            int i = 0;
            while (i < totalPlayers) {
                playerList.add(new Player("player" + i));
                i++;
            }

            Collections.shuffle(listofCountrytoAssignPlayers);
            for(Player player:playerList){
                List<Country> countryforaPlayer = new ArrayList<>();
                 for(int k=0;k<playerList.size();k++)
                 {
                    countryforaPlayer.add(listofCountrytoAssignPlayers.get(k));
                 }
                 //player.setAssignedCountries(countryforaPlayer);
                 playerList.add(player);
            }
        }

    }

I am getting the following error:

Enter number of players:  
1
Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
    at java.util.ArrayList$Itr.next(ArrayList.java:851)
    at startupphase.startup.main(startup.java:86)

Process finished with exit code 1

What I am not getting is how to implement it, every algorithm/logic think of and try to implement it I am not getting the desired result.

Java Noob: Frustrated with code

public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello World");
    String test="numbers";
    metho(test);
    System.out.println(test);
  }

  public static void metho(String x) {
    int c=x.length();
    for(int i=0;i<c;i++) {
      x=x+""+i;
    }
  }
}

I cant seem to find the error in my code, it is a logic error. My goal is just to print out my text random with the numbers that should of concatenated in my for loop. Why wont this work , what have I done wrong in this specific code?!?!

Eclipse: Errors occurred during the build. Errors running builder ‘Java Builder’

I’m having an annoying error while trying to make Eclipse Oxygen work in Kubuntu 16.04. Whenever I open a file, and sometimes on Eclipse startup too even if there’s no open ones, I get many errors, in particular some I can’t copy that occur when I try to use code completion, and most of all this one:

Errors occurred during the build.
Errors running builder 'Java Builder' on project 'MyFirstAfterReinstallAndPlugin'.
java.lang.NullPointerException

I have to specify that this started to occur after I downloaded the extension for Java 9 support and created a new project with the Java_SE9 JRE: before that it would behave in another strange way. Code correction wouldn’t find the “System” class and a lot of strange errors happened. I have installed openjdk9 and javac from command line works fine. Plus Eclipse said that I had to have Java 1.8 or superior, making the fact that it didn’t work before strange as well…

I’ve tried everything I found online but still can’t figure this out… it’s pretty annoying since I’m currently busy and I need this to work asap, any help will be appreciated!

Mapping JSON to Class not working

I have a class which contains other some properties of another classes and when I try to convert from json to my class, there is an error displayed.

This is my class:

import org.jongo.marshall.jackson.oid.MongoObjectId;
import org.json.JSONObject;

import java.util.List;

public class BusinessTravelDTO {
  @MongoObjectId
  private String id;

  private String travelerId;

  private BusinessTravelStatus status;

  List<FlightDTO> flights;

  List<HotelDTO> hotels;

  List<CarDTO> cars;

  public BusinessTravelDTO() { }

  public BusinessTravelDTO(JSONObject data) {
    this.travelerId = data.getString("travelerId");
    this.status =  BusinessTravelStatus.valueOf(data.getString("status"));
    this.flights = HandlerUtil.getInputFlights(data.getJSONArray("flights"));
    this.hotels = HandlerUtil.getInputHotels(data.getJSONArray("hotels"));
    this.cars = HandlerUtil.getInputCars(data.getJSONArray("cars"));
  }

  public JSONObject toJson() {
    return new JSONObject()
            .put("id", this.id)
            .put("travelerId", this.travelerId)
            .put("status", this.status)
            .put("flights", this.flights)
            .put("hotels", this.hotels)
            .put("cars", this.cars);
  }

And here is where I try to convert to class:

 public static JSONObject acceptBusinessTravel(JSONObject input) {
    String btId = getStringField(input, "id");
    MongoCollection businessTravels = getBTCollection();

     // Here is the problem...
    BusinessTravelDTO bt = businessTravels.findOne(new ObjectId(btId)).as(BusinessTravelDTO.class);
    bt.setStatus(BusinessTravelStatus.Accepted);

    businessTravels.save(bt);

    return new JSONObject().put("message", "The business travel has been ACCEPTED by your manager. Check your email.");
  }

Here is the error I receive:

"error": "org.jongo.marshall.MarshallingException: Unable to unmarshall result to class path.data.BusinessTravelDTO from content { "_id" : { "$oid" : "59d6905411d58632fd5bd8a5"} , "travelerId" 

In jongo docs is specified that the class should have an empty constructor… http://jongo.org/#mapping I have 2 constructors, I have tried also with @JsonCreator, but no success… 🙁
Do you have an idea why it doesn’t convert? Could it be something related to fields inside BusinesTravelDTO like List CarDTO for ex ?

Android Manifest merger failure

I have two android projects working individually (A and B). I have made a parent project with two buttons that calls each of these child projects (I have included the child projects as libraries). Initially I added one child project to my parent project and it works fine. However, upon adding the second child project, I get an android manifest merger error. Each of the child application need an SDK key to register upon startup. This is defined in the manifest as below:

Child app A:

<application
    android:name=".DemoApplication"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    tools:replace="android:icon">

    <!-- DJI SDK -->
    <uses-library android:name="com.android.future.usb.accessory" />

    <meta-data
        android:name="com.dji.sdk.API_KEY"
        android:value="f70d587986XXXXXXXXXX"/>

Child App B:

<application
    android:name=".DJIDemoApplication"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <!-- DJI SDK -->

    <uses-library android:name="com.android.future.usb.accessory" />

    <meta-data
        android:name="com.dji.sdk.API_KEY"
        android:value="2cde5eaabXXXXXXXXXXXX" /> //TODO: Enter your app key here

The error android manifest gives seems to do with the API_KEY value in metadata portion. My guess is that upon manifest merge, it does not know which value of API_KEY to use. However, I need both values to register both apps A and B. I have tried adding ‘tools:replace=android:value’ to one of the child applications but the compiled application only runs one child. The exact error is as follows:

Error: Attribute meta-data#com.dji.sdk.API_KEY@value value=(f70d587986XXXXXXXXXX) from AndroidManifest.xml:34:55-95 is also present at AndroidManifest.xml:34:55-95 value=(2cde5eaabXXXXXXXXXXXXX). Suggestion: add 'tools:replace="android:value"' to <meta-data> element at AndroidManifest.xml:34:9-97 to override. app main manifest (this file), line 33

I am new to android and don’t know how to resolve this issue. Any help regarding this will be highly appreciated.

deleting or renaming column in sqlite

please I named one of my columns as “from”and it’s causing errors, please do I rename or delete the column and I am using sqlite database system. this was what I tried and it did not work.

INSERT INTO passengerinfonew(driverid, name, surname, age, username, password, gender, marital_status, fromDest, toDest)
SELECT driverid, name, surname, age, username, password, gender, marital_status, from, to FROM passengerinfonews;
this was after creating a temporary table

java Web socket client using Socks Proxy

I have a spring boot app with Spring Websocket listener and Stomp.
Server URI = wss://XXXX:9090/chat

My server is behind firewall and client needs Socks proxy to connect to the server.

For regular Socket , the connection is established through Socks and end point like this.

SocketAddress socketAddress = new InetSocketAddress(sockshost, socksPort);
    Proxy proxy = new Proxy(Proxy.Type.SOCKS, socketAddress);
    Socket socketToClient = new Socket(proxy);
    InetSocketAddress dest = new InetSocketAddress(destinationip,port);
    try {
socketToClient.connect(dest,SOCKET_TIMEOUT_CONNECT);
    }catch (SocketTimeoutException e) {

..
}

For WebsocketClient, I cannot find an API to set SOCKS.
eg My current client is

WebSocketClient simpleWebSocketClient = new StandardWebSocketClient();
List<Transport> transports = new ArrayList<>(1);
transports.add(new WebSocketTransport(simpleWebSocketClient));
SockJsClient sockJsClient = new SockJsClient(transports);
WebSocketStompClient stompClient = new WebSocketStompClient(sockJsClient);
...
stompClient.connect(webSocketServerUrl, sessionHandler).get();

Where do I set the Proxy as SOCKS Proxy ? similar to regular socket.
Or
Can I Wrap the regular client socket as a Websocket ?

Appreciate any inputs ..