How to input the payload into a custom connector mule 4 - java-8

Trying to pass my custom connector the payload as a argument. Currently I've given it the type of a byte array, as that is the format I need it in. It worked when I was using it as an invoke static. But now it doesn't like taking the payload as an argument.
#MediaType(value = ANY, strict = false)
public void uploadFileStream(#Config WebDAVConfiguration configuration, String directoryName, String filename, byte[] data) throws IOException {
Sardine sardine = SardineFactory.begin(configuration.getUserName(),configuration.getPassword());
sardine.put(searchForResource(sardine, configuration.getbasePath(), directoryName)+filename,data);
}
Error I recieve:
Message : "Cannot instantiate class '[B' Caused by: [B" evaluating expression: "payload".
Element : pricebook_putdatastream_flow/processors/4 # pricebook_conversion:pricebook_conversion.xml:48 (Upload file stream)
Element DSL : <webdav:upload-file-stream doc:name="Upload file stream" doc:id="981aded3-0aa8-4e44-a8aa-7ed44fda1894" config-ref="Webdav_Config" directoryName="#[vars.dirname]" filename="#[vars.filename]" data="#[payload]"></webdav:upload-file-stream>
Error type : MULE:EXPRESSION
FlowStack : at pricebook_putdatastream_flow(pricebook_putdatastream_flow/processors/4 # pricebook_conversion:pricebook_conversion.xml:48 (Upload file stream))

Related

Bufferedreader and InputStreamReader

I am having trouble getting my java program to read any text files.
public static void main(String[] args) throws java.io.IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
try {
long base = Long.parseLong(args[0]);
String input = br.readLine(); //read first line till the end of file
long list = Long.parseLong(input);
convertBase(base, list);
}
finally {
br.close();
}
}
The program works when I manually type the values into the command line, but when I try to use a text file it throws exceptions:
Exception in thread "main" java.lang.NumberFormatException: For input string: "baseconverion.txt"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:589)
at java.lang.Long.parseLong(Long.java:631)
at FromDecimal.main(FromDecimal.java:46)
Not sure what I am doing wrong/missing.
when I try to use a text file
You mean 'when I enter a filename instead of a number'. You aren't 'try[ing]' to use a text file' at all. All you're doing is entering a filename at the console. There is nothing here that opens or reads a text file whatsoever. Java is not magic: it won't magically realize that's a filename and magically open it for you.
You need to read about file I/O in the Java Tutorial and the Javadoc.
You also shouldn't be using Long.parseLong() if your objective is to convert decimal into another base. You need to pass the original line to your conversion method.

What is nextMessageIdToRead parameter in browseQueue() method of AndesAdminServicePortTypeProxy class

I am using on WSO2 Message Broker as a message brokering system in my project. To get the queue browse information, I generated client from AndesAdminServics WSDL and I am trying to call browseQueue() method of AndesAdminServicePortTypeProxy class from my api. Generated browseQueue() method is
public org.wso2.carbon.andes.admin.internal.xsd.Message[] browseQueue(java.lang.String queueName, java.lang.Long nextMessageIdToRead, java.lang.Integer maxMsgCount) throws java.rmi.RemoteException{
if (andesAdminServicePortType == null)
_initAndesAdminServicePortTypeProxy();
return andesAdminServicePortType.browseQueue(queueName, nextMessageIdToRead, maxMsgCount);
}
browseQueue() method takes three parameter -
java.lang.String queueName, java.lang.Long nextMessageIdToRead, java.lang.Integer maxMsgCount
I understand parameter queueName, but i am not getting, What does parameters nextMessageIdToRead and maxMsgCount represent. At the time of browseQueue() method call, What should i pass as a parameter.
You can refer to the actual admin service code. There it contains more information
https://github.com/wso2/andes/blob/b721d5cccfd9896ec871610b7938ba96785b202c/modules/andes-core/management/common/src/main/java/org/wso2/andes/management/common/mbeans/QueueManagementInformation.java#L162
name = "queueName", description = "Name of queue to browse messages"
name = "lastMsgId", description = "Browse message this onwards"
name = "maxMsgCount", description = "Maximum message count per request"

Google Cloud Storage - SocketTimeoutException when rewriting a big object to "nearline" bucket

Environment:
Java client ("google-api-services-storage", "v1-rev33-1.20.0") using JSON API (com.google.api.services.storage.Storage class).
Goal:
Move a large object from "standard" to "nearline" bucket using Java client (file size is 512 MB).
Steps:
Use "rewrite" API method.
Problem:
I'm getting SocketTimeoutException in 20 seconds.
Investigation:
The same code works fine when I use rewrite from "standard" bucket to another "standard" bucket for the same object.
I've also tried the APIs Explorer and created a request to rewrite an object from "standard" to "nearline" bucket. The server responded in about 27 seconds and "totalBytesRewritten" property in the response was for about a half of file size. How to get and handle such response?
Documentation says:
"If the source and destination are different locations and/or storage classes, the rewrite method might require multiple calls."
My code (Java):
final Storage.Objects.Rewrite rewriteRequest = storage.objects().rewrite(
STANDARD_BUCKET_NAME,
SOURCE_OBJECT_PATH,
NEARLINE_BUCKET_NAME,
TARGET_OBJECT_PATH,
null // no metadata overriding
);
rewriteRequest.execute();
Please help.
According to the documentation, if a file was split up into chunks, you are supposed to call rewrite again, using the 'rewriteToken' returned in the first response from rewrite. The operation will resume, doing one more chunk of data. This should be repeated until the response has getDone() == true.
My implementation for the java api:
private void rewriteUntilDone(final String sourceBucket, final String sourceKey,
final String destBucket, final String destKey) throws IOException {
rewriteUntilDone(sourceBucket, sourceKey, destBucket, destKey, null);
}
private void rewriteUntilDone(final String sourceBucket, final String sourceKey,
final String destBucket, final String destKey,
#Nullable final String rewriteToken)
throws IOException {
Storage.Objects.Rewrite rewrite = googleStorage.objects().rewrite(sourceBucket, sourceKey, destBucket, destKey, null);
if (rewriteToken != null) {
rewrite.setRewriteToken(rewriteToken);
}
RewriteResponse rewriteResponse = rewrite.execute();
if (!rewriteResponse.getDone()) {
String rewriteToken2 = rewriteResponse.getRewriteToken();
BigInteger totalBytesRewritten = rewriteResponse.getTotalBytesRewritten();
log.debug("Rewriting not finished, bytes completed: {}. Calling rewrite again with token {}", totalBytesRewritten, rewriteToken2);
rewriteUntilDone(sourceBucket, sourceKey, destBucket, destKey, rewriteToken2);
}
}
EDIT:
Also, you may have to increase the read timeout. It seems that rewrite responds after 27 s but the default timout is 20 s. Wrap your GoogleCredentials to set the read timeout

Receiving an Ajax Request in a Servlet using ObjectInputStream?

I am sending my Ajax Request in the following format
xmlhttp.open("POST","http://172.16.xx.xx:8080/ajax/validate",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(send); //where send is a string retrieved from textarea
This is my Servlet code
ObjectInputStream in =new ObjectInputStream(request.getInputStream());
String inputxmlstring=(String) in.readObject();
I am getting the following exception
java.io.StreamCorruptedException: invalid stream header: 3C3F786D
What is the problem with the code? Is there anything wrong with my request header content type?
EDIT 1
BufferedInputStream in =new BufferedInputStream(req.getInputStream());
byte[] buf=new byte[req.getContentLength()];
while(in.available()>0)
{
in.read(buf);
}
String inputxmlstring=new String(buf);
System.out.println(inputxmlstring);
If I use this code for Servlet I get the following error
14:13:27,828 INFO [STDOUT] [Fatal Error] :1:1: Content is not allowed in prolog
.
14:13:27,843 INFO [STDOUT] org.xml.sax.SAXParseException: Content is not allowe
d in prolog.
EDIT 2
I use this code to parse. The String inputxmlstring has been used in Edit1.
DocumentBuilderFactory fty1 = DocumentBuilderFactory.newInstance();
fty1.setNamespaceAware(true);
DocumentBuilder builder1 = fty1.newDocumentBuilder();
ByteArrayInputStream bais1 = new ByteArrayInputStream(inputxmlstring.getBytes());
Document xmldoc1=builder1.parse(bais1);
You should use the ObjectInputStream only if you know the other end it was written using ObjectOutputStream.
When the client uses ObjectOutputStream, it writes special bytes indicating it is object stream. If these bytes are not present ObjectInputStream will throw StreamCorruptedException.
In your case you should read using request.getInputStream() because the XMLHttpRequest is not sending using ObjectOutputStream.

How do I pass the result from httpget to SAX parser

I'm want to make a request to google API and pass the resulting XML to SAX parser here are both codes...
First the request:
HttpClient hclient = new DefaultHttpClient();
HttpGet get = new HttpGet("http://www.google.com/ig/api?weather=Cardiff");
HttpResponse hrep = hclient.execute(get);
HttpEntity httpEntity = hrep.getEntity();
Then the parser:
SAXParserFactory saxpf = SAXParserFactory.newInstance();
SAXParser saxp = saxpf.newSAXParser();
XMLReader xr = saxp.getXMLReader();
ExHandler myHandler = new ExHandler();
xr.setContentHandler(myHandler);
xr.parse();
Is this the right way to do this and how do I connect both codes.
Thanks in advance
The SAXParser object can take in an input stream and the handler. So something like:
SAXParser saxParser = factory.newSAXParser();
XMLParser parser = new XMLParser();
saxParser.parse(httpEntity.getContent(),parser);
The getContent() method returns and input stream from the HttpRequest, and the XMLParser object is just a class I created (supposedly) that contains the definition of how to parse the XML.
EDIT*
You really should read the entire API for SAXParser, it has several overloaded methods:
void parse(InputSource is, DefaultHandler dh)
Parse the content given InputSource as XML using the specified DefaultHandler.
void parse(InputSource is, HandlerBase hb)
Parse the content given InputSource as XML using the specified HandlerBase.
void parse(InputStream is, DefaultHandler dh)
Parse the content of the given InputStream instance as XML using the specified DefaultHandler.
void parse(InputStream is, DefaultHandler dh, String systemId)
Parse the content of the given InputStream instance as XML using the specified DefaultHandler.
void parse(InputStream is, HandlerBase hb)
Parse the content of the given InputStream instance as XML using the specified HandlerBase.
void parse(InputStream is, HandlerBase hb, String systemId)
Parse the content of the given InputStream instance as XML using the specified HandlerBase.
Some of the methods take an InputSource, some take an InputStream, as I stated earlier.

Resources