HTTPS page not loaded on BrowserContent - blackberry

I am implementing an embedded browser in my app, and because it has to be compatible with OS 4.0, BrowserContent is my only choice.
When opening a HTTPS page the screen is blank, but this problem doesn't occur when a BrowserSession is used. So I put a println after the BrowserContent part, and it doesn't show up in the console output. So I think this is something wrong with that.
class BrowserScreen extends MainScreen {
private RenderingSession _renderingSession;
private HttpsConnection _connection;
public BrowserScreen(String url) {
_renderingSession = RenderingSession.getNewInstance();
final String _url = url;
new Thread() {
public void run() {
try {
_connection =
(HttpsConnection)Connector.open(_url, Connector.READ, true);
BrowserContent content =
_renderingSession.getBrowserContent(_connection, null, 0);
content.finishLoading();
Field field = content.getDisplayableContent();
synchronized (UiApplication.getEventLock()) {
add(field);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}

There is a bug in the sample, and the BB people have done nothing in this regards for years.. You will never know that your page is not rendered and you will be redirected to the calling page all by itself. When they are unable to render the page they insert a redirection code in the HTTP response instead of giving a render exception (check it out in the inputstream and convert it into string and you shall know), and the intended page is never shown. They have resolved this in 5.0 and higher using BrowserField, but we need solution for the low end mobiles.

Related

xamarin.android webview evaluatejavascript It does not return any value at all

I have a fundamental problem that I can not really understand where the problem comes from.
I am designing a project by xamarin.android webview.
Now I need to run a Java function in Web View and check the return value in a if function.
I searched all the websites and in all of them I got the following code:
In Main Activity Class:
public class MainActivity : AppCompatActivity
{
WebView web_view;
.
.
.
Define web_view public in class
In OnCreate :
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.activity_main);
web_view = FindViewById<WebView>(Resource.Id.webview);
web_view.Settings.JavaScriptEnabled = true;
web_view.Settings.BuiltInZoomControls = true;
web_view.Settings.AllowContentAccess = true;
web_view.SetWebViewClient(new HelloWebViewClient());
web_view.LoadUrl("https://www.example.com");
}
In Back Key Press:
public override bool OnKeyDown(Android.Views.Keycode keyCode, Android.Views.KeyEvent e)
{
if (keyCode == Keycode.Back)
{
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat)
{
JavascriptResult jsr = new JavascriptResult();
string strjs = "closePackageDetails();";
web_view.EvaluateJavascript(strjs, jsr);
string rrr = jsr.strResult;
Toast.MakeText(this, "message send:" + rrr, ToastLength.Long).Show();
}
else
{
Toast.MakeText(this, "android version less 4.4" , ToastLength.Long).Show();
}
}
}
On JavascriptResult Class (separate on C# Class Palaced in MainActivity in Root directory)
namespace webviewapp
{
class JavascriptResult : Java.Lang.Object, IValueCallback
{
public string strResult;
public void OnReceiveValue(Java.Lang.Object result)
{
Toast.MakeText(Android.App.Application.Context, "رسیدن نتیجه احضار شد", ToastLength.Long);
strResult = ((Java.Lang.String)result).ToString();
}
}
}
<>
Everything looks right and the program is debugged without error and the APK file is created successfully.
After installing the program on the mobile phone and running it, the web page is loaded and everything looks good.
By touching the back button, the JavaScript function is executed correctly and the result is visible in Web View. But the result, which is a boolean value, is not returned.
In fact, the OnReceiveValue procedure does not work.
The variable 'rrr' always displays an null value.
Where it went wrong really puzzled me?
It is happening because the callback is executed later than the next line ,so the variable 'rrr' is always null.
Add the breakpoint at OnReceiveValue and the line string rrr = jsr.strResult; to check it .
Just do the next thing directly in the method OnReceiveValue in the callback class.

Disable automatic image loading in Webview/

I am developing a web scraper using JavaFX webview. For the scraping purpose, I don't need to have the images to be loaded. When the page is being loaded, Webkit spawns lots of UrlLoader thread. So I think it's better to have the images disabled, so I will save lots of system resources. Does anyone know how to disable automatic image loading in Webview?
Solution Approach
Define your own protocol handler for http and filter out anything with an image mime type or content.
URL.setURLStreamHandlerFactory(new HandlerFactory());
Sample Code
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.web.*;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.*;
public class LynxView extends Application {
private static final String BLANK_IMAGE_LOC =
"https://upload.wikimedia.org/wikipedia/commons/c/ce/Transparent.gif";
public static final String WEBSITE_LOC =
"http://fxexperience.com";
public static final String IMAGE_MIME_TYPE_PREFIX =
"image/";
#Override
public void start(Stage stage) throws Exception {
WebView webView = new WebView();
WebEngine engine = webView.getEngine();
engine.load(WEBSITE_LOC);
stage.setScene(new Scene(new StackPane(webView)));
stage.show();
}
public static void main(String[] args) throws IOException {
URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() {
#Override
public URLStreamHandler createURLStreamHandler(String protocol) {
if ("http".equals(protocol)) {
return new sun.net.www.protocol.http.Handler() {
#Override
protected URLConnection openConnection(URL url, Proxy proxy) throws IOException {
String[] fileParts = url.getFile().split("\\?");
String contentType = URLConnection.guessContentTypeFromName(fileParts[0]);
// this small hack is required because, weirdly, svg is not picked up by guessContentTypeFromName
// because, for Java 8, svg is not in $JAVA_HOME/lib/content-types.properties
if (fileParts[0].endsWith(".svg")) {
contentType = "image/svg";
}
System.out.println(url.getFile() + " : " + contentType);
if ((contentType != null && contentType.startsWith(IMAGE_MIME_TYPE_PREFIX))) {
return new URL(BLANK_IMAGE_LOC).openConnection();
} else {
return super.openConnection(url, proxy);
}
}
};
}
return null;
}
});
Application.launch();
}
}
Sample Notes
The sample uses concepts from:
Getting A File's Mime Type In Java
The sample only probes the filename to determine the content type and not the input stream attached to the url. Though probing the input stream would be a more accurate way to determine if the resource the url is connected to is actually an image or not, it is slightly less efficient to probe the stream, so the solution presented trades accuracy for efficiency.
The provided solution only demonstrates locations served by a http protocol, and not locations served by a https protocol.
The provided solution uses a sun.net.www.protocol.http.Handler class which may not be publicly visible in Java 9, (so the solution might not work for Java 9).
The urlStreamHandlerFactory is a global setting for the JVM, so once it is set, it will stay that way (e.g. all images for any java.net.URL connections will be ignored).
The sample solution returns a blank (transparent) image, which it loads over the net. For efficiency, the image could be loaded as a resource from the classpath instead of over the net.
You could return a null connection rather a than a connection to a blank image, if you do so, the web view code will start reporting null pointer exceptions to the console because it is not getting the url connection it expects, and will replace all images with an x image to show that the image is missing (I wouldn't really recommend an approach which returned a null connection).
public URLStreamHandler createURLStreamHandler(String protocol) {
if ("http".equals(protocol)) {
return new URLFortuneHandler();
}
else return null;
}
}
public class URLFortuneHandler extends sun.net.www.protocol.http.Handler {
protected URLConnection openConnection(URL url) throws IOException {
String file = url.getFile();
int mid= file.lastIndexOf(".");
String ext = file.substring(mid+1,file.length());
if ("jpg".equals(ext) || "png".equals(ext))
return somethinghere;
else
return super.openConnection(url);
}
}

LWUIT ConnectionRequest: Bad Request on Blackberry

My lwuit application is working fine on Blackberry Simulator while on device the application installs successfully, starts normally, but where am having issues is on network connection. Trying to access network I get 400 Bad Request message. I don't no what am doing wrong, my network connection code is as below:
public ConnectionRequest prepareConnection(String page, String progressMsg, final int request)
{
final ConnectionRequest conR = new ConnectionRequest()
{
public void readResponse(InputStream input) throws IOException {
StringBuffer sb = new StringBuffer();
int ch;
while((ch=input.read()) != -1)
sb.append((char)ch);
httpResponse(sb.toString().trim(), request);
}
};
conR.setUrl(NetworkHandler.getURL()+page);
conR.setDuplicateSupported(true);
Progress progress = new Progress(progressMsg, conR)
{
public void actionCommand(Command command)
{
if(command.getCommandName().equals("Cancel"))
conR.kill();
}
};
conR.setDisposeOnCompletion(progress);
return conR;
}
private void login(String code)
{
Container container = Display.getInstance().getCurrent();
if(!validateLogin(container))
{
showDialogMessage("Alert", "Please enter your user name and password!");
return;
}
NetworkManager.getInstance().start();
ConnectionRequest conR = prepareConnection(NetworkHandler.LOGIN_PAGE, "Authenticating...", RequestType.LOGIN);
Dialog dialog = conR.getDisposeOnCompletion();
conR.setPost(true);
conR.addArgument("u", getFieldValue(findTxtUserName(container)));
conR.addArgument("p", getFieldValue(findTxtPassword(container)));
conR.addArgument("c", code);
NetworkManager.getInstance().addToQueue(conR);
dialog.show();
}
public void onLoginForm_BtnLoginAction(Component c, ActionEvent event) {
login("");
}
Please I want you guys to help me out.
Thanks in Advance.
The login me
This usually indicates a problem in APN configuration on the device. Normally Blackberry app's workaround incorrect APN configurations automatically which is a pretty difficult thing to do. CodenameOne does that seamlessly but LWUIT does not.

Integration of twitter posting in Blackberry+IllegalArguementException

i am trying to embed twitter posting feature in my application.
i am using twitter api_me-1.8
i am able to reach the login screen(though most of the text is displayed as boxes- i am guessing that the text is in hindi/tamil as i am in india...), but as soon as i enter my credentials,i get taken to another page with some text in the top in boxes...
and more text in english below that(you can revoke access to any application...) ...then i get an illeagalArguementException after a minute...
i tried to debug the application,
public TwitterUiScreen(String wallMsg) {
System.out.println("Twitter UI BEGINS!");
setTitle("Twitter");
this.wallMsg = wallMsg;
BrowserContentManager browserMngr = new BrowserContentManager(0);
RenderingOptions rendOptions = browserMngr.getRenderingSession()
.getRenderingOptions();
rendOptions.setProperty(RenderingOptions.CORE_OPTIONS_GUID,
RenderingOptions.SHOW_IMAGES_IN_HTML, false);
rendOptions.setProperty(RenderingOptions.CORE_OPTIONS_GUID,
RenderingOptions.ENABLE_EMBEDDED_RICH_CONTENT, true);
rendOptions.setProperty(RenderingOptions.CORE_OPTIONS_GUID,
RenderingOptions.DEFAULT_FONT_FACE, true);
rendOptions.setProperty(RenderingOptions.CORE_OPTIONS_GUID,
RenderingOptions.DEFAULT_CHARSET_VALUE, true);
rendOptions.setProperty(RenderingOptions.CORE_OPTIONS_GUID,
RenderingOptions.JAVASCRIPT_ENABLED, true);
/*
* browserMngr.getRenderingSession().getRenderingOptions().setProperty(
* RenderingOptions.CORE_OPTIONS_GUID,
* RenderingOptions.DEFAULT_FONT_FACE, Font.getDefaultFont());
*/
add(browserMngr);
OAuthDialogWrapper pageWrapper = new BrowserContentManagerOAuthDialogWrapper(browserMngr);
pageWrapper.setConsumerKey(CONSUMER_KEY);
pageWrapper.setConsumerSecret(CONSUMER_SECRET);
pageWrapper.setCallbackUrl(CALLBACK_URL);
pageWrapper.setOAuthListener(this);
pageWrapper.login();
}
i had breakpoints upto the last line, and all of them were hit, with no problems...
but as soon as i logged in, i hit the exception.( i think it was in this page:-
BrowserContentManagerOAuthDialogWrapper.java (version 1.1 : 45.3, super bit)
after which i get to a third screen.
the comment was barely legible- so i thought i might as well add the code over here:
public static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-twitter";
public static final String OAUTH_CALLBACK_HOST = "callback";
public static final String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME+ "://" + OAUTH_CALLBACK_HOST;
private final String CALLBACK_URL = OAUTH_CALLBACK_URL;
i managed to get the source and attach it to the jar file. the exception that the BrowserContentManagerOAuthDialogWrapper.java throws is:: Protocol not found: net.rim.device.cldc.io.x-oauthflow-twitter.Protocol
in this method::
protected void loadUrl(final String url, final byte[] postData,
final Event event) {
new Thread() {
public void run() {
try {
HttpConnection conn = getConnection(url);
//
if (postData != null) {
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty(
"Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestProperty(
"Content-Length", String.valueOf(postData.length));
//
OutputStream out = conn.openOutputStream();
out.write(postData);
out.close();
}
//
browserManager.setContent(
conn, renderingListenerOAuth, event);
} catch (IOException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
}.start();
}
feel like hitting myself.
my clients had told us that the twitter posting was not working...
so i assumed that it did not work.
for some reason, it does not work in the simulator- but seems to work fine on the device.
the clients have assumed that it does not work, as after we try logging in, it takes too long to post, and displays the third screen for about 20 seconds, and they seem to have clicked back early, deciding that posting did not work.
now i need to figure out a way to post a message on the third screen asking the user to wait for the post to be successful.

Twitter Follow Link

How do I create a link that will automatically make a user follow a certain Twitter user if they're logged in or send them to Twitter to login first if they're not? I had found how to do this about month or 2 ago but can't find it again. I think it was something basic like a link or a form post to something like twitter.com/[user]/follow.
I've looked at the API, but I'd need the user to authenticate themselves on my site, and I don't want to deal with that. I just want them to authenticate directly on Twitter and not worry about it. The way I had found was nice and simple and I just want to find that again.
Use Twitter's web intents.
While you can use the follow button, you can also send users directly to the Intent URL, like so:
https://twitter.com/intent/user?screen_name=NASA
how to use twitter api in my android application to implement follow button only
Android
http://code.google.com/p/android-hackathon-in-fukuoka/source/browse/trunk/sodefuri/src/jp/jagfukuoka/sodefuri/TimeLineActivity.java?spec=svn167&r=167
Code Snip: (I have converted chines string into standard English)
public class TimeLineActivity extends ListActivity {
private TwitterPreferenceManager tpm = new TwitterPreferenceManager(this);
private static final int FOLLOW = 1;
private static final CharSequence FOLLOW_LABEL = "Follow";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// timeline Obtaining process
String screenName = getIntent().getStringExtra("screen_name");
List<String> list = this.getTimeLine(screenName);
setListAdapter(new ArrayAdapter<String>(this, R.layout.timeline_item,list));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, FOLLOW, 0, FOLLOW_LABEL);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case FOLLOW:
ConfigurationBuilder builder = new ConfigurationBuilder();
Configuration conf = builder.setOAuthAccessToken(tpm.getAccessToken())
.setOAuthAccessTokenSecret(tpm.getAccessTokenSercret())
.setOAuthConsumerKey(TwitterPreferenceManager.CONSUMER_KEY)
.setOAuthConsumerSecret(TwitterPreferenceManager.CONSUMER_SERCRET)
.setDebugEnabled(true)
.build();
Twitter twitter = new TwitterFactory(conf).getInstance();
try {
String screen_name = getIntent().getStringExtra("screen_name");
twitter.createFriendship(screen_name);
Toast.makeText(getApplicationContext(), "Was to follow.", Toast.LENGTH_LONG).show();
} catch (TwitterException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
/**
* Get the time line for the specified user
*
* #param screenName
* #return
*/
private List<String> getTimeLine(String screenName) {
List<String> result = new ArrayList<String>();
Twitter twitter = new TwitterFactory().getInstance();
ResponseList<Status> userTimeline;
try {
userTimeline = twitter.getUserTimeline(screenName);
for (Status status : userTimeline) {
result.add(status.getText());
}
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
iPhone
http://www.chrismaddern.com/twitter-follow-button-for-ios-iphone-code/
Here is the way, How todo
The FollowMeButton can be created in Interface Builder by adding a UIButton and changing it's class to FollowMeButton or in code using the custom initialiser:
[self.view addSubview:[[FollowMeButton alloc] initWithTwitterAccount:#"chrismaddern" atOrigin:CGPointMake(205, 248) isSmallButton:YES]];
Two size modes are available controlled by setting isSmallButton in the initialiser or by later change the isSmall property of the object.

Resources