public class JmsProducer extends DefaultProducer {
    private static final transient Log LOG = LogFactory.getLog(JmsProducer.class);
    RequestorAffinity affinity;
    private final JmsEndpoint endpoint;
    private JmsOperations inOnlyTemplate;
    private JmsOperations inOutTemplate;
    private UuidGenerator uuidGenerator;
    private DeferredRequestReplyMap deferredRequestReplyMap;
    private Requestor requestor;
    private AtomicBoolean started = new AtomicBoolean(false);

    private enum RequestorAffinity {
        PER_COMPONENT(0),
        PER_ENDPOINT(1),
        PER_PRODUCER(2);
        private int value;
        private RequestorAffinity(int value) {
            this.value = value;
        }
    };

    public JmsProducer(JmsEndpoint endpoint) {
        super(endpoint);
        this.endpoint = endpoint;
        JmsConfiguration c = endpoint.getConfiguration();
        affinity = RequestorAffinity.PER_PRODUCER;
        if (c.getReplyTo() != null) {
            if (c.getReplyToTempDestinationAffinity().equals(c.REPLYTO_TEMP_DEST_AFFINITY_PER_ENDPOINT)) {
                affinity = RequestorAffinity.PER_ENDPOINT;
            } else if (c.getReplyToTempDestinationAffinity().equals(c.REPLYTO_TEMP_DEST_AFFINITY_PER_COMPONENT)) {
                affinity = RequestorAffinity.PER_COMPONENT;
            }
        }
    }

    public long getRequestTimeout() {
        return endpoint.getRequestTimeout();
    }

    protected void doStart() throws Exception {
        super.doStart();
    }

    protected void testAndSetRequestor() throws RuntimeCamelException {
        if (!started.get()) {
            synchronized (this) {
                if (started.get()) {
                    return;
                }
                try {
                    JmsConfiguration c = endpoint.getConfiguration();
                    if (c.getReplyTo() != null) {
                        requestor = new PersistentReplyToRequestor(endpoint.getConfiguration(), endpoint
                            .getExecutorService());
                        requestor.start();
                    } else {
                        if (affinity == RequestorAffinity.PER_PRODUCER) {
                            requestor = new Requestor(endpoint.getConfiguration(), endpoint
                                .getExecutorService());
                            requestor.start();
                        } else if (affinity == RequestorAffinity.PER_ENDPOINT) {
                            requestor = endpoint.getRequestor();
                        } else if (affinity == RequestorAffinity.PER_COMPONENT) {
                            requestor = ((JmsComponent)endpoint.getComponent()).getRequestor();
                        }
                    }
                } catch (Exception e) {
                    throw new FailedToCreateProducerException(endpoint, e);
                }
                deferredRequestReplyMap = requestor.getDeferredRequestReplyMap(this);
                started.set(true);
            }
        }
    }

    protected void testAndUnsetRequestor() throws Exception  {
        if (started.get()) {
            synchronized (this) {
                if (!started.get()) {
                    return;
                }
                requestor.removeDeferredRequestReplyMap(this);
                if (affinity == RequestorAffinity.PER_PRODUCER) {
                    requestor.stop();
                }
                started.set(false);
            }
        }
    }

    protected void doStop() throws Exception {
        testAndUnsetRequestor();
        super.doStop();
    }

    public void process(final Exchange exchange) {
        final org.apache.camel.Message in = exchange.getIn();

        if (exchange.getPattern().isOutCapable()) {

            testAndSetRequestor();

            final Destination replyTo = requestor.getReplyTo();

            if (replyTo == null) {
                throw new RuntimeExchangeException("Failed to resolve replyTo destination", exchange);
            }

            final boolean msgIdAsCorrId = endpoint.getConfiguration().isUseMessageIDAsCorrelationID();
            String correlationId = in.getHeader("JMSCorrelationID", String.class);

            if (correlationId == null && !msgIdAsCorrId) {
                in.setHeader("JMSCorrelationID", getUuidGenerator().generateId());
            }

            final ValueHolder<FutureTask> futureHolder = new ValueHolder<FutureTask>();
            final DeferredMessageSentCallback callback = msgIdAsCorrId ? deferredRequestReplyMap.createDeferredMessageSentCallback() : null;

            final CamelJmsTemplate template = (CamelJmsTemplate)getInOutTemplate();
            template.send(endpoint.getDestination(), new MessageCreator() {
                public Message createMessage(Session session) throws JMSException {
                    Message message = endpoint.getBinding().makeJmsMessage(exchange, in, session);
                    message.setJMSReplyTo(replyTo);
                    requestor.setReplyToSelectorHeader(in, message);

                    FutureTask future = null;
                    future = (!msgIdAsCorrId)
                        ? requestor.getReceiveFuture(message.getJMSCorrelationID(), endpoint
                            .getRequestTimeout()) : requestor.getReceiveFuture(callback);

                    futureHolder.set(future);

                    if (LOG.isDebugEnabled()) {
                        LOG.debug(endpoint + " sending JMS message: " + message);
                    }
                    return message;
                }
            }, callback);

            setMessageId(exchange);

            long requestTimeout = endpoint.getConfiguration().getRequestTimeout();
            try {
                Message message = null;
                try {
                    if (requestTimeout < 0) {
                        message = (Message)futureHolder.get().get();
                    } else {
                        message = (Message)futureHolder.get().get(requestTimeout, TimeUnit.MILLISECONDS);
                    }
                } catch (InterruptedException e) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Future interupted: " + e, e);
                    }
                } catch (TimeoutException e) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Future timed out: " + e, e);
                    }
                }
                if (message != null) {
                    exchange.setOut(new JmsMessage(message, endpoint.getBinding()));
                    if (correlationId != null) {
                        message.setJMSCorrelationID(correlationId);
                        exchange.getOut(false).setHeader("JMSCorrelationID", correlationId);
                    }
                } else {
                    exchange.setException(new ExchangeTimedOutException(exchange, requestTimeout));
                }
            } catch (Exception e) {
                exchange.setException(e);
            }
        } else {
            getInOnlyTemplate().send(endpoint.getDestination(), new MessageCreator() {
                public Message createMessage(Session session) throws JMSException {
                    Message message = endpoint.getBinding().makeJmsMessage(exchange, in, session);
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(endpoint + " sending JMS message: " + message);
                    }
                    return message;
                }
            });

            setMessageId(exchange);
        }
    }

    protected void setMessageId(Exchange exchange) {
        if (!(exchange instanceof JmsExchange)) {
            return;
        }
        try {
            JmsExchange jmsExchange = JmsExchange.class.cast(exchange);
            JmsMessage out = jmsExchange.getOut(false);
            if (out != null) {
                out.setMessageId(out.getJmsMessage().getJMSMessageID());
            }
        } catch (JMSException e) {
            LOG.warn("Unable to retrieve JMSMessageID from outgoing JMS Message and "
                     + "set it into Camel's MessageId", e);
        }
    }

    /**
     * Preserved for backwards compatibility.
     *
     * @deprecated
     * @see #getInOnlyTemplate()
     */
    public JmsOperations getTemplate() {
        return getInOnlyTemplate();
    }

    public JmsOperations getInOnlyTemplate() {
        if (inOnlyTemplate == null) {
            inOnlyTemplate = endpoint.createInOnlyTemplate();
        }
        return inOnlyTemplate;
    }

    public void setInOnlyTemplate(JmsOperations inOnlyTemplate) {
        this.inOnlyTemplate = inOnlyTemplate;
    }

    public JmsOperations getInOutTemplate() {
        if (inOutTemplate == null) {
            inOutTemplate = endpoint.createInOutTemplate();
        }
        return inOutTemplate;
    }

    public void setInOutTemplate(JmsOperations inOutTemplate) {
        this.inOutTemplate = inOutTemplate;
    }

    public UuidGenerator getUuidGenerator() {
        if (uuidGenerator == null) {
            uuidGenerator = new UuidGenerator();
        }
        return uuidGenerator;
    }

    public void setUuidGenerator(UuidGenerator uuidGenerator) {
        this.uuidGenerator = uuidGenerator;

FUNC_DECL IF CALL TRY IF CALL ASSIGN CATCH IF VAR_DECL CALL LITERAL_ANCHOR CALL THROW_RAISE BINARY_OP RETURN CALL IF LITERAL_ANCHOR CALL CALL IF BINARY_OP CALL ASSIGN IF BINARY_OP CALL BINARY_OP CALL ASSIGN CALL CALL ASSIGN CALL ASSIGN CALL CALL CALL CALL

FUNC_DECL IF CALL IF IF CALL BINARY_OP CALL CALL LITERAL_ANCHOR RETURN CALL

FUNC_DECL IF VAR_DECL PARAM BINARY_OP ASSIGN ASSIGN IF LITERAL_ANCHOR CALL CALL IF CALL CALL CALL CALL ASSIGN ASSIGN


public class FileConsumer extends ScheduledPollConsumer<FileExchange> {
    private static final transient Log LOG = LogFactory.getLog(FileConsumer.class);

    private FileEndpoint endpoint;
    private ConcurrentHashMap<File, File> filesBeingProcessed = new ConcurrentHashMap<File, File>();
    private ConcurrentHashMap<File, Long> fileSizes = new ConcurrentHashMap<File, Long>(new LRUCache(1000));
    private ConcurrentHashMap<File, Long> noopMap = new ConcurrentHashMap<File, Long>(new LRUCache(1000));

    private long lastPollTime;
    private int unchangedDelay;
    private boolean unchangedSize;
    private boolean generateEmptyExchangeWhenIdle;
    private boolean alwaysConsume;

    private boolean recursive;
    private String regexPattern = "";
    private boolean exclusiveReadLock = true;

    public FileConsumer(final FileEndpoint endpoint, Processor processor) {
        super(endpoint, processor);
        this.endpoint = endpoint;
    }

    protected synchronized void poll() throws Exception {
        int rc = pollFileOrDirectory(endpoint.getFile(), true);

        if (rc == 0 && generateEmptyExchangeWhenIdle) {
            final FileExchange exchange = endpoint.createExchange((File)null);
            getAsyncProcessor().process(exchange, new AsyncCallback() {
                public void done(boolean sync) {
                }
            });
        }

        lastPollTime = System.currentTimeMillis();
    }

    /**
     * Pools the given file or directory for files to process.
     *
     * @param fileOrDirectory  file or directory
     * @param processDir  recursive
     * @return the number of files processed or being processed async.
     */
    protected int pollFileOrDirectory(File fileOrDirectory, boolean processDir) {
        if (!fileOrDirectory.isDirectory()) {
            return pollFile(fileOrDirectory);
        } else if (processDir) {
            int rc = 0;
            if (isValidFile(fileOrDirectory)) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Polling directory " + fileOrDirectory);
                }
                File[] files = fileOrDirectory.listFiles();
                for (File file : files) {
                }
            }
            return rc;
        } else {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Skipping directory " + fileOrDirectory);
            }
            return 0;
        }
    }

    /**
     * Polls the given file
     *
     * @param target  the file
     * @return returns 1 if the file was processed, 0 otherwise.
     */
    protected int pollFile(final File target) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Polling file: " + target);
        }

        if (!target.exists()) {
            return 0;
        }
        if (!isValidFile(target)) {
            return 0;
        }
        if (!endpoint.isNoop()) {
            if (filesBeingProcessed.contains(target)) {
                return 1;
            }
            filesBeingProcessed.put(target, target);
        }

        final FileProcessStrategy processStrategy = endpoint.getFileStrategy();
        final FileExchange exchange = endpoint.createExchange(target);

        endpoint.configureMessage(target, exchange.getIn());
        try {
            if (exclusiveReadLock) {
                acquireExclusiveReadLock(target);
            }

            if (LOG.isDebugEnabled()) {
                LOG.debug("About to process file: " + target + " using exchange: " + exchange);
            }
            if (processStrategy.begin(endpoint, exchange, target)) {

                getAsyncProcessor().process(exchange, new AsyncCallback() {
                    public void done(boolean sync) {
                        final File file = exchange.getFile();
                        boolean failed = exchange.isFailed();
                        boolean handled = DeadLetterChannel.isFailureHandled(exchange);

                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Done processing file: " + file + ". Status is: " + (failed ? "failed: " + failed + ", handled by failure processor: " + handled : "processed OK"));
                        }

                        boolean committed = false;
                        try {
                            if (!failed || handled) {
                                processStrategyCommit(processStrategy, exchange, file, handled);
                                committed = true;
                            } else {
                                handleException(exchange.getException());
                            }
                        } finally {
                            if (!committed) {
                                processStrategyRollback(processStrategy, exchange, file);
                            }
                            filesBeingProcessed.remove(file);
                        }
                    }
                });

            } else {
                LOG.warn(endpoint + " can not process file: " + target);
            }
        } catch (Throwable e) {
            handleException(e);
        }

        return 1;
    }

    /**
     * Acquires exclusive read lock to the given file. Will wait until the lock is granted.
     * After granting the read lock it is realeased, we just want to make sure that when we start
     * consuming the file its not currently in progress of being written by third party.
     */
    protected void acquireExclusiveReadLock(File file) throws IOException {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Waiting for exclusive read lock to file: " + file);
        }

        FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
        try {
            FileLock lock = channel.lock();
            if (LOG.isTraceEnabled()) {
                LOG.trace("Acquired exclusive read lock: " + lock + " to file: " + file);
            }
            lock.release();
        } finally {
            ObjectHelper.close(channel, "FileConsumer during acquiring of exclusive read lock", LOG);
        }
    }

    /**
     * Strategy when the file was processed and a commit should be executed.
     *
     * @param processStrategy   the strategy to perform the commit
     * @param exchange          the exchange
     * @param file              the file processed
     * @param failureHandled    is <tt>false</tt> if the exchange was processed succesfully, <tt>true</tt> if
     * an exception occured during processing but it was handled by the failure processor (usually the
     * DeadLetterChannel).
     */
    protected void processStrategyCommit(FileProcessStrategy processStrategy, FileExchange exchange,
                                         File file, boolean failureHandled) {
        try {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Committing file strategy: " + processStrategy + " for file: " + file + (failureHandled ? " that was handled by the failure processor." : ""));
            }
            processStrategy.commit(endpoint, exchange, file);
        } catch (Exception e) {
            LOG.warn("Error committing file strategy: " + processStrategy, e);
            handleException(e);
        }
    }

    /**
     * Strategy when the file was not processed and a rollback should be executed.
     *
     * @param processStrategy   the strategy to perform the commit
     * @param exchange          the exchange
     * @param file              the file processed
     */
    protected void processStrategyRollback(FileProcessStrategy processStrategy, FileExchange exchange, File file) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Rolling back file strategy: " + processStrategy + " for file: " + file);
        }
        processStrategy.rollback(endpoint, exchange, file);
    }

    protected boolean isValidFile(File file) {
        boolean result = false;
        if (file != null && file.exists()) {
            if (isMatched(file) && (alwaysConsume || isChanged(file))) {
                result = true;
            }
        }
        return result;
    }

    protected boolean isChanged(File file) {
        if (file == null) {
            return false;
        } else if (file.isDirectory()) {
            return true;
        } else {
            boolean lastModifiedCheck = false;
            long modifiedDuration = 0;
            if (getUnchangedDelay() > 0) {
                modifiedDuration = System.currentTimeMillis() - file.lastModified();
                lastModifiedCheck = modifiedDuration >= getUnchangedDelay();
            }

            long fileModified = file.lastModified();
            Long previousModified = noopMap.get(file);
            noopMap.put(file, fileModified);
            if (previousModified == null || fileModified > previousModified) {
                lastModifiedCheck = true;
            }

            boolean sizeCheck = false;
            long sizeDifference = 0;
            if (isUnchangedSize()) {
                Long value = fileSizes.get(file);
                if (value == null) {
                    sizeCheck = true;
                } else {
                    sizeCheck = file.length() != value;
                }
            }

            boolean answer = lastModifiedCheck || sizeCheck;

            if (LOG.isDebugEnabled()) {
                LOG.debug("file:" + file + " isChanged:" + answer + " " + "sizeCheck:" + sizeCheck + "("
                          + sizeDifference + ") " + "lastModifiedCheck:" + lastModifiedCheck + "("
                          + modifiedDuration + ")");
            }

            if (isUnchangedSize()) {
                if (answer) {
                    fileSizes.put(file, file.length());
                } else {
                    fileSizes.remove(file);
                }
            }

            return answer;
        }
    }

    protected boolean isMatched(File file) {
        String name = file.getName();

        if (name.startsWith(".")) {
            return false;
        }
        if (name.endsWith(FileEndpoint.DEFAULT_LOCK_FILE_POSTFIX)) {
            return false;
        }

        if (file.isDirectory()) {
            return true;
        }

        if (regexPattern != null && regexPattern.length() > 0) {
            if (!name.matches(regexPattern)) {
                return false;
            }
        }

        if (endpoint.getExcludedNamePrefix() != null) {
            if (name.startsWith(endpoint.getExcludedNamePrefix())) {
                return false;
            }
        }
        String[] prefixes = endpoint.getExcludedNamePrefixes();
        if (prefixes != null) {
            for (String prefix : prefixes) {
                if (name.startsWith(prefix)) {
                    return false;
                }
            }
        }
        if (endpoint.getExcludedNamePostfix() != null) {
            if (name.endsWith(endpoint.getExcludedNamePostfix())) {
                return false;
            }
        }
        String[] postfixes = endpoint.getExcludedNamePostfixes();
        if (postfixes != null) {
            for (String postfix : postfixes) {
                if (name.endsWith(postfix)) {
                    return false;
                }
            }
        }

        return true;
    }

    public boolean isRecursive() {
        return this.recursive;
    }

    public void setRecursive(boolean recursive) {
        this.recursive = recursive;
    }

    public String getRegexPattern() {
        return this.regexPattern;
    }

    public void setRegexPattern(String regexPattern) {
        this.regexPattern = regexPattern;
    }

    public boolean isGenerateEmptyExchangeWhenIdle() {
        return generateEmptyExchangeWhenIdle;
    }

    /**
     * @deprecated will be removed in Camel 2.0
     */
    public void setGenerateEmptyExchangeWhenIdle(boolean generateEmptyExchangeWhenIdle) {
        this.generateEmptyExchangeWhenIdle = generateEmptyExchangeWhenIdle;
    }

    public int getUnchangedDelay() {
        return unchangedDelay;
    }

    /**
     * @deprecated will be removed in Camel 2.0
     */
    public void setUnchangedDelay(int unchangedDelay) {
        this.unchangedDelay = unchangedDelay;
    }

    public boolean isUnchangedSize() {
        return unchangedSize;
    }

    /**
     * @deprecated will be removed in Camel 2.0
     */
    public void setUnchangedSize(boolean unchangedSize) {
        this.unchangedSize = unchangedSize;
    }

    public boolean isExclusiveReadLock() {
        return exclusiveReadLock;
    }

    public void setExclusiveReadLock(boolean exclusiveReadLock) {
        this.exclusiveReadLock = exclusiveReadLock;
    }

    public boolean isAlwaysConsume() {
        return alwaysConsume;
    }

    /**
     * @deprecated will be removed in Camel 2.0 (not needed when we get rid of last polltimestamp)
     */
    public void setAlwaysConsume(boolean alwaysConsume) {
        this.alwaysConsume = alwaysConsume;
    }

    public boolean isTimestamp() {
        return !alwaysConsume;
    }

    /**
     * @deprecated will be removed in Camel 2.0 (not needed when we get rid of last polltimestamp)
     */
    public void setTimestamp(boolean timestamp) {
        this.alwaysConsume = !timestamp;

FUNC_DECL IF PARAM PARAM IF CALL RETURN RETURN IF RETURN IF VAR_DECL CALL LITERAL_ANCHOR CALL CALL LOOP VAR_DECL IF LITERAL_ANCHOR CALL CALL BINARY_OP CALL LITERAL_ANCHOR CALL BINARY_OP LITERAL_ANCHOR


public class ExtensionNamespaceSupport
{
  String m_namespace = null;
  String m_handlerClass = null;
  Class [] m_sig = null;
  Object [] m_args = null;

  public ExtensionNamespaceSupport(String namespace,
                                   String handlerClass,
                                   Object[] constructorArgs)
  {
    m_namespace = namespace;
    m_handlerClass = handlerClass;
    m_args = constructorArgs;
    m_sig = new Class[m_args.length];
    for (int i = 0; i < m_args.length; i++)
    {
      if (m_args[i] != null)
      {
        m_sig = null;
        break;
      }
    }
  }

  public String getNamespace()
  {
    return m_namespace;
  }

  /**
   * Launch the ExtensionHandler that this ExtensionNamespaceSupport object defines.
   */
  public ExtensionHandler launch()
    throws TransformerException
  {
    ExtensionHandler handler = null;
    try
    {
      Class cl = ExtensionHandler.getClassForName(m_handlerClass);
      Constructor con = null;
      if (m_sig != null)
        con = cl.getConstructor(m_sig);
      {
        Constructor[] cons = cl.getConstructors();
        for (int i = 0; i < cons.length; i ++)
        {
          if (cons[i].getParameterTypes().length == m_args.length)
          {
            con = cons[i];
            break;
          }
        }
      }
      if (con != null)
        handler = (ExtensionHandler)con.newInstance(m_args);
      else
        throw new TransformerException("ExtensionHandler constructor not found");
    }
    catch (Exception e)
    {
      throw new TransformerException(e);
    }
    return handler;


public class ExpPtg
    extends Ptg
{
    private final static int  SIZE = 5;
    public final static short sid  = 0x1;
	 private	byte[] existing = null;

    /** Creates new ExpPtg */

    public ExpPtg()
    {
    }

    /** Creates new ExpPtg */

    public ExpPtg(byte [] array, int offset)
    {
    	existing = new byte[this.getSize()];
    	System.arraycopy(array, offset, existing, 0, this.getSize());
    }

    public void writeBytes(byte [] array, int offset)
    {
    	if (existing != null) {
			System.arraycopy(existing, 0, array, offset, existing.length);
    	}
    }

    public int getSize()
    {
        return SIZE;
    }

    public String toFormulaString(Workbook book)
    {
        return "NO IDEA SHARED FORMULA EXP PTG";
    }

    public byte getDefaultOperandClass() {return Ptg.CLASS_VALUE;}

    public Object clone() {
		if (this.existing == null) throw new RuntimeException("NO IDEA SHARED FORMULA EXP PTG");

    	return new ExpPtg(this.existing, 0);

    public int getSize()
    {
        return SIZE;

FUNC_DECL PARAM PARAM CALL ASSIGN LITERAL_ANCHOR CALL CALL


org.gjt.sp.util.SyntaxUtilities

public class SyntaxUtilities
{
	public static IPropertyManager propertyManager;

	//{{{ getColorHexString() method
	/**
	 * Converts a color object to its hex value. The hex value
	 * prefixed is with `#', for example `#ff0088'.
	 * @param c The color object
	 * @since jEdit 4.3pre13
	 */
	public static String getColorHexString(Color c)
	{
		String colString = Integer.toHexString(c.getRGB() & 0xffffff);
		return "#000000".substring(0,7 - colString.length()).concat(colString);
	} //}}}

	//{{{ parseColor() method
	/**
	 * @since jEdit 4.3pre13
	 */
	public static Color parseColor(String name, Color defaultColor)
	{
		if(name == null || name.length() == 0)
			return defaultColor;
		else if(name.charAt(0) == '#')
		{
			try
			{
				return Color.decode(name);
			}
			catch(NumberFormatException nf)
			{
				return defaultColor;
			}
		}
		else if("red".equals(name))
			return Color.red;
		else if("green".equals(name))
			return Color.green;
		else if("blue".equals(name))
			return Color.blue;
		else if("yellow".equals(name))
			return Color.yellow;
		else if("orange".equals(name))
			return Color.orange;
		else if("white".equals(name))
			return Color.white;
		else if("lightGray".equals(name))
			return Color.lightGray;
		else if("gray".equals(name))
			return Color.gray;
		else if("darkGray".equals(name))
			return Color.darkGray;
		else if("black".equals(name))
			return Color.black;
		else if("cyan".equals(name))
			return Color.cyan;
		else if("magenta".equals(name))
			return Color.magenta;
		else if("pink".equals(name))
			return Color.pink;
		else
			return defaultColor;
	} //}}}

	//{{{ parseStyle() method
	/**
	 * Converts a style string to a style object.
	 * @param str The style string
	 * @param family Style strings only specify font style, not font family
	 * @param size Style strings only specify font style, not font family
	 * @param color If false, the styles will be monochrome
	 * @param defaultFgColor Default foreground color (if not specified in style string)
	 * @exception IllegalArgumentException if the style is invalid
	 * @since jEdit 4.3pre17
	 */
	public static SyntaxStyle parseStyle(String str, String family, int size,
		boolean color, Color defaultFgColor)
		throws IllegalArgumentException
	{
		Color fgColor = defaultFgColor;
		Color bgColor = null;
		boolean italic = false;
		boolean bold = false;
		StringTokenizer st = new StringTokenizer(str);
		while(st.hasMoreTokens())
		{
			String s = st.nextToken();
			if(s.startsWith("color:"))
			{
				if(color)
					fgColor = parseColor(s.substring(6), Color.black);
			}
			else if(s.startsWith("bgColor:"))
			{
				if(color)
					bgColor = parseColor(s.substring(8), null);
			}
			else if(s.startsWith("style:"))
			{
				for(int i = 6; i < s.length(); i++)
				{
					if(s.charAt(i) == 'i')
						italic = true;
					else if(s.charAt(i) == 'b')
						bold = true;
					else
						throw new IllegalArgumentException(
								"Invalid style: " + s);
				}
			}
			else
				throw new IllegalArgumentException(
						"Invalid directive: " + s);
		}
		return new SyntaxStyle(fgColor,bgColor,
				new Font(family,
						(italic ? Font.ITALIC : 0) | (bold ? Font.BOLD : 0),
						size));
	} //}}}

	//{{{ parseStyle() method
	/**
	 * Converts a style string to a style object.
	 * @param str The style string
	 * @param family Style strings only specify font style, not font family
	 * @param size Style strings only specify font style, not font family
	 * @param color If false, the styles will be monochrome
	 * @exception IllegalArgumentException if the style is invalid
	 * @since jEdit 4.3pre13
	 */
	public static SyntaxStyle parseStyle(String str, String family, int size,
		boolean color)
		throws IllegalArgumentException
	{
		return parseStyle(str, family, size, color, Color.black);
	} //}}}

	//{{{ loadStyles() methods
	/**
	 * Loads the syntax styles from the properties, giving them the specified
	 * base font family and size.
	 * @param family The font family
	 * @param size The font size
	 * @since jEdit 4.3pre13
	 */
	public static SyntaxStyle[] loadStyles(String family, int size)
	{
		return loadStyles(family,size,true);
	}

	/**
	 * Loads the syntax styles from the properties, giving them the specified
	 * base font family and size.
	 * @param family The font family
	 * @param size The font size
	 * @param color If false, the styles will be monochrome
	 * @since jEdit 4.3pre13
	 */
	public static SyntaxStyle[] loadStyles(String family, int size, boolean color)
	{
		SyntaxStyle[] styles = new SyntaxStyle[Token.ID_COUNT];

		// start at 1 not 0 to skip Token.NULL
		for(int i = 1; i < styles.length; i++)
		{
			try
			{
				String styleName = "view.style."
					+ Token.tokenToString((byte)i)
					.toLowerCase(Locale.ENGLISH);
				styles[i] = parseStyle(
					propertyManager.getProperty(styleName),
					family,size,color);
			}
			catch(Exception e)
			{
				Log.log(Log.ERROR,StandardUtilities.class,e);
			}
		}

		return styles;
	} //}}}

	private SyntaxUtilities(){}

FUNC_DECL IF PARAM PARAM IF RETURN BINARY_OP IF BINARY_OP BINARY_OP BINARY_OP IF RETURN LITERAL_ANCHOR TRY LITERAL_ANCHOR CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR IF RETURN LITERAL_ANCHOR CALL CATCH RETURN LITERAL_ANCHOR IF RETURN LITERAL_ANCHOR CALL RETURN CALL IF RETURN LITERAL_ANCHOR CALL IF RETURN LITERAL_ANCHOR CALL IF RETURN LITERAL_ANCHOR CALL IF RETURN LITERAL_ANCHOR CALL IF RETURN LITERAL_ANCHOR CALL IF RETURN LITERAL_ANCHOR CALL IF RETURN LITERAL_ANCHOR CALL IF RETURN LITERAL_ANCHOR CALL IF RETURN LITERAL_ANCHOR CALL RETURN RETURN LITERAL_ANCHOR CALL CALL

FUNC_DECL RETURN PARAM PARAM PARAM PARAM CALL

FUNC_DECL RETURN PARAM PARAM CALL LITERAL_ANCHOR


org.gjt.sp.util.IntegerArray

public class IntegerArray
{
	//{{{ IntegerArray constructor
	public IntegerArray()
	{
		this(2000);
	} //}}}

	//{{{ IntegerArray constructor
	public IntegerArray(int initialSize)
	{
		array = new int[initialSize];
	} //}}}

	//{{{ add() method
	public void add(int num)
	{
		if(len >= array.length)
		{
			int[] arrayN = new int[len * 2];
			System.arraycopy(array,0,arrayN,0,len);
			array = arrayN;
		}

		array[len++] = num;
	} //}}}

	//{{{ get() method
	public final int get(int index)
	{
		return array[index];
	} //}}}

	//{{{ getSize() method
	public final int getSize()
	{
		return len;
	} //}}}

	//{{{ setSize() method
	public final void setSize(int len)
	{
		this.len = len;
	} //}}}

	//{{{ clear() method
	public final void clear()
	{
		len = 0;
	} //}}}

	//{{{ getArray() method
	public int[] getArray()
	{
		return array;
	} //}}}

	//{{{ Private members
	private int[] array;
	private int len;

	public final void clear()
	{
		len = 0;

	public int[] getArray()
	{
		return array;


org.apache.poi.util.BlockingInputStream

public class BlockingInputStream
      extends InputStream
{
      protected InputStream is;

      public BlockingInputStream(InputStream is)
      {
          this.is = is;
      }

      public int available()
        throws IOException
      {
          return is.available();
      }

      public void close()
        throws IOException
      {
          is.close();
      }

      public void mark(int readLimit)
      {
          is.mark(readLimit);
      }

      public boolean markSupported()
      {
          return is.markSupported();
      }

      public int read()
        throws IOException
      {
          return is.read();
      }

      /**
       * We had to revert to byte per byte reading to keep
       * with slow network connections on one hand, without
       * missing the end-of-file.
       * This is the only method that does its own thing in this class
       *    everything else is delegated to aggregated stream.
       * THIS IS A BLOCKING BLOCK READ!!!
       */
      public int read(byte[] bf)
        throws IOException
      {

          int i = 0;
          int b = 4611;
          while ( i < bf.length )
          {
              b = is.read();
              if ( b == -1 )
                  break;
              bf[i++] = (byte) b;
          }
          if ( i == 0 && b == -1 )
              return -1;
          return i;
      }

      public int read(byte[] bf, int s, int l)
        throws IOException
      {
          return is.read(bf, s, l);
      }

      public void reset()
        throws IOException
      {
          is.reset();
      }

      public long skip(long n)
        throws IOException
      {
          return is.skip(n);


org.gjt.sp.jedit.msg.VFSUpdate

public class VFSUpdate extends EBMessage
{
	/**
	 * Creates a VFS update message.
	 * @param path The path in question
	 */
	public VFSUpdate(String path)
	{
		super(null);

		if(path == null)
			throw new NullPointerException("Path must be non-null");

		this.path = path;
	}

	/**
	 * Returns the path that changed.
	 */
	public String getPath()
	{
		return path;
	}

	public String paramString()
	{
		return "path=" + path + "," + super.paramString();
	}

	// private members
	private String path;

	public String getPath()
	{
		return path;


public class CxfSoapProducer implements Producer, AsyncProcessor {

    private static final Log LOG = LogFactory.getLog(CxfSoapProducer.class);

    private final CxfSoapEndpoint endpoint;
    private final Producer producer;
    private final AsyncProcessor processor;

    public CxfSoapProducer(CxfSoapEndpoint endpoint) throws Exception {
        this.endpoint = endpoint;
        this.producer = endpoint.getInnerEndpoint().createProducer();
        this.processor = new AsyncProcessorDecorator(producer,
                new Processor() {
                    public void process(Exchange exchange) throws Exception {
                        processSoapProviderIn(exchange);
                    }
                },
                new Processor() {
                    public void process(Exchange exchange) throws Exception {
                        processSoapProviderOut(exchange);
                    }
                });
    }

    public Endpoint getEndpoint() {
        return producer.getEndpoint();
    }

    public Exchange createExchange() {
        return producer.createExchange();
    }

    public Exchange createExchange(ExchangePattern pattern) {
        return producer.createExchange(pattern);
    }

    public Exchange createExchange(Exchange exchange) {
        return producer.createExchange(exchange);
    }

    public void process(Exchange exchange) throws Exception {
        AsyncProcessorHelper.process(this, exchange);
    }

    public boolean process(Exchange exchange, AsyncCallback callback) {
        return processor.process(exchange, callback);
    }

    public void start() throws Exception {
        producer.start();
    }

    public void stop() throws Exception {
        producer.stop();
    }

    protected void processSoapProviderIn(Exchange exchange) throws Exception {
        LOG.info("processSoapProviderIn: " + exchange);
    }

    protected void processSoapProviderOut(Exchange exchange) throws Exception {
        LOG.info("processSoapProviderOut: " + exchange);

FUNC_DECL PARAM ASSIGN ASSIGN ASSIGN CALL CALL CALL CALL CALL FUNC_DECL FUNC_DECL PARAM PARAM CALL CALL


public class PrintGridlinesRecord
    extends Record
{
    public final static short sid = 0x2b;
    private short             field_1_print_gridlines;

    public PrintGridlinesRecord()
    {
    }

    /**
     * Constructs a PrintGridlines record and sets its fields appropriately.
     *
     * @param id     id must be 0x2b or an exception will be throw upon validation
     * @param size  the size of the data area of the record
     * @param data  data of the record (should not contain sid/len)
     */

    public PrintGridlinesRecord(short id, short size, byte [] data)
    {
        super(id, size, data);
    }

    /**
     * Constructs a PrintGridlines record and sets its fields appropriately.
     *
     * @param id     id must be 0x2b or an exception will be throw upon validation
     * @param size  the size of the data area of the record
     * @param data  data of the record (should not contain sid/len)
     * @param offset of the record data
     */

    public PrintGridlinesRecord(short id, short size, byte [] data,
                                int offset)
    {
        super(id, size, data, offset);
    }

    protected void validateSid(short id)
    {
        if (id != sid)
        {
            throw new RecordFormatException("NOT A PrintGridlines RECORD");
        }
    }

    protected void fillFields(byte [] data, short size, int offset)
    {
        field_1_print_gridlines = LittleEndian.getShort(data, 0 + offset);
    }

    /**
     * set whether or not to print the gridlines (and make your spreadsheet ugly)
     *
     * @param pg  make spreadsheet ugly - Y/N
     */

    public void setPrintGridlines(boolean pg)
    {
        if (pg == true)
        {
            field_1_print_gridlines = 1;
        }
        else
        {
            field_1_print_gridlines = 0;
        }
    }

    /**
     * get whether or not to print the gridlines (and make your spreadsheet ugly)
     *
     * @return make spreadsheet ugly - Y/N
     */

    public boolean getPrintGridlines()
    {
        return (field_1_print_gridlines == 1);
    }

    public String toString()
    {
        StringBuffer buffer = new StringBuffer();

        buffer.append("[PRINTGRIDLINES]\n");
        buffer.append("    .printgridlines = ").append(getPrintGridlines())
            .append("\n");
        buffer.append("[/PRINTGRIDLINES]\n");
        return buffer.toString();
    }

    public int serialize(int offset, byte [] data)
    {
        LittleEndian.putShort(data, 0 + offset, sid);
        LittleEndian.putShort(data, 2 + offset, ( short ) 0x2);
        LittleEndian.putShort(data, 4 + offset, field_1_print_gridlines);
        return getRecordSize();
    }

    public int getRecordSize()
    {
        return 6;
    }

    public short getSid()
    {
        return this.sid;
    }

    public Object clone() {
      PrintGridlinesRecord rec = new PrintGridlinesRecord();
      rec.field_1_print_gridlines = field_1_print_gridlines;
      return rec;

    public int getRecordSize()
    {
        return 6;


final class ParameterRef extends VariableRefBase {

    /**
     * Name of param being referenced.
     */
    QName _name = null;

    public ParameterRef(Param param) {
	super(param);
        _name = param._name;

    }

    public String toString() {
	return "parameter-ref("+_variable.getName()+'/'+_variable.getType()+')';
    }

    public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
	final ConstantPoolGen cpg = classGen.getConstantPool();
	final InstructionList il = methodGen.getInstructionList();

        /*
         * To fix bug 24518 related to setting parameters of the form
         * {namespaceuri}localName, which will get mapped to an instance
         * variable in the class.
         */
        final String name = BasisLibrary.mapQNameToJavaName (_name.toString());
	final String signature = _type.toSignature();

	if (_variable.isLocal()) {
	    if (classGen.isExternal()) {
		Closure variableClosure = _closure;
		while (variableClosure != null) {
		    if (variableClosure.inInnerClass()) break;
		    variableClosure = variableClosure.getParentClosure();
		}

		if (variableClosure != null) {
		    il.append(ALOAD_0);
		    il.append(new GETFIELD(
			cpg.addFieldref(variableClosure.getInnerClassName(),
			    name, signature)));
		}
		else {
		    il.append(_variable.loadInstruction());
		    _variable.removeReference(this);
		}
	    }
	    else {
		il.append(_variable.loadInstruction());
		_variable.removeReference(this);
	    }
	}
	else {
	    final String className = classGen.getClassName();
	    il.append(classGen.loadTranslet());
	    if (classGen.isExternal()) {
		il.append(new CHECKCAST(cpg.addClass(className)));
	    }
	    il.append(new GETFIELD(cpg.addFieldref(className,name,signature)));
	}

	if (_variable.getType() instanceof NodeSetType) {
	    final int clone = cpg.addInterfaceMethodref(NODE_ITERATOR,
						       "cloneIterator",
						       "()" +
							NODE_ITERATOR_SIG);
	    il.append(new INVOKEINTERFACE(clone, 1));

FUNC_DECL IF IF VAR_DECL VAR_DECL VAR_DECL VAR_DECL PARAM PARAM BINARY_OP CALL VAR_DECL CALL IF VAR_DECL IF CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL IF LOOP VAR_DECL LITERAL_ANCHOR BINARY_OP LITERAL_ANCHOR CALL CALL CALL CALL BINARY_OP BINARY_OP LITERAL_ANCHOR CALL CALL LITERAL_ANCHOR IF LITERAL_ANCHOR CALL CALL CALL CALL CALL ASSIGN BREAK_CONTINUE CALL CALL CALL CALL CALL CALL


public class FuncExtFunction extends Function
{
    static final long serialVersionUID = 5196115554693708718L;

  /**
   * The namespace for the extension function, which should not normally
   *  be null or empty.
   *  @serial
   */
  String m_namespace;

  /**
   * The local name of the extension.
   *  @serial
   */
  String m_extensionName;

  /**
   * Unique method key, which is passed to ExtensionsTable#extFunction in
   *  order to allow caching of the method.
   *  @serial
   */
  Object m_methodKey;

  /**
   * Array of static expressions which represent the parameters to the
   *  function.
   *  @serial
   */
  Vector m_argVec = new Vector();

  /**
   * This function is used to fixup variables from QNames to stack frame
   * indexes at stylesheet build time.
   * @param vars List of QNames that correspond to variables.  This list
   * should be searched backwards for the first qualified name that
   * corresponds to the variable reference qname.  The position of the
   * QName in the vector from the start of the vector will be its position
   * in the stack frame (but variables above the globalsTop value will need
   * to be offset to the current stack frame).
   * NEEDSDOC @param globalsSize
   */
  public void fixupVariables(java.util.Vector vars, int globalsSize)
  {

    if (null != m_argVec)
    {
      int nArgs = m_argVec.size();

      for (int i = 0; i < nArgs; i++)
      {
        Expression arg = (Expression) m_argVec.elementAt(i);

        arg.fixupVariables(vars, globalsSize);
      }
    }
  }

  /**
   * Return the namespace of the extension function.
   *
   * @return The namespace of the extension function.
   */
  public String getNamespace()
  {
    return m_namespace;
  }

  /**
   * Return the name of the extension function.
   *
   * @return The name of the extension function.
   */
  public String getFunctionName()
  {
    return m_extensionName;
  }

  /**
   * Return the method key of the extension function.
   *
   * @return The method key of the extension function.
   */
  public Object getMethodKey()
  {
    return m_methodKey;
  }

  /**
   * Return the nth argument passed to the extension function.
   *
   * @param n The argument number index.
   * @return The Expression object at the given index.
   */
  public Expression getArg(int n) {
    if (n >= 0 && n < m_argVec.size())
      return (Expression) m_argVec.elementAt(n);
    else
      return null;
  }

  /**
   * Return the number of arguments that were passed
   * into this extension function.
   *
   * @return The number of arguments.
   */
  public int getArgCount() {
    return m_argVec.size();
  }

  /**
   * Create a new FuncExtFunction based on the qualified name of the extension,
   * and a unique method key.
   *
   * @param namespace The namespace for the extension function, which should
   *                  not normally be null or empty.
   * @param extensionName The local name of the extension.
   * @param methodKey Unique method key, which is passed to
   *                  ExtensionsTable#extFunction in order to allow caching
   *                  of the method.
   */
  public FuncExtFunction(java.lang.String namespace,
                         java.lang.String extensionName, Object methodKey)
  {
    m_namespace = namespace;
    m_extensionName = extensionName;
    m_methodKey = methodKey;
  }

  /**
   * Execute the function.  The function must return
   * a valid object.
   * @param xctxt The current execution context.
   * @return A valid XObject.
   *
   * @throws javax.xml.transform.TransformerException
   */
  public XObject execute(XPathContext xctxt)
          throws javax.xml.transform.TransformerException
  {
    if (xctxt.isSecureProcessing())
      throw new javax.xml.transform.TransformerException(
        XPATHMessages.createXPATHMessage(
          XPATHErrorResources.ER_EXTENSION_FUNCTION_CANNOT_BE_INVOKED,
          new Object[] {toString()}));

    XObject result;
    Vector argVec = new Vector();
    int nArgs = m_argVec.size();

    for (int i = 0; i < nArgs; i++)
    {
      Expression arg = (Expression) m_argVec.elementAt(i);

      XObject xobj = arg.execute(xctxt);
      /*
       * Should cache the arguments for func:function
       */
      xobj.allowDetachToRelease(false);
      argVec.addElement(xobj);
    }
    ExtensionsProvider extProvider = (ExtensionsProvider)xctxt.getOwnerObject();
    Object val = extProvider.extFunction(this, argVec);

    if (null != val)
    {
      result = XObject.create(val, xctxt);
    }
    else
    {
      result = new XNull();
    }

    return result;
  }

  /**
   * Set an argument expression for a function.  This method is called by the
   * XPath compiler.
   *
   * @param arg non-null expression that represents the argument.
   * @param argNum The argument number index.
   *
   * @throws WrongNumberArgsException If the argNum parameter is beyond what
   * is specified for this function.
   */
  public void setArg(Expression arg, int argNum)
          throws WrongNumberArgsException
  {
    m_argVec.addElement(arg);
    arg.exprSetParent(this);
  }

  /**
   * Check that the number of arguments passed to this function is correct.
   *
   *
   * @param argNum The number of arguments that is being passed to the function.
   *
   * @throws WrongNumberArgsException
   */
  public void checkNumberArgs(int argNum) throws WrongNumberArgsException{}

  class ArgExtOwner implements ExpressionOwner
  {

    Expression m_exp;

  	ArgExtOwner(Expression exp)
  	{
  		m_exp = exp;
  	}

    /**
     * @see ExpressionOwner#getExpression()
     */
    public Expression getExpression()
    {
      return m_exp;
    }

    /**
     * @see ExpressionOwner#setExpression(Expression)
     */
    public void setExpression(Expression exp)
    {
    	exp.exprSetParent(FuncExtFunction.this);
    	m_exp = exp;
    }
  }

  /**
   * Call the visitors for the function arguments.
   */
  public void callArgVisitors(XPathVisitor visitor)
  {
      for (int i = 0; i < m_argVec.size(); i++)
      {
         Expression exp = (Expression)m_argVec.elementAt(i);
         exp.callVisitors(new ArgExtOwner(exp), visitor);
      }

  }

  /**
   * Set the parent node.
   * For an extension function, we also need to set the parent
   * node for all argument expressions.
   *
   * @param n The parent node
   */
  public void exprSetParent(ExpressionNode n)
  {

    super.exprSetParent(n);

    int nArgs = m_argVec.size();

    for (int i = 0; i < nArgs; i++)
    {
      Expression arg = (Expression) m_argVec.elementAt(i);

      arg.exprSetParent(n);
    }
  }

  /**
   * Constructs and throws a WrongNumberArgException with the appropriate
   * message for this function object.  This class supports an arbitrary
   * number of arguments, so this method must never be called.
   *
   * @throws WrongNumberArgsException
   */
  protected void reportWrongNumberArgs() throws WrongNumberArgsException {
    String fMsg = XSLMessages.createXPATHMessage(
        XPATHErrorResources.ER_INCORRECT_PROGRAMMER_ASSERTION,
        new Object[]{ "Programmer's assertion:  the method FunctionMultiArgs.reportWrongNumberArgs() should never be called." });

    throw new RuntimeException(fMsg);
  }

  /**
   * Return the name of the extesion function in string format
   */
  public String toString()
  {
    if (m_namespace != null && m_namespace.length() > 0)
      return "{" + m_namespace + "}" + m_extensionName;
    else
      return m_extensionName;

FUNC_DECL PARAM PARAM PARAM ASSIGN ASSIGN ASSIGN


public class DailyRollingFileAppender extends FileAppender {

  // The code assumes that the following constants are in a increasing
  // sequence.
  static final int TOP_OF_TROUBLE=-1;
  static final int TOP_OF_MINUTE = 0;
  static final int TOP_OF_HOUR   = 1;
  static final int HALF_DAY      = 2;
  static final int TOP_OF_DAY    = 3;
  static final int TOP_OF_WEEK   = 4;
  static final int TOP_OF_MONTH  = 5;

  /**
     The date pattern. By default, the pattern is set to
     "'.'yyyy-MM-dd" meaning daily rollover.
   */
  private String datePattern = "'.'yyyy-MM-dd";

  /**
     The log file will be renamed to the value of the
     scheduledFilename variable when the next interval is entered. For
     example, if the rollover period is one hour, the log file will be
     renamed to the value of "scheduledFilename" at the beginning of
     the next hour.

     The precise time when a rollover occurs depends on logging
     activity.
  */
  private String scheduledFilename;

  /**
     The next time we estimate a rollover should occur. */
  private long nextCheck = System.currentTimeMillis () - 1;

  Date now = new Date();

  SimpleDateFormat sdf;

  RollingCalendar rc = new RollingCalendar();

  int checkPeriod = TOP_OF_TROUBLE;

  // The gmtTimeZone is used only in computeCheckPeriod() method.
  static final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT");

  /**
     The default constructor does nothing. */
  public DailyRollingFileAppender() {
  }

  /**
    Instantiate a DailyRollingFileAppender and open the
    file designated by filename. The opened filename will
    become the ouput destination for this appender.

    */
  public DailyRollingFileAppender (Layout layout, String filename,
				   String datePattern) throws IOException {
    super(layout, filename, true);
    this.datePattern = datePattern;
    activateOptions();
  }

  /**
     The DatePattern takes a string in the same format as
     expected by {@link SimpleDateFormat}. This options determines the
     rollover schedule.
   */
  public void setDatePattern(String pattern) {
    datePattern = pattern;
  }

  /** Returns the value of the DatePattern option. */
  public String getDatePattern() {
    return datePattern;
  }

  public void activateOptions() {
    super.activateOptions();
    if(datePattern != null && fileName != null) {
      now.setTime(System.currentTimeMillis());
      sdf = new SimpleDateFormat(datePattern);
      int type = computeCheckPeriod();
      printPeriodicity(type);
      rc.setType(type);
      File file = new File(fileName);
      scheduledFilename = fileName+sdf.format(new Date(file.lastModified()));

    } else {
      LogLog.error("Either File or DatePattern options are not set for appender ["
		   +name+"].");
    }
  }

  void printPeriodicity(int type) {
    switch(type) {
    case TOP_OF_MINUTE:
      LogLog.debug("Appender ["+name+"] to be rolled every minute.");
      break;
    case TOP_OF_HOUR:
      LogLog.debug("Appender ["+name
		   +"] to be rolled on top of every hour.");
      break;
    case HALF_DAY:
      LogLog.debug("Appender ["+name
		   +"] to be rolled at midday and midnight.");
      break;
    case TOP_OF_DAY:
      LogLog.debug("Appender ["+name
		   +"] to be rolled at midnight.");
      break;
    case TOP_OF_WEEK:
      LogLog.debug("Appender ["+name
		   +"] to be rolled at start of week.");
      break;
    case TOP_OF_MONTH:
      LogLog.debug("Appender ["+name
		   +"] to be rolled at start of every month.");
      break;
    default:
      LogLog.warn("Unknown periodicity for appender ["+name+"].");
    }
  }

  // This method computes the roll over period by looping over the
  // periods, starting with the shortest, and stopping when the r0 is
  // different from from r1, where r0 is the epoch formatted according
  // the datePattern (supplied by the user) and r1 is the
  // epoch+nextMillis(i) formatted according to datePattern. All date
  // formatting is done in GMT and not local format because the test
  // logic is based on comparisons relative to 1970-01-01 00:00:00
  // GMT (the epoch).

  int computeCheckPeriod() {
    RollingCalendar rollingCalendar = new RollingCalendar(gmtTimeZone, Locale.getDefault());
    // set sate to 1970-01-01 00:00:00 GMT
    Date epoch = new Date(0);
    if(datePattern != null) {
      for(int i = TOP_OF_MINUTE; i <= TOP_OF_MONTH; i++) {
	SimpleDateFormat simpleDateFormat = new SimpleDateFormat(datePattern);
	simpleDateFormat.setTimeZone(gmtTimeZone); // do all date formatting in GMT
	String r0 = simpleDateFormat.format(epoch);
	rollingCalendar.setType(i);
	Date next = new Date(rollingCalendar.getNextCheckMillis(epoch));
	String r1 =  simpleDateFormat.format(next);
	//System.out.println("Type = "+i+", r0 = "+r0+", r1 = "+r1);
	if(r0 != null && r1 != null && !r0.equals(r1)) {
	  return i;
	}
      }
    }
    return TOP_OF_TROUBLE; // Deliberately head for trouble...
  }

  /**
     Rollover the current file to a new file.
  */
  void rollOver() throws IOException {

    /* Compute filename, but only if datePattern is specified */
    if (datePattern == null) {
      errorHandler.error("Missing DatePattern option in rollOver().");
      return;
    }

    String datedFilename = fileName+sdf.format(now);
    // It is too early to roll over because we are still within the
    // bounds of the current interval. Rollover will occur once the
    // next interval is reached.
    if (scheduledFilename.equals(datedFilename)) {
      return;
    }

    // close current file, and rename it to datedFilename
    this.closeFile();

    File target  = new File(scheduledFilename);
    if (target.exists()) {
      target.delete();
    }

    File file = new File(fileName);
    boolean result = file.renameTo(target);
    if(result) {
      LogLog.debug(fileName +" -> "+ scheduledFilename);
    } else {
      LogLog.error("Failed to rename ["+fileName+"] to ["+scheduledFilename+"].");
    }

    try {
      // This will also close the file. This is OK since multiple
      // close operations are safe.
      this.setFile(fileName, true, this.bufferedIO, this.bufferSize);
    }
    catch(IOException e) {
      errorHandler.error("setFile("+fileName+", true) call failed.");
    }
    scheduledFilename = datedFilename;
  }

  /**
   * This method differentiates DailyRollingFileAppender from its
   * super class.
   *
   *
Before actually logging, this method will check whether it is
   * time to do a rollover. If it is, it will schedule the next
   * rollover time and then rollover.
   * */
  protected void subAppend(LoggingEvent event) {
    long n = System.currentTimeMillis();
    if (n >= nextCheck) {
      now.setTime(n);
      nextCheck = rc.getNextCheckMillis(now);
      try {
	rollOver();
      }
      catch(IOException ioe) {
          if (ioe instanceof InterruptedIOException) {
              Thread.currentThread().interrupt();
          }
	      LogLog.error("rollOver() failed.", ioe);
      }
    }
    super.subAppend(event);

FUNC_DECL IF VAR_DECL PARAM BINARY_OP TRY CALL CATCH ASSIGN CALL IF CALL CALL CALL BINARY_OP LITERAL_ANCHOR CALL CALL

FUNC_DECL PARAM PARAM PARAM CALL ASSIGN LITERAL_ANCHOR


org.apache.ivy.ant.IvyDeliver

public class IvyDeliver extends IvyTask {
    private final class DeliverDRResolver extends DefaultPublishingDRResolver {
        public String resolve(ModuleDescriptor published, String publishedStatus,
                ModuleRevisionId depMrid, String depStatus) {
            if (StatusManager.getCurrent().isIntegration(publishedStatus)) {
                // published status is integration one, nothing to ask
                return super.resolve(published, publishedStatus, depMrid, depStatus);
            }

            // we are publishing a delivery (a non integration module)

            if (!StatusManager.getCurrent().isIntegration(depStatus)) {
                // dependency is already a delivery, nothing to ask
                return super.resolve(published, publishedStatus, depMrid, depStatus);
            }

            // the dependency is not a delivery

            String statusProperty = depMrid.getName() + "." + depMrid.getRevision() + ".status";
            String versionProperty = depMrid.getName() + "." + depMrid.getRevision() + ".version";
            String deliveredProperty = depMrid.getName() + "." + depMrid.getRevision()
                    + ".delivered";

            String version = getProject().getProperty(versionProperty);
            String status = getProject().getProperty(statusProperty);
            String delivered = getProject().getProperty(deliveredProperty);
            Message.debug("found version = " + version + " status=" + status + " delivered="
                    + delivered);
            if (version != null && status != null) {
                if ("true".equals(delivered)) {
                    // delivery has already been done : just return the value
                    return version;
                } else {
                    deliverDependency(depMrid, version, status, depStatus);
                    loadDeliveryList();
                    return version;
                }
            }

            /**
             * By setting these properties: recursive.delivery.status and
             * recursive.delivery.version, then if the specific status/version is not found, then we
             * will use the status/version set in these global properties. This will apply to all
             * artifacts in the system. This patch is meant to be used for recursive deliveries so
             * that all deliveries will use the global status/version unless a more specific one is
             * set.
             */
            String globalStatusProperty = "recursive.delivery.status";
            String globalVersionProperty = "recursive.delivery.version";
            version = getProject().getProperty(globalVersionProperty);
            status = getProject().getProperty(globalStatusProperty);
            if (version != null && status != null) {
                // found global delivery properties
                delivered = getProject().getProperty(
                    "recursive." + depMrid.getName() + ".delivered");
                Message.debug("found global version = " + version + " and global status=" + status
                        + " - delivered = " + delivered);
                if ("true".equals(delivered)) {
                    // delivery has already been done : just return the value
                    return version;
                } else {
                    getProject().setProperty(statusProperty, status);
                    deliverDependency(depMrid, version, status, depStatus);
                    loadDeliveryList();
                    return version;
                }
            }

            // we must ask the user what version and status he want to have
            // for the dependency
            Input input = (Input) getProject().createTask("input");
            input.setOwningTarget(getOwningTarget());
            input.init();

            // ask status
            input.setMessage(depMrid.getName() + " " + depMrid.getRevision()
                    + ": please enter a status: ");
            input.setValidargs(StatusManager.getCurrent().getDeliveryStatusListString());
            input.setAddproperty(statusProperty);
            input.perform();
            status = getProject().getProperty(statusProperty);
            appendDeliveryList(statusProperty + " = " + status);

            // ask version
            input.setMessage(depMrid.getName() + " " + depMrid.getRevision()
                    + ": please enter a version: ");
            input.setValidargs(null);
            input.setAddproperty(versionProperty);
            input.perform();

            version = getProject().getProperty(versionProperty);
            appendDeliveryList(versionProperty + " = " + version);
            deliverDependency(depMrid, version, status, depStatus);

            loadDeliveryList();

            return version;
        }

        public void deliverDependency(ModuleRevisionId depMrid, String version, String status,
                String depStatus) {
            // call deliver target if any
            if (deliverTarget != null && deliverTarget.trim().length() > 0) {

                CallTarget ct = (CallTarget) getProject().createTask("antcall");
                ct.setOwningTarget(getOwningTarget());
                ct.init();
                ct.setTarget(deliverTarget);
                ct.setInheritAll(true);
                ct.setInheritRefs(true);
                Property param = ct.createParam();
                param.setName("dependency.name");
                param.setValue(depMrid.getName());
                param = ct.createParam();
                param.setName("dependency.published.status");
                param.setValue(status);
                param = ct.createParam();
                param.setName("dependency.published.version");
                param.setValue(version);
                param = ct.createParam();
                param.setName("dependency.version");
                param.setValue(depMrid.getRevision());
                param = ct.createParam();
                param.setName("dependency.status");
                param.setValue(depStatus == null ? "null" : depStatus);

                ct.perform();

                String deliveredProperty = depMrid.getName() + "." + depMrid.getRevision()
                        + ".delivered";
                getProject().setProperty(deliveredProperty, "true");
                appendDeliveryList(deliveredProperty + " = true");

                getProject().setProperty("recursive." + depMrid.getName() + ".delivered", "true");
                appendDeliveryList("recursive." + depMrid.getName() + ".delivered" + " = true");
            }
        }

    }

    private String organisation;

    private String module;

    private String revision;

    private String pubRevision;

    private String deliverpattern;

    private String status;

    private String pubdate;

    private String deliverTarget;

    private File deliveryList;

    private boolean replacedynamicrev = true;

    private String resolveId;

    private String conf;

    private String pubBranch;

    public void setCache(File cache) {
        cacheAttributeNotSupported();
    }

    public String getDeliverpattern() {
        return deliverpattern;
    }

    public void setDeliverpattern(String destivypattern) {
        this.deliverpattern = destivypattern;
    }

    public String getModule() {
        return module;
    }

    public void setModule(String module) {
        this.module = module;
    }

    public String getOrganisation() {
        return organisation;
    }

    public void setOrganisation(String organisation) {
        this.organisation = organisation;
    }

    public String getPubdate() {
        return pubdate;
    }

    public void setPubdate(String pubdate) {
        this.pubdate = pubdate;
    }

    public String getPubrevision() {
        return pubRevision;
    }

    public void setPubrevision(String pubRevision) {
        this.pubRevision = pubRevision;
    }

    public String getPubbranch() {
        return pubBranch;
    }

    public void setPubbranch(String pubBranch) {
        this.pubBranch = pubBranch;
    }

    public String getRevision() {
        return revision;
    }

    public void setRevision(String revision) {
        this.revision = revision;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public void setDelivertarget(String deliverTarget) {
        this.deliverTarget = deliverTarget;
    }

    public void setDeliveryList(File deliveryList) {
        this.deliveryList = deliveryList;
    }

    public boolean isReplacedynamicrev() {
        return replacedynamicrev;
    }

    public void setReplacedynamicrev(boolean replacedynamicrev) {
        this.replacedynamicrev = replacedynamicrev;
    }

    public String getResolveId() {
        return resolveId;
    }

    public void setResolveId(String resolveId) {
        this.resolveId = resolveId;
    }

    public String getConf() {
        return conf;
    }

    public void setConf(String confs) {
        conf = confs;
    }

    public void doExecute() throws BuildException {
        Ivy ivy = getIvyInstance();
        IvySettings settings = ivy.getSettings();

        organisation = getProperty(organisation, settings, "ivy.organisation", resolveId);
        module = getProperty(module, settings, "ivy.module", resolveId);
        revision = getProperty(revision, settings, "ivy.revision", resolveId);
        pubBranch = getProperty(pubBranch, settings, "ivy.deliver.branch");
        pubRevision = getProperty(pubRevision, settings, "ivy.deliver.revision");
        deliverpattern = getProperty(deliverpattern, settings, "ivy.deliver.ivy.pattern");
        status = getProperty(status, settings, "ivy.status");
        if (deliveryList == null) {
            String deliveryListPath = getProperty(settings, "ivy.delivery.list.file");
            if (deliveryListPath == null) {
                deliveryList = new File(System.getProperty("java.io.tmpdir")
                        + "/delivery.properties");
            } else {
                deliveryList = getProject().resolveFile(settings.substitute(deliveryListPath));
            }
        }
        if (resolveId == null) {
            if (organisation == null) {
                throw new BuildException(
                        "no organisation provided for ivy deliver task: "
                        + "It can either be set explicitely via the attribute 'organisation' "
                        + "or via 'ivy.organisation' property or a prior call to <resolve/>");
            }
            if (module == null) {
                throw new BuildException(
                        "no module name provided for ivy deliver task: "
                        + "It can either be set explicitely via the attribute 'module' "
                        + "or via 'ivy.module' property or a prior call to <resolve/>");
            }
        }
        if (revision == null) {
            revision = Ivy.getWorkingRevision();
        }
        Date pubdate = getPubDate(this.pubdate, new Date());
        if (pubRevision == null) {
            if (revision.startsWith("working@")) {
                pubRevision = Ivy.DATE_FORMAT.format(pubdate);
            } else {
                pubRevision = revision;
            }
        }
        if (deliverpattern == null) {
            throw new BuildException(
                    "deliver ivy pattern is missing: either provide it as parameters "
                    + "or through ivy.deliver.ivy.pattern properties");
        }
        if (status == null) {
            throw new BuildException(
                    "no status provided: either provide it as parameter or through "
                    + "the ivy.status.default property");
        }

        ModuleRevisionId mrid = null;
        if (resolveId == null) {
            mrid = ModuleRevisionId.newInstance(organisation, module, revision);
        }
        boolean isLeading = false;
        try {
            if (!deliveryList.exists()) {
                isLeading = true;
            }

            loadDeliveryList();

            PublishingDependencyRevisionResolver drResolver;
            if (deliverTarget != null && deliverTarget.trim().length() > 0) {
                drResolver = new DeliverDRResolver();
            } else {
                drResolver = new DefaultPublishingDRResolver();
            }

            DeliverOptions options = new DeliverOptions(status, pubdate,
                drResolver, doValidate(settings), replacedynamicrev, splitConfs(conf))
                .setResolveId(resolveId)
                .setPubBranch(pubBranch);
            if (mrid == null) {
                ivy.deliver(pubRevision, deliverpattern, options);
            } else {
                ivy.deliver(mrid, pubRevision, deliverpattern, options);
            }
        } catch (Exception e) {
            throw new BuildException("impossible to deliver " + mrid == null ? resolveId : mrid
                    + ": " + e, e);
        } finally {
            if (isLeading) {
                if (deliveryList.exists()) {
                    deliveryList.delete();
                }
            }
        }
    }

    private void loadDeliveryList() {
        Property property = (Property) getProject().createTask("property");
        property.setOwningTarget(getOwningTarget());
        property.init();
        property.setFile(deliveryList);
        property.perform();
    }

    private void appendDeliveryList(String msg) {
        Echo echo = (Echo) getProject().createTask("echo");
        echo.setOwningTarget(getOwningTarget());
        echo.init();
        echo.setFile(deliveryList);
        echo.setMessage(msg + "\n");
        echo.setAppend(true);
        echo.perform();

    public String getConf() {
        return conf;

FUNC_DECL VAR_DECL CALL CALL CALL CALL CALL CALL CALL LITERAL_ANCHOR


public class GroovyLanguage implements Language  {

    public static GroovyExpression groovy(String expression) {
        return new GroovyLanguage().createExpression(expression);
    }

    public GroovyExpression createPredicate(String expression) {
        return createExpression(expression);
    }

    public GroovyExpression createExpression(String expression) {
        Class<Script> scriptType = parseExpression(expression);
        return new GroovyExpression(scriptType, expression);
    }

    protected Class<Script> parseExpression(String expression) {
        return new GroovyClassLoader().parseClass(expression);

FUNC_DECL RETURN VAR_DECL PARAM CALL CALL


public class DOM2Helper extends DOMHelper
{

  /**
   * Construct an instance.
   */
  public DOM2Helper(){}

  /**
   * Check node to see if it was created by a DOM implementation
   * that this helper is intended to support. This is currently
   * disabled, and assumes all nodes are acceptable rather than checking
   * that they implement org.apache.xerces.dom.NodeImpl.
   *
   * @param node The node to be tested.
   *
   * @throws TransformerException if the node is not one which this
   * DOM2Helper can support. If we return without throwing the exception,
   * the node is compatable.
   * @xsl.usage internal
   */
  public void checkNode(Node node) throws TransformerException
  {

  }

  /**
   * Returns true if the DOM implementation handled by this helper
   * supports the SAX ContentHandler interface.
   *
   * @return true (since Xerces does).
   */
  public boolean supportsSAX()
  {
    return true;
  }

  /** Field m_doc: Document Node for the document this helper is currently
   * accessing or building
   * @see #setDocument
   * @see #getDocument
   *  */
  private Document m_doc;

  /**
   * Specify which document this helper is currently operating on.
   *
   * @param doc The DOM Document node for this document.
   * @see #getDocument
   */
  public void setDocument(Document doc)
  {
    m_doc = doc;
  }

  /**
   * Query which document this helper is currently operating on.
   *
   * @return The DOM Document node for this document.
   * @see #setDocument
   */
  public Document getDocument()
  {
    return m_doc;
  }

  /**
   * Parse an XML document.
   *
   *
Right now the Xerces DOMParser class is used.  This needs
   * fixing, either via jaxp, or via some other, standard method.

   *
   *
The application can use this method to instruct the SAX parser
   * to begin parsing an XML document from any valid input
   * source (a character stream, a byte stream, or a URI).

   *
   *
Applications may not invoke this method while a parse is in
   * progress (they should create a new Parser instead for each
   * additional XML document).  Once a parse is complete, an
   * application may reuse the same Parser object, possibly with a
   * different input source.

   *
   * @param source The input source for the top-level of the
   *        XML document.
   *
   * @throws TransformerException if any checked exception is thrown.
   * @xsl.usage internal
   */
  public void parse(InputSource source) throws TransformerException
  {

    try
    {

      DocumentBuilderFactory builderFactory =
        DocumentBuilderFactory.newInstance();

      builderFactory.setNamespaceAware(true);
      builderFactory.setValidating(true);

      DocumentBuilder parser = builderFactory.newDocumentBuilder();

      /*
      if(m_useDOM2getNamespaceURI)
      {
      }
      else
      {
      }

      */

      parser.setErrorHandler(
        new org.apache.xml.utils.DefaultErrorHandler());

      setDocument(parser.parse(source));
    }
    catch (org.xml.sax.SAXException se)
    {
      throw new TransformerException(se);
    }
    catch (ParserConfigurationException pce)
    {
      throw new TransformerException(pce);
    }
    catch (IOException ioe)
    {
      throw new TransformerException(ioe);
    }

  }

  /**
   * Given an XML ID, return the element. This requires assistance from the
   * DOM and parser, and is meaningful only in the context of a DTD
   * or schema which declares attributes as being of type ID. This
   * information may or may not be available in all parsers, may or
   * may not be available for specific documents, and may or may not
   * be available when validation is not turned on.
   *
   * @param id The ID to search for, as a String.
   * @param doc The document to search within, as a DOM Document node.
   * @return DOM Element node with an attribute of type ID whose value
   * uniquely matches the requested id string, or null if there isn't
   * such an element or if the DOM can't answer the question for other
   * reasons.
   */
  public Element getElementByID(String id, Document doc)
  {
    return doc.getElementById(id);
  }

  /**
   * Figure out whether node2 should be considered as being later
   * in the document than node1, in Document Order as defined
   * by the XPath model. This may not agree with the ordering defined
   * by other XML applications.
   *

   * There are some cases where ordering isn't defined, and neither are
   * the results of this function -- though we'll generally return true.
   *

   * TODO: Make sure this does the right thing with attribute nodes!!!
   *
   * @param node1 DOM Node to perform position comparison on.
   * @param node2 DOM Node to perform position comparison on .
   *
   * @return false if node2 comes before node1, otherwise return true.
   * You can think of this as
   * (node1.documentOrderPosition <= node2.documentOrderPosition).
   */
  public static boolean isNodeAfter(Node node1, Node node2)
  {

    if(node1 instanceof DOMOrder && node2 instanceof DOMOrder)
    {
      int index1 = ((DOMOrder) node1).getUid();
      int index2 = ((DOMOrder) node2).getUid();

      return index1 <= index2;
    }
    else
    {

      return DOMHelper.isNodeAfter(node1, node2);
    }
  }

  /**
   * Get the XPath-model parent of a node.  This version takes advantage
   * of the DOM Level 2 Attr.ownerElement() method; the base version we
   * would otherwise inherit is prepared to fall back on exhaustively
   * walking the document to find an Attr's parent.
   *
   * @param node Node to be examined
   *
   * @return the DOM parent of the input node, if there is one, or the
   * ownerElement if the input node is an Attr, or null if the node is
   * a Document, a DocumentFragment, or an orphan.
   */
  public static Node getParentOfNode(Node node)
  {
          Node parent=node.getParentNode();
          if(parent==null && (Node.ATTRIBUTE_NODE == node.getNodeType()) )
           parent=((Attr) node).getOwnerElement();
          return parent;
  }

  /**
   * Returns the local name of the given node, as defined by the
   * XML Namespaces specification. This is prepared to handle documents
   * built using DOM Level 1 methods by falling back upon explicitly
   * parsing the node name.
   *
   * @param n Node to be examined
   *
   * @return String containing the local name, or null if the node
   * was not assigned a Namespace.
   */
  public String getLocalNameOfNode(Node n)
  {

    String name = n.getLocalName();

    return (null == name) ? super.getLocalNameOfNode(n) : name;
  }

  /**
   * Returns the Namespace Name (Namespace URI) for the given node.
   * In a Level 2 DOM, you can ask the node itself. Note, however, that
   * doing so conflicts with our decision in getLocalNameOfNode not
   * to trust the that the DOM was indeed created using the Level 2
   * methods. If Level 1 methods were used, these two functions will
   * disagree with each other.
   *

   * TODO: Reconcile with getLocalNameOfNode.
   *
   * @param n Node to be examined
   *
   * @return String containing the Namespace URI bound to this DOM node
   * at the time the Node was created.
   */
  public String getNamespaceOfNode(Node n)
  {
    return n.getNamespaceURI();

FUNC_DECL TRY PARAM CATCH CATCH CATCH VAR_DECL VAR_DECL THROW_RAISE THROW_RAISE THROW_RAISE CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL LITERAL_ANCHOR LITERAL_ANCHOR CALL


public class FileComponent extends DefaultComponent<FileExchange> {

    /**
     * Header key holding the value: the fixed filename to use for producing files.
     */
    public static final String HEADER_FILE_NAME = "org.apache.camel.file.name";

    /**
     * Header key holding the value: absolute filepath for the actual file produced (by file producer).
     * Value is set automatically by Camel
     */
    public static final String HEADER_FILE_NAME_PRODUCED = "org.apache.camel.file.name.produced";

    public FileComponent() {
    }

    public FileComponent(CamelContext context) {
        super(context);
    }

    protected Endpoint<FileExchange> createEndpoint(String uri, String remaining, Map parameters) throws Exception {
        File file = new File(remaining);
        FileEndpoint result = new FileEndpoint(file, uri, this);
        setProperties(result, parameters);
        return result;

FUNC_DECL RETURN VAR_DECL VAR_DECL PARAM PARAM PARAM CALL CALL CALL