How would I go about loading a JSON file using Laravel? - json

I have a JSON file that I'd like to load using Laravel. I'm learning Laravel and would like to know the right way to do this. I have the JSON files in a folder called json in the public folder.
In my routes.php I have the following:
Route::get('/json/{jsonfile}', array(
'as' => 'load-json',
'uses' => 'JSONController#loadJSON'
));
In JSONController I have:
public function loadJSON($jsonfile) {
// not sure what to do here
return View::make('json.display')
->with('jsonfile', $jsonfile);
}
Also is my naming convention ok or do you have better suggestions?

Always be careful when allowing a user inputed data to decide what files to read and write. Here is simple code that will take in the filename and look in the apps/storage/json folder. I'm less familiar with what Illuminate does to protect against system injections but you might want at the very least to make sure that 'filename' doesn't contain anything but alphanumeric characters with a validator.
Unless the JSON (or any file) needs to be public you shouldn't keep it in the public folder. This way they must go through your app (and permissions) to view it. Also you can have more restrictive permissions outside the public folder.
public function loadJSON($filename) {
$path = storage_path() . "/json/${filename}.json"; // ie: /var/www/laravel/app/storage/json/filename.json
if (!File::exists($path)) {
throw new Exception("Invalid File");
}
$file = File::get($path); // string
// Verify Validate JSON?
// Your other Stuff
}

Related

ASP.NET Core Read in html file from www root and replace parameters

I am trying to create a printable page that says
Hi, [Member]
We have blah blah....[MemberLocation]
Thanks. Please contact [MemberPhone]
Replacing the [Member] tags with data from the model.
I figured the best way is to save an html on wwwroot.
So I saved the above in member.html on wwwroot/staticfiles/member.html
I am having a hard time reading this file into my code.
I was hoping to do something like
memberString = System.IO.File.ReadAllText("staticfiles/member.html").ToString();
Then do something like
var memberName = model.Name;
memberString = memberString.replace([Member], memberName)
Obviously this isn't working. I can't read the file that way.
I have tried creating a service that reads the file
public class ReturnHTML
{
private readonly IHostEnvironment _env;
public ReturnHTML(IHostEnvironment env)
{
_env = env;
}
public string ReturnHTMLPage()
{
var path = Path.Combine(_env.ContentRootPath, "StaticFiles/member.html");
var htmlString = System.IO.File.ReadAllText(path);
return htmlString.ToString();
}
}
Add this a singleton in my startup.cs
But I can't figure out how to inject this and get this string.
So my question is, what is the best way to create a printable page that I can supply values to?
There are third party stuff out there that create pdf and docs that you can template. But I am not interested in third party tools. Is there any native way of doing this?

Reactive way to read and parse file from resources using WebFlux?

I wonder what is the correct way to read, parse and serve a file from resources.
Currently, I do something like this:
fun getFile(request: ServerRequest): Mono<ServerResponse> {
val parsedJson =
objectMapper.readValue(readFile("fileName.json"), JsonModel::class.java)
// modify parsed json
return ok().contentType(APPLICATION_JSON).bodyValue(parsedJson)
}
private fun readFile(fileName: String) =
DefaultResourceLoader()
.getResource(fileName)
.inputStream.bufferedReader().use { it.readText() }
I've noticed JsonObjectDecoder class in Netty, but I don't know if can be applied to my use case.
What is the reactive way to do read/parse resource file then?
After expanding #vins answer, I've came to following solution:
Jackson2JsonDecoder()
.decodeToMono(
DataBufferUtils.read(
DefaultResourceLoader()
.getResource("$fileName.json"),
DefaultDataBufferFactory(),
4096
),
ResolvableType.forClass(JsonModel::class.java), null, null
)
.map { it as JsonModel }
You can take a look at Flux.using here for file read.
As you are using Spring framework, You can also take a look at the DataBufferUtils.
This DataBufferUtils uses AsynchronousFileChannel to read the file and it also internally uses Flux.using to release the file once the file is read / cancelled by the subscriber.
#Value("classpath:somefile.json")
private Resource resource;
#GetMapping("/resource")
public Flux<DataBuffer> serve(){
return DataBufferUtils.read(
this.resource,
new DefaultDataBufferFactory(),
4096
);
}

PHPStorm Intellisense Does Not Recognize Constants Defined in Class

Is there a way to get PhpStorm intellisense to pick up these dynamically defined constants? Given the code below, PhpStorm gives the "Undefined constant SAMPLE_CONSTANT_THAT_WAS_DYNAMICALLY_DEFINED" error message.
class ExampleConfiguration
{
private $configurationMapping;
...
public function DefineConfigConstants()
{
foreach ($this->configurationMapping as $key => $value)
define($key, $value);
}
}
class ExampleClass
{
public function Test()
{
print SAMPLE_CONSTANT_THAT_WAS_DYNAMICALLY_DEFINED;
}
}
This issue can be tracked here: https://youtrack.jetbrains.com/issue/WI-11390, what I'm looking for is suggestions for workarounds.
IDE needs to know about such constants in order to not to complain about them. This means that they have to be defined in "normal" way (actual values do not matter, as long as they are not used for file names/paths in include/require statements).
Suggestion: write custom script that create such myconstants.php file where they will be defined in a normal way (since all such constants defined by users and stored in DB, you have to fetch them from DB yourself) .. and run this script (to update generated file) before working with the code in PhpStorm.

grails - Downloading PDF getting empty file

I'm storing some files within my mysql database. The corresponding domain class looks as follows:
import org.springframework.web.multipart.commons.CommonsMultipartFile
import grails.persistence.Entity
#Entity
class Document extends BaseClass {
String documentReference
CommonsMultipartFile cmfFile
static constraints = {
documentReference nullable: true, maxSize: 500
}
static mapping = {
cmfFile sqlType: "mediumblob"
}
}
I managed to successfully store different files within the table in the database. Now I want to enable the user to download any of these files using the following action:
def download(Document documentInstance) {
if (documentInstance == null) {
notFound()
return
}
response.setContentType(documentInstance?.cmfFile?.contentType)
response.setHeader("Content-disposition", "attachment;filename=${documentInstance?.cmfFile?.originalFilename}")
response.outputStream << documentInstance?.cmfFile?.getBytes()
response.outputStream.flush()
return true
}
My problem now is that downloading works perfectly fine with .docx, textfiles or images. However, when I'm trying to download e.g. .pdf or .zip all files are empty. I don't know what the difference is as I'm also passing on the content type.
I would be greatful for any help! Thank you!
I also use Grails (2.3.11) and I store files in MySQL and it works like a charm.
The differences I can see are:
Domain
I use Blob type instead of CommonsMultipartFile and type: 'blob' instead of sqlType: 'mediumblob'. To set value to such a field you can use new javax.sql.rowset.serial.SerialBlob(byte[]).
Controller
I use (adjusted to your naming):
response.setContentType(servletContext.getMimeType(documentInstance?.cmfFile?.originalFilename))
response.setHeader("Content-disposition", "inline;filename=${documentInstance?.cmfFile?.originalFilename}")
response.outputStream << documentInstance?.cmfFile?.getBytes()
No flush(), no return true.
Notes
I also noticed you use quite small maxSize constraint. 500 B is not too much. Are you sure it's enough for your PDFs or ZIPs?
Besides, are you sure documentInstance?.cmfFile is not null?

How to export data from LinqPAD as JSON?

I want to create a JSON file for use as part of a simple web prototyping exercise. LinqPAD is perfect for accessing the data from my DB in just the shape I need, however I cannot get it out as JSON very easily.
I don't really care what the schema is, because I can adapt my JavaScript to work with whatever is returned.
Is this possible?
A more fluent solution is to add the following methods to the "My Extensions" File in Linqpad:
public static String DumpJson<T>(this T obj)
{
return
obj
.ToJson()
.Dump();
}
public static String ToJson<T>(this T obj)
{
return
new System.Web.Script.Serialization.JavaScriptSerializer()
.Serialize(obj);
}
Then you can use them like this in any query you like:
Enumerable.Range(1, 10)
.Select(i =>
new
{
Index = i,
IndexTimesTen = i * 10,
})
.DumpJson();
I added "ToJson" separately so it can be used in with "Expessions".
This is not directly supported, and I have opened a feature request here. Vote for it if you would also find this useful.
A workaround for now is to do the following:
Set the language to C# Statement(s)
Add an assembly reference (press F4) to System.Web.Extensions.dll
In the same dialog, add a namespace import to System.Web.Script.Serialization
Use code like the following to dump out your query as JSON
new JavaScriptSerializer().Serialize(query).Dump();
There's a solution with Json.NET since it does indented formatting, and renders Json dates properly. Add Json.NET from NuGet, and refer to Newtonsoft.Json.dll to your “My Extensions” query and as well the following code :
public static object DumpJson(this object value, string description = null)
{
return GetJson(value).Dump(description);
}
private static object GetJson(object value)
{
object dump = value;
var strValue = value as string;
if (strValue != null)
{
var obj = JsonConvert.DeserializeObject(strValue);
dump = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);
}
else
{
dump = JsonConvert.SerializeObject(value, Newtonsoft.Json.Formatting.Indented);
}
return dump;
}
Use .DumpJson() as .Dump() to render the result. It's possible to override more .DumpJson() with different signatures if necessary.
As of version 4.47, LINQPad has the ability to export JSON built in. Combined with the new lprun.exe utility, it can also satisfy your needs.
http://www.linqpad.net/lprun.aspx