Storing a message in flash generates encoding troubles - grails

I have some encoding problems when using flash.message = "Message" to set an error message. When printing it out in the view later, like it was ISO8859-1 instead of UTF.
This is my code:
try {
assert xml.results.result.size() == 1
}
catch(AssertionError e) {
flash.message = "Fel, hittade mer än ett resultat. Detta ska inte hända, var god och radera en xxx för detta xxx"
println "Error, found more than one result. This should not occur, please remove one of the result for this id."
println e.getMessage()
}
It's a standard grails app and all I have done is to use generate-all for a domain controller.

try to use:
render(view: "view", ..., encoding: "UTF-8")

Be sure your file (in your IDE) is encoding in the same encoding as Grails property:
grails.views.gsp.encoding
Should be UTF-8 by default.

Related

Java 8 issues printing PS to network printer

Got a weird question for you. Recently upleveled my old project from java 7(jdk1.7.0_10) to java 8(1.8.0.91.x86_64). In java 7 it printed the post script file with no issues and now it is printing the postscript file as plain text instead of converting the file. This is on a redhat linux environment. Simply I am trying to print a string containing a post script file of a file itself.
Here is my original code
DocFlavor flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
PrintService pService = PrintServiceLookup.lookupDefaultPrintService();
// In a field environment, send to the printer
if (System.getenv("USER_DEFINED_RELTOP") == null || pfr.exists()) {
if (pService.getName().isEmpty()) {
LOGGER.error("No printer selected");
} else {
LOGGER.info("Printing to " + pService.getName());
DocPrintJob pj = pService.createPrintJob();
try {
InputStream is = new ByteArrayInputStream(data.getBytes("UTF8"));
Doc doc = new SimpleDoc(is, flavor, null);
PrintJobWatcher pjw = new PrintJobWatcher(pj);
pj.print(doc, null);
pjw.waitForDone();
is.close();
} catch (PrintException | IOException e) {
LOGGER.error(e);
} // try block
} // no printer selected
// Otherwise, send to a file
} else {
That worked fine in java 7, I updated it to the oracle spec found here for java 8.
https://docs.oracle.com/javase/8/docs/api/javax/print/PrintService.html#createPrintJob--
https://docs.oracle.com/javase/8/docs/technotes/guides/jps/spec/printing.fm6.html
DocFlavor psFlavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;
PrintRequestAttributeSet attrs = new HashPrintRequestAttributeSet();
attrs.add(MediaSizeName.ISO_A4);
PrintService[] pservices = PrintServiceLookup.lookupPrintServices(psFlavor,
attrs);
File pfr = new File(PFR_INDICATOR);
// In a field environment, send to the printer
if (System.getenv("USER_DEFINED_RELTOP") == null || pfr.exists()) {
//Check we have a printer capable of post script
if (pservices.length > 0) {
LOGGER.info("Printing to " + pservices[0].getName());
DocPrintJob pj = pservices[0].createPrintJob();
try {
InputStream fis = new ByteArrayInputStream(data.getBytes("UTF8"));
//byte[] ba =data.getBytes("UTF8");
Doc doc = new SimpleDoc(fis, psFlavor, null);
LOGGER.info("Doc Flavor " + doc.getDocFlavor());
PrintJobWatcher pjw = new PrintJobWatcher(pj);
LOGGER.info("PrintJob Attributes : " + pj.getAttributes());
pj.print(doc, attrs);
pjw.waitForDone();
fis.close();
} catch (IOException e) {
LOGGER.error(e);
NotificationDialog.show(NotificationDialog.NOTICE_TYPE.ERROR, PRINT_ERROR);
} catch (PrintException e) {
LOGGER.error(e);
}
} else { // no printer selected
This gives me an error java.awt.print.PrinterIOException: java.io.IOException: /usr/bin/lpr: where it looks to not find lpr.
If I keep it the way it was originally (not write to file) it prints the postscript as plain text even if adding the check to check if the printer is post script capable. If I use the new way of printing file I get a lpr not found error. If I print the PS document using the command lpr it converts it as expected and prints fine. If I use lpr -l that doesn't format it prints it document as plain text as well.
Any suggestion/help would be great. I am lost on what to do. I really don't want to convert it to an image and print that.
At a guess I'd say that your printer is an HP or at least PCL + PS printer, not a pure PostScript-only printer.
In that case you generally need to prepend the PostScript with a language selection PJL string. If you don't do this then it usually defaults to PCL and if you don't send any PCL commands (which all begin with 0x1B) then everything is treated as plain ASCII text. That would explain why both your application and lpr -l end up writing text, but lpr itself doesn't (presumably it adds the PJL).
You could try prepending the PostScript file with something like:
%-12345X#PJL JOB
#PJL ENTER LANGUAGE=POSTSCRIPT
NB the first byte there, before the % should be a 0x1b ESC character, but I can't readily paste binary....
Try sending the file with lpr -l if that works then you could try your old printing method.

Graphaware neo4j-php-client | Cannot catch Neo4jException

I'm using Postgresql + Neo4j for my project. I need to rollback postgres queries if neo4j query has failed. So, I need to catch Neo4jException in my code. But couldn't done yet. Thanks for help.
require_once('pgconnect.php');
try{
$conn->beginTransaction();
//some pgsql code
$conn->commit();
require_once('neoconnect.php');
$result = $client->run("a query");
$conn = null;
}
catch(PDOException $e){
require_once('pgrollback.php');
}
this is my working code. But as you can see I don't have a catch block to catch neo4j exception. So I added this but no luck. also tried withNeo4jExceptionInterface as exception class (desperate times). (BTW I'm using wrong typed query to get exception)
catch(Neo4jException $ex){
//done smth
}
Also tried to do this without luck too.
$client->run("a query") or throw new Neo4jException();
I just tested and I have no issues catching an exception, can you maybe provide more code, what is in neoconnect.php for example ?
This is my test :
$client = ClientBuilder::create()
->addConnection('default', 'http://localhost:7474')
->build();
$query = 'INVALID QUERY';
try {
$result = $client->run($query);
} catch (\GraphAware\Neo4j\Client\Exception\Neo4jException $e) {
echo sprintf('Catched exception, message is "%s"', $e->getMessage());
}
-
ikwattro#graphaware ~/d/g/p/neo4j-php-client> php test.php
Catched exception, message is "Invalid input 'I': expected <init> (line 1, column 1 (offset: 0))
"INVALID QUERY"
^"⏎

Unable to print error message in foreach in magento admin

Hi i have added a new mas action in the sales order grid which allow create batch invoices.
For this my controler file is
<?php
class Iclp_Batchupdate_IndexController extends Mage_Adminhtml_Controller_Action
public function batchinvoiceAction ()
{
$already = " already ";
$refererUrl = $this->getRequest()->getServer('HTTP_REFERER');
$this->loadLayout();
$this->renderLayout();
$orderIds = explode(",",$this->getRequest()->getParam('order_ids'));
foreach ($orderIds as $orderIdss) {
$order = Mage::getModel('sales/order')->load($orderIdss);
//echo $orderIdss ."<br/>";
//echo "already ".$order->getStatusLabel();
try
{
if(!$order->canInvoice())
{
echo Mage::getSingleton('core/session')->addError($orderIdss.$already.$order->getStatusLabel());
}
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
if (!$invoice->getTotalQty()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
}
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
$invoice->register();
$transactionSave = Mage::getModel('core/resource_transaction')->addObject($invoice)->addObject($invoice->getOrder());
$transactionSave->save();
$order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true)->save();
//echo "Invoice are created";
}
catch (Mage_Core_Exception $e) {
}
}
//A Success Message
Mage::getSingleton('core/session')->addSuccess("Some success message");
//A Error Message
Mage::getSingleton('core/session')->addError("Some error message");
//A Info Message (See link below)
Mage::getSingleton('core/session')->addNotice("This is just a FYI message...");
//These lines are required to get it to work
session_write_close();
$this->getResponse()->setRedirect($refererUrl);
}
}
every thing is working fine but the problem is it is not printing the error message in foreach in above code
if(!$order->canInvoice())
{
echo Mage::getSingleton('core/session')->addError($orderIdss.$already.$order->getStatusLabel());
}
but the bottom error message are displayed properly. MOreover if i extend the class with front-action than it also prints the foreach messages. Please suggest where i am doing the mistake
You should add your errors and messages to admintml/session and not to core/session when you are in adminhtml. That should display the message correctly. You shouldn't need session_write_close();. There is also no need to echo the message, that should be handled automatically by Magento after the redirect.
There is also no need to call $this->loadLayout(); and $this->renderLayout(); because you are redirecting at the end.
Finally, regarding the redirect, you should not read the referrer yourself, Magento can to that for you more reliably. Just use the $this->_redirectReferer(); method instead of $this->getResponse()->setRedirect($refererUrl);.

Parsing Multi-part in Grails

I want to design a controller in Grails which accepts multipart like "XML+binary file1+binary file2+...". How could I parse this request? I appreciate any sample codes!
Thanks,
Reza
So I'm assuming you are talking about an input type file that has the multiple attribute. Here is how you would process it server side:
List<MultipartFile> files = request.multiFileMap.nameOfInputFileElement
files.each { uploadedFile ->
if(!uploadedFile.empty){
File newFile = new File( parentDir, uploadedFile.originalFilename)
uploadedFile.transferTo(newFile)
}
}
I would do something like:
def uploadedFile = request.getFile('filepath')
if (uploadedFile && !uploadedFile.empty)
println "file:${uploadedFile?.originalFilename} uploaded"
}

Bootstrap doesn't save entities

I'm completely new to Grails and I'm doing the tutorial "Getting started with Grails Second Edition" by Scott Davis and Jason Rudolph.
When I'm setting up the BootStrap it seems like grails doesn't save the entities and I can't see them in my application.
I've already tried save(failOnError:true), but it compiles and saves without any errors.
Here is the code of BootStrap.groovy
package racetrack
import grails.util.GrailsUtil
class BootStrap {
def init = { servletContext ->
switch(GrailsUtil.environment){
case "development":
def jane = new Runner(
firstName:"Jane",
lastName:"Doe",
dateOfBirth:(new Date() - 365*30),
gender:"F",
address:"123 Main St",
city:"Goose",
state:"NC",
zipcode:"12345",
email:"jane#whereever.com"
)
jane.save()
if(jane.hasErrors()){
println jane.errors
}
def trot = new Race(
name:"Turkey Trot",
startDate:(new Date() + 90),
city:"Duck",
state:"NC",
distance:5.0,
cost:20.0,
maxRunners:350
)
trot.save()
if(trot.hasErrors()){
println trot.errors
}
def reg = new Registration(
paid:false,
runner:jane,
race:trot
)
reg.save()
if(reg.hasErrors()){
println reg.errors
}
break
case "production" : break
}
}
def destroy = { }
}
Thank you very much
are you in development mode?
Mybe you should add a log.debug or println statement to see if your code gets executed.
and have your tried a .save(flush:true, failOnError:true)? the flush might help
Use enums instead of Strings. Enums fit best in switch-case scenario and you can avoid mistakes. Maybe GrailsUtil.environment returns DEVELOPMENT not development? Instead of:
case "development"
use
case Environment.DEVELOPMENT
Using the grails.util.Environment enum doesn't work as is. Because the grails.util.GrailsUtil.environment returns a string, not an Environment.
You are more or less forced using strings.
Though old I thought it might help if I posted something I just found :)
if (GrailsUtil.developmentEnv){
// do dev stuff
}
else {
// do other stuff
}

Resources