How to do Excel File upload in struts2? - file-upload

I am trying to upload Excel only file in Struts2 WEB Application. So using the following Code in Jsp page:
<s:label value="File Name : *" />
<s:file name="fileUpload" label="Select a File to upload"/>
<br>
<br>
<s:submit value="Add" name="add" tabindex="8" />
</s:form>
In Response.jsp page displaying the File content and It's type as Follows:
<s:form action="saveBulkStores.action" method="get" >
<h4>
File Name : <s:property value="fileUploadFileName"/>
</h4>
<h4>
Content Type : <s:property value="fileUploadContentType"/>
</h4>
<h4>
File : <s:property value="fileUpload"/>
</h4>
<br>
</s:form>
In Struts.xml:
<action name="bulkStores" class="com.action.FilesUploadAction"
method="loadBulkStoresPage">
<result name="input">/viewfile.jsp</result>
<result name="success">/uploadfile.jsp</result>
</action>
<action name="saveBulkStores" class="com.action.FilesUploadAction"
method="saveBulkStores">
<interceptor-ref name="exception"/>
<interceptor-ref name="i18n"/>
<interceptor-ref name="fileUpload">
<param name="allowedTypes">text/plain</param>
<param name="maximumSize">10240</param>
</interceptor-ref>
<interceptor-ref name="params">
<param name="excludeParams">dojo\..*,^struts\..*</param>
</interceptor-ref>
<interceptor-ref name="validation">
<param name="excludeMethods">input,back,cancel,browse</param>
</interceptor-ref>
<interceptor-ref name="workflow">
<param name="excludeMethods">input,back,cancel,browse</param>
</interceptor-ref>
<result name="input">/uploadfile.jsp</result>
<result name="success">/success.jsp</result>
</action>
In Action Classes:
public String loadBulkStoresPage(){
System.out.println("FILES BULK UPLOADS.........");
return SUCCESS;
}
private File fileUpload;
private String fileUploadContentType;
private String fileUploadFileName;
//Getters and Setters for above Fields.
Displaying filename,content type as follows:
public String saveBulkStores(){
System.out.println("check Bulk upload file");
System.out.println("fileName:"+fileUploadFileName);
System.out.println("content type:"+fileUploadContentType);
System.out.println("fileupload:"+fileUpload);
return SUCCESS;
}
Output:
It's displaying NUll value only for my display statements. So anyone help me to fix this issue. thanks in Advance.
I am new to do this task.

FileUtils is not part of the standard JDK, it a class in the Apache Commons IO library.It contains Methods like
FileUtils.readFileToString(file);
FileUtils.copyDirectoryToDirectory(source, destination);
FileUtils.deleteDirectory(source);......................which make copying files from one directory to other directory in most easier way in word it reduces voluminous amount of code as entire code is written by Apache people
please refer this URL for reference http://www.koders.com/java/fid002DB6BD79CABA7B6AA0F2669061424E3B9776D3.aspx

<s:file id="myFile" name="myFile" disabled="true" ></s:file> is the tag that is used to upload file put the tag in jsp.
And the properties in action class as i written below
private File myFile;
private String myFileContentType;
private String myFileFileName;
/**
* #return the myFile
*/
public File getMyFile() {
return myFile;
}
/**
* #return the myFileContentType
*/
public String getMyFileContentType() {
return myFileContentType;
}
/**
* #return the myFileFileName
*/
public String getMyFileFileName() {
return myFileFileName;
}
/**
* #param myFile the myFile to set
*/
public void setMyFile(File myFile) {
this.myFile = myFile;
}
/**
* #param myFileContentType the myFileContentType to set
*/
public void setMyFileContentType(String myFileContentType) {
this.myFileContentType = myFileContentType;
}
/**
* #param myFileFileName the myFileFileName to set
*/
public void setMyFileFileName(String myFileFileName) {
this.myFileFileName = myFileFileName;
}
and In execute method insert this code
String destaddress=getText("ipaddress");
if(myFile!=null){
File destDir= new File(destaddress+myFileFileName);
destDir.createNewFile();
FileUtils.copyFile(myFile, destDir);
}
you add ip address in apllication properties file as show below
ipaddress=\\\\192.168.105.68\\Shared2\\Files\\
and the following interceptors to your struts. XML file
<interceptor-ref name="fileUpload">
<param name="maximumSize">52428800</param>
</interceptor-ref>
<interceptor-ref name="basicStack"/>
ipaddress=\\\\192.168.105.68\\Shared2\\Files\\
This will solve your problem.

Related

Fetch id from url in block file

What is the standard of Magento for fetch id from URL in the block file?
My URL is http://test.com/quote/savequote/view/id/7/
My XML file
<quote_savequote_view>
<label>View Quote</label>
<reference name="root">
<action method="setTemplate">
<template>page/1column.phtml</template>
</action>
</reference>
<reference name="content">
<block type="quote/savequote" name="quote.savequote" template="quote/view.phtml" />
</reference>
</quote_savequote_view>
Controller Action
public function viewAction(){
$this->loadLayout();
$this->renderLayout();
}
Block File
public function getDetails(){
// I want to get id here and I want to use the id in collection
}
Please help me what is the standard.
Finally I have solution, We can use mage register for pass data between block and controller.
public function viewAction(){
$id = Mage::app()->getRequest()->getParam('id');
$results = // your model results
Mage::register('quotedetails', $results);
$this->loadLayout();
$this->renderLayout();
}
Block File
public function getDetails(){
return Mage::registry('quotedetails');
}

Sitecore 8 XP ContentSearch: Exclude path from Indexing

I'm having trouble with Sitecore Indexing of the general indexes "sitecore_master_index", "sitecore_web_index", which take forever because the crawler/indexer checks all items in the database.
I imported thousands of products with a whole lot of specifications and literally have hundreds of thousands of items in the product repository.
If I could exclude the path from indexing it wouldn't have to check a million items for template exclusion.
FOLLOWUP
I implemented a custom-crawler that excludes a list of paths from being indexed:
<index id="sitecore_web_index" type="Sitecore.ContentSearch.SolrProvider.SwitchOnRebuildSolrSearchIndex, Sitecore.ContentSearch.SolrProvider">
<param desc="name">$(id)</param>
<param desc="core">sitecore_web_index</param>
<param desc="rebuildcore">sitecore_web_index_sec</param>
<param desc="propertyStore" ref="contentSearch/indexConfigurations/databasePropertyStore" param1="$(id)" />
<configuration ref="contentSearch/indexConfigurations/defaultSolrIndexConfiguration" />
<strategies hint="list:AddStrategy">
<strategy ref="contentSearch/indexConfigurations/indexUpdateStrategies/onPublishEndAsync" />
</strategies>
<locations hint="list:AddCrawler">
<crawler type="Sitecore.ContentSearch.Utilities.Crawler.ExcludePathsItemCrawler, Sitecore.ContentSearch.Utilities">
<Database>web</Database>
<Root>/sitecore</Root>
<ExcludeItemsList hint="list">
<ProductRepository>/sitecore/content/Product Repository</ProductRepository>
</ExcludeItemsList>
</crawler>
</locations>
</index>
In addition I activated SwitchOnSolrRebuildIndex as it's awesome ootb functionality, cheers SC.
using System.Collections.Generic;
using System.Linq;
using Sitecore.ContentSearch;
using Sitecore.Diagnostics;
namespace Sitecore.ContentSearch.Utilities.Crawler
{
public class ExcludePathsItemCrawler : SitecoreItemCrawler
{
private readonly List<string> excludeItemsList = new List<string>();
public List<string> ExcludeItemsList
{
get
{
return excludeItemsList;
}
}
protected override bool IsExcludedFromIndex(SitecoreIndexableItem indexable, bool checkLocation = false)
{
Assert.ArgumentNotNull(indexable, "item");
if (ExcludeItemsList.Any(path => indexable.AbsolutePath.StartsWith(path)))
{
return true;
}
return base.IsExcludedFromIndex(indexable, checkLocation);
}
}
}
You can override SitecoreItemCrawler class which is used by the index you want to change:
<locations hint="list:AddCrawler">
<crawler type="Sitecore.ContentSearch.SitecoreItemCrawler, Sitecore.ContentSearch">
<Database>master</Database>
<Root>/sitecore</Root>
</crawler>
</locations>
You can then add your own parameters, e.g. ExcludeTree or even a list of ExcludedBranches.
And in the implementation of the class just override method
public override bool IsExcludedFromIndex(IIndexable indexable)
and check whether it is under excluded node.
When importing large amounts of data you should try disabling the indexing of data temporarily otherwise you'll run into issues with a crawler that can't keep up.
There's a great post here on disabling the index while importing data - it's for Lucene but I'm sure you can do the same with Solr,
http://intothecore.cassidy.dk/2010/09/disabling-lucene-indexes.html
Another option could be to store your products in a separate Sitecore database rather than in the master db.
Another post from into the core:
http://intothecore.cassidy.dk/2009/05/working-with-multiple-content-databases.html

Pdf Document Link control error - PdfDocumentLink.ascx

I just upgraded from 5.1 to 7.0 and now I am getting this error on one of the pages that have a PdfDocumentLink control (in Edit Mode):
A required control was not found in the template for "~/Sitefinity/Extensions/WidgetTemplates/Libraries/Documents/PdfDocumentLink.ascx". The control must be assignable from type "System.Web.UI.HtmlControls.HtmlGenericControl" and must have ID "itemsContainer".
I get a 500 in Preview mode.
This is the code for the ascx, in \Sitefinity\Extensions\WidgetTemplates\Libraries\Documents
<%# Control Language="C#" %>
<%# Register TagPrefix="sitefinity" Assembly="Telerik.Sitefinity" Namespace="Telerik.Sitefinity.Web.UI" %>
<%# Register TagPrefix="sf" Namespace="Telerik.Sitefinity.Web.UI.PublicControls.BrowseAndEdit" Assembly="Telerik.Sitefinity" %>
<sitefinity:ResourceLinks id="resourcesLinks2" runat="server" UseEmbeddedThemes="false" Theme="Default">
<sitefinity:ResourceFile Name="~/Sitefinity/Extensions/WidgetTemplates/Libraries/Documents/PdfDocumentLink.css" Static="true" />
</sitefinity:ResourceLinks>
<sitefinity:SitefinityHyperLink ID="documentLink" runat="server" target="_blank" CssClass="PdfDocumentLink" />
<sf:BrowseAndEditToolbar ID="browseAndEditToolbar" runat="server" Mode="Edit"></sf:BrowseAndEditToolbar>
Here's the cs file ... under C:\inetpub\xxx\App_Code\Widgets
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace xxx.Sitefinity.Widgets.Libraries.Documents {
/// <summary>
/// Summary description for PdfDocumentLink
/// </summary>
public class PdfDocumentLink : Telerik.Sitefinity.Modules.Libraries.Web.UI.Documents.DocumentLink {
public PdfDocumentLink() : base () {
//
// TODO: Add constructor logic here
//
}
public override string LayoutTemplatePath {
get {
return "~/Sitefinity/Extensions/WidgetTemplates/Libraries/Documents/PdfDocumentLink.ascx";
}
set {
base.LayoutTemplatePath = value;
}
}
public string LinkTitle {
get;
set;
}
protected override void OnPreRender(EventArgs e) {
base.OnPreRender(e);
if (this.LinkTitle != null)
this.DocumentLinkControl.Text = this.LinkTitle;
}
}
}
And ToolboxesConfig.config file:
...
<toolboxesConfig xmlns:config="urn:telerik:sitefinity:configuration" xmlns:type="urn:telerik:sitefinity:configuration:type" config:version="7.0.5100.0">
<toolboxes>
<toolbox name="PageControls">
<sections>
<add name="ContentToolboxSection">
<tools>...
<add enabled="True" type="OneCommand.Sitefinity.Widgets.Libraries.Documents.PdfDocumentLink" title="PDF Document Link" description="Link to a PDF Document" cssClass="sfDownloadLinkIcn" moduleName="Libraries" Name="PDFDocumentLink" visibilityMode="None" name="PDFDocumentLink" />
If I delete the widget, and add it back in, and select a pdf document, I get the same error.
The Document Link widget appears to work ok, but that one doesn't have the left side PDF icon that we want to display.
Any ideas?
Try adding this to your .ascx file:
<div runat="server" id="itemsContainer"></div>

How to Email an Entire Log File through Nlog

Salvete! nLog for .NET has the capability to send log entries as email. But if we want to send the entire current log file, how can it be done, short of reading the log file into a string and passing that as an nLog {$message}? I don't see that nLog has a property in its mailtarget for attachments. How can this be done?
I just did this today in C#. I followed the answer provided by arkmuetz here How to get path of current target file using NLog in runtime? to first get the filename of the Nlog target. I then read the file and copied the contents of the file to another Nlog target which emailed the log in the body of the message.
First I created an NlogHelper Class
public static class NlogHelper
{
/// <summary>
/// Gets LogFileName by TargetName
/// </summary>
/// <param name="targetName">The nLog targetname for the specified logger.</param>
/// <returns></returns>
/// <remarks>https://stackoverflow.com/questions/11452645/how-to-get-path-of-current-target-file-using-nlog-in-runtime</remarks>
public static string GetLogFileName(string targetName)
{
string fileName = null;
if (LogManager.Configuration != null && LogManager.Configuration.ConfiguredNamedTargets.Count != 0)
{
Target target = LogManager.Configuration.FindTargetByName(targetName);
if (target == null)
{
throw new Exception("Could not find target named: " + targetName);
}
FileTarget fileTarget = null;
WrapperTargetBase wrapperTarget = target as WrapperTargetBase;
// Unwrap the target if necessary.
if (wrapperTarget == null)
{
fileTarget = target as FileTarget;
}
else
{
fileTarget = wrapperTarget.WrappedTarget as FileTarget;
}
if (fileTarget == null)
{
throw new Exception("Could not get a FileTarget from " + target.GetType());
}
var logEventInfo = new LogEventInfo { TimeStamp = DateTime.Now };
fileName = fileTarget.FileName.Render(logEventInfo);
}
else
{
throw new Exception("LogManager contains no Configuration or there are no named targets");
}
//if (!File.Exists(fileName))
//{
// throw new Exception("File " + fileName + " does not exist");
//}
return fileName;
}
}
Next I retrieved the file name in the constructor and stored it for later use.
_logLileName = NlogHelper.GetLogFileName("DailyFile");
For my purposes I created property that I later used to retrieve the contents of the log file.
public string LogFileContent
{
get
{
return File.ReadAllText(_logLileName);
}
}
Finally I added the contents of the file to the log to be emailed.
_logger.Error("Excel Builder LinkShare Error encountered -- Some companies did not complete succesfully!. Please review logs. \n" + mfb.LogFileContent);
Here is my nLog.config file thought will help make things more clear.
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
<targets>
<target name="console" xsi:type="ColoredConsole"
layout="${date:format=HH\:mm\:ss}|${level}|${stacktrace}|${message}" />
<target name="file" xsi:type="File" fileName="${basedir}/DomoExcelBuilderLog.txt"
layout="${stacktrace} ${message}" />
<target name="DailyFile" xsi:type="File" fileName="C:\Temp\Log${shortdate}.txt"
layout="${date:format=HH\:mm\:ss} --> ${message}" deleteOldFileOnStartup="true" />
<target name="file2" xsi:type="File" fileName="${basedir}/ServiceLog.txt"
layout="${stacktrace} ${message}" />
<target name="MyMailer" xsi:type="Mail"
smtpServer="some.server.com"
smtpPort="587"
smtpAuthentication="Basic"
smtpUsername="no-reply"
smtpPassword="somepassword"
enableSsl="true"
from="no-reply#some.server.com"
to="myemail#gmail.com"/>
</targets>
<rules>
<logger name="MultipleFileBuilder" minlevel="Trace" writeTo="DailyFile" />
<logger name="ExcelBuilderService" minlevel="Debug" writeto="MyMailer" />
</rules>
</nlog>
My application first logs to the logger named 'MultipleFileBuilder'. I then use the NLogHelper class to retrieve the contents of the Target 'DailiyFile'.
Hope this helps someoneout.
(NOTE: I removed the checking to see if the file exists in the 'GetLogFileName' method because in my case file didn't exist.)
I think you may use a combination of targets: default target + MethodCall and then send email manually or use Mail + Buffering to send a batch of records.

Struts2 Multiple File Upload with Map

I am doing Multiple file upload with Struts2. It was working fine I map with java static action properties. But I am using Map to collect all the files. I am getting only the file object. I am not getting the fileName and content type.
public class TableListAction extends ActionSupport
{
private Map raja;
public Map getRaja()
{
return raja;
}
public void setRaja(Map raja)
{
this.raja = raja;
}
public String upload() throws Exception
{
System.out.println(raja);
return SUCCESS;
}
}
My Jsp like this
<s:form enctype="multipart/form-data" method="post" action="upload">
<s:file name="raja['column']"></s:file>
<s:file name="raja['column']"></s:file>
<s:file name="raja['column']"></s:file>
<s:file name="raja['column']"></s:file>
<s:submit/>
During uploading I am getting the file object array in that raja Map but I am not getting the fileName and contenttype.
Thanks in Advance
regards
Shreeram A
<s:form enctype="multipart/form-data" method="post" action="upload">
<s:file name="raja.column"></s:file>
<s:file name="raja.column"></s:file>
<s:file name="raja.column"></s:file>
<s:file name="raja.column"></s:file>
<s:submit/>
They are append name attribute with FileName and ContentType.
I used before name like this raja['column'], so the result raja['column']FileName and
raja['column']ContentType. It wont come into the the Map.
Then i modified raja.column. Then it will append FileName and ContentType correctly like raja.columnContentType and raja.columnFileName
Its work fine now.
Thanks
Shreeram A