// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try{
HashMap<String, String> propMap = readIniFile("search.ini");
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator iterator = fileItems.iterator();
HashMap<String,String> fieldMap = null;
fieldMap = new HashMap<String, String>();
In the above code, exception is caught at line List fileItems = upload.parseRequest(request);. Here ServletFileUpload is used as a file handler and we usecommons-fileupload-1.4.jar for it.
We were trying to upload file using this program, but we are getting IllegalStateException : getInputStream() called after getReader() called at 2nd line inside the try block itself. And also we are not getting the details were the exception is occurred. I want the reason for this exception and how it can be solved
Related
I am having difficulties working with azure pageable.
I have these dificulties in several places.......
What happens is, if i interact with an AzurePageable and something goes wrong, the thread just doesnt return ........
For example yesterday I had too many requests to Azure Appconfiguration, the following piece of code would just hang.......
// Get all the settings from Azure app configuration
private static Dictionary<string, string> GetAllXYZSettings(ConfigurationClient client)
{
var settingsSelector = new SettingSelector() { KeyFilter = "xyz:*" };
var settings = client.GetConfigurationSettings(settingsSelector);
Dictionary<string, string> config = new();
foreach (dynamic setting in settings)
{
string settingValue = (string)setting.Value;
if (!string.IsNullOrEmpty(settingValue))
{
config.Add(setting.Key, settingValue);
}
}
return config;
}
I tried several things, wrapped everything in a try catch but my thread would just not return.
How should i read the config so i can do some correct error handeling .....
Same behaviour is also observed when reading the servicebus queues.......
wrapped in try catch, didn't work
i am writing my own image import for my product catalog. I want to read the images from the local filesystem and store them in the configured assets folder. The import is very simple for now. Its one controller in the admin project and i trigger it by calling an url.
It is creating the files along with the folder structure and the files seem to have the same filesize, but somehow they get messed up along the way and they are not readable as images anymore (picture viewers wont open them). Any ideas why its being messed up ?
here the code:
#Controller("blImageImportController")
#RequestMapping("/imageimport")
public class ImageImportController extends AdminAbstractController {
#Value("${image.import.folder.location}")
private String importFolderLocation;
#Resource(name = "blStaticAssetService")
protected StaticAssetService staticAssetService;
#Resource(name = "blStaticAssetStorageService")
protected StaticAssetStorageService staticAssetStorageService;
#RequestMapping(method = {RequestMethod.GET})
public String chooseMediaForMapKey(HttpServletRequest request,
HttpServletResponse response,
Model model
) throws Exception {
File imageImportFolder = new File(importFolderLocation);
if (imageImportFolder.isDirectory()) {
Arrays.stream(imageImportFolder.listFiles()).forEach(directory ->
{
if (directory.isDirectory()) {
Arrays.stream(directory.listFiles()).forEach(this::processFile);
}
});
}
return "";
}
private void processFile(File file) {
FileInputStream fis = null;
try {
HashMap properties = new HashMap();
properties.put("entityType", "product");
properties.put("entityId", file.getParentFile().getName());
fis = new FileInputStream(file);
StaticAsset staticAsset = this.staticAssetService.createStaticAsset(fis, file.getName(), file.length(), properties);
this.staticAssetStorageService.createStaticAssetStorage(fis, staticAsset);
fis.close();
} catch (Exception e) {
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
There is a check in the StaticAssetService to try to detect this as an image (see https://github.com/BroadleafCommerce/BroadleafCommerce/blob/b55848f/admin/broadleaf-contentmanagement-module/src/main/java/org/broadleafcommerce/cms/file/service/StaticAssetServiceImpl.java#L217-L220). If it detected this correctly, you should get back an ImageStaticAssetImpl in the result to that call.
The flipside of this is the controller that actually reads the file (the StaticAssetViewController that renders a StaticAssetView). One of the things that the StaticAssetView does is set a response header for mimeType which the browser uses to render. This is set by this piece in the StaticAssetStorageService: https://github.com/BroadleafCommerce/BroadleafCommerce/blob/b55848f837f26022a620f0c2c143eed7902ba3f1/admin/broadleaf-contentmanagement-module/src/main/java/org/broadleafcommerce/cms/file/service/StaticAssetStorageServiceImpl.java#L213. I suspect that is the root of your problem.
Also just a note, sending those properties is not necessary when you are uploading the file yourself. That is mainly used in the admin when you are uploading an image for a specific entity (like a product or a category).
I have an OwinMiddleware with an Invoke method looking kind of like this:
public override async Task Invoke(IOwinContext context)
{
...
//The next line launches the execution of the Get method of a controller
await Next.Invoke(context);
//Now context.Response should contain "myvalue" right?
...
}
The Invoke method invokes a Get method, located inside a controller, which looks kind of like this:
[HttpGet]
public IHttpActionResult Get(some params...)
{
...
return "myvalue";
...
}
After the execution of the Get method, the program goes back to the Invoke method of my middleware. I think that the response of the Get method, namely myvalue, should be contained inside context.Response, but I don't know where precisely, because it's full of things.
Actualy response is a stream and You need to do this to get response back in orignal form
try{
var stream = context.Response.Body;
var buffer = new MemoryStream();
context.Response.Body = buffer;
await _next.Invoke(environment);
buffer.Seek(0, SeekOrigin.Begin);
var reader = new StreamReader(buffer);
// Here you will get you response body like this
string responseBody = reader.ReadToEndAsync().Result;
// Then you again need to set the position to 0 for other layers
context.Response.Body.Position = 0;
buffer.Seek(0, SeekOrigin.Begin);
await buffer.CopyToAsync(stream);
}
catch(Exception ex)
{
}
Currently my project uses a Controller class and utilizes AbstractJExcelView Class to generate an Excel Report which gives a prompt to user to either open or save the excel file. Basicall it uses http protocol for calling the controller.
Now what I need to do is generate the same excel file during (Spring) batch jobs and send it as an attachment directly through email. We're using org.springframework.mail.MailSender for sending mails.
I'm not supposed to use any other external API and I have no clue where to start from.
This is a similar code of what we're doing :-
Controller
public class RevenueReportController extends AbstractController{
#Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String output =
ServletRequestUtils.getStringParameter(request, "output");
//dummy data
Map<String,String> revenueData = new HashMap<String,String>();
revenueData.put("Jan-2010", "$100,000,000");
revenueData.put("Feb-2010", "$110,000,000");
revenueData.put("Mar-2010", "$130,000,000");
revenueData.put("Apr-2010", "$140,000,000");
revenueData.put("May-2010", "$200,000,000");
if(output ==null || "".equals(output)){
//return normal view
return new ModelAndView("RevenueSummary","revenueData",revenueData);
}else if("EXCEL".equals(output.toUpperCase())){
//return excel view
return new ModelAndView("ExcelRevenueSummary","revenueData",revenueData);
}else{
//return normal view
return new ModelAndView("RevenueSummary","revenueData",revenueData);
}
}
View
public class ExcelRevenueReportView extends AbstractJExcelView{
#Override
protected void buildExcelDocument(Map model, WritableWorkbook workbook,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
Map<String,String> revenueData = (Map<String,String>) model.get("revenueData");
WritableSheet sheet = workbook.createSheet("Revenue Report", 0);
sheet.addCell(new Label(0, 0, "Month"));
sheet.addCell(new Label(1, 0, "Revenue"));
int rowNum = 1;
for (Map.Entry<String, String> entry : revenueData.entrySet()) {
//create the row data
sheet.addCell(new Label(0, rowNum, entry.getKey()));
sheet.addCell(new Label(1, rowNum, entry.getValue()));
rowNum++;
}
}
}
Is there any way to do that ? I need to generate the excel sheet with passed and failed job data. I can handle populating and creating the file but I have no idea how to generate the excel in buffer or may be in some temp directory which could again be attached while sending the mail. The user is not required to respond to any prompts. Neither are we going to use any http request.
Thanks in advance!
There is an MimeMessageItemWriter in Spring Batch that you should be able to use to send the emails. You'll need to create an ItemProcessor that creates the MimeMessage. You can either create the Excel file and add it as an attachment within that ItemProcessor, or have one step generate all the Excel files that need to be sent, then in the next step, you can send them. I have an example of sending emails from Spring Batch in my book: Pro Spring Batch
I did the following in and it served the purpose :-
private ByteArrayOutputStream outputStream;
outputStream = new ByteArrayOutputStream();
WritableWorkbook workbook = Workbook.createWorkbook(outputStream);
.
.
.
.
workbook.write();
workbook.close();
Now, a getter to fetch the value :-
public ByteArrayOutputStream getOutputStream()
{
return this.outputStream;
}
And finally, for email attachement :-
JavaMailSenderImpl sender = new JavaMailSenderImpl();
MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(destiny);
helper.setSubject(subject);
helper.setText(msg);
helper.setFrom(from);
.
.
.
FileSystemResource fsr = new FileSystemResource(file);
helper.addAttachment("Sample.xls", fsr);
Thanks for the help guyz!
I would like to get DB connection parameters from a properties file in a static block. The properties file location is WEB-INF/classes/db.properties.
I will prefer to use getResourceAsStream() method. I have tried many ways, but they all returned null.
private static Properties prop = new Properties();
static{
try {
FacesContext facesContext = FacesContext.getCurrentInstance();
ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
InputStream inputStream = servletContext.getResourceAsStream("/db.properties");
InputStream is = prop.getClass().getResourceAsStream("/db.properties");
if(inputStream!=null){//it is null
prop.load(inputStream);
}
if(is!=null){//it is null
prop.load(is);
}
} catch (Exception e) {
e.printStackTrace();
}
}
How is this caused and how can I solve it?
As Thufir wrote in a comment, there is a nice tutorial from reading properties from Java code: http://jaitechwriteups.blogspot.ca/2007/01/how-to-read-properties-file-in-web.html
/**
* Some Method
*
* #throws IOException
*
*/
public void doSomeOperation() throws IOException {
// Get the inputStream
InputStream inputStream = this.getClass().getClassLoader()
.getResourceAsStream("myApp.properties");
Properties properties = new Properties();
System.out.println("InputStream is: " + inputStream);
// load the inputStream using the Properties
properties.load(inputStream);
// get the value of the property
String propValue = properties.getProperty("abc");
System.out.println("Property value is: " + propValue);
}
InputStream inputStream = servletContext.getResourceAsStream("/db.properties");
This attempt expects the file to be in /WebContent/db.properties.
InputStream is = prop.getClass().getResourceAsStream("/db.properties");
This attempt expects it to be in at least the same archive (JAR) as the java.util.Properties class.
Neither of those attempts reads the file which you've placed in /WEB-INF/classes/db.properties. You can fix this problem in basically 2 ways.
Move it directly in the /WEB-INF folder as /WEB-INF/db.properties and load it as follows:
InputStream input = externalContext.getResourceAsStream("/WEB-INF/db.properties");
(note that you don't need to haul the ServletContext from under the JSF's hoods; there's already a delegate method for that)
Load it relative to the class which is also present in /WEB-INF/classes, e.g. the current managed bean class.
InputStream input = Bean.class.getResourceAsStream("/db.properties");
Or just use the context classloader, it has access to everything.
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");
(note the lack of the / prefix)
See also:
Where to place and how to read configuration resource files in servlet based application?