http://git-wip-us.apache.org/repos/asf/flex-blazeds/blob/8315f8fa/core/src/flex/messaging/util/RedeployManager.java ---------------------------------------------------------------------- diff --git a/core/src/flex/messaging/util/RedeployManager.java b/core/src/flex/messaging/util/RedeployManager.java deleted file mode 100644 index b14c812..0000000 --- a/core/src/flex/messaging/util/RedeployManager.java +++ /dev/null @@ -1,296 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package flex.messaging.util; - -import flex.messaging.FlexComponent; -import flex.messaging.config.ConfigMap; - -import java.io.File; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; - -/** - * This class watches for changes on files and forces a re-deploy by touching the specified files. - * - * - */ -public class RedeployManager implements FlexComponent -{ - private boolean enabled; - private long watchInterval; - private List watches; - private List touches; - - private ScheduledExecutorService redeployService; - private boolean started; - - //-------------------------------------------------------------------------- - // - // Constructor - // - //-------------------------------------------------------------------------- - - /** - * Constructs a new <code>RedeployManager</code> with default settings. - */ - public RedeployManager() - { - this(null); - } - - /** - * Constructs a new <code>RedeployManager</code> with the supplied thread - * factory. - * - * @param tf Thread factory to use for the scheduled service used. - */ - public RedeployManager(ThreadFactory tf) - { - if (tf == null) - tf = new MonitorThreadFactory(); - - enabled = false; - touches = new ArrayList(); - watchInterval = 20; - watches = new ArrayList(); - - redeployService = Executors.newSingleThreadScheduledExecutor(tf); - } - - //-------------------------------------------------------------------------- - // - // Initialize, validate, start, and stop methods. - // - //-------------------------------------------------------------------------- - - /** - * Implements FlexComponents.initialize. - * This is no-op for RedeployManager as it does not have an id and all - * its properties are directly settable. - */ - public void initialize(String id, ConfigMap properties) - { - // No-op - } - - /** - * Implements FlexComponent.start. - * Starts the <code>RedeployManager</code>. - */ - public void start() - { - if (!started && enabled) - { - redeployService.schedule(new RedeployTask(), 20 * 1000, TimeUnit.MILLISECONDS); - started = true; - } - } - - /** - * Stops the <code>RedeployManager</code>. - */ - public void stop() - { - if (started && enabled) - { - started = false; - } - redeployService.shutdownNow(); - } - - //-------------------------------------------------------------------------- - // - // Public Methods - // - //-------------------------------------------------------------------------- - - /** - * Returns whether redeploy is enabled or not. - * - * @return <code>true</code> if redeploy is enabled; otherwise <code>false</code>. - */ - public boolean isEnabled() - { - return enabled; - } - - /** - * Sets whether redeploy is enabled or not. - * - * @param enabled Whether redeploy is enabled or not. - */ - public void setEnabled(boolean enabled) - { - this.enabled = enabled; - } - - /** - * Implements FlexComponent.isStarted. - * Returns whether the RedeployManager is started or not. - * - * @return <code>true</code> if the component is started; otherwise <code>false</code>. - */ - public boolean isStarted() - { - return started; - } - - /** - * Returns the watch interval. - * - * @return The watch interval. - */ - public long getWatchInterval() - { - return watchInterval; - } - - /** - * Sets the watch interval. - * - * @param watchInterval The watch interval to set. - */ - public void setWatchInterval(long watchInterval) - { - this.watchInterval = watchInterval; - } - - /** - * Returns the list of watch files. - * - * @return The list of watch files. - */ - public List getWatchFiles() - { - return watches; - } - - /** - * Adds a watch file. Note that the watch file set with this method should - * not contain the context.root token. - * - * @param watch The watch file to add. - */ - public void addWatchFile(String watch) - { - watches.add(watch); - } - - /** - * Sets the list of watch files. Note that watch files set with this method - * should not contain contain the context.root token. - * - * @param watches The list of watch files to set. - */ - public void setWatchFiles(List watches) - { - this.watches = watches; - } - - /** - * Returns the list of touch files. - * - * @return The list of touch files. - */ - public List getTouchFiles() - { - return touches; - } - - /** - * Adds a touch file. Note that the touch file set with this method should - * not contain the context.root token. - * - * @param touch The touch file to add. - */ - public void addTouchFile(String touch) - { - touches.add(touch); - } - - /** - * Sets the list of touch files. Note that touch files set with this method - * should not contain the context.root token. - * - * @param touches The list of touch files to set. - */ - public void setTouchFiles(List touches) - { - this.touches = touches; - } - - /** - * Forces the redeployment. - */ - public void forceRedeploy() - { - Iterator iter = touches.iterator(); - while (iter.hasNext()) - { - String filename = (String)iter.next(); - File file = new File(filename); - if (file.exists() && (file.isFile() || file.isDirectory())) - { - file.setLastModified(System.currentTimeMillis()); - } - } - } - - //-------------------------------------------------------------------------- - // - // Nested Classes - // - //-------------------------------------------------------------------------- - - class MonitorThreadFactory implements ThreadFactory - { - public Thread newThread(Runnable r) - { - Thread t = new Thread(r); - t.setDaemon(true); - t.setName("RedeployManager"); - return t; - } - } - - class RedeployTask implements Runnable - { - public void run() - { - boolean redeploy = false; - - // check if any of the redeploy watches have changed - Iterator iter = watches.iterator(); - while (iter.hasNext() && !redeploy) - { - WatchedObject watched = (WatchedObject)iter.next(); - if (!watched.isUptodate()) - redeploy = true; - } - - if (redeploy) - forceRedeploy(); - else - redeployService.schedule(new RedeployTask(), watchInterval * 1000, TimeUnit.MILLISECONDS); - } - } -}
http://git-wip-us.apache.org/repos/asf/flex-blazeds/blob/8315f8fa/core/src/flex/messaging/util/SettingsReplaceUtil.java ---------------------------------------------------------------------- diff --git a/core/src/flex/messaging/util/SettingsReplaceUtil.java b/core/src/flex/messaging/util/SettingsReplaceUtil.java deleted file mode 100644 index 5edc4e0..0000000 --- a/core/src/flex/messaging/util/SettingsReplaceUtil.java +++ /dev/null @@ -1,369 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package flex.messaging.util; - -import flex.messaging.MessageException; -import flex.messaging.FlexContext; - -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -/** - * Methods for replacing tokens in config files - * {context.root}, {context-root}, {server.name}, {server-name}, {server.port}, {server-port}. - * - * - */ -public class SettingsReplaceUtil -{ - private static final int TOKEN_NOT_SUPPORTED = 10129; - private static final int TOKEN_NOT_SUPPORTED_ANY = 10130; - private static final int PARSE_ERROR_DYNAMIC_URL = 10131; - - public static final String SLASH_CONTEXT_PATH_TOKEN = "/{context.root}"; - public static final String CONTEXT_PATH_TOKEN = "{context.root}"; - public static final String CONTEXT_PATH_ALT_TOKEN = "{context-root}"; - public static final String SERVER_NAME_TOKEN = "{server.name}"; - public static final String SERVER_NAME_ALT_TOKEN = "{server-name}"; - public static final String SERVER_PORT_TOKEN = "{server.port}"; - public static final String SERVER_PORT_ALT_TOKEN = "{server-port}"; - - /** - * Replace {context.root} in the url string. - * @param url the url string - * @param contextPath the context path - * @return String the url string after replacement - */ - public static String replaceContextPath(String url, String contextPath) - { - String token = CONTEXT_PATH_TOKEN; - int contextIndex = url.indexOf(CONTEXT_PATH_ALT_TOKEN); - if (contextIndex != -1) - { - token = CONTEXT_PATH_ALT_TOKEN; - url = StringUtils.substitute(url, CONTEXT_PATH_ALT_TOKEN, CONTEXT_PATH_TOKEN); - } - contextIndex = url.indexOf(CONTEXT_PATH_TOKEN); - - if ((contextPath == null) && (contextIndex != -1)) - { - MessageException me = new MessageException(); - if (FlexContext.getHttpRequest() == null) - me.setMessage(TOKEN_NOT_SUPPORTED, "0", new Object[] {token}); - else - me.setMessage(TOKEN_NOT_SUPPORTED, new Object[] {token}); - throw me; - } - else if (contextPath != null) - { - if (contextIndex == 0) - { - url = contextPath + url.substring(CONTEXT_PATH_TOKEN.length()); - } - else if (contextIndex > 0) - { - // Avoid adding //contextPath to URLs that have a /{context.root} pattern - if (url.indexOf(SLASH_CONTEXT_PATH_TOKEN) != -1) - { - url = StringUtils.substitute(url, SLASH_CONTEXT_PATH_TOKEN, contextPath); - } - else - { - url = StringUtils.substitute(url, CONTEXT_PATH_TOKEN, contextPath); - } - } - } - - return url; - } - - public static String replaceAllTokensGivenServerName(String url, String contextPath, String serverName, - String serverPort, String serverProtocol) - { - if (url.startsWith("/")) - { - url = serverProtocol + "://{server.name}:{server.port}" + url; - } - url = SettingsReplaceUtil.replaceContextPath(url, contextPath); - - String token = SERVER_NAME_TOKEN; - int serverNameIndex = url.indexOf(SERVER_NAME_ALT_TOKEN); - if (serverNameIndex != -1) - { - token = SERVER_NAME_ALT_TOKEN; - url = StringUtils.substitute(url, SERVER_NAME_ALT_TOKEN, SERVER_NAME_TOKEN); - } - - serverNameIndex = url.indexOf(SERVER_NAME_TOKEN); - if ((serverName == null) && (serverNameIndex != -1)) - { - MessageException me = new MessageException(); - me.setMessage(TOKEN_NOT_SUPPORTED, new Object[] {token}); - throw me; - } - else if ((serverName != null) && (serverNameIndex != -1)) - { - url = StringUtils.substitute(url, SERVER_NAME_TOKEN, serverName); - } - - token = SERVER_PORT_TOKEN; - int serverPortIndex = url.indexOf(SERVER_PORT_ALT_TOKEN); - if (serverPortIndex != -1) - { - token = SERVER_PORT_ALT_TOKEN; - url = StringUtils.substitute(url, SERVER_PORT_ALT_TOKEN, SERVER_PORT_TOKEN); - } - - serverPortIndex = url.indexOf(SERVER_PORT_TOKEN); - if ((serverPort == null) && (serverPortIndex != -1)) - { - MessageException me = new MessageException(); - me.setMessage(TOKEN_NOT_SUPPORTED, new Object[] {token}); - throw me; - } - else if ((serverPort != null) && (serverPortIndex != -1)) - { - url = StringUtils.substitute(url, SERVER_PORT_TOKEN, serverPort); - } - - return updateIPv6(url); - } - - /** - * Replace all tokens in the urls. - * @param urls a list of urls - * @param contextPath the context path - * @return Set a set of urls after replacement - */ - public static Set replaceAllTokensCalculateServerName(List urls, String contextPath) - { - List contextParsedUrls = new ArrayList(urls.size()); - Set newURLs = new HashSet(urls.size()); - - // first replace context path - for (int i = 0; i < urls.size(); i++) - { - String url = (String)urls.get(i); - url = url.toLowerCase().trim(); - url = SettingsReplaceUtil.replaceContextPath(url, contextPath); - contextParsedUrls.add(url); - - } - // then replace {server.name} - replaceServerNameWithLocalHost(contextParsedUrls, newURLs); - - return newURLs; - } - - - /** - * Replace {server.name} a horribly complicated way. This is needed to support relative - * URLs. I would like for us to rethink this someday and find a better way to do this - * - * @param urls the list of urls to replace - * @param newURLs the set of new urls - */ - public static void replaceServerNameWithLocalHost(List urls, Set newURLs) - { - for (Iterator iterator = urls.iterator(); iterator.hasNext();) - { - String url = (String) iterator.next(); - url = url.toLowerCase().trim(); - - String token = SERVER_PORT_TOKEN; - int serverPortIndex = url.indexOf(SERVER_PORT_ALT_TOKEN); - if (serverPortIndex != -1) - { - token = SERVER_PORT_ALT_TOKEN; - url = StringUtils.substitute(url, SERVER_PORT_ALT_TOKEN, SERVER_PORT_TOKEN); - } - - serverPortIndex = url.indexOf(SERVER_PORT_TOKEN); - if (serverPortIndex != -1) - { - MessageException me = new MessageException(); - me.setMessage(TOKEN_NOT_SUPPORTED_ANY, new Object[] {token}); - throw me; - } - - if (url.indexOf(SERVER_NAME_ALT_TOKEN) != 0) - { - StringUtils.substitute(url, SERVER_NAME_ALT_TOKEN, SERVER_NAME_TOKEN); - } - - if (url.indexOf(SERVER_NAME_TOKEN) != 0) - { - - try - { - addLocalServerURL(url, "localhost", newURLs); - addLocalServerURL(url, "127.0.0.1", newURLs); - addLocalServerURL(url, "[::1]", newURLs); // for IPv6 - - InetAddress local = InetAddress.getLocalHost(); - addInetAddress(local, url, newURLs); - - // if we're using JDK 1.4 or higher, we use NetworkInterface to get the list of hostnames - // and IP addresses. - Enumeration e = NetworkInterface.getNetworkInterfaces(); - while (e.hasMoreElements()) - { - NetworkInterface address = (NetworkInterface)e.nextElement(); - Enumeration e2 = (Enumeration)address.getInetAddresses(); - while (e2.hasMoreElements()) - { - local = (InetAddress) e2.nextElement(); - addInetAddress(local, url, newURLs); - } - } - } - catch(Exception e) - { - MessageException me = new MessageException(); - me.setMessage(PARSE_ERROR_DYNAMIC_URL); - throw me; - } - } - else { - addParsedURL(url, newURLs); - } - } - } - - private static void addInetAddress(InetAddress local, String url, Set newURLs) throws Exception - { - String localHostAddress = local.getHostAddress(); - if (localHostAddress != null) - { - addLocalServerURL(url, localHostAddress, newURLs); - } - - String localHostName = local.getHostName(); - if (localHostName != null) - { - addLocalServerURL(url, localHostName, newURLs); - - InetAddress[] addrs = InetAddress.getAllByName(localHostName); - for (int i = 0; i < addrs.length; i++) - { - InetAddress addr = addrs[i]; - String hostName = addr.getHostName(); - if (! hostName.equals(localHostName)) - { - addLocalServerURL(url, hostName, newURLs); - } - String hostAddress = addr.getHostAddress(); - if (! hostAddress.equals(localHostAddress)) - { - addLocalServerURL(url, hostAddress, newURLs); - } - } - } - } - - private static void addLocalServerURL(String url, String sub, Set newURLs) - { - String toSub = null; - - // if ipv6, then add square brackets - if (sub.indexOf(":") != -1) - { - StringBuffer ipv6Sub = new StringBuffer("["); - ipv6Sub.append(sub); - ipv6Sub.append("]"); - toSub = ipv6Sub.toString(); - } - else - { - toSub = sub; - } - - String newUrl = StringUtils.substitute(url, SERVER_NAME_TOKEN, toSub); - addParsedURL(newUrl, newURLs); - } - - private static void addParsedURL(String url, Set newURLs) - { - if (! newURLs.contains(url)) - { - newURLs.add(updateIPv6(url)); - } - } - - /** - * Update IPv6 IP address. - * @param src the source IP address string - * @return String the updated IP address string - */ - public static String updateIPv6(String src) - { - // if the ip address has "[" and "]" then it's IPv6, check that it's long form as well - if ((src != null) && (src.indexOf('[') != -1) && (src.indexOf(']') != -1)) - { - // then, it's IPv6 and remove the square brackets and update to long form if required - int start = src.indexOf('['); - int end = src.indexOf(']'); - - StringBuffer updated = new StringBuffer(src.substring(0, start + 1)); - updated.append(updateToLongForm(src.substring(start + 1, end))); - updated.append(src.substring(end)); - - return updated.toString(); - } - else - { - return src; - } - } - - protected static String updateToLongForm(String src) - { - // Let's see if the short form is in use. - int numberOfTokens = 0; - int doubleColonIndex = src.indexOf("::", 0); - if (doubleColonIndex != -1) - { - String[] hexTokens = src.split("\\:"); - for (int i = 0; i < hexTokens.length; i++) - { - if (!hexTokens[i].equals("")) - numberOfTokens++; - } - - // Replace missing zeros - int numberOfMissingZeros = 8 - numberOfTokens; - if (numberOfMissingZeros > 0) - { - String replacement = ""; - if (!src.startsWith("::")) - replacement = ":"; - while (numberOfMissingZeros-- > 0) - replacement += "0:"; - src = src.replaceFirst("\\::", replacement); - } - } - - return src; - } - -} http://git-wip-us.apache.org/repos/asf/flex-blazeds/blob/8315f8fa/core/src/flex/messaging/util/TimeoutAbstractObject.java ---------------------------------------------------------------------- diff --git a/core/src/flex/messaging/util/TimeoutAbstractObject.java b/core/src/flex/messaging/util/TimeoutAbstractObject.java deleted file mode 100644 index 1314ef0..0000000 --- a/core/src/flex/messaging/util/TimeoutAbstractObject.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package flex.messaging.util; - -import java.util.concurrent.Future; - -/** - * This class defines the default implementation of TimeoutCapable, - * providing the default behavior for an object that is capable of timing - * out where that time out mechanism is managed by TimeoutManager. - * - * - */ -public abstract class TimeoutAbstractObject implements TimeoutCapable -{ - private long lastUse; - private volatile boolean timeoutCanceled; - private TimeoutManager timeoutManager; - private Runnable timeoutTask; - private Future timeoutFuture; - private long timeoutPeriod; - private final Object lock = new Object(); - - /** {@inheritDoc} */ - public void cancelTimeout() - { - if (timeoutCanceled) - return; - - boolean purged = false; - if ((timeoutManager != null) && (timeoutTask != null) && (timeoutFuture != null)) - purged = timeoutManager.unscheduleTimeout(this); - - if (!purged && (timeoutFuture != null)) - { - timeoutFuture.cancel(false); - } - - timeoutCanceled = true; - } - - /** {@inheritDoc} */ - public long getLastUse() - { - synchronized (lock) - { - return lastUse; - } - } - - /** - * Updates the time this object was last used. - * @param lastUse time this object was last used - */ - public void setLastUse(long lastUse) - { - synchronized (lock) - { - this.lastUse = lastUse; - } - } - - /** - * Updates the time this object was last used to be the current time. - */ - public void updateLastUse() - { - synchronized (lock) - { - this.lastUse = System.currentTimeMillis(); - } - } - - /** - * Returns manager responsible for this object. - * @return manager responsible for this object - */ - public TimeoutManager getTimeoutManager() - { - synchronized (lock) - { - return timeoutManager; - } - } - - /** - * Sets the manager responsible for this object. - * @param timeoutManager manager responsible for this object - */ - public void setTimeoutManager(TimeoutManager timeoutManager) - { - synchronized (lock) - { - this.timeoutManager = timeoutManager; - } - } - - /** - * Returns the runnable task that will be executed once this object times out. - * @return the runnable task that will be executed once this object times out - */ - public Runnable getTimeoutTask() - { - synchronized (lock) - { - return timeoutTask; - } - } - - /** - * Sets the runnable task that will be executed once this object times out. - * @param timeoutTask the runnable task that will be executed once this object times out - */ - public void setTimeoutTask(Runnable timeoutTask) - { - synchronized (lock) - { - this.timeoutTask = timeoutTask; - } - } - - /** - * Return the object encapsulating result of the execution of this object once it has timed out. - * @return the object encapsulating result of the execution of this object once it has timed out - */ - public Future getTimeoutFuture() - { - synchronized (lock) - { - return timeoutFuture; - } - } - - /** {@inheritDoc} */ - public void setTimeoutFuture(Future timeoutFuture) - { - synchronized (lock) - { - this.timeoutFuture = timeoutFuture; - } - } - - /** {@inheritDoc} */ - public long getTimeoutPeriod() - { - synchronized (lock) - { - return timeoutPeriod; - } - } - - /** - * Set the time to be elapsed before this object times out and its associated task gets executed. - * @param timeoutPeriod the time to be elapsed before this object times out and its associated task gets executed - */ - public void setTimeoutPeriod(long timeoutPeriod) - { - synchronized (lock) - { - this.timeoutPeriod = timeoutPeriod; - } - } -} http://git-wip-us.apache.org/repos/asf/flex-blazeds/blob/8315f8fa/core/src/flex/messaging/util/TimeoutCapable.java ---------------------------------------------------------------------- diff --git a/core/src/flex/messaging/util/TimeoutCapable.java b/core/src/flex/messaging/util/TimeoutCapable.java deleted file mode 100644 index e6226ae..0000000 --- a/core/src/flex/messaging/util/TimeoutCapable.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package flex.messaging.util; - -import java.util.concurrent.Future; - -/** - * This interface defines the contract for an object that can time - * out, where the timeout mechanism is provided by the TimeoutManager - * class. - * - * - */ -public interface TimeoutCapable -{ - /** - * Revoke the timeout task, removing it from future evaluation and execution. - */ - void cancelTimeout(); - - /** - * Determine the timestamp of this object's last use, where "last use" should - * denote all tasks that eliminate idleness. - * - * @return last used time - */ - long getLastUse(); - - /** - * Determine the time, in milliseconds, that this object is allowed to idle - * before having its timeout method invoked. - * - * @return timeout period - */ - long getTimeoutPeriod(); - - /** - * Set the Future used to provide access to the Runnable task that invokes - * the timeout method. A Future is used instead of a Runnable so that it may - * be canceled according to the Java concurrency standard. - * - * @param future Future used to provide access to the Runnable task that invokes the timeout method. - */ - void setTimeoutFuture(Future future); - - /** - * Inform the object that it has timed out. - */ - void timeout(); -} http://git-wip-us.apache.org/repos/asf/flex-blazeds/blob/8315f8fa/core/src/flex/messaging/util/TimeoutManager.java ---------------------------------------------------------------------- diff --git a/core/src/flex/messaging/util/TimeoutManager.java b/core/src/flex/messaging/util/TimeoutManager.java deleted file mode 100644 index 3c794d3..0000000 --- a/core/src/flex/messaging/util/TimeoutManager.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package flex.messaging.util; - -import flex.messaging.log.Log; -import flex.messaging.log.LogCategories; - -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; - -/** - * This class provides a means of managing TimeoutCapable objects. It leverages - * facilities in the the Java concurrency package to provide a common utility - * for scheduling timeout Futures and managing the underlying worker thread pools. - * - * - */ -public class TimeoutManager -{ - private static final String LOG_CATEGORY = LogCategories.TIMEOUT; - - private ScheduledThreadPoolExecutor timeoutService; - - /** - * Default constructor calls parameterized constructor will a null factory argument. - */ - public TimeoutManager() - { - this(null); - } - - /** - * Constructs a new TimeoutManager using the passed in factory for thread creation. - * and a single thread of the TimeoutManager. - * - * @param tf ThreadFactory - */ - public TimeoutManager(ThreadFactory tf) - { - this(tf, 1); - } - - /** - * Constructs a new TimeoutManager using the passe din factory for thread creation - * and the passed in number of threads for TimeoutManager to use. - * - * @param tf The ThreadFactory to use. - * @param numberOfThreads The number of threads for the ThreadFactory to use. - */ - public TimeoutManager(ThreadFactory tf, int numberOfThreads) - { - if (tf == null) - { - tf = new MonitorThreadFactory(); - } - if (numberOfThreads < 1) - numberOfThreads = 1; - timeoutService = new ScheduledThreadPoolExecutor(numberOfThreads, tf); - } - - /** - * Schedule a task to be executed in the future. - * - * @param t task to be executed at some future time - * @return a Future object that enables access to the value(s) returned by the task - */ - public Future scheduleTimeout(TimeoutCapable t) - { - Future future = null; - if (t.getTimeoutPeriod() > 0) - { - Runnable timeoutTask = new TimeoutTask(t); - future = timeoutService.schedule(timeoutTask, t.getTimeoutPeriod(), TimeUnit.MILLISECONDS); - t.setTimeoutFuture(future); - if (t instanceof TimeoutAbstractObject) - { - TimeoutAbstractObject timeoutAbstract = (TimeoutAbstractObject)t; - timeoutAbstract.setTimeoutManager(this); - timeoutAbstract.setTimeoutTask(timeoutTask); - } - if (Log.isDebug()) - Log.getLogger(LOG_CATEGORY).debug("TimeoutManager '" + System.identityHashCode(this) + "' has scheduled instance '" + - System.identityHashCode(t) + "' of type '" + t.getClass().getName() + "' to be timed out in " + t.getTimeoutPeriod() + " milliseconds. Task queue size: "+ timeoutService.getQueue().size()); - } - return future; - } - - /** - * Cancel the execution of a future task and remove all references to it. - * - * @param timeoutAbstract the task to be canceled - * @return true if cancellation were successful - */ - public boolean unscheduleTimeout(TimeoutAbstractObject timeoutAbstract) - { - Object toRemove = timeoutAbstract.getTimeoutFuture(); - /* - * In more recent versions of the backport, they are requiring that we - * pass in the Future returned by the schedule method. This should always - * implement Runnable even in 2.2 but I'm a little paranoid here so just - * to be sure, if we get a future which is not a runnable we go back to the old - * code which calls the remove on the instance we passed into the schedule method. - */ - if (!(toRemove instanceof Runnable)) - toRemove = timeoutAbstract.getTimeoutTask(); - if (timeoutService.remove((Runnable) toRemove)) - { - if (Log.isDebug()) - Log.getLogger(LOG_CATEGORY).debug("TimeoutManager '" + System.identityHashCode(this) + "' has removed the timeout task for instance '" + - System.identityHashCode(timeoutAbstract) + "' of type '" + timeoutAbstract.getClass().getName() + "' that has requested its timeout be cancelled. Task queue size: "+ timeoutService.getQueue().size()); - } - else - { - Future timeoutFuture = timeoutAbstract.getTimeoutFuture(); - timeoutFuture.cancel(false); // Don't interrupt it if it's running. - if (Log.isDebug()) - Log.getLogger(LOG_CATEGORY).debug("TimeoutManager '" + System.identityHashCode(this) + "' cancelling timeout task for instance '" + - System.identityHashCode(timeoutAbstract) + "' of type '" + timeoutAbstract.getClass().getName() + "' that has requested its timeout be cancelled. Task queue size: "+ timeoutService.getQueue().size()); - if (timeoutFuture.isDone()) - { - timeoutService.purge(); // Force the service to give up refs to task immediately rather than hanging on to them. - if (Log.isDebug()) - Log.getLogger(LOG_CATEGORY).debug("TimeoutManager '" + System.identityHashCode(this) + "' purged queue of any cancelled or completed tasks. Task queue size: "+ timeoutService.getQueue().size()); - } - } - - // to aggressively clean up memory remove the reference from the unscheduled timeout to its - // time out object - Object unscheduledTimeoutTask = timeoutAbstract.getTimeoutTask(); - if (unscheduledTimeoutTask != null && unscheduledTimeoutTask instanceof TimeoutTask) - ((TimeoutTask)timeoutAbstract.getTimeoutTask()).clearTimeoutCapable(); - - return true; - } - - /** - * Cancel all outstanding and any future tasks. - */ - public void shutdown() - { - timeoutService.shutdownNow(); - // shutdownNow() returns List<Runnable> for all unexecuted tasks - // but we ignore these because we're only queuing dependent tasks - // for timed execution and they can be safely discarded when the - // parent object goes away and shuts down the TimeoutManager it is using. - // Also, we may need to introduce an interface that encompasses - // using either a ScheduledThreadPoolExecutor or a CommonJ Timer; - // in the case of a CommonJ Timer only a stop() method is provided - // which does not return handles to any queued, unexecuted tasks. - } - - class MonitorThreadFactory implements ThreadFactory - { - public Thread newThread(Runnable r) - { - Thread t = new Thread(r); - t.setDaemon(true); - t.setName("TimeoutManager"); - return t; - } - } - - class TimeoutTask implements Runnable - { - private TimeoutCapable timeoutObject; - - - /** - * Removes the reference from this timeout task to the object that would - * have been timed out. This is useful for memory clean up when timeouts are unscheduled. - */ - public void clearTimeoutCapable() - { - timeoutObject = null; - } - - public TimeoutTask(TimeoutCapable timeoutObject) - { - this.timeoutObject = timeoutObject; - } - - public void run() - { - // Because of the weird clearTimeCapable() in the middle of timeout call, we got NPE in the debug log level. - // Now copy the reference to local varable - TimeoutCapable timeoutObject = this.timeoutObject; - long inactiveMillis = System.currentTimeMillis() - timeoutObject.getLastUse(); - if (inactiveMillis >= timeoutObject.getTimeoutPeriod()) - { - try - { - timeoutObject.timeout(); - - if (Log.isDebug()) - Log.getLogger(LOG_CATEGORY).debug("TimeoutManager '" + System.identityHashCode(TimeoutManager.this) + "' has run the timeout task for instance '" + - System.identityHashCode(timeoutObject) + "' of type '" + timeoutObject.getClass().getName() + "'. Task queue size: "+ timeoutService.getQueue().size()); - } - catch (Throwable t) - { - if (Log.isError()) - Log.getLogger(LOG_CATEGORY).error("TimeoutManager '" + System.identityHashCode(TimeoutManager.this) + "' encountered an error running the timeout task for instance '" + - System.identityHashCode(timeoutObject) + "' of type '" + timeoutObject.getClass().getName() + "'. Task queue size: "+ timeoutService.getQueue().size(), t); - } - } - else - { - // Reschedule timeout and store new Future for cancellation. - timeoutObject.setTimeoutFuture(timeoutService.schedule(this, (timeoutObject.getTimeoutPeriod()-inactiveMillis), TimeUnit.MILLISECONDS)); - if (Log.isDebug()) - Log.getLogger(LOG_CATEGORY).debug("TimeoutManager '" + System.identityHashCode(TimeoutManager.this) + "' has rescheduled a timeout for the active instance '" + - System.identityHashCode(timeoutObject) + "' of type '" + timeoutObject.getClass().getName() + "'. Task queue size: "+ timeoutService.getQueue().size()); - } - } - } -} http://git-wip-us.apache.org/repos/asf/flex-blazeds/blob/8315f8fa/core/src/flex/messaging/util/ToStringPrettyPrinter.java ---------------------------------------------------------------------- diff --git a/core/src/flex/messaging/util/ToStringPrettyPrinter.java b/core/src/flex/messaging/util/ToStringPrettyPrinter.java deleted file mode 100644 index 9f4b434..0000000 --- a/core/src/flex/messaging/util/ToStringPrettyPrinter.java +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package flex.messaging.util; - -import java.io.IOException; -import java.lang.reflect.Array; -import java.util.Collection; -import java.util.IdentityHashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.w3c.dom.Document; - -import flex.messaging.io.PropertyProxy; -import flex.messaging.io.PropertyProxyRegistry; -import flex.messaging.log.Log; - -/** - * Recursively convert an Object graph into a String - * for logging/debugging purposes. Cyclical references are - * handled by tracking known objects. - * - * TODO: Remove check for custom toString implementations... we - * should be able to extend the PrettyPrintable interface to handle - * any custom toString requirements without needing to actually call - * toString on a custom object. - */ -public class ToStringPrettyPrinter extends BasicPrettyPrinter -{ - private IdentityHashMap knownObjects; - private int knownObjectsCount; - - /** - * Default constructor. - */ - public ToStringPrettyPrinter() - { - super(); - } - - /** {@inheritDoc} */ - public String prettify(Object o) - { - try - { - knownObjects = new IdentityHashMap(); - knownObjectsCount = 0; - return super.prettify(o); - } - finally - { - knownObjects = null; - knownObjectsCount = 0; - } - } - - /** {@inheritDoc} */ - public Object copy() - { - return new ToStringPrettyPrinter(); - } - - protected void prettifyComplexType(Object o) - { - // Avoid circular references - if (!isKnownObject(o)) - { - StringBuffer header = new StringBuffer(); - - Class c = o.getClass(); - - if (hasCustomToStringMethod(c)) - { - trace.write(String.valueOf(o)); - } - else if (o instanceof Collection) - { - Collection col = ((Collection)o); - header.append(c.getName()).append(" (Collection size:").append(col.size()).append(")"); - trace.startArray(header.toString()); - - Iterator it = col.iterator(); - int i = 0; - while (it.hasNext()) - { - trace.arrayElement(i); - internalPrettify(it.next()); - trace.newLine(); - i++; - } - - trace.endArray(); - } - else if (c.isArray()) - { - Class componentType = c.getComponentType(); - int count = Array.getLength(o); - - header.append(componentType.getName()).append("[] (Array length:").append(count).append(")"); - trace.startArray(header.toString()); - - // Check whether it is primitive array case, we omit printing the content of primitive array - // To avoid cases like large byte array. - if (!componentType.isPrimitive()) - { - for (int i = 0; i < count; i++) - { - trace.arrayElement(i); - internalPrettify(Array.get(o, i)); - trace.newLine(); - } - } - - trace.endArray(); - } - else if (o instanceof Document) - { - try - { - String xml = XMLUtil.documentToString((Document)o); - trace.write(xml); - } - catch (IOException ex) - { - trace.write("(Document not printable)"); - } - } - else - { - PropertyProxy proxy = PropertyProxyRegistry.getProxy(o); - - if (o instanceof PrettyPrintable) - { - PrettyPrintable pp = (PrettyPrintable)o; - header.append(pp.toStringHeader()); - } - else - { - header.append(c.getName()); - if (o instanceof Map) - { - header.append(" (Map size:").append(((Map)o).size()).append(")"); - } - } - - trace.startObject(header.toString()); - - List propertyNames = proxy.getPropertyNames(); - if (propertyNames != null) - { - Iterator it = propertyNames.iterator(); - while (it.hasNext()) - { - String propName = (String)it.next(); - trace.namedElement(propName); - - Object value = null; - if (trace.nextElementExclude) - { - trace.nextElementExclude = false; - value = Log.VALUE_SUPRESSED; - } - else - { - if (o instanceof PrettyPrintable) - { - String customToString = ((PrettyPrintable)o).toStringCustomProperty(propName); - if (customToString != null) - { - value = customToString; - } - } - - - if (value == null) - { - value = proxy.getValue(propName); - } - } - - internalPrettify(value); - trace.newLine(); - } - } - - trace.endObject(); - } - } - } - - private boolean isKnownObject(Object o) - { - Object ref = knownObjects.get(o); - if (ref != null) - { - try - { - int refNum = ((Integer)ref).intValue(); - trace.writeRef(refNum); - } - catch (ClassCastException e) - { - // Ignore - } - } - else - { - rememberObject(o); - } - return (ref != null); - } - - private void rememberObject(Object o) - { - knownObjects.put(o, new Integer(knownObjectsCount++)); - } -} http://git-wip-us.apache.org/repos/asf/flex-blazeds/blob/8315f8fa/core/src/flex/messaging/util/Trace.java ---------------------------------------------------------------------- diff --git a/core/src/flex/messaging/util/Trace.java b/core/src/flex/messaging/util/Trace.java deleted file mode 100644 index 39a5604..0000000 --- a/core/src/flex/messaging/util/Trace.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package flex.messaging.util; - -import java.util.Date; - - -/** - * Primitive run-time tracing class - * - * Code as follows: - * if (Trace.foo) - * Trace.trace("trace msg"...); - * - * Enable as follows: - * java -Dtrace.foo -Dtrace.foo2 -Dtrace.foo3 or -Dtrace.all - * - * Special flags: - * -Dtrace.flex -- enables all tracing - * -Dtrace.foo -- enables tracing on foo subsystem - * -Dtrace.timeStamp -- timeStamp all output lines - * -Dtrace.caller -- print the Class:method caller - * -Dtrace.stackLines=10 -- print 10 stack lines - * -Dtrace.stackPrefix=java.lang -- print the stack up to java.lang - * - * Add new xxx members as desired. - * - * - */ - -public class Trace -{ - public static final boolean config = (System.getProperty("trace.config") != null); - - public static final boolean amf = (System.getProperty("trace.amf") != null); - public static final boolean remote = amf || (System.getProperty("trace.remote") != null); - public static final boolean ssl = (System.getProperty("trace.ssl") != null); - - public static final boolean rtmp = (System.getProperty("trace.rtmp") != null); - public static final boolean command = rtmp || (System.getProperty("trace.command") != null); - public static final boolean error = rtmp || (System.getProperty("trace.error") != null); - public static final boolean message = rtmp || (System.getProperty("trace.message") != null); - public static final boolean resolve = rtmp || (System.getProperty("trace.resolve") != null); - public static final boolean transport = rtmp || (System.getProperty("trace.transport") != null); - public static final boolean ack = rtmp || (System.getProperty("trace.ack") != null); - public static final boolean io = rtmp || (System.getProperty("trace.io") != null); - public static final boolean threadpool = rtmp || (System.getProperty("trace.threadpool") != null); - - // print just the stack caller - public static final boolean caller = (System.getProperty("trace.caller") != null); - // print stack up to the prefix - public static final String stackPrefix = System.getProperty("trace.stackPrefix"); - - // print this number of stack lines - public static int stackLines = 0; - static { - try - { - stackLines = Integer.parseInt(System.getProperty("trace.stackLines")); - } - catch (NumberFormatException e) - { - } - } - // print a timestamp with each line - public static final boolean timeStamp = (System.getProperty("trace.timeStamp") != null); - - /** - * Write the string as a line to the trace stream. If the - * "stack" property is enabled, then the caller's stack call - * is also shown in the date. - * - * @param str string to write to the trace stream - */ - public static void trace(String str) - { - if (timeStamp) - System.err.print(new Date()); - - if(caller) - System.err.print(ExceptionUtil.getCallAt(new Throwable(), 1) + " "); - - System.err.println(str); - - if (stackLines > 0) - System.err.println(ExceptionUtil.getStackTraceLines(new Throwable(), stackLines)); - else if (stackPrefix != null) - System.err.println(ExceptionUtil.getStackTraceUpTo(new Throwable(), stackPrefix)); - } -} - http://git-wip-us.apache.org/repos/asf/flex-blazeds/blob/8315f8fa/core/src/flex/messaging/util/URLDecoder.java ---------------------------------------------------------------------- diff --git a/core/src/flex/messaging/util/URLDecoder.java b/core/src/flex/messaging/util/URLDecoder.java deleted file mode 100644 index c240e83..0000000 --- a/core/src/flex/messaging/util/URLDecoder.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package flex.messaging.util; - -import java.io.UnsupportedEncodingException; - - -/** - * Utility class for URL decoding. - */ -public final class URLDecoder -{ - public static String decode(String s) - { - try - { - return decode(s, "UTF8"); - } - catch (UnsupportedEncodingException ex) - { - throw new IllegalArgumentException("UTF8"); - } - } - - public static String decode(String s, String enc) throws UnsupportedEncodingException - { - if (!needsDecoding(s)) - { - return s; - } - - int length = s.length(); - byte[] bytes = new byte[length]; - // FIXME: This needs to specify a character encoding (ASCII?) - s.getBytes(0, length, bytes, 0); - int k = 0; - length = bytes.length; - for (int i = 0; i < length; i++) - { - if (bytes[i] == '%') - { - while (bytes[i + 1] == '%') - { - i++; - } - if (i < length - 2) - { - bytes[k] = x2c(bytes, i); - i += 2; - } - else - { - throw new IllegalArgumentException(s); - } - } - else if (bytes[i] == '+') - { - bytes[k] = (byte)' '; - } - else - { - bytes[k] = bytes[i]; - } - k++; - } - - return new String(bytes, 0, k, enc); - } - - private static boolean needsDecoding(String s) - { - if (s == null) - { - return false; - } - - int length = s.length(); - - for (int i = 0; i < length; i++) - { - int c = (int)s.charAt(i); - if (c == '+' || c == '%') - { - return true; - } - } - - return false; - - } - - private static byte x2c(byte[] b, int i) - { - int result; - byte b1 = b[i + 1]; - byte b2 = b[i + 2]; - - // return Byte.parseByte("" + (char) b1 + (char) b2, 16); - - if (b1 < '0' || (b1 > 'F' && b1 < 'a') || b1 > 'f' || - b2 < '0' || (b2 > 'F' && b2 < 'a') || b2 > 'f') - { - throw new IllegalArgumentException("%" + (char)b1 + (char)b2); - } - - result = b1 >= 'A' ? (b1 & 0xdf) - 'A' + 10 : b1 - '0'; - result *= 16; - result += b2 >= 'A' ? (b2 & 0xdf) - 'A' + 10 : b2 - '0'; - return (byte)result; - } -} http://git-wip-us.apache.org/repos/asf/flex-blazeds/blob/8315f8fa/core/src/flex/messaging/util/URLEncoder.java ---------------------------------------------------------------------- diff --git a/core/src/flex/messaging/util/URLEncoder.java b/core/src/flex/messaging/util/URLEncoder.java deleted file mode 100644 index 65e1ffa..0000000 --- a/core/src/flex/messaging/util/URLEncoder.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package flex.messaging.util; - -import java.io.BufferedWriter; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.UnsupportedEncodingException; - -/** - * Utility class for URL encoding. - * - * - */ -public final class URLEncoder -{ - public static String charset = "UTF8"; - - private URLEncoder() - { - } - - public static String encode(String s) - { - try - { - return encode(s, charset); - } - catch (UnsupportedEncodingException ex) - { - throw new IllegalArgumentException(charset); - } - } - - public static String encode(String s, String enc) throws UnsupportedEncodingException - { - if (!needsEncoding(s)) - { - return s; - } - - int length = s.length(); - - StringBuffer out = new StringBuffer(length); - - ByteArrayOutputStream buf = new ByteArrayOutputStream(10); // why 10? w3c says so. - - BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(buf, enc)); - - for (int i = 0; i < length; i++) - { - int c = (int)s.charAt(i); - if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == ' ') - { - if (c == ' ') - { - c = '+'; - } - - toHex(out, buf.toByteArray()); - buf.reset(); - - out.append((char)c); - } - else - { - try - { - writer.write(c); - - if (c >= 0xD800 && c <= 0xDBFF && i < length - 1) - { - int d = (int)s.charAt(i + 1); - if (d >= 0xDC00 && d <= 0xDFFF) - { - writer.write(d); - i++; - } - } - - writer.flush(); - } - catch (IOException ex) - { - throw new IllegalArgumentException(s); - } - } - } - try - { - writer.close(); - } - catch (IOException ioe) - { - // Ignore exceptions on close. - } - - toHex(out, buf.toByteArray()); - - return out.toString(); - } - - private static void toHex(StringBuffer buffer, byte[] b) - { - for (int i = 0; i < b.length; i++) - { - buffer.append('%'); - - char ch = Character.forDigit((b[i] >> 4) & 0xF, 16); - if (Character.isLetter(ch)) - { - ch -= 32; - } - buffer.append(ch); - - ch = Character.forDigit(b[i] & 0xF, 16); - if (Character.isLetter(ch)) - { - ch -= 32; - } - buffer.append(ch); - } - } - - private static boolean needsEncoding(String s) - { - if (s == null) - return false; - - for (int i = 0; i < s.length(); i++) - { - int c = (int)s.charAt(i); - if (!(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9')) - return true; - // Otherwise, keep going - } - - return false; - } -} http://git-wip-us.apache.org/repos/asf/flex-blazeds/blob/8315f8fa/core/src/flex/messaging/util/URLEncoderUtil.java ---------------------------------------------------------------------- diff --git a/core/src/flex/messaging/util/URLEncoderUtil.java b/core/src/flex/messaging/util/URLEncoderUtil.java deleted file mode 100644 index 9b8433b..0000000 --- a/core/src/flex/messaging/util/URLEncoderUtil.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package flex.messaging.util; - -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; - -/** - * Utility class for URL encoding - * - * - */ -public class URLEncoderUtil -{ - /** - * Encode a URL into using the specified encoding string. - * - * @param s URL to encode - * @param encoding encoding string - * @return encoded URL - * @throws UnsupportedEncodingException Throws UnsupportedEncodingException - */ - public static String encode(String s, String encoding) - throws UnsupportedEncodingException - { - return URLEncoder.encode(s, encoding); - } -} http://git-wip-us.apache.org/repos/asf/flex-blazeds/blob/8315f8fa/core/src/flex/messaging/util/URLEncoderUtil.jsl ---------------------------------------------------------------------- diff --git a/core/src/flex/messaging/util/URLEncoderUtil.jsl b/core/src/flex/messaging/util/URLEncoderUtil.jsl deleted file mode 100644 index b1e30d4..0000000 --- a/core/src/flex/messaging/util/URLEncoderUtil.jsl +++ /dev/null @@ -1,40 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// -// Licensed to the Apache Software Foundation (ASF) under one or more -// contributor license agreements. See the NOTICE file distributed with -// this work for additional information regarding copyright ownership. -// The ASF licenses this file to You under the Apache License, Version 2.0 -// (the "License"); you may not use this file except in compliance with -// the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -//////////////////////////////////////////////////////////////////////////////// -package flex.messaging.util; - -import java.io.UnsupportedEncodingException; -import System.NotSupportedException; -import System.Text.Encoding; -import System.Web.HttpUtility; - -public class URLEncoderUtil -{ - public static String encode(String s, String encoding) - throws UnsupportedEncodingException - { - try - { - return HttpUtility.UrlEncode(s, Encoding.GetEncoding(encoding)); - } - catch (NotSupportedException notSupportedException) - { - throw new UnsupportedEncodingException(); - } - } -} http://git-wip-us.apache.org/repos/asf/flex-blazeds/blob/8315f8fa/core/src/flex/messaging/util/UUIDGenerator.java ---------------------------------------------------------------------- diff --git a/core/src/flex/messaging/util/UUIDGenerator.java b/core/src/flex/messaging/util/UUIDGenerator.java deleted file mode 100644 index cedba04..0000000 --- a/core/src/flex/messaging/util/UUIDGenerator.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package flex.messaging.util; - -/** - * A custom UUID generator can be set on MessageBroker in order to provide custom - * uuid generation for NIO-HTTP session cookie and FlexClient id. - */ -public interface UUIDGenerator -{ - /** - * Creates and returns a UUID. - * - * @return UUID. - */ - String createUUID(); -} http://git-wip-us.apache.org/repos/asf/flex-blazeds/blob/8315f8fa/core/src/flex/messaging/util/UserAgentManager.java ---------------------------------------------------------------------- diff --git a/core/src/flex/messaging/util/UserAgentManager.java b/core/src/flex/messaging/util/UserAgentManager.java deleted file mode 100644 index b02d375..0000000 --- a/core/src/flex/messaging/util/UserAgentManager.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package flex.messaging.util; - -import flex.messaging.client.UserAgentSettings; -import flex.messaging.config.ConfigMap; - -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Manages user agent information. - */ -public class UserAgentManager -{ - /** - * The name of the HTTP header that transports the user agent value. - */ - public static final String USER_AGENT_HEADER_NAME = "User-Agent"; - - /* - * Configuration constants - */ - private static final String KICKSTART_BYTES = "kickstart-bytes"; - private static final String MATCH_ON = "match-on"; - // max-streaming-connections-per-session is deprecated; use max-persistent-connections-per-session instead. - public static final String MAX_STREAMING_CONNECTIONS_PER_SESSION = "max-streaming-connections-per-session"; - public static final String MAX_PERSISTENT_CONNECTIONS_PER_SESSION = "max-persistent-connections-per-session"; - private static final String USER_AGENT = "user-agent"; - private static final String USER_AGENT_SETTINGS = "user-agent-settings"; - - /** - * Used to keep track of the mapping between user agent match strings and - * the settings object. - */ - private Map<String, UserAgentSettings> userAgentSettingsMap = new HashMap<String, UserAgentSettings>(); - - /** - * Default settings, where match="*". - */ - private UserAgentSettings defaultSettings; - - /** - * Given a match-on string, returns the settings for that user agent, or - * null if no user agent settings exist for that match-on string. - * - * @param matchOn The match-on string used to match a specific user agent. - * @return The settings for that user agent, or null if no user agent settings - * exist for that match-on string. - */ - public UserAgentSettings getUserAgentSettings(String matchOn) - { - return userAgentSettingsMap.get(matchOn); - } - - /** - * Returns the collection of user agent settings. - * Collection can be empty. - * - * @return The (possibly empty) collection of user agent settings. - */ - public Collection<UserAgentSettings> getUserAgentSettings() - { - return userAgentSettingsMap.values(); - } - - /** - * Puts a new user agent to the existing list of user agents. If an existing - * user agent with the same match-on property as the new user agent exists, - * it is simply overwritten. - * @param userAgent the UserAgentSettings - */ - public void putUserAgentSettings(UserAgentSettings userAgent) - { - userAgentSettingsMap.put(userAgent.getMatchOn(), userAgent); - } - - /** - * Removes the user agent with the same match-on property from the list of - * existing user agents. - * @param useAgent the UserAgentSettings object - */ - public void removeUserAgentSettings(UserAgentSettings userAgent) - { - if (userAgent != null) - userAgentSettingsMap.remove(userAgent.getMatchOn()); - } - - /** - * Set the default settings to return when there is no match found. - * @param settings the UserAgentSettings object - */ - public void setDefaultUserAgentSettings(UserAgentSettings settings) - { - defaultSettings = settings; - } - - /** - * Look for the best match (based on longest match) for a user agent. - * If no match is found, the default settings are returned if set. - * - * @param userAgent a user agent to look for - * @return settings or null if no match and no default. - * @see UserAgentManager#setDefaultUserAgentSettings(flex.messaging.client.UserAgentSettings) - */ - public UserAgentSettings match(String userAgent) - { - // Dearch for the longest match - if (userAgent != null && userAgentSettingsMap.size() > 0) - { - // Search for the best match based upon length. - int bestMatchLength = 0; - String matchedAgent = null; - for (String key : userAgentSettingsMap.keySet()) - { - if (userAgent.indexOf(key) != -1) - { - int matchLength = key.length(); - if (matchLength > bestMatchLength) - { - bestMatchLength = matchLength; - matchedAgent = key; - } - } - } - - if (matchedAgent != null) - return userAgentSettingsMap.get(matchedAgent); - } - - // Return default if we have one - return defaultSettings; - } - - /** - * Initializes the provided manager with settings from the property map. - * Sets default settings if it encounters a match="*" entry. - * - * @param properties configuration properties, possibly containing "user-agent-settings" element - * @param manager the UserAgentManager to configure - */ - public static void setupUserAgentManager(ConfigMap properties, UserAgentManager manager) - { - // Add default entries for user agents. - manager.putUserAgentSettings(UserAgentSettings.getAgent(UserAgentSettings.USER_AGENT_ANDROID)); - manager.putUserAgentSettings(UserAgentSettings.getAgent(UserAgentSettings.USER_AGENT_CHROME)); - manager.putUserAgentSettings(UserAgentSettings.getAgent(UserAgentSettings.USER_AGENT_FIREFOX)); - manager.putUserAgentSettings(UserAgentSettings.getAgent(UserAgentSettings.USER_AGENT_FIREFOX_1)); - manager.putUserAgentSettings(UserAgentSettings.getAgent(UserAgentSettings.USER_AGENT_FIREFOX_2)); - manager.putUserAgentSettings(UserAgentSettings.getAgent(UserAgentSettings.USER_AGENT_MSIE)); - manager.putUserAgentSettings(UserAgentSettings.getAgent(UserAgentSettings.USER_AGENT_MSIE_5)); - manager.putUserAgentSettings(UserAgentSettings.getAgent(UserAgentSettings.USER_AGENT_MSIE_6)); - manager.putUserAgentSettings(UserAgentSettings.getAgent(UserAgentSettings.USER_AGENT_MSIE_7)); - manager.putUserAgentSettings(UserAgentSettings.getAgent(UserAgentSettings.USER_AGENT_OPERA)); - manager.putUserAgentSettings(UserAgentSettings.getAgent(UserAgentSettings.USER_AGENT_OPERA_8)); - manager.putUserAgentSettings(UserAgentSettings.getAgent(UserAgentSettings.USER_AGENT_OPERA_10)); - manager.putUserAgentSettings(UserAgentSettings.getAgent(UserAgentSettings.USER_AGENT_SAFARI)); - - if (properties == null) - return; - - ConfigMap userAgents = properties.getPropertyAsMap(USER_AGENT_SETTINGS, null); - if (userAgents == null) - return; - - List userAgent = userAgents.getPropertyAsList(USER_AGENT, null); - if (userAgent == null || userAgent.size() == 0) - return; - - for (Object anUserAgent : userAgent) - { - ConfigMap agent = (ConfigMap)anUserAgent; - String matchOn = agent.getPropertyAsString(MATCH_ON, null); - if (matchOn == null) - continue; - - int kickstartBytes = agent.getPropertyAsInt(KICKSTART_BYTES, 0); - int connectionsPerSession = agent.getPropertyAsInt(MAX_PERSISTENT_CONNECTIONS_PER_SESSION, - agent.getPropertyAsInt(MAX_STREAMING_CONNECTIONS_PER_SESSION, UserAgentSettings.MAX_PERSISTENT_CONNECTIONS_DEFAULT)); - - UserAgentSettings ua = UserAgentSettings.getAgent(matchOn); - ua.setKickstartBytes(kickstartBytes); - ua.setMaxPersistentConnectionsPerSession(connectionsPerSession); - if (matchOn.equals("*")) - manager.setDefaultUserAgentSettings(ua); - else - manager.putUserAgentSettings(ua); - } - } - -} http://git-wip-us.apache.org/repos/asf/flex-blazeds/blob/8315f8fa/core/src/flex/messaging/util/WatchedObject.java ---------------------------------------------------------------------- diff --git a/core/src/flex/messaging/util/WatchedObject.java b/core/src/flex/messaging/util/WatchedObject.java deleted file mode 100644 index baa0471..0000000 --- a/core/src/flex/messaging/util/WatchedObject.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package flex.messaging.util; - -import java.io.File; -import java.io.FileNotFoundException; - -/** - * Used by redeployment manager to monitor for changes to the files. - * - * - */ -public class WatchedObject -{ - private String filename; - private long modified; - - /** - * Creates a watched object for the specified file. - * - * @param filename file to watch - * @throws FileNotFoundException when specified file could not be found - */ - public WatchedObject(String filename) throws FileNotFoundException - { - this.filename = filename; - File file = new File(filename); - - if (!file.isFile() && !file.isDirectory()) - { - throw new FileNotFoundException(); - } - this.modified = file.lastModified(); - } - - /** - * Returns true if the watched file has been modified since creation of this - * watched object or since the last call to this method. - * - * @return true if the watched file has been modified since creation of this - * watched object or since the last call to this method - */ - public boolean isUptodate() - { - boolean uptodate = true; - - long current = new File(filename).lastModified(); - - if (Math.abs(current - modified) > 1000) - { - uptodate = false; - } - - modified = current; - - return uptodate; - } -} http://git-wip-us.apache.org/repos/asf/flex-blazeds/blob/8315f8fa/core/src/flex/messaging/util/XMLUtil.java ---------------------------------------------------------------------- diff --git a/core/src/flex/messaging/util/XMLUtil.java b/core/src/flex/messaging/util/XMLUtil.java deleted file mode 100644 index e27149c..0000000 --- a/core/src/flex/messaging/util/XMLUtil.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package flex.messaging.util; - -import flex.messaging.MessageException; -import org.w3c.dom.Document; -import org.xml.sax.InputSource; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import java.io.IOException; -import java.io.StringReader; -import java.io.StringWriter; - -/** - * Utility class for converting strings to XML documents and - * vice versa. - * - * - */ -public class XMLUtil -{ - public static String INDENT_XML = "no"; - public static String OMIT_XML_DECLARATION = "yes"; - - private XMLUtil() - { - } - - /** - * Uses a TransformerFactory with an identity transformation to convert a - * Document into a String representation of the XML. - * - * @param document Document. - * @return An XML String. - * @throws IOException if an error occurs during transformation. - */ - public static String documentToString(Document document) throws IOException - { - String xml; - - try - { - DOMSource dom = new DOMSource(document); - StringWriter writer = new StringWriter(); - StreamResult output = new StreamResult(writer); - - // Use Transformer to serialize a DOM - TransformerFactory factory = TransformerFactory.newInstance(); - Transformer transformer = factory.newTransformer(); - - // No need for pretty printing - transformer.setOutputProperty(OutputKeys.INDENT, INDENT_XML); - - // XML Declarations unexpected whitespace for legacy AS XMLDocument type, - // so we always omit it. We can't tell whether one was present when - // constructing the Document in the first place anyway... - transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, OMIT_XML_DECLARATION); - - transformer.transform(dom, output); - - xml = writer.toString(); - } - catch (TransformerException te) - { - throw new IOException("Error serializing Document as String: " + te.getMessageAndLocation()); - } - return xml; - } - - /** - * Uses the current DocumentBuilderFactory to converts a String - * representation of XML into a Document. - * - * @param xml XML serialized as a String - * @return Document - */ - public static Document stringToDocument(String xml) - { - return stringToDocument(xml, true, false, false); - } - - /** - * Uses the current DocumentBuilderFactory to converts a String - * representation of XML into a Document. - * - * @param xml XML serialized as a String - * @param nameSpaceAware determines whether the constructed Document - * is name-space aware - * @return Document - */ - public static Document stringToDocument(String xml, boolean nameSpaceAware, boolean allowXmlDoctypeDeclaration, - boolean allowXmlExternalEntityExpansion) - { - ClassUtil.validateCreation(Document.class); - - Document document = null; - try - { - if (xml != null) - { - StringReader reader = new StringReader(xml); - InputSource input = new InputSource(reader); - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - - if(!allowXmlDoctypeDeclaration) - { - factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); - } - - if(!allowXmlExternalEntityExpansion) - { - // Disable local resolution of entities due to security issues - // See: https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing - factory.setFeature("http://xml.org/sax/features/external-general-entities", false); - factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); - factory.setXIncludeAware(false); - factory.setExpandEntityReferences(false); - } - - factory.setNamespaceAware(nameSpaceAware); - factory.setValidating(false); - DocumentBuilder builder = factory.newDocumentBuilder(); - - document = builder.parse(input); - } - } - catch (Exception ex) - { - throw new MessageException("Error deserializing XML type " + ex.getMessage()); - } - - return document; - } -}