How to POST File to an URL in Java CodeName One? - java

I wanna to upload an image in java and copied in a directory with WebService in Symfony
i tried it with Postman and it worked but when i did it in Java, it didn't work, i don't know how to pass a file like paramatre in the Url request
Please help me to find a solution
Symfony Code:
$file = $request->files->get('nomImage');
$status = array('status' => "success","fileUploaded" => false);
// If a file was uploaded
if(!is_null($file)){
// generate a random name for the file but keep the extension
$filename = uniqid().".".$file->getClientOriginalExtension();
$path = "C:\wamp64\www\pidev\web\uploads\images";
$file->move($path,$filename); // move the file to a path
$status = array('status' => "success","fileUploaded" => true);
}
return new JsonResponse($status);
Postman Screenshot:
I sent the URL with Postman and add the image in Body with nomImage like key and the image like value and it worked
Java Code:
This code is to connect to the URL and i wanted to get the image like file in the URL like in Postman
public void ajoutProduit(File image)
{
ConnectionRequest con = new ConnectionRequest();
con.setUrl("http://localhost/PIDEV/web/app_dev.php/Api/produit/ajout?nomImage="+image);
NetworkManager.getInstance().addToQueueAndWait(con);
}
This is my form and the uploading of the image and execute the Copy of the image which it didn't work
public class AjoutProduit {
private Form fAjout = new Form("", new BoxLayout(BoxLayout.Y_AXIS));
public AjoutProduit() {
TextField nomProduit = new TextField("", "Nom du produit");
TextField descProduit = new TextField("", "Description du produit");
ComboBox<String> opProduit = new ComboBox<>(
"",
"echanger",
"donner",
"recycler",
"reparer"
);
final String[] jobPic = new String[1];
Label jobIcon = new Label();
Button image = new Button("Ajouter une image ");
final String[] image_name = {""};
final String[] pathToBeStored={""};
/////////////////////Upload Image
image.addActionListener((ActionEvent actionEvent) -> {
Display.getInstance().openGallery(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ev) {
if (ev != null && ev.getSource() != null) {
String filePath = (String) ev.getSource();
int fileNameIndex = filePath.lastIndexOf("/") + 1;
String fileName = filePath.substring(fileNameIndex);
Image img = null;
try {
img = Image.createImage(FileSystemStorage.getInstance().openInputStream(filePath));
} catch (IOException e) {
e.printStackTrace();
}
image_name[0] = System.currentTimeMillis() + ".jpg";
jobIcon.setIcon(img);
System.out.println(filePath);
System.out.println(image_name[0]);
try {
pathToBeStored[0] = FileSystemStorage.getInstance().getAppHomePath()+ image_name[0];
OutputStream os = FileSystemStorage.getInstance().openOutputStream(pathToBeStored[0]);
ImageIO.getImageIO().save(img, os, ImageIO.FORMAT_JPEG, 0.9f);
os.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}, Display.GALLERY_IMAGE);});
////////////Copied with URL Symfony
Button myButton = new Button("Valider");
myButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
ServiceProduit sp = new ServiceProduit();
ServiceEchange se = new ServiceEchange();
String path = "C:/Users/omark/.cn1/"+image_name[0];
File file = new File(path);
sp.ajoutProduit(file);
}
});
fAjout.addAll(nomProduit,descProduit,opProduit,jobIcon,myButton,image);
fAjout.show();
}

Try the x-www-url-form-encoded. If that works then use MultipartRequest to submit binary data to the server. It implicitly handles form encode submission for you. If something doesn't work use the network monitor tool in Codename One to inspect the outgoing request/response which often provide helpful information about the process.
This isn't correct:
ConnectionRequest con = new ConnectionRequest();
con.setUrl("http://localhost/PIDEV/web/app_dev.php/Api/produit/ajout?nomImage="+image);
NetworkManager.getInstance().addToQueueAndWait(con);
You're submitting a URL using the GET style argument passing. You need to submit the date of the image and not the image itself. You need to use addArgument() or addData() etc. to include the content in the request.

i resolved the problem, i modified the " Java Code ":
MultipartRequest cr = new MultipartRequest();
cr.setUrl("http://localhost/PIDEV/web/app_dev.php/Api/produit/ajout");
cr.setPost(true);
String mime = "image/png";
try {
cr.addData("file", filePath, mime);
} catch (IOException e) {
e.printStackTrace();
}
String fichernom = System.currentTimeMillis() + ".png";
cr.setFilename("file", fichernom);
InfiniteProgress prog = new InfiniteProgress();
Dialog dlg = prog.showInifiniteBlocking();
cr.setDisposeOnCompletion(dlg);
NetworkManager.getInstance().addToQueueAndWait(cr);

Related

TelegramBot. SenDocument pdf

I send file pdf through custom app telegramBot to client in telegram. Client get .txt (default type)
// file = "application/pdf;base64,JVBERi0xLjMN...DAwMT=="
private String sendFileToClient(String clientExtId, String file) {
String fileLink;
byte[] data = DatatypeConverter.parseBase64Binary(file);
SendDocument sendDocument = new SendDocument(clientExtId, data);
try {
SendResponse execute = telegramBot.execute(sendDocument);
Document document = execute.message().document();
final String documentId = document.fileId();
fileLink = getFileLink(documentId);
return fileLink;
} catch (Exception e) {
....
}
}
public String getFileLink(String fileId) {
GetFile getFile = new GetFile(fileId);
GetFileResponse fileResponse = telegramBot.execute(getFile);
File file = fileResponse.file();
log.info("getRelativeFilePath filePath : {}", file.filePath()); // documents/file_203.txt ????
return telegramBot.getFullFilePath(file);
}
Why my file return .txt not pdf?
when I send photo, return - photos/file_202.jpg
What problem? Pls help)
UP: compile('com.github.pengrad:java-telegram-bot-api:X.X.X')
solution:
new SendDocument(clientExtId, data).fileName(fileName.pdf);

How to properly save frames from mp4 as png files using ExtractMpegFrames.java?

I am trying to get all frames from an mp4 file using the ExtractMpegFrames.java class found here http://bigflake.com/mediacodec/ExtractMpegFramesTest.java.txt
What I currently do is create a temp file (File.createTempFile) in a directory that stores all the frames, create a FileOutputStream and do
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut)
where fOut is the OutputStream with the file.
Currently, the saved images look like this: https://imgur.com/a/XpsV2
Using the Camera2 Api, I record a video and save it as an mp4. According to VLC, the color space for the video is Planar 4:2:0 YUV Full Scale.
Looking around, it seems that each vendor uses different color spaces
https://stackoverflow.com/a/21266510/7351748. I know ffmpeg can conversions with color spaces, but I cannot use it.
I am not sure where to start to solve this issue of the strange output pngs. I am assuming that this is a color space issue, but I can be completely wrong here.
You can get all Frames of Video Using ffmpeg library here is working code.
add dependancy
compile 'com.writingminds:FFmpegAndroid:0.3.2'
to your gradle
private void loadFFMpegBinary() {
try {
if (ffmpeg == null) {
ffmpeg = FFmpeg.getInstance(this);
}
ffmpeg.loadBinary(new LoadBinaryResponseHandler() {
// #Override
// public void onFailure() {
// showUnsupportedExceptionDialog();
// }
#Override
public void onSuccess() {
Log.d(TAG, "ffmpeg : correct Loaded");
}
});
} catch (FFmpegNotSupportedException e) {
} catch (Exception e) {
Log.d(TAG, "EXception : " + e);
}
}
here is image extratct method
public void extractImagesVideo() {
File moviesDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES
);
String filePrefix = "extract_picture";
String fileExtn = ".jpg";
String yourRealPath = getPath(Pick_Video.this, DataModel.selectedVideoUri);
Log.d("selected url", "" + DataModel.selectedVideoUri);
File src = new File(yourRealPath).getAbsoluteFile();
File appDir=new File(moviesDir,"/"+app_name+"/");
if(!appDir.exists())
appDir.mkdir();
DataModel.appDir=appDir;
File dir = new File(appDir, "testVideo");
int fileNo = 0;
while (dir.exists()) {
fileNo++;
dir = new File(moviesDir+"/"+app_name+"/", "testVideo" + fileNo);
}
dir.mkdir();
DataModel.dir = dir;
resultList = new ArrayList<String>(256);
filePath = dir.getAbsolutePath();
File dest = new File(dir, filePrefix + "%03d" + fileExtn);
Log.d(TAG, "startTrim: src: " + src.toString());
Log.d(TAG, "startTrim: dest: " + dest.getAbsolutePath());
String[] complexCommand = { "-i",""+src.toString(),"-qscale:v", "2","-vf", "fps=fps=20/1",dest.getAbsolutePath()};
//"-qscale:v", "2","-vf", "fps=fps=20/1",//
//works fine with speed and
execFFmpegBinary(complexCommand);
}
call this two method on button click event
Comment If Any query.

Eclipse 4 - How can I save dirty part when i save my perspective

I used E4XMIResourceFactory to save perspective in my eclipse 4 application. But when I went to load my perspective from xmi file, I could found my data in the part. In other world I'd like to save dirty part inside my xmi file. Somebody can help me I cannot find any resurce online to solve my problem.
public class SaveHandler {
#Execute
public void execute(EModelService modelService, MWindow window, MApplication app, Shell shell) {
MPerspective savePerspective = modelService.getActivePerspective(window);
E4XMIResourceFactory e4xmiResourceFactory = new E4XMIResourceFactory();
Resource resource = e4xmiResourceFactory.createResource(null);
MUIElement clonedPerspective = modelService.cloneElement(savePerspective, window);
resource.getContents().add((EObject) clonedPerspective);
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(new String [] {"*.xmi"});
//dialog.setFilterPath("c:\\temp");
String result = dialog.open();
FileOutputStream outputStream = null;
try {
// Use a stream to save the model element
outputStream = new FileOutputStream(result);
resource.save(outputStream, null);
if (outputStream != null)
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And the loader method is
public class OpenHandler {
#Execute
public void execute(EPartService partService,EModelService modelService,MWindow window, MApplication app, Shell shell) {
E4XMIResourceFactory e4xmiResourceFactory = new E4XMIResourceFactory();
Resource resource = e4xmiResourceFactory.createResource(null);
FileInputStream inputStream = null;
try {
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(new String [] {"*.xmi"});
//dialog.setFilterPath("c:\\temp");
String result = dialog.open();
inputStream = new FileInputStream(result);
resource.load(inputStream, null);
if (!resource.getContents().isEmpty()) {
MPerspective loadedPerspective = (MPerspective) resource.getContents().get(0);
//MPerspective perspective = (MPerspective)modelService.find("ktool_aie.perspective.connectionandmaps",app);
MPerspective perspective = modelService.getActivePerspective(window);
MElementContainer<MUIElement> perspectiveParent = perspective.getParent();
List<MPerspective> alreadyPresentPerspective = modelService.findElements(window,loadedPerspective.getElementId(), MPerspective.class, null);
for (MPerspective i_perspective : alreadyPresentPerspective) {
modelService.removePerspectiveModel(i_perspective, window);
}
// add the loaded perspective and switch to it
perspectiveParent.getChildren().add(loadedPerspective);
partService.switchPerspective(loadedPerspective);
}
if (inputStream != null) inputStream.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}

Passing text and multiple images as an array using okhttp

I am using Okhttp lib to send data to server. I want to set text and images in RequestBody. For uploading multiple image to server using Okhttp i follow this link. I have implemented that type of code in my app in another activity class and its work fine. I have checked this question that how to pass array in RequestBody.
My arrayList format is like this
blockList
{
block0
{
description0 = First block
image0 = {image1, image2}
video0 = videolink
disp_order0 = 0
block0 = 0
}
block1
{
description1 = second block
image1 = {image1,image2,image2}
video1 = videolink
disp_order1 = 1
block1 = 1
}
.....
}
My Requirement :-
Now i want to send multiple images as an array in single parameter. When i send first block then parameter names are description0,image0[],video1,disp_order and block0 and image0[] will contain first block images as array and same for other.
API is working fine because when i test in postman then i receive the data in server side. You can see in below..
Here is my java function that set the data in RequestBody and make a call to send that data on sever.
ProgressDialog pd;
private OkHttpClient client;
private void saveCastBoxOnServer(String castBoxTitle, String selectedCastBoxId, String selectedCategoryId,
String userId, String action, ArrayList<CastBoxBlock> blockList)
{
try
{
client = new OkHttpClient.Builder()
.retryOnConnectionFailure(true)
.build();
ArrayList<CastBoxBlock> blockArrayList = blockList;
int blockSize = blockArrayList.size();
MultipartBody.Builder multipartBuilderNew = new MultipartBody.Builder().setType(MultipartBody.FORM);
for (int i = 0; i < blockSize; i++)
{
String description = blockArrayList.get(i).getBlockDescription();
String descriptionField = "description"+i;
multipartBuilderNew.addFormDataPart(descriptionField, description);
/**This is used for distribution of images and videos. After that set that
* Images and video in multipartBuilder.
**/
CastBoxBlock model = blockArrayList.get(i);
ArrayList<SelectedMediaModel> mediaModels = model.getSelectedMediaModelArrayList();
int mediaModelsSize = mediaModels.size();
String passingVideoUri = "";
String videoUri = "";
for (int j = 0; j < mediaModelsSize; j++)
{
String mediaType = mediaModels.get(j).getMediaType();
if (mediaType.equals(StringKeyConstant.mediaVideo))
{
videoUri = mediaModels.get(j).getMediaPath();
if (passingVideoUri.trim().length()==0){
passingVideoUri = videoUri;
}else{
passingVideoUri = passingVideoUri + "," + videoUri;
}
}
else if (mediaType.equals(StringKeyConstant.mediaImage))
{
String imagePath = mediaModels.get(j).getMediaPath();
File sourceFile = new File(imagePath);
/**Changes whether JPEG or PNG**/
final MediaType MEDIA_TYPE = MediaType.parse(
constant.getFileExt(imagePath).endsWith("png") ? "image/png" : "image/jpeg");
String imageName = System.currentTimeMillis() + j + "_block_img.jpg";
String imageField = "image"+i+"["+j+"]";
multipartBuilderNew.addFormDataPart(imageField,imageName,
RequestBody.create(MEDIA_TYPE, sourceFile));
}
}
/**This is used to set the {#videoUri} block of videos and send to sever**/
String videoField = "video"+i;
multipartBuilderNew.addFormDataPart(videoField, passingVideoUri);
/**This will set the {#display_order} in multipartBuilder**/
String displayOrderField = "disp_order"+i;
String displayOrder = blockArrayList.get(i).getBlockIndex();
multipartBuilderNew.addFormDataPart(displayOrderField, displayOrder);
/**This will set the {#block} value in multipartBuilder**/
String blockField = "block"+i;
String block = ""+i;
multipartBuilderNew.addFormDataPart(blockField, block);
}
pd = new ProgressDialog(activity);
pd.setCancelable(false);
pd.setMessage(getResources().getString(R.string.please_wait));
pd.show();
RequestBody formBody = multipartBuilderNew
.addFormDataPart("cast_title", castBoxTitle)
.addFormDataPart("user_id", userId)
.addFormDataPart("cast_box", selectedCastBoxId)
.addFormDataPart("category", selectedCategoryId)
.addFormDataPart("action", action)
.build();
Request request = new Request.Builder()
.url(ApiUtils.ADD_FETCH_USER_CAST)
.post(formBody)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.e(TAG, "Get Api credential fail."+call.toString());
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException
{
try
{
if (pd != null){
pd.cancel();
pd.dismiss();
pd = null;
}
String castSavedResponse = response.body().string();
Log.i(TAG, "castSavedResponse = " + castSavedResponse);
}
catch (Exception e){
Log.e(TAG, "***Error : onResponse() method");
e.printStackTrace();
}
}
});
}
catch (Exception e){
Log.e(TAG, "***Error : saveCastBoxOnServer()");
e.printStackTrace();
}
}
Thanks in advance. If any one will help it would be very appreciate.
When i check your code then i note one things. I am no sure but i think you change your code on image[] place. you can just change your code as below. I hope this will help you and you got the solution.
Use this code
String imageField = "image"+i+"[]";
Instead of
String imageField = "image"+i+"["+j+"]";
when i passed simple images as an array in Okhttp then i do code as above. For uploading multiple images on server using Okhttp, i also follow this link as you follow.

Running OpenOffice Macro from Java API

I'm trying to write a Java program that will run an OpenOffice Macro. I'm getting this error:
java.lang.RuntimeException:
com.sun.star.script.provider.ScriptFrameworkErrorException: Incorrect
format for Script URI: vnd.sun.star.script:Name of macro
I believe it has something to do with the way that I'm calling the macro (String cmd)
I've searched high and low but can't seem to find any information on this. There are a few posts on the OO forums but none of them seemed to help. Here is some of the code:
public static void main(String[] args) throws BootstrapException {
if(args.length == 0)
{
System.out.println("Must enter a filename");
System.exit(1);
}
try
{
String param = args[0];
//String cmd = "Standard.Conversion.ConvertHTMLToWord?langauge=Basic&location=application";
String cmd = "Name.Of.Macro?langauge=Basic&location=Document";
System.out.println("Running macro on " + param);
Macro macObj = new Macro();
macObj.executeMacro(cmd, new Object[]{param}]);
System.out.println("Completed");
}
catch(Exception e)
{
System.out.println(e.toString());
//e.printStackTrace();
}
Macro Class:
class Macro {
private static final String ooExecPath = "C:/Program Files/OpenOffice.org 3/program";
public Object executeMacro(String strMacroName, Object[] aParams) throws BootstrapException
{
try
{
com.sun.star.uno.XComponentContext xContext;
System.out.println("Connecting to OpenOffice");
xContext = BootstrapSocketConnector.bootstrap(ooExecPath);
System.out.println("Connected to a running instance of OpenOffice");
System.out.println("Trying to execute macro...");
com.sun.star.text.XTextDocument mxDoc = openWriter(xContext);
XScriptProviderSupplier xScriptPS = (XScriptProviderSupplier) UnoRuntime.queryInterface(XScriptProviderSupplier.class, mxDoc);
XScriptProvider xScriptProvider = xScriptPS.getScriptProvider();
XScript xScript = xScriptProvider.getScript("vnd.sun.star.script:"+strMacroName);
short[][] aOutParamIndex = new short[1][1];
Object[][] aOutParam = new Object[1][1];
return xScript.invoke(aParams, aOutParamIndex, aOutParam);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static com.sun.star.text.XTextDocument openWriter(com.sun.star.uno.XComponentContext xContext)
{
com.sun.star.frame.XComponentLoader xCLoader;
com.sun.star.text.XTextDocument xDoc = null;
com.sun.star.lang.XComponent xComp = null;
try {
// get the remote office service manager
com.sun.star.lang.XMultiComponentFactory xMCF =
xContext.getServiceManager();
Object oDesktop = xMCF.createInstanceWithContext(
"com.sun.star.frame.Desktop", xContext);
xCLoader = (com.sun.star.frame.XComponentLoader)
UnoRuntime.queryInterface(com.sun.star.frame.XComponentLoader.class,
oDesktop);
com.sun.star.beans.PropertyValue [] szEmptyArgs =
new com.sun.star.beans.PropertyValue [0];
/*
ArrayList<PropertyValue> props = new ArrayList<PropertyValue>();
PropertyValue p = new PropertyValue();
p.Name = "Hidden";
p.Value = new Boolean(true);
props.add(p);
PropertyValue[] properties = new PropertyValue[props.size()];
props.toArray(properties);
String strDoc = "private:factory/swriter";
xComp = xCLoader.loadComponentFromURL(strDoc, "_blank", 0, properties);
*/
String strDoc = "private:factory/swriter";
xComp = xCLoader.loadComponentFromURL(strDoc, "_blank", 0, szEmptyArgs);
xDoc = (com.sun.star.text.XTextDocument)
UnoRuntime.queryInterface(com.sun.star.text.XTextDocument.class,
xComp);
} catch(Exception e){
System.err.println(" Exception " + e);
e.printStackTrace(System.err);
}
return xDoc;
}
}
I suppose your problem is in the "Name.Of.Macro": it must be: Library.Module.NameOfMacro.
"langauge=Basic" of course sets the language name, and "location=application" means the macro library should be searched in the opened document, and not in global OO libraries.
As far as parameters are involved, I use:
XScriptProviderSupplier xScriptPS = (XScriptProviderSupplier) UnoRuntime.queryInterface(XScriptProviderSupplier.class, xComponent);
XScriptProvider xScriptProvider = xScriptPS.getScriptProvider();
XScript xScript = xScriptProvider.getScript("vnd.sun.star.script:"+macroName);
short[][] aOutParamIndex = new short[1][1];
Object[][] aOutParam = new Object[1][1];
Object[] aParams = new String[2];
aParams[0] = myFirstParameterName;
aParams[1] = mySecondParameterName;
#SuppressWarnings("unused")
Object result = xScript.invoke(aParams, aOutParamIndex, aOutParam);
System.out.println("xScript invoke macro " + macroName);
Hope it can be useful, after such long time... :-(
XScriptProviderSupplier xScriptPS = (XScriptProviderSupplier) UnoRuntime.queryInterface(XScriptProviderSupplier.class, xComponent);
What is xComponent in the above code?
Compare: ?langauge=Basic&location=Document"
to: ?language=Basic&location=Document"
wring is: "langauge" :D, swap "au" to "ua". :)

Categories