List of usage examples for javax.servlet ServletContext getRealPath
public String getRealPath(String path);
From source file:nl.strohalm.cyclos.utils.WebImageHelper.java
/** * Return the real path for thumbnails of a given image nature *//*from ww w .j a v a 2 s . c o m*/ public static File thumbnailPath(final Image.Nature nature, final ServletContext context) { String path = null; switch (nature) { case SYSTEM: path = WebImageHelper.SYSTEM_THUMBNAILS_PATH; break; case CUSTOM: path = WebImageHelper.CUSTOM_THUMBNAILS_PATH; break; case STYLE: path = WebImageHelper.STYLE_THUMBNAILS_PATH; break; default: return null; } return new File(context.getRealPath(path)); }
From source file:org.jahia.tools.patches.GroovyPatcher.java
private static File getPatchesFolder(ServletContext ctx) { String varFolder = System.getProperty("jahiaVarDiskPath"); if (varFolder == null) { varFolder = SettingsBean.getInstance() != null ? SettingsBean.getInstance().getJahiaVarDiskPath() : null;/* www . jav a2 s .c o m*/ } if (varFolder == null) { varFolder = ctx.getRealPath("WEB-INF/var"); } File lookupFolder = new File(varFolder, "patches" + File.separator + "groovy"); return lookupFolder.isDirectory() ? lookupFolder : null; }
From source file:org.apache.velocity.tools.view.servlet.ServletToolboxManager.java
/** * ServletToolboxManager factory method. * This method will ensure there is exactly one ServletToolboxManager * per xml toolbox configuration file./*from w w w.j a va 2 s . c o m*/ */ public static synchronized ServletToolboxManager getInstance(ServletContext servletContext, String toolboxFile) { // little fix up if (!toolboxFile.startsWith("/")) { toolboxFile = "/" + toolboxFile; } // get config file pathname String pathname = servletContext.getRealPath(toolboxFile); // check if a previous instance exists ServletToolboxManager toolboxManager = (ServletToolboxManager) managersMap.get(pathname); if (toolboxManager == null) { // if not, build one InputStream is = null; try { // get the bits is = servletContext.getResourceAsStream(toolboxFile); if (is != null) { LOG.info("Using config file '" + toolboxFile + "'"); toolboxManager = new ServletToolboxManager(servletContext); toolboxManager.load(is); // remember it managersMap.put(pathname, toolboxManager); LOG.info("Toolbox setup complete."); } } catch (Exception e) { LOG.error("Problem loading toolbox '" + toolboxFile + "' : " + e); // if this happens, it probably deserves // to have the stack trace logged StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); LOG.error(sw.toString()); } finally { try { if (is != null) { is.close(); } } catch (Exception ee) { } } } return toolboxManager; }
From source file:gov.utah.dts.det.ccl.actions.facility.information.license.reports.LicenseCertificate.java
private static void writePdf(License license, ByteArrayOutputStream ba, HttpServletRequest request) throws DocumentException, BadElementException { SimpleDateFormat df = new SimpleDateFormat("MMMM d, yyyy"); StringBuilder sb;//from w w w. jav a 2s .c om // Retrieve the certificate template to use as watermark ServletContext context = request.getSession().getServletContext(); String templatefile = context.getRealPath("/resources") + "/LicenseCertificateTemplate.pdf"; PdfReader reader = getTemplateReader(templatefile); if (reader != null && reader.getNumberOfPages() > 0) { Phrase phrase; // Create new document using the page size of the certificate template document Document document = new Document(reader.getPageSizeWithRotation(1), 0, 0, 0, 0); PdfWriter writer = PdfWriter.getInstance(document, ba); document.open(); // Get the writer under content byte for placing of watermark PdfContentByte under = writer.getDirectContentUnder(); PdfContentByte over = writer.getDirectContent(); // Retrieve the first page of the template document and wrap as an Image to use as new document watermark PdfImportedPage page = writer.getImportedPage(reader, 1); Image img = Image.getInstance(page); // Make sure the image has an absolute page position if (!img.hasAbsoluteX() || !img.hasAbsoluteY()) { img.setAbsolutePosition(0, 0); } under.addImage(img); /* * THE FOLLOWING TWO FUNCTION CALLS DISPLAY THE PAGE MARGINS AND TEXT COLUMN BORDERS FOR DEBUGGING TEXT PLACEMENT. * UNCOMMENT EACH FUNCTION CALL TO HAVE BORDERS DISPLAYED ON THE OUTPUT DOCUMENT. THIS WILL HELP WHEN YOU NEED * TO SEE WHERE TEXT WILL BE PLACED ON THE CERTIFICATE FORM. */ // Show the page margins //showPageMarginBorders(over); // Show the text column borders //showColumnBorders(over); ColumnText ct = new ColumnText(over); ct.setLeading(fixedLeading); // Add Facility Name to column String text = license.getFacility().getName(); if (text != null) { phrase = new Phrase(text.toUpperCase(), mediumfontB); phrase.setLeading(noLeading); ct.addText(phrase); ct.addText(Chunk.NEWLINE); } // Add Facility Site to column text = license.getFacility().getSiteName(); if (text != null) { phrase = new Phrase(text.toUpperCase(), mediumfontB); phrase.setLeading(noLeading); ct.addText(phrase); ct.addText(Chunk.NEWLINE); } // Add Facility Address to column text = license.getFacility().getLocationAddress().getAddressOne(); if (text != null) { phrase = new Phrase(text.toUpperCase(), mediumfontB); phrase.setLeading(noLeading); ct.addText(phrase); ct.addText(Chunk.NEWLINE); } text = license.getFacility().getLocationAddress().getCityStateZip(); if (text != null) { phrase = new Phrase(text.toUpperCase(), mediumfontB); phrase.setLeading(noLeading); ct.addText(phrase); ct.addText(Chunk.NEWLINE); } // Write column to document ct.setAlignment(Element.ALIGN_CENTER); ct.setSimpleColumn(COLUMNS[0][0], COLUMNS[0][1], COLUMNS[0][2], COLUMNS[0][3]); ct.go(); // Add Certification Service Code to column ct = new ColumnText(over); ct.setLeading(fixedLeading); String service = ""; if (license.getSpecificServiceCode() != null && StringUtils.isNotBlank(license.getSpecificServiceCode().getValue()) && DV_TREATMENT.equalsIgnoreCase(license.getSpecificServiceCode().getValue())) { service += DOMESTIC_VIOLENCE; } if (!license.getProgramCodeIds().isEmpty()) { // redmine 25410 mentalHealthLoop: for (PickListValue pkv : license.getProgramCodeIds()) { String program = pkv.getValue(); int idx = program.indexOf(" -"); if (idx >= 0) { String code = program.substring(0, idx); if (MENTAL_HEALTH_CODES.indexOf(code + ":") >= 0) { if (service.length() > 0) { service += " / "; } service += MENTAL_HEALTH; break mentalHealthLoop; } } } substanceAbuseLoop: for (PickListValue pkv : license.getProgramCodeIds()) { String program = pkv.getValue(); int idx = program.indexOf(" -"); if (idx >= 0) { String code = program.substring(0, idx); if (SUBSTANCE_ABUSE_CODES.indexOf(code + ":") >= 0) { if (service.length() > 0) { service += " / "; } service += SUBSTANCE_ABUSE; break substanceAbuseLoop; } } } } if (StringUtils.isNotBlank(license.getServiceCodeDesc())) { if (service.length() > 0) { service += " / "; } service += license.getServiceCodeDesc(); } if (StringUtils.isNotEmpty(service)) { phrase = new Phrase(service.toUpperCase(), mediumfont); phrase.setLeading(noLeading); ct.addText(phrase); ct.addText(Chunk.NEWLINE); } // Add CLIENTS Info to column sb = new StringBuilder("FOR "); if (license.getAgeGroup() == null || license.getAgeGroup().getValue().equalsIgnoreCase("Adult & Youth")) { // Adult & Youth if (license.getAdultTotalSlots() != null) { sb.append(license.getAdultTotalSlots().toString()); } sb.append(" ADULT AND YOUTH CLIENTS"); } else if (license.getAgeGroup().getValue().equalsIgnoreCase("Adult")) { // Adult if (license.getAdultTotalSlots() != null) { // Are male or female counts specified? sb.append(license.getAdultTotalSlots().toString()); sb.append(" ADULT"); if (license.getAdultFemaleCount() != null || license.getAdultMaleCount() != null) { // Does either the male or female count equal the total slot count? if ((license.getAdultFemaleCount() != null && license.getAdultFemaleCount().equals(license.getAdultTotalSlots()))) { sb.append(" FEMALE CLIENTS"); } else if (license.getAdultMaleCount() != null && license.getAdultMaleCount().equals(license.getAdultTotalSlots())) { sb.append(" MALE CLIENTS"); } else { sb.append(" CLIENTS, "); if (license.getAdultMaleCount() != null) { sb.append(license.getAdultMaleCount().toString() + " MALE"); } if (license.getAdultFemaleCount() != null) { if (license.getAdultMaleCount() != null) { sb.append(" AND "); } sb.append(license.getAdultFemaleCount().toString() + " FEMALE"); } if (license.getFromAge() != null || license.getToAge() != null) { sb.append(","); } } } else { sb.append(" CLIENTS"); } } else { sb.append(" ADULT CLIENTS"); } } else { // Youth if (license.getYouthTotalSlots() != null) { // Are male or female counts specified? sb.append(license.getYouthTotalSlots().toString()); sb.append(" YOUTH"); if (license.getYouthFemaleCount() != null || license.getYouthMaleCount() != null) { // Does either the male or female count equal the total slot count? if ((license.getYouthFemaleCount() != null && license.getYouthFemaleCount().equals(license.getYouthTotalSlots()))) { sb.append(" FEMALE CLIENTS"); } else if (license.getYouthMaleCount() != null && license.getYouthMaleCount().equals(license.getYouthTotalSlots())) { sb.append(" MALE CLIENTS"); } else { sb.append(" CLIENTS, "); if (license.getYouthMaleCount() != null) { sb.append(license.getYouthMaleCount().toString() + " MALE"); } if (license.getYouthFemaleCount() != null) { if (license.getYouthMaleCount() != null) { sb.append(" AND "); } sb.append(license.getYouthFemaleCount().toString() + " FEMALE"); } if (license.getFromAge() != null || license.getToAge() != null) { sb.append(","); } } } else { sb.append(" CLIENTS"); } } else { sb.append(" YOUTH CLIENTS"); } } if (license.getFromAge() != null || license.getToAge() != null) { sb.append(" AGES "); if (license.getFromAge() != null) { sb.append(license.getFromAge().toString()); if (license.getToAge() != null) { sb.append(" TO " + license.getToAge().toString()); } else { sb.append(" AND OLDER"); } } else { sb.append("TO " + license.getToAge().toString()); } } phrase = new Phrase(sb.toString(), mediumfont); phrase.setLeading(noLeading); ct.addText(phrase); ct.addText(Chunk.NEWLINE); // Add Certificate Comments if (StringUtils.isNotBlank(license.getCertificateComment())) { phrase = new Phrase(license.getCertificateComment().toUpperCase(), mediumfont); phrase.setLeading(noLeading); ct.addText(phrase); } // Write column to document ct.setAlignment(Element.ALIGN_CENTER); ct.setSimpleColumn(COLUMNS[1][0], COLUMNS[1][1], COLUMNS[1][2], COLUMNS[1][3]); ct.go(); // Add Certificate Start Date if (license.getStartDate() != null) { phrase = new Phrase(df.format(license.getStartDate()), mediumfont); phrase.setLeading(noLeading); ct = new ColumnText(over); ct.setSimpleColumn(phrase, COLUMNS[2][0], COLUMNS[2][1], COLUMNS[2][2], COLUMNS[2][3], fixedLeading, Element.ALIGN_RIGHT); ct.go(); } // Add Certificate End Date if (license.getEndDate() != null) { phrase = new Phrase(df.format(license.getEndDate()), mediumfont); phrase.setLeading(noLeading); ct = new ColumnText(over); ct.setSimpleColumn(phrase, COLUMNS[3][0], COLUMNS[3][1], COLUMNS[3][2], COLUMNS[3][3], fixedLeading, Element.ALIGN_LEFT); ct.go(); } // Add License Number if (license.getLicenseNumber() != null) { phrase = new Phrase(license.getLicenseNumber().toString(), largefontB); phrase.setLeading(noLeading); ct = new ColumnText(over); ct.setSimpleColumn(phrase, COLUMNS[4][0], COLUMNS[4][1], COLUMNS[4][2], COLUMNS[4][3], numberLeading, Element.ALIGN_CENTER); ct.go(); } document.close(); } }
From source file:org.jumpmind.vaadin.ui.common.CommonUiUtils.java
public static AceEditor createAceEditor() { AceEditor editor = new AceEditor(); editor.setSizeFull();/*from w w w . jav a 2 s .c o m*/ editor.setImmediate(true); ServletContext context = VaadinServlet.getCurrent().getServletContext(); if (context.getRealPath("/ace") != null) { String acePath = context.getContextPath() + "/ace"; editor.setThemePath(acePath); editor.setModePath(acePath); editor.setWorkerPath(acePath); } else { log.warn("Could not find a local version of the ace editor. " + "You might want to consider installing the ace web artifacts at " + context.getRealPath("")); } editor.setTextChangeEventMode(TextChangeEventMode.EAGER); editor.setHighlightActiveLine(true); editor.setShowPrintMargin(false); return editor; }
From source file:com.future.pos.util.SystemInitializer.java
/** * Initialize the security groups based on<br> * physical files saved in the web server. * /*from w w w. ja v a2 s . c o m*/ * @param servletContext */ private static void initializeSecurityGroups(ServletContext servletContext) { // For every account number, there's a list of column view security. Map<Integer, List<SecurityPermission>> viewSecurityMap = new HashMap<Integer, List<SecurityPermission>>(); Map<Integer, List<SecurityPermission>> colSecuMap = new HashMap<Integer, List<SecurityPermission>>(); File dir = new File(servletContext.getRealPath(User.FILEPATH_ROLES)); File[] fileList = dir.listFiles(); // Loop through each file in the directory. for (File file : fileList) { String fileContents = Utilities.getFileContents(file); List<SecurityPermission> permissions = new ArrayList<SecurityPermission>(); List<SecurityPermission> disallowedList = new ArrayList<SecurityPermission>(); // Loop through each line in the role file. boolean isFirst = true; boolean isAllowDone = false; String accountName = ""; String[] contentsArray = fileContents.split("\n"); for (String line : contentsArray) { // If now entering disallow portion. line = line.trim(); if (line != null && line.equals("[Disallow]")) { isAllowDone = true; continue; } if (!isAllowDone) { // If the first line, initialize the account name. // Account name is declared in first line. if (isFirst) { accountName = line; isFirst = false; continue; } String tableName = line.split("=")[0]; String[] actionList = line.split("=")[1].split(","); List<Integer> actionIDList = new ArrayList<Integer>(); for (String action : actionList) { actionIDList.add(Integer.valueOf(action)); } SecurityPermission permission = new SecurityPermission(accountName, tableName, actionIDList); permissions.add(permission); } // Now is phase where system parses all disallowed columns. else { String table = line.split("=")[0]; String[] columns = line.split("=")[1].split(","); List<String> columnList = Utilities.convertArrayToList(columns); SecurityPermission disallowed = new SecurityPermission(table, columnList); disallowedList.add(disallowed); } } Integer accountType = Integer.valueOf(file.getName()); colSecuMap.put(accountType, disallowedList); viewSecurityMap.put(accountType, permissions); } setColumnSecurityMap(colSecuMap); setPermissionSecurityMap(viewSecurityMap); }
From source file:org.openmrs.web.Listener.java
/** * Load the pre-packaged modules from web/WEB-INF/bundledModules. <br> * <br>/*from www. j ava 2 s . c o m*/ * This method assumes that the api startup() and WebModuleUtil.startup() will be called later * for modules that loaded here * * @param servletContext the current servlet context for the webapp */ public static void loadBundledModules(ServletContext servletContext) { Log log = LogFactory.getLog(Listener.class); String path = servletContext.getRealPath(""); path += File.separator + "WEB-INF" + File.separator + "bundledModules"; File folder = new File(path); if (!folder.exists()) { log.warn("Bundled module folder doesn't exist: " + folder.getAbsolutePath()); return; } if (!folder.isDirectory()) { log.warn("Bundled module folder isn't really a directory: " + folder.getAbsolutePath()); return; } // loop over the modules and load the modules that we can for (File f : folder.listFiles()) { if (!f.getName().startsWith(".")) { // ignore .svn folder and the like try { Module mod = ModuleFactory.loadModule(f); log.debug("Loaded bundled module: " + mod + " successfully"); } catch (Exception e) { log.warn("Error while trying to load bundled module " + f.getName() + "", e); } } } }
From source file:com.meltmedia.cadmium.core.util.WarUtils.java
/** * Gets the currently deployed war file name from the ServletContext. * @param context/* ww w .j av a 2 s . c o m*/ * @return */ public static String getWarName(ServletContext context) { String[] pathSegments = context.getRealPath("/WEB-INF/web.xml").split("/"); String warName = pathSegments[pathSegments.length - 3]; if (!warName.endsWith(".war")) { URL webXml = WarUtils.class.getClassLoader().getResource("/cadmium-version.properties"); if (webXml != null) { String urlString = webXml.toString().substring(0, webXml.toString().length() - "/WEB-INF/classes/cadmium-version.properties".length()); File warFile = null; if (webXml.getProtocol().equalsIgnoreCase("file")) { warFile = new File(urlString.substring(5)); } else if (webXml.getProtocol().equalsIgnoreCase("vfszip")) { warFile = new File(urlString.substring(7)); } else if (webXml.getProtocol().equalsIgnoreCase("vfsfile")) { warFile = new File(urlString.substring(8)); } else if (webXml.getProtocol().equalsIgnoreCase("vfs") && System.getProperty(JBOSS_7_DEPLOY_DIR) != null) { String path = urlString.substring("vfs:/".length()); String deployDir = System.getProperty(JBOSS_7_DEPLOY_DIR); warFile = new File(deployDir, path); } if (warFile != null) { warName = warFile.getName(); } } } return warName; }
From source file:fll.web.admin.UploadSubjectiveData.java
/** * Save the data stored in file to the database and update the subjective * score totals./*from ww w. j a va2 s.c om*/ * * @param file the file to read the data from * @param connection the database connection to write to * @throws SAXException if there is an error parsing the document */ public static void saveSubjectiveData(final File file, final int currentTournament, final ChallengeDescription challengeDescription, final Connection connection, final ServletContext application) throws SQLException, IOException, ParseException, SAXException { if (LOGGER.isDebugEnabled()) { try { LOGGER.debug("Saving uploaded file to "); final String baseFilename = "subjective-upload_" + DATE_TIME_FORMAT.get().format(new Date()); final String filename = application.getRealPath("/WEB-INF/" + baseFilename); final File copy = new File(filename); FileOutputStream output = null; FileInputStream input = null; try { input = new FileInputStream(file); output = new FileOutputStream(copy); IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } catch (final IOException e) { LOGGER.debug("Error creating copy of subjective datafile", e); } } ZipFile zipfile = null; Document scoreDocument = null; try { try { zipfile = new ZipFile(file); // read in score data final ZipEntry scoreZipEntry = zipfile.getEntry("score.xml"); if (null == scoreZipEntry) { throw new RuntimeException("Zipfile does not contain score.xml as expected"); } final InputStream scoreStream = zipfile.getInputStream(scoreZipEntry); scoreDocument = XMLUtils.parseXMLDocument(scoreStream); scoreStream.close(); zipfile.close(); } catch (final ZipException ze) { LOGGER.info("Subjective upload is not a zip file, trying as an XML file"); // not a zip file, parse as just the XML file FileInputStream fis = null; try { fis = new FileInputStream(file); scoreDocument = XMLUtils.parseXMLDocument(fis); } finally { IOUtils.closeQuietly(fis); } } if (null == scoreDocument) { throw new FLLRuntimeException( "Cannot parse input as a compressed subjective data file or an uncompressed XML file"); } saveSubjectiveData(scoreDocument, currentTournament, challengeDescription, connection); } finally { if (null != zipfile) { zipfile.close(); } } }
From source file:org.jruby.rack.mock.WebUtils.java
/** * Set a system property to the web application root directory. * The key of the system property can be defined with the "webAppRootKey" * context-param in {@code web.xml}. Default is "webapp.root". * <p>Can be used for tools that support substition with {@code System.getProperty} * values, like log4j's "${key}" syntax within log file locations. * @param servletContext the servlet context of the web application * @throws IllegalStateException if the system property is already set, * or if the WAR file is not expanded/* w w w .java 2 s . c om*/ * @see #WEB_APP_ROOT_KEY_PARAM * @see #DEFAULT_WEB_APP_ROOT_KEY * @see WebAppRootListener * @see Log4jWebConfigurer */ public static void setWebAppRootSystemProperty(ServletContext servletContext) throws IllegalStateException { Assert.notNull(servletContext, "ServletContext must not be null"); String root = servletContext.getRealPath("/"); if (root == null) { throw new IllegalStateException( "Cannot set web app root system property when WAR file is not expanded"); } String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM); String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY); String oldValue = System.getProperty(key); if (oldValue != null && !StringUtils.pathEquals(oldValue, root)) { throw new IllegalStateException("Web app root system property already set to different value: '" + key + "' = [" + oldValue + "] instead of [" + root + "] - " + "Choose unique values for the 'webAppRootKey' context-param in your web.xml files!"); } System.setProperty(key, root); servletContext.log("Set web app root system property: '" + key + "' = [" + root + "]"); }