I have an akka http service. I simply return the api documentation for a get request. The documentation is in html file.
It all works fine when run within the IDE. When I package it as a jar I get error 'resource not found'. I am not sure why it can not read the html file when hosted in a jar and works fine when in IDE.
Here is the code for the route.
private Route topLevelRoute() {
return pathEndOrSingleSlash(() -> getFromResource("asciidoc/html/api.html"));
}
The files are located in resource path.
I have got this working now.
I am doing this.
private Route topLevelRoute() {
try {
InputStreamReader inputStreamReader = new InputStreamReader(getClass().getResourceAsStream("/asciidoc/html/api.html"));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//Get the stream input into string builder
reader.lines().forEach(s -> strBuild.append(s));
inputStreamReader.close();
bufferedReader.close();
//pass the string builder as string with contenttype set to html
complete(HttpEntities.create(ContentTypes.TEXT_HTML_UTF8, strBuild.toString()))
} catch (Exception ex) {
//Catch any exception here
}
}
Related
I'm trying to get a midi file through a form in Vaadin, but when I try to get this File into a File class and getting a UnsupportedOperationException. This is happening in the File midiFile = fileData.getFile();
java.lang.UnsupportedOperationException: class java.io.ByteArrayOutputStream not supported. Use a UploadOutputStream
In the form it seems that the file has been loaded, but there was an error as trying to generate the File. I don't know why is this happening as I follow the methods in Vaadin documentation to get the file from the Upload. And I don't understand why it says in this exception "Happens if outputBuffer is not an UploadOutputStream".
https://vaadin.com/api/platform/23.0.9/com/vaadin/flow/component/upload/receivers/FileData.html
And if I run getFileName() from FileData after getting it from the MemoryBuffer I see that the recently uploaded file is there.
https://vaadin.com/api/platform/23.0.9/com/vaadin/flow/component/upload/receivers/MemoryBuffer.html
This is the full code.
import com.vaadin.flow.component.upload.Upload;
import com.vaadin.flow.component.upload.receivers.FileData;
import com.vaadin.flow.component.upload.receivers.MemoryBuffer;
public MainView() {
MemoryBuffer memoryBuffer = new MemoryBuffer();
Upload midiFileUpload = new Upload(memoryBuffer);
midiFileUpload.setDropLabel(new Label("Upload a file in .mid format"));
midiFileUpload.addSucceededListener(event -> {
InputStream inputFileData = memoryBuffer.getInputStream();
String fileName = event.getFileName();
long contentLength = event.getContentLength();
String mimeType = event.getMIMEType();
FileData fileData = memoryBuffer.getFileData();
try {
File midiFile = fileData.getFile();
} catch (UnsupportedOperationException uoe) {
System.out.println("OutputBuffer is not an UploadOutputStream.");
uoe.printStackTrace();
} catch (NullPointerException npe) {
System.out.println("Empty buffer.");
npe.printStackTrace();
}
});
}
As the name implies, MemoryBuffer stores the uploaded file in memory, so it can't provide a java.io.File, only an InputStream to read the data from. If you want Upload to use a (temporary!) file, use a FileBuffer instead.
I don't know why this issue is happening but I solved it just changing from MemoryBuffer to FileBuffer class. Now it works.
I want to parse a huge file in RDF4J using the following code but I get an exception due to parser limit;
public class ConvertOntology {
public static void main(String[] args) throws RDFParseException, RDFHandlerException, IOException {
String file = "swetodblp_april_2008.rdf";
File initialFile = new File(file);
InputStream input = new FileInputStream(initialFile);
RDFParser parser = Rio.createParser(RDFFormat.RDFXML);
parser.setPreserveBNodeIDs(true);
Model model = new LinkedHashModel();
parser.setRDFHandler(new StatementCollector(model));
parser.parse(input, initialFile.getAbsolutePath());
FileOutputStream out = new FileOutputStream("swetodblp_april_2008.nt");
RDFWriter writer = Rio.createWriter(RDFFormat.TURTLE, out);
try {
writer.startRDF();
for (Statement st: model) {
writer.handleStatement(st);
}
writer.endRDF();
}
catch (RDFHandlerException e) {
}
finally {
out.close();
}
}
The parser has encountered more than "100,000" entity expansions in this document; this is the limit imposed by the application.
I execute my code as following as suggested on the RDF4J web site to set up the two parameters (as in the following command)
mvn -Djdk.xml.totalEntitySizeLimit=0 -DentityExpansionLimit=0 exec:java
any help please
The error is due to the Apache Xerces XML parser, rather than the default JDK XML parser.
So Just delete Xerces XML folder from you .m2 repository and the code works fine.
I want to attach multiple files to issue. I'm able to create issue successfully however i am facing problem in attaching documents after creating issue. I have referred to this link SOLVED: attach a file using REST from scriptrunner
I am getting 404 error even though issue exists and also user has all the permissions.
File fileToUpload = new File("D:\\dummy.txt");
InputStream in = null;
try {
in = new FileInputStream(fileToUpload);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
HttpResponse < String > response3 = Unirest
.post("https://.../rest/api/2/issue/test-85/attachments")
.basicAuth(username, password).field("file", in , "dummy.txt")
.asString();
System.out.println(response3.getStatus());
here test-85 is a issueKey value.
And i am using open-unirest-java-3.3.06.jar. Is the way i am attaching documents is correct?
I am not sure how open-unirest manages its fields, maybe it tries to put them as json field, rather than post content.
I've been using Rcarz's Jira client. It's a little bit outdated but it still works.
Maybe looking at its code will help you, or you can just use it directly.
The Issue class:
public JSON addAttachment(File file) throws JiraException {
try {
return restclient.post(getRestUri(key) + "/attachments", file);
} catch (Exception ex) {
throw new JiraException("Failed add attachment to issue " + key, ex);
}
}
And in RestClient class:
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
public JSON post(String path, File file) throws RestException, IOException, URISyntaxException {
return request(new HttpPost(buildURI(path)), file);
}
private JSON request(HttpEntityEnclosingRequestBase req, File file) throws RestException, IOException {
if (file != null) {
File fileUpload = file;
req.setHeader("X-Atlassian-Token", "nocheck");
MultipartEntity ent = new MultipartEntity();
ent.addPart("file", new FileBody(fileUpload));
req.setEntity(ent);
}
return request(req);
}
So I'm not sure why you're getting a 404, Jira is sometime fuzzy and not really clear about its error, try printing the full error, or checking Jira's log if you can. Maybe it's just the "X-Atlassian-Token", "nocheck", try adding it.
I am developing a code for xcel generation and download using apache poi. LocalHost server and app server is jboss. When i run the code on localhost, a temp folder is generated in jboss's deployment folder and in that the xcel is generated and then downloaded through frontend. I am using java spring angularjs and html. This runs fine on localhost but after deploying on app server the xcel is not downloaded and it gives 500:internal server error.
angularjs controller code:
$scope.generateExcel=function(sDate,eDate,doc,search)
{
console.log("hello");
var sDate = document.getElementById('sD').value
var eDate = document.getElementById('eD').value
$scope.obj.sDate = sDate;
$scope.obj.eDate = eDate;
$scope.obj.iou = doc;
$scope.obj.du = search;
console.log($scope.obj);
$http.post('abc/generateExcel',$scope.obj).then(function()
{
//console.log(path);
$window.location.href="/ProjectName/file_name.xls";
})
.error(function()
{
console.log("Error!!");
});
};
java code:
//Method
public HttpServletResponse generateExcel ( HttpServletRequest request , HttpServletResponse response, String sD, String eD, String doc, String search)
{
//EXCEL GENERATION HERE
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=filename.xls");
//Path Specification
String path = request.getRealPath("/file_name.xls");
//System.out.println("Here...");
System.out.println(path);
FileOutputStream fileOut2 = new FileOutputStream(path);
workbook.write(fileOut2);
/*returning response*/
}
It's difficult to answer this unless one knows what's the error you are getting on the server side. Put your server code in a try-catch block. Rerun the code, and check the server logs. Paste them here.
try{
String path = request.getRealPath("/file_name.xls");
//System.out.println("Here...");
System.out.println(path);
FileOutputStream fileOut2 = new FileOutputStream(path);
workbook.write(fileOut2);
} catch(Exception e){
e.printStackTrace(); // this should print some error in server logs
}
I am having an android application that is using an external jar that
has in addition to regular classes an html file.
Meaning my final apk root directory looks something like this
assests
res
AndroidManifest.xml
classes.dex
resources.arsc
helloworld.html
How can I access from my application to the last file
"helloworld.html"?
Android package hierarchy is not a like java application package.
So you can't access files like this.
I think you have to use this helloworld.html file in your application.
So put this file in /asset directory and in your activity code just get file using
getAssets().
also access file like: file:///android_asset/helloworld.html
Why not making a library project instead of a jar?
You have to replace the string "assets/SecureManifest.xml" with your file "helloworld.html"
public static InputStream getInputStreamFromApkResource(String apkFilePath, String apkResPath) throws IOException {
JarFile jarFile = new JarFile(apkFilePath);
JarEntry jarEntry = jarFile.getJarEntry(apkResPath);
return jarFile.getInputStream(jarEntry);
}
// Example usage reading the file "SecureManifest.xml" under "assets" folder:
File sdcard = Environment.getExternalStorageDirectory();
File apkFile = new File(sdcard, "file.apk");
if (apkFile.exists()) {
try {
InputStream is =getInputStreamFromApkResource(apkFile.toString(), "assets/SecureManifest.xml");
BufferedReader br = new BufferedReader( new InputStreamReader(is));
String str;
while ((str = br.readLine()) != null) {
Log.d("***", str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
The github gist can be found here