Amazon rest call via android - java

I would like to perform rest calls to Amazon API from Android.
Amazon demands that all ws calls will be authenticated using HMAC signatures (Hash-based Message Authentication Code).
I'm missing a similar object to Apache Base64 object to sign my request.
Is there a simple way to do that in Android, or even better is there an Android client for Amazon web service (Product Advertising API).

You should be able to just include the Apache Base64 package in your project.
See this: http://www.delaytolerant.com/android-http-managing-base64-with-apache-commons-codec/
Or if there are any Java based Amazon clients, have you tried including those jars in your Android project?
Apparently the link above is now dead. Here's the contents of the page from Google's cache:
This post continues on programming
HTTP within Android. In the following,
I’ll show how to manage Base64 coded
content in Android and how to render
an image on WebView from a String that
we encoded.
First, the tool to use is commons
codec package from Apache. The
documentation can be found here. The
source is available here. You can just
include the source of the package to
your project, it is all Android
compatible.
The commons codec package has also
convenient method for Base64 decoding,
String imageString = "";
try {
FileInputStream fin = openFileInput("camera.jpg");
int jpeg_size = fin.available();
byte[] imagedata = new byte[jpeg_size];
fin.read(imagedata);
byte[] encodedData = Base64.encodeBase64(imagedata);
imageString = new String(encodedData);
final String mimetype = "text/html";
final String encoding = "UTF-8";
// replace below [ with html "<" and ] similarly ] with ">"
String html = "[html][body][center][img height=\"200\" width=\"200\"
src=\"data:image/jpeg;base64,"+imageString+"\"/][/center][/body][/html]";
mWebView.loadData(html, mimetype, encoding);
} catch (Exception e) {
e.printStackTrace();
}
There is also convenient Base64
decoding functionality in the package,
which can be used for example, to
decode Base64 encoded content in MIME
messages, which were covered in
previous post.

Make sure to encode the result as a url (signature = URLEncoder.encode(signature);) or you any end up in some misfortunes

Related

How to fetch Azure Blob Content Using Java from Azure Functions

I am creating Azure function using Java, My requirement I need to copy blob from one container to another container with encryption
so, for encrypting blob I am adding 4bites before and after the blob while uploading to sink container
now, I need to fetch blob content, for this I found one class in azure i.e,
#BlobInput(
name = "InputFileName",
dataType = "binary",
path = sourceContainerName+"/{InputFileName}")
byte[] content,
Here byte[] content, fetching content of blob
but I am facing some errors like, if I pass any file name as InputFileName parameter it is giving 200ok means returning successful. also it is difficult to mefor exception handling
so I am looking for other ways for fetching blob content.... please answer me if any methods or classes we have
If you are looking for more control, instead of using the bindings, you can use the Azure Storage SDK directly. Check out the quickstart doc for getting
setup.
This sample code has full end-to-end code that you could build upon. Here is the code that you are looking for in it for reference
String data = "Hello world!";
InputStream dataStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
/*
* Create the blob with string (plain text) content.
*/
blobClient.upload(dataStream, data.length());
dataStream.close();
/*
* Download the blob's content to output stream.
*/
int dataSize = (int) blobClient.getProperties().getBlobSize();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(dataSize);
blobClient.downloadStream(outputStream);
outputStream.close();

Microsoft Graph REST API beta: Get hosted content bytes

In the Microsoft Graph REST API beta documentation in section Get chatMessageHostedContent there is the Java example for getting hosted content bytes for an image:
InputStream stream = graphClient
.chats("19:2da4c29f6d7041eca70b638b43d45437#thread.v2")
.messages("1615971548136") .hostedContents("aWQ9eF8wLXd1cy1kOS1lNTRmNjM1NWYxYmJkNGQ3ZTNmNGJhZmU4NTI5MTBmNix0eXBlPTEsdXJsPWh0dHBzOi8vdXMtYXBpLmFzbS5za3lwZS5jb20vdjEvb2JqZWN0cy8wLXd1cy1kOS1lNTRmNjM1NWYxYmJkNGQ3ZTNmNGJhZmU4NTI5MTBmNi92aWV3cy9pbWdv")
.content()
.buildRequest()
.get();
... but using the latest tag microsoftgraph/msgraph-beta-sdk-java (0.9.0-20210615.3) this example doesn't work as content method in ChatMessageHostedContentRequestBuilder cannot be resolved.
With that in mind my question is what is official way of downloading hosted content bytes.
Related question with some more details is also present on GitHub.
It looks like this will be fixed in the future - but for the time being this workaround should do it:
String valueUrl = graphClient
.chats(chatId)
.messages(messageId)
.hostedContents(hostedContentId)
.getRequestUrlWithAdditionalSegment("$value");
InputStream stream = new CustomRequestBuilder<>(valueUrl, graphClient, null, InputStream.class).buildRequest().get();

Creating QR Code as Base64 String using Spring Boot

I am creating a microservice using spring boot where in i have a file handling.
My task is to write the QR code to image file and base64 encode to transfer over network.
Because I need to write to an image file and then read and then base64 encode it , I need to first create the image file and then write to it.
Creating a temperory folder and keep the file ?, create a folder in root directory and keep the file? or use the java.io.tmpdir ....
Note: I have no use of this file once I encode it. Also there are lot of user to whom we will be exposing this service as rest api.
I want to know what is the best way to do this.
If you are using the https://github.com/zxing/zxing library i.e.
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.2.1</version>
</dependency>
Then something like the following will work.
#RestController
public class TestController {
#GetMapping(value = "/test")
public QrInfo getQrInfo() throws Exception {
String url = "https://news.bbc.co.uk";
int imageSize = 200;
BitMatrix matrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE,
imageSize, imageSize);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(matrix, "png", bos);
String image = Base64.getEncoder().encodeToString(bos.toByteArray()); // base64 encode
// return QrInfo
QrInfo qrInfo = new QrInfo();
qrInfo.setUrl(url);
qrInfo.setImage(image);
return qrInfo;
}
}
#Data // lombok for brevity
class QrInfo {
private String url;
private String image;
}
NOTE: This approach doesn't write any files but does it all in-memory using a ByteArrayOutputStream .
If you hit this endpoint you'll see the following: -
{
"url": "https://news.bbc.co.uk",
"image": "iVBORw0KGgoAAAANSUhEUgAAAMgAAADIAQAAAACFI5MzAAABGUlEQVR42u2YSw7DIAxEzYpjcFM+N+UYrErtMUkjpd2WWQQlyudtLI89JpH5a8lDHvJnUkVXmkMPKcMeAg1peo70inrpRbm/ISFDwkhNX4NUSWxEo26WVFKisgc2ArWncSO3OthJvEs0nTju/bOT+NJKzJK++c5OovJWRIob2AwNsf6YXWJ3eFGbgXS4skgEGafaDGSifVONS/ZCQ/Q2YI5l8BdSS0ImwtTezehjiM9C3FG8fbVdykft/URTeEY918hlIZZFC9Yq0Rw6ns63nyxXtkTCYK6VuJv4NKvmMdgFMBHfBbRjb8JFxgoWW04RPmKfEaY2pgcZcT/OsL3GQ5baFrUN23iZZrvJ6pKjDJFXFvL8P3jIfvIGvNX7jsCaJvEAAAAASUVORK5CYII="
}
If you paste the Base64 into e.g https://codebeautify.org/base64-to-image-converter and point camera from your phone you will see the URL.
If you rendering this out it is easy i.e. in React (any JavaScript approach will be similar).
<img src={`data:image/png;base64,${image}`} />
I like this approach as if you are e.g. generate 2FA codes you can pass down both the random secret and the QR code - useful to have both as a backup if the user doesn't have access to a mobile device.
You can do this in a designated folder in your file-system easily and once you are done with the transfer, you can remove the file. But since, this operation is exposed over a rest api, concurrency and file collision can be an issue. To avoid that you can give unique to every file-name, that way same file-name collision can be avoided.
One approach could be to UUID for writing the file-name and storing the file with this name in the file-system. It will ensure collision doesn't occur.
String fileName = UUID.randomUUID().toString();

JMeter not decoding base64 correctly - Results in blank PDF

In JMeter, I get a base64 encoded PDF in a Response that I extract using the RegEx Extractor. That is all working great.
Then I need to decode that base64 encoded document and write it out to a file, which I'm doing with the following in a BeanShell Post Processor:
import org.apache.commons.io.FileUtils;
import org.apache.commons.codec.binary.Base64;
// Set the response variable
String response = vars.get("documentText");
// Remove the carriage return hex code and condense to single string
String encodedFile = response.replace("
","").replaceAll("[\n]+","");
// Decode the encoded string
vars.put("decodedFile",new String(Base64.decodeBase64(encodedFile)));
// Write out the decoded file
Output = vars.get("decodedFile");
f = new FileOutputStream("C:\\Users\\user\\Desktop\\decodedFile.pdf");
p = new PrintStream(f);
this.interpreter.setOut(p);
print(Output);
p.flush();
f.close();
My problem is that the file that gets decoded and written out opens as a blank PDF.
In troubleshooting this, I wrote out a file with the encoded string from JMeter and then manually decoded it using this base64 tool. When I manually decoded the file, it opened as expected.
I then compared the text of the file that was produced by JMeter and the one I decoded with the tool and noticed that the file produced by JMeter included random ?'s throughout
I am assuming this must be the culprit, however, I do not know what is causing these to show up or how to fix it.
JMeter is not decoding Base64 correctly because JMeter cannot decode Base64. If you are using some custom code to do it I would suggest look into this code first.
Given you need to do this magic:
String encodedFile = response.replace("
","").replaceAll("[\n]+","");
my expectation is that your either your regular expression or server response is shitty
Given you use scripting-based post-processor you ain't gonna need this "regex" interim step, you should be able to access parent sampler response from Beanshell PostProcessor via data shorthand
So your great script can be optimized into something like:
FileUtils.writeByteArrayToFile(new File("C:\\Users\\user\\Desktop\\decodedFile.pdf"), Base64.decodeBase64(data));
As a fallback option you can execute this decb64.exe program using OS Process Sampler.

How do I upload a pdf to elasticsearch when using the elastic search java client?

This link explains how to use the REST API to upload an attachment.
But I want to upload an attachment with the java client...
I assume the following classes are relevant (though I may be wrong)...
org.elasticsearch.ingest.IngestService
org.elasticsearch.ingest.PipelineStore
I realize that I can just fall back to the REST interface but I'd rather try and use the native client first...
Just send a BASE64 encoded PDF in a field like:
String base64;
try (InputStream is = YourClass.class.getResourceAsStream(pathToYourFile)) {
byte bytes[] = IOUtils.toByteArray(is);
base64 = Base64.getEncoder().encodeToString(bytes);
}
IndexRequest indexRequest = new IndexRequest("index", "type", "id")
.setPipeline("foo")
.source(
jsonBuilder().startObject()
.field("field", base64)
.endObject()
);
In case you are not aware of it, I'm also linking to FSCrawler project in case it solves something you want to do already.
Here is four options that you can use to index PDFs to ElasticSearch
Ingest Attachment Plugin
Apache Tika
FsCrawler
Ambar
Pros/cons described in this post

Categories

Resources