I'd like to invoke IBM Bluemix service (say Text to Speech) from my Java code.
I've managed to get service credentials and URL but how can I invoke it after?
I've seen some example where people have used similar to below code but wondering how it works for a Text to Speech where it outputs a wav stream.
String profileString = ex.execute(profileRequest)
.handleResponse(new ResponseHandler<String>() {
#Override
public String handleResponse(HttpResponse r)
throws ClientProtocolException, IOException {
}
}
Can any one suggest on priority please?
The link below has a Java code example of how to use the Watson text-to-speech service.
https://github.com/watson-developer-cloud/text-to-speech-java
You should be looking for something like this from the DemoServlet.java class:
#Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
if (req.getParameter("text") == null || req.getParameter("voice") == null) {
req.getRequestDispatcher("/index.jsp").forward(req, resp);
} else {
boolean download = false;
if (req.getParameter("download") != null && req.getParameter("download").equalsIgnoreCase("true")) {
download = true;
}
req.setCharacterEncoding("UTF-8");
try {
String queryStr = req.getQueryString();
String url = baseURL + "/v1/synthesize";
if (queryStr != null) {
url += "?" + queryStr;
}
URI uri = new URI(url).normalize();
Request newReq = Request.Get(uri);
newReq.addHeader("Accept", "audio/ogg; codecs=opus");
Executor executor = Executor.newInstance().auth(username, password);
Response response = executor.execute(newReq);
if (download)
{
resp.setHeader("content-disposition", "attachment; filename=transcript.ogg");
}
ServletOutputStream servletOutputStream = resp.getOutputStream();
response.returnResponse().getEntity()
.writeTo(servletOutputStream);
servletOutputStream.flush();
servletOutputStream.close();
} catch (Exception e) {
// Log something and return an error message
logger.log(Level.SEVERE, "got error: " + e.getMessage(), e);
resp.setStatus(HttpStatus.SC_BAD_GATEWAY);
}
}
}
Finally, the link below has instructions on how to create a Java war file and deploy to Bluemix:
https://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/doc/getting_started/gs-full-java.shtml
I want to call a method based on JSON-RPC request from a servlet I have code like this:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
ServletInputStream in = request.getInputStream();
PrintWriter out = response.getWriter();
String json_request = this.readStream(in);
Object id = null;
try {
JSONRPC2Request reqIn = JSONRPC2Request.parse(json_request);
id = reqIn.getID();
Object params = reqIn.getPositionalParams().toArray();
String method_name = reqIn.getMethod();
Service service = new Service();
Method[] methods = service.getClass().getMethods();
Method method = null;
// getMethod need class as second argument
for (int i=0; i<methods.length; ++i) {
if (methods[i].getName().equals(method_name)) {
method = methods[i];
break;
}
}
if (method != null) {
Object result = method.invoke(service, params);
JSONRPC2Response respOut = new JSONRPC2Response(result, id);
out.println(respOut);
} else {
out.println(JSONRPC2Error.METHOD_NOT_FOUND);
}
} catch (IllegalArgumentException e) {
out.println(new JSONRPC2Response(JSONRPC2Error.INVALID_PARAMS, id));
} catch (IllegalAccessException e) {
out.println(new JSONRPC2Response(JSONRPC2Error.INTERNAL_ERROR, id));
} catch (InvocationTargetException e) {
out.println(new JSONRPC2Response(JSONRPC2Error.INTERNAL_ERROR, id));
} catch (JSONRPC2ParseException e) {
out.println("{\"error\": \"Parse Error: " + e.getMessage() + "\"}");
}
}
I try to call method login from service class:
public class Service {
public String login(String username, String password) {
return "token";
}
}
I call it from javascript using jQuery:
var request = JSON.stringify({
method: "login",
params: ["foo", "Bar"],
id: 1,
jsonrpc: "2.0"
});
$.post('/app/rpc', request, function(res) { console.log(res); });
But I keep getting runtime IllegalArgumentException. What's wrong with my code? I also try to cast params to object with the same result.
I am trying to cache images in an android app with this solution Android image caching. I have already implemented a specific ResponseCache and overriden the get and put methods.
Despite that, images are not properly cached. When I debug I can see that the put method of my ResponseCache implementation is never called. My get method is properly called each time a request is made but never is the put method. Nothing is never cached so it can't retrieve any file...
My request use HTTPS so i was wondering if caching the response was allowed or if i'll have to deal with requesting the server every time I want to display my images.
Here is the code :
public class ImageResponseCache extends ResponseCache {
File cacheDir;
public ImageResponseCache(File cacheDir) {
super();
this.cacheDir = cacheDir;
}
#Override
public CacheResponse get(URI uri, String s,
Map<String, List<String>> headers) throws IOException {
final File file = new File(cacheDir, escape(uri.getPath()));
if (file.exists()) {
return new CacheResponse() {
#Override
public Map<String, List<String>> getHeaders()
throws IOException {
return null;
}
#Override
public InputStream getBody() throws IOException {
return new FileInputStream(file);
}
};
} else {
return null;
}
}
#Override
public CacheRequest put(URI uri, URLConnection urlConnection)
throws IOException {
Log.i("Image Response", "PUT");
final File file = new File(cacheDir, escape(urlConnection.getURL()
.getPath()));
return new CacheRequest() {
#Override
public OutputStream getBody() throws IOException {
return new FileOutputStream(file);
}
#Override
public void abort() {
file.delete();
}
};
}
private String escape(String url) {
return url.replace("/", "-").replace(".", "-");
}
}
Here is the function that request my images in an adapter:
private Bitmap requestImage(String file) {
Bitmap bm = null;
Log.d(TAG, "path: " + file);
URL url = null;
HttpURLConnection http = null;
try {
url = new URL(file);
if (url.getProtocol().toLowerCase().equals("https")) {
NetworkUtils.trustAllHosts();
HttpsURLConnection https = (HttpsURLConnection) url
.openConnection();
https.setHostnameVerifier(NetworkUtils.DO_NOT_VERIFY);
http = https;
} else {
http = (HttpURLConnection) url.openConnection();
}
http.setUseCaches(true);
ResponseCache.setDefault(new ImageResponseCache(
ImageAdapter.this.mContext.getCacheDir()));
http.setRequestProperty(
"Authorization",
"Basic "
+ Base64.encodeToString(
(Constants.USER + ":" + Constants.PASSWORD)
.getBytes(), Base64.NO_WRAP));
http.setConnectTimeout(Constants.TIME_OUT);
bm = BitmapFactory.decodeStream((InputStream) http.getContent());
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
return bm;
}
Does anyone know what could be wrong?
I have this action class, this class takes care of my response
Update now passing response from DownloadStatus class, but it looks like it is null
public final class DownloadStatus extends ActionSupport implements ServletRequestAware,ServletResponseAware
{
static Logger logger = Logger.getLogger(DownloadStatus.class);
private HttpServletRequest request;
private HttpServletResponse response;
private File cfile;
private String cfileFileName;
#Override
public String execute()
{
logger.debug("Inside DownloadStatus.execute method")
try {
ChainsInvoker invoker = new ChainsInvoker()
def executionResponse = invoker.invoke(request, MYChains.download, cfile, cfileFileName)
if(executionResponse == null || ErrorHandler.checkIfError(executionResponse))
{
return ERROR
}
response.setContentType("APPLICATION/xml")
logger.debug("filename: $cfileFileName")
response.addHeader("Content-Disposition", "attachment; filename=\""+cfileFileName+"\"")
response.getWriter().print(executionResponse)
logger.debug("executionResponse :" + executionResponse)
invoker.invoke(MYChains.clean)
}catch (Exception exp) {
logger.error("Exception while Creating Status ")
logger.error(exp.printStackTrace())
}
return NONE
}
#Override
public void setServletRequest(HttpServletRequest request) { this.request = request; }
#Override
public void setServletResponse(HttpServletResponse response) { this.response = response; }
public File getcfile() { cfile }
public void setcfile(File cfile) { this.cfile = cfile }
public String getcfileFileName() { cfileFileName }
public void setcfileFileName(String cfileFileName){ this.cfileFileName = cfileFileName }
}
and below class to write stream into response
class DownloadStatusResponse implements Command {
static Logger logger = Logger.getLogger(DownloadStatusResponse.class);
#Override
public boolean execute(Context ctx) throws Exception
{
logger.debug("Inside DownloadStatusResponse.execute() method")
OutputStream response = null;
if(ctx.get(ContextParams.absFileName) != null && ctx.get(ContextParams.absFileName).toString().trim().length() != 0 )
{
HttpServletResponse resp = ctx.get(ContextParams.response)
/*I am trying to get Response here*/
response=downloadStatusFile(ctx.get(ContextParams.absFileName).toString(),resp)
}
logger.debug("Response: " + response)
ctx.put(ContextParams.response,response); /*ContextParams is a enum of keywords, having response*/
return false;
}
private OutputStream downloadStatusFile(String filename,HttpServletResponse resp)
{
logger.info("Inside downloadStatusFile() method")
File fname = new File(filename)
if(!fname.exists())
{
logger.info("$filename does not exists")
return null
}
else
{
resp.setContentType("APPLICATION/xml")
/*Exception: cannot setContentType on null object*/
resp.addHeader("Content-Disposition", "attachment; filename=\""+fname.getName()+"\"")
FileInputStream istr = new FileInputStream(fname)
OutputStream ostr = resp.getOutputStream()
/*I need to use resp.getOutputStream() for ostr*/
int curByte=-1;
while( (curByte=istr.read()) !=-1)
ostr.write(curByte)
ostr.flush();
}
return ostr
}
}
My question is how can ostr be returned to the response in DownloadStatus class?
Update (working test servlet)
I have this below servlet which does the job of getting file content into a stream and giving it back to the HttpServletResponse, but i want to use it in above code
public class DownloadServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String fileName = req.getParameter("zipFile");
if(fileName == null) return;
File fname = new File(fileName);
System.out.println("filename");
if(!fname.exists()) {System.out.println("Does not exists"); return;}
FileInputStream istr = null;
OutputStream ostr = null;
//resp.setContentType("application/x-download");
resp.setContentType("APPLICATION/ZIP");
resp.addHeader("Content-Disposition", "attachment; filename=\""+fname.getName()+"\"");
System.out.println(fname.getName());
try {
istr = new FileInputStream(fname);
ostr = resp.getOutputStream();
int curByte=-1;
while( (curByte=istr.read()) !=-1)
ostr.write(curByte);
ostr.flush();
} catch(Exception ex){
ex.printStackTrace(System.out);
} finally{
try {
if(istr!=null) istr.close();
if(ostr!=null) ostr.close();
} catch(Exception ex){
ex.printStackTrace();
System.out.println(ex.getMessage());
}
}
try {
resp.flushBuffer();
} catch(Exception ex){
ex.printStackTrace();
System.out.println(ex.getMessage());
}
}
}
As far as I understand all you require is how to download a file using Struts2.
You need something like this is your struts.xml file
<action name="downloadfile" class="DownloadAction">
<result name="success" type="stream">
<param name="contentType">application/pdf</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename="document.pdf"</param>
<param name="bufferSize">1024</param>
</result>
</action>
Code:
public class DownloadAction extends ActionSupport {
private InputStream inputStream;
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public String execute() throws FileNotFoundException {
String filePath = ServletActionContext.getServletContext().getRealPath("/uploads");
File f = new File(filePath + "/nn.pdf");
System.out.println(f.exists());
inputStream = new FileInputStream(f);
return SUCCESS;
}
}
I am trying to get the whole body from the HttpServletRequest object.
The code I am following looks like this:
if ( request.getMethod().equals("POST") )
{
StringBuffer sb = new StringBuffer();
BufferedReader bufferedReader = null;
String content = "";
try {
//InputStream inputStream = request.getInputStream();
//inputStream.available();
//if (inputStream != null) {
bufferedReader = request.getReader() ; //new BufferedReader(new InputStreamReader(inputStream));
char[] charBuffer = new char[128];
int bytesRead;
while ( (bytesRead = bufferedReader.read(charBuffer)) != -1 ) {
sb.append(charBuffer, 0, bytesRead);
}
//} else {
// sb.append("");
//}
} catch (IOException ex) {
throw ex;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
throw ex;
}
}
}
test = sb.toString();
}
and I am testing the functionality with curl and wget as follows:
curl --header "MD5: abcd" -F "fileupload=#filename.txt http://localhost:8080/abcd.html"
wget --header="MD5: abcd" --post-data='{"imei":"351553012623446","hni":"310150","wdp":false}' http://localhost:8080/abcd.html"
But the while ( (bytesRead = bufferedReader.read(charBuffer)) != -1 ) does not return anything, and so I get nothing appended on StringBuffer.
In Java 8, you can do it in a simpler and clean way :
if ("POST".equalsIgnoreCase(request.getMethod()))
{
test = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
}
Easy way with commons-io.
IOUtils.toString(request.getReader());
https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/IOUtils.html
Be aware, that your code is quite noisy.
I know the thread is old, but a lot of people will read it anyway.
You could do the same thing using the guava library with:
if ("POST".equalsIgnoreCase(request.getMethod())) {
test = CharStreams.toString(request.getReader());
}
If all you want is the POST request body, you could use a method like this:
static String extractPostRequestBody(HttpServletRequest request) throws IOException {
if ("POST".equalsIgnoreCase(request.getMethod())) {
Scanner s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
return "";
}
Credit to: https://stackoverflow.com/a/5445161/1389219
This works for both GET and POST:
#Context
private HttpServletRequest httpRequest;
private void printRequest(HttpServletRequest httpRequest) {
System.out.println(" \n\n Headers");
Enumeration headerNames = httpRequest.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = (String)headerNames.nextElement();
System.out.println(headerName + " = " + httpRequest.getHeader(headerName));
}
System.out.println("\n\nParameters");
Enumeration params = httpRequest.getParameterNames();
while(params.hasMoreElements()){
String paramName = (String)params.nextElement();
System.out.println(paramName + " = " + httpRequest.getParameter(paramName));
}
System.out.println("\n\n Row data");
System.out.println(extractPostRequestBody(httpRequest));
}
static String extractPostRequestBody(HttpServletRequest request) {
if ("POST".equalsIgnoreCase(request.getMethod())) {
Scanner s = null;
try {
s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A");
} catch (IOException e) {
e.printStackTrace();
}
return s.hasNext() ? s.next() : "";
}
return "";
}
If the request body is empty, then it simply means that it's already been consumed beforehand. For example, by a request.getParameter(), getParameterValues() or getParameterMap() call. Just remove the lines doing those calls from your code.
This will work for all HTTP method.
public class HttpRequestWrapper extends HttpServletRequestWrapper {
private final String body;
public HttpRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
body = IOUtils.toString(request.getReader());
}
#Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(getBody().getBytes());
ServletInputStream servletInputStream = new ServletInputStream() {
public int read() throws IOException {
return byteArrayInputStream.read();
}
#Override
public boolean isFinished() {
return false;
}
#Override
public boolean isReady() {
return false;
}
#Override
public void setReadListener(ReadListener listener) {
}
};
return servletInputStream;
}
public String getBody() {
return this.body;
}
}
Easiest way I could think of:
request.getReader().lines().reduce("",String::concat)
However, this will be one long string which you will have to parse. IF you send a username of tim and a password of 12345. The output of the code above would look like this:
{ "username":"tim", "password": "12345"}
Please be aware
Please be aware that with the reduce() method we are performing a Mutable Reduction which does a great deal of string copying and has a runtime of O(N^2) with N being the number of characters. Please check the Mutable Reduction documentation if you need a more performant result.
I resolved that situation in this way. I created a util method that return a object extracted from request body, using the readValue method of ObjectMapper that is capable of receiving a Reader.
public static <T> T getBody(ResourceRequest request, Class<T> class) {
T objectFromBody = null;
try {
ObjectMapper objectMapper = new ObjectMapper();
HttpServletRequest httpServletRequest = PortalUtil.getHttpServletRequest(request);
objectFromBody = objectMapper.readValue(httpServletRequest.getReader(), class);
} catch (IOException ex) {
log.error("Error message", ex);
}
return objectFromBody;
}
I personnally use this code (on a dev server, not in production). Seems to work. The main difficulty is that once you read the request body, it will be lost and not transferred to the app. So you have to "cache" it first.
/* Export this filter as a jar and place it under directory ".../tomcat/lib" on your Tomcat server/
In the lib directory, also place the dependencies you need
(ex. org.apache.commons.io => commons-io-2.8.0.jar)
Once this is done, in order to activate the filter, on the Tomcat server:
o in .../tomcat/conf/server.xml, add:
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="localhost_access_log" suffix=".txt" pattern="%h %l %u %t "%r" [%{postdata}r] %s %b"/>
=> the server will log the "postdata" attribute we generate in the Java code.
o in .../tomcat/conf/web.xml, add:
<filter>
<filter-name>post-data-dumper-filter</filter-name>
<filter-class>filters.PostDataDumperFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>post-data-dumper-filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Once you've done this, restart your tomcat server. You will get extra infos in file "localhost_access_log.<date>.txt"
*/
package filters;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.stream.Collectors;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.io.IOUtils;
class MultiReadHttpServletRequest extends HttpServletRequestWrapper {
private ByteArrayOutputStream cachedBytes;
public MultiReadHttpServletRequest(HttpServletRequest request) {
super(request);
}
#Override
public ServletInputStream getInputStream() throws IOException {
if (cachedBytes == null)
cacheInputStream();
return new CachedServletInputStream();
}
#Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
private void cacheInputStream() throws IOException {
/* Cache the inputstream in order to read it multiple times.
*/
cachedBytes = new ByteArrayOutputStream();
IOUtils.copy(super.getInputStream(), cachedBytes);
}
/* An input stream which reads the cached request body */
public class CachedServletInputStream extends ServletInputStream {
private ByteArrayInputStream input;
public CachedServletInputStream() {
/* create a new input stream from the cached request body */
input = new ByteArrayInputStream(cachedBytes.toByteArray());
}
//---------------------
#Override
public int read() throws IOException {
return input.read();
}
#Override
public boolean isFinished() {
return input.available() == 0;
}
#Override
public boolean isReady() {
return true;
}
//---------------------
#Override
public void setReadListener(ReadListener arg0) {
// TODO Auto-generated method stub
// Ex. : throw new RuntimeException("Not implemented");
}
}
}
public final class PostDataDumperFilter implements Filter {
private FilterConfig filterConfig = null;
public void destroy() {
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (filterConfig == null)
return;
StringBuffer output = new StringBuffer();
output.append("PostDataDumperFilter-");
/* Wrap the request in order to be able to read its body multiple times */
MultiReadHttpServletRequest multiReadRequest = new MultiReadHttpServletRequest((HttpServletRequest) request);
// TODO : test the method in order not to log the body when receiving GET/DELETE requests ?
// I finally leave it "as it", since I've seen GET requests containing bodies (hell...).
output.append("Content-type=" + multiReadRequest.getContentType());
output.append(" - HTTP Method=" + multiReadRequest.getMethod());
output.append(" - REQUEST BODY = " + multiReadRequest.getReader().lines().collect(Collectors.joining(System.lineSeparator())));
// Log the request parameters:
Enumeration names = multiReadRequest.getParameterNames();
if (names.hasMoreElements()) {
output.append("- REQUEST PARAMS = ");
}
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
output.append(name + "=");
String values[] = multiReadRequest.getParameterValues(name);
for (int i = 0; i < values.length; i++) {
if (i > 0) output.append("' ");
output.append(values[i]);
}
if (names.hasMoreElements()) output.append("&");
}
multiReadRequest.setAttribute("postdata", output);
chain.doFilter(multiReadRequest, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
}