I have a screenshot that I have got from the browser through the javascript code converted into string (type). I need Web Service that could read this string and convert it into image on the server side.
The question is:
How should I make a web Service that would be posible to read the string from browser and convert it into image to the server side.
Below the code is shown
package com.myfirst.wsServer;
import java.io.FileOutputStream;
import java.util.UUID;
import javax.jws.WebService;
import org.apache.commons.codec.binary.Base64;
#WebService
public class ConvertToImage {
/**
* Convert input string image to image
* #param imageDataString
*/
public static void StringToImage(String imageDataString){
try {
// Converting a Base64 String into Image byte array
byte[] imageByteArray = decodeImage(imageDataString);
// Write a image byte array into file system
FileOutputStream imageOutFile = new FileOutputStream("D:\\" + getNewFileName() + ".png");
imageOutFile.write(imageByteArray);
imageOutFile.close();
System.out.println("Image Successfully Manipulated!");
}
catch (Exception e) {
// TODO: handle exception
}
}
/**
* Encodes the byte array into base64 string
*
* #param imageByteArray - byte array
* #return String
*/
public static String encodeImage(byte[] imageByteArray) {
return Base64.encodeBase64URLSafeString(imageByteArray);
}
/**
* Decodes the base64 string into byte array
*
* #param imageDataString
* #return byte array
*/
public static byte[] decodeImage(String imageDataString) {
return Base64.decodeBase64(imageDataString);
}
/**
* Generate uuid an convert to String
* #return uuid.toString()
*/
public static String getNewFileName(){
UUID uuid = UUID.randomUUID();
return uuid.toString();
}
}
Any questions or suggestions are welcomed
Thank you
PS: If you could help me and you are interested in javasvript code I can share it.
Related
I am trying to export HTML page into a PDF using iText7.1.0 and pdfHTML2.0.0. For some reason, the pages have formatting issue for the Pie chart images (aligned horizontally in HTML whereas vertically aligned in PDF) and the table (titled "Features") on left is pushed down vertically. The jsFiddle link to my HTML code that is being used by PDF renderer.
Below is the Java code used for rendering the PDF (Page1.html is the same HTML code in the fiddle):
/*
* Copyright 2016-2017, iText Group NV.
* This example was created by Bruno Lowagie.
* It was written in the context of the following book:
* https://leanpub.com/itext7_pdfHTML
* Go to http://developers.itextpdf.com for more info.
*/
package com.itextpdf.htmlsamples.chapter01;
import java.io.File;
import java.io.IOException;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.licensekey.LicenseKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Converts a simple HTML file to PDF using File objects
* as arguments for the convertToPdf() method.
*/
public class C01E03_HelloWorld {
/** The Base URI of the HTML page. */
public static final String BASEURI = "src/main/resources/html/";
/** The path to the source HTML file. */
public static final String SRC = String.format("%sPage1.html", BASEURI);
/** The target folder for the result. */
public static final String TARGET = "target/results/ch01/";
/** The path to the resulting PDF file. */
public static final String DEST = String.format("%stest-03.pdf", TARGET);
/**
* The main method of this example.
*
* #param args no arguments are needed to run this example.
* #throws IOException Signals that an I/O exception has occurred.
*/
public static void main(String[] args) throws IOException {
LicenseKey.loadLicenseFile("C://Users//Sparks//Desktop//itextkey-0.xml");
File file = new File(TARGET);
file.mkdirs();
new C01E03_HelloWorld().createPdf(BASEURI, SRC, DEST);
}
/**
* Creates the PDF file.
*
* #param baseUri the base URI
* #param src the path to the source HTML file
* #param dest the path to the resulting PDF
* #throws IOException Signals that an I/O exception has occurred.
*/
public void createPdf(String baseUri, String src, String dest) throws IOException {
HtmlConverter.convertToPdf(new File(src), new File(dest));
}
}
The output PDF file is here. It should have formatting similar to the one in HTML page.
Any suggestions would be helpful.
I have a java echo httpserver up.
It works with test sites, but the client code I'm working with fails to get the data.
The server works perfectly with https://www.hurl.it/
The client works perfectly with https://requestb.in/ and http://httpbin.org/post
When combining the two I get a response with a status code of 200, but no metadata / body content shows up in the client even though it's being sent.
My only guess is because the content type isn't included, the client might be picky about that.
How can i specify the content type in my response?
(A note, the client sends a single string to the server with a POST as a parameter along with some header info. This code is currently setup to only return the body content/parameter.)
Any ideas appreciated!
import static java.net.HttpURLConnection.HTTP_OK;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.util.List;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
/**
* Echo the body of an HTTP request back as the HTTP response. This is merely
* a simple exercise of the Secret Sun Web Server. As configured, the URL to
* access it is http://localhost:8000/echo.
*
* #author Andrew Cowie
*/
public final class Test
{
public static void main(String[] args) throws IOException {
final InetSocketAddress addr;
final HttpServer server;
addr = new InetSocketAddress(8000);
server = HttpServer.create(addr, 10);
server.createContext("/echo", new EchoHandler());
server.start();
}
}
class EchoHandler implements HttpHandler
{
public void handle(HttpExchange t) throws IOException {
final InputStream is;
final OutputStream os;
StringBuilder buf;
int b;
final String request, response;
buf = new StringBuilder();
/*
* Get the request body and decode it. Regardless of what you are
* actually doing, it is apparently considered correct form to consume
* all the bytes from the InputStream. If you don't, closing the
* OutputStream will cause that to occur
*/
is = t.getRequestBody();
while ((b = is.read()) != -1) {
buf.append((char) b);
}
is.close();
if (buf.length() > 0) {
request = URLDecoder.decode(buf.toString(), "UTF-8");
} else {
request = null;
}
/*
* Construct our response:
*/
buf = new StringBuilder();
//buf.append("<html><head><title>HTTP echo server</title></head><body>");
//buf.append("<p><pre>");
//buf.append(t.getRequestMethod() + " " + t.getRequestURI() + " " + t.getProtocol() + "\n");
/*
* Process the request headers. This is a bit involved due to the
* complexity arising from the fact that headers can be repeated.
*/
Headers headers = t.getRequestHeaders();
for (String name : headers.keySet()) {
List<String> values = headers.get(name);
for (String value : values) {
//buf.append(name + ": " + value + "\n");
}
}
/*
* If there was an actual body to the request, add it:
*/
if (request != null) {
//buf.append("\n");
buf.append(request);
}
//buf.append("</pre></p>");
//buf.append("</body></html>\n");
response = buf.toString();
System.out.println(response);
/*
* And now send the response. We could have instead done this
* dynamically, using 0 as the response size (forcing chunked
* encoding) and writing the bytes of the response directly to the
* OutputStream, but building the String first allows us to know the
* exact length so we can send a response with a known size. Better :)
*/
t.sendResponseHeaders(HTTP_OK, response.length());
os = t.getResponseBody();
os.write(response.getBytes());
/*
* And we're done!
*/
os.close();
t.close();
}
}
Try to add
t.getResponseHeaders().put("Content-Type", "text/html");
before writing
It seems the interface has been changed since the answer. In Java 11 you need:
t.getRequestHeaders().put("Content-Type", Collections.singletonList("text/html"));
In Java 17 either:
t.getResponseHeaders().set("Content-Type", "text/html");
Or:
t.getResponseHeaders().put("Content-Type", Collections.singletonList("text/html"));
Also, adding works, though being more specific:
t.getResponseHeaders().add("Content-Type", "text/html");
Sources:
com.sun.net.httpserver.HttpExchange — getResponseHeaders()
com.sun.net.httpserver.Headers — set(), put(), add()
I am looking for a simple java function that can accept an address and return the longitude and latitude coordinates for that address. Based on my research this is what i found thus far:
I am abit unsure how to implements this. I am not sure what order i will need to call the different methods.
E.g. would i have to do this? :
String address = 'Some Place, Venezuela';
Geocoder geo = new Geocoder();
String url = geo.encode(address);
String encodeUrl = geo.urlEncode(url);
GLatLng latLng = geo.decode(encodeUrl);
If there are others that you have used feel free to share it.
/*
*
* ==============================================================================
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.wicketstuff.gmap.geocoder;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.StringTokenizer;
import org.wicketstuff.gmap.api.GLatLng;
/**
* Geocoder. See: http://www.google.com/apis/maps/documentation/services.html# Geocoding_Direct
*
* #author Thijs Vonk
*/
public class Geocoder implements Serializable
{
private static final long serialVersionUID = 1L;
// Constants
public static final String OUTPUT_CSV = "csv";
public static final String OUTPUT_XML = "xml";
public static final String OUTPUT_KML = "kml";
public static final String OUTPUT_JSON = "json";
private final String output = OUTPUT_CSV;
public Geocoder()
{
}
public GLatLng decode(String response) throws GeocoderException
{
StringTokenizer gLatLng = new StringTokenizer(response, ",");
String status = gLatLng.nextToken();
gLatLng.nextToken(); // skip precision
String latitude = gLatLng.nextToken();
String longitude = gLatLng.nextToken();
if (Integer.parseInt(status) != GeocoderException.G_GEO_SUCCESS)
{
throw new GeocoderException(Integer.parseInt(status));
}
return new GLatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
}
/**
* builds the google geo-coding url
*
* #param address
* #return
*/
public String encode(final String address)
{
return "http://maps.google.com/maps/geo?q=" + urlEncode(address) + "&output=" + output;
}
/**
* #param address
* #return
* #throws IOException
*/
public GLatLng geocode(final String address) throws IOException
{
InputStream is = invokeService(encode(address));
if (is != null)
{
try
{
String content = org.apache.wicket.util.io.IOUtils.toString(is);
return decode(content);
}
finally
{
is.close();
}
}
return null;
}
/**
* fetches the url content
*
* #param address
* #return
* #throws IOException
*/
protected InputStream invokeService(final String address) throws IOException
{
URL url = new URL(address);
return url.openStream();
}
/**
* url-encode a value
*
* #param value
* #return
*/
private String urlEncode(final String value)
{
try
{
return URLEncoder.encode(value, "UTF-8");
}
catch (UnsupportedEncodingException ex)
{
throw new RuntimeException(ex.getMessage());
}
}
}
If you're using Google Maps API, you need to show a map with your application in order to use the data, as far as I understand their TOS.
Here's an example on GitHub that uses an address verification API from SmartyStreets to verify a US address and get the coordinates. There license restrictions are much more lenient this way. (I work at SmartyStreets and actually wrote this particular example.)
Alternatively, there's a small library for massively-batch geocoding in Java by exoanalytic.
I know the image is valid because I can convert the IplImage to an Image and even draw it on a JPanel. But when I convert a byte array to an Image most of the time I get null reference to an Image. Look at this code below to get a picture what I am facing with and comments, questions, answers are all welcome and even tips are all welcome.
Image i = Convert.getImage(image);
byte[] buffer = Convert.getBytes(image);
Image i2 = Convert.getImage(buffer);
//i2 is a null reference and i is a valid image. i can be drawn but i2 is useless.
Convert class:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Security;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.ByteArrayInputStream;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
/**
*
* #author danny
*/
public final class Convert
{
public static Image getImage(IplImage image)
{
return image.getBufferedImage();
}
public static byte[] getBytes(IplImage image)
{
byte[] buffer;
BufferedImage bI = image.getBufferedImage();
buffer = ((DataBufferByte) (bI).getRaster().getDataBuffer()).getData();
return buffer;
}
public static String getString(byte[] buffer)
{
return new String(buffer);
}
public static Image getImage(byte[] buffer)
{
try
{
Image i = ImageIO.read(new ByteArrayInputStream(buffer));
return i;
}
catch (Exception e)
{
System.out.printf("Exception Message:\n%s", e.getMessage() );
return null;
}
}
}
Now some of you may ask why do I need as a byte array. Well because I need to send across a network.
Extra Things To Be Aware Of:
No exception is being thrown
IplImage is a valid object
Update:
I have tried using the ToolKit class to create an image from a byte array. But it fails probably because it is not a JPEG or GIF. Although it does return a valid Image object the Image object is pointing to an image that is blank. Here is the code I was trying to use but failed to do so.
public static Image getImage(byte[] buffer)
{
try
{
Toolkit toolkit = Toolkit.getDefaultToolkit();
Image i = toolkit.createImage(buffer);
return i;
}
catch (Exception e)
{
System.out.printf("Exception Message:\n%s", e.getMessage() );
return null;
}
}
DataBufferByte.getData will: "Returns the default (first) byte data array." The first bank that is. That seems an uncertain, incomplete way to get the bytes; especially on the way back. Besides there is the implementation dependent cast from DataBuffer to DataBufferByte.
ImageIO can write to an OutputStream, for instance to a ByteArrayOutputStream, of which you can take the bytes. And on the other side ImageIO can read it in again. That is not the pure only-pixel-data you had in mind, but fool-proof.
I'm using a rdf crawler, in that I had a class named as:
import edu.unika.aifb.rdf.crawler.*;
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.util.FileManager;
These are class file termed as error, and I try with jena packages but I had attached, it does not make any changes.
Update:
Full SampleCrawl.java class content:
import java.util.*;
import edu.unika.aifb.rdf.crawler.*;
/**
* Call this class with 3 arguments - URL to crawl to,
* depth and time in seconds
*/
public class SampleCrawl {
/**
* #param uRI
* #param depth
* #param time
*/
#SuppressWarnings("rawtypes")
public SampleCrawl(Vector uRI, Vector hf, int depth, int time){
// Initialize Crawling parameters
CrawlConsole c = new CrawlConsole(uRI,hf,depth,time);
// get an ontology file from its local location
// (OPTIONAL)
c.setLocalNamespace("http://www.daml.org/2000/10/daml-ont","c:\\temp\\rdf\\schemas\\daml-ont.rdf");
// set all the paths to get all the results
c.setLogPath("c:\\temp\\crawllog.xml");
c.setCachePath("c:\\temp\\crawlcache.txt");
c.setModelPath("c:\\temp\\crawlmodel.rdf");
try{
// crawl and get RDF model
c.start();
// This writes all three result files out
c.writeResults();
}catch(Exception e){
}
}
/**
* #param args
* #throws Exception
*/
#SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) throws Exception {
if (args.length != 3) {
System.err.println("Usage: java -cp [JARs] SampleCrawl [URL] [depth:int] [time:int]");
System.exit(0);
}
Vector uris = new Vector();
uris.add(args[0]);
// no host filtering - crawl to all hosts
Vector hostfilter = null;
/* You may want to do something else to enable host filtering:
* Vector hostfilter = new Vector();
* hostfilter.add("http://www.w3.org");
*/
int depth = 2;
int time = 60;
try {
depth = Integer.parseInt(args[1]);
time = Integer.parseInt(args[2]);
}
catch (Exception e) {
System.err.println("Illegal argument types:");
System.err.println("Argument list: URI:String depth:int time(s):int");
System.exit(0);
}
new SampleCrawl(uris,hostfilter,depth,time);
}
}
Question:
How to add import edu.unika.aifb.rdf.crawler.; error occurs here
I googled the package that you're trying to import, and it appears that you're using Kaon. Assuming that's so, you have made an error in your import declaration. You have:
import edu.unika.aifb.rdf.crawler.*;
whereas the download available on SourceForge would require:
import edu.unika.aifb.rdf.rdfcrawler.*;
As an aside, it would be helpful if you would include information, such as "I'm trying to use Kaon's rdfcrawler from ..." in your question. Otherwise, we have to try to guess important details in your setup.