Access nested Items of a JSON array using Volley library

I’m trying to access information from within a nested JSON array using the Volley library. Specifically, I am trying to get the properties of ‘statusSeverityDescription’ from within ‘lineStatuses’. I’ve searched for and tried many solutions I have seen. Just cant seem to get the data i need. Please see code and JSON below.

Code

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

    bob = (TextView) findViewById(R.id.bob);
    tempTextView = (TextView) findViewById(R.id.tempTextView);

    String url = "https://api.tfl.gov.uk/Line/victoria/Status";

     JsonArrayRequest jsArrayRequest = new JsonArrayRequest
            (Request.Method.GET, url, null, new Response.Listener<JSONArray>() {

                @Override
                public void onResponse(JSONArray response) {

                    try{
                        // Loop through the array elements
                        for(int i=0;i<response.length();i++){
                            // Get current json object
                            JSONObject line = response.getJSONObject(i);

                            // Get the current line (json object) data
                            String lineName = line.getString("name");

                            String lineStatus = line.getString("lineStatuses");

                            // Display the formatted json data in text view

                            tempTextView.setText(lineName);

                            bob.setText(lineStatus);

                            Log.v("status", "Response: " + lineStatus);

                        }
                    }catch (JSONException e){
                        e.printStackTrace();
                    }
                }
            },






             new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("TAG", "Error response:", error);
                }
            });

JSON

[
{
    "$type": "Tfl.Api.Presentation.Entities.Line, Tfl.Api.Presentation.Entities",
    "id": "northern",
    "name": "Northern",
    "modeName": "tube",
    "disruptions": [],
    "created": "2017-10-31T10:48:22.99Z",
    "modified": "2017-10-31T10:48:22.99Z",
    "lineStatuses": [
        {
            "$type": "Tfl.Api.Presentation.Entities.LineStatus, Tfl.Api.Presentation.Entities",
            "id": 0,
            "statusSeverity": 10,
            "statusSeverityDescription": "Good Service",
            "created": "0001-01-01T00:00:00",
            "validityPeriods": []
        }
    ],
    "routeSections": [],
    "serviceTypes": [
        {
            "$type": "Tfl.Api.Presentation.Entities.LineServiceTypeInfo, Tfl.Api.Presentation.Entities",
            "name": "Regular",
            "uri": "/Line/Route?ids=Northern&serviceTypes=Regular"
        },
        {
            "$type": "Tfl.Api.Presentation.Entities.LineServiceTypeInfo, Tfl.Api.Presentation.Entities",
            "name": "Night",
            "uri": "/Line/Route?ids=Northern&serviceTypes=Night"
        }
    ],
    "crowding": {
        "$type": "Tfl.Api.Presentation.Entities.Crowding, Tfl.Api.Presentation.Entities"
    }
}
   ]

Thanks for looking.

Save chat messages with closed app

Good evening!

I’m developing a chat application that looks like WhatsApp. I need the received messages to be saved on the user’s mobile device. Until then everything was ok, because I was saving the messages when the user received the push notification on the mobile, but the problem happens when the application is closed because when the application is closed the push notification does not trigger the received push event (I am using the Onesignal to send the push).

I’d like to know how I can do this, ie get a notification and process it even with my closed application. I think it has to do this because Whatsapp does this and also Spotify also does it when I connect the Spotify to another device it automatically forces the opening of the application on my cell phone.

So my question is, how do I handle an event with the application closed or even force it to open according to a particular event?

I’m using the technology of Ionic 1 and Angular.js. For push notification I am using the OneSignal provider.

Thanks in advance for your attention and hope someone can help me. Thank you!

How do I provide create a CloseableHttpPipeliningClient that doesn’t validate SSL certificates?

I’m trying to use Apache HttpAsyncClient with HTTP pipelining support. I want to add a trust-all SSL strategy similar to what’s discussed here Ignoring SSL certificate in Apache HttpClient 4.3 (and a bunch of other places). But I don’t see any way to get a pipelining client builder using the custom SSLContext: the HttpAsyncClients.createPipelining() method doesn’t return a builder, and HttpAsyncClients.custom() builder doesn’t build a ClosableHttpPipeliningClient

HashMap.get returns null

I have a class that is a holder class for a HashMap and I create an instance of it in my main class and use it throughout all my classes. I have checked that my object is being added to my map but at some point during runtime when I go to access a value from the hashmap it returns null. Any ideas?

// Own class public boolean isFrozen(UUID uuid)
{
    User user = userManager.get(uuid);

    return lastFrozenLocations.containsKey(uuid) || user.isFrozen();
}
// Another class  private static Map<UUID, User> users = new HashMap<UUID, User>();

public Collection<User> getAll()
{
    return users.values();
}

public User get(UUID uuid)
{
    return users.get(uuid);
}

public boolean has(UUID uuid)
{
    return users.containsKey(uuid);
}

public void add(User user)
{
    users.put(user.getUuid(), user);
}

public void remove(UUID uuid)
{
    users.remove(uuid);
}
//Again another class 

    UUID uuid = player.getUniqueId();

    if(userManager.has(uuid))
    {
        userManager.get(uuid).setOnline(true);
    }else new Load(player);
}

XMLUnit tag containing name attribute not matching

I am using xmlunit 2.5.0.

Below are my two xml string : One is the controlxml and one is testxml.

String controlXml = "<flowers><flower><f1 name = "Roses"/></flower><flower><f1 name = "Daisy"/></flower><flower><f1 name = "Crocus"/></flower></flowers>";

String testXml = "<flowers><flower><f1 name = "Daisy"/></flower><flower><f1 name = "Roses"/></flower><flower><f1 name = "Crocus"/></flower></flowers>";

Here i am comparing these two string xmls using xmlunit.

My java code is:

org.xmlunit.diff.Diff myDiff = DiffBuilder.compare(controlXml).withTest(testXml)
                    .checkForSimilar() 
                    .withNodeMatcher(new 
                     DefaultNodeMatcher(ElementSelectors.conditionalBuilder()
                               .whenElementIsNamed("f1")
                               .thenUse(ElementSelectors.byName)
                               .elseUse(ElementSelectors.byNameAndText)
                               .build()))
                    .build();

Getting error:

***********************
Expected attribute value 'Roses' but was 'Daisy' - comparing <f1 name="Roses"...> at /flowers[1]/flower[1]/f1[1]/@name to <f1 name="Daisy"...> at /flowers[1]/flower[1]/f1[1]/@name (DIFFERENT)
***********************
***********************
Expected attribute value 'Daisy' but was 'Roses' - comparing <f1 name="Daisy"...> at /flowers[1]/flower[2]/f1[1]/@name to <f1 name="Roses"...> at /flowers[1]/flower[2]/f1[1]/@name (DIFFERENT)
***********************

I want to get no error since Rose is present in the testxml. Why is Rose in controlxml is being compared to Daisy in testxml even though i have rose in the testxml and i have ElementSelectors.byName and whenElementIsNamed("f1").

Which ElementSelector should I use?

Fragment declared target fragment that does not belong to this FragmentManager

I have made an activity A which have a fragment x in it. By fragment x, edit text item on click event, i want to open another fragment y, where a list is shown and i just press the name on list, the y fragment closes and send the selected name of list to fragment x edit text and the code i did is

YFragment y = new YFragment();
y.setTargetFragment(x.class, code);
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frame, y)
.addToBackStack(null).commit();

and in fragment y i did the target code to send the data but problem in this block of code above. if i comment set target fragment line the code will work but no use as data will not be send but if i run the app this error occurs

java.lang.IllegalStateException: Fragment y{46d3d31 #3 id=0x7f090069} declared target fragment x{e2c16 #0 id=0x7f090104 android:switcher:2131296516:0} that does not belong to this FragmentManager!

Can I mock some static methods only using powermock+mockito+junit?

I am writing a test using junit + mockito + powermock.

I have a class like which I want to test:

public class MyUtils {
    public static Object method1() {} //I want to mock this only
    public static void method2() {}   //I want to keep this as is during my test.
    public static void method3() {}   //I want to keep this as is during my test.
}

I want to mock only method1 but not method2 or method3.

@RunWith(PowerMockRunner.class)
@PrepareForTest(MyUtils.class)
public class MyTest {

    @Before
    public void setUpBeforeClass() throws Exception {
        PowerMockito.mockStatic(MyUtils.class);
    }

    @Test
    public void test1() throws Exception {
        when(MyUtils.method1()).thenReturn(something);

        MyUtils.method3(); //method3 is getting mocked with an empty implementation by PowerMockito
    }

    ...
}

Can I have some methods be mocked and some not be mocked i.e. they keep their original implementation during the test. Is this possible with mockito + powermock?

My test may not look very elegant but I have simplified my usecase before posting here.

Thank you.

Could someone get me started with converting this code into a function? [on hold]

I am trying to convert my already written code into a function but I am having trouble. Could anyone re-write the snippet of code below into a function so I can get an understanding on what to do.

    package functions;

     import java.util.Scanner;
     import java.io.*;


    public class functions {
    public static void main(String[] args) throws IOException {

    Scanner kbd = new Scanner(System.in);
    File priceFile;

    double entreePrice[], beveragePrice[], dessertPrice[];
    entreePrice = new double[3];
    beveragePrice = new double[4];
    dessertPrice = new double[2];


//Load Meal Prices from File
    priceFile = new File("pricefile.txt");
    priceSC = new Scanner(priceFile);
    entreePrice[0] = priceSC.nextDouble();
    entreePrice[1] = priceSC.nextDouble();
    entreePrice[2] = priceSC.nextDouble();

    beveragePrice[0] = priceSC.nextDouble();
    beveragePrice[1] = priceSC.nextDouble();
    beveragePrice[2] = priceSC.nextDouble();
    beveragePrice[3] = priceSC.nextDouble();

    dessertPrice[0] = priceSC.nextDouble();
    dessertPrice[1] = priceSC.nextDouble();

    priceSC.close();
    }
    }

Eureka Client – can’t autowire client (spring says there are 2 beans defined)

I have an application that is a eureka discovery client.

It registers with my Eureka server just fine.

Sadly when I try to autowire the EurekaClient in any @Component or @Service class to fetch registry instance details, I’m told that I can’t autowire as there are 2 bean definitions:

enter image description here

I don’t know what is causing this. I have the following dependencies in my pom.

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
    <exclusions>
        <exclusion>
            <groupId>javax.ws.rs</groupId>
            <artifactId>jsr311-api</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jersey</artifactId>
</dependency>`

The exclusion in the first dependency is due to conflicts with the second.

My app is a discovery enabled app through the following configuration class:

@Configuration
@EnableDiscoveryClient
public class EurekaDiscoveryConfiguration {
}

I really don’t understand why it thinks there are 2 beans matching that description.

FWIW, strangely enough I can autowire it in classes that are not annotated with @Component or @Service… and they work – i’ve managed to get them returning instance info correctly.

I have a feeling, and i’ve read a bit around it, that using jersey 2.0 for my services interferes with eureka. I might just swap to consul……

Many thanks in advance for any advice.

Java Spring Boot Config Standard

I have an interface hierarchy like this:

public interface Shape {
    //code
}

@Component
public class Circle implements Shape {
    //code
}

@Component
public class Square implements Shape {
    //code
}

I want to know the best way to wire these in using Spring Boot bean convention.

Solution 1:

@Component(value = "Circle")
public class Circle implements Shape {
    //code
}

@Component(value = "Square")
public class Square implements Shape {
    //code
}

@Configuration
public class ShapeConfig {
    @Bean
    Foo circleFoo(@Qualifiers("Circle") Shape shape) {
        return new Foo(shape);
    }

    @Bean
    Foo squareFoo(@Qualifiers("Square") Shape shape) {
        return new Foo(shape);
    }
}

Solution 2:

@Component
public class Circle implements Shape {
    //code
}

@Component
public class Square implements Shape {
    //code
}

@Configuration
public class ShapeConfig {
    @Bean
    Foo circleFoo(Circle shape) {
        return new Foo(shape);
    }

    @Bean
    Foo squareFoo(Square shape) {
        return new Foo(shape);
    }
}

What’s the best java/spring practice in this case? I find the value and @Qualifier stuff to be a bit verbose but I’m wondering if wiring in concrete implementations is frowned upon