pdfbox extract word coordinates - coordinates

Hi This question refers to previous post:
Could someone give me an example of how to extract coordinates for a 'word' using PDFBox
I am using PDFBOX 2.0.10
I have successfully compiled the combined code but getting exception error when trying to run an example.
The solution provided does not have a standard main method which is where I am getting confused.
Can someone please advise how I can run the combined code successfully.
package org.apache.pdfbox.examples.text;
import java.io.File;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import org.apache.pdfbox.examples.text.ExtractWordCoordinates;
public class ExtractWordCoordinates2 {
public static void main(String[] args) throws IOException {
ExtractWordCoordinates ewc = new ExtractWordCoordinates();
ewc.testExtractWordsForGoodJuJu();
}
}
Stack Trace
Jul 08, 2018 4:15:41 PM org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB suggestKCMS
INFO: To get higher rendering speed on java 8 oder 9,
Jul 08, 2018 4:15:41 PM org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB suggestKCMS
INFO: use the option -Dsun.java2d.cmm=sun.java2d.cmm.kcms.KcmsServiceProvider
Jul 08, 2018 4:15:41 PM org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB suggestKCMS
INFO: or call System.setProperty("sun.java2d.cmm", "sun.java2d.cmm.kcms.KcmsServiceProvider")
Exception in thread "main" java.lang.NullPointerException
at org.apache.pdfbox.io.ScratchFile.createBuffer(ScratchFile.java:422)
at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:1142)
at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:1041)
at org.apache.pdfbox.examples.text.ExtractWordCoordinates.testExtractWordsForGoodJuJu(ExtractWordCoordinates.java:47)
at org.apache.pdfbox.examples.text.ExtractWordCoordinates2.main(ExtractWordCoordinates2.java:17)
ExtractWordCoordinates can be found here
https://github.com/mkl-public/testarea-pdfbox2/blob/master/src/test/java/mkl/testarea/pdfbox2/extract/ExtractWordCoordinates.java#L69

Problem solved.
The following line in ExtractWordCoordinates was returning a null:
try ( InputStream resource = getClass().getResourceAsStream("apache.pdf")) {
After copying the document (apache.pdf) to the same directory as ExtractWordCoordinates.class the code ran successfully.

Related

I am getting initialization error :java.util.NoSuchElementException while running runner file using Junit

java.util.NoSuchElementException
at java.base/java.util.ArrayList$Itr.next(ArrayList.java:970)
at java.base/java.util.Collections.max(Collections.java:713)
at io.cucumber.core.feature.FeatureParser.parseResource(FeatureParser.java:46)
at java.base/java.util.function.BiFunction.lambda$andThen$0(BiFunction.java:70)
at io.cucumber.core.resource.ResourceScanner.lambda$processResource$1(ResourceScanner.java:79)
at io.cucumber.core.resource.PathScanner$ResourceFileVisitor.visitFile(PathScanner.java:75)
at io.cucumber.core.resource.PathScanner$ResourceFileVisitor.visitFile(PathScanner.java:60)
at java.base/java.nio.file.Files.walkFileTree(Files.java:2810)
at io.cucumber.core.resource.PathScanner.findResourcesForPath(PathScanner.java:53)
at io.cucumber.core.resource.PathScanner.findResourcesForUri(PathScanner.java:31)
at io.cucumber.core.resource.ResourceScanner.findResourcesForUri(ResourceScanner.java:61)
at io.cucumber.core.resource.ResourceScanner.scanForResourcesUri(ResourceScanner.java:134)
at io.cucumber.core.runtime.FeaturePathFeatureSupplier.loadFeatures(FeaturePathFeatureSupplier.java:62)
at io.cucumber.core.runtime.FeaturePathFeatureSupplier.get(FeaturePathFeatureSupplier.java:45)
at io.cucumber.junit.Cucumber.<init>(Cucumber.java:156)
at java.base/jdk.internal.reflect.DirectConstructorHandleAccessor.newInstance(DirectConstructorHandleAccessor.java:67)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:484)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:70)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:37)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:70)
at org.junit.internal.requests.ClassRequest.createRunner(ClassRequest.java:28)
at org.junit.internal.requests.MemoizingRequest.getRunner(MemoizingRequest.java:19)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:90)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:76)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:49)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:513)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
I have been doing many workarounds for couple of days but couldn't resolve this issue. Can anyone please help?
Below are the jars I used.
cucumber-core-7.10.1.jar
cucumber-expressions-16.1.1.jar
cucumber-extentsreport-3.1.1.jar
cucumber-gherkin-5.2.0.jar
cucumber-gherkin-messages-7.10.1.jar
cucumber-java-7.10.1.jar
cucumber-junit-7.10.1.jar
cucumber-jvm-deps-1.0.6.jar
cucumber-plugin-7.10.1.jar
cucumber-reporting-5.7.4.jar
datatable-7.10.1.jar
datatable-dependencies-3.0.0.jar
extentreports-3.1.2.jar
extentreports-cucumber7-adapter-1.2.0.jar
gherkin-5.2.0.jar
gherkin-jvm-deps-1.0.6.jar
hamcrest-2.2.jar
hamcrest-core-1.3.jar
junit-4.13.2.jar
selenium-java-4.7.2.jar
selenium-server-4.7.2.jar
tag-expressions-5.0.1.jar
This is my project folder structure
[folder-structure-image][1]
[1]: https://i.stack.imgur.com/abYF2.png
This is my runner file:
package com.qa.myrunner;
import java.io.*;
import org.junit.runner.RunWith;
import com.vimalselvam.cucumber.listener.Reporter;
import io.cucumber.junit.CucumberOptions;
import io.cucumber.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(features = {"E:/Programming/LearnAutomation/SeleniumCucumberBDDV2/src/main/java/com/qa/features/SelectFlight.feature" },
glue = {"/SeleniumCucumberBDDV2/src/main/java/com/qa/stepDefinitions" },
monochrome = true,
dryRun = false)
public class SuiteRunner {
}

Junit class failing after ACS Commons version upgrade to 5.3.4

I upgraded ACS Commons version from 5.0.6 to 5.3.4 in my project and now can see most of the test classes failing with below error
org.junit.jupiter.api.extension.ParameterResolutionException: Failed to resolve parameter [io.wcm.testing.mock.aem.junit5.AemContext arg0] in method [void com.test.test.core.filters.LoggingFilterTest.doFilter(io.wcm.testing.mock.aem.junit5.AemContext) throws java.io.IOException,javax.servlet.ServletException]: Could not create io.wcm.testing.mock.aem.junit5.ResourceResolverMockAemContext instance.
at org.junit.jupiter.engine.execution.ExecutableInvoker.resolveParameter(ExecutableInvoker.java:232)
at org.junit.jupiter.engine.execution.ExecutableInvoker.resolveParameters(ExecutableInvoker.java:176)
at org.junit.jupiter.engine.execution.ExecutableInvoker.resolveParameters(ExecutableInvoker.java:137)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:118)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:184)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:180)
a
Caused by: org.reflections.ReflectionsException: Scanner TypeAnnotationsScanner was not configured
at org.reflections.Store.get(Store.java:39)
at org.reflections.Store.get(Store.java:61)
at org.reflections.Store.get(Store.java:46)
Please find below my test class. I am using JUnit version as below
<dependency>
<groupId>io.wcm</groupId>
<artifactId>io.wcm.testing.aem-mock.junit5</artifactId>
<version>4.0.4</version>
<scope>test</scope>
</dependency>
Attaching the class below:
import java.io.IOException;
import java.util.List;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import org.apache.sling.testing.mock.sling.servlet.MockRequestPathInfo;
import org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletRequest;
import org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import io.wcm.testing.mock.aem.junit5.AemContext;
import io.wcm.testing.mock.aem.junit5.AemContextExtension;
import uk.org.lidalia.slf4jext.Level;
import uk.org.lidalia.slf4jtest.LoggingEvent;
import uk.org.lidalia.slf4jtest.TestLogger;
import uk.org.lidalia.slf4jtest.TestLoggerFactory;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
#ExtendWith(AemContextExtension.class)
class LoggingFilterTest {
private LoggingFilter fixture = new LoggingFilter();
private TestLogger logger = TestLoggerFactory.getTestLogger(fixture.getClass());
#BeforeEach
void setup() {
TestLoggerFactory.clear();
}
#Test
void doFilter(AemContext context) throws IOException, ServletException {
MockSlingHttpServletRequest request = context.request();
MockSlingHttpServletResponse response = context.response();
MockRequestPathInfo requestPathInfo = (MockRequestPathInfo) request.getRequestPathInfo();
requestPathInfo.setResourcePath("/content/test");
requestPathInfo.setSelectorString("selectors");
fixture.init(mock(FilterConfig.class));
fixture.doFilter(request, response, mock(FilterChain.class));
fixture.destroy();
List<LoggingEvent> events = logger.getLoggingEvents();
assertEquals(0, events.size());
}
}
Does anyone know why it is failing with the ACS Commons version change?
This is like breaking lot many junit test classes

Running appium with .bat file

I need some to help me with the below. I am having error each time i run this project. It launches the cmd but fail to run the test.
package Automation;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Test;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.MobileCapabilityType;
import io.appium.java_client.remote.MobilePlatform;
public class FirstAppiumTest {
#Test
public void startappium () throws IOException, InterruptedException
{
Runtime.getRuntime().exec ("cmd /c start C:\\startappium.bat");
Thread.sleep(7000L);
File appDir=new File("src");
File app = new File(appDir,"app.apk");
DesiredCapabilities cap=new DesiredCapabilities();
cap.setCapability(MobileCapabilityType.PLATFORM_NAME,MobilePlatform.ANDROID);
cap.setCapability(MobileCapabilityType.DEVICE_NAME,"Android Emulator");
cap.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 100);
cap.setCapability(MobileCapabilityType.APP, app.getAbsolutePath());
AndroidDriver driver = new AndroidDriver (new URL ("http://127.0.0.1:4723/wd/hub"),cap);
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
}
}
Here are the errors below.
FAILED: startappium
java.lang.NoSuchMethodError: com.google.common.collect.ImmutableSet.toImmutableSet()Ljava/util/stream/Collector;
at org.openqa.selenium.remote.ProtocolHandshake.streamW3CProtocolParameters(ProtocolHandshake.java:238)
===============================================
Default test
Tests run: 1, Failures: 1, Skips: 0
I appreciate your prompt reply. Thank you

Jersey 1.9 webapp on Tomcat 8 (Eclipse) upgrade to 1.19.1 cause 404 error

if I change the jersey version to a higher one than 1.9 then a 404 error returns when I try to run the servlet.
Here are some details of my setting:
- Tomcat 8
- Eclipse Luna
- Maven for integrating the lib
I guess there are maybe changes in the syntax of the RestFul service provide since 1.9, but I'm not sure. So here is the servlet code:
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
#Path("/helloWorldREST")
public class HelloWorldREST {
#GET
#Path("/{parameter}")
public Response responseMsg( #PathParam("parameter") String parameter,
#DefaultValue("Nothing to say") #QueryParam("value") String value) {
String output = "Hello from: " + parameter + " : " + value;
return Response.status(200).entity(output).build();
}
}

org.drools.RuntimeDroolsException: invalid package name

I am a new bie to JBPM.
I have created bpmn file with a start ,diverge and two scripts and a converge and endtask.
MY code is
package com.sample;
import java.util.HashMap;
import java.util.Map;
import org.drools.KnowledgeBase;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.ResourceFactory;
import org.drools.runtime.StatefulKnowledgeSession;
import org.drools.runtime.process.ProcessInstance;
public class ProcessTest {
public static void main(String[] args){
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add( ResourceFactory.newClassPathResource("sample.bpmn"),
ResourceType.BPMN2 );
KnowledgeBase kbase = kbuilder.newKnowledgeBase();
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
Map<String,Object> params=new HashMap<String,Object>();
params.put("income", 1200);
ProcessInstance processInstance = ksession.startProcess("com.sample.bpmn.hello",params);
}
}
But i am getting the following error
org.drools.RuntimeDroolsException: invalid package name
at org.jbpm.compiler.ProcessBuilderImpl.buildProcess(ProcessBuilderImpl.java:175)
at org.jbpm.compiler.ProcessBuilderImpl.addProcessFromXml(ProcessBuilderImpl.java:254)
at org.drools.compiler.PackageBuilder.addProcessFromXml(PackageBuilder.java:564)
at org.drools.compiler.PackageBuilder.addKnowledgeResource(PackageBuilder.java:608)
at org.drools.builder.impl.KnowledgeBuilderImpl.add(KnowledgeBuilderImpl.java:37)
at com.sample.ProcessTest.main(ProcessTest.java:23)
[6,13]: [ERR 102] Line 6:13 mismatched input 'income' in rule "RuleFlow- Split-com.sample.bpmn.hello-2-3-DROOLS_DEFAULT"
[13,13]: [ERR 102] Line 13:13 mismatched input 'income' in rule "RuleFlow- Split-com.sample.bpmn.hello-2-4-DROOLS_DEFAULT"
[0,0]: Parser returned a null Package
ProcessLoadError: unable to parse xml : Exception class org.drools.RuntimeDroolsException : invalid package name
Exception in thread "main" java.lang.IllegalArgumentException: Could not parse knowledge.
at org.drools.builder.impl.KnowledgeBuilderImpl.newKnowledgeBase(KnowledgeBuilde rImpl.java:67)
at com.sample.ProcessTest.main(ProcessTest.java:26)
I have given package name com.sample in sample.bpmn
My sample.bpmn file is
Found the solution for this issue. This is related to config change in the Diverge gateway Constraints. For each constraint, try using **Type: code and Dialect: java. Also do not forget to put semicolon ; at the end of the statement in the Textual editor of each constraint. Best way to check this is to open the RF file in a text editor and validate the content.
Something like:
<constraints>
<constraint toNodeId="3" toType="DROOLS_DEFAULT" name="Flight" priority="1" type="code" dialect="java" >return income > 1000;</constraint>
<constraint toNodeId="4" toType="DROOLS_DEFAULT" name="Train" priority="1" type="code" dialect="java" >return income < 1000;</constraint>
</constraints>
Hope this will help.