Problem when executing report ".jasper" in Apache ISIS - isis

The execution of the method "ReporteListadoVehiculos()" only displays up to the line "JasperPrint j = JasperFillManager.fillReport(report, null, conectar());", and apparently there's an error that avoids continuing the execution.
How can I find the error that is avoiding the execution of the report, and which are the steps I should follow to fix this tipe of problems?
This is the code I'm using to execute the report:
package domainapp.modules.simple.dominio.reportes;
import java.io.File;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JOptionPane;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.view.JasperViewer;
public class EjecutarReportes {
public static Connection conectar() {
Connection con = null;
try {
String url = "jdbc:postgresql://127.0.0.1:5432/adet?user=adetuser&password=Passw0rd";
con = DriverManager.getConnection(url);
if (con != null) {
System.out.println("Conexion Satisfactoria");
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return con;
}
public void ReporteListadoVehiculos(){
try {
File ruta = new File("C:\\Users\\4G\\Desktop\\Proyecto_Final\\Codigo\\AdeT\\module-simple\\src\\main\\java\\domainapp\\modules\\simple\\dominio\\reportes\\ListadoVehiculos.jasper");
JasperReport report = (JasperReport) JRLoader.loadObject(ruta);
JasperPrint j = JasperFillManager.fillReport(report, null, conectar());
JasperViewer jv = new JasperViewer(j,false);
jv.setTitle("Listado de Vehiculos");
jv.setVisible(true);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error al mostrar el Reporte: "+e);
}
}
}

AFAIK JOptionPane is part of swing. By default Apache Isis comes with a WicketViewer.
Try using a logger (eg. log4j) or even System.out.println() to get closer to the problem.

Related

Error message "FileNotFoundException" is showing if I run the runnable .jar file from command line

Error message is showing when I run the created runnable .jar file from command line
Error message "java.io.FileNotFoundException: Files\Learners_login_sheet_1.xlsx (The system cannot find the path specified)" is showing when I run the runnable .jar file from the Command line.
Same code is working fine if I run the same code from the Eclipse "run as TestNG".
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.stream.Collectors;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Utility
{
public static ArrayList<String[]> getDataFromExcel()
{
ArrayList<String[]> myData = new ArrayList<String[]>();
Workbook dataWorkbook = null;
try
{
FileInputStream file = new FileInputStream(new File("Files/Learners_login_sheet_1.xlsx"));
String fileName="Learners_login_sheet_1.xlsx";
String fileExtensionName = fileName.substring(fileName.indexOf("."));
if(fileExtensionName.equals(".xlsx"))
{
dataWorkbook = new XSSFWorkbook(file);
}
else if(fileExtensionName.equals(".xls"))
{
dataWorkbook = new HSSFWorkbook(file);
}
}
catch (Exception e){
e.printStackTrace();
}
String sheetName="Learner_details";
org.apache.poi.ss.usermodel.Sheet signupSheet = dataWorkbook.getSheet(sheetName);
int rowCount = signupSheet.getLastRowNum()-signupSheet.getFirstRowNum();
for(int rowNum=2; rowNum <=rowCount; rowNum++ )
{
Row row=signupSheet.getRow(rowNum);
String Email=row.getCell(0).toString();
String Password=row.getCell(1).toString();
String obj[]={Email, Password};
myData.add(obj);
}
return myData;
}
}

Paginating OpenLDAP with Apache Directory LDAP API over multiple connections

I've used the Apache Directory API to load in user data from an Active Directory. It's similar to the example code by 'oers' found in this stackoverflow question: Apache Directory LDAP - Paged searches
Some differences I have are:
I'm coding it with in Nashorn (Javascript running in Java)
I'm using the PagedResultsImpl class instead of PagedResultsDecorator
I'm saving the cookie as a string between calls by using a Base64 encoding of the byte[] cookie.
I'm using Apache Directory API with the following maven import:
<dependency>
<groupId>org.apache.directory.api</groupId>
<artifactId>api-all</artifactId>
<version>1.0.3</version>
</dependency>
Here's some of the important bits:
...
var pageCursor = ""; /** or some Base64 encoded byte[] cookie if I'm trying to start from where i left off last time. */
...
pagedSearchControl = new PagedResultsImpl();
pagedSearchControl.setSize(pageSize);
pagedSearchControl.setCookie(Base64.getEncoder().encodeToString(pageCursor.getBytes()));
...
var searchRequest = new SearchRequestImpl();
...
searchRequest.addControl(pagedSearchControl);
...
var cursor = new EntryCursorImpl(connection.search(searchRequest));
...
pagingResults = cursor.getSearchResultDone().getControl(PagedResults.OID);
if (pagingResults != null){
nextPageCursor = Base64.getEncoder().encodeToString(pagingResults.getCookie());
}
When run against Active Directory I can page all the users just fine. When I change my connection to point to an OpenLDAP directory I am able to search for users just fine, EXCEPT for when I set the page control cookie using a non-null value for pageCursor (one I got from base 64 encoding a previous call's cookie). Basically, I can't get the paged results from OpenLDAP. I get no results and there are no exceptions.
What is needed in order to get OpenLDAP to page properly?
Am I missing something with setting up page control in Apache Directory?
Is paging a setting in OpenLDAP I need to turn on?
[UPDATE] I Ported my code outside of Nashorn to just Java and now I can see it is because the paging cookie appears to be only valid within the same connection for OpenLDAP, but for Active Directory it can be different connections. You can see yourself with the code below.:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Base64;
import java.util.Iterator;
import java.util.Properties;
import java.util.StringJoiner;
import javax.naming.ConfigurationException;
//imports for json
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
//imports for LDAP
import org.apache.directory.api.ldap.model.cursor.EntryCursor;
import org.apache.directory.api.ldap.model.entry.Attribute;
import org.apache.directory.api.ldap.model.entry.DefaultEntry;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.entry.Value;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException;
import org.apache.directory.api.ldap.model.message.Control;
import org.apache.directory.api.ldap.model.message.ResultCodeEnum;
import org.apache.directory.api.ldap.model.message.SearchRequest;
import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
import org.apache.directory.api.ldap.model.message.SearchResultDone;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.api.ldap.model.message.controls.AbstractControl;
import org.apache.directory.api.ldap.model.message.controls.PagedResults;
import org.apache.directory.api.ldap.model.message.controls.PagedResultsImpl;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.ldap.client.api.EntryCursorImpl;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
//Nashorn
import delight.nashornsandbox.NashornSandbox;
import delight.nashornsandbox.NashornSandboxes;
public class Executor
{
public static void main( String[] args )
{
pagingTest();
}
private static void pagingTest(){
//ENTER YOUR CREDENTIALS
String server = "";
int port = 0;
String loginId = "";
String loginPassword = "";
String usersBaseDN = "";
String userObjectClass = "";
String base64cookie = null;
LdapNetworkConnection connection = new LdapNetworkConnection(server, port, true );
try{
connection.setTimeOut( 300 );
connection.bind(loginId,loginPassword);
/*First Pass*/
PagedResultsImpl pagedSearchControl = new PagedResultsImpl();
pagedSearchControl.setSize(5);
pagedSearchControl.setCookie(Base64.getDecoder().decode(""));
SearchRequestImpl searchRequest = new SearchRequestImpl();
searchRequest.setBase(new Dn(usersBaseDN));
searchRequest.setFilter("(objectClass=" + userObjectClass +")");
searchRequest.setScope(SearchScope.SUBTREE);
searchRequest.addAttributes("*");
searchRequest.addControl(pagedSearchControl);
EntryCursorImpl cursor = new EntryCursorImpl(connection.search(searchRequest));
while (cursor.next()) {
System.out.println("First Pass User: " + cursor.get().getDn());
}
PagedResults pagingResults = (PagedResults)cursor.getSearchResultDone().getControl(PagedResults.OID);
if (pagingResults != null){
byte[] cookie = pagingResults.getCookie();
if (cookie != null && cookie.length > 0) {
base64cookie = Base64.getEncoder().encodeToString(cookie);
System.out.println("First Pass Cookie: " + cookie);
}
}
cursor.close();
}catch(Exception e){
System.out.println(e);
}
finally {
//COMMENT THIS CODE BLOCK TO SEE IT WORKING (IT WILL USE THE SAME CONNECTION)
try {
connection.unBind();
connection.close();
} catch (Exception e) {
System.out.println(e);
}
connection = new LdapNetworkConnection( server, port, true );
}
try{
connection.setTimeOut( 300 );
connection.bind(loginId,loginPassword);
/*Second Pass*/
PagedResultsImpl secondPagedSearchControl = new PagedResultsImpl();
secondPagedSearchControl.setSize(5);
secondPagedSearchControl.setCookie(Base64.getDecoder().decode(base64cookie));
SearchRequestImpl secondSearchRequest = new SearchRequestImpl();
secondSearchRequest.setBase(new Dn(usersBaseDN));
secondSearchRequest.setFilter("(objectClass=" + userObjectClass +")");
secondSearchRequest.setScope(SearchScope.SUBTREE);
secondSearchRequest.addAttributes("*");
secondSearchRequest.addControl(secondPagedSearchControl);
EntryCursorImpl secondCursor = new EntryCursorImpl(connection.search(secondSearchRequest));
while (secondCursor.next()) {
System.out.println("Second Pass User: " + secondCursor.get().getDn());
}
secondCursor.close();
}catch(Exception e){
System.out.println(e);
}
finally {
try {
connection.unBind();
connection.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
}
So I guess my new question is:
Is anybody aware of a workaround to allow OpenLDAP to accept
pagination cookies from previous connections?

Query Expansion lucene

I am new to lucene and I am trying to do query expansion.
I have referred to these two posts (first , second) and I've managed to reuse the code in a way that suits version 6.0.0, as the one in the previous is deprecated.
The issue is, either I'm not getting a results or I didn't access the results (expanded queries) appropriately.
Here is my code:
import com.sun.corba.se.impl.util.Version;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.core.LowerCaseFilter;
import org.apache.lucene.analysis.standard.ClassicTokenizer;
import org.apache.lucene.analysis.standard.StandardFilter;
import org.apache.lucene.analysis.synonym.SynonymFilter;
import org.apache.lucene.analysis.synonym.SynonymMap;
import org.apache.lucene.analysis.synonym.WordnetSynonymParser;
import org.apache.lucene.analysis.util.CharArraySet;
import org.apache.lucene.util.*;
public class Graph extends Analyzer
{
protected static TokenStreamComponents createComponents(String fieldName, Reader reader) throws ParseException{
System.out.println("1");
// TODO Auto-generated method stub
Tokenizer source = new ClassicTokenizer();
source.setReader(reader);
TokenStream filter = new StandardFilter( source);
filter = new LowerCaseFilter(filter);
SynonymMap mySynonymMap = null;
try {
mySynonymMap = buildSynonym();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
filter = new SynonymFilter(filter, mySynonymMap, false);
return new TokenStreamComponents(source, filter);
}
private static SynonymMap buildSynonym() throws IOException, ParseException
{ System.out.print("build");
File file = new File("wn\\wn_s.pl");
InputStream stream = new FileInputStream(file);
Reader rulesReader = new InputStreamReader(stream);
SynonymMap.Builder parser = null;
parser = new WordnetSynonymParser(true, true, new StandardAnalyzer(CharArraySet.EMPTY_SET));
System.out.print(parser.toString());
((WordnetSynonymParser) parser).parse(rulesReader);
SynonymMap synonymMap = parser.build();
return synonymMap;
}
public static void main (String[] args) throws UnsupportedEncodingException, IOException, ParseException
{
Reader reader = new FileReader("C:\\input.txt"); // here I have the queries that I want to expand
TokenStreamComponents TSC = createComponents( "" , new StringReader("some text goes here"));
**System.out.print(TSC); //How to get the result from TSC????**
}
#Override
protected TokenStreamComponents createComponents(String string)
{
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
Please suggest ways to help me access the expanded queries!
So, are you just trying to figure out how to iterate through the terms from the TokenStreamComponents in your main method?
Something like this:
TokenStreamComponents TSC = createComponents( "" , new StringReader("some text goes here"));
TokenStream stream = TSC.getTokenStream();
CharTermAttribute termattr = stream.addAttribute(CharTermAttribute.class);
stream.reset();
while (stream.incrementToken()) {
System.out.println(termattr.toString());
}

Parsing content from Word document using docx4j

Thanks to a previous answer, I'm now able to read my password-protected Word 2010 documents. (I have to translate them one by one from .doc to .docx. They go back to 1994, but that's okay.)
I wrote a simple Java class to get started:
package model.docx4j;
import model.JournalEntry;
import model.JournalEntryFactory;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.OpcPackage;
import org.docx4j.openpackaging.parts.Parts;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.LinkedList;
import java.util.List;
/**
* JournalEntryFactoryImpl using docx4j
* #author Michael
* #link
* #since 9/8/12 12:44 PM
*/
public class JournalEntryFactoryImpl implements JournalEntryFactory {
#Override
public List<JournalEntry> getEntries(InputStream inputStream, String password) throws IOException, GeneralSecurityException {
List<JournalEntry> journalEntries = new LinkedList<JournalEntry>();
if (inputStream != null) {
try {
OpcPackage opcPackage = OpcPackage.load(inputStream, password);
Parts parts = opcPackage.getParts();
} catch (Docx4JException e) {
LOGGER.error("Could not load document into docx4j", e);
throw new IOException(e);
}
}
return journalEntries;
}
}
And a JUnit test to drive it:
package model.docx4j;
import model.JournalEntry;
import model.JournalEntryFactory;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.OpcPackage;
import org.docx4j.openpackaging.parts.Parts;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.LinkedList;
import java.util.List;
/**
* JournalEntryFactoryImpl using docx4j
* #author Michael
* #link
* #since 9/8/12 12:44 PM
*/
public class JournalEntryFactoryImpl implements JournalEntryFactory {
#Override
public List<JournalEntry> getEntries(InputStream inputStream, String password) throws IOException, GeneralSecurityException {
List<JournalEntry> journalEntries = new LinkedList<JournalEntry>();
if (inputStream != null) {
try {
OpcPackage opcPackage = OpcPackage.load(inputStream, password);
Parts parts = opcPackage.getParts();
} catch (Docx4JException e) {
LOGGER.error("Could not load document into docx4j", e);
throw new IOException(e);
}
}
return journalEntries;
}
}
I put a breakpoint into the test to see what docx4j was doing once it read my document. I see a list of 8 parts, but I walked through the tree without finding the content.
Each document consists of a page with a date and content, but I can't find pages. Where do they live?
The main document content lives in the "main document part", which is often named "/word/document.xml".
The usual way to get it with docx4j is:
WordprocessingMLPackage wordMLPackage = (WordprocessingMLPackage)opcPackage;
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
but you'd expect your approach to work as well.

Selenium tests for custom portlets

Can anyone provide me a link/document with information on how to write and test custom liferay portlets with Selenium.
I am using Liferay 6.1EE
Thanks
Same as with other tests, assuming you want to run as JUnit test
package org.ood.selenium.test;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.IncorrectnessListener;
import com.gargoylesoftware.htmlunit.ScriptException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlButton;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.javascript.JavaScriptErrorListener;
import com.thoughtworks.selenium.SeleneseTestBase;
import com.thoughtworks.selenium.Selenium;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.regex.Pattern;
public class MyTest extends SeleneseTestBase {
WebDriver driver =null;
#Before
public void setUp() throws Exception {
DesiredCapabilities dc = DesiredCapabilities.firefox();
// dc.setCapability(FirefoxDriver.BINARY, new
//File("C:/Program Files (x86)/Mozilla Firefox/firefox.exe").getAbsolutePath());
dc.setJavascriptEnabled(true);
// driver= new HtmlUnitDriver(true);//Not properly working
driver = new FirefoxDriver(dc);
String baseUrl = "http://localhost:8080/web/guest/home";
selenium = new WebDriverBackedSelenium(driver, baseUrl);
}
/* #Test
public void homePage() throws Exception {
final WebClient webClient = new WebClient();
//HTMLUNit throws lots of errors
webClient.setJavaScriptEnabled(true);
webClient.setJavaScriptErrorListener(new JavaScriptErrorListener() {
public void timeoutError(HtmlPage htmlPage, long allowedTime,
long executionTime) {
// TODO Auto-generated method stub
}
public void scriptException(HtmlPage htmlPage,
ScriptException scriptException) {
System.out.println(scriptException.getMessage());
}
public void malformedScriptURL(HtmlPage htmlPage, String url,
MalformedURLException malformedURLException) {
System.out.println(url);
}
public void loadScriptError(HtmlPage htmlPage, URL scriptUrl,
Exception exception) {
// TODO Auto-generated method stub
}
});
//webClient.setThrowExceptionOnFailingStatusCode(false);
webClient.setThrowExceptionOnScriptError(false);
final HtmlPage page = webClient.getPage("http://localhost:8080/web/guest/home");
webClient.getCache().clear();
page.getElementById("sign-in").click();
page.getElementById("_58_login").type("test#liferay.com");
page.getElementById("_58_password").type("test#liferay.com");
final HtmlButton submit = (HtmlButton)page.getByXPath("//input").get(0);
submit.click();
//assertEquals("HtmlUnit - Welcome to HtmlUnit", page.getTitleText());
System.out.println("Title= " +page.getTitleText());
final String pageAsXml = page.asXml();
// assertTrue(pageAsXml.contains("<body class=\"composite\">"));
System.out.println("pageAsXml=" +pageAsXml);
final String pageAsText = page.asText();
//assertTrue(pageAsText.contains("Support for the HTTP and HTTPS protocols"));
System.out.println("pageAsText="+pageAsText);
webClient.closeAllWindows();
}*/
#Test //Using Graphical GUI
public void testMytest() throws Exception {
//driver.get("http://localhost:8080/web/guest/home");
selenium.open("/");
//selenium.click("id=sign-in");
driver.findElement(By.id("sign-in")).click();
driver.findElement(By.name("_58_login")).clear();
driver.findElement(By.name("_58_login")).sendKeys("test#liferay.com");
driver.findElement(By.name("_58_password")).sendKeys("123");
//driver.findElement(By.name("_58_login")).sendKeys("test#nsn.com");
//driver.findElement(By.name("_58_password")).sendKeys("test");
driver.findElement(By.className("aui-button-input-submit")).submit();
//selenium.setSpeed("1000");
//selenium.waitForPageToLoad("5000");
//Select a nested div( the NodeTree)
driver.findElement(By.xpath("//div[contains(#class,'aui-tree-node-content')" +
" and (contains(.,'TreeNodeX'))]//div[contains(#class,'aui-tree-hitarea')]"))
.click();
//selenium.captureScreenshot("d:/_del/sel_screen.png");//this throws an error
//workaround
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("d:/_del/sel_screen.png"));
System.out.println("Bodytex=[" +selenium.getBodyText() +"]End Body Text");
String[] titles= selenium.getAllWindowTitles();
System.out.println("Titles Start-");
for (int i = 0; i < titles.length; i++) {
System.out.println(titles[i]);
}
System.out.println("Titles End");
verifyEquals(true, selenium.getBodyText().contains("Site View"));
}
#After
public void tearDown() throws Exception {
selenium.stop();
}
}