I have made this code for class but I just can't figure out why it is that when I click on a link, it won't show me the .jpg or .mp4 file. I've been scouring the Internet and I've tried converting the image from CMYK to RGB, adding even more CRLF to the end of the file and I simply can't understand why it gives me this error:
"The image cannot be displayed because it contains errors."
or
"The mp4 file cannot be displayed because it is corrupted"
This is my "welcome page"
<html>
<head>
<title> Welcome to my server</title>
</head>
<body bgcolor=white>
<p> Click one of the following: </p>
<p> Candy </p>
<p> Rossi vs Stoner </p>
</body>
</html>
And this is my server.
import java.io.*;
import java.net.Socket;
import java.util.*;
import java.awt.*;
import javax.imageio.*;
public class HTTPRequest implements Runnable
{
public static String CRLF = "\r\n"; // returning carriage return (CR) and a line feed (LF)
Socket socket;
// constructor
public HTTPRequest(Socket socket) throws Exception
{
this.socket = socket;
}
// Implement the run() method of the Runnable interface.
// Within run(), we explicitly catch and handle exceptions with a try/catch statement.
public void run()
{
try
{
processRequest();
} catch (Exception e)
{
System.out.println(e);
}
}
private void processRequest() throws Exception
{
//create an input and an output stream
InputStream instream = socket.getInputStream();
DataOutputStream outStream = new DataOutputStream(socket.getOutputStream());
// create a buffer
BufferedReader buffRead = new BufferedReader(new InputStreamReader(instream));// reads the input data
// Get the request line of the HTTP request message.
String requestLine = buffRead.readLine();// get /path/file.html version of http
// Display the request line.
System.out.println();
System.out.println(requestLine);
// HERE WE NEED TO DEAL WITH THE REQUEST
// Extract the filename from the request line.
StringTokenizer tokens = new StringTokenizer(requestLine);
tokens.nextToken();
String fileName = tokens.nextToken();
//this is so that i don't have to write /front.html at the start
if(fileName.equals("/")){
fileName="/front.html";
}
// attach a "." so that file request is within the current directory.
fileName = "." + fileName;
// Open the requested file.
FileInputStream fis = null;
boolean fileExists = true;
try
{
fis = new FileInputStream(fileName);
} catch (FileNotFoundException e)
{
fileExists = false;
}
// Construct the response message.
String statusLine = null;
String contentTypeLine = null;
String entityBody = null;
if (fileExists)
{
statusLine = "HTTP/1.0 200 OK" + CRLF; // 200 success code
contentTypeLine = "Content-type: " + contentType(fileName) + CRLF;
}// content info
else
{
contentTypeLine = "Content-type: text/html" + CRLF;// content info
entityBody = "<HTML>" + "<HEAD><TITLE>Not Found</TITLE></HEAD>"
+ "<BODY>Not Found</BODY></HTML>";
statusLine = "HTTP/1.0 404 Not Found" + CRLF;// 404 not found...
}
// Send the status line.
outStream.writeBytes(statusLine);
// Send the content type line.
outStream.writeBytes(contentTypeLine);
// Send a blank line to indicate the end of the header lines.
outStream.writeBytes(CRLF);
// Send the entity body.
if (fileExists)
{
outStream.writeBytes(statusLine);// Send the status line.
outStream.writeBytes("\n"+contentTypeLine);// Send the content type line.
sendBytes(fis, outStream);
fis.close();
} else
{
outStream.writeBytes(statusLine);// Send the status line
outStream.writeBytes("\n"+contentTypeLine);// Send the content type line.
outStream.writeBytes(entityBody);// Send the an html error message info body.
}
System.out.println("*****");
System.out.println(fileName);// print out file request to console
System.out.println("*****");
// Get and display the header lines.
String headerLine = null;
while ((headerLine = buffRead.readLine()).length() != 0)
{
System.out.println(headerLine);
}
// Close streams and socket.
outStream.close();
buffRead.close();
socket.close();
}
// return the file types
private static String contentType(String fileName)
{
if (fileName.endsWith(".htm") || fileName.endsWith(".html"))
{
return "text/html";
}
if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg"))
{
return "image/jpeg";
}
if (fileName.endsWith(".gif"))
{
return "image/gif";
}
if(fileName.endsWith(".mp4"))
{
return "movie";
}
return "application/octet-stream";
}
// set up i/o streams
private static void sendBytes(FileInputStream fis, DataOutputStream outStream)
throws Exception
{
// Construct a 1K buffer to hold bytes on their way to the socket.
byte[] buffer = new byte[1024];
int bytes = 0;
// Copy requested file into the socket's output stream.
while ((bytes = fis.read(buffer)) != -1)// read() returns minus one, indicating that the end of the file
{
outStream.write(buffer, 0, bytes);
outStream.writeBytes("\r\n");
}
}
}
Please help me. thank you.
i don't get this line :
outStream.writeBytes("\r\n");
anyway, could you dump the post so that we could check what's going on ?
Related
An attempt was made to implement file downloads through the SpringBoot MVC structure. There is no error, it says it has run normally, but the download does not proceed.
All information about the file is entered correctly, and also the path and name of the file are entered correctly.
I'd like to know why the download doesn't proceed even though there's no error.
#RestController
public class Controller {
#PostMapping("/fileDownload")
public void fileDownload(#RequestBody BoardFileDTO dto,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
//File contains all stored paths, names, and extensions
Path fileNamePath = Paths.get(Directory + dto.getFile_save_name()).toAbsolutePath();
String filename = dto.getFile_save_name(); //The name of the saved file
String downname = dto.getFile_name(); //The name of the file to be saved
if (filename == null || "".equals(filename)) {
filename = downname;
}
try {
String browser = request.getHeader("User-Agent");
//File Encoding
if (browser.contains("MSIE") || browser.contains("Trident")
|| browser.contains("Chrome")) {
filename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+",
"%20");
} else {
filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
}
} catch (UnsupportedEncodingException ex) {
System.out.println("UnsupportedEncodingException");
}
System.out.println(fileNamePath);
File file1 = new File(fileNamePath.toString());
if (!file1.exists()) {
return ;
}
// Specifying a File
response.setContentType("application/octer-stream");
response.setHeader("Content-Transfer-Encoding", "binary;");
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
try {
OutputStream os = response.getOutputStream();
FileInputStream fis = new FileInputStream(fileNamePath.toString());
int ncount = 0;
byte[] bytes = new byte[512];
while ((ncount = fis.read(bytes)) != -1 ) {
os.write(bytes, 0, ncount);
}
fis.close();
os.close();
} catch (FileNotFoundException ex) {
System.out.println("FileNotFoundException");
} catch (IOException ex) {
System.out.println("IOException");
}
}
}
Your code is a bit convoluted imho. A couple of issues I see with your code
Using Path.toString to convert to a File, use the proper factory methods instead or use java.nio.Files to check the existence.
Your content-type is wrong application/octer-stream isn't a known content-type (you probably want application/octet-stream.
Copying from a Path or File is better done with either the StreamUtils from Spring or the java.nio.Files class (if you already have a Path use that).
#PostMapping("/fileDownload")
public void fileDownload(#RequestBody BoardFileDTO dto, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
//File contains all stored paths, names, and extensions
Path fileNamePath = Paths.get(Directory, dto.getFile_save_name()).toAbsolutePath();
if (!Files.exists(fileNamePath)) {
return;
}
String filename = determineFilename(dto, request);
// Specifying a File
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader("Content-Transfer-Encoding", "binary;");
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
try {
Files.copy(fileNamePath, response.getOutputStream());
} catch (IOException ex) {
System.out.println("IOException");
}
}
private static String determineFilename(BoardFileDTO dto, HttpServletRequest request) {
String filename = dto.getFile_save_name(); //The name of the saved file
if (filename == null || "".equals(filename)) {
filename = dto.getFile_name();
}
String browser = request.getHeader("User-Agent");
//File Encoding
if (browser.contains("MSIE") || browser.contains("Trident") || browser.contains("Chrome")) {
filename = URLEncoder.encode(filename, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
} else {
filename = new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
}
return filename;
}
It would write it something like that. As you have a path use the java.nio.Files to check for existence and copying. Use constants for mediatypes and charsets.
Your error handling is quite basic (I would say non-existing and at least not proper) as the processing just stops and returns an empty 200 to the client. No information what so ever.
I took the liberty to factor out the logic to determine the filename, which should make your code more readable.
Im using FOP version 2.1. I have a xsl fo template where i want to show images:
<xsl:variable name="ImagePath" select="defaultImageUrl"/>
<fo:external-graphic src="{$ImagePath}" content-width="scale-down-to-fit" width="100%"/>
Some images have a webadress like so:
https://upload.wikimedia.org/wikipedia/commons/thumb/b/b1/Tulipa_biflora_UME.jpg/800px-Tulipa_biflora_UME.jpg
But other images come from my webserver from address like:
https://localhost:4200/api/download/image/?fixedPrice=true&productId=1329&fileId=1304
This responds to endpoint:
public ResponseEntity<byte[]> getFileAsResponseEntity(#RequestParam boolean fixedPrice, #RequestParam long productId, #RequestParam long fileId) throws IOException, SQLException {
HttpHeaders headers = new HttpHeaders();
FileDownload fileDownload = productService.getProductFile(productId, fileId, fixedPrice);
headers.setCacheControl(CacheControl.noCache().getHeaderValue());
String n = fileDownload.getFileName().toLowerCase();
if (fileDownload.getFileTypeEnum().equals(FileTypeEnum.PICTURE) && (n.contains(".jpeg") || n.contains("jpg"))) {
headers.setContentType(MediaType.IMAGE_JPEG);
} else if (fileDownload.getFileTypeEnum().equals(FileTypeEnum.PICTURE) && (n.contains(".png"))) {
headers.setContentType(MediaType.IMAGE_PNG);
} else if (fileDownload.getFileTypeEnum().equals(FileTypeEnum.PICTURE) && (n.contains(".gif"))) {
headers.setContentType(MediaType.IMAGE_GIF);
}
return new ResponseEntity<>(fileDownload.getByteArray(), headers, HttpStatus.OK);
}
Is there a way for fo:external-graphic to accept these 2 different urls? Or is there something additional i need to do for it to work, since currently when the image comes from the webserver, the the resulting pdf file does not have the image in it, only a white space.
EDIT:
Here is the code that should make the XML to XSL to PDF:
byte[] xsl = IOUtils.toByteArray(this.getClass().getResourceAsStream("/browserDocument.xsl"));
byte[] xml = getBrowserDocument(filter, clientId, representId, ecatMain, showImage, language);
InputStream inStr = this.getClass().getResourceAsStream("/fop.xml");
FopFactory fopFactory = FopFactory.newInstance(new java.net.URI("."), inStr);
ByteArrayOutputStream out = new ByteArrayOutputStream();
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);
javax.xml.transform.Source xsltSrc = new StreamSource(new ByteArrayInputStream(xsl));
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer(xsltSrc);
String xmlStr = new String(xml, "UTF-8");
xmlStr = xmlStr.replaceAll("<", "<");
xmlStr = xmlStr.replaceAll(">", ">");
javax.xml.transform.Source src = new StreamSource(new ByteArrayInputStream(xmlStr.getBytes("UTF-8")));
Result res = new SAXResult(fop.getDefaultHandler());
transformer.transform(src, res);
return out.toByteArray();
I keep getting error message in the log files:
2019-01-30 16:07:48.300 ERROR 8424 --- [https-jsse-nio-8087-exec-3] org.apache.fop.apps.FOUserAgent : Image not found. URI: https://localhost:4200/api/efront/secure/download/product/image/?fixedPrice=false&productId=2823&fileId=1756. (No context info available)
It seems like it is calling the URL, but it is not getting the actual image from it. Maybe some issue with the image headers or the FOUseragent is getting blocked?
Well, implementing all above possible logic and seeing your code, I think URIResolver would help getting out of this as below:
Add it to your code : fopFactory.setURIResolver(new ResolveURIForWebServer());
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
public class ResolveURIForWebServer implements URIResolver {
#Override
public Source resolve(String href, String baseURI) throws TransformerException {
Source source = null;
try {
// CONVERT IMAGE TO INPUTSTREAM
source = new StreamSource(InputStream);
} catch (Exception e) {
} finally {
}
return source;
}
}
Hope it helps.
I am currently new on Apache Nifi and still exploring it.
I made a custom processor where I will fetch data from server with pagination.
I pass the input file which will contains the attribute "url".
Finally transfer the response in output flow file, as I fetch data with pagination, so I made a new output flow file for each page and transferred it to Successful relationship.
Below is the code part:
#Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
FlowFile incomingFlowFile = session.get();
String api = null;
if (incomingFlowFile == null) {
logger.info("empty input flow file");
session.commit();
return;
} else {
api=incomingFlowFile.getAttribute("url");
}
session.remove(incomingFlowFile);
if(api == null) {
logger.warn("API url is null");
session.commit();
return;
}
int page = Integer.parseInt(context.getProperty(PAGE).getValue());
while(page < 3) {
try {
String url = api + "&curpg=" + page;
logger.info("input url is: {}", url);
HttpResponse response = httpGetApiCall(url, 10000);
if(response == null || response.getEntity() == null) {
logger.warn("response null");
session.commit();
return;
}
String resp = EntityUtils.toString(response.getEntity());
InputStream is = new ByteArrayInputStream(StandardCharsets.UTF_16.encode(resp).array());
FlowFile outFlowFile = session.create();
outFlowFile = session.importFrom(is, outFlowFile);
session.transfer(outFlowFile, SUCCESSFUL);
} catch (IOException e) {
logger.warn("IOException :{}", e.getMessage());
return;
}
++page;
}
session.commit();
}
I am facing issue that for a single Input flow file, this processor get triggered twice and so it generates 4 flow files for a single input flow file.
I am not able to figure out this where I have done wrong.
Please help in this issue.
Thanks in advance.
======================================================================
processor group 1(Nifi_Parvin)
processor group 2 (News_Point_custom)
I have a list of files to send from my device to my server.
List<myFiles> list = new List<myFiles>() { "[long list of files...]" };
For that I want to create a list of tasks: for each file I should invoke a function that sends to my webapi that file via PUT
public async Task<bool> UploadPhoto(byte[] photoBytes, int PropertyId, string fileName)
{
bool rtn = false;
if (CrossConnectivity.Current.IsConnected)
{
var content = new MultipartFormDataContent();
var fileContent = new ByteArrayContent(photoBytes);
fileContent.Headers.ContentType =
MediaTypeHeaderValue.Parse("multipart/form-data");
fileContent.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment")
{
FileName = fileName + ".jpg"
};
content.Add(fileContent);
string url = RestURL() + "InventoriesPicture/Put";
try
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("authenticationToken", SyncData.Token);
HttpResponseMessage response = await client.PutAsync(url, content);
if (response.IsSuccessStatusCode)
{
rtn = true;
Debug.WriteLine($"UploadPhoto response {response.ReasonPhrase}");
}
else
{
Debug.WriteLine($"UploadPhoto response {response.ReasonPhrase}");
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"UploadPhoto exception {ex.Message}");
}
Debug.WriteLine($"UploadPhoto ends {fileName}");
}
return rtn;
}
In a function I have a foreach that calls UploadPhoto. I think there are too many tasks at the same time then I want to send a file, wait the result from the webapi and then send next file and so on.
What can I do? What is the best practice for that? Or in any case how can I resolve my problem? :)
Thank you in advance
I am facing a problem in value 'return' in Asynctask class in doInBackground method. I am getting an error, about 'missing return statement in below code.
`public class ForecastNetwork extends AsyncTask {
public final String TAG = ForecastNetwork.class.getSimpleName();
#Override
protected Void doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7");
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
} catch (IOException e) {
Log.e(TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(TAG, "Error closing stream", e);
}
}
}
}`
What Should I return at the end?
I assume that you forgot to return the processing result
forecastJsonStr = buffer.toString();
return forecastJsonStr;