I created a report from my NetBeans GUI and It was working fine, but all of a sudden the compiler showing error now.
package dreportsample;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import net.sf.dynamicreports.examples.Templates;
import net.sf.dynamicreports.report.builder.style.StyleBuilder;
import net.sf.dynamicreports.report.constant.HorizontalAlignment;
import net.sf.dynamicreports.report.datasource.DRDataSource;
import net.sf.dynamicreports.report.exception.DRException;
import net.sf.jasperreports.engine.JRDataSource;
/**
* #author Ricardo Mariaca (dynamicreports#gmail.com)
*/
public class DReportSample {
public DReportSample() {
build();
}
private void build() {
StyleBuilder boldStyle = stl.style().bold();
StyleBuilder boldCenteredStyle = stl.style(boldStyle).setHorizontalAlignment
(HorizontalAlignment.CENTER).setFontSize(15);
StyleBuilder footerLeft = stl.style().setHorizontalAlignment
(HorizontalAlignment.LEFT) ;
StyleBuilder footerRight = stl.style().setHorizontalAlignment
(HorizontalAlignment.RIGHT) ;
//BufferedImage img = new BufferedImage(1200,1200,BufferedImage.TYPE_INT_RGB);
BufferedImage img = null;
try {
// img = ImageIO.read(new File("D:/Hysteresis.png"));
img = ImageIO.read(new File("D:/Hysteresis.png"));
} catch (IOException e) {
}
BufferedImage logo = null;
try {
// img = ImageIO.read(new File("D:/Hysteresis.png"));
logo = ImageIO.read(new File("D:/Logo.jpg"));
} catch (IOException e) {
}
try {
report()//create new report design
// .setColumnTitleStyle(boldStyle)
// .setColumnStyle(boldStyle)
.highlightDetailEvenRows()
.columns(//add columns
col.column(null,"Col_1", type.stringType()),
col.column(null,"Col_2", type.stringType())
)
.summary(
cmp.verticalList()
.add(cmp.text("\n\nHYSTERISIS PLOT").setStyle(boldStyle))
.add(cmp.text("A brief description of what this plot signifies "
+ "which means that change in are related to"
+ " pain relief and subsequently"
+ "should be encouraged \n\n\n\n"))
// .add(cmp.image(getClass().getResourceAsStream
// ("D:/Hysteresis.png")).setFixedDimension(300, 300))
.add(cmp.image(img).setFixedDimension(400, 300))
.add(cmp.text("ANALYSIS\n\n\n").setStyle(boldStyle))
.add(cmp.text("REMARKS\n\n\n\n").setStyle(boldStyle))
.add(cmp.text("Doctor Signature").setStyle(boldStyle))
)
.title(
cmp.horizontalList()
.add(
cmp.image(logo).setFixedDimension(70, 70),
cmp.verticalList()
.add(
cmp.text("Address Line 1").setStyle(boldCenteredStyle),
cmp.text("Address Line 2").setStyle(boldCenteredStyle),
cmp.text("Address Line 3").setStyle(boldCenteredStyle))
)
.newRow()
.add(cmp.filler().setStyle(stl.style().setTopBorder(stl.pen2Point())).setFixedHeight(10))
)//shows report title
// .pageFooter(cmp.pageXofY())//shows number of page at page footer
.pageFooter(
Templates.footerComponent,
//cmp.text("Emsol Software Solution \t\t\t\t\t\t\t\t"
// + " copyright: gauravbvelelx#gmail.com")
cmp.horizontalList()
.add(cmp.text("Emsol Software Solution").setStyle(footerLeft),
cmp.text("copyright: gauravbvelex#gmail.com").setStyle(footerRight))
)
.setDataSource(createDataSource())//set datasource
.show();//create and show report
} catch (DRException e) {
e.printStackTrace();
}
}
private JRDataSource createDataSource() {
DRDataSource dataSource = new DRDataSource("Col_1", "Col_2");
dataSource.add("Name","Sample");
dataSource.add("Age","26");
dataSource.add("Sex","Female");
dataSource.add("Weight","53 Kg");
dataSource.add("BMI","20");
dataSource.add("Massage Duration (Mins)","4.5");
dataSource.add("RPM","26");
dataSource.add("Doctor Attended","Doctor");
dataSource.add("Date","22-Feb-2013");
return dataSource;
}
public static void main(String[] args) {
new DReportSample();
}
}
This code worked fine just few hours back. But now it is suddenly showing error:
Screen shot attached
Same kind of error it is showing at report() and other parts as well. Basically it is not able to recognize various classes and fields of dynamic reports library though the library has been imported successfully, though few hours back it was working well.
The way I am using dynamic reports is by adding the libraries as below:
1) Downloaded dynamicreports-3.1.0-project-with-dependencies
2) Unzipped
3) In my Netbeans Project
Libraries -> Add Jar/folder -> Selecting all files from dynamicreports-3.1.0-project-with-dependencies\dynamicreports-3.1.0\lib
Libraries -> Add Jar/folder -> Selecting all files from dynamicreports-3.1.0-project-with-dependencies\dynamicreports-3.1.0\dist
It worked fine, but then then I changed the name of the folder where I saved dynamicreports-3.1.0-project-with-dependencies, due to which It gave me Reference Error for added libraries. So I again rechanged it to previous name, but since then I am getting the error shown.
I have tried everything, building new project and following the steps mentioned or re downloading new dynamicreports-3.1.0-project-with-dependencies and again following the steps. But nothing seems to work, its frustrating as I was so close to complete my project.
Can anyone help please.
Thanks
Ok.. resolved it..
Below line got deleted causing the errors:
import static net.sf.dynamicreports.report.builder.DynamicReports.*;
Related
I am trying to verify a toaster message in Android Mobile app but not able to get text of toaster message as it doesn't show in uiautomatorviewer.
Got some information that by the help of OCR it can be done taking screenshots and fetching the text from that screenshots
Can anyone help me out how to do this step by step using java in Appium project?
You can follow the information on the below links to install the Tesseract on your machine:
For Mac: http://emop.tamu.edu/Installing-Tesseract-Mac
For Windows: http://emop.tamu.edu/Installing-Tesseract-Windows8
After installing the TessEract on your machine you need to add the dependency of TessEract Java library in your project. If you are using Maven for it, adding below dependency will work:
<dependency>
<groupId>org.bytedeco.javacpp-presets</groupId>
<artifactId>tesseract</artifactId>
<version>3.04-1.1</version>
</dependency>
Also the 'Step 3' which is mentioned by Ivan need not to be followed.
If you are using 'TestNG' the TessEract API needs to be initialised only once so instead of initialising it every time, as per your framework you can initialise it either in the 'BeforeTest' or 'BeforeSuite' or 'BeforeClass' method and accordingly close the API either in 'AfterTest' or 'AfterSuite' or 'AfterClass' method.
Below is the code that I have written to achieve it.
import static org.bytedeco.javacpp.lept.pixDestroy;
import static org.bytedeco.javacpp.lept.pixRead;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.bytedeco.javacpp.lept.PIX;
import org.bytedeco.javacpp.tesseract.TessBaseAPI;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
public class BaseTest {
static TessBaseAPI api = new TessBaseAPI();
#BeforeSuite
public void beforeSuit() throws IOException {
File screenshotsDirec = new File("target/screenshots");
if (screenshotsDirec.exists())
FileUtils.forceDelete(screenshotsDirec);
FileUtils.forceMkdir(screenshotsDirec);
System.out.println("Initializing TessEract library");
if (api.Init("/opt/local/share", "eng") != 0) {
System.err.println("Could not initialize tesseract.");
}
}
public synchronized boolean verifyToastMessage(String msg)
throws IOException {
TakesScreenshot takeScreenshot = ((TakesScreenshot) driver);
File[] screenshots = new File[5];
for (int i = 0; i < screenshots.length; i++) {
screenshots[i] = takeScreenshot.getScreenshotAs(OutputType.FILE);
}
String outText;
Boolean isMsgContains = false;
for (int i = 0; i < screenshots.length; i++) {
PIX image = pixRead(screenshots[i].getAbsolutePath());
api.SetImage(image);
outText = api.GetUTF8Text().getString().replaceAll("\\s", "");
System.out.println(outText);
isMsgContains = outText.contains(msg);
pixDestroy(image);
if (isMsgContains) {
break;
}
}
return isMsgContains;
}
#AfterSuite()
public void afterTest() {
try {
api.close();
} catch (Exception e) {
api.End();
e.printStackTrace();
}
}
}
I would also like to add that writing tests to read and verify the Toast messages in this way is not very much reliable as in one of my tests this code successfully captures the Toast message while in another test it fails to capture the toast message because the capturing of the screenshots starts when the toast message disappears. That was the reason I tried to write this code very much efficiently. However that also does not serve the purpose.
Follow this discussion on Appium forum: https://discuss.appium.io/t/verifying-toast/3676.
Basic steps to verify a Toaster are:
Perform action to trigger the toast message to appear on screen
Take x number of screenshots
Increase resolutions of all screenshots
Use tessearct OCR to detect the toast message.
Refer this repo to use Java OCR library (see at the bottom):
import org.bytedeco.javacpp.*;
import static org.bytedeco.javacpp.lept.*;
import static org.bytedeco.javacpp.tesseract.*;
public class BasicExample {
public static void main(String[] args) {
BytePointer outText;
TessBaseAPI api = new TessBaseAPI();
// Initialize tesseract-ocr with English, without specifying tessdata path
if (api.Init(null, "eng") != 0) {
System.err.println("Could not initialize tesseract.");
System.exit(1);
}
// Open input image with leptonica library
PIX image = pixRead(args.length > 0 ? args[0] : "/usr/src/tesseract/testing/phototest.tif");
api.SetImage(image);
// Get OCR result
outText = api.GetUTF8Text();
System.out.println("OCR output:\n" + outText.getString());
// Destroy used object and release memory
api.End();
outText.deallocate();
pixDestroy(image);
}
}
I am beginner in java.
I want run native application from applet.
I found Run App In Every Browser
Java Code
import com.ms.security.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.io.* ;
import java.util.*;
import netscape.security.PrivilegeManager;
public class RunApp extends Applet implements ActionListener {
TextArea ta = new TextArea (25, 80);
Button startbutton = new Button("Start Application") ;
private static String execommand = "C:\\windows\\notepad.exe" ;
private String osname;
public void init() {
try {
if (Class.forName("com.ms.security.PolicyEngine") != null) { // required for IE
PolicyEngine.assertPermission(PermissionID.SYSTEM);
}
}
catch (Throwable cnfe) {
}
this.setBackground(Color.white) ;
startbutton.addActionListener(this) ;
add(startbutton) ;
startbutton.setBackground(Color.red) ;
try{
PrivilegeManager.enablePrivilege("UniversalExecAccess") ; // required for NN
}
catch(Exception cnfe) {
System.out.println("netscape.security.PrivilegeManager class not found") ;
}
osname = System.getProperty("os.name"); // if NT, Win2000 or WinXP, adjust path
if(osname.equals("Windows NT") || osname.equals("Windows 2000")|| osname.equals("Windows XP"))
execommand = "C:\\winnt\\notepad.exe" ;
}
public void actionPerformed(ActionEvent e) {
if( (e.getActionCommand()).equals("Start Application")) {
try{
PrivilegeManager.enablePrivilege("UniversalExecAccess") ; // required for NN
}
catch(Exception cnfe) {
System.out.println("netscape.security.PrivilegeManager class not found") ;
}
try {
Process proc = Runtime.getRuntime().exec(execommand) ;
}
catch(IOException ieo) {
System.out.println("Problem starting " + execommand) ;
}
// System.out.println("execommand: " + execommand) ;
}
}
}
But when run it say error:package com.ms.security does not exit!
I does not any folder with ms or security name .
I should create folder with ms and then security in root file or should import library ms.security .
where is com.ms.security or netscape.security.PrivilegeManager?
how can download it?i search for download this package but i does not found anythings
I use eclipse for write code.
This package does not exist any more. The tutorial you point to dates from 2002. You can look at this javaranch post: http://www.coderanch.com/t/375470/java/java/Location-Jar-ms-security, and at the Microsoft documentation (https://msdn.microsoft.com/en-us/library/aa242534(v=vs.60).aspx). So basically your code would have worked 13 years ago, but with Microsoft not supporting their own JVM any more it's obsolete. Sorry!
You need to download that jar having this package ,com.ms.security. And b4 compiling your java class set that jar in your classpath from command prompt.
set classpath=%classpath%;path_of_your_jar;
This package is not existed anymore. Microsoft is not supporting their own JVM anymore. You should try to learn java applet in the new way, such as http://www.tutorialspoint.com/java/java_applet_basics.htm.
The import statement import com.ms.security.*; requires you to have a folder com, with a subfolder ms, with a subfolder security, which contains the needed files.
I think you are missing some files for your application.
I recommend reading this post, for the use of imports: https://stackoverflow.com/a/12620773/3234981
Please check your jar file which contain the respective package are present in the classpath or not. If not, push them to classpath and re-compile the same class on a new command line.
Happy Learning.
I can not find any documenration on this library (https://code.google.com/p/sfntly/). I've been taking stabs at it for 2 days now. I'm trying to convert any font that gets uploaded to "WOFF" format.
Could someone shed some light?
I successfully converted my TTF into a WOFF file by following these steps:
Download and install ant following "The Short Story" steps (http://ant.apache.org/manual/install.html#getBinary)
Download SFNTLY via SVN checkout (https://code.google.com/p/sfntly/source/checkout) and followed the steps contained into the file "sfntly\java\quickstart.txt"
Created a new java project and imported the following four jars I created following the previous steps into my project:
sfntly.jar
woffconverter.jar
guava-16.0.1.jar
I slightly tweaked display_name code which contained a few syntax mistakes.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import com.google.common.io.Files;
import com.google.typography.font.sfntly.Font;
import com.google.typography.font.sfntly.FontFactory;
import com.google.typography.font.sfntly.data.WritableFontData;
import com.google.typography.font.tools.conversion.woff.WoffWriter;
public class Main {
public static void main(String[] args) {
WoffWriter ww = new WoffWriter();
FontFactory fontFactory = FontFactory.getInstance();
byte[] bytes;
try {
bytes = Files.toByteArray(new File("C:\\FontName.TTF"));
Font font = fontFactory.loadFonts(bytes)[0];
WritableFontData wfd = ww.convert(font);
FileOutputStream fs = new FileOutputStream("out.fnt");
wfd.copyTo(fs);
fs.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
After reading the source code of SFNTLY I am no expert in sfntly, so use my answer at your risk :).
I would convert the font with WoffWriter#convert() to writeable font data, then copy the wfd to outputstream.
WoffWriter ww = new WoffWriter();
WriteableFontData wfd = ww.convert(yourFont);
try {
FileOutPutStream fs = new FileOutputStream("out.fnt");
wfd.copyTo(fs, wfd);
fs.close();
} catch (IOException e) {
}
Hi I am new to flickrj library.
Have foundational java knowledge though.
The project that I am working on requires me to authenticate into flickr and then download geo-tagged images into a folder in local hard drive. The program will be Desktop application program.
I am approaching the program by breaking down into 3 steps.
1.Proper authentication to be completed.(which i have succeeded)
2.Try to download all the photos that user has when authenticated.
3.Try to alter the code a little so that it will only download geo-tagged images.
My problems is on step 2. I cant download logged-in user images let alone geo-tagged ones.
I am trying the code provided by Daniel Cukier here
But I am running into problem.
My netbeans simply strike off at the line 77 on .getOriginalAsStream() part, with the error "java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: java.io.ByteArrayOutputStream.write"
From my understanding netbeans striking off a line means , it is depreciated but shouldnt it still work? What is holding this whole problem back?
I have tried researching and basically I have to admit , it is beyond my capability to trouble shoot. If anyone has any idea on what i am doing wrong , I would be so grateful.
Ps: I am not looking to be spoon fed but please answer me in idiot-friendly way as I am still a student and my java isn't the greatest.
This code is what I have so far.
import com.aetrion.flickr.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Properties;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import com.aetrion.flickr.auth.Auth;
import com.aetrion.flickr.auth.AuthInterface;
import com.aetrion.flickr.auth.Permission;
import com.aetrion.flickr.photos.Photo;
import com.aetrion.flickr.photos.PhotoList;
import com.aetrion.flickr.photos.PhotosInterface;
import com.aetrion.flickr.util.IOUtilities;
import java.io.*;
import java.util.Iterator;
import org.apache.commons.io.FileUtils;
public class authenticate {
Flickr f;
RequestContext requestContext;
String frob = "";
String token = "";
Properties properties = null;
public authenticate() throws ParserConfigurationException, IOException, SAXException {
InputStream in = null;
try {
in = getClass().getResourceAsStream("/setup.properties");
properties = new Properties();
properties.load(in);
} finally {
IOUtilities.close(in);
}
f = new Flickr(
properties.getProperty("apiKey"),
properties.getProperty("secret"),
new REST()
);
Flickr.debugStream = false;
requestContext = RequestContext.getRequestContext();
AuthInterface authInterface = f.getAuthInterface();
try {
frob = authInterface.getFrob();
} catch (FlickrException e) {
e.printStackTrace();
}
System.out.println("frob: " + frob);
URL url = authInterface.buildAuthenticationUrl(Permission.DELETE, frob);
System.out.println("Press return after you granted access at this URL:");
System.out.println(url.toExternalForm());
BufferedReader infile =
new BufferedReader ( new InputStreamReader (System.in) );
String line = infile.readLine();
try {
Auth auth = authInterface.getToken(frob);
System.out.println("Authentication success");
// This token can be used until the user revokes it.
System.out.println("Token: " + auth.getToken());
System.out.println("nsid: " + auth.getUser().getId());
System.out.println("Realname: " + auth.getUser().getRealName());
System.out.println("Username: " + auth.getUser().getUsername());
System.out.println("Permission: " + auth.getPermission().getType());
PhotoList list = f.getPhotosetsInterface().getPhotos("72157629794698308", 100, 1);
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Photo photo = (Photo) iterator.next();
File file = new File("/tmp/" + photo.getId() + ".jpg");
ByteArrayOutputStream b = new ByteArrayOutputStream();
b.write(photo.getOriginalAsStream());
FileUtils.writeByteArrayToFile(file, b.toByteArray());
}
} catch (FlickrException e) {
System.out.println("Authentication failed");
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
authenticate t = new authenticate();
} catch(Exception e) {
e.printStackTrace();
}
System.exit(0);
}
}
You are correct in your interpretation of the strikeout that getOriginalAsStream() is deprecated. It looks like you might want to rework your code to use PhotosInterface.getImageAsStream(), passing the ORIGINAL size as one of the arguments.
To adjust NetBeans' behavior with respect to deprecated methods, you can follow the link recommended by #AljoshaBre as well as this one.
If you want download all your photos from Flickr, this is possible if you have a mac computer.
Download Aperture program on Apple Store and install it.
After to install, open the Aperture.
Go on preferences.
Click on 'Accounts' tab.
Click on plus sign (+) on bottom left to add a photo service.
Add the Flicker option.
Follow the login and authorization instructions.
Done! All your photos will be synchronized in you aperture library locate on ~/images/
I hope I have helped.
I need to insert various images in a doc or odt document using java, the images are generated on runtime. At the time I am tempted to use jodreports because it is very easy to generate the template of the final document, but I am stuck because I cannot find any kind of documentation telling me how to insert images. If you can answer my question please post a code snippet or tell me which other library I can use.
Thanks a lot for your help(and sorry for my bad English).
Create a ImageSource-object in your class.
ImageSource imagen =
new RenderedImageSource(ImageIO.read(new File(ruta_fisica_imagen)));
Add this object into Map object
In template define jooscript.image(name)
More information, the document is Spanish
http://www.montesinos.org.es/2010/11/jodreports-mini-how-to.html
In my page https://xbrowser.altervista.org/informatica-portata/odt-converter/
you can find step by step how to implement your question.
Libraries are:
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import net.sf.jooreports.templates.DocumentTemplate;
import net.sf.jooreports.templates.DocumentTemplateException;
import net.sf.jooreports.templates.DocumentTemplateFactory;
import net.sf.jooreports.templates.image.FileImageSource;
This is the method
private Map<String, Object> data = new HashMap<String, Object>();;
private Logger log = Logger.getLogger(this.getClass().getName());
private void createOdt() {
DocumentTemplateFactory documentTemplateFactory = new DocumentTemplateFactory();
DocumentTemplate template = null;
File inputFile = new File("/path/template.odt"); //inserire il path relativo alla posizione del template .odt
try {
template = documentTemplateFactory.getTemplate(inputFile);
log.debug("input file ok -> " + inputFile);
} catch (IOException e) {
log.error(e);
}
try {
tmpFile = File.createTempFile("odt_", ".odt");
data.put("qrcode", new FileImageSource(new File("/img/src/qrcode.jpg"))); //qui รจ possibile generare per esempio un qrcode
template.createDocument(data, new FileOutputStream(tmpFile));
log.debug("output file temporaneo creato ("+ tmpFile.getAbsolutePath() + ")..");
} catch (FileNotFoundException e) {
log.error(e);
} catch (IOException e) {
log.error(e);
} catch (DocumentTemplateException e) {
log.error(e);
}
}
At this point it is necessary that in the .odt template an image is inserted with the following modality:
Insert an image
Double click on the image to go into properties of image
Select "options" tab
In the field "Name" insert: jooscript.image(qrcode)
As you can see the name of the image shows qrcode which is exactly the name of the hashmap key in our code(data.put("qrcode")).
In this way it is possible to show dynamically generated images from the java code in a template defined in .odt.
I hope you have been helpful
Just want to confirm that approach from #Jarabid works.
//visual signature
ImageSource signatureImage =
new RenderedImageSource(ImageIO.read(new File("resources/Signature.png")));
data.put("signature", signatureImage);
I'm using LibreOffice on the Mac and what I did was:
Insert Image From File (used placeholder image)
Double click on image to bring up Picture properties
Select the "Options" tab
In name paste: jooscript.image(signature)
Worked perfectly first try. Happy :)