I am trying to access to a method named sendHttpPost(final AsyncReponseHttpSending delegate, final String urlString, final Object data), which is in another class, and this class has a private constructor. However when I get the method like HttpSending postMethod = HttpSending.sendHttpPost() and I start to pass the same parameters than in the original class I get the error "delegate is always null" , "data is always null", delegate is an instance of the AsyncResponseHttpSending interface which have only one method void onHttpResult(int httpCode, String httpMessage, String body);what am I doing wrong?
Class from where I get the method
public class HttpSending {
private static final String TAG = "HttpSending: ";
private static final int TIMEOUT_CONNECTION = (int) (30 * UnitsConstants.SECOND_TO_MILISECOND);
private static final int TIMEOUT_READ = (int) (60 * UnitsConstants.SECOND_TO_MILISECOND);
private HttpSending() {
}
public static void sendHttpPost(final AsyncReponseHttpSending delegate, final String urlString, final Object data) {
new Thread(TAG) {
#Override
public void run() {
//BUNCH OF CODE
}
}.start();
}
Class where I do my request
public class HttpPost {
AsyncReponseHttpSending delegate = new AsyncReponseHttpSending() {
#Override
public void onHttpResult(int httpCode, String httpMessage, String body) {
}
};
final String url = "https://postman-echo.com/post";
final Object data = null;
HttpSending postMethod = HttpSending.sendHttpPost(delegate,url,data );
}
This line:
HttpSending postMethod = HttpSending.sendHttpPost(delegate,url,data );
should not compile because HttpSending.sendHttpPost is a void method.
Because you never instantiate delegate that's why you get the warnings for its null.
Related
So I have 4 classes
PrefUtil - Shared Preference to set and get data
public class PrefUtil {
private static final String TAG = "PrefUtil";
private SharedPreferences mSettings;
PrefUtil(SharedPreferences prefs) {
this.mSettings = prefs;
}
public String get_string(String key) {
try {
String value = this.mSettings.getString(key, null);
Log.d(TAG, String.format("get_string: %s='%s'", new Object[]{key, value}));
return value;
} catch (ClassCastException e) {
Log.d(TAG, String.format("get_string %s class cast exception", new Object[]{key}));
return "";
}
}
public void set_string(String key, String value) {
Editor editor = this.mSettings.edit();
editor.putString(key, value);
Log.d(TAG, String.format("set_string: %s='%s'", new Object[]{key, value}));
editor.apply();
}
}
OpenVPNService - uses PrefUtil to set data
private PrefUtil prefs;
prefs.set_string("payload", pl);
prefs.set_string("proxyhost", pr);
prefs.set_string("proxyport", String.valueOf(pport));
HTTPSupport - to get or fetch data
public class HTTPSupport
{
private Socket incoming;
private String netDataString;
private String[] bugHostRotate;
private String[] bugHostRotate2;
private String[] bugHostRotate3;
private int countRotate = 0;
private int countRotate2 = 0;
private int countRotate3 = 0;
private Random mRandom = new Random();
private int k = 0;
private int h = 0;
private int i = 0;
private Context mContext;
private Socket mSocket;
private PrinceUtil util;
public HTTPSupport(Socket in){
incoming = in;
}
public HTTPSupport(Context c){
mContext = c;
}
public Socket socket() {
Toast.makeText(mContext, util.getPayload(), Toast.LENGTH_LONG).show();
String trim;
Socket socket = null;
String remote = util.getProxyHost() + ":" + util.getProxyPort();
}
}
PrinceUtil - class to get data
public class PrinceUtil {
private PrefUtil prefs;
public String getPayload() {
return prefs.get_string("payload");
}
public String getProxyHost() {
return prefs.get_string("proxyhost");
}
public String getProxyPort() {
return prefs.get_string("proxyport");
}
}
The problem is that set string works it returns data when I debug it or toast it to MainActivity but in HTTPSupport when I call util.getProxyHost() it is null it doesn't return data. What I am doing wrong?
In the PrinceUtil class, the prefs field is never assigned. In Java, the default value of a reference type field is null, so attempts to call any methods on prefs will throw a NullPointerException. You can correct this by adding a constructor that allows an instance of PrefUtil to be supplied when creating an instance of PrinceUtil:
public PrinceUtil(PrefUtil prefs) {
this.prefs = prefs;
}
Note that this is similar to how PrefUtil has a constructor that accepts a SharedPreferences instance.
You'll also need to do the same for the util field in HTTPSupport. The current code includes two constructors in that class, one that sets incoming, and one that sets mContext. This means that in any instance of HTTPSupport, one of these fields will be unset, and util will always be unset. I would recommend combining these into one constructor that takes all three values:
public HTTPSupport(Socket incoming, Context mContext, PrinceUtil util){
this.incoming = incoming;
this.mContext = mContext;
this.util = util;
}
There are other unset fields in the source code provided, but they're also not used in any of the methods. I'm assuming that the code is incomplete, but these also need to be initialized before use.
I am writing an integration test for elasticsearch 5.3.
public class ProtectedWordsIndexTests extends ESIntegTestCase {
private final WordDelimiterActionListener wordsListener =
WordDelimiterActionListener.getInstance();
private final static String INDEX_NAME = "protected_words";
private final static String TYPE_NAME = "word";
private final static String FILTER_NAME = "my_word_delimiter";
#Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return Collections.singleton(WordDelimiterPlugin.class);
}
#Override
protected Settings nodeSettings(int nodeOrdinal) {
return builder()
.put("plugin.types", TYPE_NAME)
.put("plugin.dynamic_word_delimiter.refresh_interval", "500ms")
.put(super.nodeSettings(nodeOrdinal))
.build();
}
public void testAddWordToIndex() throws Exception {
Settings indexSettings = builder()
.put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT)
.put("index.analysis.filter.my_word_delimiter.type", "dynamic_word_delimiter")
.build();
TokenFilterFactory filterFactory = filterFactory(indexSettings, FILTER_NAME);
createIndex(INDEX_NAME);
ensureGreen();
client().prepareIndex(INDEX_NAME, TYPE_NAME, "1")
.setSource("word", "1tb")
.execute();
Thread.sleep(TimeValue.timeValueSeconds(1).getMillis());
Set<String> protectedWords = wordsListener.getProtectedWords();
assertTrue(protectedWords.size() == 1);
}
}
When I am running testAddWordToIndex() I am getting the following error:
"java.lang.IllegalArgumentException: unknown setting
[plugin.dynamic_word_delimiter.refresh_interval] please check that any
required plugins are installed, or check the breaking changes
documentation for removed settings"
If I remove the following part and increase the refresh interval to be more than the default, the test passes. So I just can't override this.
.put("plugin.dynamic_word_delimiter.refresh_interval", "500ms")
The default refresh interval is declared here:
public class WordDelimiterRunnable extends AbstractRunnable {
public static final TimeValue REFRESH_INTERVAL = TimeValue.timeValueSeconds(20);
public static final String INDEX_NAME = "protected_words";
public static final String INDEX_TYPE = "word";
public static final int RESULTS_SIZE = 10000;
private volatile boolean running;
private final Client client;
private final String index;
private final long interval;
private final String type;
public WordDelimiterRunnable(Client client, Settings settings) {
this.client = client;
this.index = settings.get("plugin.dynamic_word_delimiter.protected_words_index", INDEX_NAME);
this.type = settings.get("plugin.dynamic_word_delimiter.protected_words_type", INDEX_TYPE);
this.interval = settings.getAsTime("plugin.dynamic_word_delimiter.refresh_interval", REFRESH_INTERVAL).getMillis();
}
// more code here
}
You need to register the setting using the SettingsModule#registerSettings(Setting) method as explain here:
https://www.elastic.co/guide/en/elasticsearch/reference/5.x/breaking_50_settings_changes.html#breaking_50_settings_changes
I can generate a list of strings used to select an item using AutoCompleteTextField but it puts the entire string in the edit control. I would like it to just insert the 'name' string.
Should I create a Model that contains the name string and the rendered string?
Which functions should I override to get the required string, to get a value or to handle the click?
private Model<String> groupToJoinModel = new Model<String>();
final AutoCompleteTextField<String> field = new AutoCompleteTextField<String>("ac", new Model<String>(""))
{
private static final long serialVersionUID = 1L;
#Override
protected Iterator<String> getChoices(String input)
{
List<String> choices = new ArrayList<String>(5);
// from a database: generate lookup items
// by concatenating strings: name, type, description
// code omitted
return choices.iterator();
}
};
form.add(field);
groupToJoinModel = (Model<String>) field.getDefaultModel();
// Create a button to perform an action
Button joinGroupsButton = new Button("joinGroupButton")
{
private static final long serialVersionUID = -4974389888115885756L;
#Override
public void onSubmit()
{
if (groupToJoinModel.getObject() != null)
{
// An action is performed on the contents of the edit control
}
}
};
form.add(joinGroupsButton);
You can use AbstarctAutoCompleteRenderer.
AbstractAutoCompleteRenderer<String> autoCompleteRenderer = new AbstractAutoCompleteRenderer<String>() {
private static final long serialVersionUID = 1L;
protected final String getTextValue(final String bean) {
String name;
// Do you logic to extract the name from the bean
...
...
...
return name;
}
#Override
protected final void renderChoice(final String object, final Response response, final String criteria) {
response.write(getTextValue(object));
}
};
final AutoCompleteTextField<String> autoComp = new AutoCompleteTextField<String>("item", new PropertyModel(str, "item"),
autoCompleteRenderer) {
private static final long serialVersionUID = 1L;
#Override
protected Iterator<String> getChoices(String arg0) {
// Your logic
...
...
...
return filteredList.iterator();
}
};
The renderer is passed in the Auto complete constructor.
I am trying to Authorize a LinkedIn app to post status from my Android App to linkedin. But nothing comesup in my webview when I click for authorisation.
Here is my OwnAuthLinkPage.java:
public class OwnOuthLinkPage extends Activity implements SoapClient {
/** Called when the activity is first created. */
Button b;
WebView wb;
String ftoken,verifire,outh_token,verifire2,requesttokensecret,urlM,OuthT;
CookieManager cookieManager ;
public static SharedPreferences prefs;
public static Editor e;
private static final String API_KEY = "API_KEY_HERE";
//This is the private api key of our application
private static final String SECRET_KEY = "SECRET_KEY_HERE";
//This is any string we want to use. This will be used for avoid CSRF attacks. You can generate one here: http://strongpasswordgenerator.com/
private static final String STATE = "STATE_HERE";
//This is the url that LinkedIn Auth process will redirect to. We can put whatever we want that starts with http:// or https:// .
//We use a made up url that we will intercept when redirecting. Avoid Uppercases.
private static final String REDIRECT_URI = "http://smartprotech.com/1Push/WebService1.asmx";
/*********************************************/
//These are constants used for build the urls
private static final String AUTHORIZATION_URL = "https://www.linkedin.com/uas/oauth2/authorization";
private static final String ACCESS_TOKEN_URL = "https://www.linkedin.com/uas/oauth2/accessToken";
private static final String SECRET_KEY_PARAM = "client_secret";
private static final String RESPONSE_TYPE_PARAM = "response_type";
private static final String GRANT_TYPE_PARAM = "grant_type";
private static final String GRANT_TYPE = "authorization_code";
private static final String RESPONSE_TYPE_VALUE ="code";
private static final String CLIENT_ID_PARAM = "client_id";
private static final String STATE_PARAM = "state";
private static final String REDIRECT_URI_PARAM = "redirect_uri";
/*---------------------------------------*/
private static final String QUESTION_MARK = "?";
private static final String AMPERSAND = "&";
private static final String EQUALS = "=";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.linkdin);
getWindow().setFeatureInt( Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
wb= (WebView)findViewById(R.id.webv);
final Activity OwnOuthLinkPage = this;
cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
String authUrl = getAuthorizationUrl();
wb.loadUrl(authUrl);
wb.setWebViewClient(new HelloWebViewClient());
wb.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
//Make the bar disappear after URL is loaded, and changes string to Loading...
OwnOuthLinkPage.setTitle("Loading...");
OwnOuthLinkPage.setProgress(progress * 100); //Make the bar disappear after URL is loaded
// Return the app name after finish loading
if(progress == 100)
OwnOuthLinkPage.setTitle(R.string.app_name);
}
});
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.equalsIgnoreCase("http://smartprotech.com/1Push/WebService1.asmx"))
{
finish();
}
view.loadUrl(url);
try{
StringTokenizer t = new StringTokenizer(url,"=");
String s1 = t.nextToken();
String tokenHint = t.nextToken();//token
verifire = t.nextToken();//verifire
StringTokenizer t2 = new StringTokenizer(tokenHint,"&");
ftoken = t2.nextToken();
ftoken = ftoken.replace("oauth_token=","");
if(!verifire.equalsIgnoreCase("uas-continue")){
StringTokenizer cookies = new StringTokenizer(cookieManager.getCookie("http://smartprotech.com/1Push/Default.aspx"),";");
/* outh_token = cookies.nextToken();
verifire2 = cookies.nextToken();*/
requesttokensecret = cookies.nextToken();
requesttokensecret = cookies.nextToken();
requesttokensecret = requesttokensecret.replace(" TOKENSECREAT=", "");
// System.out.println("*secret**"+reqToken.replace(" requesttoken=", ""));
getToken();
}
}
catch(Exception e){}
return true;
}
}
/************************************************
* making SOAP request for getting nearby values.
************************************************/
public void getToken() {
SoapObject request = new SoapObject("http://tempuri.org/",
"getAccessTS");
request.addProperty("oauth_token", ftoken );
request.addProperty("oauth_Tokensecret",requesttokensecret );
request.addProperty("oauth_verifier",verifire);
SoapConnection connection = new SoapConnection((SoapClient) this, url,
"http://tempuri.org/getAccessTS");
connection.requestWith(request);
}
private static String getAccessTokenUrl(String authorizationToken){
return ACCESS_TOKEN_URL
+QUESTION_MARK
+GRANT_TYPE_PARAM+EQUALS+GRANT_TYPE
+AMPERSAND
+RESPONSE_TYPE_VALUE+EQUALS+authorizationToken
+AMPERSAND
+CLIENT_ID_PARAM+EQUALS+API_KEY
+AMPERSAND
+REDIRECT_URI_PARAM+EQUALS+REDIRECT_URI
+AMPERSAND
+SECRET_KEY_PARAM+EQUALS+SECRET_KEY;
}
/**
* Method that generates the url for get the authorization token from the Service
* #return Url
*/
private static String getAuthorizationUrl(){
return AUTHORIZATION_URL
+QUESTION_MARK+RESPONSE_TYPE_PARAM+EQUALS+RESPONSE_TYPE_VALUE
+AMPERSAND+CLIENT_ID_PARAM+EQUALS+API_KEY
+AMPERSAND+STATE_PARAM+EQUALS+STATE
+AMPERSAND+REDIRECT_URI_PARAM+EQUALS+REDIRECT_URI;
}
#Override
public void success(Object result) {
//SoapObject sobj = (SoapObject) result;
String accessToken,accessSecret;
StringTokenizer t2 = new StringTokenizer(result.toString(),";;");
accessToken = t2.nextToken();
accessSecret = t2.nextToken();
OwnOuthLinkPage.e = prefs.edit();
e.putString("Token", accessToken.replace("AccessToken=", ""));
e.putString("TokenSecret", accessSecret.replace("AccessTokenSecret =", ""));
e.putString("Verifire", verifire);
e.commit();
/* Intent i = new Intent(getApplicationContext(),Main.class);
startActivity(i);*/
finish();
}
#Override
public void error(Object error) {
System.out.println("*******Fail******" + error);
}
}
I am unable to solve. Please help.!
I want do declare a Subclass of an HTMLPanel.
In its constructor I want to give it a few paramters to construct the containing html.
Because I have to call the super-constructor as first statement, I have to change the html later in the constructor.
How can I do this?
public class MyHTMLPanel extends HTMLPanel
{
public MyHTMLPanel(String id, int anotherParameter)
{ super("");
String html=""
// ... some code th construct the html
//??? this.setHtml(html);
}
}
You can find below an example I used and worked well for me.
I don't remember why I don't sub-class HTMLPanel, whether a good reason or not.
You will notice a mechanism to randomize the html ids in case you include several objects of the same type in a single page.
public abstract class HtmlPanelBase extends Composite
{
private String _dynPostfix = "";
protected final String id(final String staticId) { return staticId + _dynPostfix; }
private final String wrapId(final String id) { return "id=\"" + id + "\""; }
private final String wrapDynId(final String refId) { return wrapId(id(refId)); }
private String _htmlAsText = null;
public String getHtmlAsText() { return _htmlAsText; }
abstract protected String htmlPanelBundleHtmlText();
abstract protected List<String> idList();
protected HTMLPanel _holder = null;
private HTMLPanel createHtmlPanel(final boolean defineGloballyUniqueIds)
{
// Referent HTML panel text containing the reference id's.
_htmlAsText = htmlPanelBundleHtmlText();
if (defineGloballyUniqueIds)
{
// List of id's in the HTML Panel reference page to replace with dynamic/unique id's.
final List<String> refIdList = idList();
// Replace the reference id's with dynamic/unique id's.
for (String refId : refIdList)
_htmlAsText = _htmlAsText.replace(wrapId(refId), wrapDynId(refId));
}
// Return the HTMLPanel containing the globally unique id's.
return new HTMLPanel(_htmlAsText);
}
public HtmlPanelBase(final boolean defineGloballyUniqueIds)
{
setup(defineGloballyUniqueIds);
initWidget(_holder);
}
private void setup(final boolean defineGloballyUniqueIds)
{
if (defineGloballyUniqueIds)
_dynPostfix = "_" + UUID.uuid().replace("-", "_");
_holder = createHtmlPanel(defineGloballyUniqueIds);
}
}
And now how you could sub-class from the above base:
public class HtmlPanelTemplate extends HtmlPanelBase
{
private final static boolean _defineGloballyUniqueIds = false;
private final static int _numIdCapacity = 40;
public HtmlPanelTemplate()
{
super(_defineGloballyUniqueIds);
setup();
}
#Override
protected String htmlPanelBundleHtmlText()
{
return YourClientBundle.INSTANCE.getYourFileHtml().getText();
}
#Override
protected List<String> idList()
{
final List<String> idList = new ArrayList<String>(_numIdCapacity);
return idList;
}
private void setup()
{
}
}
You don't need to subclass HTMLPanel. You can create a simple Composite widget:
public class myPanel extends Composite {
private HTMLPanel panel = new HTMLPanel();
public myPanel(String id, int anotherParameter) {
// set HTML to panel based on your parameters
initWidget(panel);
}
}
htmlPanel.getElement().setInnerHTML(...)
Don't know whether this works in derived class' constructor. But setting up a class for specific content text isn't really a good solution.