When I use Struts 2.1.8, I used freemarker like this :
configure a bean in applicationContext.xml:
<bean id="freemarkerManager"
class="org.apache.struts2.views.freemarker.FreemarkerManager"/>
in the code :
try {
ServletContext servletContext = ServletActionContext.getServletContext();
System.out.println(freemarkerManager.getConfig());
Configuration configuration =
freemarkerManager.getConfiguration(servletContext);
Template template = configuration.getTemplate(templateFilePath);
File htmlFile = new File(servletContext.getRealPath(htmlFilePath));
File htmlDirectory = htmlFile.getParentFile();
if (!htmlDirectory.exists()) {
htmlDirectory.mkdirs();
}
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(htmlFile), "UTF-8"));
template.process(data, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
It worked well with Struts 2.1.8;
but now that I use Struts 2.3.15, it doesn't work; it could't load freemarker.properties. I read the source code , the problem is the fileManager is null in loadSettings() method :
try {
in = fileManager.loadFile(
ClassLoaderUtil.getResource("freemarker.properties", getClass()));
in Struts 2.1.8 loadSettings() method is like this:
InputStream in = null;
try {
in = FileManager.loadFile("freemarker.properties", FreemarkerManager.class);
It has no problem
could any one tell me how can I use freemarkerManager with Struts 2.3.15?
You must initialize freemarkerManager like this:
FreemarkerManager freemarkerManager = Dispatcher.getInstance().getContainer().getInstance(FreemarkerManager.class);
Related
I want to register and execute stored proc. I am using spring+Java with cosmos DB. Everytime I stop my application and restart it , it tried to create new sproc and since it already exists in cosmos DB it fails with below error . Is their any option available like "only create if not exist". I am fetching js file from src/main/resources folder.
I am following below doc to register the stored proc
https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/how-to-use-stored-procedures-triggers-udfs?tabs=java-sdk
#Configuration
public class StoredProcConfig
{
#Autowired
#Qualifier(BeansConstants.PAYMENT_CONTAINER)
CosmosContainer container;
#Bean
public CosmosStoredProcedureResponse registerSp() throws IOException
{
InputStream is = getFileFromResourceAsStream("storedProcedures/createStudent.js");
CosmosStoredProcedureProperties definition = new CosmosStoredProcedureProperties("spCreateToDoItems",
IOUtils.toString(is, StandardCharsets.UTF_8));
return container.getScripts().createStoredProcedure(definition);
}
private InputStream getFileFromResourceAsStream(String fileName)
{
// The class loader that loaded the class
ClassLoader classLoader = getClass().getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(fileName);
// the stream holding the file content
if (inputStream == null)
{
throw new IllegalArgumentException("file not found! " + fileName);
} else
{
return inputStream;
}
}
}
Error
Caused by: com.azure.cosmos.CosmosException: {"innerErrorMessage":"Message: {\"Errors\":[\"Resource with specified id, name, or unique index already exists.\"]}
Modify your registerSp() bean as below:
private static final Logger logger = LoggerFactory.getLogger(CosmosConfiguration.class);
#Bean
public CosmosStoredProcedureResponse registerSp() throws IOException
{
InputStream is = getFileFromResourceAsStream("storedProcedures/createStudent.js");
CosmosStoredProcedureProperties definition = new CosmosStoredProcedureProperties("spCreateToDoItems",
IOUtils.toString(is, StandardCharsets.UTF_8));
return createStoredProcedureIfNotExists(definition);
}
public CosmosStoredProcedureResponse createStoredProcedureIfNotExists(CosmosStoredProcedureProperties definition){
try {
CosmosStoredProcedureResponse storedProc = container.getScripts().getStoredProcedure(definition.getId()).read();
logger.info("found stored proc");
return storedProc;
}
catch (CosmosException e){
logger.info("stored proc not found, creating....");
return container.getScripts().createStoredProcedure(definition);
}
}
I'm building a Neo4J Server plugin. I'd like to have some configuration values that I can manually set in neo4j.properties or neo4j-server.properties and then the plugin can read and utilize these value. How can I access config values from a ServerPlugin?
Clarification:
I'd really like something that will work across future releases of Neo4J, so something that is part of the public API and is not deprecated would be best.
Using Neo4j's internal dependency mechanism, you can access a instance of Config (https://github.com/neo4j/neo4j/blob/master/community/kernel/src/main/java/org/neo4j/kernel/configuration/Config.java). This class gives you access to the configuration.
Take the following untested snippet as a guideline:
...
import org.neo4j.kernel.configuration.Config
...
#Description( "An extension to the Neo4j Server accessing config" )
public class ConfigAwarePlugin extends ServerPlugin
{
#Name( "config" )
#Description( "Do stuff with config" )
#PluginTarget( GraphDatabaseService.class )
public void sample( #Source GraphDatabaseService graphDb ) {
Config config = ((GraphDatabaseAPI)graphDb).getDependencyResolver().resolveDependency(Config.class);
// do stuff with config
}
}
I use Properties:
Properties props = new Properties();
try
{
FileInputStream in = new FileInputStream("./conf/neo4j.properties");
props.load(in);
}
catch (FileNotFoundException e)
{
try
{
FileInputStream in = new FileInputStream("./neo4j.properties");
props.load(in);
}
catch (FileNotFoundException e2)
{
logger.warn(e2.getMessage());
}
catch (IOException e2)
{
logger.warn(e2.getMessage());
}
}
catch (IOException e)
{
logger.warn(e.getMessage());
}
String myPropertyString = props.getProperty("myProperty");
if (myPropertyString != null)
{
myProperty = Integer.parseInt(myPropertyString);
}
else
{
myProperty = 100;
}
and in neo4j.properties I have:
...
# Enable shell server so that remote clients can connect via Neo4j shell.
#remote_shell_enabled=true
# Specify custom shell port (default is 1337).
#remote_shell_port=1234
myProperty=100
Ok so I'm trying to move my project from Primefaces 3.5 to 4.0 and I'm struggling with the new MenuModel API. I'm sure it's something stupid, but I can't display a DefaultMenuItem for my Breadcrumb where the value is from a .properties file (defined in faces-config as resource bundle).
What I had with Primefaces 3.5 :
MenuItem menuItem;
// Where "getPath()" returns all the pages needed to get to the current one
for (Page page : currentPage.getPath()) {
menuItem = new MenuItem();
// Where "getTitle()" returns something like "#{message.home}" which will be resolved as "Home"
menuItem.setValueExpression("value", expressionFactory.createValueExpression(elContext, page.getTitle(), String.class));
menuItem.setActionExpression(expressionFactory.createMethodExpression(elContext, page.getAction(), String.class, new Class[0]));
menuItem.setAjax(false);
menuItem.setAsync(false);
menuItem.setImmediate(true);
breadCrumbModel.addMenuItem(menuItem);
}
What I tried with Primefaces 4.0 and the new DefaultMenuItem object :
menuItem.setValue(page.getTitle());
menuItem.setValue(expressionFactory.createValueExpression(elContext, tmp.getTitle(), String.class));
menuItem.setParam("value", expressionFactory.createValueExpression(elContext, tmp.getTitle(), String.class));
menuItem.setTitle(page.getTitle()); <--- I even tried that in despair haha
I looked up the user guide and the api doc (uncommented :( ) but it doesn't talk much about this scenario, most of the time the examples use plain ol' String. What am I doing wrong ?
Thanks.
After having the same issue i found this solution and it works!, i'm using primefaces 5.0:
public void addMiga(String action, String label) throws Exception {
DefaultMenuItem item = new DefaultMenuItem();
item.setFragment(label);
String valueTitulo = "";
HtmlOutputText seccionLabel = new HtmlOutputText();
if (label != null && !"".equals(label)) {
String[] expresiones = label.split(",");
for (String expresion : expresiones) {
if (expresion.contains("label_")
|| expresion.contains("_label")) {
seccionLabel.setValueExpression("value",
getValueExpression(expresion));
} else {
seccionLabel.setValue(expresion);
}
valueTitulo += " " + (String) seccionLabel.getValue();
}
}
item.setValue(valueTitulo);
item.setId(Integer.toString(this.migas.getElements().size()));
item.setOnclick(ConstantesErp.FUNCION_STATUS);
item.setCommand(action);
item.setAjax(false);
this.migas.addElement(item);
}
public static ValueExpression getValueExpression(String nombre) {
FacesContext fc = FacesContext.getCurrentInstance();
Application app = fc.getApplication();
ELContext elContext = fc.getELContext();
ExpressionFactory factory = app.getExpressionFactory();
ValueExpression ve = null;
try {
ve = factory.createValueExpression(elContext, "#" + "{" + nombre
+ "}", String.class);
} catch (Exception e) {
ve = null;
}
return ve;
}
I am generating pdf and displaying it in separate window/tab using the approach described in The BalusC Code: PDF handling.I need to display blockui ajax loader when i select the commandlink to display pdf.The pdf gets generated but the ajax loader image remains as it is.I need to manually refresh the page to hide it.Is there any way using which it can be hidden as soon as the pdf gets displayed.
My code snippet is as below
JSF page
<h:form id="subFrm">
<p:commandLink value="Download PDF" action="#{pdfBean.downloadPDF}"
onclick="blkUi.show()" oncomplete="blkUi.hide()" id="cmdLink"
ajax="false" />
<p:blockUI block="subFrm" trigger="cmdLink" widgetVar="blkUi">
processing...<br />
<p:graphicImage value="/images/ajaxLoader.gif" />
</p:blockUI>
</h:form>
snippet of Managed bean which is of request scope
#ManagedBean
#RequestScoped
public class PdfBean {
// Constants ----------------------------------------------------------------------------------
private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.
// Actions ------------------------------------------------------------------------------------
public void downloadPDF() throws IOException {
// Prepare.
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
String filePath=externalContext.getRealPath("/pdf");
File file = new File(filePath, "modified.pdf");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
// Open file.
input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
// Init servlet response.
response.reset();
response.setHeader("Content-Type", "application/pdf");
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "inline; filename=\"" + "modified.pdf" + "\"");
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
// Write file contents to response.
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
// Finalize task.
output.flush();
} finally {
// Gently close streams.
close(output);
close(input);
}
// Inform JSF that it doesn't need to handle response.
// This is very important, otherwise you will get the following exception in the logs:
// java.lang.IllegalStateException: Cannot forward after response has been committed.
//externalContext.redirect(((HttpServletRequest)externalContext.getRequest()).getRequestURI());
facesContext.responseComplete();
/*FacesContext.getCurrentInstance().getExternalContext()
.redirect("index.xhtml");*/
}
// Helpers (can be refactored to public utility class) ----------------------------------------
private static void close(Closeable resource) {
if (resource != null) {
try {
resource.close();
} catch (IOException e) {
// Do your thing with the exception. Print it, log it or mail it. It may be useful to
// know that this will generally only be thrown when the client aborted the download.
e.printStackTrace();
}
}
}
}
You don't need to open the blockui explicitly. Just remove the code from your commandLink
onclick="blkUi.show()" oncomplete="blkUi.hide()"
remove above. The BlockUI will show up and hides itself.
I want to use to generate a pdf dataexporter, use the method preprocessor to insert some content. By giving the type letter size page assimilates well as formats of texts. Then make a page break to put the chart on a new page, right there is the problem that generates the second page with other size and also find a way to change the font size of the text of the exported table.
<h:commandLink>
<p:graphicImage value="/images/pdf.png"/>
<p:dataExporter type="pdf" target="dataTableAddDetalles" fileName="pdf" preProcessor="#{serviciosMB.preProcessPDF}"/>
</h:commandLink>
backing bean
public void preProcessPDF(Object document) throws Exception {
try {
Document pdf = (Document) document;
pdf.open();
pdf.setPageSize(PageSize.LETTER);
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
String logo = servletContext.getRealPath("") + File.separator + "images" + File.separator + "header.gif";
// pdf.add(Image.getInstance(logo));
pdf.add(new Paragraph("EMNI", FontFactory.getFont(FontFactory.HELVETICA, 22, Font.BOLD, new Color(0, 0, 0))));
SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
pdf.add(new Phrase("Fecha: " + formato.format(new Date())));
pdf.newPage();
} catch (Exception e) {
//JsfUtil.addErrorMessage(e, e.getMessage());
}
}
You can't do what you want using dataexporter, you need to change your code to:
<h:commandLink actionListener="#{serviciosMB.createPDF}">
<p:graphicImage value="/images/pdf.png" />
</h:commandLink>
And your managed bean:
public void createPDF() {
try { //catch better your exceptions, this is just an example
FacesContext context = FacesContext.getCurrentInstance();
Document document = new Document();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos);
if (!document.isOpen()) {
document.open();
}
PdfPTable pdfTable = exportPDFTable();
document.add(pdfTable);
//Keep modifying your pdf file (add pages and more)
document.close();
String fileName = "PDFFile";
writePDFToResponse(context.getExternalContext(), baos, fileName);
context.responseComplete();
} catch (Exception e) {
//e.printStackTrace();
}
}
exportPDFTable method:
private PdfPTable exportPDFTable() {
int numberOfColumns = 1;
itemOfList item = null;
PdfPTable pdfTable = new PdfPTable(numberOfColumns);
pdfTable.setWidthPercentage(100);
BaseFont helvetica = null;
try {
helvetica = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
} catch (Exception e) {
//font exception
}
Font font = new Font(helvetica, 8, Font.NORMAL);
pdfTable.addCell(new Paragraph("columnName", font));
for (int i = 0; i < lstPdfTable.size(); i++) { //lstPdfTable is the list from your datatable. A List of "itemOfList" type
item = new itemOfList();
item = lstPdfTable.get(i);
//pdfTable.addCell(new Paragraph('any_string_field', font));
pdfTable.addCell(new Paragraph(item.getStringField(), font));
}
return pdfTable;
}
and writePDFToResponse method is:
private void writePDFToResponse(ExternalContext externalContext, ByteArrayOutputStream baos, String fileName) {
try {
externalContext.responseReset();
externalContext.setResponseContentType("application/pdf");
externalContext.setResponseHeader("Expires", "0");
externalContext.setResponseHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
externalContext.setResponseHeader("Pragma", "public");
externalContext.setResponseHeader("Content-disposition", "attachment;filename=" + fileName + ".pdf");
externalContext.setResponseContentLength(baos.size());
OutputStream out = externalContext.getResponseOutputStream();
baos.writeTo(out);
externalContext.responseFlushBuffer();
} catch (Exception e) {
//e.printStackTrace();
}
}
The primefaces documentation (as of 4.0) does not mention any ability to write a custom data exporter, only pre & post processors, which in the case of PDF prevents you from doing extensive modifications to data, etc.
But what you can do is create a package in your project called
org.primefaces.component.export
and copy ExporterFactory.java from primefaces source.
You can then replace the original PDFExporter call with your own implementation.
The exporter implementation is fairly simple. It uses iText library (although an outdated version) and you can easily extend it to your needs.
An obvious problem with this approach is that you may have to be extra careful when (and if) you are updating your primefaces library in the future.