/** * This Function retrieves the number of entries in the colour lookup table for the device making * the request. If the repository contains no entry for this then the supplied default value will be * returned. If this default value is not valid, zero will be returned. */ public class DIColorIndexFunction extends ZeroMandatoryArgumentsExpressionFunction { /** Used for logging. */ private static final LogDispatcher LOGGER = LocalizationFactory.createLogger(DIColorIndexFunction.class); /** The DefaultValueProvider for this class. */ private static final DefaultValueProvider DEFAULT_VALUE_PROVIDER = new DefaultValueProvider(); // Javadoc inherited. protected DefaultValueProvider getDefaultValueProvider() { return DEFAULT_VALUE_PROVIDER; } // Javadoc inherited. protected Value execute( ExpressionContext expressionContext, DevicePolicyValueAccessor accessor, Value defaultValue) { Value value = null; ExpressionFactory factory = expressionContext.getFactory(); // determine the size of the colour palette String palette = accessor.getDependentPolicyValue(DevicePolicyConstants.PALETTE); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Size of colour palette (from repository):" + palette); } try { value = factory.createIntValue(Integer.parseInt(palette)); } catch (NumberFormatException e) { // log it but continue LOGGER.info( "function-bad-parameter-value", new Object[] {palette, DevicePolicyConstants.PALETTE}); } if (value == null) { // Verify that the default value is of the correct type if (defaultValue instanceof NumericValue) { value = defaultValue; } else { if (defaultValue != null) { // log the fact that the default was present but wrong type LOGGER.info("function-bad-default-value", "NumericValue"); } value = new SimpleIntValue(factory, 0); } } return value; } // Javadoc inherited. protected String getFunctionName() { return "cssmq-color-index"; } }
/** A property handler for mcs:cache-auto */ public class CacheAutoMetaPropertyHandler extends AbstractMetaPropertyHandler { /** Used to obtain localized messages */ private static final MessageLocalizer LOCALIZER = LocalizationFactory.createMessageLocalizer(CacheAutoMetaPropertyHandler.class); // javadoc inherited public DataType getDefaultDataType() { return StringContentProcessor.STRING_TYPE; } // javadoc inherited protected boolean hasPageScope() { return true; } // javadoc inherited protected void checkContent(final Object content, final XDIMEContextInternal context) throws XDIMEException { // check the right type if (content != null) { checkContentType(content, String.class); if (((String) content).length() != 0) { throw new XDIMEException( LOCALIZER.format( "empty-meta-content-expected", new Object[] {MetaPropertyHandlerFactory.CACHE_AUTO, content})); } } } // javadoc inherited public void process( final Object content, final XDIMEContextInternal context, final String id, final String propertyName) throws XDIMEException { // Perform default property processing. super.process(content, context, id, propertyName); // Enable caching final EnvironmentContext environmentContext = ContextInternals.getEnvironmentContext(context.getInitialRequestContext()); final ResponseCachingDirectives cachingDirectives = environmentContext.getCachingDirectives(); if (cachingDirectives != null) { cachingDirectives.enable(); } } }
public class OperationHelper { /** The logger used by this class. */ private static final LogDispatcher logger = LocalizationFactory.createLogger(OperationHelper.class); /** Geocoder host. */ private static String HOST = "http://maps.google.com/maps/geo?"; /** Key for geocoder API. */ private static String KEY = "ABQIAAAApcwDXZe7X6BilUwJbUBpaxRBOd3Ksdikbh80-kvHC15zaVzJFBRl08lXxta6N-wmA4oBk5U21engqA"; private static OperationHelper instance = null; /** For coordinates calculation. */ private GoogleCalculator calc; private OperationHelper() { this.calc = GoogleCalculatorExtended.getInstance(); } public static OperationHelper getInstance() { if (null == instance) { instance = new OperationHelper(); } return instance; } /** * Perform search in map mode. * * @param q * @return */ public String performSearchMap(String q, Integer zoom) throws GeocoderException { GImage gImage; GPoint gPoint; int zoomInt = (zoom == null) ? GoogleCalculator.INITIAL_ZOOM : zoom.intValue(); GLatLng gLatLng = doSearch(q); if (gLatLng != null) { gPoint = this.calc.fromLatLngToPixel(gLatLng, zoomInt); } else { zoomInt = GoogleCalculator.WORLD_ZOOM; gPoint = this.calc.fromLatLngToPixel(GoogleCalculator.WORLD_LAT_LNG, zoomInt); } gImage = this.calc.fromGPixelToGImage(gPoint); return getMainMapImagesList(gImage.getImgX(), gImage.getImgY(), zoomInt); } /** * Perform search in satellite mode. If no location found default world map with lang,lat (0,0) is * returned. * * @param q * @param mode * @return */ public String performSearchPhoto(String q, Integer zoom) throws GeocoderException { GGeoString geoString; GPoint gPoint; int zoomInt = (zoom == null) ? GoogleCalculator.INITIAL_ZOOM : zoom.intValue(); GLatLng gLatLng = doSearch(q); if (gLatLng != null) { gPoint = this.calc.fromLatLngToPixel(gLatLng, zoomInt); } else { zoomInt = GoogleCalculator.WORLD_ZOOM; gPoint = this.calc.fromLatLngToPixel(GoogleCalculator.WORLD_LAT_LNG, zoomInt); } GImage gImage = this.calc.fromGPixelToGImage(gPoint); gImage.setZoom(zoomInt); geoString = this.calc.fromGImageToGeoString(gImage); return getMainSatImagesList(geoString); } /** * Perform search operation, contact geocoder server, get response, parse it and return lattitude * and longitude for queried location. * * @param q * @return * @throws GeocoderException */ private GLatLng doSearch(String q) throws GeocoderException { GLatLng gLatLng = null; String result = doRequest(q, HOST, KEY); int colorIndex = result.indexOf("coordinates"); if (colorIndex != -1) { colorIndex += "coordinates".length(); int start = result.indexOf('[', colorIndex); int stop = result.indexOf(']', colorIndex); String tab = result.substring(start + 1, stop); int separator = tab.indexOf(","); double lng = new Double(tab.substring(0, separator - 1)).doubleValue(); double lat = new Double(tab.substring(separator + 1, tab.indexOf(",", separator + 1))).doubleValue(); gLatLng = new GLatLng(lat, lng); } else { logger.warn("map-location-not-found", q); } return gLatLng; } /** * Request geocoder host to get location for queried place. * * @param q * @param host * @param key * @return * @throws GeocoderException */ private String doRequest(String q, String host, String key) throws GeocoderException { URL url; URLConnection conn; String query = ""; StringBuffer buffer = new StringBuffer(); try { query = "q=" + URLEncoder.encode(q, "UTF-8") + "&output=js&key=" + URLEncoder.encode(key, "UTF-8"); } catch (UnsupportedEncodingException e) { logger.error("widget-unsupported-encoding", query, e); throw new GeocoderException(e); } try { url = new URL(host + query); conn = url.openConnection(); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { buffer.append(line); } rd.close(); } catch (MalformedURLException e) { logger.error("widget-geocoder-malformed-url", host + query, e); throw new GeocoderException(e); } catch (IOException e) { logger.error("widget-geocoder-io-exception", host + query, e); throw new GeocoderException(e); } return buffer.toString(); } /** * Return satellite images for zoom in operation * * @param t * @param direction * @return */ public String getSatZoomIn(String t, int offx, int offy) { GGeoString gString = new GGeoString(t, offx, offy); GGeoString zoomInString = this.calc.getZoomInGeoString(gString); return getMainSatImagesList(zoomInString); } /** * Return satellite images for zoom out operation * * @param t * @param direction * @return */ public String getSatZoomOut(String t, int offx, int offy) { GGeoString gString = new GGeoString(t, offx, offy); GGeoString zoomOutString = this.calc.getZoomOutGeoString(gString); return getMainSatImagesList(zoomOutString); } /** * Return map images after zoom in operation * * @param x * @param y * @param currentZoom * @return */ public String getMapZoomIn(int x, int y, int currentZoom) { int newX = x << 1; int newY = y << 1; int newZoom = currentZoom - 1; return getMainMapImagesList(newX, newY, newZoom); } /** * Return map images after zoom out operation * * @param x * @param y * @param currentZoom * @return */ public String getMapZoomOut(int x, int y, int currentZoom) { int newX = x >> 1; int newY = y >> 1; int newZoom = currentZoom + 1; return getMainMapImagesList(newX, newY, newZoom); } /** * Return images for given direction * * @param x * @param y * @param zoom * @param direction * @return */ public String getMapImagesList(int x, int y, int zoom, String direction) { GImage centerImage = new GImage(x, y, zoom); GImage[] newImages = null; ; newImages = this.calc.getMapImages(centerImage, (int[][]) this.calc.shiftMap.get(direction)); return "{ zoom : " + zoom + ", imgList : " + this.calc.mapImageListToString(newImages) + "}"; } /** * Wrapper for getPhotoImagesList(String dir,GGeoString geoString); * * @param direction * @param t * @param offx * @param offy * @return */ public String getPhotoImagesList(String direction, String t, int offx, int offy) { GGeoString geoString = new GGeoString(t, offx, offy); return this.getPhotomagesList(direction, geoString); } /** * Return satellites for given direction * * @param t * @param direction * @return */ public String getPhotomagesList(String direction, GGeoString geoString) { GImage centerImage = this.calc.fromGeoStringToGImage(geoString); GImage[] imageList = this.calc.getMapImages(centerImage, (int[][]) this.calc.shiftMap.get(direction)); GGeoString[] photoList = new GGeoString[imageList.length]; for (int i = 0; i < imageList.length; i++) { photoList[i] = this.calc.fromGImageToGeoString(imageList[i]); } return "{ zoom : " + geoString.getZoom() + ", imgList : " + this.calc.gGeoStringListToString(photoList) + "}"; } /** * Get map images list for given satellite coordinate. * * @param t satellite coordinate * @param area * @return */ public String getMapImagesListFromTxt(String t, int offx, int offy) { GGeoString geoString = new GGeoString(t, offx, offy); GImage gImage = this.calc.fromGeoStringToGImage(geoString); int zoom = this.calc.fromTxtZoomToCoordZoom(geoString.getZoom()); return getMainMapImagesList(gImage.getImgX(), gImage.getImgY(), zoom); } /** * Get sattelites images list fro given map coordinates. * * @param x * @param y * @param zoom * @param area * @return */ public String getPhotoImagesListFromCoord(int x, int y, int zoom) { GGeoString gString = this.calc.fromGImageToGeoString(new GImage(x, y, zoom)); return getMainSatImagesList(gString); } /** * Get main images list for map mode. * * @param x * @param y * @param zoom * @return */ private String getMainMapImagesList(int x, int y, int zoom) { return getMapImagesList(x, y, zoom, GoogleCalculator.MAIN_IMAGES); } /** * Get background images list for map mode. * * @param x * @param y * @param zoom * @return */ public String getBgMapImagesList(int x, int y, int zoom) { return getMapImagesList(x, y, zoom, GoogleCalculator.BG_IMAGES); } /** * Get main images list for sattelite mode. * * @param t * @return */ private String getMainSatImagesList(GGeoString t) { return getPhotomagesList(GoogleCalculator.MAIN_IMAGES, t); } public String getBgPhotoImagesList(String t, int offx, int offy) { GGeoString geoString = new GGeoString(t, offx, offy); return this.getBgPhotoImagesList(geoString); } /** * Get background images list for sattellite mode. * * @param t * @return */ public String getBgPhotoImagesList(GGeoString t) { return getPhotomagesList(GoogleCalculator.BG_IMAGES, t); } }
public class CookieManager { /** Copyright */ private static String mark = "(c) Volantis Systems Ltd 2000."; /** Used for logging */ private static final LogDispatcher logger = LocalizationFactory.createLogger(CookieManager.class); /** The cookie map */ private Map cookieMap = null; /** Creates a new instance of CookieManager */ public CookieManager() { cookieMap = new Hashtable(); } /** * Return a named cookie store or null if there isnt one. * * @param application The name of the application owning the store * @return the CookieStore for that application or null */ public CookieStore getCookieStore(String application) { return (CookieStore) cookieMap.get(application); } /** * Create an empty cookie store for an application. * * @param application the application name */ public void createCookieStore(String application) { if (cookieMap.containsKey(application) == false) { cookieMap.put(application, new CookieStore()); } } /** * Remove a CookieStore for a named application * * @param application the application name */ public void removeCookieStore(String application) { if (cookieMap.containsKey(application)) { cookieMap.remove(application); } } /** * Create or remove an applications cookie store. * * @param application the application name * @param state true if the store is to be created, false to remove it */ public void setCookieStoreEnabled(String application, boolean state) { if (state) { if (isCookieStoreEnabled(application) == false) { createCookieStore(application); } } else { if (isCookieStoreEnabled(application) == true) { removeCookieStore(application); } } } /** * Determine whether or not an application has an active cookie store * * @param application the application name * @return boolean flag true denotes that a cookie store exists. */ public boolean isCookieStoreEnabled(String application) { return cookieMap.containsKey(application); } }
/** * A LogicalWhitespaceWriter which quietly catches, logs and continues whenever it finds an {@link * IOException}. * * <p>Designed to be used in situations where an error is "impossible", for example writers which * write to a buffer. * * <p>Paul said Protocols ought not to throw exceptions as it's "too late at this point", so I * presume this is class is safe to use within the protocol layer. */ public final class QuietLogicalWhitespaceWriter extends LogicalWhitespaceWriter { /** Used for logging */ private static final LogDispatcher logger = LocalizationFactory.createLogger(QuietLogicalWhitespaceWriter.class); /** The underlying writer. */ private final LogicalWhitespaceWriter logical; /** * Construct the <code>QuietLogicalWhitespaceWriter</code>, which passes writes it's content to * the writer supplied. * * @param out */ public QuietLogicalWhitespaceWriter(LogicalWhitespaceWriter out) { super(out); logical = out; } /** Write a character, quietly. */ public void write(int c) { try { logical.write(c); } catch (IOException e) { logger.error("unexpected-ioexception", e); // and continue! } } /** Write a string, quietly. */ public void write(String s) { write(s, 0, s.length()); } /** Write a character array, quietly. */ public void write(char cbuf[]) { write(cbuf, 0, cbuf.length); } /** Write a portion of a character array, quietly. */ public void write(char cbuf[], int off, int len) { try { logical.write(cbuf, off, len); } catch (IOException e) { logger.error("unexpected-ioexception", e); // and continue! } } /** Write a portion of a string, quietly. */ public void write(String str, int off, int len) { try { logical.write(str, off, len); } catch (IOException e) { logger.error("unexpected-ioexception", e); // and continue! } } /** Flush the stream, quietly. */ public void flush() { try { logical.flush(); } catch (IOException e) { logger.error("unexpected-ioexception", e); // and continue! } } public void writeLine() { try { logical.writeLine(); } catch (IOException e) { logger.error("unexpected-ioexception", e); // and continue! } } public void writeSpace() { try { logical.writeSpace(); } catch (IOException e) { logger.error("unexpected-ioexception", e); // and continue! } } public void writeTrimmed(char cbuf[], int off, int len) { try { logical.writeTrimmed(cbuf, off, len); } catch (IOException e) { logger.error("unexpected-ioexception", e); // and continue! } } }
/** * Implementation of response element from widgets-response namespace. * * <p>Elements from this namespace are used for building responses to AJAX requests in a * device-independent way. */ public class ResponseResponseElement extends ResponseElement { /** Used for logging. */ private static final LogDispatcher logger = LocalizationFactory.createLogger(ResponseResponseElement.class); /** the runtime device layout being used for the page */ private String layoutName; /** The collection of theme style sheets associated with this page. */ private CompiledStyleSheetCollection themeStyleSheets = new CompiledStyleSheetCollection(); public ResponseResponseElement(XDIMEContextInternal context) { super(ResponseElements.RESPONSE, context); protocolAttributes = new ResponseResponseAttributes(); } // Javadoc inherited public XDIMEResult callOpenOnProtocol(XDIMEContextInternal context, XDIMEAttributes attributes) throws XDIMEException { // In XDIME 2 mode we are responsible for setting up the canvas. // As the first stage of this we deal with any per-project default // themes and layouts. These need to be set up before we get any // per-page versions. // Get the current project. MarinerPageContext pageContext = getPageContext(context); final RuntimeProject runtimeProject = (RuntimeProject) pageContext.getCurrentProject(); if (runtimeProject != null) { // Add any project specified style sheets into the list of // theme style sheets. These must be added before any style // sheets that are specified in the head. addProjectStyleSheets(context, runtimeProject); // Extract any default layout from the project. // This will be overridden with an any explicit layout // provided in the head. layoutName = runtimeProject.getDefaultProjectLayoutLocation(); if (logger.isDebugEnabled()) { logger.debug("Project layout: " + layoutName); } } // else, presumably this is only for test...? // todo: later: avoid test specific code paths. return XDIMEResult.PROCESS_ELEMENT_BODY; } /** * Add any project specified style sheets into the list of theme style sheets. * * @param context * @param runtimeProject */ private void addProjectStyleSheets(XDIMEContextInternal context, RuntimeProject runtimeProject) { MarinerPageContext pageContext = getPageContext(context); // Find any theme style sheets which are specified in the project, // compile them and add them to the collection of compiled theme style // sheets. List projectThemeLocations = runtimeProject.getProjectThemesLocations(); if (projectThemeLocations != null) { for (Iterator themeLocations = projectThemeLocations.iterator(); themeLocations.hasNext(); ) { String projectThemeLocation = (String) themeLocations.next(); if (projectThemeLocation != null) { if (logger.isDebugEnabled()) { logger.debug("Project theme: " + projectThemeLocation); } CompiledStyleSheet projectStyleSheet = pageContext.retrieveThemeStyleSheet(projectThemeLocation); if (projectStyleSheet != null) { themeStyleSheets.addStyleSheet(projectStyleSheet); } } } } } // Javadoc inherited public void callCloseOnProtocol(XDIMEContextInternal context) { // NO-OP } // javadoc unnecessary public CompiledStyleSheetCollection getThemeStyleSheets() { return themeStyleSheets; } /** * Add the provided compiled style sheet obtained from the <link> element to the collection of * theme style sheets. The mode must be XDIME2 if this function is called. * * @param compiledStyleSheet */ public void addLinkStyleSheet(CompiledStyleSheet compiledStyleSheet) { themeStyleSheets.addStyleSheet(compiledStyleSheet); } /** * set the name of the runtime device layout being used. * * @param layout */ public void setLayoutName(String layout) { this.layoutName = layout; } public String getLayoutName() { return this.layoutName; } }
/** Composite that displays the form sections that constitute the device overview page */ public class DeviceOverviewForm extends Composite implements XPathFocusable { /** Used for logging */ private static final LogDispatcher LOGGER = LocalizationFactory.createLogger(DeviceOverviewForm.class); /** Used to retrieve localized exception messages. */ private static final ExceptionLocalizer EXCEPTION_LOCALIZER = LocalizationFactory.createExceptionLocalizer(DeviceOverviewForm.class); /** The prefix for resources associated with this class. */ private static final String RESOURCE_PREFIX = "DeviceOverviewForm."; /** Constant for device overview forms margin height */ private static final int MARGIN_HEIGHT = EditorMessages.getInteger("Editor.marginHeight").intValue(); /** Constant for device overview forms margin width */ private static final int MARGIN_WIDTH = EditorMessages.getInteger("Editor.marginWidth").intValue(); /** Constant for device overview forms horizontal spacing */ private static final int HORIZONTAL_SPACING = EditorMessages.getInteger("Editor.horizontalSpacing").intValue(); /** Constant for device overview forms vertical spacing */ private static final int VERTICAL_SPACING = EditorMessages.getInteger("Editor.verticalSpacing").intValue(); /** The text for the Restore Defaults button. */ private static final String RESTORE_DEFAULTS_TEXT = DevicesMessages.getString(RESOURCE_PREFIX + "restoreDefaults.text"); /** Create a filter so that only device elements are included in the selection. */ private static final ODOMSelectionFilter DEVICE_FILTER = new ODOMSelectionFilter( null, new String[] {DeviceRepositorySchemaConstants.DEVICE_ELEMENT_NAME}, new ODOMSelectionFilterConfiguration(true, true)); /** FormSection that displays the hierarchy document in a tree format. */ private DeviceHierarchySection deviceHierarchySection; /** The ODOMEditor context for the device repository */ private DeviceEditorContext context; /** The Restore Defaults button. */ private Button restoreButton; /** Maintain the selected element so that we restore it if necessary (via the restore action). */ private Element deviceIDElement; /** * Initializes a <code>DeviceOverviewForm</code> with the given arguments * * @param parent the parent composite * @param style a bitset used to specify any styles * @param context the DeviceEditorContext. */ public DeviceOverviewForm(Composite parent, int style, DeviceEditorContext context) { super(parent, style); this.context = context; createDisplayArea(); } /** Creates the display area for this form */ private void createDisplayArea() { // create the top level layout for the form GridLayout layout = new GridLayout(); layout.marginHeight = MARGIN_HEIGHT; layout.marginWidth = MARGIN_WIDTH; layout.verticalSpacing = VERTICAL_SPACING; layout.horizontalSpacing = HORIZONTAL_SPACING; GridData data = new GridData(GridData.FILL_BOTH); setLayout(layout); setLayoutData(data); // set the background color to white Color white = getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND); setBackground(white); // add an alerts and actions section AlertsActionsSection alerts = new AlertsActionsSection(this, SWT.NONE, context); alerts.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); // add a two column contianer for the form sections. The first // column will display the DeviceHierarchy section and the second // column will display the primary and secondary pattern sections. Composite formContainer = new Composite(this, SWT.NONE); GridLayout formLayout = new GridLayout(2, false); formLayout.marginWidth = 0; formLayout.marginHeight = 0; formLayout.horizontalSpacing = HORIZONTAL_SPACING; GridData formData = new GridData(GridData.FILL_BOTH); formContainer.setLayout(formLayout); formContainer.setLayoutData(formData); formContainer.setBackground(white); // add the hierarchy section to the formContainer deviceHierarchySection = new DeviceHierarchySection(formContainer, SWT.NONE, context); GridData hierarchyData = new GridData(GridData.FILL_VERTICAL); deviceHierarchySection.setLayoutData(hierarchyData); // add a scroll area for the patterns sections ScrolledComposite controlsScroller = new ScrolledComposite(formContainer, SWT.H_SCROLL | SWT.V_SCROLL); controlsScroller.setLayout(new FillLayout()); controlsScroller.setLayoutData(new GridData(GridData.FILL_BOTH)); controlsScroller.setExpandHorizontal(true); controlsScroller.setExpandVertical(true); controlsScroller.setAlwaysShowScrollBars(false); controlsScroller.setBackground(white); // add the container for the patterns sections Composite patternContainer = new Composite(controlsScroller, SWT.NONE); GridLayout patternLayout = new GridLayout(); patternLayout.marginHeight = 0; patternLayout.marginWidth = 0; patternLayout.verticalSpacing = VERTICAL_SPACING; GridData patternData = new GridData(GridData.FILL_BOTH); patternContainer.setLayout(patternLayout); patternContainer.setLayoutData(patternData); patternContainer.setBackground(white); // Add the primary patterns section PrimaryPatternsSection primaryPatterns = new PrimaryPatternsSection(patternContainer, SWT.NONE, context); primaryPatterns.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); // Add the secondary patterns section SecondaryPatternsSection secondaryPatterns = new SecondaryPatternsSection(patternContainer, SWT.NONE, context); secondaryPatterns.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); createRestoreMechanism(patternContainer); TACPatternsSection TACPatterns = new TACPatternsSection(patternContainer, SWT.NONE, context); TACPatterns.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); patternContainer.setSize(patternContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT)); patternContainer.layout(); controlsScroller.setMinSize(patternContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT)); controlsScroller.setContent(patternContainer); layout(); } /** * Get the name of the selected device. * * @return the name of the selected device or null if none selected. */ String getSelectedDeviceName() { String selectedDeviceName = null; if (deviceIDElement != null) { selectedDeviceName = deviceIDElement.getAttributeValue(DeviceRepositorySchemaConstants.DEVICE_NAME_ATTRIBUTE); } return selectedDeviceName; } /** * Add the restore button and the standard element handling facility. * * @param parent the parent composite for the resotre button. */ private void createRestoreMechanism(Composite parent) { restoreButton = new Button(parent, SWT.NONE); restoreButton.setText(RESTORE_DEFAULTS_TEXT); restoreButton.setEnabled(!context.isAdminProject()); restoreButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); restoreButton.addSelectionListener( new SelectionListener() { public void widgetSelected(SelectionEvent e) { widgetDefaultSelected(e); } public void widgetDefaultSelected(SelectionEvent event) { if (deviceIDElement != null) { ((DeviceODOMElement) deviceIDElement).restore(); } } }); // Add a listener to the selection manager which responds to device // element selections. context .getODOMSelectionManager() .addSelectionListener( new ODOMElementSelectionListener() { public void selectionChanged(ODOMElementSelectionEvent event) { ODOMElementSelection selection = event.getSelection(); if (!selection.isEmpty()) { Element deviceElement = (Element) selection.getFirstElement(); // Retrieve the device name. final String deviceName = deviceElement.getAttributeValue( DeviceRepositorySchemaConstants.DEVICE_NAME_ATTRIBUTE); deviceIDElement = context .getDeviceRepositoryAccessorManager() .retrieveDeviceIdentification(deviceName); if (deviceIDElement == null) { Object params = new Object[] { deviceName, context.getDeviceRepositoryAccessorManager().getDeviceRepositoryName() }; LOGGER.error("device-not-found", params); String message = EXCEPTION_LOCALIZER.format("device-not-found", params); throw new UndeclaredThrowableException(new RepositoryException(message)); } else { DeviceODOMElement parent = (DeviceODOMElement) deviceIDElement.getParent(); if (parent == null) { LOGGER.error("device-no-parent", deviceName); String message = EXCEPTION_LOCALIZER.format("device-no-parent", deviceName); throw new UndeclaredThrowableException(new RepositoryException(message)); } else { parent.submitRestorableName(deviceName); } } } else { deviceIDElement = null; } } }, DEVICE_FILTER); } // javadoc inherited public boolean setFocus(XPath path) { // todo implement this return false; } }
public class ZoomOperation implements MapOperation { /** The logger used by this class. */ private static final LogDispatcher logger = LocalizationFactory.createLogger(ZoomOperation.class); /** Used to retrieve localized exception messages. */ private static final ExceptionLocalizer exceptionLocalizer = LocalizationFactory.createExceptionLocalizer(ZoomOperation.class); // javadoc inherited public String perform(Map params) throws IllegalArgumentException, Exception { String direction = WidgetServiceHelper.getParameter(params, P_DIR); Integer x = WidgetServiceHelper.getIntParameter(params, P_X); Integer y = WidgetServiceHelper.getIntParameter(params, P_Y); String t = WidgetServiceHelper.getParameter(params, P_T); Integer offx = WidgetServiceHelper.getIntParameter(params, P_OFFX); Integer offy = WidgetServiceHelper.getIntParameter(params, P_OFFY); Integer zoom = WidgetServiceHelper.getIntParameter(params, P_ZOOM); if (null == direction) { throw new IllegalArgumentException(exceptionLocalizer.format("widget-missing-dir-parameter")); } if (null == zoom) { throw new IllegalArgumentException( exceptionLocalizer.format("widget-missing-zoom-parameter")); } if (null != t && null != offx && null != offy && DIR_IN.equals(direction)) { return zoomInPhoto(zoom.intValue(), t, offx.intValue(), offy.intValue()); } if (null != t && null != offx && null != offy && DIR_OUT.equals(direction)) { return zoomOutPhoto(zoom.intValue(), t, offx.intValue(), offy.intValue()); } else if ((null != x) && (null != y) && DIR_IN.equals(direction)) { return zoomInMap(zoom.intValue(), x.intValue(), y.intValue()); } else if ((null != x) && (null != y) && DIR_OUT.equals(direction)) { return zoomOutMap(zoom.intValue(), x.intValue(), y.intValue()); } throw new IllegalArgumentException( exceptionLocalizer.format("widet-invalid-zoom-operation-params")); } private String zoomInPhoto(int currentZoom, String t, int offx, int offy) { if (logger.isDebugEnabled()) { logger.debug("Executing zoomInPhoto(zoom=" + currentZoom + ", t=" + t + ")"); } return OperationHelper.getInstance().getSatZoomIn(t, offx, offy); } private String zoomOutPhoto(int currentZoom, String t, int offx, int offy) { if (logger.isDebugEnabled()) { logger.debug("Executing zoomOutPhoto(zoom=" + currentZoom + ", t=" + t + ")"); } return OperationHelper.getInstance().getSatZoomOut(t, offx, offy); } private String zoomInMap(int currentZoom, int x, int y) { if (logger.isDebugEnabled()) { logger.debug("Executing zoomInMap(zoom=" + currentZoom + ", x=" + x + ", y=" + y + ")"); } return OperationHelper.getInstance().getMapZoomIn(x, y, currentZoom); } private String zoomOutMap(int currentZoom, int x, int y) { if (logger.isDebugEnabled()) { logger.debug("Executing zoomOutMap(zoom=" + currentZoom + ", x=" + x + ", y=" + y + ")"); } return OperationHelper.getInstance().getMapZoomOut(x, y, currentZoom); } }
/** Class that is used to Rewrite Asset URL values */ public class DefaultAssetURLRewriter implements AssetURLRewriter { /** Used for logging */ private static final LogDispatcher logger = LocalizationFactory.createLogger(DefaultAssetURLRewriter.class); /** The Volantis object */ private Volantis volantisBean = null; /** * Determine if we have logged out a message common in viking settlements, which may cause * seasonal flooding of their console if they provide GIGO in their policies WOW. * * <p>Explanation: American Casualty Department is ER. A Chip is often nown as an IC. Eric the * Viking is Eric Bowman from Three. * * <p>Eric has made several remartks about the code quality and uses expressions like suprise * suprise it doesn't work WOW! * * <p>When pointed out the Garbage In = Garbage Out he complained that the messages generated * would flood his console (ah bless)! */ private static boolean vikingCasualtyChipWOWFlag = false; /** * Method to allow an Asset URL to be rewritten * * @param requestContext the request context object * @param asset the asset associated with the URL * @param assetGroup the assets associated asset group * @param marinerURL the URL that is to be rewritten * @return the rewritten URL as a MarinerURL object that is immutable (read only) * @throws RepositoryException if a repository exception occurs. */ public MarinerURL rewriteAssetURL( MarinerRequestContext requestContext, Asset asset, AssetGroup assetGroup, MarinerURL marinerURL) throws RepositoryException { // If the asset is a chart asset then do nothing. MarinerURL urlResult = null; if (asset instanceof ChartAsset) { urlResult = marinerURL; } else { // Compute the non-cacheable url and if we do not obtain a valid url // (the url is null) then we do have to build the 'cached URL'. urlResult = computeNoncacheableURL(requestContext, assetGroup, asset); } // If the resulting URL is null then we need to compute the cacheable // url. if (urlResult == null) { urlResult = computeCacheableURL(requestContext, asset, assetGroup, marinerURL); } return urlResult; } /** * Creates a MarinerUrl * * @param requestContext * @param asset * @param assetGroup * @param marinerURL * @return * @throws RepositoryException */ public static MarinerURL createMarinerURL( MarinerRequestContext requestContext, Asset asset, AssetGroup assetGroup, MarinerURL marinerURL) throws RepositoryException { MarinerURL urlResult = computeURL(requestContext, asset, assetGroup, marinerURL); if (asset instanceof ConvertibleImageAsset) { String url = urlResult.getExternalForm(); // Construct the url for the convertible image asset. ConvertibleImageAsset convertible = (ConvertibleImageAsset) asset; PreservedArea area = PreservedArea.get(convertible.getPreserveLeft(), convertible.getPreserveRight(), true); String value = ContextInternals.constructImageURL(requestContext, url, area); urlResult = new MarinerURL(value); } // Complete the URL urlResult = completeURL(requestContext, asset, assetGroup, urlResult); // Make sure that the url cannot be modified (even if it is a // convertible image asset). urlResult.makeReadOnly(); return urlResult; } /** * Return a <code>MarinerURL</code> for any cacheable urls. * * @param requestContext the mariner request context * @param assetGroup the assetgroup * @param asset the asset * @return a mariner url or null if none can be computed. */ protected MarinerURL computeCacheableURL( MarinerRequestContext requestContext, Asset asset, AssetGroup assetGroup, MarinerURL marinerURL) throws RepositoryException { MarinerURL urlResult = null; // we are not caching the URLs urlResult = createMarinerURL(requestContext, asset, assetGroup, marinerURL); if (logger.isDebugEnabled()) { logger.debug( "Asset " + asset + " resolved absolute url '" + urlResult + "' without using cache"); } // If we get here we should definitely have a url from the cache or one // that has been computed and then completed. return urlResult; } /** * Return a <code>MarinerURL</code> (or null) for any non-cacheable urls. * * @param requestContext the mariner request context * @param assetGroup the assetgroup * @param asset the asset * @return a mariner url or null if none can be computed. * @throws RepositoryException if a repository exception occurs. */ protected MarinerURL computeNoncacheableURL( MarinerRequestContext requestContext, AssetGroup assetGroup, Asset asset) throws RepositoryException { // If the asset is a DynamicVisualAsset and the encoding is TV then the // asset url consists of the device specific tv channel prefix and the // value appended if it is set. If the tv channel prefix is not valid in // a url then we have problems. if (asset.getClass() == DynamicVisualAsset.class) { DynamicVisualAsset dynamicVisualAsset = (DynamicVisualAsset) asset; if (dynamicVisualAsset.getEncoding() == DynamicVisualAsset.TV) { MarinerPageContext marinerPageContext = ContextInternals.getMarinerPageContext(requestContext); InternalDevice device = marinerPageContext.getDevice(); String tvChannelPrefix = device.getTVChannelPrefix(); String url = tvChannelPrefix; String value = dynamicVisualAsset.getValue(); if (value != null) { url += value; } return new MarinerURL(url); } } return null; } /** * Method that computes the URL for an asset. The computed URL may require completing at a later * stage. * * @param requestContext the mariner request context * @param asset the Asset whose URL we are computing * @param assetGroup the AssetGroup associated with the Asset * @param marinerURL the URL that is being rewritten/computed * @return the computed URL */ public static MarinerURL computeURL( MarinerRequestContext requestContext, Asset asset, AssetGroup assetGroup, MarinerURL marinerURL) { RuntimeProject project = (RuntimeProject) asset.getIdentity().getProject(); if (project == null) { project = (RuntimeProject) requestContext.getCurrentProject(); } MarinerURL prefix = null; MarinerURL newURL = marinerURL; if (assetGroup != null) { prefix = new MarinerURL(assetGroup.getPrefixURL()); if (logger.isDebugEnabled()) { logger.debug("Retrieved prefix from asset group as " + prefix); } } else { prefix = getPrefixURL(project, asset); if (logger.isDebugEnabled()) { logger.debug("Retrieved prefix from project " + project + " as " + prefix); } } if (prefix != null) { newURL = new MarinerURL(prefix, marinerURL); } return newURL; } private static MarinerURL getPrefixURL(RuntimeProject project, Asset asset) { VariantType variantType; if (asset instanceof AudioAsset) { variantType = VariantType.AUDIO; } else if (asset instanceof DynamicVisualAsset) { variantType = VariantType.VIDEO; } else if (asset instanceof ImageAsset) { variantType = VariantType.IMAGE; } else if (asset instanceof ScriptAsset) { variantType = VariantType.SCRIPT; } else if (asset instanceof TextAsset) { variantType = VariantType.TEXT; } else { variantType = null; } return project.getPrefixURL(variantType); } /** * Method that completes a computed URL * * @param requestContext the mariner request context * @param asset the Asset whose URL we are completing * @param assetGroup the AssetGroup associated with the Asset * @param marinerURL the URL that is being completed * @return the completed URL */ public static MarinerURL completeURL( MarinerRequestContext requestContext, Asset asset, AssetGroup assetGroup, MarinerURL marinerURL) { // Get the project that owns the resource. If an asset group is // provided then it is the asset group's project, otherwise it is the // asset's project. RuntimeProject assetProject = (RuntimeProject) asset.getProject(); RuntimeProject project = null; if (assetGroup == null) { project = assetProject; } else { project = (RuntimeProject) assetGroup.getProject(); } if (project == null) { throw new IllegalStateException("Project not set"); } MarinerURL assetsBaseURL = project.getAssetsBaseURL(); if (isClientSideURL(asset, assetGroup)) { // Client side URLs are not affected by the project's base URL. } else if (project.getContainsOrphans() && project.isRemote()) { // Asset URLs from remote policies that are not in a remote project // should already be fully qualified. if (!marinerURL.isAbsolute()) { synchronized (DefaultAssetURLRewriter.class) { if (!vikingCasualtyChipWOWFlag) { vikingCasualtyChipWOWFlag = true; logger.warn("url-not-absolute", marinerURL.getExternalForm()); } } } } else if (marinerURL.containsDocumentRelativePath()) { // Document relative assets should only be resolved if the project // is portable, otherwise leave them as they are. // todo Always resolve these and then provide a way later to optimise URLs in the page to try // and make them relative if possible. if (project.isPortable()) { // If the project is portable then get the project relative path to the // policy so that it can be used to resolve relative asset references // against. MarinerURL projectRelativePath; String name = asset.getName(); if (name.startsWith("/")) { projectRelativePath = new MarinerURL(name); } else { projectRelativePath = new MarinerURL(assetProject.makeProjectRelativePath(name, true)); } // Resolve relative asset references against the project // relative path and then make sure that it can be resolved // against the assets base URL by removing leading /. marinerURL = new MarinerURL(projectRelativePath, marinerURL); marinerURL = new MarinerURL( URLNormalizer.convertHostRelativeToDocumentRelative(marinerURL.getExternalForm())); // Resolve the document relative asset URL against the assets // base URL. marinerURL = new MarinerURL(assetsBaseURL, marinerURL); // The result must be absolute, or host relative. if (marinerURL.isAbsolute()) { // Nothing more to do. } else if (marinerURL.containsHostRelativePath()) { // May need to make it relative to the context. EnvironmentContext environmentContext = ContextInternals.getEnvironmentContext(requestContext); MarinerURL contextPath = environmentContext.getContextPathURL(); marinerURL = new MarinerURL( contextPath, URLNormalizer.convertHostRelativeToDocumentRelative( marinerURL.getExternalForm())); } else { throw new IllegalStateException( "The rewritten URL " + marinerURL + " for remote asset " + asset + " " + "must be absolute or host relative but is not"); } } } else if (marinerURL.containsHostRelativePath()) { // Host relative paths are treated as being relative to the // project's asset base URL. This is because otherwise assets // and asset groups would need to know the host relative path to // the assets including the web application context (if any). // NOTE: I have the feeling this should be dealt with when the url // is computed but there is no description for the intermediate form // of the url so I am not prepared to change that. This class needs // rewriting/clarifying. Until then we are left with the following // bodge... // todo: later: deal with document relative urls which are from // asset groups which are host relative. // // If the url was computed from an asset group which was relative // to the host, then we should leave this as host relative. if (assetGroup != null && assetGroup.getLocationType() == AssetGroup.HOST) { // Leave the url as host relative. This will mean than when // resolved against the context the context is ignored. if (logger.isDebugEnabled()) { logger.debug( "leaving existing host relative url computed " + "from host relative asset group url as host " + "relative"); } } else { // Either it was not from an asset group or the asset group was // context relative. In either case we should... // Strip the / off the front of the host relative URL to make it // a document relative URL so it will resolve against the base // URL properly. String url = URLNormalizer.convertHostRelativeToDocumentRelative(marinerURL.getExternalForm()); marinerURL = new MarinerURL(assetsBaseURL, url); } // The resulting URL must be either a host relative path or an // absolute URL. If it is not then it is a fatal error as it could // only have arisen due to invalid configuration which should have // been detected during init. if (marinerURL.isRelative() && marinerURL.containsDocumentRelativePath()) { throw new RuntimeException( "The rewritten URL " + marinerURL + " for Asset " + asset + " is not host relative or " + "absolute. The configuration is probably wrong."); } } return marinerURL; } /** * Is the asset a client-side asset or a server-side asset * * @param asset the Asset * @param assetGroup the AssetGroup associated with the Asset * @return true if the asset is a client-side asset, false if asset is a server side-asset */ protected static boolean isClientSideURL(Asset asset, AssetGroup assetGroup) { if (assetGroup != null && assetGroup.getLocationType() == AssetGroup.ON_DEVICE) { return true; } if (asset instanceof ImageAsset && ((ImageAsset) asset).isLocalSrc()) { return true; } return false; } /** * Method to return the Volantis bean * * @param requestContext the MarinerRequestContext * @return the Volantis bean */ private Volantis getVolantisBean(MarinerRequestContext requestContext) { if (volantisBean == null) { MarinerPageContext marinerPageContext = ContextInternals.getMarinerPageContext(requestContext); volantisBean = marinerPageContext.getVolantisBean(); } return volantisBean; } }
/** * This class is the base class for all the elements which can appear in a dom. * * <p>These are doubly linked as it is likely that they will be rearranged quite a lot and the extra * link makes it much easier to remove them and add them at arbitrary positions in the list. */ public abstract class NodeImpl implements Node { /** Used for logging */ private static final LogDispatcher logger = LocalizationFactory.createLogger(NodeImpl.class); protected final boolean CHECK_INVARIANTS; protected final boolean DEBUG; protected final DOMFactory factory; /** * The parent element, is null if this is the root node. * * <p>This is package private so it can be accessed by other classes in this package. */ ElementImpl parent; /** * The next node, is null if this is the last node in the list. * * <p>This is package private so it can be accessed by other classes in this package. */ NodeImpl next; /** * The previous node, is null if this is the first node in the list. * * <p>This is package private so it can be accessed by other classes in this package. */ NodeImpl previous; /** * User data associated with the node. This data is just for use within a single processing stage, * and can be overwritten at any time. Therefore it cannot be guaranteed to persist across * processing stages. */ Object object; /** * Annotation data associated with the node. This data is longer-lived than the user data and * persists across processing stages. This data can only be set once. */ Object annotation; /** Create a new <code>Node</code>. */ NodeImpl(DOMFactory factory) { this.factory = factory; this.CHECK_INVARIANTS = factory.isDebug(); this.DEBUG = logger.isDebugEnabled(); } // Javadoc inherited. public DOMFactory getDOMFactory() { return factory; } public Element getParent() { return parent; } public Node getPrevious() { return previous; } public Node getNext() { return next; } public void setObject(Object object) { this.object = object; } public Object getObject() { return object; } public void setAnnotation(Object annotation) { if (this.annotation != null) { throw new IllegalStateException("annotation has already been set."); } this.annotation = annotation; } public Object getAnnotation() { return annotation; } public void insertAfter(Node node) { NodeImpl nodeImpl = (NodeImpl) node; if (logger.isDebugEnabled()) { logger.debug("Inserting " + this + " after " + nodeImpl); } if (CHECK_INVARIANTS) { checkIsolated(); nodeImpl.checkInvariants(); } // Update this node's links. previous = nodeImpl; next = nodeImpl.next; parent = nodeImpl.parent; // Update the links in the tree. if (next == null) { // This node is the last in the list so we need to make this node // the tail. parent.tail = this; } else { // Add a link back to this node. next.previous = this; } // Make this node the next node after the one in the tree. nodeImpl.next = this; if (CHECK_INVARIANTS) { nodeImpl.checkInvariants(); } } public void insertBefore(Node node) { NodeImpl nodeImpl = (NodeImpl) node; if (logger.isDebugEnabled()) { logger.debug("Inserting " + this + " before " + nodeImpl); } if (CHECK_INVARIANTS) { checkIsolated(); nodeImpl.checkInvariants(); } // Update this node's links. previous = nodeImpl.previous; next = nodeImpl; parent = nodeImpl.parent; // Update the links in the tree. if (previous == null) { // This node is the first in the list so we need to make it the head. parent.head = this; } else { // Add a link forward to this node. previous.next = this; } // Make this node the previous node before the one in the tree. nodeImpl.previous = this; if (CHECK_INVARIANTS) { nodeImpl.checkInvariants(); } } public void addToTail(Element element) { if (logger.isDebugEnabled()) { logger.debug("Adding " + this + " to tail of " + element); } if (CHECK_INVARIANTS) { checkInvariants(); } element.addTail(this); if (CHECK_INVARIANTS) { checkInvariants(); } } public void addToHead(Element element) { if (logger.isDebugEnabled()) { logger.debug("Adding " + this + " to head of " + element); } if (CHECK_INVARIANTS) { checkInvariants(); } element.addHead(this); if (CHECK_INVARIANTS) { checkInvariants(); } } public void replace(Node node) { NodeImpl nodeImpl = (NodeImpl) node; nodeImpl.replaceWith(this); } /** * Replace this node with the specified node. * * @param node The node which will replace this one. */ private void replaceWith(NodeImpl node) { if (logger.isDebugEnabled()) { logger.debug("Replacing " + this + " with " + node); } if (CHECK_INVARIANTS) { node.checkIsolated(); checkInvariants(); } if (previous == null) { parent.head = node; } else { previous.next = node; } if (next == null) { parent.tail = node; } else { next.previous = node; } node.parent = parent; node.next = next; node.previous = previous; parent = null; next = null; previous = null; if (CHECK_INVARIANTS) { node.checkInvariants(); checkIsolated(); } } public void remove() { if (logger.isDebugEnabled()) { logger.debug("Removing " + this); } if (CHECK_INVARIANTS) { checkInvariants(); } if (previous == null) { // This node is the first in the list so update the parent element's // head to reference the next node. parent.head = next; } else { // Update the previous node's next link so that it references the node // after this one. previous.next = next; } if (next == null) { // This node is the last in the list so update the parent element's // tail to reference the previous node. parent.tail = previous; } else { // Update the next node's previous link so that it references the node // before this one. next.previous = previous; } ElementImpl oldParent = parent; // Reset this node. previous = null; parent = null; next = null; if (CHECK_INVARIANTS) { oldParent.checkInvariants(); checkIsolated(); } } public boolean promote() { return parent.promoteNode(this); } public boolean promote(boolean trimEmptyNodes) { return parent.promoteNode(this, trimEmptyNodes); } // Javadoc inherited. public void replaceWith(NodeSequence sequence) { if (CHECK_INVARIANTS) { checkInvariants(); } PrivateNodeSequence s = (PrivateNodeSequence) sequence; // If the sequence is empty then simply remove this node and return // immediately. NodeImpl first = (NodeImpl) s.getFirst(); if (first == null) { remove(); return; } // Make sure that the node being replaced is not in the sequence as // that would corrupt the DOM. Node end = s.getEnd(); for (NodeImpl node = first; node != end; node = node.next) { if (this == node) { throw new IllegalStateException("Cannot replace node with sequence containing node"); } // Update the parent. node.parent = parent; } NodeImpl last = (NodeImpl) s.getLast(); if (previous == null) { parent.head = first; } else { previous.next = first; } first.previous = previous; if (next == null) { parent.tail = last; } else { next.previous = last; } last.next = next; if (CHECK_INVARIANTS) { checkInvariants(); } } void checkIsolated() { if (parent != null) { throw new IllegalStateException( this + ": Isolated node should have a null parent but it is " + parent); } if (next != null) { throw new IllegalStateException( this + ": Isolated node should have a null next but it is " + next); } if (previous != null) { throw new IllegalStateException( this + ": Isolated node should have a null previous but it is " + previous); } checkInvariants(); } void checkWholeTree() { NodeImpl root = this; while (root.parent != null) { root = root.parent; } root.checkInvariants(); } void checkInvariants() { if (parent != null) { checkWholeTree(); } else { try { if (logger.isDebugEnabled()) { debug(); } checkInvariantsImpl(); } catch (IllegalStateException e) { if (logger.isDebugEnabled()) { debug(); } throw e; } } } void checkInvariantsImpl() { if (parent == null) { if (previous != null) { throw new IllegalStateException( this + ": previous should be null when not in tree but is " + previous); } if (next != null) { throw new IllegalStateException( this + ": next should be null when not in tree but is " + next); } } else { if (previous == null && parent.head != this) { throw new IllegalStateException( this + ": previous is null but this is not head of the list"); } if (next == null && parent.tail != this) { throw new IllegalStateException(this + ": next is null but this is not tail of the list"); } } } void debug() { // logger.debug ("Who is calling this", new Throwable ()); if (logger.isDebugEnabled()) { logger.debug("Starting"); } debug(" "); if (logger.isDebugEnabled()) { logger.debug("Ending"); } } void debug(String indent) { if (logger.isDebugEnabled()) { logger.debug(indent + "node " + this); } debugLinks(indent); } void debugLinks(String indent) { if (logger.isDebugEnabled()) { logger.debug(indent + "previous " + previous); logger.debug(indent + "parent " + parent); logger.debug(indent + "next " + next); } } }
/** * {@link AbstractMenuRenderer} for rendering numeric shortcut style menus on generic WML devices. * * <p>Since generic WML phones don't support automagic accesskey generation ala OpenWave phones, we * emulate the Openwave behaviour for generic WML. * * <p>NOTE: there is no rendering of stylistic emulation markup here. This is because we only write * 'a' tags which cannot contain the stylistic tags. * * @see OpenwaveNumericShortcutMenuRenderer */ public class WMLNumericShortcutMenuRenderer extends AbstractNumericShortcutMenuRenderer { /** Used for logging */ private static final LogDispatcher logger = LocalizationFactory.createLogger(WMLNumericShortcutMenuRenderer.class); /** * Create a new <code>WMLNumericShortcutMenuRenderer</code> instance * * @param menuRendererContext the current <code>MenuRendererContext</code> * @param pageContext the current <code>MarinerPageContext</code> */ public WMLNumericShortcutMenuRenderer( MenuRendererContext menuRendererContext, MarinerPageContext pageContext) { super(menuRendererContext, pageContext); } // javadoc inherited protected void openMenu(DOMOutputBuffer outputBuffer, MenuAttributes attributes) throws ProtocolException { // do nothing } // javadoc inherited protected void closeMenu(DOMOutputBuffer outputBuffer, MenuAttributes attributes) throws ProtocolException { // do nothing } // javadoc inherited protected void openMenuGroup(DOMOutputBuffer outputBuffer, MenuItemGroupAttributes groupAtts) throws ProtocolException { // do nothing } // javadoc inherited protected void closeMenuGroup(DOMOutputBuffer outputBuffer, MenuItemGroupAttributes groupAtts) throws ProtocolException { // do nothing } // javadoc inherited protected void writeMenuItem(DOMOutputBuffer outputBuffer, MenuItem menuItem) throws ProtocolException { InternalDevice device = pageContext.getDevice(); boolean isAccesskeyPrefixKeyNeeded = !device.getBooleanPolicyValue( DevicePolicyConstants.SUPPORTS_WML_ACCESSKEY_AUTOMAGIC_NUMBER_DISPLAY); // Extract the href from the menu item. LinkAssetReference reference = menuItem.getHref(); String href = reference.getURL(); // Extract the text from the menu item. String text = menuItem.getText(); // Add the dummy access key prefix to the text if necessary. if (isAccesskeyPrefixKeyNeeded) { text = AccesskeyConstants.DUMMY_ACCESSKEY_VALUE_STRING + " " + text; } // Report what we are about to do for debugging. if (logger.isDebugEnabled()) { logger.debug("writing numeric shortcut menu item with href=" + href + ", text=" + text); } // Open the annotation element. // @todo 2005060816 annotate child with style information if it's not inherited from the parent Element annotator = outputBuffer.openStyledElement(AccesskeyConstants.ACCESSKEY_ANNOTATION_ELEMENT, menuItem); // Open the anchor element. Element anchor = outputBuffer.openElement("a"); // Copy attributes into the anchor element. menuRendererContext.writeTitleAttribute(anchor, menuItem); anchor.setAttribute("href", href); // Add the dummy accesskey attribute as well. anchor.setAttribute("accesskey", AccesskeyConstants.DUMMY_ACCESSKEY_VALUE_STRING); // Write out the menu text as the content of the link. outputBuffer.appendEncoded(text); // Close the anchor element. outputBuffer.closeElement(anchor); // Close the annotation element. outputBuffer.closeElement(annotator); // Add BR to force hardcoded vertical alignment. // This is compatible with actual Openwave numeric shortcut rendering // which is always vertical. // NOTE: This means that the mariner-menu-orientation style is ignored. outputBuffer.addStyledElement("br", menuItem); } }
/** * An {@link com.volantis.mcs.integration.AppServerInterface AppServerInterface} implementation * appropriate to Weblogic 6.0. */ public class Weblogic60Interface extends AbstractAppServer { /** Used for logging */ private static final LogDispatcher logger = LocalizationFactory.createLogger(Weblogic60Interface.class); /** Initializes the new instance. */ public Weblogic60Interface() { if (logger.isDebugEnabled()) { logger.debug("Weblogic " + appServerVersion() + " Application Server Interface started"); } } /** * Returns a string of the version of the app server implemented. * * @return the app server version number */ protected String appServerVersion() { return "6.0"; } // Javadoc inherited from interface. public DataSource getAppServerDataSource() { // This method uses the jndi-provider and datasource // from the config file to get the datasource reference // from Weblogic Context ctx = null; String dataSource = volantisBean.getConfig().getAttributeValue(CONFIG_WEBAPP_ELEMENT, "datasource"); if (dataSource == null) { logger.info("connection-pool-datasource-not-found"); return null; } Hashtable ht; String jndiProvider = volantisBean.getConfig().getAttributeValue(CONFIG_WEBAPP_ELEMENT, "jndi-provider"); if (jndiProvider == null) { logger.info("jndi-provider-not-found"); ht = null; } else { ht = new Hashtable(); logger.info("jndi-provider-config-used"); ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"); ht.put(Context.PROVIDER_URL, jndiProvider); } try { ctx = new InitialContext(ht); } catch (NamingException nex) { logger.error("unexpected-exception", nex); return null; } try { DataSource ds = (DataSource) ctx.lookup(dataSource); ctx.close(); if (logger.isDebugEnabled()) { logger.debug("Using Weblogic Datasource " + dataSource); } return ds; } catch (NamingException ne) { logger.error("unexpected-exception", ne); return null; } } // Javadoc inherited from interface. public boolean useAppServerDataSource() { com.volantis.mcs.runtime.Config c = volantisBean.getConfig(); if (logger.isDebugEnabled()) { logger.debug( CONFIG_WEBAPP_ELEMENT + ".use-server-connection-pool = " + c.getAttributeValue(CONFIG_WEBAPP_ELEMENT, "use-server-connection-pool")); } return c.getBooleanAttributeValue(CONFIG_WEBAPP_ELEMENT, "use-server-connection-pool"); } }
/** * The include element. Allows an XML or plain text file to be processed, causing the content to be * incorporated into the page being generated. */ public class IncludeElementImpl extends AbstractExprElementImpl { /** Used for logging */ private static final LogDispatcher logger = LocalizationFactory.createLogger(IncludeElementImpl.class); /** Used to retrieve localized exception messages. */ private static final ExceptionLocalizer exceptionLocalizer = LocalizationFactory.createExceptionLocalizer(IncludeElementImpl.class); // Javadoc inherited. protected int exprElementStart(MarinerRequestContext context, PAPIAttributes papiAttributes) throws PAPIException { // This tag specifically does not push itself onto the page context // element stack (it can't have children anyway). However, it // is important that there is an element in that stack in order to // allow the integration process to operate correctly. return SKIP_ELEMENT_BODY; } // Javadoc inherited. protected int exprElementEnd(MarinerRequestContext context, PAPIAttributes papiAttributes) throws PAPIException { IncludeAttributes attributes = (IncludeAttributes) papiAttributes; if (attributes.getHref() == null) { throw new PAPIException(exceptionLocalizer.format("include-href-missing")); } else { // @todo this is a bit duff since it relies on markup naming not to change; do this a // different way // Set up the markup that will be sent down the pipeline StringBuffer markup = new StringBuffer(); InputSource inputSource; markup.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"); markup .append("<urid:fetch xmlns:urid=\"") .append(Namespace.URID.getURI()) .append("\" href=\"") .append(attributes.getHref()) .append("\""); if (attributes.getParse() != null) { markup.append(" parse=\"").append(attributes.getParse()).append("\""); } if (attributes.getEncoding() != null) { markup.append(" encoding=\"").append(attributes.getEncoding()).append("\""); } markup.append("/>"); if (logger.isDebugEnabled()) { logger.debug("Set up inclusion command as: " + markup.toString()); } inputSource = new InputSource(new StringReader(markup.toString())); // Set up and execute the pipeline to perform the required // inclusion MarinerPageContext pageContext = ContextInternals.getMarinerPageContext(context); XMLReader reader = MarlinSAXHelper.getXMLReader(context); reader.setContentHandler(MarlinSAXHelper.getContentHandler(context)); // @todo this is nasty: we assume that the reader is actually an XMLPipelineFilter XMLPipelineFilter filter = (XMLPipelineFilter) reader; XMLPipelineContext pipelineContext = filter.getPipelineContext(); // set the Base URI in the pipeline's context try { URL baseURI = pageContext.getAbsoluteURL(pageContext.getRequestURL(false)); if (logger.isDebugEnabled()) { logger.debug("Setting Base URI " + baseURI); } pipelineContext.pushBaseURI(baseURI.toExternalForm()); } catch (MalformedURLException e) { throw new PAPIException(e); } PipelineIntegrationUtilities.setUpIntegration( filter, pageContext.getCurrentElement(), context, pageContext.getCurrentOutputBuffer()); if (logger.isDebugEnabled()) { logger.debug("Executing inclusion"); } // Execute the inclusion try { reader.parse(inputSource); } catch (IOException e) { throw new PAPIException(e); } catch (SAXException e) { throw new PAPIException(e); } finally { PipelineIntegrationUtilities.tearDownIntegration(filter); } } if (logger.isDebugEnabled()) { logger.debug("Successful execution of inclusion"); } return CONTINUE_PROCESSING; } // javadoc inherited boolean hasMixedContent() { return false; } }