I want to download a file in my telegram bot code many tutorials say that I must use the getFile method that I can't find that in 4.2 version of the telegram API
so how I can download a file to a specific destination in host pc?
thanks
Assuming you are using TelegramBot SDK from rubenlagus (https://github.com/rubenlagus/TelegramBots), as I faced same issue. Below is my solution.
GetFile getFile = new GetFile().setFileId(fileId);
String filePath = execute(getFile).getFilePath();
File file = downloadFile(filePath, outputFile);
I had the same problem.
This was my solution. Not very nice but it works.
if (update.getMessage().hasDocument()){
String doc_id = update.getMessage().getDocument().getFileId();
String doc_name = update.getMessage().getDocument().getFileName();
String doc_mine = update.getMessage().getDocument().getMimeType();
int doc_size = update.getMessage().getDocument().getFileSize();
String getID = String.valueOf(update.getMessage().getFrom().getId());
Document document = new Document();
document.setMimeType(doc_mine);
document.setFileName(doc_name);
document.setFileSize(doc_size);
document.setFileId(doc_id);
GetFile getFile = new GetFile();
getFile.setFileId(document.getFileId());
try {
org.telegram.telegrambots.meta.api.objects.File file = execute(getFile);
downloadFile(file, new File("./data/userDoc/"+getID+"_"+doc_name));
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
Here I got this solution
enter link description here
Related
This is the qr-code generator, I put on String qrCodeData to try access the storage of my phone and open up a file, but it doesnt work. Turns out the generated qr code only gives the link.
public class QRCode {
public static void main(String[] args) {
try {
String qrCodeData = "Device storage/Download/japanese/Mastering_Kanji_1500.pdf";
String filePath = "D:\\QR code project\\Generated QR codes\\qr.png";
String charset = "UTF-8"; // or "ISO-8859-1"
Map < EncodeHintType, ErrorCorrectionLevel > hintMap = new HashMap < EncodeHintType, ErrorCorrectionLevel > ();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
BitMatrix matrix = new MultiFormatWriter().encode(
new String(qrCodeData.getBytes(charset), charset),
BarcodeFormat.QR_CODE, 200, 200, hintMap);
MatrixToImageWriter.writeToFile(matrix, filePath.substring(filePath
.lastIndexOf('.') + 1), new File(filePath));
System.out.println("QR Code image created successfully! and stored at location"+filePath);
} catch (Exception e) {
System.err.println(e);
}
}
}
We are able to view and manipulate PDF files via the PDFBox library.
Android version.
We may also use MuPDF. It has an Android version.
Interpret the received link as a file or download it to storage, then proceed to interface with PDFBox library.
Note that file downloading and access on Android should now be done via Room interface or SQLite as recommended by Google.
Hope this helps.
I'm trying to build a jsoup based java app to automatically download English subtitles for films (I'm lazy, I know. It was inspired from a similar python based app). It's supposed to ask you the name of the film and then download an English subtitle for it from subscene.
I can make it reach the download link but I get an Unhandled content type error when I try to 'go' to that link. Here's my code
public static void main(String[] args) {
try {
String videoName = JOptionPane.showInputDialog("Title: ");
subscene(videoName);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void subscene(String videoName){
try {
String siteName = "http://www.subscene.com";
String[] splits = videoName.split("\\s+");
String codeName = "";
String text = "";
if(splits.length>1){
for(int i=0;i<splits.length;i++){
codeName = codeName+splits[i]+"-";
}
videoName = codeName.substring(0, videoName.length());
}
System.out.println("videoName is "+videoName);
// String url = "http://www.subscene.com/subtitles/"+videoName+"/english";
String url = "http://www.subscene.com/subtitles/title?q="+videoName+"&l=";
System.out.println("url is "+url);
Document doc = Jsoup.connect(url).get();
Element exact = doc.select("h2.exact").first();
Element yuel = exact.nextElementSibling();
Elements lis = yuel.children();
System.out.println(lis.first().children().text());
String hRef = lis.select("div.title > a").attr("href");
hRef = siteName+hRef+"/english";
System.out.println("hRef is "+hRef);
doc = Jsoup.connect(hRef).get();
Element nonHI = doc.select("td.a40").first();
Element papa = nonHI.parent();
Element link = papa.select("a").first();
text = link.text();
System.out.println("Subtitle is "+text);
hRef = link.attr("href");
hRef = siteName+hRef;
Document subDownloadPage = Jsoup.connect(hRef).get();
hRef = siteName+subDownloadPage.select("a#downloadButton").attr("href");
Jsoup.connect(hRef).get(); //<-- Here's where the problem lies
}
catch (java.io.IOException e) {
System.out.println(e.getMessage());
}
}
Can someone please help me so I don't have to manually download subs?
I just found out that using
java.awt.Desktop.getDesktop().browse(java.net.URI.create(hRef));
instead of
Jsoup.connect(hRef).get();
downloads the file after prompting me to save it. But I don't want to be prompted because this way I won't be able to read the name of the downloaded zip file (I want to unzip it after saving using java).
Assuming that your files are small, you can do it like this. Note that you can tell Jsoup to ignore the content type.
// get the file content
Connection connection = Jsoup.connect(path);
connection.timeout(5000);
Connection.Response resultImageResponse = connection.ignoreContentType(true).execute();
// save to file
FileOutputStream out = new FileOutputStream(localFile);
out.write(resultImageResponse.bodyAsBytes());
out.close();
I would recommend to verify the content before saving.
Because some servers will just return a HTML page when the file cannot be found, i.e. a broken hyperlink.
...
String body = resultImageResponse.body();
if (body == null || body.toLowerCase().contains("<body>"))
{
throw new IllegalStateException("invalid file content");
}
...
Here:
Document subDownloadPage = Jsoup.connect(hRef).get();
hRef = siteName+subDownloadPage.select("a#downloadButton").attr("href");
//specifically here
Jsoup.connect(hRef).get();
Looks like jsoup expects that the result of Jsoup.connect(hRef) should be an HTML or some text that it's able to parse, that's why the message states:
Unhandled content type. Must be text/*, application/xml, or application/xhtml+xml
I followed the execution of your code manually and the last URL you're trying to access returns a content type of application/x-zip-compressed, thus the cause of the exception.
In order to download this file, you should use a different approach. You could use the old but still useful URLConnection, URL or use a third party library like Apache HttpComponents to fire a GET request and retrieve the result as an InputStream, wrap it into a proper writer and write your file into your disk.
Here's an example about doing this using URL:
URL url = new URL(hRef);
InputStream in = url.openStream();
OutputStream out = new BufferedOutputStream(new FileOutputStream("D:\\foo.zip"));
final int BUFFER_SIZE = 1024 * 4;
byte[] buffer = new byte[BUFFER_SIZE];
BufferedInputStream bis = new BufferedInputStream(in);
int length;
while ( (length = bis.read(buffer)) > 0 ) {
out.write(buffer, 0, length);
}
out.close();
in.close();
I am trying to open ".docx" document using open office but i am not getting how to open a password protected ".docx" file using open office java api.
please suggest me what properties i have to use to access password protedted ".docx" file.
When i try to open with below property values, i got IllegalArgumentException
PropertyValue[] loadProps = new PropertyValue[3];
loadProps[0] = new PropertyValue();
loadProps[0].Name = "FilterName";
loadProps[0].Value = "StarOffice XML (Writer)";
loadProps[1] = new PropertyValue();
loadProps[1].Name = "PassWord";
loadProps[1].Value = "abcdef";
Object objectDocumentToStore = xcomponentloader.loadComponentFromURL(loadUrl, "_default", 0, loadProps);
Exception
com.sun.star.lang.IllegalArgumentException: URL seems to be an unsupported one.
at com.sun.star.lib.uno.environments.remote.Job.remoteUnoRequestRaisedException(Job.java:180)
at com.sun.star.lib.uno.environments.remote.Job.execute(Job.java:146)
at com.sun.star.lib.uno.environments.remote.JobQueue.enter(JobQueue.java:338)
at com.sun.star.lib.uno.environments.remote.JobQueue.enter(JobQueue.java:307)
at com.sun.star.lib.uno.environments.remote.JavaThreadPool.enter(JavaThreadPool.java:94)
at com.sun.star.lib.uno.bridges.java_remote.java_remote_bridge.sendRequest(java_remote_bridge.java:642)
at com.sun.star.lib.uno.bridges.java_remote.ProxyFactory$Handler.request(ProxyFactory.java:154)
at com.sun.star.lib.uno.bridges.java_remote.ProxyFactory$Handler.invoke(ProxyFactory.java:136)
at com.sun.proxy.$Proxy3.loadComponentFromURL(Unknown Source)
at com.pravridh.puneeth.DocumentToPdfWithFilterData.main(DocumentToPdfWithFilterData.java:49)
just write this code to open documents
String cmds[] = new String[] {"cmd", "/c",
"C:\\Users\\PC\\Desktop\\EA01.pdf"};
try {
Runtime.getRuntime().exec(cmds);
} catch (IOException ex) {
Logger.getLogger(secretry.class.getName()).log(Level.SEVERE, null, ex);
}
I am trying to work with Open Office in my Java app.
Based on SDK, with extra help from bootstrapconnector.jar I successfully started empty swritter and can write to the document.
Now, I would like to open document stored in ByteArray and after some modifications save changes doc to ByteArray.
Can somebody help me doing that, please?
Here is the SDK part starting sWritter.
public static com.sun.star.text.XTextDocument openWriter(
com.sun.star.uno.XComponentContext xContext) {
//define variables
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];
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;
}
as you can see there is a method loadComponentFromURL.
I saw somewhere else, in the OOoBeanViewer, that it is possible to read and write doc to ByteArray, however I don't know how to achieve that without officebean.jar which I don't want to use in my project.
Thanks for your comments and hints.
Am trying to upload a pdf file to Google Docs/Drive,
For that am using the following code...
int MAX_CONCURRENT_UPLOADS = 10;
int PROGRESS_UPDATE_INTERVAL = 1000;
int DEFAULT_CHUNK_SIZE = 10485760;
ExecutorService executor = Executors.newFixedThreadPool(MAX_CONCURRENT_UPLOADS);
File file = new File(filePath);
String mimeType=DocumentListEntry.MediaType.fromFileName(file.getName()).getMimeType();
String contentType=DocumentListEntry.MediaType.fromFileName(file.getName()).getMimeType();
MediaFileSource mediaFile = new MediaFileSource(file, contentType);
URL createUploadUrl = new URL("https://drive.google.com/feeds/upload/create-session/default/private/full");
FileUploadProgressListener listener = new FileUploadProgressListener();
ResumableGDataFileUploader uploader=new ResumableGDataFileUploader(createUploadUrl,mediaFile,service, DEFAULT_CHUNK_SIZE, executor, listener, PROGRESS_UPDATE_INTERVAL);
But FileUploadProgressListener showing error, It is a google api or a class...?
Please help what am wrong to upload a pdf file....
Thanks in advance
You are using Google's older API. Try the new Google Drive API
Reference :
https://developers.google.com/drive/
http://code.google.com/p/google-api-java-client/source/browse/drive-cmdline-sample/src/main/java/com/google/api/services/samples/drive/cmdline/DriveSample.java?repo=samples&r=08555cd2a27be66dc97505e15c60853f47d84b5a