From 14127fccd05fd4dc20411d3c551908103fcd28a9 Mon Sep 17 00:00:00 2001
From: zapata
+ ${lang("article.homepage.prefix")}: ${utility.encodeHTML(article.creator_main_url)}
true
if the article should be visible
+ * to "open posting" users. This method is used to determine whether the request
+ * for a pdf, or an email for the article should be allowed. It is however
+ * Title:
- *Description:
- *Copyright: Copyright (c) 2003
- *Company:
- * @author not attributable - * @version 1.0 - */ +import java.util.HashMap; +import java.util.Map; public class MirBasicMediaLocalizer implements MirMediaLocalizer { - private Map mediaHandlers; + private final Map mediaHandlers = new HashMap(); - /** - * - * @throws MirLocalizerExc - * @throws MirLocalizerFailure - */ - public MirBasicMediaLocalizer() throws MirLocalizerExc, MirLocalizerFailure { + public MirBasicMediaLocalizer() throws MirLocalizerFailure { MirPropertiesConfiguration configuration; try { @@ -76,9 +51,6 @@ public class MirBasicMediaLocalizer implements MirMediaLocalizer { throw new MirLocalizerFailure("Can't get configuration", t); } - mediaHandlers = new HashMap(); - - registerMediaHandler("Audio", new MediaHandlerAudio()); registerMediaHandler("Generic", new MediaHandlerGeneric()); registerMediaHandler("ImagesExtern", new MediaHandlerImagesExtern()); diff --git a/source/mircoders/localizer/basic/MirBasicOpenPostingLocalizer.java b/source/mircoders/localizer/basic/MirBasicOpenPostingLocalizer.java index 0009383e..b6833ed9 100755 --- a/source/mircoders/localizer/basic/MirBasicOpenPostingLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicOpenPostingLocalizer.java @@ -61,7 +61,7 @@ public class MirBasicOpenPostingLocalizer implements MirOpenPostingLocalizer { protected LoggerWrapper logger; protected MirPropertiesConfiguration configuration; - public MirBasicOpenPostingLocalizer() throws MirLocalizerExc, MirLocalizerFailure { + public MirBasicOpenPostingLocalizer() throws MirLocalizerFailure { logger = new LoggerWrapper("Localizer.Basic.OpenPosting"); try { @@ -133,10 +133,18 @@ public class MirBasicOpenPostingLocalizer implements MirOpenPostingLocalizer { } } - public void afterContentPosting(EntityContent aContent) { + public void afterArticlePosting() { afterContentPosting(); } + public void afterArticlePosting(EntityContent anArticle) { + afterContentPosting(anArticle); + } + + public void afterContentPosting(EntityContent anArticle) { + afterArticlePosting(); + } + public void afterCommentPosting(EntityComment aComment) { afterCommentPosting(); } @@ -175,6 +183,10 @@ public class MirBasicOpenPostingLocalizer implements MirOpenPostingLocalizer { return filterTypes; } + public boolean allowArticlePublication(EntityContent anArticle){ + return (anArticle!=null) && "t".equals(anArticle.getFieldValue("is_published")); + } + public void removeSimpleAntiAbuseFilterType(String aName) { filterTypes.remove(filterTypesMap.get(aName)); filterTypesMap.remove(aName); diff --git a/source/mircoders/localizer/basic/MirBasicProducerAssistantLocalizer.java b/source/mircoders/localizer/basic/MirBasicProducerAssistantLocalizer.java index d26fab55..40c95cd1 100755 --- a/source/mircoders/localizer/basic/MirBasicProducerAssistantLocalizer.java +++ b/source/mircoders/localizer/basic/MirBasicProducerAssistantLocalizer.java @@ -70,7 +70,7 @@ public class MirBasicProducerAssistantLocalizer implements MirProducerAssistantL private RE regularExpressionLT; private RE regularExpressionGT; - public MirBasicProducerAssistantLocalizer() throws MirLocalizerExc, MirLocalizerFailure { + public MirBasicProducerAssistantLocalizer() throws MirLocalizerFailure { try{ regularExpressionLT = new RE("<"); regularExpressionGT = new RE(">"); diff --git a/source/mircoders/media/MediaHandlerImagesExtern.java b/source/mircoders/media/MediaHandlerImagesExtern.java index ac964787..58e1a0b6 100755 --- a/source/mircoders/media/MediaHandlerImagesExtern.java +++ b/source/mircoders/media/MediaHandlerImagesExtern.java @@ -108,8 +108,7 @@ public class MediaHandlerImagesExtern extends MediaHandlerGeneric } } catch(Throwable t) { - logger.error("MediaHandlerImagesExtern.execute: " + t.toString()); - t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE)); + logger.error("MediaHandlerImagesExtern.execute: " + t.getMessage(), t); throw new MediaFailure(t.getMessage(), t); } } diff --git a/source/mircoders/media/MediaHelper.java b/source/mircoders/media/MediaHelper.java index 762cce0a..4222dc73 100755 --- a/source/mircoders/media/MediaHelper.java +++ b/source/mircoders/media/MediaHelper.java @@ -29,16 +29,12 @@ */ package mircoders.media; -import java.util.HashMap; -import java.util.Map; - import mir.entity.Entity; import mir.media.MediaExc; import mir.media.MediaFailure; import mir.media.MediaHandler; import mir.storage.Database; import mircoders.global.MirGlobal; -import mircoders.localizer.MirLocalizerExc; import mircoders.storage.DatabaseAudio; import mircoders.storage.DatabaseImages; import mircoders.storage.DatabaseOther; @@ -53,23 +49,10 @@ import mircoders.storage.DatabaseVideo; */ public final class MediaHelper { - private static Map nameToMediaHandler = new HashMap(); - - public static void addHandler(String aName, MediaHandler aHandler) { - synchronized (nameToMediaHandler) { - nameToMediaHandler.put(aName, aHandler); - } - } - public static MediaHandler getHandler(Entity aMediaType) throws MediaExc, MediaFailure { String handlerName = aMediaType.getFieldValue("classname"); - try { - return MirGlobal.localizer().media().getHandler(handlerName); - } - catch (MirLocalizerExc e) { - throw new MediaFailure(e); - } + return MirGlobal.localizer().media().getHandler(handlerName); } public static Database getStorage(Entity mediaType, String aTable) throws MediaExc, MediaFailure { diff --git a/source/mircoders/pdf/PDFGenerator.java b/source/mircoders/pdf/PDFGenerator.java index ebfe9844..1a158685 100755 --- a/source/mircoders/pdf/PDFGenerator.java +++ b/source/mircoders/pdf/PDFGenerator.java @@ -65,9 +65,9 @@ import com.lowagie.text.pdf.ColumnText; import com.lowagie.text.pdf.PdfContentByte; import com.lowagie.text.pdf.PdfTemplate; import com.lowagie.text.pdf.PdfWriter; +import multex.Failure; -public class PDFGenerator{ - +public class PDFGenerator { public Document document; public PdfWriter writer; public PdfContentByte cb; @@ -83,8 +83,8 @@ public class PDFGenerator{ public float rightEdge; public float leftEdge; - public int maxImageHeight; - public int maxImageWidth; + public int maxImageHeight; + public int maxImageWidth; protected LoggerWrapper logger; public int indexFontSize; @@ -118,264 +118,262 @@ public class PDFGenerator{ protected MirPropertiesConfiguration configuration; - public PDFGenerator(ByteArrayOutputStream out){ + public PDFGenerator(ByteArrayOutputStream out) { logger = new LoggerWrapper("PDFGenerator"); configuration = MirPropertiesConfiguration.instance(); - localImageDir=configuration.getString("Producer.Image.Path"); + localImageDir = configuration.getString("Producer.Image.Path"); try { - indexFontSize = Integer.parseInt(configuration.getString("PDF.Index.FontSize")); + indexFontSize = Integer.parseInt(configuration.getString("PDF.Index.FontSize")); indexLineHeight = Integer.parseInt(configuration.getString("PDF.Index.LineHeight")); indexFontFamily = getFontByName(configuration.getString("PDF.Index.FontFamily")); footerText = configuration.getString("PDF.Footer.String"); - footerFontSize = Integer.parseInt(configuration.getString("PDF.Footer.FontSize")); + footerFontSize = Integer.parseInt(configuration.getString("PDF.Footer.FontSize")); footerFontFamily = getFontByName(configuration.getString("PDF.Footer.FontFamily")); footerHeight = Integer.parseInt(configuration.getString("PDF.Footer.Height")); - metaFontSize = Integer.parseInt(configuration.getString("PDF.Meta.FontSize")); + metaFontSize = Integer.parseInt(configuration.getString("PDF.Meta.FontSize")); metaFontFamily = getFontByName(configuration.getString("PDF.Meta.FontFamily")); metaHeight = Integer.parseInt(configuration.getString("PDF.Meta.Height")); - descriptionFontSize = Integer.parseInt(configuration.getString("PDF.Description.FontSize")); + descriptionFontSize = Integer.parseInt(configuration.getString("PDF.Description.FontSize")); descriptionLineHeight = Integer.parseInt(configuration.getString("PDF.Description.LineHeight")); descriptionFontFamily = getFontByName(configuration.getString("PDF.Description.FontFamily")); - contentFontSize = Integer.parseInt(configuration.getString("PDF.Content.FontSize")); + contentFontSize = Integer.parseInt(configuration.getString("PDF.Content.FontSize")); contentLineHeight = Integer.parseInt(configuration.getString("PDF.Content.LineHeight")); contentFontFamily = getFontByName(configuration.getString("PDF.Content.FontFamily")); - sourceFontSize = Integer.parseInt(configuration.getString("PDF.Source.FontSize")); + sourceFontSize = Integer.parseInt(configuration.getString("PDF.Source.FontSize")); sourceLineHeight = Integer.parseInt(configuration.getString("PDF.Source.LineHeight")); sourceFontFamily = getFontByName(configuration.getString("PDF.Source.FontFamily")); - bigImageCaptionFontSize = Integer.parseInt(configuration.getString("PDF.BigImageCaption.FontSize")); + bigImageCaptionFontSize = Integer.parseInt(configuration.getString("PDF.BigImageCaption.FontSize")); bigImageCaptionFontFamily = getFontByName(configuration.getString("PDF.BigImageCaption.FontFamily")); } - catch (NumberFormatException e){ - e.printStackTrace(); + catch (NumberFormatException e) { + throw new Failure(e.getMessage(), e); } // step 1: make a document String pageSize = configuration.getString("PDF.Pagesize"); - if (pageSize.equals("LETTER")){ + if (pageSize.equals("LETTER")) { document = new Document(PageSize.LETTER); pageWidth = 612; pageHeight = 792; - } - else { - document = new Document(PageSize.A4); - pageWidth=595; - pageHeight=842; + } else { + document = new Document(PageSize.A4); + pageWidth = 595; + pageHeight = 842; } - maxImageHeight = 250; - maxImageWidth = 250; + maxImageHeight = 250; + maxImageWidth = 250; verticalMargin = 20; horizontalMargin = 20; + topEdge = pageHeight - verticalMargin; + bottomEdge = verticalMargin; + rightEdge = pageWidth - horizontalMargin; + leftEdge = horizontalMargin; - topEdge=pageHeight-verticalMargin; - bottomEdge=verticalMargin; - rightEdge=pageWidth-horizontalMargin; - leftEdge=horizontalMargin; - - currentYPosition=topEdge; + currentYPosition = topEdge; currentPage = 1; String headerText = configuration.getString("PDF.Title.String"); - try{ + try { writer = PdfWriter.getInstance(document, out); cb = writer.getDirectContent(); document.open(); addHeader(headerText); } - catch(DocumentException de) { + catch (DocumentException de) { logger.error(de.getMessage()); } } - public void stop(){ + public void stop() { addFooter(); document.close(); } - public void addHeader(String headerText){ - int titleFontSize=Integer.parseInt(configuration.getString("PDF.Title.FontSize")); - int titleLineHeight=Integer.parseInt(configuration.getString("PDF.Title.LineHeight")); - String titleFontFamily=configuration.getString("PDF.Title.FontFamily"); - String headerImage=configuration.getString("PDF.Header.Image"); + public void addHeader(String headerText) { + int titleFontSize = Integer.parseInt(configuration.getString("PDF.Title.FontSize")); + int titleLineHeight = Integer.parseInt(configuration.getString("PDF.Title.LineHeight")); + String titleFontFamily = configuration.getString("PDF.Title.FontFamily"); + String headerImage = configuration.getString("PDF.Header.Image"); int headerImageHeight = Integer.parseInt(configuration.getString("PDF.Header.ImageHeight")); try { - if ((! headerImage.equals("")) && headerImageHeight != 0){ - PdfTemplate template = cb.createTemplate(rightEdge-horizontalMargin,headerImageHeight); + if ((! headerImage.equals("")) && headerImageHeight != 0) { + PdfTemplate template = cb.createTemplate(rightEdge - horizontalMargin, headerImageHeight); - float toYPosition=currentYPosition - headerImageHeight; - Image theImage = Image.getInstance(headerImage); - theImage.setAbsolutePosition(0,0); - // theImage.scaleAbsolute(img_width,img_height); - template.addImage(theImage); + float toYPosition = currentYPosition - headerImageHeight; + Image theImage = Image.getInstance(headerImage); + theImage.setAbsolutePosition(0, 0); + // theImage.scaleAbsolute(img_width,img_height); + template.addImage(theImage); - cb.addTemplate(template,leftEdge,toYPosition); - currentYPosition = toYPosition; + cb.addTemplate(template, leftEdge, toYPosition); + currentYPosition = toYPosition; } - if (! headerText.equals("")){ - ColumnText ct = new ColumnText(cb); - //add a basic header - ct.addText(new Phrase(headerText, new Font(getFontByName(titleFontFamily), titleFontSize,Font.BOLD))); - float[] rightCol = {rightEdge,currentYPosition,rightEdge,currentYPosition-titleLineHeight}; - float[] leftCol = {leftEdge,currentYPosition,leftEdge,currentYPosition-titleLineHeight}; - ct.setColumns(leftCol,rightCol); - ct.setYLine(currentYPosition); - ct.setAlignment(Element.ALIGN_CENTER); - ct.go(); - - currentYPosition = currentYPosition - titleLineHeight; + if (! headerText.equals("")) { + ColumnText ct = new ColumnText(cb); + //add a basic header + ct.addText(new Phrase(headerText, new Font(getFontByName(titleFontFamily), titleFontSize, Font.BOLD))); + float[] rightCol = {rightEdge, currentYPosition, rightEdge, currentYPosition - titleLineHeight}; + float[] leftCol = {leftEdge, currentYPosition, leftEdge, currentYPosition - titleLineHeight}; + ct.setColumns(leftCol, rightCol); + ct.setYLine(currentYPosition); + ct.setAlignment(Element.ALIGN_CENTER); + ct.go(); + + currentYPosition = currentYPosition - titleLineHeight; } } - catch(DocumentException de) { + catch (DocumentException de) { logger.error(de.getMessage()); } - catch(MalformedURLException de) { + catch (MalformedURLException de) { logger.error(de.getMessage()); } - catch(IOException de) { + catch (IOException de) { logger.error(de.getMessage()); } } - public void addIndexItem(EntityContent entityContent){ + + public void addIndexItem(EntityContent entityContent) { try { ColumnText ict = new ColumnText(cb); String theTitle = entityContent.getFieldValue("title"); String theCreator = entityContent.getFieldValue("creator"); - Phrase titleP=new Phrase(" - " + theTitle,new Font(indexFontFamily,indexFontSize,Font.BOLD)); - Phrase creatorP=new Phrase( " :: " + theCreator,new Font(indexFontFamily,indexFontSize)); + Phrase titleP = new Phrase(" - " + theTitle, new Font(indexFontFamily, indexFontSize, Font.BOLD)); + Phrase creatorP = new Phrase(" :: " + theCreator, new Font(indexFontFamily, indexFontSize)); float toYPosition = currentYPosition - indexLineHeight; - float[] leftIndexCols = {leftEdge,currentYPosition,leftEdge,toYPosition}; - float[] rightIndexCols = {rightEdge,currentYPosition,rightEdge,toYPosition}; + float[] leftIndexCols = {leftEdge, currentYPosition, leftEdge, toYPosition}; + float[] rightIndexCols = {rightEdge, currentYPosition, rightEdge, toYPosition}; ict.addText(titleP); ict.addText(creatorP); - ict.setColumns(leftIndexCols,rightIndexCols); + ict.setColumns(leftIndexCols, rightIndexCols); ict.setYLine(currentYPosition); ict.setAlignment(Element.ALIGN_LEFT); ict.go(); currentYPosition = toYPosition; } - catch(DocumentException de) { + catch (DocumentException de) { logger.error(de.getMessage()); } - } - private int addTextLine(ColumnText ct,int lineHeight,int alignment,float left, float right){ + private int addTextLine(ColumnText ct, int lineHeight, int alignment, float left, float right) { logger.debug("adding a line of text"); - if (! enoughY(lineHeight)){ + if (! enoughY(lineHeight)) { newPage(); } float toYPosition = currentYPosition - lineHeight; - float[] leftContentCols = {left,currentYPosition,left,toYPosition}; - float[] rightContentCols = {right,currentYPosition,right,toYPosition}; - ct.setColumns(leftContentCols,rightContentCols); + float[] leftContentCols = {left, currentYPosition, left, toYPosition}; + float[] rightContentCols = {right, currentYPosition, right, toYPosition}; + ct.setColumns(leftContentCols, rightContentCols); ct.setYLine(currentYPosition); ct.setAlignment(alignment); - try{ - int status=ct.go(); + try { + int status = ct.go(); currentYPosition = toYPosition; return status; } - catch(DocumentException de) { + catch (DocumentException de) { logger.error(de.getMessage()); } return 0; } - public void addLine(){ + public void addLine() { cb.setLineWidth(1f); - cb.moveTo(rightEdge, currentYPosition-5); - cb.lineTo(leftEdge, currentYPosition-5); + cb.moveTo(rightEdge, currentYPosition - 5); + cb.lineTo(leftEdge, currentYPosition - 5); cb.stroke(); currentYPosition = currentYPosition - 10; } - public void addFooter(){ - try{ - ColumnText fct = new ColumnText(cb); - cb.setLineWidth(1f); - cb.moveTo(rightEdge, bottomEdge+footerHeight-5); - cb.lineTo(leftEdge, bottomEdge+footerHeight-5); - cb.stroke(); - float[] leftFooterCols = {leftEdge,bottomEdge+footerHeight-1,leftEdge,bottomEdge}; - float[] rightFooterCols = {rightEdge,bottomEdge+footerHeight-1,rightEdge,bottomEdge}; + public void addFooter() { + try { + ColumnText fct = new ColumnText(cb); + cb.setLineWidth(1f); + cb.moveTo(rightEdge, bottomEdge + footerHeight - 5); + cb.lineTo(leftEdge, bottomEdge + footerHeight - 5); + cb.stroke(); + float[] leftFooterCols = {leftEdge, bottomEdge + footerHeight - 1, leftEdge, bottomEdge}; + float[] rightFooterCols = {rightEdge, bottomEdge + footerHeight - 1, rightEdge, bottomEdge}; - Paragraph footerP=new Paragraph(footerText,new Font(footerFontFamily,footerFontSize)); - fct.addText(footerP); + Paragraph footerP = new Paragraph(footerText, new Font(footerFontFamily, footerFontSize)); + fct.addText(footerP); - fct.setColumns(leftFooterCols,rightFooterCols); - fct.setYLine(bottomEdge+footerHeight-1); - fct.setAlignment(Element.ALIGN_JUSTIFIED); - fct.go(); + fct.setColumns(leftFooterCols, rightFooterCols); + fct.setYLine(bottomEdge + footerHeight - 1); + fct.setAlignment(Element.ALIGN_JUSTIFIED); + fct.go(); - Paragraph numberP=new Paragraph((new Integer(currentPage)).toString(),new Font(footerFontFamily,footerFontSize,Font.BOLD)); - fct.addText(numberP); - fct.setAlignment(Element.ALIGN_RIGHT); - fct.go(); + Paragraph numberP = new Paragraph((new Integer(currentPage)).toString(), new Font(footerFontFamily, footerFontSize, Font.BOLD)); + fct.addText(numberP); + fct.setAlignment(Element.ALIGN_RIGHT); + fct.go(); } - catch (DocumentException de){ + catch (DocumentException de) { logger.error(de.getMessage()); } } - public void newPage(){ - try{ + public void newPage() { + try { //add a footer addFooter(); document.newPage(); currentPage++; - currentYPosition=topEdge; + currentYPosition = topEdge; } - catch(DocumentException de) { + catch (DocumentException de) { logger.error(de.getMessage()); } } - public void addArticleSeparator(){ + public void addArticleSeparator() { // make a line - if (! enoughY(10)){ + if (! enoughY(10)) { newPage(); } cb.setLineWidth(1f); - cb.moveTo(rightEdge, currentYPosition-5); - cb.lineTo(leftEdge, currentYPosition-5); + cb.moveTo(rightEdge, currentYPosition - 5); + cb.lineTo(leftEdge, currentYPosition - 5); cb.stroke(); currentYPosition = currentYPosition - 10; } - public void addArticleMetaInfo(ColumnText ct,String theTitle,String theCreator,String theDate){ - //see if we have room for the author and title + public void addArticleMetaInfo(ColumnText ct, String theTitle, String theCreator, String theDate) { + //see if we have room for the author and title - if (! enoughY(metaHeight)){ - newPage(); - } + if (! enoughY(metaHeight)) { + newPage(); + } - Paragraph titleP=new Paragraph(theTitle+"\n",new Font(metaFontFamily,metaFontSize,Font.BOLD)); - Paragraph whowhenP=new Paragraph(theCreator + " " + theDate ,new Font(metaFontFamily,metaFontSize)); + Paragraph titleP = new Paragraph(theTitle + "\n", new Font(metaFontFamily, metaFontSize, Font.BOLD)); + Paragraph whowhenP = new Paragraph(theCreator + " " + theDate, new Font(metaFontFamily, metaFontSize)); ct.addText(titleP); ct.addText(whowhenP); @@ -383,243 +381,240 @@ public class PDFGenerator{ ct.setAlignment(Element.ALIGN_LEFT); float toYPosition = currentYPosition - metaHeight; - float[] leftHeadCols = {leftEdge,currentYPosition,leftEdge,toYPosition}; - float[] rightHeadCols = {rightEdge,currentYPosition,rightEdge,toYPosition}; + float[] leftHeadCols = {leftEdge, currentYPosition, leftEdge, toYPosition}; + float[] rightHeadCols = {rightEdge, currentYPosition, rightEdge, toYPosition}; - ct.setColumns(leftHeadCols,rightHeadCols); + ct.setColumns(leftHeadCols, rightHeadCols); try { ct.go(); currentYPosition = toYPosition; } - catch(DocumentException de) { + catch (DocumentException de) { logger.error(de.getMessage()); } } - public void addArticleDescription(ColumnText ct,String theDescription){ + public void addArticleDescription(ColumnText ct, String theDescription) { // Now we add the description, one line at a time, the ct should be empty at this point - Paragraph descP=new Paragraph(theDescription,new Font(descriptionFontFamily,descriptionFontSize,Font.BOLD)); + Paragraph descP = new Paragraph(theDescription, new Font(descriptionFontFamily, descriptionFontSize, Font.BOLD)); ct.addText(descP); // every article has a description, so we can assume that: int status = ColumnText.NO_MORE_COLUMN; - int brake=1000; - while ((status & ColumnText.NO_MORE_TEXT) == 0 && brake >0){ + int brake = 1000; + while ((status & ColumnText.NO_MORE_TEXT) == 0 && brake > 0) { //there is still text left in the description. - status = addTextLine(ct,descriptionLineHeight,Element.ALIGN_JUSTIFIED,leftEdge,rightEdge); + status = addTextLine(ct, descriptionLineHeight, Element.ALIGN_JUSTIFIED, leftEdge, rightEdge); brake--; } if (brake == 0) logger.error("runaway description...try increasing the line height or decreasing the font size"); } - public void addArticleContent(ColumnText ct,String theContent,Iterator images){ + public void addArticleContent(ColumnText ct, String theContent, Iterator images) { //let's go ahead and add in all the body text - Paragraph contentP=new Paragraph(theContent,new Font(contentFontFamily,contentFontSize)); + Paragraph contentP = new Paragraph(theContent, new Font(contentFontFamily, contentFontSize)); ct.addText(contentP); - int contentLinesBeforeImages=3; + int contentLinesBeforeImages = 3; //and assume we have at least one line of text in the content int status = ColumnText.NO_MORE_COLUMN; // let's add a little bit of text, like a couple of lines int x = 0; - while (((status & ColumnText.NO_MORE_TEXT) == 0) && xTitle:
- *Description:
- *Copyright: Copyright (c) 2003
- *Company:
- * @author not attributable - * @version 1.0 + * ServletModule for managing article types */ -public class ServletModuleArticleType extends ServletModule -{ - private static ServletModuleArticleType instance = new ServletModuleArticleType(); - public static ServletModule getInstance() { return instance; } - - private ServletModuleArticleType() { - logger = new LoggerWrapper("ServletModule.ArticleType"); - - try { - definition = "articleType"; - mainModule = new ModuleArticleType(); - } - catch (Exception e) { - logger.error("Initialization of ServletModuleArticleType failed!: " + e.getMessage()); - } +public class ServletModuleArticleType extends AdminServletModule { + public ServletModuleArticleType() { + definition = "articleType"; + mainModule = new ModuleArticleType(); } } diff --git a/source/mircoders/servlet/ServletModuleAudio.java b/source/mircoders/servlet/ServletModuleAudio.java index 4ef89ed0..7595b81e 100755 --- a/source/mircoders/servlet/ServletModuleAudio.java +++ b/source/mircoders/servlet/ServletModuleAudio.java @@ -29,36 +29,17 @@ */ package mircoders.servlet; -import mir.log.LoggerWrapper; -import mir.servlet.ServletModule; import mircoders.module.ModuleUploadedMedia; import mircoders.storage.DatabaseAudio; -/* - * - * - * @author br1 +/** + * ServletModule for managing Audio uploads */ - public class ServletModuleAudio extends ServletModuleUploadedMedia { - private static ServletModuleAudio instance = new ServletModuleAudio(); - - public static ServletModule getInstance() { - return instance; - } - - private ServletModuleAudio() { - logger = new LoggerWrapper("ServletModule.Audio"); - - moduleName = "Audio"; - - try { - definition = "audio"; - mainModule = new ModuleUploadedMedia(DatabaseAudio.getInstance()); - } - catch (Throwable e) { - logger.error("servletmodule audio could not be initialized: " + e.getMessage()); - } + public ServletModuleAudio() { + super("Audio"); + definition = "audio"; + mainModule = new ModuleUploadedMedia(DatabaseAudio.getInstance()); } } diff --git a/source/mircoders/servlet/ServletModuleBreaking.java b/source/mircoders/servlet/ServletModuleBreaking.java index c18ffc79..2ea482ef 100755 --- a/source/mircoders/servlet/ServletModuleBreaking.java +++ b/source/mircoders/servlet/ServletModuleBreaking.java @@ -30,34 +30,16 @@ package mircoders.servlet; -import mir.log.LoggerWrapper; -import mir.servlet.ServletModule; +import mir.servlet.AdminServletModule; import mircoders.module.ModuleBreaking; /** - * - *Title:
- *Description:
- *Copyright: Copyright (c) 2003
- *Company:
- * @author not attributable - * @version 1.0 + * ServletModule for managing breaking news */ -public class ServletModuleBreaking extends ServletModule -{ - private static ServletModuleBreaking instance = new ServletModuleBreaking(); - public static ServletModule getInstance() { return instance; } - - private ServletModuleBreaking() { - logger = new LoggerWrapper("ServletModule.Breaking"); - - try { - definition = "breakingNews"; - mainModule = new ModuleBreaking(); - } - catch (Exception e) { - logger.error("Initialisation of ServletModuleBreaking failed!: " + e.getMessage()); - } +public class ServletModuleBreaking extends AdminServletModule { + public ServletModuleBreaking() { + definition = "breakingNews"; + mainModule = new ModuleBreaking(); } } diff --git a/source/mircoders/servlet/ServletModuleComment.java b/source/mircoders/servlet/ServletModuleComment.java index eff08cd9..8f6bbebb 100755 --- a/source/mircoders/servlet/ServletModuleComment.java +++ b/source/mircoders/servlet/ServletModuleComment.java @@ -32,8 +32,7 @@ package mircoders.servlet; import mir.entity.adapter.EntityAdapterEngine; import mir.entity.adapter.EntityAdapterModel; -import mir.log.LoggerWrapper; -import mir.servlet.ServletModule; +import mir.servlet.AdminServletModule; import mir.servlet.ServletModuleExc; import mir.servlet.ServletModuleFailure; import mir.servlet.ServletModuleUserExc; @@ -48,29 +47,20 @@ import mircoders.storage.DatabaseComment; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.util.*; - -/* - * ServletModuleComment - controls navigation for Comments - * - * - * @author the mir-coders +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +/** + * ServletModule for managing Comments */ -public class ServletModuleComment extends ServletModule -{ - private static ServletModuleComment instance = new ServletModuleComment(); - public static ServletModule getInstance() { return instance; } - - private ServletModuleComment() { - logger = new LoggerWrapper("ServletModule.Comment"); - try { - mainModule = new ModuleComment(); - definition = "comment"; - } - catch (Exception e) { - logger.error("servletmodule comment could not be initialized:" + e.getMessage()); - } +public class ServletModuleComment extends AdminServletModule { + public ServletModuleComment() { + mainModule = new ModuleComment(); + definition = "comment"; } public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure { @@ -84,12 +74,12 @@ public class ServletModuleComment extends ServletModule } } - public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { + public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { String idParam = aRequest.getParameter("id"); - if (idParam == null) + if (idParam == null) { throw new ServletModuleExc("Invalid call: id not supplied "); + } editObject(aRequest, aResponse, idParam); } @@ -139,7 +129,9 @@ public class ServletModuleComment extends ServletModule String mediaIdParam = aRequest.getParameter("mid"); String commentId = aRequest.getParameter("commentid"); - if (commentId == null || mediaIdParam==null) throw new ServletModuleExc("smod comment :: attach :: commentid/mid missing"); + if (commentId == null || mediaIdParam==null) { + throw new ServletModuleExc("smod comment :: attach :: commentid/mid missing"); + } try { EntityComment comment = (EntityComment) mainModule.getById(commentId); @@ -158,10 +150,12 @@ public class ServletModuleComment extends ServletModule { String commentId = aRequest.getParameter("commentid"); String midParam = aRequest.getParameter("mid"); - if (commentId == null) + if (commentId == null) { throw new ServletModuleExc("smod comment :: dettach :: commentid missing"); - if (midParam == null) + } + if (midParam == null) { throw new ServletModuleExc("smod comment :: dettach :: mid missing"); + } try { EntityComment comment = (EntityComment)mainModule.getById(commentId); @@ -199,10 +193,10 @@ public class ServletModuleComment extends ServletModule String searchStatus = requestParser.getParameter("searchstatus"); String searchOrder = requestParser.getParameter("searchorder"); - if (searchIsPublished.equals("0")) { + if ("0".equals(searchIsPublished)) { queryBuilder.appendAndCondition("is_published='f'"); } - else if (searchIsPublished.equals("1")) { + else if ("1".equals(searchIsPublished)) { queryBuilder.appendAndCondition("is_published='t'"); } @@ -217,26 +211,27 @@ public class ServletModuleComment extends ServletModule } if (searchOrder.length()>0) { - if (searchOrder.equals("datedesc")) + if ("datedesc".equals(searchOrder)) { queryBuilder.appendDescendingOrder("webdb_create"); - else if (searchOrder.equals("dateasc")) + } + else if ("dateasc".equals(searchOrder)) { queryBuilder.appendAscendingOrder("webdb_create"); - else if (searchOrder.equals("articletitle")) + } + else if ("articletitle".equals(searchOrder)) { queryBuilder.appendAscendingOrder("(select content.title from content where content.id = comment.to_media)"); - else if (searchOrder.equals("creator")) + } + else if ("creator".equals(searchOrder)) { queryBuilder.appendDescendingOrder("creator"); + } } returnList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0); } - public void articlecomments(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { + public void articlecomments(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { String articleIdString = aRequest.getParameter("articleid"); - int articleId; - try { - articleId = Integer.parseInt(articleIdString); + int articleId = Integer.parseInt(articleIdString); returnList( aRequest, aResponse, "to_media="+articleId, "webdb_create desc", 0); } @@ -255,7 +250,8 @@ public class ServletModuleComment extends ServletModule Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); List commentList = - EntityAdapterEngine.retrieveAdapterList(model, definition, aWhereClause, anOrderByClause, nrEntitiesPerListPage, anOffset); + EntityAdapterEngine.retrieveAdapterList(getModel(), definition, aWhereClause, + anOrderByClause, nrEntitiesPerListPage, anOffset); responseData.put("nexturl", null); responseData.put("prevurl", null); @@ -278,7 +274,7 @@ public class ServletModuleComment extends ServletModule responseData.put("searchorder", requestParser.getParameter("searchorder")); urlBuilder.setValue("offset", anOffset); - responseData.put("offset" , new Integer(anOffset).toString()); + responseData.put("offset" , Integer.toString(anOffset)); responseData.put("thisurl" , urlBuilder.getQuery()); if (commentList.size()>=nrEntitiesPerListPage) { @@ -310,19 +306,23 @@ public class ServletModuleComment extends ServletModule String returnUrl = requestParser.getParameter("returnurl"); String idParam = aRequest.getParameter("id"); - if (idParam == null) + if (idParam == null) { throw new ServletModuleExc("Wrong call: (id) is missing"); + } Map withValues = getIntersectingValues(aRequest, DatabaseComment.getInstance()); - if (!withValues.containsKey("is_published")) + if (!withValues.containsKey("is_published")) { withValues.put("is_published","0"); - if (!withValues.containsKey("is_html")) + } + if (!withValues.containsKey("is_html")) { withValues.put("is_html","0"); + } String webdbCreate = (String) withValues.get("webdb_create"); - if (webdbCreate==null || webdbCreate.trim().length()==0) + if (webdbCreate==null || webdbCreate.trim().length()==0) { withValues.remove("webdb_create"); + } String id = mainModule.set(withValues); @@ -331,8 +331,9 @@ public class ServletModuleComment extends ServletModule if (returnUrl!=null){ ServletHelper.redirect(aResponse, returnUrl); } - else + else { editObject(aRequest, aResponse, idParam); + } } catch (Throwable e) { throw new ServletModuleFailure(e); diff --git a/source/mircoders/servlet/ServletModuleCommentStatus.java b/source/mircoders/servlet/ServletModuleCommentStatus.java index 71767a0b..881f91ff 100755 --- a/source/mircoders/servlet/ServletModuleCommentStatus.java +++ b/source/mircoders/servlet/ServletModuleCommentStatus.java @@ -29,25 +29,13 @@ */ package mircoders.servlet; -import mir.log.LoggerWrapper; -import mir.servlet.ServletModule; +import mir.servlet.AdminServletModule; import mircoders.module.ModuleCommentStatus; -public class ServletModuleCommentStatus extends ServletModule -{ - private static ServletModuleCommentStatus instance = new ServletModuleCommentStatus(); - public static ServletModule getInstance() { return instance; } - - private ServletModuleCommentStatus() { - logger = new LoggerWrapper("ServletModule.CommentStatus"); - - try { - definition = "commentStatus"; - mainModule = new ModuleCommentStatus(); - } - catch (Throwable e) { - logger.error("Initialization of ServletModuleCommentStatus failed!: " + e.getMessage()); - } +public class ServletModuleCommentStatus extends AdminServletModule { + public ServletModuleCommentStatus() { + definition = "commentStatus"; + mainModule = new ModuleCommentStatus(); } } diff --git a/source/mircoders/servlet/ServletModuleContent.java b/source/mircoders/servlet/ServletModuleContent.java index 7bd4dba2..563fde8c 100755 --- a/source/mircoders/servlet/ServletModuleContent.java +++ b/source/mircoders/servlet/ServletModuleContent.java @@ -34,12 +34,15 @@ import mir.entity.adapter.EntityAdapter; import mir.entity.adapter.EntityAdapterEngine; import mir.entity.adapter.EntityAdapterModel; import mir.generator.Generator; -import mir.log.LoggerWrapper; import mir.misc.StringUtil; -import mir.servlet.ServletModule; +import mir.servlet.AdminServletModule; import mir.servlet.ServletModuleExc; import mir.servlet.ServletModuleFailure; -import mir.util.*; +import mir.util.HTTPRequestParser; +import mir.util.JDBCStringRoutines; +import mir.util.SQLQueryBuilder; +import mir.util.StringRoutines; +import mir.util.URLBuilder; import mircoders.entity.EntityContent; import mircoders.entity.EntityUsers; import mircoders.global.MirGlobal; @@ -49,32 +52,26 @@ import mircoders.storage.DatabaseContentToTopics; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; /** * Article admin interface code */ -public class ServletModuleContent extends ServletModule { - private static ServletModuleContent instance = new ServletModuleContent(); - public static ServletModule getInstance() { return instance; } - private static ModuleContent contentModule; +public class ServletModuleContent extends AdminServletModule { + private ModuleContent contentModule = new ModuleContent(); - private ServletModuleContent() { - super(); - - propagatedParameters.add("selectarticleurl"); - - logger = new LoggerWrapper("ServletModule.Content"); - - try { - definition = "content"; - contentModule = new ModuleContent(); - mainModule = contentModule; - } - catch (Throwable e) { - logger.fatal("ServletModuleContent could not be initialized: " + e.toString()); - } + public ServletModuleContent() { + addPropagatedParameter("selectarticleurl"); + definition = "content"; + mainModule = contentModule; } public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleFailure { @@ -88,24 +85,29 @@ public class ServletModuleContent extends ServletModule { String searchArticleType = requestParser.getParameterWithDefault("searcharticletype", ""); if (searchValue.length()>0) { - if (searchField.equals("id")) + if ("id".equals(searchField)) { queryBuilder.appendAndCondition( "id='"+JDBCStringRoutines.escapeStringLiteral(searchValue)+"'"); - else if (searchField.equals("contents")) + } + else if ("contents".equals(searchField)) { queryBuilder.appendAndCondition( "(lower(content_data) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')"+ " or (lower(description) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')"); - else + } + else { queryBuilder.appendAndCondition( "lower("+ searchField + ") like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%'"); + } } if (searchispublished.length()>0) { - if (searchispublished.equals("0")) + if ("0".equals(searchispublished)) { queryBuilder.appendAndCondition("is_published='f'"); - else + } + else { queryBuilder.appendAndCondition("is_published='t'"); + } } if (searchArticleType.length()>0) { @@ -113,14 +115,18 @@ public class ServletModuleContent extends ServletModule { } if (searchOrder.length()>0) { - if (searchOrder.equals("datedesc")) + if ("datedesc".equals(searchOrder)) { queryBuilder.appendDescendingOrder("webdb_create"); - else if (searchOrder.equals("dateasc")) + } + else if ("dateasc".equals(searchOrder)) { queryBuilder.appendAscendingOrder("webdb_create"); - else if (searchOrder.equals("title")) + } + else if ("title".equals(searchOrder)) { queryBuilder.appendAscendingOrder("title"); - else if (searchOrder.equals("creator")) + } + else if ("creator".equals(searchOrder)) { queryBuilder.appendAscendingOrder("creator"); + } } returnList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0); @@ -143,14 +149,17 @@ public class ServletModuleContent extends ServletModule { withValues.put("publish_path", StringUtil.webdbDate2path(now)); withValues.put("to_publisher", ServletHelper.getUser(aRequest).getId()); withValues.put("is_produced", "0"); - if (!withValues.containsKey("is_published")) + if (!withValues.containsKey("is_published")) { withValues.put("is_published","0"); - if (!withValues.containsKey("is_html")) + } + if (!withValues.containsKey("is_html")) { withValues.put("is_html","0"); + } String webdbCreate = (String) withValues.get("webdb_create"); - if (webdbCreate==null || webdbCreate.trim().length()==0) + if (webdbCreate==null || webdbCreate.trim().length()==0) { withValues.remove("webdb_create"); + } String id = mainModule.add(withValues); logAdminUsage(aRequest, id, "object added"); @@ -177,21 +186,22 @@ public class ServletModuleContent extends ServletModule { public void attach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { String mediaIdParam = aRequest.getParameter("mid"); String articleId = aRequest.getParameter("articleid"); - if (articleId == null || mediaIdParam==null) + if (articleId == null || mediaIdParam==null) { throw new ServletModuleExc("smod content :: attach :: articleid/mid missing"); + } + // check if mediaIdParam and articleid are correct integers - try - { + try { Integer.parseInt(mediaIdParam); Integer.parseInt(articleId); } - catch(NumberFormatException e) - { - throw new ServletModuleExc("smod content :: attach :: invalid articleid/mid"); + catch (NumberFormatException e) { + throw new ServletModuleExc("smod content :: attach :: invalid articleid/mid", e); } - if (!MirGlobal.accessControl().article().mayEditArticle(ServletHelper.getUser(aRequest), articleId)) + if (!MirGlobal.accessControl().article().mayEditArticle(ServletHelper.getUser(aRequest), articleId)) { throw new ServletModuleExc("Article has been locked"); + } try { EntityContent entContent = (EntityContent) mainModule.getById(articleId); @@ -241,13 +251,15 @@ public class ServletModuleContent extends ServletModule { HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); String idParam = requestParser.getParameter("id"); - if (idParam == null) + if (idParam == null) { throw new ServletModuleExc("Wrong call: (id) is missing"); + } EntityUsers user = ServletHelper.getUser(aRequest); - if (!MirGlobal.accessControl().article().mayLockArticle(user, idParam)) + if (!MirGlobal.accessControl().article().mayLockArticle(user, idParam)) { throw new ServletModuleExc("Unable to lock"); + } contentModule.lockArticle(idParam, user.getId(), false); @@ -262,13 +274,15 @@ public class ServletModuleContent extends ServletModule { HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); String idParam = requestParser.getParameter("id"); - if (idParam == null) + if (idParam == null) { throw new ServletModuleExc("Wrong call: (id) is missing"); + } EntityUsers user = ServletHelper.getUser(aRequest); - if (!MirGlobal.accessControl().article().mayUnlockArticle(user, idParam)) + if (!MirGlobal.accessControl().article().mayUnlockArticle(user, idParam)) { throw new ServletModuleExc("Unable to unlock"); + } contentModule.unlockArticle(idParam, user.getId(), false); @@ -303,23 +317,28 @@ public class ServletModuleContent extends ServletModule { HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); String idParam = requestParser.getParameter("id"); - if (idParam == null) + if (idParam == null) { throw new ServletModuleExc("Wrong call: (id) is missing"); + } - if (!MirGlobal.accessControl().article().mayEditArticle(ServletHelper.getUser(aRequest), idParam)) + if (!MirGlobal.accessControl().article().mayEditArticle(ServletHelper.getUser(aRequest), idParam)) { throw new ServletModuleExc("Article has been locked"); + } Map withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance()); withValues.put("is_produced", "0"); - if (!withValues.containsKey("is_published")) + if (!withValues.containsKey("is_published")) { withValues.put("is_published","0"); - if (!withValues.containsKey("is_html")) + } + if (!withValues.containsKey("is_html")) { withValues.put("is_html","0"); + } String webdbCreate = (String) withValues.get("webdb_create"); - if (webdbCreate==null || webdbCreate.trim().length()==0) + if (webdbCreate==null || webdbCreate.trim().length()==0) { withValues.remove("webdb_create"); + } String id = mainModule.set(withValues); @@ -328,7 +347,7 @@ public class ServletModuleContent extends ServletModule { DatabaseContentToTopics.getInstance().setTopics(aRequest.getParameter("id"), aRequest.getParameterValues("to_topic")); if (MirGlobal.accessControl().article().mayUnlockArticle(ServletHelper.getUser(aRequest), idParam) && - (requestParser.getParameterWithDefault("unlock", "0").equals("1"))) { + requestParser.getParameterWithDefault("unlock", "0").equals("1")) { contentModule.unlockArticle(id, ServletHelper.getUser(aRequest).getId(), false); } @@ -343,11 +362,11 @@ public class ServletModuleContent extends ServletModule { /** * Returns the basic article editing form. * - * @param id identifier of the article.null
, means show an
+ * @param anId identifier of the article. null
, means show an
* empty form to add a new article.
*/
- public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse, String id)
- throws ServletModuleExc {
+ public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse,
+ String anId) throws ServletModuleExc {
try {
HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
@@ -357,19 +376,20 @@ public class ServletModuleContent extends ServletModule {
urlBuilder.setValue("module", "Content");
urlBuilder.setValue("do", "edit");
- urlBuilder.setValue("id", id);
+ urlBuilder.setValue("id", anId);
urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
- if (id!=null) {
+ if (anId !=null) {
responseData.put("new", Boolean.FALSE);
- article = model.makeEntityAdapter("content", mainModule.getById(id));
+ article = model.makeEntityAdapter("content", mainModule.getById(anId));
EntityUsers user = ServletHelper.getUser(aRequest);
- responseData.put("mayEdit", new Boolean(MirGlobal.accessControl().article().mayEditArticle(user, id)));
- responseData.put("mayLock", new Boolean(MirGlobal.accessControl().article().mayLockArticle(user, id)));
- responseData.put("mayForceLock", new Boolean(MirGlobal.accessControl().article().mayForceLockArticle(user, id)));
- responseData.put("mayUnlock", new Boolean(MirGlobal.accessControl().article().mayUnlockArticle(user, id)));
+ responseData.put("mayEdit",
+ new Boolean(MirGlobal.accessControl().article().mayEditArticle(user, anId)));
+ responseData.put("mayLock", new Boolean(MirGlobal.accessControl().article().mayLockArticle(user, anId)));
+ responseData.put("mayForceLock", new Boolean(MirGlobal.accessControl().article().mayForceLockArticle(user, anId)));
+ responseData.put("mayUnlock", new Boolean(MirGlobal.accessControl().article().mayUnlockArticle(user, anId)));
}
else {
List fields = DatabaseContent.getInstance().getFieldNames();
@@ -395,7 +415,7 @@ public class ServletModuleContent extends ServletModule {
List topicsList = new ArrayList();
- String[] topicCategories = configuration.getStringArray("Mir.Localizer.Admin.TopicLists");
+ String[] topicCategories = getConfiguration().getStringArray("Mir.Localizer.Admin.TopicLists");
if (topicCategories.length==0 ) {
Map categoryMap = new HashMap();
@@ -407,37 +427,37 @@ public class ServletModuleContent extends ServletModule {
}
else {
for (int i = 0; i < topicCategories.length; i++) {
- try {
- Map categoryMap = new HashMap();
- List parts = StringRoutines.splitString(topicCategories[i], ":");
-
- String key = null;
- String listtype = "0";
- String listparameter = "5";
- String where = "";
- String order = "";
-
- if (parts.size() > 0)
- key = (String) parts.get(0);
- if (parts.size() > 1)
- listtype = (String) parts.get(1);
- if (parts.size() > 2)
- listparameter = (String) parts.get(2);
- if (parts.size() > 3)
- where = (String) parts.get(3);
- if (parts.size() > 4)
- order = (String) parts.get(4);
-
- if (key != null) {
- categoryMap.put("key", key);
- categoryMap.put("listtype", listtype);
- categoryMap.put("listparameter", listparameter);
- categoryMap.put("items", EntityAdapterEngine.retrieveAdapterList(model, "topic", where, order, -1, 0));
- topicsList.add(categoryMap);
- }
+ Map categoryMap = new HashMap();
+ List parts = StringRoutines.splitString(topicCategories[i], ":");
+
+ String key = null;
+
+ if (parts.size() > 0) {
+ key = (String) parts.get(0);
+ }
+ String listtype = "0";
+ if (parts.size() > 1) {
+ listtype = (String) parts.get(1);
+ }
+ String listparameter = "5";
+ if (parts.size() > 2) {
+ listparameter = (String) parts.get(2);
}
- catch (Throwable t) {
- logger.error("error while preparing topics: " + t.toString());
+ String where = "";
+ if (parts.size() > 3) {
+ where = (String) parts.get(3);
+ }
+ String order = "";
+ if (parts.size() > 4) {
+ order = (String) parts.get(4);
+ }
+
+ if (key != null) {
+ categoryMap.put("key", key);
+ categoryMap.put("listtype", listtype);
+ categoryMap.put("listparameter", listparameter);
+ categoryMap.put("items", EntityAdapterEngine.retrieveAdapterList(model, "topic", where, order, -1, 0));
+ topicsList.add(categoryMap);
}
}
}
@@ -473,13 +493,14 @@ public class ServletModuleContent extends ServletModule {
}
public void listchildren(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
- try {
- HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
- String articleId = requestParser.getParameter("article_id");
+ HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+ String articleId = requestParser.getParameter("article_id");
- if (articleId == null)
- throw new ServletModuleExc("ServletModuleContent.listchildren: article_id not set!");
+ if (articleId == null) {
+ throw new ServletModuleExc("ServletModuleContent.listchildren: article_id not set!");
+ }
+ try {
returnList(aRequest, aResponse, "to_content = " + articleId, "webdb_create desc", 0);
}
catch (Throwable e) {
@@ -504,7 +525,8 @@ public class ServletModuleContent extends ServletModule {
logAdminUsage(aRequest, articleId, "parent set to " + parentId);
}
catch(Throwable e) {
- logger.error("ServletModuleContent.setparent: " + e.getMessage());
+ getLogger().error("ServletModuleContent.setparent: " + e.getMessage());
+
throw new ServletModuleFailure(e);
}
@@ -524,8 +546,7 @@ public class ServletModuleContent extends ServletModule {
logAdminUsage(aRequest, articleId, "parent cleared");
}
catch(Throwable e) {
- e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
- logger.error("ServletModuleContent.clearparent: " + e.getMessage());
+ getLogger().error("ServletModuleContent.clearparent: " + e.getMessage(), e);
throw new ServletModuleFailure("ServletModuleContent.clearparent: " + e.getMessage(), e);
}
@@ -537,14 +558,14 @@ public class ServletModuleContent extends ServletModule {
try {
HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
String articleId = requestParser.getParameter("id");
- EntityAdapter article = model.makeEntityAdapter("content", mainModule.getById(articleId));
+ EntityAdapter article = getModel().makeEntityAdapter("content", mainModule.getById(articleId));
String preview = requestParser.getParameterWithDefault("preview", "default");
Map generationValues = new HashMap();
Generator generator =
MirGlobal.localizer().adminInterface().prepareArticlePreview(preview, article, generationValues);
- generator.generate(aResponse.getWriter(), generationValues, logger);
+ generator.generate(aResponse.getWriter(), generationValues, getLogger());
}
catch (Exception e) {
throw new ServletModuleFailure(e);
diff --git a/source/mircoders/servlet/ServletModuleFileEdit.java b/source/mircoders/servlet/ServletModuleFileEdit.java
index b74a6002..52bf4bea 100755
--- a/source/mircoders/servlet/ServletModuleFileEdit.java
+++ b/source/mircoders/servlet/ServletModuleFileEdit.java
@@ -46,8 +46,7 @@ import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
import mir.servlet.ServletModuleExc;
import mir.servlet.ServletModuleFailure;
import mir.util.FileRoutines;
@@ -61,59 +60,22 @@ import mir.util.URLBuilder;
* in the config file.
*
* @author $Author: zapata $
- * @version $Revision: 1.13.2.10 $ $Date: 2005/08/21 17:09:24 $
+ * @version $Revision: 1.13.2.11 $ $Date: 2005/10/01 18:40:41 $
*
*/
-public class ServletModuleFileEdit extends ServletModule
-{
- private static ServletModuleFileEdit instance = new ServletModuleFileEdit();
- public static ServletModule getInstance() { return instance; }
-
+public class ServletModuleFileEdit extends AdminServletModule {
private Map directories;
private List directoryNames;
private FilenameFilter dirFilter;
- private class FileEditDirectory {
- private String name;
- private FileRoutines.RegExpFileFilter filter;
- private File rootDirectory;
- private boolean recursive;
-
- public FileEditDirectory(String aName, String aRootDirectory, String aFilter, boolean aRecursive) {
- name = aName;
- rootDirectory = new File(aRootDirectory);
- filter = new FileRoutines.RegExpFileFilter(aFilter);
- recursive = aRecursive;
- }
-
- public String getName() {
- return name;
- }
-
- public FileRoutines.RegExpFileFilter getFilter() {
- return filter;
- }
-
- public File getRootDirectory() {
- return rootDirectory;
- }
-
- public boolean getRecursive() {
- return recursive;
- }
- }
-
- private ServletModuleFileEdit() {
- super();
-
- logger = new LoggerWrapper("ServletModule.FileEdit");
-
+ public ServletModuleFileEdit() {
directories = new HashMap();
directoryNames = new ArrayList();
- String settings[] = configuration.getStringArray("ServletModule.FileEdit.Configuration");
+ String settings[] =
+ getConfiguration().getStringArray("ServletModule.FileEdit.Configuration");
if (settings!=null) {
for (int i = 0; i < settings.length; i++) {
@@ -122,7 +84,7 @@ public class ServletModuleFileEdit extends ServletModule
if (setting.length() > 0) {
List parts = StringRoutines.splitStringWithEscape(setting, ':', '\\');
if (parts.size() != 4) {
- logger.error("config error: " + settings[i] + ", 4 parts expected");
+ getLogger().error("config error: " + settings[i] + ", 4 parts expected");
}
else {
String name = (String) parts.get(0);
@@ -131,7 +93,7 @@ public class ServletModuleFileEdit extends ServletModule
String recursive = (String) parts.get(3);
directories.put(name, new FileEditDirectory(name, directory, filter,
- recursive.equals("1") || recursive.toLowerCase().equals("y")));
+ "1".equals(recursive) || "y".equals(recursive.toLowerCase())));
directoryNames.add(name);
}
}
@@ -212,7 +174,7 @@ public class ServletModuleFileEdit extends ServletModule
try {
File f = new File(new File(directory.getRootDirectory(), subDirectory), filename);
- if (validateDirectory(directory, f)) {
+ if (isDirectoryValid(directory, f)) {
FileWriter out = new FileWriter(f);
try {
out.write(text.toCharArray());
@@ -239,7 +201,7 @@ public class ServletModuleFileEdit extends ServletModule
Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
File dir = new File(aDirectory.getRootDirectory(), aSubDirectory);
- if (!validateDirectory(aDirectory, dir) || !dir.isDirectory()) {
+ if (!isDirectoryValid(aDirectory, dir) || !dir.isDirectory()) {
dir = aDirectory.getRootDirectory();
aSubDirectory = "";
}
@@ -274,7 +236,7 @@ public class ServletModuleFileEdit extends ServletModule
try {
File f = new File(new File(aDirectory.getRootDirectory(), aSubDirectory), aFileName);
- if (!validateDirectory(aDirectory, f) || f.isDirectory() || !validateFile(aDirectory, f)) {
+ if (!isDirectoryValid(aDirectory, f) || f.isDirectory() || !isFileValid(aDirectory, f)) {
listSubDirectory(aDirectory, "", aRequest, aResponse);
}
else {
@@ -314,16 +276,16 @@ public class ServletModuleFileEdit extends ServletModule
}
}
- protected boolean validateDirectory(FileEditDirectory aDirectory, File aFile) {
+ private boolean isDirectoryValid(FileEditDirectory aDirectory, File aFile) {
try {
- return (aFile.getCanonicalPath().startsWith(aDirectory.getRootDirectory().getCanonicalPath()));
+ return aFile.getCanonicalPath().startsWith(aDirectory.getRootDirectory().getCanonicalPath());
}
catch (Throwable t) {
return false;
}
}
- protected boolean validateFile(FileEditDirectory aDirectory, File aFile) {
+ private boolean isFileValid(FileEditDirectory aDirectory, File aFile) {
try {
return aDirectory.getFilter().accept(aFile.getParentFile(), aFile.getName());
}
@@ -331,4 +293,35 @@ public class ServletModuleFileEdit extends ServletModule
return false;
}
}
+
+ private class FileEditDirectory {
+ private String name;
+ private FileRoutines.RegExpFileFilter filter;
+ private File rootDirectory;
+ private boolean recursive;
+
+ public FileEditDirectory(String aName, String aRootDirectory, String aFilter, boolean aRecursive) {
+ name = aName;
+ rootDirectory = new File(aRootDirectory);
+ filter = new FileRoutines.RegExpFileFilter(aFilter);
+ recursive = aRecursive;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public FileRoutines.RegExpFileFilter getFilter() {
+ return filter;
+ }
+
+ public File getRootDirectory() {
+ return rootDirectory;
+ }
+
+ public boolean getRecursive() {
+ return recursive;
+ }
+ }
+
}
diff --git a/source/mircoders/servlet/ServletModuleHidden.java b/source/mircoders/servlet/ServletModuleHidden.java
index f4939111..bd936385 100755
--- a/source/mircoders/servlet/ServletModuleHidden.java
+++ b/source/mircoders/servlet/ServletModuleHidden.java
@@ -30,11 +30,9 @@
package mircoders.servlet;
import mir.entity.adapter.EntityAdapterEngine;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
import mir.servlet.ServletModuleExc;
import mir.servlet.ServletModuleFailure;
-import mir.storage.DatabaseFailure;
import mir.util.HTTPRequestParser;
import mir.util.JDBCStringRoutines;
import mircoders.module.ModuleContent;
@@ -51,46 +49,36 @@ import java.util.Map;
* @version $Id
*/
-public class ServletModuleHidden extends ServletModule {
- private static ServletModuleHidden instance = new ServletModuleHidden();
- public static ServletModule getInstance() { return instance; }
-
- private ServletModuleHidden() {
- super();
-
- logger = new LoggerWrapper("ServletModule.Hidden");
-
- try {
- definition = "content";
- mainModule = new ModuleContent();
- }
- catch (DatabaseFailure e) {
- logger.error("initialization of servletmoduleHidden failed: " + e.getMessage());
- }
+public class ServletModuleHidden extends AdminServletModule {
+ public ServletModuleHidden() {
+ definition = "content";
+ mainModule = new ModuleContent();
}
- public void list(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {
- HTTPRequestParser requestParser = new HTTPRequestParser(req);
- Map responseData = ServletHelper.makeGenerationData(req, res, new Locale[] { getLocale(req), getFallbackLocale(req)});
+ public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
+ HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+ Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
- String query_year = requestParser.getParameter("year");
- String query_month = requestParser.getParameter("month");
+ String queryYear = requestParser.getParameter("year");
+ String queryMonth = requestParser.getParameter("month");
try {
- if ((query_year!=null && !query_year.equals("")) && (query_month!=null && !query_month.equals(""))) {
+ if ((queryYear !=null && !queryYear.equals("")) &&
+ (queryMonth !=null && !queryMonth.equals(""))) {
String whereClause = "is_published=false AND webdb_create LIKE "+
- "'"+JDBCStringRoutines.escapeStringLiteral(query_year)+"-"+JDBCStringRoutines.escapeStringLiteral(query_month)+"%'";
+ "'"+JDBCStringRoutines.escapeStringLiteral(queryYear)+"-"+
+ JDBCStringRoutines.escapeStringLiteral(queryMonth)+"%'";
- List articleList = EntityAdapterEngine.retrieveAdapterList(model, definition, whereClause, "webdb_create", -1, 0);
+ List articleList = EntityAdapterEngine.retrieveAdapterList(getModel(), definition, whereClause, "webdb_create", -1, 0);
- responseData.put("year", query_year);
- responseData.put("month", query_month);
+ responseData.put("year", queryYear);
+ responseData.put("month", queryMonth);
responseData.put("articles", articleList);
}
- ServletHelper.generateResponse(res.getWriter(), responseData, listGenerator);
+ ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);
}
catch (Throwable e) {
throw new ServletModuleFailure(e);
diff --git a/source/mircoders/servlet/ServletModuleImages.java b/source/mircoders/servlet/ServletModuleImages.java
index 1bfe0d8d..20bfaad4 100755
--- a/source/mircoders/servlet/ServletModuleImages.java
+++ b/source/mircoders/servlet/ServletModuleImages.java
@@ -29,36 +29,21 @@
*/
package mircoders.servlet;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
import mircoders.module.ModuleImages;
/*
* ServletModuleImages -
*
- * @version $Id: ServletModuleImages.java,v 1.26.2.5 2005/04/10 10:52:00 zapata Exp $
+ * @version $Id: ServletModuleImages.java,v 1.26.2.6 2005/10/01 18:40:41 zapata Exp $
* @author RK, the mir-coders group
*/
-public class ServletModuleImages extends ServletModuleUploadedMedia
-{
- private static ServletModuleImages instance = new ServletModuleImages();
- public static ServletModule getInstance() { return instance; }
-
-
- private ServletModuleImages() {
- super();
- logger = new LoggerWrapper("ServletModule.Images");
- moduleName = "Images";
-
- try {
- definition = "image";
- mainModule = new ModuleImages();
- }
- catch (Throwable e) {
- logger.error("Initialization of ServletModuleImages failed!: " + e.getMessage());
- }
+public class ServletModuleImages extends ServletModuleUploadedMedia {
+ public ServletModuleImages() {
+ super("Images");
+
+ definition = "image";
+ mainModule = new ModuleImages();
}
-
}
diff --git a/source/mircoders/servlet/ServletModuleLanguage.java b/source/mircoders/servlet/ServletModuleLanguage.java
index 616f3b68..0a6e2d49 100755
--- a/source/mircoders/servlet/ServletModuleLanguage.java
+++ b/source/mircoders/servlet/ServletModuleLanguage.java
@@ -29,33 +29,16 @@
*/
package mircoders.servlet;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
import mircoders.module.ModuleLanguage;
-/*
- * ServletModuleLanguage -
- * Servlet-Interface to Language
- *
- *
- * @author idefix
+/**
+ * ServletModule for managing languages
*/
-public class ServletModuleLanguage extends ServletModule
-{
- private static ServletModuleLanguage instance = new ServletModuleLanguage();
- public static ServletModule getInstance() { return instance; }
-
- private ServletModuleLanguage() {
- super();
- logger = new LoggerWrapper("ServletModule.Language");
-
- try {
- definition = "language";
- mainModule = new ModuleLanguage();
- }
- catch (Throwable e) {
- logger.error("Initialization of ServletModuleLanguage failed: " + e.getMessage());
- }
+public class ServletModuleLanguage extends AdminServletModule {
+ public ServletModuleLanguage() {
+ definition = "language";
+ mainModule = new ModuleLanguage();
}
}
\ No newline at end of file
diff --git a/source/mircoders/servlet/ServletModuleLocalizer.java b/source/mircoders/servlet/ServletModuleLocalizer.java
index e5b92b8d..3862daf0 100755
--- a/source/mircoders/servlet/ServletModuleLocalizer.java
+++ b/source/mircoders/servlet/ServletModuleLocalizer.java
@@ -29,16 +29,7 @@
*/
package mircoders.servlet;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
import mir.servlet.ServletModuleExc;
import mir.util.StringRoutines;
import mircoders.entity.EntityComment;
@@ -47,24 +38,22 @@ import mircoders.global.MirGlobal;
import mircoders.module.ModuleComment;
import mircoders.module.ModuleContent;
-public class ServletModuleLocalizer extends ServletModule {
- private static ServletModuleLocalizer instance = new ServletModuleLocalizer();
- public static ServletModule getInstance() { return instance; }
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
- private ModuleContent contentModule;
- private ModuleComment commentModule;
- private List administerOperations;
+public class ServletModuleLocalizer extends AdminServletModule {
+ private final ModuleContent contentModule = new ModuleContent();
+ private final ModuleComment commentModule = new ModuleComment();
+ private final List administerOperations = new ArrayList();
- private ServletModuleLocalizer() {
+ public ServletModuleLocalizer() {
try {
- logger = new LoggerWrapper("ServletModule.Localizer");
-
- contentModule = new ModuleContent();
- commentModule = new ModuleComment();
-
- administerOperations = new ArrayList();
-
- String settings[] = configuration.getStringArray("Mir.Localizer.Admin.AdministerOperations");
+ String settings[] =
+ getConfiguration().getStringArray("Mir.Localizer.Admin.AdministerOperations");
if (settings!=null) {
for (int i = 0; i < settings.length; i++) {
@@ -73,7 +62,7 @@ public class ServletModuleLocalizer extends ServletModule {
if (setting.length() > 0) {
List parts = StringRoutines.splitString(setting, ":");
if (parts.size() != 2) {
- logger.error("config error: " + settings[i] + ", 2 parts expected");
+ getLogger().error("config error: " + settings[i] + ", 2 parts expected");
}
else {
Map entry = new HashMap();
@@ -86,7 +75,7 @@ public class ServletModuleLocalizer extends ServletModule {
}
}
catch (Exception e) {
- logger.error("ServletModuleLocalizer could not be initialized: " + e.getMessage());
+ getLogger().error("ServletModuleLocalizer could not be initialized" + e.getMessage(), e);
}
}
@@ -101,22 +90,20 @@ public class ServletModuleLocalizer extends ServletModule {
* @param anOperation The identifier of the operation to perform
*/
public void performCommentOperation(HttpServletRequest aRequest, String anId, String anOperation) {
- EntityComment entity;
-
try {
- entity = (EntityComment) commentModule.getById(anId);
+ EntityComment entity = (EntityComment) commentModule.getById(anId);
if (entity != null) {
MirGlobal.performCommentOperation(ServletHelper.getUser(aRequest), entity, anOperation);
- logger.info("Operation " + anOperation + " successfully performed on comment " + anId);
+ getLogger().debug("Operation " + anOperation + " successfully performed on comment " + anId);
logAdminUsage(aRequest, "comment."+anId, "operation " + anOperation + " performed");
}
else {
- logger.error("Error while performing " + anOperation + " on comment " + anId + ": comment is null");
+ getLogger().error("Error while performing " + anOperation + " on comment " + anId + ": comment is null");
}
}
catch (Throwable e) {
- logger.error("Error while performing " + anOperation + " on comment " + anId + ": " + e.getMessage());
+ getLogger().error("Error while performing " + anOperation + " on comment " + anId + ": " + e.getMessage(), e);
}
}
@@ -141,7 +128,7 @@ public class ServletModuleLocalizer extends ServletModule {
List parts = StringRoutines.splitString(operations[i], ";");
if (parts.size() != 2) {
- logger.error("commentoperationbatch: operation string invalid: " +
+ getLogger().error("commentoperationbatch: operation string invalid: " +
operations[i]);
}
else {
@@ -165,15 +152,15 @@ public class ServletModuleLocalizer extends ServletModule {
if (entity != null) {
MirGlobal.performArticleOperation(ServletHelper.getUser(aRequest), entity, anOperation);
- logger.info("Operation " + anOperation + " successfully performed on article " + anId);
+ getLogger().info("Operation " + anOperation + " successfully performed on article " + anId);
logAdminUsage(aRequest, "article." + anId, "operation " + anOperation + " performed");
}
else {
- logger.error("Error while performing " + anOperation + " on article " + anId + ": article is null");
+ getLogger().error("Error while performing " + anOperation + " on article " + anId + ": article is null");
}
}
catch (Throwable e) {
- logger.error("Error while performing " + anOperation + " on article " + anId + ": " + e.getMessage());
+ getLogger().error("Error while performing " + anOperation + " on article " + anId + ": " + e.getMessage());
}
}
@@ -198,7 +185,7 @@ public class ServletModuleLocalizer extends ServletModule {
List parts = StringRoutines.splitString(operations[i], ";");
if (parts.size() != 2) {
- logger.error("articleoperationbatch: operation string invalid: " + operations[i]);
+ getLogger().error("articleoperationbatch: operation string invalid: " + operations[i]);
}
else {
String articleIdString = (String) parts.get(0);
diff --git a/source/mircoders/servlet/ServletModuleMediaType.java b/source/mircoders/servlet/ServletModuleMediaType.java
index 62ac870f..3d3bb6eb 100755
--- a/source/mircoders/servlet/ServletModuleMediaType.java
+++ b/source/mircoders/servlet/ServletModuleMediaType.java
@@ -29,24 +29,12 @@
*/
package mircoders.servlet;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
import mircoders.module.ModuleMediaType;
-public class ServletModuleMediaType extends ServletModule
-{
- private static ServletModuleMediaType instance = new ServletModuleMediaType();
- public static ServletModule getInstance() { return instance; }
-
- private ServletModuleMediaType() {
- logger = new LoggerWrapper("ServletModule.MediaType");
-
- try {
- definition = "mediaType";
- mainModule = new ModuleMediaType();
- }
- catch (Exception e) {
- logger.error("Initialization of ServletModuleArticleType failed!: " + e.getMessage());
- }
+public class ServletModuleMediaType extends AdminServletModule {
+ public ServletModuleMediaType() {
+ definition = "mediaType";
+ mainModule = new ModuleMediaType();
}
}
diff --git a/source/mircoders/servlet/ServletModuleMediafolder.java b/source/mircoders/servlet/ServletModuleMediafolder.java
index 0054cd96..2ee76157 100755
--- a/source/mircoders/servlet/ServletModuleMediafolder.java
+++ b/source/mircoders/servlet/ServletModuleMediafolder.java
@@ -35,30 +35,14 @@ import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import mir.log.LoggerWrapper;
import mir.misc.StringUtil;
-import mir.servlet.ServletModule;
+import mir.servlet.AdminServletModule;
import mircoders.module.ModuleMediafolder;
-/**
- *
- */
-public class ServletModuleMediafolder extends ServletModule
-{
- public static ServletModule getInstance() { return instance; }
- private static ServletModuleMediafolder instance = new ServletModuleMediafolder();
-
- private ServletModuleMediafolder() {
- super();
- logger = new LoggerWrapper("ServletModule.Mediafolder");
-
- try {
- definition = "mediaFolder";
- mainModule = new ModuleMediafolder();
- }
- catch (Throwable t) {
- logger.error("Failed to initialize ServletModuleMediafolder: " + t.toString());
- }
+public class ServletModuleMediafolder extends AdminServletModule {
+ public ServletModuleMediafolder() {
+ definition = "mediaFolder";
+ mainModule = new ModuleMediafolder();
}
protected void initializeNewObject(Map aNewObject, HttpServletRequest aRequest, HttpServletResponse aResponse) {
diff --git a/source/mircoders/servlet/ServletModuleMessage.java b/source/mircoders/servlet/ServletModuleMessage.java
index 6b76231b..8be9d696 100755
--- a/source/mircoders/servlet/ServletModuleMessage.java
+++ b/source/mircoders/servlet/ServletModuleMessage.java
@@ -29,44 +29,17 @@
*/
package mircoders.servlet;
-import java.util.Map;
+import mir.servlet.AdminServletModule;
+import mircoders.module.ModuleMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import java.util.Map;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
-import mir.servlet.ServletModuleFailure;
-import mircoders.module.ModuleMessage;
-
-/**
- * Title: ServletModuleMessage
- * Description:
- * Copyright: Copyright (c) 2001-2002
- * Company: mir-coders
- * @author
- * @version 1.0
- */
-
-
-public class ServletModuleMessage extends ServletModule
-{
- private static ServletModuleMessage instance = new ServletModuleMessage();
- public static ServletModule getInstance() { return instance; }
-
- private ServletModuleMessage() {
- super();
- logger = new LoggerWrapper("ServletModule.Messages");
-
- try {
- definition = "internalMessage";
- mainModule = new ModuleMessage();
- }
- catch (Throwable e) {
- logger.error("initialization of ServletModuleMessage failed!: " + e.getMessage());
-
- throw new ServletModuleFailure(e);
- }
+public class ServletModuleMessage extends AdminServletModule {
+ public ServletModuleMessage() {
+ definition = "internalMessage";
+ mainModule = new ModuleMessage();
}
protected void initializeNewObject(Map aNewObject, HttpServletRequest aRequest, HttpServletResponse aResponse) {
diff --git a/source/mircoders/servlet/ServletModuleOpenIndy.java b/source/mircoders/servlet/ServletModuleOpenIndy.java
index ea91bf08..e5b19606 100755
--- a/source/mircoders/servlet/ServletModuleOpenIndy.java
+++ b/source/mircoders/servlet/ServletModuleOpenIndy.java
@@ -33,29 +33,38 @@ package mircoders.servlet;
import gnu.regexp.RE;
import gnu.regexp.REMatch;
import mir.bundle.Bundle;
-import mir.entity.Entity;
import mir.generator.Generator;
-import mir.log.LoggerWrapper;
import mir.misc.StringUtil;
import mir.servlet.ServletModule;
import mir.servlet.ServletModuleExc;
import mir.servlet.ServletModuleFailure;
import mir.servlet.ServletModuleUserExc;
-import mir.session.*;
-import mir.storage.DatabaseFailure;
-import mir.util.*;
-import mircoders.entity.EntityComment;
+import mir.session.HTTPAdapters;
+import mir.session.Request;
+import mir.session.Session;
+import mir.session.SessionHandler;
+import mir.session.SimpleResponse;
+import mir.util.FileRoutines;
+import mir.util.HTTPParsedRequest;
+import mir.util.HTTPRequestParser;
+import mir.util.StringRoutines;
+import mir.module.ModuleExc;
import mircoders.entity.EntityContent;
import mircoders.global.CacheKey;
import mircoders.global.MirGlobal;
-import mircoders.media.MediaUploadProcessor;
-import mircoders.media.UnsupportedMediaTypeExc;
-import mircoders.module.ModuleComment;
import mircoders.module.ModuleContent;
import mircoders.pdf.PDFGenerator;
-import mircoders.search.*;
-import mircoders.storage.*;
-import org.apache.commons.fileupload.FileItem;
+import mircoders.search.AudioSearchTerm;
+import mircoders.search.ContentSearchTerm;
+import mircoders.search.ImagesSearchTerm;
+import mircoders.search.KeywordSearchTerm;
+import mircoders.search.TextSearchTerm;
+import mircoders.search.TopicMatrixSearchTerm;
+import mircoders.search.TopicSearchTerm;
+import mircoders.search.UnIndexedSearchTerm;
+import mircoders.search.VideoSearchTerm;
+import mircoders.storage.DatabaseTopics;
+import mircoders.localizer.MirLocalizerExc;
import org.apache.commons.net.smtp.SMTPClient;
import org.apache.commons.net.smtp.SMTPReply;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
@@ -70,62 +79,39 @@ import org.apache.lucene.store.FSDirectory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
-import java.io.*;
-import java.util.*;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.ListIterator;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Random;
+import java.util.Set;
/*
- * ServletModuleOpenIndy -
- * is the open-access-servlet, which is responsible for
- * adding comments to articles &
- * open-postings to the newswire
- *
- * @author mir-coders group
- * @version $Id: ServletModuleOpenIndy.java,v 1.89.2.18 2005/08/21 17:09:24 zapata Exp $
- *
*/
-public class ServletModuleOpenIndy extends ServletModule
-{
-
- private String commentFormTemplate, commentFormDoneTemplate, commentFormDupeTemplate;
- private String postingFormTemplate, postingFormDoneTemplate, postingFormDupeTemplate;
+public class ServletModuleOpenIndy extends ServletModule {
private String searchResultsTemplate;
private String prepareMailTemplate,sentMailTemplate,emailAnArticleTemplate;
private ModuleContent contentModule;
- private ModuleComment commentModule;
- private String directOp ="yes";
- private static ServletModuleOpenIndy instance = new ServletModuleOpenIndy();
- public static ServletModule getInstance() {
- return instance;
- }
+ public ServletModuleOpenIndy() {
+ searchResultsTemplate = getConfiguration().getString("ServletModule.OpenIndy.SearchResultsTemplate");
+ prepareMailTemplate = getConfiguration().getString("ServletModule.OpenIndy.PrepareMailTemplate");
+ emailAnArticleTemplate = getConfiguration().getString("ServletModule.OpenIndy.MailableArticleTemplate");
+ sentMailTemplate = getConfiguration().getString("ServletModule.OpenIndy.SentMailTemplate");
- private ServletModuleOpenIndy() {
- super();
- try {
- logger = new LoggerWrapper("ServletModule.OpenIndy");
-
- commentFormTemplate = configuration.getString("ServletModule.OpenIndy.CommentTemplate");
- commentFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.CommentDoneTemplate");
- commentFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.CommentDupeTemplate");
-
- postingFormTemplate = configuration.getString("ServletModule.OpenIndy.PostingTemplate");
- postingFormDoneTemplate = configuration.getString("ServletModule.OpenIndy.PostingDoneTemplate");
- postingFormDupeTemplate = configuration.getString("ServletModule.OpenIndy.PostingDupeTemplate");
-
- searchResultsTemplate = configuration.getString("ServletModule.OpenIndy.SearchResultsTemplate");
- prepareMailTemplate = configuration.getString("ServletModule.OpenIndy.PrepareMailTemplate");
- emailAnArticleTemplate = configuration.getString("ServletModule.OpenIndy.MailableArticleTemplate");
- sentMailTemplate = configuration.getString("ServletModule.OpenIndy.SentMailTemplate");
- directOp = configuration.getString("DirectOpenposting").toLowerCase();
- commentModule = new ModuleComment();
- mainModule = commentModule;
- contentModule = new ModuleContent();
- defaultAction = "defaultAction";
- }
- catch (DatabaseFailure e) {
- logger.error("servletmoduleopenindy could not be initialized: " + e.getMessage());
- }
+ contentModule = new ModuleContent();
}
/**
@@ -145,334 +131,7 @@ public class ServletModuleOpenIndy extends ServletModule
* @throws ServletModuleFailure
*/
public void openPostingDisabled(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
- deliver(aRequest, aResponse, null, null, configuration.getString("ServletModule.OpenIndy.PostingDisabledTemplate"));
- }
-
- /**
- * Method for making a comment
- */
- public void addcomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
- if (MirGlobal.abuse().getOpenPostingDisabled()) {
- openPostingDisabled(req, res);
-
- return;
- }
-
- String aid = req.getParameter("aid"); // the article id the comment will belong to
-
- if (aid != null && !aid.equals("")) {
- try {
- Map mergeData = new HashMap();
-
- // onetimepasswd
- if (MirGlobal.abuse().getOpenPostingPassword()) {
- String passwd = generateOnetimePassword();
- HttpSession session = req.getSession(false);
- session.setAttribute("passwd", passwd);
- mergeData.put("passwd", passwd);
- }
- else {
- mergeData.put("passwd", null);
- }
- mergeData.put("aid", aid);
-
- Map extraInfo = new HashMap();
- extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());
-
- deliver(req, res, mergeData, extraInfo, commentFormTemplate);
- }
- catch (Throwable t) {
- throw new ServletModuleFailure("ServletModuleOpenIndy.addcomment: " + t.getMessage(), t);
- }
- }
- else
- throw new ServletModuleExc("aid not set!");
- }
-
- /**
- * Method for inserting a comment into the Database and delivering
- * the commentDone Page
- */
-
- public void inscomment(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
- if (MirGlobal.abuse().getOpenPostingDisabled()) {
- openPostingDisabled(req, res);
-
- return;
- }
-
- String aid = req.getParameter("to_media"); // the article id the comment will belong to
- if (aid != null && !aid.equals("")) {
- // ok, collecting data from form
- try {
- Map withValues = getIntersectingValues(req, DatabaseComment.getInstance());
-
- //no html in comments(for now)
- for (Iterator i = withValues.keySet().iterator(); i.hasNext(); ) {
- String k = (String) i.next();
- String v = (String) withValues.get(k);
-
- withValues.put(k, StringUtil.removeHTMLTags(v));
- }
- withValues.put("is_published", "1");
- withValues.put("to_comment_status", "1");
- withValues.put("is_html", "0");
-
- //checking the onetimepasswd
- HttpSession session = req.getSession(false);
- String sessionPasswd = (String) session.getAttribute("passwd");
- if (sessionPasswd != null) {
- String passwd = req.getParameter("passwd");
- if (passwd == null || passwd.length() == 0) {
- throw new ServletModuleUserExc("comment.error.missingpassword", new String[] {});
- }
- if (!sessionPasswd.equals(passwd)) {
- throw new ServletModuleUserExc("comment.error.invalidpassword", new String[] {});
- }
- session.invalidate();
- }
-
- String id = mainModule.add(withValues);
-
- SimpleResponse response = new SimpleResponse();
- response.setResponseGenerator(commentFormDoneTemplate);
-
- if (id == null) {
- deliver(req, res, null, null, commentFormDupeTemplate);
- }
- else {
- DatabaseContent.getInstance().setUnproduced("id=" + aid);
-
- try {
- EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(id);
- MirGlobal.localizer().openPostings().afterCommentPosting(comment);
- MirGlobal.abuse().checkComment(
- comment, new HTTPAdapters.HTTPRequestAdapter(req), res);
- }
- catch (Throwable t) {
- throw new ServletModuleExc(t.getMessage());
- }
- }
-
- // redirecting to url
- // should implement back to article
- deliver(req, res, response.getResponseValues(), null, response.getResponseGenerator());
- }
- catch (Throwable e) {
- throw new ServletModuleFailure(e);
- }
- }
- else
- throw new ServletModuleExc("aid not set!");
-
- }
-
- /**
- * Method for delivering the form-Page for open posting
- */
-
- public void addposting(HttpServletRequest req, HttpServletResponse res)
- throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
- try {
- if (MirGlobal.abuse().getOpenPostingDisabled()) {
- openPostingDisabled(req, res);
-
- return;
- }
-
- Map mergeData = new HashMap();
-
- // onetimepasswd
- if (MirGlobal.abuse().getOpenPostingPassword()) {
- String passwd = generateOnetimePassword();
- HttpSession session = req.getSession(false);
- session.setAttribute("passwd", passwd);
- mergeData.put("passwd", passwd);
- }
- else {
- mergeData.put("passwd", null);
- }
-
- String maxMedia = configuration.getString("ServletModule.OpenIndy.MaxMediaUploadItems");
- String defaultMedia = configuration.getString("ServletModule.OpenIndy.DefaultMediaUploadItems");
- String numOfMedia = req.getParameter("medianum");
-
- if (numOfMedia == null || numOfMedia.equals("")) {
- numOfMedia = defaultMedia;
- }
- else if (Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
- numOfMedia = maxMedia;
- }
-
- int mediaNum = Integer.parseInt(numOfMedia);
- List mediaFields = new ArrayList();
- for (int i = 0; i < mediaNum; i++) {
- Integer mNum = new Integer(i + 1);
- mediaFields.add(mNum.toString());
- }
- mergeData.put("medianum", numOfMedia);
- mergeData.put("mediafields", mediaFields);
- mergeData.put("to_topic", null);
-
- Map extraInfo = new HashMap();
- extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());
- extraInfo.put("themenPopupData", DatabaseTopics.getInstance().getPopupData());
-
- deliver(req, res, mergeData, extraInfo, postingFormTemplate);
- }
- catch (Throwable t) {
- throw new ServletModuleFailure(t);
- }
- }
-
- /**
- * Method for inserting an open posting into the Database and delivering
- * the postingDone Page
- */
-
- public void insposting(HttpServletRequest aRequest, HttpServletResponse aResponse) throws
- ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
- if (MirGlobal.abuse().getOpenPostingDisabled()) {
- openPostingDisabled(aRequest, aResponse);
-
- return;
- }
-
- try {
- HTTPParsedRequest parsedRequest = new HTTPParsedRequest(
- aRequest,
- configuration.getString("Mir.DefaultEncoding"),
- configuration.getInt("MaxMediaUploadSize")*1024,
- configuration.getString("TempDir"));
-
- Map mergeData = new HashMap();
-
- HttpSession session = aRequest.getSession(false);
- String sessionPasswd = (String) session.getAttribute("passwd");
- if (sessionPasswd != null) {
- String passwd = parsedRequest.getParameter("passwd");
-
- if (passwd == null || passwd.length() == 0) {
- throw new ServletModuleUserExc("posting.error.missingpassword", new String[] {});
- }
- if (!sessionPasswd.equals(passwd)) {
- throw new ServletModuleUserExc("posting.error.invalidpassword", new String[] {});
- }
- session.invalidate();
- }
-
- if (((parsedRequest.getParameter("title")).length() == 0) ||
- ((parsedRequest.getParameter("description")).length() == 0) ||
- ((parsedRequest.getParameter("content_data")).length() == 0))
- throw new ServletModuleUserExc("posting.error.missingfield", new String[] {});
-
- List mediaList = new ArrayList();
- Iterator i = parsedRequest.getFiles().iterator();
-
- while (i.hasNext()) {
- UploadedFile file = new mir.session.CommonsUploadedFileAdapter((FileItem) i.next());
- Map mediaValues = new HashMap();
-
- String suffix = file.getFieldName().substring(5); // media${m}
- logger.debug("media_title" + suffix);
- String title = parsedRequest.getParameter("media_title" + suffix);
-
- mediaValues.put("title", StringUtil.removeHTMLTags(title));
- mediaValues.put("creator", StringUtil.removeHTMLTags(parsedRequest.getParameter("creator")));
- mediaValues.put("to_publisher", "0");
- mediaValues.put("is_published", "1");
- mediaValues.put("to_media_folder", "7");
-
- mediaList.add(MediaUploadProcessor.processMediaUpload(file, mediaValues));
- }
-
- Map withValues = new HashMap();
- i = DatabaseContent.getInstance().getFieldNames().iterator();
- while (i.hasNext()) {
- String field = (String) i.next();
- String value = parsedRequest.getParameter(field);
- if (value!=null)
- withValues.put(field, value);
- }
-
-
- for (i = withValues.keySet().iterator(); i.hasNext(); ) {
- String k = (String) i.next();
- String v = (String) withValues.get(k);
-
- if (k.equals("content_data")) {
- //this doesn't quite work yet, so for now, all html goes
- //withValues.put(k,StringUtil.approveHTMLTags(v));
- withValues.put(k, StringUtil.deleteForbiddenTags(v));
- }
- else if (k.equals("description")) {
- String tmp = StringUtil.deleteForbiddenTags(v);
- withValues.put(k, StringUtil.deleteHTMLTableTags(tmp));
- }
- else {
- withValues.put(k, StringUtil.removeHTMLTags(v));
- }
- }
-
- withValues.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));
- withValues.put("publish_path",
- StringUtil.webdbDate2path( (String) withValues.get("date")));
- withValues.put("is_produced", "0");
- withValues.put("is_published", "1");
- if (directOp.equals("yes"))
- withValues.put("to_article_type", "1");
-
- withValues.put("to_publisher", "1");
-
- // inserting content into database
- String cid = contentModule.add(withValues);
- logger.debug("id: " + cid);
- //insert was not successfull
- if (cid == null) {
- deliver(aRequest, aResponse, mergeData, null, postingFormDupeTemplate);
- return;
- }
-
- List topics = parsedRequest.getParameterList("to_topic");
- if (topics.size() > 0) {
- try {
- DatabaseContentToTopics.getInstance().setTopics(cid, topics);
- }
- catch (Throwable e) {
- logger.error("setting content_x_topic failed");
- contentModule.deleteById(cid);
- throw new ServletModuleFailure(
- "smod - openindy :: insposting: setting content_x_topic failed: " +
- e.toString(), e);
- }
- }
-
- i = mediaList.iterator();
- while (i.hasNext()) {
- Entity mediaEnt = (Entity) i.next();
- DatabaseContentToMedia.getInstance().addMedia(cid, mediaEnt.getId());
- }
-
- EntityContent article = (EntityContent) contentModule.getById(cid);
- try {
- MirGlobal.abuse().checkArticle(
- article, new HTTPAdapters.HTTPRequestAdapter(aRequest), aResponse);
- MirGlobal.localizer().openPostings().afterContentPosting(article);
- }
- catch (Throwable t) {
- logger.error("Error while post-processing article: " + t.getMessage());
- }
- deliver(aRequest, aResponse, mergeData, null, postingFormDoneTemplate);
- }
- catch (Throwable e) {
- e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
- Throwable cause = ExceptionRoutines.traceCauseException(e);
-
- if (cause instanceof UnsupportedMediaTypeExc) {
- throw new ServletModuleUserExc("media.unsupportedformat", new String[] {});
- }
- throw new ServletModuleFailure(e);
- }
+ deliver(aRequest, aResponse, null, null, getConfiguration().getString("ServletModule.OpenIndy.PostingDisabledTemplate"));
}
/**
@@ -491,7 +150,7 @@ public class ServletModuleOpenIndy extends ServletModule
String requestLanguage = aRequest.getParameter("language");
String sessionLanguage = (String) aSession.getAttribute("language");
String acceptLanguage = aRequest.getLocale().getLanguage();
- String defaultLanguage = configuration.getString("Mir.Login.DefaultLanguage", "en");
+ String defaultLanguage = getConfiguration().getString("Mir.Login.DefaultLanguage", "en");
String language = requestLanguage;
@@ -525,18 +184,23 @@ public class ServletModuleOpenIndy extends ServletModule
try {
Request request =
new HTTPAdapters.HTTPParsedRequestAdapter(new HTTPParsedRequest(aRequest,
- configuration.getString("Mir.DefaultEncoding"),
- configuration.getInt("MaxMediaUploadSize")*1024,
- configuration.getString("TempDir")));
+ getConfiguration().getString("Mir.DefaultEncoding"),
+ getConfiguration().getInt("MaxMediaUploadSize")*1024,
+ getConfiguration().getString("TempDir")));
if (aRequest.isRequestedSessionIdValid() && !aRequest.isRequestedSessionIdFromURL() &&
- !aRequest.getRequestedSessionId().equals(aRequest.getParameter(SESSION_REQUEST_KEY)))
+ !aRequest.getRequestedSessionId().equals(aRequest.getParameter(SESSION_REQUEST_KEY))) {
aRequest.getSession().invalidate();
+ }
Session session = new HTTPAdapters.HTTPSessionAdapter(aRequest.getSession());
SimpleResponse response = new SimpleResponse(
- ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getResponseLocale(aRequest.getSession(), aRequest), getFallbackLocale(aRequest)},
+ ServletHelper.makeGenerationData(aRequest, aResponse,
+ new Locale[] {
+ getResponseLocale(aRequest.getSession(), aRequest),
+ getFallbackLocale(aRequest)
+ },
"etc/bundles/open"));
response.setResponseValue("actionURL", aResponse.encodeURL(MirGlobal.config().getString("RootUri") + "/servlet/OpenMir")+"?"+SESSION_REQUEST_KEY+"="+aRequest.getSession().getId());
@@ -547,8 +211,7 @@ public class ServletModuleOpenIndy extends ServletModule
ServletHelper.generateOpenPostingResponse(aResponse.getWriter(), response.getResponseValues(), response.getResponseGenerator());
}
catch (Throwable t) {
- logger.error(t.toString());
- t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+ getLogger().error(t.toString(), t);
throw new ServletModuleFailure(t);
}
@@ -557,20 +220,20 @@ public class ServletModuleOpenIndy extends ServletModule
/**
* Method for preparing and sending a content as an email message
*/
- public void mail(HttpServletRequest req, HttpServletResponse res)
- throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
- {
- String aid = req.getParameter("mail_aid");
+ public void mail(HttpServletRequest aRequest, HttpServletResponse aResponse)
+ throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
+ String aid = aRequest.getParameter("mail_aid");
if (aid == null){
- throw new ServletModuleExc("An article id must be specified in requests to email an article. Something therefore went badly wrong....");
+ throw new ServletModuleExc("An article id must be specified in requests " +
+ "to email an article. Something therefore went badly wrong....");
}
- String to = req.getParameter("mail_to");
- String from = req.getParameter("mail_from");
- String from_name = req.getParameter("mail_from_name");
- String from_ip = req.getRemoteAddr();
- String comment = req.getParameter("mail_comment");
- String mail_language = req.getParameter("mail_language");
+ String to = aRequest.getParameter("mail_to");
+ String from = aRequest.getParameter("mail_from");
+ String from_name = aRequest.getParameter("mail_from_name");
+ String from_ip = aRequest.getRemoteAddr();
+ String comment = aRequest.getParameter("mail_comment");
+ String mail_language = aRequest.getParameter("mail_language");
Map mergeData = new HashMap();
mergeData.put("mail_to",to);
@@ -582,7 +245,7 @@ public class ServletModuleOpenIndy extends ServletModule
if (to == null || from == null || from_name == null|| to.equals("") || from.equals("") || from_name.equals("") || mail_language == null || mail_language.equals("")){
- deliver(req, res, mergeData, null, prepareMailTemplate);
+ deliver(aRequest, aResponse, mergeData, null, prepareMailTemplate);
}
else {
//run checks on to and from and mail_language to make sure no monkey business occurring
@@ -601,31 +264,46 @@ public class ServletModuleOpenIndy extends ServletModule
CacheKey theCacheKey=new CacheKey("email",aid+mail_language);
String theEmailText;
+ EntityContent article;
+ try {
+ article = (EntityContent) contentModule.getById(aid);
+ }
+ catch (ModuleExc e) {
+ throw new ServletModuleExc("Couldn't retrieve article " + aid);
+ }
+
+ if (!MirGlobal.localizer().openPostings().allowArticlePublication(article)) {
+ throw new ServletModuleExc("Illegal article");
+ }
+
if (MirGlobal.mruCache().hasObject(theCacheKey)){
- logger.info("fetching email text for article "+aid+" from cache");
+ getLogger().info("fetching email text for article "+aid+" from cache");
theEmailText = (String) MirGlobal.mruCache().getObject(theCacheKey);
}
else {
- EntityContent contentEnt;
+ StringWriter theEMailTextWriter = new StringWriter();
+ PrintWriter dest = new PrintWriter(theEMailTextWriter);
try {
- contentEnt = (EntityContent) contentModule.getById(aid);
- StringWriter theEMailTextWriter = new StringWriter();
- PrintWriter dest = new PrintWriter(theEMailTextWriter);
Map articleData = new HashMap();
- articleData.put("article", MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("content", contentEnt));
+ try {
+ articleData.put("article",
+ MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("content", article));
+ }
+ catch (MirLocalizerExc e) {
+ throw new ServletModuleExc("Can't retrieve article " + aid, e);
+ }
articleData.put("languagecode", mail_language);
- deliver(dest, req, res, articleData, null, emailAnArticleTemplate, mail_language);
- theEmailText = theEMailTextWriter.toString();
- MirGlobal.mruCache().storeObject(theCacheKey, theEmailText);
+ deliver(dest, aRequest, aResponse, articleData, null, emailAnArticleTemplate, mail_language);
}
- catch (Throwable e) {
- throw new ServletModuleFailure("Couldn't get content for article " + aid + mail_language + ": " + e.getMessage(), e);
+ finally {
+ dest.close();
}
+ theEmailText = theEMailTextWriter.toString();
+ MirGlobal.mruCache().storeObject(theCacheKey, theEmailText);
}
String content = theEmailText;
-
// add some headers
content = "To: " + to + "\nReply-To: "+ from + "\nX-Originating-IP: "+ from_ip + "\n" + content;
// put in the comment where it should go
@@ -650,7 +328,7 @@ public class ServletModuleOpenIndy extends ServletModule
SMTPClient client=new SMTPClient();
try {
int reply;
- client.connect(configuration.getString("ServletModule.OpenIndy.SMTPServer"));
+ client.connect(getConfiguration().getString("ServletModule.OpenIndy.SMTPServer"));
reply = client.getReplyCode();
@@ -659,11 +337,11 @@ public class ServletModuleOpenIndy extends ServletModule
throw new ServletModuleExc("SMTP server refused connection.");
}
- client.sendSimpleMessage(configuration.getString("ServletModule.OpenIndy.EmailIsFrom"), to, content);
+ client.sendSimpleMessage(getConfiguration().getString("ServletModule.OpenIndy.EmailIsFrom"), to, content);
client.disconnect();
//mission accomplished
- deliver(req, res, mergeData, null, sentMailTemplate);
+ deliver(aRequest, aResponse, mergeData, null, sentMailTemplate);
}
catch(IOException e) {
if(client.isConnected()) {
@@ -731,7 +409,7 @@ public class ServletModuleOpenIndy extends ServletModule
mergeData.put("topics", DatabaseTopics.getInstance().getPopupData());
}
catch (Throwable e) {
- logger.debug("Can't get topics: " + e.toString());
+ getLogger().debug("Can't get topics: " + e.toString());
}
String searchBackValue = req.getParameter("search_back");
@@ -758,7 +436,7 @@ public class ServletModuleOpenIndy extends ServletModule
session.setAttribute("positionInResults", new Integer(newPosition));
}
else {
- File indexFile = FileRoutines.getAbsoluteOrRelativeFile(configuration.getHome(), configuration.getString("IndexPath"));
+ File indexFile = FileRoutines.getAbsoluteOrRelativeFile(getConfiguration().getHome(), getConfiguration().getString("IndexPath"));
String creatorFragment = creatorTerm.makeTerm(req);
if (creatorFragment != null) {
@@ -769,7 +447,7 @@ public class ServletModuleOpenIndy extends ServletModule
// the contentTerm uses param "search_boolean" to combine its terms
String contentFragment = contentTerm.makeTerm(req);
if (contentFragment != null) {
- logger.debug("contentFragment: " + contentFragment);
+ getLogger().debug("contentFragment: " + contentFragment);
queryString = queryString + " +" + contentFragment;
}
@@ -804,22 +482,22 @@ public class ServletModuleOpenIndy extends ServletModule
else {
try {
Searcher searcher = null;
-
+
try {
searcher = new IndexSearcher(FSDirectory.getDirectory(indexFile,false));
}
catch (IOException e) {
- logger.debug("Can't open indexPath: " + indexFile.getAbsolutePath());
+ getLogger().debug("Can't open indexPath: " + indexFile.getAbsolutePath());
throw new ServletModuleExc("Problem with Search Index! : " + e.toString());
}
- Query query = null;
+ Query query;
try {
query = QueryParser.parse(queryString, "content", new StandardAnalyzer());
}
catch (Exception e) {
searcher.close();
- logger.debug("Query don't parse: " + queryString);
+ getLogger().debug("Query don't parse: " + queryString);
throw new ServletModuleExc("Problem with Query String! (was '" + queryString + "')");
}
@@ -829,7 +507,7 @@ public class ServletModuleOpenIndy extends ServletModule
}
catch (IOException e) {
searcher.close();
- logger.debug("Can't get hits: " + e.toString());
+ getLogger().debug("Can't get hits: " + e.toString());
throw new ServletModuleExc("Problem getting hits!");
}
@@ -889,7 +567,7 @@ public class ServletModuleOpenIndy extends ServletModule
searcher.close();
}
catch (IOException e) {
- logger.debug("Can't close searcher: " + e.toString());
+ getLogger().debug("Can't close searcher: " + e.toString());
throw new ServletModuleFailure("Problem closing searcher(normal):" + e.getMessage(), e);
}
@@ -903,7 +581,7 @@ public class ServletModuleOpenIndy extends ServletModule
}
catch (IOException e) {
- logger.debug("Can't close searcher: " + e.toString());
+ getLogger().debug("Can't close searcher: " + e.toString());
throw new ServletModuleFailure("Problem closing searcher: " + e.getMessage(), e);
}
}
@@ -956,7 +634,7 @@ public class ServletModuleOpenIndy extends ServletModule
}
}
catch (Throwable e) {
- logger.error("Can't iterate over hits: " + e.toString());
+ getLogger().error("Can't iterate over hits: " + e.toString());
throw new ServletModuleFailure("Problem getting hits: " + e.getMessage(), e);
}
@@ -976,17 +654,17 @@ public class ServletModuleOpenIndy extends ServletModule
public void getpdf(HttpServletRequest req, HttpServletResponse res)
throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
+
long starttime = System.currentTimeMillis();
+
String ID_REQUEST_PARAM = "id";
int maxArticlesInNewsleter = 15; // it is nice not to be dos'ed
try {
String idParam = req.getParameter(ID_REQUEST_PARAM);
if (idParam != null) {
-
RE re = new RE("[0-9]+");
REMatch[] idMatches = re.getAllMatches(idParam);
-
String cacheSelector = "";
for (int i = 0; i < idMatches.length; i++) {
@@ -1000,11 +678,11 @@ public class ServletModuleOpenIndy extends ServletModule
byte[] thePDF;
if (MirGlobal.mruCache().hasObject(theCacheKey)) {
- logger.info("fetching pdf from cache");
+ getLogger().debug("fetching pdf from cache");
thePDF = (byte[]) MirGlobal.mruCache().getObject(theCacheKey);
}
else {
- logger.info("generating pdf and caching it");
+ getLogger().debug("generating pdf and caching it");
ByteArrayOutputStream out = new ByteArrayOutputStream();
PDFGenerator pdfMaker = new PDFGenerator(out);
@@ -1014,6 +692,8 @@ public class ServletModuleOpenIndy extends ServletModule
REMatch aMatch = idMatches[i];
String id = aMatch.toString();
EntityContent contentEnt = (EntityContent) contentModule.getById(id);
+
+
pdfMaker.addIndexItem(contentEnt);
}
}
@@ -1021,9 +701,13 @@ public class ServletModuleOpenIndy extends ServletModule
for (int i = 0; i < idMatches.length; i++) {
REMatch aMatch = idMatches[i];
String id = aMatch.toString();
- EntityContent contentEnt = (EntityContent) contentModule.getById(id);
+ EntityContent article = (EntityContent) contentModule.getById(id);
+
+ if (!MirGlobal.localizer().openPostings().allowArticlePublication(article)) {
+ throw new ServletModuleExc("Illegal article");
+ }
- pdfMaker.add(contentEnt);
+ pdfMaker.add(article);
}
pdfMaker.stop();
@@ -1038,7 +722,7 @@ public class ServletModuleOpenIndy extends ServletModule
res.getOutputStream().write(thePDF);
res.getOutputStream().flush();
String elapsedtime = (new Long(System.currentTimeMillis() - starttime)).toString();
- logger.info("pdf retireval took " + elapsedtime + " milliseconds");
+ getLogger().info("pdf retireval took " + elapsedtime + " milliseconds");
}
else {
@@ -1046,7 +730,8 @@ public class ServletModuleOpenIndy extends ServletModule
}
}
catch (Throwable t) {
- logger.error(t.toString());
+ getLogger().error(t.toString());
+
throw new ServletModuleFailure(t);
}
}
@@ -1085,12 +770,12 @@ public class ServletModuleOpenIndy extends ServletModule
Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
- generator.generate(anOutputWriter, responseData, logger);
+ generator.generate(anOutputWriter, responseData, getLogger());
anOutputWriter.close();
}
catch (Throwable e) {
- logger.error("Error while generating " + aGenerator + ": " + e.getMessage());
+ getLogger().error("Error while generating " + aGenerator + ": " + e.getMessage());
throw new ServletModuleFailure(e);
}
@@ -1105,12 +790,12 @@ public class ServletModuleOpenIndy extends ServletModule
Generator generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
- generator.generate(anOutputWriter, responseData, logger);
+ generator.generate(anOutputWriter, responseData, getLogger());
anOutputWriter.close();
}
catch (Throwable e) {
- logger.error("Error while generating " + aGenerator + ": " + e.getMessage());
+ getLogger().error("Error while generating " + aGenerator + ": " + e.getMessage());
throw new ServletModuleFailure(e);
}
@@ -1119,13 +804,13 @@ public class ServletModuleOpenIndy extends ServletModule
public void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) {
try {
- logger.error("Error during open action", anException);
+ getLogger().error("Error during open action", anException);
Map data = new HashMap();
data.put("errorstring", anException.getMessage());
data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));
- deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.ErrorTemplate"));
+ deliver(out, aRequest, aResponse, data, null, getConfiguration().getString("ServletModule.OpenIndy.ErrorTemplate"));
}
catch (Throwable e) {
throw new ServletModuleFailure(e);
@@ -1135,7 +820,7 @@ public class ServletModuleOpenIndy extends ServletModule
public void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse,
PrintWriter out, ServletModuleUserExc anException) {
try {
- logger.warn("user error: " + anException.getMessage());
+ getLogger().warn("user error: " + anException.getMessage());
Map data = new HashMap();
Bundle bundle =
@@ -1144,7 +829,7 @@ public class ServletModuleOpenIndy extends ServletModule
data.put("errorstring", bundle.getValue(anException.getMessage(), Arrays.asList(anException.getParameters())));
data.put("date", StringUtil.date2readableDateTime(new GregorianCalendar()));
- deliver(out, aRequest, aResponse, data, null, configuration.getString("ServletModule.OpenIndy.UserErrorTemplate"));
+ deliver(out, aRequest, aResponse, data, null, getConfiguration().getString("ServletModule.OpenIndy.UserErrorTemplate"));
}
catch (Throwable e) {
throw new ServletModuleFailure(e);
diff --git a/source/mircoders/servlet/ServletModuleOtherMedia.java b/source/mircoders/servlet/ServletModuleOtherMedia.java
index d447c098..6a65fca7 100755
--- a/source/mircoders/servlet/ServletModuleOtherMedia.java
+++ b/source/mircoders/servlet/ServletModuleOtherMedia.java
@@ -30,40 +30,19 @@
package mircoders.servlet;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
import mircoders.module.ModuleUploadedMedia;
import mircoders.storage.DatabaseOther;
/**
- *
- * Title:
- *Description:
- *Copyright: Copyright (c) 2003
- *Company:
- * @author the mir coders - * @version 1.0 + * Admin ServletModule to manage "other" (i.e. non-audio, video or image) media uploads */ public class ServletModuleOtherMedia extends ServletModuleUploadedMedia { - private static ServletModuleOtherMedia instance = new ServletModuleOtherMedia(); - - public static ServletModule getInstance() { - return instance; - } - - private ServletModuleOtherMedia() { - super(); - logger = new LoggerWrapper("ServletModule.OtherMedia"); - moduleName = "OtherMedia"; + public ServletModuleOtherMedia() { + super("OtherMedia"); - try { - definition = "otherMedia"; - mainModule = new ModuleUploadedMedia(DatabaseOther.getInstance()); - } - catch (Throwable e) { - logger.error("servletmodule otherMedia could not be initialized: " + e.getMessage()); - } + definition = "otherMedia"; + mainModule = new ModuleUploadedMedia(DatabaseOther.getInstance()); } } diff --git a/source/mircoders/servlet/ServletModuleProducer.java b/source/mircoders/servlet/ServletModuleProducer.java index c5b02dc3..3d76981c 100755 --- a/source/mircoders/servlet/ServletModuleProducer.java +++ b/source/mircoders/servlet/ServletModuleProducer.java @@ -29,6 +29,15 @@ */ package mircoders.servlet; +import mir.generator.Generator; +import mir.producer.ProducerFactory; +import mir.servlet.AdminServletModule; +import mir.servlet.ServletModuleFailure; +import mir.util.HTTPRequestParser; +import mircoders.global.MirGlobal; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; @@ -38,30 +47,9 @@ import java.util.List; import java.util.Locale; import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import mir.generator.Generator; -import mir.log.LoggerWrapper; -import mir.producer.ProducerFactory; -import mir.servlet.ServletModule; -import mir.servlet.ServletModuleFailure; -import mir.util.HTTPRequestParser; -import mircoders.global.MirGlobal; - -public class ServletModuleProducer extends ServletModule -{ - private static ServletModuleProducer instance = new ServletModuleProducer(); - public static ServletModule getInstance() { return instance; } - - Object comments; - int totalNrComments; - - - private ServletModuleProducer() { - super(); - logger = new LoggerWrapper("ServletModule.Producer"); - defaultAction="showProducerQueueStatus"; +public class ServletModuleProducer extends AdminServletModule { + public void defaultAction(HttpServletRequest aRequest, HttpServletResponse aResponse) { + showProducerQueueStatus(aRequest, aResponse); } /** @@ -70,18 +58,14 @@ public class ServletModuleProducer extends ServletModule * @param aResponse */ public void showProducerQueueStatus(HttpServletRequest aRequest, HttpServletResponse aResponse) { - Map generationData; - Generator generator; - List producersData; - try { // TODO: use ServletHelper - generator = MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator("producerqueue.template"); + Generator generator = MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator("producerqueue.template"); - generationData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); + Map generationData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); generationData.put( "thisurl", "module=Producer&do=showProducerQueueStatus"); - producersData = new ArrayList(); + List producersData = new ArrayList(); Iterator i = MirGlobal.getProducerEngine().getFactories().iterator(); while (i.hasNext()) { ProducerFactory factory = (ProducerFactory) i.next(); @@ -106,7 +90,7 @@ public class ServletModuleProducer extends ServletModule generationData.put("producers", producersData); generationData.put("queue", MirGlobal.getProducerEngine().getQueueStatus()); - generator.generate(aResponse.getWriter(), generationData, logger); + generator.generate(aResponse.getWriter(), generationData, getLogger()); } catch (Throwable t) { throw new ServletModuleFailure(t); @@ -118,25 +102,28 @@ public class ServletModuleProducer extends ServletModule * The output therefore is very simple. */ public void produce(HttpServletRequest aRequest, HttpServletResponse aResponse) { + PrintWriter out; try { - PrintWriter out = aResponse.getWriter(); - - if (aRequest.getParameter("producer")!=null) { - String producerParam = aRequest.getParameter("producer"); - String verbParam = aRequest.getParameter("verb"); - - try { - MirGlobal.getProducerEngine().addJob(producerParam, verbParam); - out.println("job added"); - } - catch (Throwable t) { - out.println("Can't add job: " + t.getMessage()); - } - } + out = aResponse.getWriter(); } catch (IOException e) { throw new ServletModuleFailure(e); } + + if (aRequest.getParameter("producer")!=null) { + String producerParam = aRequest.getParameter("producer"); + String verbParam = aRequest.getParameter("verb"); + + try { + MirGlobal.getProducerEngine().addJob(producerParam, verbParam); + + out.println("job added"); + } + catch (Throwable t) { + + out.println("Can't add job: " + t.getMessage()); + } + } } /** diff --git a/source/mircoders/servlet/ServletModuleTopics.java b/source/mircoders/servlet/ServletModuleTopics.java index e7700d0e..4b1fa1b6 100755 --- a/source/mircoders/servlet/ServletModuleTopics.java +++ b/source/mircoders/servlet/ServletModuleTopics.java @@ -30,29 +30,15 @@ package mircoders.servlet; -import mir.log.LoggerWrapper; -import mir.servlet.ServletModule; +import mir.servlet.AdminServletModule; import mircoders.module.ModuleTopics; /** - * + * Admin ServletModule for managing topics */ - -public class ServletModuleTopics extends ServletModule -{ - private static ServletModuleTopics instance = new ServletModuleTopics(); - public static ServletModule getInstance() { return instance; } - - private ServletModuleTopics() { - super(); - logger = new LoggerWrapper("ServletModule.Topics"); - - try { - definition = "topic"; - mainModule = new ModuleTopics(); - } - catch (Throwable e) { - logger.error("Initialization of ServletModuleTopics failed!: " + e.getMessage()); - } +public class ServletModuleTopics extends AdminServletModule { + public ServletModuleTopics() { + definition = "topic"; + mainModule = new ModuleTopics(); } } \ No newline at end of file diff --git a/source/mircoders/servlet/ServletModuleUploadedMedia.java b/source/mircoders/servlet/ServletModuleUploadedMedia.java index d40eb376..87c321c3 100755 --- a/source/mircoders/servlet/ServletModuleUploadedMedia.java +++ b/source/mircoders/servlet/ServletModuleUploadedMedia.java @@ -34,14 +34,19 @@ import mir.config.MirPropertiesConfiguration; import mir.entity.Entity; import mir.entity.adapter.EntityAdapter; import mir.entity.adapter.EntityAdapterEngine; -import mir.log.LoggerWrapper; import mir.media.MediaHandler; -import mir.servlet.ServletModule; +import mir.servlet.AdminServletModule; import mir.servlet.ServletModuleExc; import mir.servlet.ServletModuleFailure; import mir.servlet.ServletModuleUserExc; import mir.session.UploadedFile; -import mir.util.*; +import mir.session.CommonsUploadedFileAdapter; +import mir.util.ExceptionRoutines; +import mir.util.HTTPParsedRequest; +import mir.util.HTTPRequestParser; +import mir.util.JDBCStringRoutines; +import mir.util.SQLQueryBuilder; +import mir.util.URLBuilder; import mircoders.entity.EntityComment; import mircoders.entity.EntityContent; import mircoders.entity.EntityUploadedMedia; @@ -57,30 +62,19 @@ import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.InputStream; -import java.util.*; - -/** - * - *Title:
- *Description:
- *Copyright: Copyright (c) 2003
- *Company:
- * @author the mir coders - * @version 1.0 - */ - -public abstract class ServletModuleUploadedMedia extends ServletModule { - protected String moduleName = "UploadedMedia"; - - public static ServletModule getInstance() { - return null; - } - - public ServletModuleUploadedMedia() { - super(); - +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +public abstract class ServletModuleUploadedMedia extends AdminServletModule { + private String moduleName; + + protected ServletModuleUploadedMedia(String aModuleName) { + moduleName = aModuleName; definition = "uploadedMedia"; - logger = new LoggerWrapper("ServletModule.UploadedMedia"); } public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse) @@ -88,9 +82,9 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { try { HTTPParsedRequest parsedRequest = new HTTPParsedRequest(aRequest, - configuration.getString("Mir.DefaultEncoding"), - configuration.getInt("MaxMediaUploadSize")*1024, - configuration.getString("TempDir")); + getConfiguration().getString("Mir.DefaultEncoding"), + getConfiguration().getInt("MaxMediaUploadSize")*1024, + getConfiguration().getString("TempDir")); Map mediaValues = new HashMap(); @@ -108,7 +102,7 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { i = parsedRequest.getFiles().iterator(); while (i.hasNext()) { - UploadedFile file = new mir.session.CommonsUploadedFileAdapter((FileItem) i.next()); + UploadedFile file = new CommonsUploadedFileAdapter((FileItem) i.next()); String suffix = file.getFieldName().substring(5); mediaValues.put("title", parsedRequest.getParameter("media_title" + suffix)); @@ -120,19 +114,19 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { String commentid = parsedRequest.getParameter("commentid"); if (articleid!=null) { - EntityContent entContent = (EntityContent) DatabaseContent.getInstance().selectById(articleid); + EntityContent entContent = (EntityContent) + DatabaseContent.getInstance().selectById(articleid); i = mediaList.iterator(); while (i.hasNext()) { - String id = ((EntityUploadedMedia) i.next()).getId(); + String id = ((Entity) i.next()).getId(); entContent.attach(id); logAdminUsage(aRequest, id, "object attached to article " + articleid); } - (ServletModuleContent.getInstance()).editObject(aRequest, aResponse, articleid); - + ServletHelper.redirect(aResponse, "module=content&do=edit&id=" + articleid); return; } @@ -150,7 +144,7 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { logAdminUsage(aRequest, id, "object attached to comment " + commentid); } - (ServletModuleComment.getInstance()).editObject(aRequest, aResponse, commentid); + ServletHelper.redirect(aResponse, "module=comment&do=edit&id=" + commentid); return; } @@ -173,26 +167,29 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { try { HTTPParsedRequest parsedRequest = new HTTPParsedRequest(aRequest, - configuration.getString("Mir.DefaultEncoding"), - configuration.getInt("MaxMediaUploadSize")*1024, - configuration.getString("TempDir")); + getConfiguration().getString("Mir.DefaultEncoding"), + getConfiguration().getInt("MaxMediaUploadSize")*1024, + getConfiguration().getString("TempDir")); + Map mediaValues = new HashMap(); Iterator i = mainModule.getStorageObject().getFieldNames().iterator(); while (i.hasNext()) { String field = (String) i.next(); String value = parsedRequest.getParameter(field); - if (value!=null) + if (value!=null) { mediaValues.put(field, value); + } } mediaValues.put("to_publisher", ServletHelper.getUser(aRequest).getId()); mediaValues.put("is_produced", "0"); - if (!mediaValues.containsKey("is_published")) + if (!mediaValues.containsKey("is_published")) { mediaValues.put("is_published", "0"); + } String id = mainModule.set(mediaValues); - logger.debug("update: media ID = " + id); + getLogger().debug("update: media ID = " + id); logAdminUsage(aRequest, id, "object modified"); editUploadedMediaObject(id, aRequest, aResponse); @@ -248,7 +245,7 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { try { List list = - EntityAdapterEngine.retrieveAdapterList(model, definition, aWhereClause, anOrderByClause, nrEntitiesPerListPage, anOffset); + EntityAdapterEngine.retrieveAdapterList(getModel(), definition, aWhereClause, anOrderByClause, nrEntitiesPerListPage, anOffset); urlBuilder.setValue("module", moduleName); urlBuilder.setValue("do", "list"); @@ -337,7 +334,7 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)}); int nrMedia = requestParser.getIntegerWithDefault("nrmedia", 1); - int maxNrMedia=configuration.getInt("ServletModule.OpenIndy.MaxMediaUploadItems", 20); + int maxNrMedia = getConfiguration().getInt("ServletModule.OpenIndy.MaxMediaUploadItems", 20); List fields = mainModule.getStorageObject().getFieldNames(); Map media = new HashMap(); @@ -382,11 +379,11 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { } private void editUploadedMediaObject(String idParam, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { - if (idParam != null && !idParam.equals("")) { + if (idParam != null && !"".equals(idParam)) { try { Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)}); EntityAdapter object = - model.makeEntityAdapter(definition, mainModule.getById(idParam)); + getModel().makeEntityAdapter(definition, mainModule.getById(idParam)); HTTPRequestParser requestParser = new HTTPRequestParser(aRequest); responseData.put("uploadedmedia", object); responseData.put("new", Boolean.FALSE); @@ -442,7 +439,9 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { throw new ServletModuleFailure(e); } } - else logger.error("id not specified."); + else { + getLogger().error("id not specified."); + } // no exception allowed } @@ -489,15 +488,18 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { } } catch (Throwable e) { - logger.error("getIcon: " + e.toString()); + getLogger().error("getIcon: " + e.toString()); } } - else logger.error("getIcon: id not specified."); + else { + getLogger().error("getIcon: id not specified."); + } } protected void addExtraData(Map aTarget) throws ServletModuleExc, ServletModuleFailure { try { - aTarget.put("mediafolders", EntityAdapterEngine.retrieveAdapterList(model, "mediaFolder", "", "", -1, 0)); + aTarget.put("mediafolders", + EntityAdapterEngine.retrieveAdapterList(getModel(), "mediaFolder", "", "", -1, 0)); } catch (Throwable t) { throw new ServletModuleFailure(t); @@ -509,7 +511,7 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { if (idParam!=null && !idParam.equals("")) { try { // TODO rewrite as relational sql - ServletModuleContent.getInstance().returnList( + ServletHelper.getServletModuleContent().returnList( aRequest, aResponse, "exists (select * from content_x_media where content_id=content.id and media_id='" + @@ -519,7 +521,9 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { throw new ServletModuleFailure(t); } } - else logger.error("showarticles: id not specified."); + else { + getLogger().error("showarticles: id not specified."); + } } public void showcomments(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc @@ -528,7 +532,7 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { if (idParam!=null && !idParam.equals("")) { try { // TODO rewrite as relational sql - ServletModuleComment.getInstance().returnList( + ServletHelper.getServletModuleComment().returnList( aRequest, aResponse, "exists (select * from comment_x_media where comment_id=comment.id and media_id='" + JDBCStringRoutines.escapeStringLiteral( idParam ) + "')", "", 0); @@ -537,6 +541,8 @@ public abstract class ServletModuleUploadedMedia extends ServletModule { throw new ServletModuleFailure(t); } } - else logger.error("showcomments: id not specified."); + else { + getLogger().error("showcomments: id not specified."); + } } } \ No newline at end of file diff --git a/source/mircoders/servlet/ServletModuleUsers.java b/source/mircoders/servlet/ServletModuleUsers.java index 4d29ed4f..6191551a 100755 --- a/source/mircoders/servlet/ServletModuleUsers.java +++ b/source/mircoders/servlet/ServletModuleUsers.java @@ -32,8 +32,7 @@ package mircoders.servlet; import mir.entity.adapter.EntityAdapterEngine; import mir.entity.adapter.EntityAdapterModel; -import mir.log.LoggerWrapper; -import mir.servlet.ServletModule; +import mir.servlet.AdminServletModule; import mir.servlet.ServletModuleExc; import mir.servlet.ServletModuleFailure; import mir.servlet.ServletModuleUserExc; @@ -46,38 +45,30 @@ import mircoders.storage.DatabaseUsers; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.util.*; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; /** * * */ -public class ServletModuleUsers extends ServletModule -{ - private static ServletModuleUsers instance = new ServletModuleUsers(); - public static ServletModule getInstance() { return instance; } - protected ModuleUsers usersModule; +public class ServletModuleUsers extends AdminServletModule { + protected ModuleUsers usersModule = new ModuleUsers(); - private ServletModuleUsers() { - super(); - logger = new LoggerWrapper("ServletModule.Users"); - - try { - definition = "user"; - usersModule = new ModuleUsers(); - mainModule = usersModule; - } - catch (Throwable e) { - logger.debug("initialization of ServletModuleUsers failed!: " + e.getMessage()); - } + public ServletModuleUsers() { + definition = "user"; + mainModule = usersModule; } - public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc - { + public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc { String idParam = aRequest.getParameter("id"); - if (idParam == null) + if (idParam == null) { throw new ServletModuleExc("ServletModuleUser.edit: invalid call: (id) not specified"); + } try { EntityUsers user = (EntityUsers) mainModule.getById(idParam); @@ -247,7 +238,8 @@ public class ServletModuleUsers extends ServletModule Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}); List list = - EntityAdapterEngine.retrieveAdapterList(model, definition, "", "login", nrEntitiesPerListPage, anOffset); + EntityAdapterEngine.retrieveAdapterList(getModel(), definition, + "", "login", nrEntitiesPerListPage, anOffset); responseData.put("nexturl", null); responseData.put("prevurl", null); @@ -256,11 +248,11 @@ public class ServletModuleUsers extends ServletModule urlBuilder.setValue("do", "list"); urlBuilder.setValue("offset", anOffset); - responseData.put("offset" , new Integer(anOffset).toString()); + responseData.put("offset" , Integer.toString(anOffset)); responseData.put("thisurl" , urlBuilder.getQuery()); if (list.size()>=nrEntitiesPerListPage) { - urlBuilder.setValue("offset", (anOffset + nrEntitiesPerListPage)); + urlBuilder.setValue("offset", anOffset + nrEntitiesPerListPage); responseData.put("nexturl" , urlBuilder.getQuery()); } diff --git a/source/mircoders/servlet/ServletModuleVideo.java b/source/mircoders/servlet/ServletModuleVideo.java index 5344273b..bd95b01c 100755 --- a/source/mircoders/servlet/ServletModuleVideo.java +++ b/source/mircoders/servlet/ServletModuleVideo.java @@ -30,40 +30,18 @@ package mircoders.servlet; -import mir.log.LoggerWrapper; -import mir.servlet.ServletModule; import mircoders.module.ModuleUploadedMedia; import mircoders.storage.DatabaseVideo; /** - * - *Title:
- *Description:
- *Copyright: Copyright (c) 2003
- *Company:
- * @author not attributable - * @version 1.0 + * Admin ServletModule for managing video uploads */ public class ServletModuleVideo extends ServletModuleUploadedMedia { - private static ServletModuleVideo instance = new ServletModuleVideo(); - - public static ServletModule getInstance() { - return instance; - } - private ServletModuleVideo() { - super(); - logger = new LoggerWrapper("ServletModule.Video"); - - moduleName = "Video"; + super("Video"); - try { - definition = "video"; - mainModule = new ModuleUploadedMedia(DatabaseVideo.getInstance()); - } - catch (Throwable e) { - logger.error("servletmodule video could not be initialized: " + e.getMessage()); - } + definition = "video"; + mainModule = new ModuleUploadedMedia(DatabaseVideo.getInstance()); } } \ No newline at end of file -- 2.11.0