I'm using GeoTools 12.2 for developing java class library project.
Firstly, I'm working on GeoTools WMS module with this guide.
The point that I was failed is doing get map request so that I could get capabilities document and layers etc.
My wms url http://sampleserver1.arcgisonline.com/ArcGIS/services/Specialty/ESRI_StatesCitiesRivers_USA/MapServer/WMSServer
It contains 3 layers (States,Rivers,Cities)
I'm using structure to get map operation like below.
GetMapRequest getMapRequest = wms.createGetMapRequest();//wms is my WebMapServer object
getMapRequest.addLayer(tempLayer);//tempLayer contains states layer
GetMapResponse response = (GetMapResponse) wms.issueRequest(getMapRequest);
BufferedImage image = ImageIO.read(response.getInputStream());
I also tried other methods in guide to do GetMapRequest but I can't succeed, always getting NullPointerException to BufferedImage object.
What is your suggestions? Thanks in advance.
You need to set some more parameters for your request, the WMS getMapResponse doesn't provide any defaults for several of them (as they are unique to your request/map). So you need at least the following:
private BufferedImage getLayer(Layer l) {
GetMapRequest getMapRequest = wms.createGetMapRequest();
getMapRequest.addLayer(l);
getMapRequest.setBBox(l.getEnvelope(DefaultGeographicCRS.WGS84));
getMapRequest.setDimensions(200, 400);
getMapRequest.setFormat("image/png");
getMapRequest.setSRS("CRS:84");
System.out.println(getMapRequest.getFinalURL());
try {
GetMapResponse response = wms.issueRequest(getMapRequest);
BufferedImage image = ImageIO.read(response.getInputStream());
return image;
} catch (ServiceException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
In general to avoid getting an empty image you can do some error checking on the response:
if (response.getContentType().equalsIgnoreCase("image/png")) {
BufferedImage image = ImageIO.read(response.getInputStream());
return image;
} else {
StringWriter writer = new StringWriter();
IOUtils.copy(response.getInputStream(), writer);
String error = writer.toString();
System.out.println(error);
return null;
}
which will give you an XML encoded error to tell you what went wrong:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<ServiceExceptionReport version="1.3.0"
xmlns="http://www.opengis.net/ogc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.opengis.net/ogc http://schemas.opengis.net/wms/1.3.0/exceptions_1_3_0.xsd">
<ServiceException code="InvalidFormat">
Parameter 'bbox' can not be empty.
</ServiceException>
</ServiceExceptionReport>
Related
sorry if this has been asked quite a few times, I'm new here.
I've used three different approaches to get a file to be loaded and nothing worked:
Using Toolkit:
Image image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("apple.png"));
Using a File:
BufferedImage img = null;
try {
img = ImageIO.read(new File("apple.png"));
} catch(IOException e) {
e.printStackTrace();
}
Using a FileInputStream:
Path path=Paths.get(".").toAbsolutePath().normalize();
String dir=path.toFile().getAbsolutePath()+"\\resources\\apple.png";
BufferedImage image = null;
try {
image = ImageIO.read(new FileInputStream(dir));
} catch(IOException e) {
e.printStackTrace();
}
path and dir are working fine getting me an absolute path but I alway end up with image = null.
/edit:
#DuncG: I don't get an exception so there's no stacktrace to post, sorry. new File("apple.png").exists() evaluates to false.
#Harald_K: It is a normal .png image-file I have on my local system. It is located in src/main/resources/apple.png.
The issue is that your program is NOT able to find the required file and then further read it as an Image. This is a common recurring problem statement in any modern-day app where a required resource is NOT found, halting subsequent operations.
I would suggest writing a common piece of code to always locate such files/resources in your project dir just by giving the filename and returning the path.
#Slf4j
public class PathFinder {
private static Path filepath;
public static Path getFilePathForFile(String filename) {
log.info("Looking for filepath for given filename: ".concat(filename));
try {
filepath = Files.walk(Paths.get("."))
.collect(Collectors.toList()).stream()
.filter(file -> !Files.isDirectory(file) &&
file.getFileName().toString().startsWith(filename))
.findFirst().get();
} catch (IOException exception) {
log.error(exception.getMessage());
} return filepath;
}
}
Now you can easily use the above Pathfinder utility class to look for any given file and further operate on it as shown below:
BufferedImage img = ImageIO.read(PathFinder.getFilePathForFile("apple.png")
.toFile());
I've decided to use Glen K Peterson's Pdf Layout Manager available on GitHub(https://github.com/GlenKPeterson/PdfLayoutManager) to generate PDF documents with my app, I've imported the source files and the pom.xml dependencies and everything, it's working just fine.
The problem is, I'm trying to build a table in one of the documents I want to generate with a button click. I have no idea how to extract(use) the TableBuilder, as I'm getting the error message inside my JDeveloper IDE, that the class has private access.
Here's my code:
private void jBtnSalvareVerMetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnSalvareVerMetActionPerformed
// TODO add your handling code here:
PDDocument document = new PDDocument();
try {
PDPage page = new PDPage();
document.addPage(page);
PDFont font = PDType1Font.COURIER;
PDPageContentStream contents = new PDPageContentStream(document, page);
contents.beginText();
contents.setFont(font, 14);
contents.newLineAtOffset(50, 500);
Coord coordinate = new Coord(10, 700);
PdfLayoutMgr pageMgr = PdfLayoutMgr.newRgbPageMgr();
LogicalPage locatieTabel = pageMgr.logicalPageStart();
TableBuilder tabel = new TableBuilder(locatieTabel, coordinate); // Getting the error at this point
contents.newLineAtOffset(10, 700);
contents.showText(tabel.toString());
contents.endText();
contents.close();
} catch (IOException ex) {
java.util.logging.Logger.getLogger(MeniuTaburi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} finally {
try {
document.close();
} catch (IOException ex) {
java.util.logging.Logger.getLogger(MeniuTaburi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
}
jLabelAverstismenteVerMet.setText("<html><center>Datele au fost salvate cu succes!</center></html>");
}//GEN-LAST:event_jBtnSalvareVerMetActionPerformed
I thought of changing the type of access permission from private to public, for the TableBuilder, but I don't think, that's the way it's actually supposed to work...
Is there any other way, I can build the table I need, without resorting to changing the access modifier, inside the TableBuilder class??
You try to use
TableBuilder tabel = new TableBuilder(locatieTabel, coordinate); // Getting the error at this point
But that constructor is private
private TableBuilder(LogicalPage lp, Coord tl) {
logicalPage = lp; topLeft = tl;
}
I.e. you are not meant to use it. Unfortunately there also is no JavaDoc indicating what you should use instead. But looking at the TableBuilder source a bit beyond that constructor, you'll find immediately following this:
public static TableBuilder of(LogicalPage lp, Coord tl) {
return new TableBuilder(lp, tl);
}
Thus, instead of your direct constructor call you should use this factory method:
TableBuilder tabel = TableBuilder.of(locatieTabel, coordinate);
I am currently using the Apache FOP library to generate PDF's. I want these PDF's protected from copy-pasting, so people would have to use actual OCR libraries (or manual typing) to get the information on the PDF.
FOP apparently offers some security, which then is added as meta-data on the PDF, to protect from things like printing or copying, but this doesn't seem to work properly (can't disable the copy-pasting when printing is enabled, etc).
A possibility which seemed straight forward to me is basically somehow transforming all the text on the PDF's to images, but I can't find any information on the matter.
Obviously I don't care if the PDF is searchable or not. I just want to prevent people from copy-pasting while they should still be able to print it.
My current FOP code:
private static FopFactory fopFactory;
private static FopFactory initializeFactory() throws IOException,
SAXException {
if (fopFactory == null) {
File f = new File(SettingUtil.getSetting(LetterGeneratorSettings.FOP_CONFIG_LOCATION));
fopFactory = FopFactory.newInstance(f);
}
return fopFactory;
}
public static File generatePDFFromXML(File fopTemplate, File xmlSource,
File resultFileLocation) throws IOException {
try {
initializeFactory();
URL url = fopTemplate.toURI().toURL();
// creation of transform source
StreamSource transformSource = new StreamSource(url.openStream());
// create an instance of fop factory
// a user agent is needed for transformation
FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
foUserAgent.getRendererOptions().put("encryption-params",
getEncryptionParams());
// to store output
ByteArrayOutputStream pdfoutStream = new ByteArrayOutputStream();
StreamSource source = new StreamSource(new ByteArrayInputStream(IOUtils.toByteArray(new FileInputStream(xmlSource))));
Transformer xslfoTransformer;
try {
TransformerFactory transfact = TransformerFactory.newInstance();
xslfoTransformer = transfact.newTransformer(transformSource);
// Construct fop with desired output format
Fop fop;
try {
fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, pdfoutStream);
// Resulting SAX events (the generated FO)
// must be piped through to FOP
Result res = new SAXResult(fop.getDefaultHandler());
// Start XSLT transformation and FOP processing
try {
// everything will happen here..
xslfoTransformer.transform(source, res);
// if you want to save PDF file use the following code
OutputStream out = new java.io.FileOutputStream(resultFileLocation);
out = new java.io.BufferedOutputStream(out);
FileOutputStream str = new FileOutputStream(resultFileLocation);
str.write(pdfoutStream.toByteArray());
str.close();
out.close();
} catch (TransformerException e) {
e.printStackTrace();
}
} catch (FOPException e) {
e.printStackTrace();
}
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
e.printStackTrace();
}
return resultFileLocation;
} catch (Exception ex) {
throw new IOException(ex);
}
}
private static PDFEncryptionParams getEncryptionParams() {
return new PDFEncryptionParams(null,
SettingUtil.getSetting(LetterGeneratorSettings.PDF_PASSWORD),
true, false, false, false, false);
}
The following is the contents of my fopconfig.xml
<fop version="1.0">
<!-- Strict user configuration -->
<strict-configuration>false</strict-configuration>
<!-- Strict FO validation -->
<strict-validation>false</strict-validation>
<!-- Base URL for resolving relative URLs -->
<base>./</base>
<!-- Font Base URL for resolving relative font URLs -->
<font-base>./</font-base>
<!-- Source resolution in dpi (dots/pixels per inch) for determining the size of pixels in SVG and bitmap images, default: 72dpi -->
<source-resolution>72</source-resolution>
<!-- Target resolution in dpi (dots/pixels per inch) for specifying the target resolution for generated bitmaps, default: 72dpi -->
<target-resolution>72</target-resolution>
<!-- default page-height and page-width, in case
value is specified as auto -->
<default-page-settings height="11in" width="8.26in"/>
<!-- etc. etc..... -->
</fop>
I am not sure how it works with Apache FOP but it is quite easy with iText lib.
Here a tutorial i wrote a while back ago about this http://tutors4all.net/index.php/2015/05/06/encrypt-pdf-file/
This shouldn't be that hard, but I cannot figure this out. I need to save an image, on my end only, and build it dynamically so all my users will view these images. The tutorials on Parse.com are very helpful, but not in the case of images. I need detailed explanations or helpful links. Thanks for looking.
This is all I have so far as far as saving an image. I am properly getting the file in my Data Browser, but if I try to view it, it only shows my string "beatdown.jpg" not the actual jpg.
....
private void saveImage() {
// TODO Auto-generated method stub
InputStream header = new FileInputStream("beatdown.jpg");
byte[] head = IOUtils.toByteArray(header);
ParseFile file = new ParseFile(head);
try{
file.save();
} catch (ParseException e) {
e.printStackTrace();
}
ParseObject displayImage = new ParseObject("displayImage");
displayImage.put("header", file);
try{
displayImage.save();
} catch (ParseException e1){
e1.printStackTrace();
}
}
I understand I am trying to get the string of "beatdown.jpg" to bytes in the code above, and it is not handling it as a .jpg. But I don't know how to make it a .jpg.
EDIT: I added commons-io. But when I run the code (see the above updated code), it won't register on anything on parse.com. I am getting this in my logcat;
Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection#40cf2498 that was originally bound here
The key elements are:
File f = new File("pathToFile");
FileInputStream fis = new FileInputStream(f);
byte[] bytes = new byte[f.length()];
fis.read(bytes);
Of course there's exception handling and the like to do, but this should be enough to give you the general idea.
We work on a Java (Java EE) application, and we generate XML files in order to send them to a remote .NET application with MSMQ reading on their side.
The XML file is generated by JDom, like so :
// add elements...
Document doc = new Document(root);
String XmlData = new XMLOutputter(Format.getPrettyFormat().setOmitEncoding(true)).outputString(doc);
try {
SendFile( XmlData, "title" , "path");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MessageQueueException e) {
e.printStackTrace();
}
Then we use this function, using the MsmqJava library to send the file :
private void SendFile(String data, String title, String outputPath) throws UnsupportedEncodingException, MessageQueueException{
String qname="name_of_the_queue";
String fullname= "server_path" + qname;
String body = data;
String label = title;
String correlationId= "L:none";
try {
Queue queue= new Queue(fullname);
Message msg= new Message(body, label, correlationId);
queue.send(msg);
} catch (MessageQueueException ex1) {
System.out.println("Put failure: " + ex1.toString());
}
}
They correctly receive the file, but they told us that the bodyType was set to "VT_EMPTY" while they wanted "VT_BSTR", and we haven't find a clue about how to fix this. If you know another lib who does the job, or a workaround to this one, we can change with no problem.
Thanks !
Looking at the documentation for the library you use, it is not possible using that library.
Jmsmqqueue also doesn't provide the functionality you need.
It seems sun also had an adapter: https://wikis.oracle.com/display/JavaCAPS/Sun+Adapter+for+MSMQ