I just created a new project with Symfony (This is not my first time), but when I run the application in the browser, appears this error:
Parse error: syntax error, unexpected '{' in
/var/www/ProjectName/var/bootstrap.php.cache on line 2094
If I go to that line in that file there is :
$this->loading[$id] = true;
try {
$service = $this->$method();
} catch (\Exception $e) {
unset($this->services[$id]);
throw $e;
} finally {
unset($this->loading[$id]);
}
return $service;
}
The line 2094 is this piece:
} finally {
What I have to do to make it work?
Related
Wp action-scheduler job is running successfully but I want it to fail when any exception comes in the code.
try {
$records = some records in array;
foreach ($records as $r) {
$sku = $r["SKU"] ?? null;
if (!isset($sku)) {
throw new \Exception("SKU is missing");
return;
}
$product_id = Wp::wc_get_product_id_by_sku($sku);
Wp::update_post_meta($product_id, "_regular_price", 500);
}
} catch (\Exception $e) {
echo($e);
**//Here I want to fail the action scheduler job**
return false;
}
In my case, everything works correctly but it should be failed schedule job if comes into catch (\Exception $e){---} without site break.
I have Java CLI application based on cliche library and I want to migrate it to picocli.
My application was based on cliche so I have a lot of methods with asg.cliche.Command annotation which return some result. cliche prints command methods's result automatically so result was printed in command line. I replaced asg.cliche.Command annotations by picocli.CommandLine.Command and I see that picocli does not print command methods's results.
I have following class:
import picocli.CommandLine;
#CommandLine.Command(subcommandsRepeatable = true)
public class Foo
{
public static void main( String[] args )
{
new CommandLine( new Foo() ).execute( args );
}
#CommandLine.Command
public String sayHello()
{
return "Hello";
}
#CommandLine.Command
public String sayGoodbye()
{
return "GoodBye";
}
}
when I call java -cp myJar.jar Foo sayHello sayGoodbye I do not see any output.
I see three solutions:
1. Modify each methods to print result instead of return it.
import picocli.CommandLine;
#CommandLine.Command( subcommandsRepeatable = true )
public class Foo2
{
public static void main( String[] args )
{
new CommandLine( new Foo2() ).execute( args );
}
#CommandLine.Command
public void sayHello()
{
System.out.println( "Hello" );
}
#CommandLine.Command
public void sayGoodbye()
{
System.out.println( "GoodBye" );
}
}
I am not happy with this solution. I prefer not modify my methods.
Retrieve results after execution.
public static void main( String[] args )
{
final CommandLine commandLine = new CommandLine( new Foo() );
commandLine.execute( args );
CommandLine.ParseResult parseResult = commandLine.getParseResult();
for( CommandLine.ParseResult pr : parseResult.subcommands() )
{
System.out.println( pr.commandSpec().commandLine()
.getExecutionResult()
.toString() );
}
}
I see a few problems with this solution. The main problem is formatting. Execution result can be null, array, collection. The second problem is that results are printed after execution of all subcommands. If second subcommand throws exception then I firstly see exception stack trace and after that I see result of first subcommand.
Ask on stackoverflow if there is some better solution. I do not believe that there is no any configuration option in picocli which enable results printing.
Personally, I like your first solution best, it is simple and easy to maintain. Maybe introduce a helper method for the printing and formatting so the command methods can look like this:
#CommandLine.Command
public String sayGoodbye()
{
return printValue("GoodBye");
}
You already found the CommandLine.getParseResult method; perhaps a helper method could assist with the formatting there as well.
There is a third option, but it is unfortunately quite a bit more complex: you can create a custom IExecutionStrategy that prints the result of each command after executing it. It involves copying a lot of code from the picocli internals and it’s not really a realistic solution; I just mention it for completeness.
// extend RunLast to handle requests for help/version and exit code stuff
class PrintingExecutionStrategy extends CommandLine.RunLast {
#Override
protected List<Object> handle(ParseResult parseResult) throws ExecutionException {
// Simplified: executes only the last subcommand (so no repeating subcommands).
// Look at RunLast.executeUserObjectOfLastSubcommandWithSameParent if you need repeating subcommands.
List<CommandLine> parsedCommands = parseResult.asCommandLineList();
CommandLine last = parsedCommands.get(parsedCommands.size() - 1);
return execute(last, new ArrayList<Object>());
}
// copied from CommandLine.executeUserObject,
// modified to print the execution result
private List<Object> execute(CommandLine cmd, List<Object> executionResultList) throws Exception {
Object command = parsed.getCommand();
if (command instanceof Runnable) {
try {
((Runnable) command).run();
parsed.setExecutionResult(null); // 4.0
executionResultList.add(null); // for compatibility with picocli 2.x
return executionResultList;
} catch (ParameterException ex) {
throw ex;
} catch (ExecutionException ex) {
throw ex;
} catch (Exception ex) {
throw new ExecutionException(parsed, "Error while running command (" + command + "): " + ex, ex);
}
} else if (command instanceof Callable) {
try {
#SuppressWarnings("unchecked") Callable<Object> callable = (Callable<Object>) command;
Object executionResult = callable.call();
System.out.println(executionResult); <-------- print result
parsed.setExecutionResult(executionResult);
executionResultList.add(executionResult);
return executionResultList;
} catch (ParameterException ex) {
throw ex;
} catch (ExecutionException ex) {
throw ex;
} catch (Exception ex) {
throw new ExecutionException(parsed, "Error while calling command (" + command + "): " + ex, ex);
}
} else if (command instanceof Method) {
try {
Method method = (Method) command;
Object[] parsedArgs = parsed.getCommandSpec().argValues();
Object executionResult;
if (Modifier.isStatic(method.getModifiers())) {
executionResult = method.invoke(null, parsedArgs); // invoke static method
} else if (parsed.getCommandSpec().parent() != null) {
executionResult = method.invoke(parsed.getCommandSpec().parent().userObject(), parsedArgs);
} else {
executionResult = method.invoke(parsed.factory.create(method.getDeclaringClass()), parsedArgs);
}
System.out.println(executionResult); <-------- print result
parsed.setExecutionResult(executionResult);
executionResultList.add(executionResult);
return executionResultList;
} catch (InvocationTargetException ex) {
Throwable t = ex.getTargetException();
if (t instanceof ParameterException) {
throw (ParameterException) t;
} else if (t instanceof ExecutionException) {
throw (ExecutionException) t;
} else {
throw new ExecutionException(parsed, "Error while calling command (" + command + "): " + t, t);
}
} catch (Exception ex) {
throw new ExecutionException(parsed, "Unhandled error while calling command (" + command + "): " + ex, ex);
}
}
throw new ExecutionException(parsed, "Parsed command (" + command + ") is not a Method, Runnable or Callable");
}
}
Use it like this:
public static void main(String... args) {
new CommandLine(new Foo())
.setExecutionStrategy(new PrintingExecutionStrategy())
.execute(args);
}
I wouldn’t recommend the above.
Update: I thought of another, fourth, option (actually a variation of your 2nd solution). You can specify a custom IExecutionExceptionHandler that doesn’t print the stacktrace, but instead stores the exception so you can print the stacktrace after printing the command results. Something like this:
class MyHandler extends IExecutionExceptionHandler() {
Exception exception;
public int handleExecutionException(Exception ex,
CommandLine commandLine,
ParseResult parseResult) {
//ex.printStackTrace(); // no stack trace
exception = ex;
}
}
Use it like this:
public static void main(String... args) {
MyHandler handler = new MyHandler();
CommandLine cmd = new CommandLine(new Foo())
.setExecutionExceptionHandler(handler);
cmd.execute(args);
ParseResult parseResult = cmd.getParseResult();
for( ParseResult pr : parseResult.subcommands() )
{
System.out.println( pr.commandSpec().commandLine()
.getExecutionResult()
.toString() );
}
if (handler.exception != null) {
handler.exception.printStackTrace();
}
}
I built a web application using spring MVC, everything is working fine except the file upload in which I got random FileNotFoundExceptions. I found some solutions online like using a different tmp folder but I keep getting random error.
My code is:
#RequestMapping(value="/upload", method=RequestMethod.POST)
public #ResponseBody String handleFileUpload(#RequestParam("file") final MultipartFile multipartFile,
#RequestHeader("email") final String email, #RequestHeader("password") String password){
if (authenticateUser(email, password)) {
if (!multipartFile.isEmpty()) {
System.out.println("Start processing");
Thread thread = new Thread(){
public void run(){
ProcessCSV obj = new ProcessCSV();
try {
File file = multipartToFile(multipartFile);
if(file !=null) {
obj.extractEvents(file, email, cluster, session);
}
else {
System.out.println("null File");
}
} catch (IOException e) {
System.out.println("File conversion error");
e.printStackTrace();
}
}
};
thread.start();
return "true";
} else {
return "false";
}
}
else {
return "false";
}
}
and:
public File multipartToFile(MultipartFile multipartFile) throws IOException {
File uploadFile = null;
if(multipartFile != null && multipartFile.getSize() > 0) {
uploadFile = new File("/tmp/" + multipartFile.getOriginalFilename());
FileOutputStream fos = null;
try {
uploadFile.createNewFile();
fos = new FileOutputStream(uploadFile);
IOUtils.copy(multipartFile.getInputStream(), fos);
} catch (FileNotFoundException e) {
System.out.println("File conversion error");
e.printStackTrace();
} catch (IOException e) {
System.out.println("File conversion error");
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
System.out.println("File conversion error");
e.printStackTrace();
}
}
}
}
else {
System.out.println("null MultipartFile");
}
return uploadFile;
}
and the configuration file:
multipart.maxFileSize: 100MB
multipart.maxRequestSize: 100MB
multipart.location = ${user.home}
server.port = 8090
I used different versions of the multipartToFile function, one was using multipartfile.transferTo() but I was getting the same random error. Any advice?
Thank you
EDIT stack trace:
java.io.IOException: java.io.FileNotFoundException: /Users/aaa/upload_07720775_4b37_4b86_b370_40280388f3a4_00000003.tmp (No such file or directory)
at org.apache.catalina.core.ApplicationPart.write(ApplicationPart.java:121)
at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile.transferTo(StandardMultipartHttpServletRequest.java:260)
at main.RESTController.multipartToFile(RESTController.java:358)
at main.RESTController$1.run(RESTController.java:241)
Caused by: java.io.FileNotFoundException: /Users/aaa/upload_07720775_4b37_4b86_b370_40280388f3a4_00000003.tmp (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at org.apache.tomcat.util.http.fileupload.disk.DiskFileItem.write(DiskFileItem.java:392)
at org.apache.catalina.core.ApplicationPart.write(ApplicationPart.java:119)
... 3 more
I had just had a night of terror with this error. I found out that MultiPartFile is only recognisable to and by the #Controller class. So if you pass it to another bean which is not a controller, Spring will not be able to help you. It somewhat makes sense that the #Controller is tightly bound to the front screen (communication from the browser to the system - Controllers are the entry point from the browser). So any conversation must happen there in the Controller.
In my case, I did something like the following:
#Controller
public class FileUploadingController{
#PostMapping("/uploadHistoricData")
public String saveUploadedDataFromBrowser(#RequestParam("file") MultipartFile file) {
try {
String pathToFile = "/home/username/destination/"
new File(pathToFile).mkdir();
File newFile = new File(pathToFile + "/uploadedFile.csv");
file.transferTo(newFile); //transfer the uploaded file data to a java.io.File which can be passed between layers
dataService.processUploadedFile( newFile);
} catch (IOException e) {
//handle your exception here please
}
return "redirect:/index?successfulDataUpload";
}
}`
I had the same problem, it looks like MultipartFile is using different current dir internally, so all not absolute paths are not working.
I had to convert my path to an absolute path and then it worked.
It is working inside #RestController and in other beans too.
Path path = Paths.get(filename).toAbsolutePath();
fileToImport.transferTo(path.toFile());
fileToImport is MultipartFile.
I am using the google api client to get a list of blogger posts (see below code).
try {
// create service and get data
$blogger = new \Google_Service_Blogger($this->client);
// https://developers.google.com/blogger/docs/3.0/reference/posts/list
// GET https://www.googleapis.com/blogger/v3/blogs/blogId/posts
if ($this->cache->contains('posts')) {
$posts = $this->cache->fetch('posts');
}
else {
$posts = $blogger->posts->listPosts($this->bloggerId, $optParams);
$this->cache->save('posts', $posts, 600); // 600 = 10 mins
}
return $posts;
} catch (apiServiceException $e) {
// Error from the API.
//print 'There was an API error : ' . $e->getCode() . ' : ' . $e->getMessage();
} catch (Exception $e) {
//print 'There was a general error : ' . $e->getMessage();
}
This works fine on most occasions, but occasionally I get an API error which is not caught.
Google_Service_Exception: Error calling GET https://www.googleapis.com/blogger/v3/blogs/8894809254783984374/posts?maxResults=5: (500) Backend Error at /var/www/releases/20140607051057/vendor/google/apiclient/src/Google/Http/REST.php:79)"} []
Does anyone know why this error is thrown, and how I can deal with it?
Cheers
The problem is with the namespaces. You can use the generic:
} catch (\Exception $e) {
//print 'There was a general error : ' . $e->getMessage();
}
or, more specific:
try {
...
} catch (\Google_Service_Exception $e) {
//print 'There was a general error : ' . $e->getMessage();
}
Exception is the base class for all Exceptions. See http://php.net/manual/en/class.exception.php
I am a total noob at Laravel
public function stageFiles($user, $project) {
try
{
$path = Input.get("item");
}
catch (Exception $e)
{
$exceptionMessage = $e->getMessage();
$responseText = json_encode($exceptionMessage);
}
}
What I want to do is return the response text and a status code, 500, how can I do this?
This is how you send a 500:
public function stageFiles($user, $project) {
try
{
$path = Input.get("item");
}
catch (Exception $e)
{
$exceptionMessage = $e->getMessage();
$responseText = json_encode($exceptionMessage);
return Response::make($responseText, 500);
}
}