calculating string width java 1.4 - java

I have java 1.4 application that is running on server.
I need to calculate the width of strings before I create pdf files that include them.
When running the app locally (on my pc) it is o.k. , but when I run it on a server I get an error :
Exception in thread "main" java.lang.InternalError: Can't connect to X11 window server using ':0.0' as the value of the DISPLAY
variable.
at sun.awt.X11GraphicsEnvironment.initDisplay(Native Method)
at sun.awt.X11GraphicsEnvironment.<clinit>(X11GraphicsEnvironment.java:77)
at java.lang.Class.forName1(Native Method)
at java.lang.Class.forName(Class.java:142)
at java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(GraphicsEnvironment.java:72)
at java.awt.Font.initializeFont(Font.java:285)
at java.awt.Font.<init>(Font.java:319)
the code that create the problem calculate the width of a string as follows :
protected static String mCutStr(String iText , int iWidthPt , int iEstimatedNumOfChars)
{
iWidthPt = iWidthPt-4; //remove padding
AffineTransform affinetransform = new AffineTransform();
FontRenderContext frc = new FontRenderContext(affinetransform,true,true);
Font font = new Font("Times", Font.PLAIN, 9);
int textwidth = (int)(font.getStringBounds(iText, frc).getWidth());
// System.out.println("iText="+iText+"; textwidth = "+textwidth+" iWidthPt ="+iWidthPt);
if(textwidth <= iWidthPt)
return iText;
String vTestStr = iText.substring(0 , iEstimatedNumOfChars)+">>";
textwidth = (int)(font.getStringBounds(vTestStr, frc).getWidth());
while(textwidth < iWidthPt)
{
iEstimatedNumOfChars++;
vTestStr = iText.substring(0 , iEstimatedNumOfChars)+">>";
textwidth = (int)(font.getStringBounds(vTestStr, frc).getWidth());
// System.out.println("vTestStr="+vTestStr+" textwidth = "+textwidth);
}
vTestStr = iText.substring(0 , iEstimatedNumOfChars-1)+">>";
return vTestStr;
}
Is there an other way to calc this without using AWT?
(it must support minimum java 5)

You need to run your server in headless mode. Headless mode is useful when actual Window system like X server is not available and you need to perform some AWT related functions.
Java Documentation about Headless mode
If you are using web server like tomcat search how to execute that specific server in headless mode
OR
set system environment property java.awt.headless to true

Related

Selenium Headless Chrome Positions differ

I'm trying to get the positions of Web Elements in headless chrome mode. The Problem is, the y-positions of the Elements are always Different to the y-positions in non headless mode like +36 px on one Screen and +45 on another.
Can I setup Chrome headless so the Positions are the same like in non headless Mode?
Here are my Chrome Options:
options.addArguments("headless"); // mode
options.addArguments("disable-gpu");
options.setExperimentalOption("useAutomationExtension", false);
options.addArguments("disable-infobars"); // disabling infobars
Window size is set to Screen Resolution:
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int width = (int)screenSize.getWidth();
int height = (int)screenSize.getHeight();
System.out.println("Width: " + width + " height: " + height);
driver.manage().window().setSize(new org.openqa.selenium.Dimension(width,height));

Issue with Scrolling in Android Native app using Appium

For my Native Android App , I have been trying for the past 2 weeks to get appium to scroll down on my native app. I have tried driver.scrollTo("Accounts");
Then I got this error
[org.openqa.selenium.WebDriverException: CATCH_ALL: io.selendroid.server.common.exceptions.SelendroidException: method (by) not found: -android uiautomator
and many other examples that I have found. Nothing seems to work . This is the latest example that I have tried .
Using appium 1.5.2 and appium java client version: ‘3.3.0'. When I try to run the following code.
TouchAction tAction=new TouchAction(driver);
int startx = driver.findElement(By.id("line_chart_line_chart")).getLocation().getX();
int starty = driver.findElement(By.id("line_chart_line_chart")).getLocation().getY();
int endx = driver.findElement(By.id("actionBarLogo")).getLocation().getX();
int endy = driver.findElement(By.id("actionBarLogo")).getLocation().getY();
System.out.println(startx + " ::::::: " + starty + " ::::::: " + endx + " ::::::: " + endy);
// This is what the console printed out startX=560 ::::::: starty=1420 ::::::: endx=560 ::::::: endy=240
//First tap on the screen and swipe up using moveTo function
tAction.press(startx,starty).moveTo(endx,endy).release().perform();
Then I get this error message
org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command. Original error: Could not proxy. Proxy
error: Could not proxy command to remote server. Original error: 404 - undefined (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 27 milliseconds
I am at a loss on what to do. In order to click on an element it has to be visible on the screen . In order for this element to appear on the screen I need to scroll down to it.
Is there something that I am doing wrong??? I just can't seem to figure it out.
You used Selendroid mode, which does not support UiAutomator By method.
You can change your appium running mode to UiAutomator by setting desired capability automationName to Appium
This function does the trick for me, put in "Accounts" for elementName when calling it in your case.
public static void scrollToElementAndroid(AndroidDriver driver, String elementName, boolean scrollDown) {
String listID = ((RemoteWebElement) driver.findElementByAndroidUIAutomator("new UiSelector().className(android.widget.ListView)")).getId();
String direction;
if (scrollDown) {
direction = "down";
} else {
direction = "up";
}
HashMap<String, String> scrollObject = new HashMap<String, String>();
scrollObject.put("direction", direction);
scrollObject.put("element", listID);
scrollObject.put("text", elementName);
driver.executeScript("mobile: scrollTo", scrollObject);
}
Use code like below:
Dimension size = driver.manage().window().getSize();
int x = size.width / 2;
int endy = (int) (size.height * 0.75);
int starty = (int) (size.height * 0.20);
driver.swipe(x, starty, x, endy, 1000);

Change image object on template using Brother print Android SDK

I have set up label printing from our app using the b-PAC Android SDK (Java). Using the code below I can replace the text from my template with what I want.
// Start creating P-touch Template command print data
Boolean val= myPrinter.startPTTPrint(6, null);
Log.i("print", "startPTTPrint "+val);
// Replace text
myPrinter.replaceText("abcde");
// Trasmit P-touch Template command print data
PrinterStatus status=myPrinter.flushPTTPrint();
I am now trying to replace an image object within the template. I know it can be done in VBScript using:
bpac.Object ob = doc.GetObject("Photo");
ob.SetData(0, #"C:\Photo\635466380534236711.png", 4);
I can't find any Java examples of this within the b-PAC 3.1 SDK help guide and I have only just began coding in Java so I am very much a novice.
Does anyone have experience with the Brother SDK/Java who can point me in the right direction?
Thanks!
I got this working
Basically I have a template that I copy to an new file on which I make the changes
The image object in the template is called imgPart, the other objects are textblocks
Dim m_partNum As String = "12345"
Dim m_PartName As String = "Plate Special 1 x 2" & vbCrLf & "4 Studs"
Dim m_PartImage As String = "c:\Danny\myLego\Labels\PartImages\3033.png"
Dim m_template As String = "c:\Danny\myLego\Templates\PRINTME.lbx"
Dim m_target As String = "c:\Danny\myLego\Templates\" & m_partNum & ".lbx"
Dim doc As bpac.DocumentClass = New bpac.DocumentClass
Try
File.Copy(m_template, m_target, vbTrue)
If doc.Open(m_target) <> False Then
doc.GetObject("imgPart").SetData(0, m_PartImage, 4)
doc.GetObject("txtPartName").Text = m_PartName
doc.GetObject("txtPartNum").Text = m_partNum
doc.Save()
doc.Close()
Else
MsgBox("Open Error on Receipt with error")
End If
Catch ex As Exception
MsgBox("Error occurred : " & ex.ToString)
End Try

Appium MobileElement.tap(); not working on iosSimulator 8.2 for mobile web

I'm using Java to automate tests for mobile web on ios safari
Everything seems to be set up correctly but appium is crashing with the error:
uncaughtException: Cannot read property 'x' of undefined
the touch command comes through in the logs like so:
info: --> POST /wd/hub/session/1a925d31-d3cd-4231-9698-f7ff4db739fd/touch/perform {"actions":[{"action":"press","options":{"element":"5001"}},{"action":"wait","options":{"ms":1}},{"action":"release","options":{}}]}
info: [debug] Pushing command to appium work queue: "au.getElement('5001').rect()"
info: [debug] Sending command to instruments: au.getElement('5001').rect()
my code looks like this:
public void tap(MobileElement element) {
appiumDriver.context(getContext("NATIVE"));
element.tap(1,1);
appiumDriver.context(getContext("WEBVIEW"));
}
protected String getContext(String partial) {
String result = null;
Set<String> contextNames = driver.getContextHandles();
for (String contextName : contextNames) {
if(contextName.contains(partial)){
result = contextName;
}
}
if (result == null){
throw new NoSuchContextException("Could not find requested context");
}
return result;
}
and I'm feeding it a mobileElement.
I can get the element location by treating it like a WebElement and doing getlocation() and then I can use a TouchAction, which works in terms of what appium is doing, but the location is super off so I'm trying to use the mobileElement tap() action here instead.
Does anyone know a workaround or see what I might be doing wrong? My site has a lot of elements that require a tap().
This also occurs when I define a WebElement, then move into Native context and use iosDriver.tap(1, webelement, 1); with the same crash on the appium side.
Try below:
AppiumDriver appiumDriver = new AppiumDriver();
String originalContext = appiumDriver.getContext();
Point coordinate = element.getLocation();
Dimension loc = element.getSize();
int centerX = loc.getWidth() / 2 + coordinate.getX();
int centerY = loc.getHeight() / 2 + coordinate.getY();
appiumDriver.context("NATIVE_APP");
appiumDriver.tap(1, centerX, centerY, 2);
appiumDriver.context(originalContext);
The Issues is that, in Native context Appium does not have any visibility to webelements on the webPage, You need to get the coordinated and then click using Tap method with coordinates

Android Webview, scale content to fit screen

My friend made an application using javascript, and uploaded it to his website.
Now I'm trying to wrap it into a webview in android, and that's working fine in some ways.
The page is 480x320
But no matter what screensize I select on Android, there is a white space at the bottom on the webview. I have tried a lot of ways to make it zoom, but nothing worked.
My code at this moment is this
final WebView browser = (WebView)findViewById(R.id.webview);
browser.getSettings().setJavaScriptEnabled(true);
browser.loadUrl("http://page.xx");
I needed to scale-to-fit for the width and this variation of FunkTheMonk's answer worked well for me:
#Override
public void onPageFinished(android.webkit.WebView view, String url)
{
super.onPageFinished(view, url);
WindowManager manager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics metrics = new DisplayMetrics();
manager.getDefaultDisplay().getMetrics(metrics);
metrics.widthPixels /= metrics.density;
loadUrl("javascript:var scale = " + metrics.widthPixels + " / document.body.scrollWidth; document.body.style.zoom = scale;");
}
wb.loadUrl("javascript:document.body.style.zoom = "+String.valueOf(scale)+";");
Where scale is a float, which you could calculate - I think in your case you want something like the following: browser.getHeight() / 480dp.
Load this Url after your webpage has finished loading.
Can you try to add :
browser.getSettings().setBuiltInZoomControls(true);
browser.setInitialScale(1);
browser.setPadding(0, 0, 0, 0);
And see if it's working ?

Categories

Resources