Categories
discuss

passing base url from command line in protractor

i am trying to test my angularjs app using protractor. my conf.js looks like this

exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',

capabilities: {
    'browserName': 'chrome'
},
specs: ['HomePageCtrl_spec.js'],
chromeOnly: true,
jasmineNodeOpts: {
    onComplete: null,
    isVerbose: false,
    showColors: true,
    includeStackTrace: true
},
onPrepare: function() {
    browser.manage().window().setSize(1600, 1000);
},
params : {
    url : 'test'
}};

and i am runnig this command on command prompt

protractor Conf.js --params.url='https://XXXXX/YYY'

in my spec file, in beforeEach function i am able to get the passed url (console.log((browser.params.url)) is coming correctly), but when i do browser.get(browser.params.url).. it is not working

anyone has idea why this is failing?

Answer

Protractor provides it by default. You just have to declare the correct variable.

exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',

capabilities: {
    'browserName': 'chrome'
},
specs: ['HomePageCtrl_spec.js'],
chromeOnly: true,
jasmineNodeOpts: {
    onComplete: null,
    isVerbose: false,
    showColors: true,
    includeStackTrace: true
},
onPrepare: function() {
    browser.manage().window().setSize(1600, 1000);
},
  baseUrl: 'test'
};

and then, you run the tests:

protractor Conf.js --baseUrl="https://XXXXX/YYY"

To use this url within your tests:

browser.get(browser.baseUrl)
Categories
discuss

Application hangs and suspends all threads while using AsyncTask

I am trying to use the AsyncTask class to get a website’s content. The logcat tells me W/art: Suspending all threads took: 15(or any other number)ms repeatedly. My application is frozen until the log messages are done printing. UI shows up after the log is done. I followed a tutorial and have double checked that my code should be the same as the tutorial. After a while, it logs a few lines of code from the website, but nothing more. I tried with different websites as well. Here is my AsyncTask:

public class MainActivity extends AppCompatActivity {

    public class DownloadTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... urls) {

            String result = "";
            URL url;
            HttpURLConnection urlConnection = null;

            try {

                url = new URL(urls[0]);

                urlConnection = (HttpURLConnection) url.openConnection();

                InputStream in = urlConnection.getInputStream();

                InputStreamReader reader = new InputStreamReader(in);

                int data = reader.read();

                while (data != -1) {

                    char current = (char) data;

                    result += current;

                    data = reader.read();

                }

                return result;

            } catch (Exception e) {

                e.printStackTrace();

            }

            return null;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DownloadTask task = new DownloadTask();
        String result = null;

        try {

            result = task.execute("http://www.vg.no/").get();

            Log.i("URL content" , result);

        } catch (InterruptedException e) {

            e.printStackTrace();

        } catch (ExecutionException e) {

            e.printStackTrace();

        }

    }


}

Answer

The following line is a problem:

result = task.execute("http://www.vg.no/").get();

The .get() part of this statement means “wait until the task completes”. This effectively blocks the UI thread while the task executes.

Just let the background task do its stuff and get any results back via onPostExecute(). Check out the following AsyncTask:

public class MainActivity extends AppCompatActivity {

   public class DownloadTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... urls) {
            ...
        }

        @Override
        protected void onPostExecute(String result) {
            Log.i("URL content" , result);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DownloadTask task = new DownloadTask();
        task.execute("http://www.vg.no/");
    }


}
Categories
discuss

Why is a thread blocking my JavaFX UI Thread?

I am trying to provide feedback in a JavaFX 8 application when a user chooses a menu item that launches a blocking process in another thread. In my real application it’s a file download, but I have created a test case using minimal code by way of example:

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.MenuButton;
import javafx.scene.control.ToolBar;
import javafx.scene.control.MenuItem;
import javafx.stage.Stage;

public class BlockingThreadTestCase extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        MenuItem menuItem = new MenuItem("Start");
        MenuButton menuButton = new MenuButton();
        menuButton.setText("Async Process");
        menuButton.getItems().addAll(menuItem);

        menuItem.setOnAction(event -> {
            menuButton.setText("Running...");

            Platform.runLater(() -> {
                try {
                    // Simulate a blocking process
                    Thread.sleep(5000);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                menuButton.setText(menuButton.getText() + "Done!");
            });
        });

        final ToolBar toolbar = new ToolBar(menuButton);
        final Scene scene = new Scene(toolbar);
        primaryStage.setScene(scene);
        primaryStage.setWidth(150);
        primaryStage.show();
    }
}

Here’s how it’s supposed to work: When you select the “Start” menu item, the main menu text should immediately change to “Running…”, and then it should append “Done!” after the 5-second sleep that simulates my file download.

What is actually happening is both text updates are firing after the blocking process is done, even though I’m using Platform.runLater(). What am I doing wrong?

Answer

The easiest way to do this is by using a Task. Platform.runLater is only needed if you need to update the UI from a different thread and therefore is not necessary in your case. If you would like to track progress of the background task while it is running, you may use updateMessage and updateProgress methods in the task to safely pass messages to the UI thread without worrying about the scheduling via EDT. You may find more information on this here https://docs.oracle.com/javase/8/javafx/interoperability-tutorial/concurrency.htm .

See the minimal working example below.

import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.MenuButton;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ToolBar;
import javafx.stage.Stage;


public class BlockingThreadTestCase extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        MenuItem menuItem = new MenuItem("Start");
        MenuButton menuButton = new MenuButton();
        menuButton.setText("Async Process");
        menuButton.getItems().addAll(menuItem);

        menuItem.setOnAction(event -> {
            menuButton.setText("Running...");

            Task task = new Task<Void>() {
                @Override
                public Void call() {
                    //SIMULATE A FILE DOWNLOAD
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return null;
                }
            };
            task.setOnSucceeded(taskFinishEvent -> menuButton.setText(menuButton.getText() + "Done!"));
            new Thread(task).start();
        });

        final ToolBar toolbar = new ToolBar(menuButton);
        final Scene scene = new Scene(toolbar);
        primaryStage.setScene(scene);
        primaryStage.setWidth(150);
        primaryStage.show();
    }
}
Categories
discuss

How do I remove unused resources from third-party libraries I’ve included on Android?

The third-party libraries that I link into my app often include resource files that aren’t being used by my application, and as such, end up bloating my APK.

For example, including the Google Play services library, but not using the login button functionality; all those image and layout resources end up in my final build.

Since these resources are included in a compiled library, how can I remove them from my build?

Answer

This answer is summarized from Removing Unused Resources which explains how to use minifyEnabled and shrinkResources, which are covered in more depth at the Official document page.

It’s a common problem for third-party libraries to include assets that your application codepath does not use, and it’s critically important to remove those assets in order to produce smaller APK files for your users. Thankfully, the latest version of Gradle and Android Studio provides a solution to help.

By setting minifyEnabled and shrinkResources to true in your Gradle configuration, the system will go forth removing unused resources from your application.

android {
    ...

    buildTypes {
        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'),
                         'proguard-rules.pro'
        }
    }
}

It is important to note that removing unused resources requires the minifyEnabled flag to be set. This flag (as mentioned in Removing unused code) will trigger ProGuard to remove code paths that aren’t being used by your application. This is an important step in the removal of resources from included libraries. If the code paths aren’t removed, then the compiler will still believe the resources are referenced by an existing codepath and won’t remove them properly.

It’s worth noting that this is a pretty extensive system. For instance, it will look through specific string constants in your code, as well as various res/raw resources looking for any URLs in the form of file:///…. to keep. It will even go so far as to analyze CSS, HTML, and JavaScript files as well.

Now, there may be instances here of false positives or false negatives. Assets might be getting cut, or kept, when you want the opposite behavior. (To be fair, resource shrinking tends to be overeager…) To adjust this, you can add the tools:keep and tools:discard attributes to define the desired behavior, by convention in a res/raw/keep.xml file.

<resources xmlns:tools="http://schemas.android.com/tools"
     tools:keep= "@layout/l_used*_c,  @layout/l_used_b*"
     tools:discard="@layout/unused2"
/>
Categories
discuss

GSON TypeAdapter: DeSerialize Polymorphic Objects Based on “Type” Field

I’m using Retrofit with the default Gson parser for JSON processing. Oftentimes, I have a series of 4~5 related but slightly different objects, which are all subtypes of a common base (let’s call it “BaseType”). I know we can deserialize the different JSONs to their respective child models by checking the “type” field. The most commonly prescribed way is to extend a JsonDeserializer and register it as a type adapter in the Gson instance:

class BaseTypeDeserializer implements JsonDeserializer<BaseType> {
    private static final String TYPE_FIELD = "type";

    @Override
    public BaseType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if (json.isJsonObject() && json.getAsJsonObject().has(TYPE_FIELD)) {
            JsonObject jsonObject = json.getAsJsonObject();
            final String type = jsonObject.get(TYPE_FIELD).getAsString();
            if ("type_a".equals(type)) {
                return context.deserialize(json, AType.class);
            } else if ("type_b".equals(type)) {
                return context.deserialize(json, BType.class);
            } ...

            // If you need to deserialize as BaseType,
            // deserialize without the current context
            // or you will infinite loop
            return new Gson().fromJson(json, typeOfT);

        } else {
            // Return a blank object on error
            return new BaseType();
        }
    }
}

However, in my experience this is really slow, and seemingly because we have to load up the entire JSON document into a JsonElement and then traverse it to find the type field. I also don’t like it that this deserializer has to be run on every one of our REST calls, even though the data isn’t always necessarily being mapped to a BaseType (or its children).

This foursquare blog post mentioned using TypeAdapters as an alternative but it didn’t really go further with an example.

Anybody here know how to use TypeAdapterFactory to deserialize based on a ‘type’ field without having to read up the entire json stream into a JsonElement object tree?

Answer

  1. The custom deserializer should only be run when you have a BaseType or a sub-classes in the deserialization data, not every request. You register it based on the type, and it is only called when gson need to serialize that type.

  2. Do you deserialize BaseType as well as the sub-classes? If so, this line is going to kill your performance —

    return new Gson().fromJson(json, typeOfT);

creation of new Gson objects is not cheap. You are creating one each time you deserialize a base class object. Moving this call to a constructor of BaseTypeDeserializer and stashing it in a member variable will improve performance (assuming you do deserialize the base class).

  1. The issue with creating a TypeAdapter or TypeAdapterFactory for selecting type based on the field is that you need to know the type before you start consuming the stream. If the type field is part of the object, you cannot know the type at that point. The post you linked to mentions as much —

Deserializers written using TypeAdapters may be less flexible than those written with JsonDeserializers. Imagine you want a type field to determine what an object field deserializes to. With the streaming API, you need to guarantee that type comes down in the response before object.

If you can get the type before the object in the JSON stream, you can do it, otherwise your TypeAdapter implementation is probably going to mirror your current implementation, except that the first thing you do is convert to Json tree yourself so you can find the type field. That is not going to save you much over your current implementation.

  1. If your subclasses are similar and you don’t have any field conflicts between them (fields with the same name but different types), you can use a data transfer object that has all the fields. Use gson to deserialize that, and then use it create your objects.

    public class MyDTO {
       String type;
       // Fields from BaseType
       String fromBase;
       // Fields from TypeA
       String fromA;
       // Fields from TypeB
       // ...
    }
    
    
    public class BaseType {
      String type;
      String fromBase;
    
      public BaseType(MyDTO dto) {
        type = dto.type;
        fromBase = dto.fromBase;
      }
    }
    
    public class TypeA extends BaseType {
      String fromA;
    
      public TypeA(MyDTO dto) {
        super(dto);
        fromA = dto.fromA;
      }
    }
    

you can then create a TypeAdapterFactory that handles the conversion from DTO to your object —

public class BaseTypeAdapterFactory implements TypeAdapterFactory {

  public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {
    if(BaseType.class.isAssignableFrom(type.getRawType())) {
      TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
      return newItemAdapter((TypeAdapter<BaseType>) delegate,
          gson.getAdapter(new TypeToken<MyDTO>(){}));
    } else {
      return null;
    }
  }

  private TypeAdapter newItemAdapter(
      final TypeAdapter<BaseType> delagateAdapter,
      final TypeAdapter<MyDTO> dtoAdapter) {
    return new TypeAdapter<BaseType>() {

      @Override
      public void write(JsonWriter out, BaseType value) throws IOException {
        delagateAdapter.write(out, value);
      }

      @Override
      public BaseType read(JsonReader in) throws IOException {
        MyDTO dto = dtoAdapter.read(in);
        if("base".equals(dto.type)) {
          return new BaseType(dto);
        } else if ("type_a".equals(dto.type)) {
          return new TypeA(dto);
        } else {
          return null;
        }
      }
    };
  }
}

and use like this —

Gson gson = new GsonBuilder()
    .registerTypeAdapterFactory(new BaseTypeAdapterFactory())
    .create();

BaseType base = gson.fromJson(baseString, BaseType.class);
Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..