/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
 *
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
 * Other names may be trademarks of their respective owners.
 *
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common
 * Development and Distribution License("CDDL") (collectively, the
 * "License"). You may not use this file except in compliance with the
 * License. You can obtain a copy of the License at
 * http://www.netbeans.org/cddl-gplv2.html
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
 * specific language governing permissions and limitations under the
 * License.  When distributing the software, include this License Header
 * Notice in each file and include the License file at
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the GPL Version 2 section of the License file that
 * accompanied this code. If applicable, add the following below the
 * License Header, with the fields enclosed by brackets [] replaced by
 * your own identifying information:
 * "Portions Copyrighted [year] [name of copyright owner]"
 *
 * Contributor(s):
 * The Original Software is NetBeans. The Initial Developer of the Original
 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
 * Microsystems, Inc. All Rights Reserved.
 *
 * If you wish your version of this file to be governed by only the CDDL
 * or only the GPL Version 2, indicate your decision by adding
 * "[Contributor] elects to include this software in this distribution
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
 * single choice of license, a recipient has the option to distribute
 * your version of this file under either the CDDL, the GPL Version 2 or
 * to extend the choice of license to its licensees as provided above.
 * However, if you add GPL Version 2 code and therefore, elected the GPL
 * Version 2 license, then the option applies only if the new code is
 * made subject to such option by the copyright holder.
 */

package org.graalvm.visualvm.lib.profiler.heapwalk.memorylint.rules;

import org.graalvm.visualvm.lib.jfluid.heap.Heap;
import org.graalvm.visualvm.lib.jfluid.heap.Instance;
import org.graalvm.visualvm.lib.jfluid.heap.JavaClass;
import org.graalvm.visualvm.lib.jfluid.heap.ObjectArrayInstance;
import org.graalvm.visualvm.lib.profiler.heapwalk.memorylint.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.openide.util.NbBundle;

//@org.openide.util.lookup.ServiceProvider(service=org.graalvm.visualvm.lib.profiler.heapwalk.memorylint.Rule.class)
public class WrongWeakHashMap extends IteratingRule {
    //~ Inner Classes ------------------------------------------------------------------------------------------------------------

    private class WHMRecord {
        //~ Instance fields ------------------------------------------------------------------------------------------------------

        private Instance hm;
        private Instance key;
        private Instance value;

        //~ Constructors ---------------------------------------------------------------------------------------------------------

        WHMRecord(Instance hm, Instance key, Instance value) {
            this.hm = hm;
            this.key = key;
            this.value = value;
        }

        //~ Methods --------------------------------------------------------------------------------------------------------------

        @Override
        public String toString() {
            return NbBundle.getMessage(WrongWeakHashMap.class, "FMT_WWHM_Entry",
                    new Object[] {
                        Utils.printClass(getContext(), getContext().getRootIncommingString(hm)),
                        Utils.printInstance(hm),
                        Utils.printInstance(key),
                        Utils.printInstance(value)
                    }
            );
        }
    }

    //~ Instance fields ----------------------------------------------------------------------------------------------------------

    private FieldAccess fldHMEKey;
    private FieldAccess fldHMENext;
    private FieldAccess fldHMEValue;
    private FieldAccess fldHMTable;
    private JavaClass clsHM;
    private JavaClass clsHME;
    private Set<WHMRecord> poorWHM = new HashSet<WHMRecord>();

    //~ Constructors -------------------------------------------------------------------------------------------------------------

    public WrongWeakHashMap() {
        super(NbBundle.getMessage(WrongWeakHashMap.class, "LBL_WWHM_Name"),
                NbBundle.getMessage(WrongWeakHashMap.class, "LBL_WWHM_Desc"),
                "java.util.WeakHashMap");

    }

    //~ Methods ------------------------------------------------------------------------------------------------------------------

    @Override
    public String getHTMLDescription() {
        return NbBundle.getMessage(WrongWeakHashMap.class, "LBL_WWHM_LongDesc");
    }

    protected void perform(Instance hm) {
        scanWeakHashmap(hm);
    }

    @Override
    protected void prepareRule(MemoryLint context) {
        // TODO WeakHashMap might not be present in the dump
        Heap heap = context.getHeap();
        clsHM = heap.getJavaClassByName("java.util.WeakHashMap"); // NOI18N
        clsHME = heap.getJavaClassByName("java.util.WeakHashMap$Entry"); // NOI18N
        fldHMTable = new FieldAccess(clsHM, "table"); // NOI18N

        JavaClass ref = heap.getJavaClassByName("java.lang.ref.Reference"); // NOI18N
        fldHMEKey = new FieldAccess(ref, "referent"); // NOI18N
        fldHMEValue = new FieldAccess(clsHME, "value"); // NOI18N
        fldHMENext = new FieldAccess(clsHME, "next"); // NOI18N
    }

    @Override
    protected void summary() {
        for (WHMRecord whm : poorWHM) {
            getContext().appendResults(whm.toString());
        }
    }

    private void scanWeakHashmap(Instance hm) {
        ObjectArrayInstance table = (ObjectArrayInstance) fldHMTable.getRefValue(hm);

        if (table == null) { // ?

            return;
        }

        @SuppressWarnings("unchecked")
        List<Instance> tval = table.getValues();

        for (Instance entry : tval) {
            while (entry != null) {
                Instance key = fldHMEKey.getRefValue(entry);

                if (key != null) { // XXX can also scan for weak HM pending cleanup

                    Instance value = fldHMEValue.getRefValue(entry);

                    if (Utils.isReachableFrom(value, key)) {
                        poorWHM.add(new WHMRecord(hm, key, value));

                        return;
                    }
                }

                entry = fldHMENext.getRefValue(entry);
            }
        }

        return;
    }
}


// $Id: ary.java,v 1.1 2004-05-22 07:27:00 bfulgham Exp $
// http://www.bagley.org/~doug/shootout/

// this program is modified from:
//   http://cm.bell-labs.com/cm/cs/who/bwk/interps/pap.html
// Timing Trials, or, the Trials of Timing: Experiments with Scripting
// and User-Interface Languages</a> by Brian W. Kernighan and
// Christopher J. Van Wyk.

import java.io.*;
import java.util.*;

public class ary {
    public static void main(String args[]) {
        int i, j, k, n = Integer.parseInt(args[0]);
        int x[] = new int[n];
        int y[] = new int[n];

        for (i = 0; i < n; i++)
            x[i] = i + 1;
        for (k = 0; k < 1000; k++ )
            for (j = n-1; j >= 0; j--)
                y[j] += x[j];

        System.out.println(y[0] + " " + y[n-1]);
    }
}


/*******************************************************************************
 * Copyright (c) 2017 the TeXlipse team and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     The TeXlipse team - initial API and implementation
 *******************************************************************************/
package org.eclipse.texlipse.viewer.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.eclipse.texlipse.builder.BuilderRegistry;

/**
 * A helper class to read the viewer error stream if an error occurs.
 *
 * @author Kimmo Karlsson
 */
public class ViewerErrorScanner implements Runnable {

    // the process to monitor
    private Process process;

    public ViewerErrorScanner(Process process) {
        this.process = process;
    }

    /**
     * Wait for the program to exit and read the status.
     */
    public void run() {

        BufferedReader in = new BufferedReader(new InputStreamReader(process.getErrorStream()));

        ArrayList buffer = new ArrayList();
        String tmp = null;
        try {

            // read the error output stream lines before the program exits
            // the stream is not available anymore after the program has exit
            while ((tmp = in.readLine()) != null) {
                buffer.add(tmp);
            }
            in.close();

        } catch (IOException e) {
        }

        int exitCode = 0;
        try {
            exitCode = process.waitFor();
        } catch (InterruptedException e) {
        }

        // if there was an error, the viewer exited with non-zero status
        if (exitCode != 0) {
            // print the error messages
            for (int i = 0; i < buffer.size(); i++) {
                tmp = (String) buffer.get(i);
                BuilderRegistry.printToConsole("viewer> " + tmp);
            }
        }
    }
}


/*
 * 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 org.apache.taverna.workbench.ui.views.contextualviews;

import static java.awt.BorderLayout.CENTER;

import java.awt.BorderLayout;
import java.awt.Frame;

import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.JPanel;

/**
 * An abstract class defining the base container to hold a contextual view over
 * Dataflow element.
 *

 * The specific implementation of this class to support a given dataflow element
 * needs to implement the {@link #getMainFrame()} and {@link #getViewTitle()}.
 *

 * If a view is associated with an action handler to configure this component,
 * then the {@link #getConfigureAction(Frame) getConfigureAction} handler must
 * be over-ridden. If this returns null then the configure button is left
 * disabled and it is not possible to configure the element.
 *
 * @author Stuart Owen
 * @author Ian Dunlop
 * @author Alan R Williams
 */
@SuppressWarnings("serial")
public abstract class ContextualView extends JPanel {
	/**
	 * When implemented, this method should define the main frame that is placed
	 * in this container, and provides a static view of the Dataflow element.
	 *
	 * @return a JComponent that represents the dataflow element.
	 */
	public abstract JComponent getMainFrame();

	/**
	 * @return a String providing a title for the view
	 */
	public abstract String getViewTitle();

	/**
	 * Allows the item to be configured, but returning an action handler that
	 * will be invoked when selecting to configure. By default this is provided
	 * by a button.
	 *

	 * If there is no ability to configure the given item, then this should
	 * return null.
	 *
	 * @param owner
	 *            the owning dialog to be used when displaying dialogues for
	 *            configuration options
	 * @return an action that allows the element being viewed to be configured.
	 */
	public Action getConfigureAction(Frame owner) {
		return null;
	}

	/**
	 * This must be called by any sub-classes after they have initialised
	 * their own view since it gets their main panel and adds it to the main
	 * contextual view. If you don't do this you will get a very empty frame
	 * popping up!
	 */
	public void initView() {
		setLayout(new BorderLayout());
		add(getMainFrame(), CENTER);
		setName(getViewTitle());
	}

	public abstract void refreshView();

	public abstract int getPreferredPosition();

	public static String getTextFromDepth(String kind, Integer depth) {
		String labelText = "The last prediction said the " + kind;
		if (depth == null) {
			labelText += " would not transmit a value";
		} else if (depth == -1) {
			labelText += " was invalid/unpredicted";
		} else if (depth == 0) {
			labelText += " would carry a single value";
		} else {
			labelText += " would carry a list of depth " + depth;
		}
		return labelText;
	}
}


/*
 * Copyright 2009-2010 the original author or authors.
 *
 * Licensed 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 org.springframework.batch.admin.web;

public class LaunchRequest {
	private String jobName;

	String jobParameters;

	public String getJobName() {
		return jobName;
	}

	public void setJobName(String jobName) {
		this.jobName = jobName;
	}

	public String getJobParameters() {
		return jobParameters;
	}

	public void setJobParameters(String jobParameters) {
		this.jobParameters = jobParameters;
	}

}


/*
 * 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 org.apache.deltaspike.jsf.impl.injection;

import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import java.io.Serializable;

class DependentBeanEntry<T> implements Serializable
{
    private static final long serialVersionUID = 7148484695430831322L;

    private final T instance;
    private final Bean<?> bean;
    private final CreationalContext<T> creationalContext;

    DependentBeanEntry(T instance, Bean<?> bean, CreationalContext<T> creationalContext)
    {
        this.instance = instance;
        this.bean = bean;
        this.creationalContext = creationalContext;
    }

    T getInstance()
    {
        return instance;
    }

    Bean<?> getBean()
    {
        return bean;
    }

    CreationalContext<T> getCreationalContext()
    {
        return creationalContext;
    }
}


/**
 * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
 */
package com.oracle.bmc.waas.requests;

import com.oracle.bmc.waas.model.*;

@javax.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: 20181116")
@lombok.Builder(builderClassName = "Builder", buildMethodName = "buildWithoutInvocationCallback")
@lombok.Getter
public class CreateCertificateRequest extends com.oracle.bmc.requests.BmcRequest {

    /**
     * The details of the SSL certificate resource to create.
     */
    private CreateCertificateDetails createCertificateDetails;

    /**
     * The unique Oracle-assigned identifier for the request. If you need to contact Oracle about a particular request, please provide the request ID.
     */
    private String opcRequestId;

    /**
     * A token that uniquely identifies a request so it can be retried in case of a timeout or server error without risk of executing that same action again. Retry tokens expire after 24 hours, but can be invalidated before then due to conflicting operations
     * *Example:* If a resource has been deleted and purged from the system, then a retry of the original delete request may be rejected.
     */
    private String opcRetryToken;

    public static class Builder {
        private com.oracle.bmc.util.internal.Consumer<javax.ws.rs.client.Invocation.Builder>
                invocationCallback = null;

        /**
         * Set the invocation callback for the request to be built.
         * @param invocationCallback the invocation callback to be set for the request
         * @return this builder instance
         */
        public Builder invocationCallback(
                com.oracle.bmc.util.internal.Consumer<javax.ws.rs.client.Invocation.Builder>
                        invocationCallback) {
            this.invocationCallback = invocationCallback;
            return this;
        }

        /**
         * Copy method to populate the builder with values from the given instance.
         * @return this builder instance
         */
        public Builder copy(CreateCertificateRequest o) {
            createCertificateDetails(o.getCreateCertificateDetails());
            opcRequestId(o.getOpcRequestId());
            opcRetryToken(o.getOpcRetryToken());
            invocationCallback(o.getInvocationCallback());
            return this;
        }

        /**
         * Build the instance of CreateCertificateRequest as configured by this builder
         *
         * Note that this method takes calls to {@link Builder#invocationCallback(com.oracle.bmc.util.internal.Consumer)} into account,
         * while the method {@link Builder#buildWithoutInvocationCallback} does not.
         *
         * This is the preferred method to build an instance.
         *
         * @return instance of CreateCertificateRequest
         */
        public CreateCertificateRequest build() {
            CreateCertificateRequest request = buildWithoutInvocationCallback();
            request.setInvocationCallback(invocationCallback);
            return request;
        }
    }
}


/*
 * Copyright (c) 2012-2018 Red Hat, Inc.
 * This program and the accompanying materials are made
 * available under the terms of the Eclipse Public License 2.0
 * which is available at https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 *   Red Hat, Inc. - initial API and implementation
 */
package org.eclipse.che.api.factory.server.jpa;

import com.google.inject.AbstractModule;
import org.eclipse.che.api.factory.server.jpa.JpaFactoryDao.RemoveFactoriesBeforeUserRemovedEventSubscriber;
import org.eclipse.che.api.factory.server.spi.FactoryDao;

/** @author Yevhenii Voevodin */
public class FactoryJpaModule extends AbstractModule {
  @Override
  protected void configure() {
    bind(FactoryDao.class).to(JpaFactoryDao.class);
    bind(RemoveFactoriesBeforeUserRemovedEventSubscriber.class).asEagerSingleton();
  }
}


// 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 org.apache.cloudstack.api.response;

import com.google.gson.annotations.SerializedName;

import org.apache.cloudstack.api.BaseResponse;

import com.cloud.serializer.Param;

public class SuccessResponse extends BaseResponse {
    @SerializedName("success")
    @Param(description = "true if operation is executed successfully")
    private Boolean success = true;

    @SerializedName("displaytext")
    @Param(description = "any text associated with the success or failure")
    private String displayText;

    public Boolean getSuccess() {
        return success;
    }

    public void setSuccess(Boolean success) {
        this.success = success;
    }

    public String getDisplayText() {
        return displayText;
    }

    public void setDisplayText(String displayText) {
        this.displayText = displayText;
    }

    public SuccessResponse() {
    }

    public SuccessResponse(String responseName) {
        super.setResponseName(responseName);
    }
}


/*
 * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package sun.lwawt.macosx;

import java.awt.*;
import java.awt.event.FocusEvent;

import sun.java2d.SurfaceData;
import sun.java2d.opengl.CGLLayer;
import sun.lwawt.LWWindowPeer;
import sun.lwawt.PlatformWindow;
import sun.util.logging.PlatformLogger;

/*
 * Provides a lightweight implementation of the EmbeddedFrame.
 */
public class CPlatformEmbeddedFrame implements PlatformWindow {

    private static final PlatformLogger focusLogger = PlatformLogger.getLogger(
            "sun.lwawt.macosx.focus.CPlatformEmbeddedFrame");

    private CGLLayer windowLayer;
    private LWWindowPeer peer;
    private CEmbeddedFrame target;

    private volatile int screenX = 0;
    private volatile int screenY = 0;

    @Override // PlatformWindow
    public void initialize(Window target, final LWWindowPeer peer, PlatformWindow owner) {
        this.peer = peer;
        this.windowLayer = new CGLLayer(peer);
        this.target = (CEmbeddedFrame)target;
    }

    @Override
    public LWWindowPeer getPeer() {
        return peer;
    }

    @Override
    public long getLayerPtr() {
        return windowLayer.getPointer();
    }

    @Override
    public void dispose() {
        windowLayer.dispose();
    }

    @Override
    public void setBounds(int x, int y, int w, int h) {
        // This is a lightweight implementation of the EmbeddedFrame
        // and we simply synthesize a reshape request.
        screenX = x;
        screenY = y;
        peer.notifyReshape(x, y, w, h);
    }

    @Override
    public GraphicsDevice getGraphicsDevice() {
        // REMIND: return the main screen for the initial implementation
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        return ge.getDefaultScreenDevice();
    }

    @Override
    public Point getLocationOnScreen() {
        return new Point(screenX, screenY);
    }

    @Override
    public FontMetrics getFontMetrics(Font f) {
        throw new RuntimeException("Not implemented");
    }

    @Override
    public SurfaceData getScreenSurface() {
        return windowLayer.getSurfaceData();
    }

    @Override
    public SurfaceData replaceSurfaceData() {
        return windowLayer.replaceSurfaceData();
    }

    @Override
    public void setVisible(boolean visible) {}

    @Override
    public void setTitle(String title) {}

    @Override
    public Insets getInsets() {
        return new Insets(0, 0, 0, 0);
    }

    @Override
    public void toFront() {}

    @Override
    public void toBack() {}

    @Override
    public void setMenuBar(MenuBar mb) {}

    @Override
    public void setAlwaysOnTop(boolean value) {}

    @Override
    public void updateFocusableWindowState() {}

    @Override
    public boolean rejectFocusRequest(FocusEvent.Cause cause) {
        // Cross-app activation requests are not allowed.
        if (cause != FocusEvent.Cause.MOUSE_EVENT &&
            !target.isParentWindowActive())
        {
            focusLogger.fine("the embedder is inactive, so the request is rejected");
            return true;
        }
        return false;
    }

    @Override
    public boolean requestWindowFocus() {
        CEmbeddedFrame.updateGlobalFocusedWindow(target);
        target.synthesizeWindowActivation(true);
        return true;
    }

    @Override
    public boolean isActive() {
        return true;
    }

    @Override
    public void setResizable(boolean resizable) {}

    @Override
    public void setSizeConstraints(int minW, int minH, int maxW, int maxH) {}

    @Override
    public void updateIconImages() {}

    @Override
    public void setOpacity(float opacity) {}

    @Override
    public void setOpaque(boolean isOpaque) {}

    @Override
    public void enterFullScreenMode() {}

    @Override
    public void exitFullScreenMode() {}

    @Override
    public boolean isFullScreenMode() {
        return false;
    }

    @Override
    public void setWindowState(int windowState) {}

    @Override
    public void setModalBlocked(boolean blocked) {}

    /*
     * The method could not be implemented due to CALayer restrictions.
     * The exeption enforce clients not to use it.
     */
    @Override
    public boolean isUnderMouse() {
        throw new RuntimeException("Not implemented");
    }
}


/*
 * Copyright (C) 2006 The Guava Authors
 *
 * Licensed 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 com.google.common.util.concurrent;

import static com.google.common.util.concurrent.MoreExecutors.directExecutor;

import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Preconditions;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;

/**
 * Implementation of {@code Futures#withTimeout}.
 *
 * <p>Future that delegates to another but will finish early (via a {@link TimeoutException} wrapped
 * in an {@link ExecutionException}) if the specified duration expires. The delegate future is
 * interrupted and cancelled if it times out.
 */
@GwtIncompatible
final class TimeoutFuture<V> extends FluentFuture.TrustedFuture<V> {
  static <V> ListenableFuture<V> create(
      ListenableFuture<V> delegate,
      long time,
      TimeUnit unit,
      ScheduledExecutorService scheduledExecutor) {
    TimeoutFuture<V> result = new TimeoutFuture<>(delegate);
    Fire<V> fire = new Fire<>(result);
    result.timer = scheduledExecutor.schedule(fire, time, unit);
    delegate.addListener(fire, directExecutor());
    return result;
  }

  /*
   * Memory visibility of these fields. There are two cases to consider.
   *
   * 1. visibility of the writes to these fields to Fire.run:
   *
   * The initial write to delegateRef is made definitely visible via the semantics of
   * addListener/SES.schedule. The later racy write in cancel() is not guaranteed to be observed,
   * however that is fine since the correctness is based on the atomic state in our base class. The
   * initial write to timer is never definitely visible to Fire.run since it is assigned after
   * SES.schedule is called. Therefore Fire.run has to check for null. However, it should be visible
   * if Fire.run is called by delegate.addListener since addListener is called after the assignment
   * to timer, and importantly this is the main situation in which we need to be able to see the
   * write.
   *
   * 2. visibility of the writes to an afterDone() call triggered by cancel():
   *
   * Since these fields are non-final that means that TimeoutFuture is not being 'safely published',
   * thus a motivated caller may be able to expose the reference to another thread that would then
   * call cancel() and be unable to cancel the delegate.
   * There are a number of ways to solve this, none of which are very pretty, and it is currently
   * believed to be a purely theoretical problem (since the other actions should supply sufficient
   * write-barriers).
   */

  @NullableDecl private ListenableFuture<V> delegateRef;
  @NullableDecl private ScheduledFuture<?> timer;

  private TimeoutFuture(ListenableFuture<V> delegate) {
    this.delegateRef = Preconditions.checkNotNull(delegate);
  }

  /** A runnable that is called when the delegate or the timer completes. */
  private static final class Fire<V> implements Runnable {
    @NullableDecl TimeoutFuture<V> timeoutFutureRef;

    Fire(TimeoutFuture<V> timeoutFuture) {
      this.timeoutFutureRef = timeoutFuture;
    }

    @Override
    public void run() {
      // If either of these reads return null then we must be after a successful cancel or another
      // call to this method.
      TimeoutFuture<V> timeoutFuture = timeoutFutureRef;
      if (timeoutFuture == null) {
        return;
      }
      ListenableFuture<V> delegate = timeoutFuture.delegateRef;
      if (delegate == null) {
        return;
      }

      /*
       * If we're about to complete the TimeoutFuture, we want to release our reference to it.
       * Otherwise, we'll pin it (and its result) in memory until the timeout task is GCed. (The
       * need to clear our reference to the TimeoutFuture is the reason we use a *static* nested
       * class with a manual reference back to the "containing" class.)
       *
       * This has the nice-ish side effect of limiting reentrancy: run() calls
       * timeoutFuture.setException() calls run(). That reentrancy would already be harmless, since
       * timeoutFuture can be set (and delegate cancelled) only once. (And "set only once" is
       * important for other reasons: run() can still be invoked concurrently in different threads,
       * even with the above null checks.)
       */
      timeoutFutureRef = null;
      if (delegate.isDone()) {
        timeoutFuture.setFuture(delegate);
      } else {
        try {
          ScheduledFuture<?> timer = timeoutFuture.timer;
          String message = "Timed out";
          if (timer != null) {
            long overDelayMs = Math.abs(timer.getDelay(TimeUnit.MILLISECONDS));
            if (overDelayMs > 10) { // Not all timing drift is worth reporting
              message += " (timeout delayed by " + overDelayMs + " ms after scheduled time)";
            }
          }
          timeoutFuture.timer = null; // Don't include already elapsed delay in delegate.toString()
          timeoutFuture.setException(new TimeoutFutureException(message + ": " + delegate));
        } finally {
          delegate.cancel(true);
        }
      }
    }
  }

  private static final class TimeoutFutureException extends TimeoutException {
    private TimeoutFutureException(String message) {
      super(message);
    }

    @Override
    public synchronized Throwable fillInStackTrace() {
      setStackTrace(new StackTraceElement[0]);
      return this; // no stack trace, wouldn't be useful anyway
    }
  }

  @Override
  protected String pendingToString() {
    ListenableFuture<? extends V> localInputFuture = delegateRef;
    ScheduledFuture<?> localTimer = timer;
    if (localInputFuture != null) {
      String message = "inputFuture=[" + localInputFuture + "]";
      if (localTimer != null) {
        final long delay = localTimer.getDelay(TimeUnit.MILLISECONDS);
        // Negative delays look confusing in an error message
        if (delay > 0) {
          message += ", remaining delay=[" + delay + " ms]";
        }
      }
      return message;
    }
    return null;
  }

  @Override
  protected void afterDone() {
    maybePropagateCancellationTo(delegateRef);

    Future<?> localTimer = timer;
    // Try to cancel the timer as an optimization.
    // timer may be null if this call to run was by the timer task since there is no happens-before
    // edge between the assignment to timer and an execution of the timer task.
    if (localTimer != null) {
      localTimer.cancel(false);
    }

    delegateRef = null;
    timer = null;
  }
}


package main;

public class Main {
    public static void main (String[] args) {
    }
}


/*
 * Copyright 2012-2018 the original author or authors.
 *
 * Licensed 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
 *
 *      https://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 org.springframework.boot.actuate.autoconfigure.web.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.boot.actuate.autoconfigure.web.ManagementContextConfiguration;
import org.springframework.boot.actuate.autoconfigure.web.ManagementContextType;
import org.springframework.context.annotation.DeferredImportSelector;
import org.springframework.core.OrderComparator;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.support.SpringFactoriesLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
import org.springframework.util.StringUtils;

/**
 * Selects configuration classes for the management context configuration. Entries are
 * loaded from {@code /META-INF/spring.factories} under the
 * {@code org.springframework.boot.actuate.autoconfigure.web.ManagementContextConfiguration}
 * key.
 *
 * @author Dave Syer
 * @author Phillip Webb
 * @author Andy Wilkinson
 * @see ManagementContextConfiguration
 */
@Order(Ordered.LOWEST_PRECEDENCE)
class ManagementContextConfigurationImportSelector
		implements DeferredImportSelector, BeanClassLoaderAware {

	private ClassLoader classLoader;

	@Override
	public String[] selectImports(AnnotationMetadata metadata) {
		ManagementContextType contextType = (ManagementContextType) metadata
				.getAnnotationAttributes(EnableManagementContext.class.getName())
				.get("value");
		// Find all management context configuration classes, filtering duplicates
		List<ManagementConfiguration> configurations = getConfigurations();
		OrderComparator.sort(configurations);
		List<String> names = new ArrayList<>();
		for (ManagementConfiguration configuration : configurations) {
			if (configuration.getContextType() == ManagementContextType.ANY
					|| configuration.getContextType() == contextType) {
				names.add(configuration.getClassName());
			}
		}
		return StringUtils.toStringArray(names);
	}

	private List<ManagementConfiguration> getConfigurations() {
		SimpleMetadataReaderFactory readerFactory = new SimpleMetadataReaderFactory(
				this.classLoader);
		List<ManagementConfiguration> configurations = new ArrayList<>();
		for (String className : loadFactoryNames()) {
			addConfiguration(readerFactory, configurations, className);
		}
		return configurations;
	}

	private void addConfiguration(SimpleMetadataReaderFactory readerFactory,
			List<ManagementConfiguration> configurations, String className) {
		try {
			MetadataReader metadataReader = readerFactory.getMetadataReader(className);
			configurations.add(new ManagementConfiguration(metadataReader));
		}
		catch (IOException ex) {
			throw new RuntimeException(
					"Failed to read annotation metadata for '" + className + "'", ex);
		}
	}

	protected List<String> loadFactoryNames() {
		return SpringFactoriesLoader
				.loadFactoryNames(ManagementContextConfiguration.class, this.classLoader);
	}

	@Override
	public void setBeanClassLoader(ClassLoader classLoader) {
		this.classLoader = classLoader;
	}

	/**
	 * A management configuration class which can be sorted according to {@code @Order}.
	 */
	private static final class ManagementConfiguration implements Ordered {

		private final String className;

		private final int order;

		private final ManagementContextType contextType;

		ManagementConfiguration(MetadataReader metadataReader) {
			AnnotationMetadata annotationMetadata = metadataReader
					.getAnnotationMetadata();
			this.order = readOrder(annotationMetadata);
			this.className = metadataReader.getClassMetadata().getClassName();
			this.contextType = readContextType(annotationMetadata);
		}

		private ManagementContextType readContextType(
				AnnotationMetadata annotationMetadata) {
			Map<String, Object> annotationAttributes = annotationMetadata
					.getAnnotationAttributes(
							ManagementContextConfiguration.class.getName());
			return (annotationAttributes != null)
					? (ManagementContextType) annotationAttributes.get("value")
					: ManagementContextType.ANY;
		}

		private int readOrder(AnnotationMetadata annotationMetadata) {
			Map<String, Object> attributes = annotationMetadata
					.getAnnotationAttributes(Order.class.getName());
			Integer order = (attributes != null) ? (Integer) attributes.get("value")
					: null;
			return (order != null) ? order : Ordered.LOWEST_PRECEDENCE;
		}

		public String getClassName() {
			return this.className;
		}

		@Override
		public int getOrder() {
			return this.order;
		}

		public ManagementContextType getContextType() {
			return this.contextType;
		}

	}

}


/**
 * 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 org.apache.tez.runtime.library.common.shuffle.orderedgrouped;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableUtils;

/**
 * Shuffle Header information that is sent by the TaskTracker and
 * deciphered by the Fetcher thread of Reduce task
 *
 */
@InterfaceAudience.Private
@InterfaceStability.Stable
public class ShuffleHeader implements Writable {

  /** Header info of the shuffle http request/response */
  public static final String HTTP_HEADER_NAME = "name";
  public static final String DEFAULT_HTTP_HEADER_NAME = "mapreduce";
  public static final String HTTP_HEADER_VERSION = "version";
  public static final String DEFAULT_HTTP_HEADER_VERSION = "1.0.0";

  /**
   * The longest possible length of task attempt id that we will accept.
   */
  private static final int MAX_ID_LENGTH = 1000;

  String mapId;
  long uncompressedLength;
  long compressedLength;
  int forReduce;

  public ShuffleHeader() { }

  public ShuffleHeader(String mapId, long compressedLength,
      long uncompressedLength, int forReduce) {
    this.mapId = mapId;
    this.compressedLength = compressedLength;
    this.uncompressedLength = uncompressedLength;
    this.forReduce = forReduce;
  }

  public String getMapId() {
    return this.mapId;
  }

  public int getPartition() {
    return this.forReduce;
  }

  public long getUncompressedLength() {
    return uncompressedLength;
  }

  public long getCompressedLength() {
    return compressedLength;
  }

  public void readFields(DataInput in) throws IOException {
    mapId = WritableUtils.readStringSafely(in, MAX_ID_LENGTH);
    compressedLength = WritableUtils.readVLong(in);
    uncompressedLength = WritableUtils.readVLong(in);
    forReduce = WritableUtils.readVInt(in);
  }

  public int writeLength() throws IOException {
    int length = 0;
    int mapIdLength = Text.encode(mapId).limit();
    length += mapIdLength;

    length += WritableUtils.getVIntSize(mapIdLength);
    length += WritableUtils.getVIntSize(compressedLength);
    length += WritableUtils.getVIntSize(uncompressedLength);
    length += WritableUtils.getVIntSize(forReduce);

    return length;
  }
  public void write(DataOutput out) throws IOException {
    Text.writeString(out, mapId);
    WritableUtils.writeVLong(out, compressedLength);
    WritableUtils.writeVLong(out, uncompressedLength);
    WritableUtils.writeVInt(out, forReduce);
  }
}


/*
 * 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.
 */
/*
 * $Id$
 */
package org.apache.xml.dtm.ref;

/**
 * The class ExtendedType represents an extended type object used by
 * ExpandedNameTable.
 */
public final class ExtendedType
{
    private int nodetype;
    private String namespace;
    private String localName;
    private int hash;

    /**
     * Create an ExtendedType object from node type, namespace and local name.
     * The hash code is calculated from the node type, namespace and local name.
     *
     * @param nodetype Type of the node
     * @param namespace Namespace of the node
     * @param localName Local name of the node
     */
    public ExtendedType (int nodetype, String namespace, String localName)
    {
      this.nodetype = nodetype;
      this.namespace = namespace;
      this.localName = localName;
      this.hash = nodetype + namespace.hashCode() + localName.hashCode();
    }

    /**
     * Create an ExtendedType object from node type, namespace, local name
     * and a given hash code.
     *
     * @param nodetype Type of the node
     * @param namespace Namespace of the node
     * @param localName Local name of the node
     * @param hash The given hash code
     */
    public ExtendedType (int nodetype, String namespace, String localName, int hash)
    {
      this.nodetype = nodetype;
      this.namespace = namespace;
      this.localName = localName;
      this.hash = hash;
    }

    /**
     * Redefine this ExtendedType object to represent a different extended type.
     * This is intended to be used ONLY on the hashET object. Using it elsewhere
     * will mess up existing hashtable entries!
     */
    protected void redefine(int nodetype, String namespace, String localName)
    {
      this.nodetype = nodetype;
      this.namespace = namespace;
      this.localName = localName;
      this.hash = nodetype + namespace.hashCode() + localName.hashCode();
    }

    /**
     * Redefine this ExtendedType object to represent a different extended type.
     * This is intended to be used ONLY on the hashET object. Using it elsewhere
     * will mess up existing hashtable entries!
     */
    protected void redefine(int nodetype, String namespace, String localName, int hash)
    {
      this.nodetype = nodetype;
      this.namespace = namespace;
      this.localName = localName;
      this.hash = hash;
    }

    /**
     * Override the hashCode() method in the Object class
     */
    public int hashCode()
    {
      return hash;
    }

    /**
     * Test if this ExtendedType object is equal to the given ExtendedType.
     *
     * @param other The other ExtendedType object to test for equality
     * @return true if the two ExtendedType objects are equal.
     */
    public boolean equals(ExtendedType other)
    {
      try
      {
        return other.nodetype == this.nodetype &&
                other.localName.equals(this.localName) &&
                other.namespace.equals(this.namespace);
      }
      catch(NullPointerException e)
      {
        return false;
      }
    }

    /**
     * Return the node type
     */
    public int getNodeType()
    {
      return nodetype;
    }

    /**
     * Return the local name
     */
    public String getLocalName()
    {
      return localName;
    }

    /**
     * Return the namespace
     */
    public String getNamespace()
    {
      return namespace;
    }

}


/*
 * 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 org.apache.camel.processor.aggregate;

/**
 * A default {@link org.apache.camel.processor.aggregate.AggregateController} that offers Java and JMX API.
 */
public class DefaultAggregateController implements AggregateController {

    private AggregateProcessor processor;

    public void onStart(AggregateProcessor processor) {
        this.processor = processor;
    }

    public void onStop(AggregateProcessor processor) {
        this.processor = null;
    }

    public int forceCompletionOfGroup(String key) {
        if (processor != null) {
            return processor.forceCompletionOfGroup(key);
        } else {
            return 0;
        }
    }

    public int forceCompletionOfAllGroups() {
        if (processor != null) {
            return processor.forceCompletionOfAllGroups();
        } else {
            return 0;
        }
    }

}


/*
 * Licensed 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 org.apache.karaf.cellar.config.shell;

import org.apache.karaf.cellar.config.Constants;
import org.apache.karaf.cellar.config.shell.completers.ClusterConfigCompleter;
import org.apache.karaf.cellar.core.CellarSupport;
import org.apache.karaf.cellar.core.Configurations;
import org.apache.karaf.cellar.core.Group;
import org.apache.karaf.cellar.core.event.EventType;
import org.apache.karaf.cellar.core.shell.CellarCommandSupport;
import org.apache.karaf.cellar.core.shell.completer.AllGroupsCompleter;
import org.apache.karaf.shell.api.action.Argument;
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.Completion;
import org.apache.karaf.shell.api.action.Option;
import org.apache.karaf.shell.api.action.lifecycle.Service;

import java.util.Set;

@Command(scope = "cluster", name = "config-block", description = "Change the blocking policy for a bundle")
@Service
public class BlockCommand extends CellarCommandSupport {

    @Argument(index = 0, name = "group", description = "The cluster group name", required = true, multiValued = false)
    @Completion(AllGroupsCompleter.class)
    String groupName;

    @Argument(index = 1, name = "pidPattern", description = "The configuration PID pattern", required = false, multiValued = false)
    @Completion(ClusterConfigCompleter.class)
    String pid;

    @Option(name = "-in", description = "Update the inbound direction", required = false, multiValued = false)
    boolean in = false;

    @Option(name = "-out", description = "Update the outbound direction", required = false, multiValued = false)
    boolean out = false;

    @Option(name = "-whitelist", description = "Allow the feature by updating the whitelist (false by default)", required = false, multiValued = false)
    boolean whitelist = false;

    @Option(name = "-blacklist", description = "Block the feature by updating the blacklist (true by default)", required = false, multiValued = false)
    boolean blacklist = false;

    public Object doExecute() throws Exception {

        Group group = groupManager.findGroupByName(groupName);
        if (group == null) {
            System.err.println("Cluster group " + groupName + " doesn't exist");
            return null;
        }

        CellarSupport support = new CellarSupport();
        support.setClusterManager(clusterManager);
        support.setGroupManager(groupManager);
        support.setConfigurationAdmin(configurationAdmin);

        if (!in && !out) {
            in = true;
            out = true;
        }
        if (!whitelist && !blacklist) {
            whitelist = true;
            blacklist = true;
        }

        if (pid == null || pid.isEmpty()) {
            // display mode
            if (in) {
                System.out.println("INBOUND:");
                if (whitelist) {
                    System.out.print("\twhitelist: ");
                    Set<String> list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND);
                    System.out.println(list.toString());
                }
                if (blacklist) {
                    System.out.print("\tblacklist: ");
                    Set<String> list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND);
                    System.out.println(list.toString());
                }
            }
            if (out) {
                System.out.println("OUTBOUND:");
                if (whitelist) {
                    System.out.print("\twhitelist: ");
                    Set<String> list = support.getListEntries(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND);
                    System.out.println(list.toString());
                }
                if (blacklist) {
                    System.out.print("\tblacklist: ");
                    Set<String> list = support.getListEntries(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND);
                    System.out.println(list.toString());
                }
            }
        } else {
            // edit mode
            System.out.println("Updating blocking policy for " + pid);
            if (in) {
                if (whitelist) {
                    System.out.println("\tinbound whitelist ...");
                    support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid);
                }
                if (blacklist) {
                    System.out.println("\tinbound blacklist ...");
                    support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, pid);
                }
            }
            if (out) {
                if (whitelist) {
                    System.out.println("\toutbound whitelist ...");
                    support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid);
                }
                if (blacklist) {
                    System.out.println("\toutbound blacklist ...");
                    support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, pid);
                }
            }
        }

        return null;
    }

}


/**
 * 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 org.apache.tajo.storage.jdbc;

import com.google.common.base.Function;
import org.apache.tajo.catalog.Column;
import org.apache.tajo.exception.TajoRuntimeException;
import org.apache.tajo.exception.UnsupportedException;
import org.apache.tajo.plan.Target;
import org.apache.tajo.plan.expr.EvalNode;
import org.apache.tajo.plan.logical.*;
import org.apache.tajo.util.StringUtils;

import javax.annotation.Nullable;
import java.sql.DatabaseMetaData;
import java.util.List;
import java.util.Stack;

/**
 * Generator to build a SQL statement from a plan fragment
 */
public class SQLBuilder {
  @SuppressWarnings("unused")
  private final DatabaseMetaData dbMetaData;
  private final SQLExpressionGenerator sqlExprGen;

  public static class SQLBuilderContext {
    StringBuilder sb;
  }

  public SQLBuilder(DatabaseMetaData dbMetaData, SQLExpressionGenerator exprGen) {
    this.dbMetaData = dbMetaData;
    this.sqlExprGen = exprGen;
  }

  public String build(String tableName, Column [] targets, @Nullable EvalNode filter, @Nullable Long limit) {

    StringBuilder selectClause = new StringBuilder("SELECT ");
    if (targets.length > 0) {
      selectClause.append(StringUtils.join(targets, ",", new Function<Column, String>() {
        @Override
        public String apply(@Nullable Column input) {
          return input.getSimpleName();
        }
      }));
    } else {
      selectClause.append("1");
    }
    selectClause.append(" ");

    StringBuilder fromClause = new StringBuilder("FROM ");
    fromClause.append(tableName).append(" ");

    StringBuilder whereClause = null;
    if (filter != null) {
      whereClause = new StringBuilder("WHERE ");
      whereClause.append(sqlExprGen.generate(filter)).append(" ");
    }

    StringBuilder limitClause = null;
    if (limit != null) {
      limitClause = new StringBuilder("LIMIT ");
      limitClause.append(limit).append(" ");
    }

    return generateSelectStmt(selectClause, fromClause, whereClause, limitClause);
  }

  public String generateSelectStmt(StringBuilder selectClause,
                                   StringBuilder fromClause,
                                   @Nullable StringBuilder whereClause,
                                   @Nullable StringBuilder limitClause) {
    return
        selectClause.toString() +
        fromClause.toString() +
        (whereClause != null ? whereClause.toString() : "") +
        (limitClause != null ? limitClause.toString() : "");
  }

  public String build(LogicalNode planPart) {
    SQLBuilderContext context = new SQLBuilderContext();
    visit(context, planPart, new Stack<LogicalNode>());
    return context.sb.toString();
  }

  public void visit(SQLBuilderContext context, LogicalNode node, Stack<LogicalNode> stack) {
    stack.push(node);

    switch (node.getType()) {
    case SCAN:
      visitScan(context, (ScanNode) node, stack);
      break;

    case GROUP_BY:
      visitGroupBy(context, (GroupbyNode) node, stack);
      break;

    case SELECTION:
      visitFilter(context, (SelectionNode) node, stack);
      break;

    case PROJECTION:
      visitProjection(context, (ProjectionNode) node, stack);
      break;

    case TABLE_SUBQUERY:
      visitDerivedSubquery(context, (TableSubQueryNode) node, stack);
      break;

    default:
      throw new TajoRuntimeException(new UnsupportedException("plan node '" + node.getType().name() + "'"));
    }

    stack.pop();
  }

  public void visitDerivedSubquery(SQLBuilderContext ctx, TableSubQueryNode derivedSubquery, Stack<LogicalNode> stack) {
    ctx.sb.append(" (");
    visit(ctx, derivedSubquery.getSubQuery(), stack);
    ctx.sb.append(" ) ").append(derivedSubquery.getTableName());
  }

  public void visitProjection(SQLBuilderContext ctx, ProjectionNode projection, Stack<LogicalNode> stack) {

    visit(ctx, projection.getChild(), stack);
  }

  public void visitGroupBy(SQLBuilderContext ctx, GroupbyNode groupby, Stack<LogicalNode> stack) {
    visit(ctx, groupby.getChild(), stack);
    ctx.sb.append("GROUP BY ").append(StringUtils.join(groupby.getGroupingColumns(), ",", 0)).append(" ");
  }

  public void visitFilter(SQLBuilderContext ctx, SelectionNode filter, Stack<LogicalNode> stack) {
    visit(ctx, filter.getChild(), stack);
    ctx.sb.append("WHERE " + sqlExprGen.generate(filter.getQual()));
  }

  public void visitScan(SQLBuilderContext ctx, ScanNode scan, Stack<LogicalNode> stack) {

    StringBuilder selectClause = new StringBuilder("SELECT ");
    if (scan.getTargets().size() > 0) {
      selectClause.append(generateTargetList(scan.getTargets()));
    } else {
      selectClause.append("1");
    }

    selectClause.append(" ");

    ctx.sb.append("FROM ").append(scan.getTableName()).append(" ");

    if (scan.hasAlias()) {
      ctx.sb.append("AS ").append(scan.getAlias()).append(" ");
    }

    if (scan.hasQual()) {
      ctx.sb.append("WHERE " + sqlExprGen.generate(scan.getQual()));
    }
  }

  public String generateTargetList(List<Target> targets) {
    return StringUtils.join(targets, ",", new Function<Target, String>() {
      @Override
      public String apply(@Nullable Target t) {
        StringBuilder sb = new StringBuilder(sqlExprGen.generate(t.getEvalTree()));
        if (t.hasAlias()) {
          sb.append(" AS ").append(t.getAlias());
        }
        return sb.toString();
      }
    });
  }
}


package basic;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamC2 {

    public static void main(String[] args) {
        System.out.println("This is Java8");
    }

    public static int run() {
        List<Integer> integers = Arrays.asList(1, 2, 3, 4);
        List<Integer> mapped = integers.stream().map(n -> n).collect(Collectors.toList());
        return mapped.size();
    }

}


/**
 * 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 org.apache.zookeeper.server;

import org.apache.zookeeper.common.Time;
import org.apache.zookeeper.server.metric.AvgMinMaxCounter;
import org.apache.zookeeper.server.quorum.BufferStats;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicLong;

/**
 * Basic Server Statistics
 */
public class ServerStats {
    private static final Logger LOG = LoggerFactory.getLogger(ServerStats.class);

    private final AtomicLong packetsSent = new AtomicLong();
    private final AtomicLong packetsReceived = new AtomicLong();

    private final AvgMinMaxCounter requestLatency = new AvgMinMaxCounter("request_latency");

    private AtomicLong fsyncThresholdExceedCount = new AtomicLong(0);

    private final BufferStats clientResponseStats = new BufferStats();

    private final Provider provider;
    private final long startTime = Time.currentElapsedTime();

    public interface Provider {
        public long getOutstandingRequests();
        public long getLastProcessedZxid();
        public String getState();
        public int getNumAliveConnections();
        public long getDataDirSize();
        public long getLogDirSize();
    }

    public ServerStats(Provider provider) {
        this.provider = provider;
    }

    // getters
    public long getMinLatency() {
        return requestLatency.getMin();
    }

    public double getAvgLatency() {
        return requestLatency.getAvg();
    }

    public long getMaxLatency() {
        return requestLatency.getMax();
    }

    public long getOutstandingRequests() {
        return provider.getOutstandingRequests();
    }

    public long getLastProcessedZxid(){
        return provider.getLastProcessedZxid();
    }

    public long getDataDirSize() {
        return provider.getDataDirSize();
    }

    public long getLogDirSize() {
        return provider.getLogDirSize();
    }

    public long getPacketsReceived() {
        return packetsReceived.get();
    }

    public long getPacketsSent() {
        return packetsSent.get();
    }

    public String getServerState() {
        return provider.getState();
    }

    /** The number of client connections alive to this server */
    public int getNumAliveClientConnections() {
    	return provider.getNumAliveConnections();
    }

    public long getUptime() {
        return Time.currentElapsedTime() - startTime;
    }

    public boolean isProviderNull() {
        return provider == null;
    }

    @Override
    public String toString(){
        StringBuilder sb = new StringBuilder();
        sb.append("Latency min/avg/max: " + getMinLatency() + "/"
                + getAvgLatency() + "/" + getMaxLatency() + "\n");
        sb.append("Received: " + getPacketsReceived() + "\n");
        sb.append("Sent: " + getPacketsSent() + "\n");
        sb.append("Connections: " + getNumAliveClientConnections() + "\n");

        if (provider != null) {
            sb.append("Outstanding: " + getOutstandingRequests() + "\n");
            sb.append("Zxid: 0x"+ Long.toHexString(getLastProcessedZxid())+ "\n");
        }
        sb.append("Mode: " + getServerState() + "\n");
        return sb.toString();
    }

    /**
     * Update request statistic. This should only be called from a request
     * that originated from that machine.
     */
    public void updateLatency(Request request, long currentTime) {
        long latency = currentTime - request.createTime;
        if (latency < 0) {
            return;
        }
        requestLatency.addDataPoint(latency);
        if (request.getHdr() != null) {
            // Only quorum request should have header
            ServerMetrics.UPDATE_LATENCY.add(latency);
        } else {
            // All read request should goes here
            ServerMetrics.READ_LATENCY.add(latency);
        }
    }

    public void resetLatency() {
        requestLatency.reset();
    }

    public void resetMaxLatency() {
        requestLatency.resetMax();
    }

    public void incrementPacketsReceived() {
        packetsReceived.incrementAndGet();
    }

    public void incrementPacketsSent() {
        packetsSent.incrementAndGet();
    }

    public void resetRequestCounters(){
        packetsReceived.set(0);
        packetsSent.set(0);
    }

    public long getFsyncThresholdExceedCount() {
        return fsyncThresholdExceedCount.get();
    }

    public void incrementFsyncThresholdExceedCount() {
        fsyncThresholdExceedCount.incrementAndGet();
    }

    public void resetFsyncThresholdExceedCount() {
        fsyncThresholdExceedCount.set(0);
    }

    public void reset() {
        resetLatency();
        resetRequestCounters();
        clientResponseStats.reset();
        ServerMetrics.resetAll();
    }

    public void updateClientResponseSize(int size) {
        clientResponseStats.setLastBufferSize(size);
    }

    public BufferStats getClientResponseStats() {
        return clientResponseStats;
    }
}


/*
 * 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 org.apache.pluto.container.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Collection;

import javax.portlet.ClientDataRequest;
import javax.portlet.PortletException;
import javax.servlet.ServletException;
import javax.servlet.http.Part;

import org.apache.pluto.container.PortletRequestContext;
import org.apache.pluto.container.PortletResponseContext;

/**
 * Implementation of the javax.portlet.ClientDataRequest interface.
 */
public abstract class ClientDataRequestImpl extends PortletRequestImpl implements ClientDataRequest
{
    /** Flag indicating if the HTTP body reader has been accessed. */
    protected boolean readerAccessed = false;

    public ClientDataRequestImpl(PortletRequestContext requestContext, PortletResponseContext responseContext, String lifecyclePhase)
    {
        super(requestContext, responseContext, lifecyclePhase);
    }

    private void checkPostedFormData()
    {
        if (getMethod().equals("POST"))
        {
            String contentType = getContentType();
            if (contentType == null || contentType.equals("application/x-www-form-urlencoded"))
            {
                throw new IllegalStateException("User request HTTP POST data is of type "
                                                + "application/x-www-form-urlencoded. "
                                                + "This data has been already processed "
                                                + "by the portlet-container and is available "
                                                + "as request parameters.");
            }
        }
    }

    public java.lang.String getCharacterEncoding()
    {
        return getServletRequest().getCharacterEncoding();
    }

    public int getContentLength()
    {
        return getServletRequest().getContentLength();
    }

    @Override
    public long getContentLengthLong()
    {
        return getServletRequest().getContentLengthLong();
    }

    @Override
    public Part getPart(String name) throws IOException, PortletException
    {
       try {
          return getServletRequest().getPart(name);
       } catch (ServletException e) {
          throw new PortletException(e);
       }
    }

    @Override
    public Collection<Part> getParts() throws IOException, PortletException
    {
       try {
          return getServletRequest().getParts();
       } catch (ServletException e) {
          throw new PortletException(e);
       }
    }

    public java.lang.String getContentType()
    {
        return getServletRequest().getContentType();
    }

    public String getMethod()
    {
        return getServletRequest().getMethod();
    }

    public InputStream getPortletInputStream() throws IOException
    {
        checkPostedFormData();
        // the HttpServletRequest will ensure that a IllegalStateException is thrown
        //   if getReader() was called earlier
        return getServletRequest().getInputStream();
    }

    public BufferedReader getReader()
    throws UnsupportedEncodingException, IOException
    {
        checkPostedFormData();
        // the HttpServletRequest will ensure that a IllegalStateException is thrown
        //   if getInputStream() was called earlier
        BufferedReader reader = getServletRequest().getReader();
        readerAccessed = true;
        return reader;

    }

    public void setCharacterEncoding(String encoding)
    throws UnsupportedEncodingException
    {
        if (readerAccessed)
        {
            throw new IllegalStateException("Cannot set character encoding "
                    + "after HTTP body reader is accessed.");
        }
        getServletRequest().setCharacterEncoding(encoding);
    }
}


/**
 * 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 org.apache.storm.starter.tools;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;

public class Rankings implements Serializable {

    private static final long serialVersionUID = -1549827195410578903L;
    private static final int  DEFAULT_COUNT    = 10;

    private final int            maxSize;
    private final List<Rankable> rankedItems = Lists.newArrayList();

    public Rankings() {
        this(DEFAULT_COUNT);
    }

    public Rankings(int topN) {
        if (topN < 1) {
            throw new IllegalArgumentException("topN must be >= 1");
        }
        maxSize = topN;
    }

    /**
     * Copy constructor.
     *
     * @param other
     */
    public Rankings(Rankings other) {
        this(other.maxSize());
        updateWith(other);
    }

    /**
     * @return the maximum possible number (size) of ranked objects this
     *         instance can hold
     */
    public int maxSize() {
        return maxSize;
    }

    /**
     * @return the number (size) of ranked objects this instance is currently
     *         holding
     */
    public int size() {
        return rankedItems.size();
    }

    /**
     * The returned defensive copy is only "somewhat" defensive. We do, for
     * instance, return a defensive copy of the enclosing List instance, and we
     * do try to defensively copy any contained Rankable objects, too. However,
     * the contract of {@link org.apache.storm.starter.tools.Rankable#copy()}
     * does not guarantee that any Object's embedded within a Rankable will be
     * defensively copied, too.
     *
     * @return a somewhat defensive copy of ranked items
     */
    public List<Rankable> getRankings() {
        List<Rankable> copy = Lists.newLinkedList();
        for (Rankable r : rankedItems) {
            copy.add(r.copy());
        }
        return ImmutableList.copyOf(copy);
    }

    public void updateWith(Rankings other) {
        for (Rankable r : other.getRankings()) {
            updateWith(r);
        }
    }

    public void updateWith(Rankable r) {
        synchronized (rankedItems) {
            addOrReplace(r);
            rerank();
            shrinkRankingsIfNeeded();
        }
    }

    private void addOrReplace(Rankable r) {
        Integer rank = findRankOf(r);
        if (rank != null) {
            rankedItems.set(rank, r);
        } else {
            rankedItems.add(r);
        }
    }

    private Integer findRankOf(Rankable r) {
        Object tag = r.getObject();
        for (int rank = 0; rank < rankedItems.size(); rank++) {
            Object cur = rankedItems.get(rank).getObject();
            if (cur.equals(tag)) {
                return rank;
            }
        }
        return null;
    }

    private void rerank() {
        Collections.sort(rankedItems);
        Collections.reverse(rankedItems);
    }

    private void shrinkRankingsIfNeeded() {
        if (rankedItems.size() > maxSize) {
            rankedItems.remove(maxSize);
        }
    }

    /**
     * Removes ranking entries that have a count of zero.
     */
    public void pruneZeroCounts() {
        int i = 0;
        while (i < rankedItems.size()) {
            if (rankedItems.get(i).getCount() == 0) {
                rankedItems.remove(i);
            } else {
                i++;
            }
        }
    }

    public String toString() {
        return rankedItems.toString();
    }

    /**
     * Creates a (defensive) copy of itself.
     */
    public Rankings copy() {
        return new Rankings(this);
    }
}


/* ====================================================================
   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 org.apache.poi.hssf.converter;

import org.apache.poi.POIDataSamples;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.util.XMLHelper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FilenameFilter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.assertNotNull;

@RunWith(Parameterized.class)
public class TestExcelConverterSuite
{
    /**
     * YK: a quick hack to exclude failing documents from the suite.
     */
    @SuppressWarnings("ArraysAsListWithZeroOrOneArgument")
    private static List<String> failingFiles = Arrays.asList(
            /* not failing, but requires more memory */
            "ex45698-22488.xls" );

    @Parameterized.Parameters(name="{index}: {0}")
    public static Iterable<Object[]> files() {
        List<Object[]> files = new ArrayList<>();
        File directory = POIDataSamples.getDocumentInstance().getFile(
                "../spreadsheet" );
        for ( final File child : directory.listFiles( new FilenameFilter()
        {
            @Override
            public boolean accept( File dir, String name )
            {
                return name.endsWith( ".xls" ) && !failingFiles.contains( name );
            }
        } ) )
        {
            files.add(new Object[] { child });
        }

        return files;
    }

    @Parameterized.Parameter
    public File child;

    @Test
    public void testFo() throws Exception
    {
        HSSFWorkbook workbook;
        try {
            workbook = ExcelToHtmlUtils.loadXls( child );
        } catch ( Exception exc ) {
            // unable to parse file -- not ExcelToFoConverter fault
            return;
        }

        ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter(
                XMLHelper.getDocumentBuilderFactory().newDocumentBuilder().newDocument() );
        excelToHtmlConverter.processWorkbook( workbook );

        StringWriter stringWriter = new StringWriter();

        Transformer transformer = TransformerFactory.newInstance()
                .newTransformer();
        transformer.setOutputProperty( OutputKeys.ENCODING, "utf-8" );
        transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
        transformer.setOutputProperty( OutputKeys.METHOD, "xml" );
        transformer.transform(
                new DOMSource( excelToHtmlConverter.getDocument() ),
                new StreamResult( stringWriter ) );

        assertNotNull(stringWriter.toString());
    }

    @Test
    public void testHtml() throws Exception
    {
        HSSFWorkbook workbook;
        try {
            workbook = ExcelToHtmlUtils.loadXls( child );
        } catch ( Exception exc ) {
            // unable to parse file -- not ExcelToFoConverter fault
            return;
        }

        ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter(
                XMLHelper.getDocumentBuilderFactory().newDocumentBuilder().newDocument() );
        excelToHtmlConverter.processWorkbook( workbook );

        StringWriter stringWriter = new StringWriter();

        Transformer transformer = TransformerFactory.newInstance()
                .newTransformer();
        transformer.setOutputProperty( OutputKeys.ENCODING, "utf-8" );
        transformer.setOutputProperty( OutputKeys.INDENT, "no" );
        transformer.setOutputProperty( OutputKeys.METHOD, "html" );
        transformer.transform(
                new DOMSource( excelToHtmlConverter.getDocument() ),
                new StreamResult( stringWriter ) );

        assertNotNull(stringWriter.toString());
    }
}


/*
 * 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 org.apache.syncope.core.provisioning.java.data;

import java.util.Iterator;
import java.util.stream.Collectors;
import org.apache.syncope.common.lib.SyncopeClientException;
import org.apache.syncope.common.lib.to.ApplicationTO;
import org.apache.syncope.common.lib.to.PrivilegeTO;
import org.apache.syncope.common.lib.types.ClientExceptionType;
import org.apache.syncope.core.persistence.api.dao.ApplicationDAO;
import org.apache.syncope.core.persistence.api.entity.Application;
import org.apache.syncope.core.persistence.api.entity.EntityFactory;
import org.apache.syncope.core.persistence.api.entity.Privilege;
import org.apache.syncope.core.provisioning.api.data.ApplicationDataBinder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ApplicationDataBinderImpl implements ApplicationDataBinder {

    private static final Logger LOG = LoggerFactory.getLogger(ApplicationDataBinder.class);

    @Autowired
    private ApplicationDAO applicationDAO;

    @Autowired
    private EntityFactory entityFactory;

    @Override
    public Application create(final ApplicationTO applicationTO) {
        return update(entityFactory.newEntity(Application.class), applicationTO);
    }

    @Override
    public Application update(final Application toBeUpdated, final ApplicationTO applicationTO) {
        toBeUpdated.setKey(applicationTO.getKey());
        Application application = applicationDAO.save(toBeUpdated);

        application.setDescription(applicationTO.getDescription());

        // 1. add or update all (valid) privileges from TO
        applicationTO.getPrivileges().forEach(privilegeTO -> {
            if (privilegeTO == null) {
                LOG.error("Null {}", PrivilegeTO.class.getSimpleName());
            } else {
                Privilege privilege = applicationDAO.findPrivilege(privilegeTO.getKey());
                if (privilege == null) {
                    privilege = entityFactory.newEntity(Privilege.class);
                    privilege.setKey(privilegeTO.getKey());
                    privilege.setApplication(application);

                    application.add(privilege);
                } else if (!application.equals(privilege.getApplication())) {
                    SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.InvalidPrivilege);
                    sce.getElements().add(
                            "Privilege " + privilege.getKey() + " already owned by " + privilege.getApplication());
                    throw sce;
                }

                privilege.setDescription(privilegeTO.getDescription());
                privilege.setSpec(privilegeTO.getSpec());
            }
        });

        // 2. remove all privileges not contained in the TO
        for (Iterator<? extends Privilege> itor = application.getPrivileges().iterator(); itor.hasNext();) {
            Privilege privilege = itor.next();
            if (!applicationTO.getPrivileges().stream().
                    anyMatch(privilegeTO -> privilege.getKey().equals(privilegeTO.getKey()))) {

                privilege.setApplication(null);
                itor.remove();
            }
        }

        return application;
    }

    @Override
    public PrivilegeTO getPrivilegeTO(final Privilege privilege) {
        PrivilegeTO privilegeTO = new PrivilegeTO();
        privilegeTO.setKey(privilege.getKey());
        privilegeTO.setDescription(privilege.getDescription());
        privilegeTO.setApplication(privilege.getApplication().getKey());
        privilegeTO.setSpec(privilege.getSpec());
        return privilegeTO;
    }

    @Override
    public ApplicationTO getApplicationTO(final Application application) {
        ApplicationTO applicationTO = new ApplicationTO();

        applicationTO.setKey(application.getKey());
        applicationTO.setDescription(application.getDescription());
        applicationTO.getPrivileges().addAll(
                application.getPrivileges().stream().map(privilege -> getPrivilegeTO(privilege)).
                        collect(Collectors.toList()));

        return applicationTO;
    }

}


/*******************************************************************************
 * Copyright (c) 2017 Pivotal Software, Inc.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * Pivotal Software, Inc. - initial API and implementation
 *******************************************************************************/
package org.springframework.ide.eclipse.boot.wizard;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.springframework.ide.eclipse.boot.core.initializr.InitializrServiceSpec.Dependency;
import org.springsource.ide.eclipse.commons.livexp.core.LiveExpression;
import org.springsource.ide.eclipse.commons.livexp.ui.ExpandableSection;
import org.springsource.ide.eclipse.commons.livexp.ui.IPageWithSections;
import org.springsource.ide.eclipse.commons.livexp.ui.Scroller;
import org.springsource.ide.eclipse.commons.livexp.ui.WizardPageSection;
import org.springsource.ide.eclipse.commons.livexp.util.Filter;

public class FilteredDependenciesSection extends WizardPageSection {

	private Composite dependencyArea;
	private Scroller scroller;

	private LiveExpression<Filter<Dependency>> filter;

	private Point sizeHint = new Point(SWT.DEFAULT, SWT.DEFAULT);

	private int columns = 1;
	private HierarchicalMultiSelectionFieldModel<Dependency> dependencies;

	public FilteredDependenciesSection(IPageWithSections owner, NewSpringBootWizardModel model,
			LiveExpression<Filter<Dependency>> filter) {
		this(owner, model.dependencies, filter);
	}

	public FilteredDependenciesSection(IPageWithSections owner,  HierarchicalMultiSelectionFieldModel<Dependency> dependencies,
			LiveExpression<Filter<Dependency>> filter) {
		super(owner);
		this.dependencies = dependencies;
		this.filter = filter;
	}

	public FilteredDependenciesSection sizeHint(Point sizeHint) {
		if (sizeHint != null) {
			this.sizeHint = sizeHint;
		}
		return this;
	}

	public FilteredDependenciesSection columns(int columns) {
		this.columns = columns;
		return this;
	}

	@Override
	public void createContents(Composite page) {
		scroller = new Scroller(page);
		GridDataFactory.fillDefaults().grab(true, true).minSize(sizeHint).hint(sizeHint).applyTo(scroller);
		dependencyArea = scroller.getBody();
		GridLayoutFactory.fillDefaults().applyTo(dependencyArea);
		GridDataFactory.fillDefaults().grab(true, true).applyTo(dependencyArea);
		Map<String, CheckboxExpandableSection<Dependency>> sectionsToRefresh = new HashMap<>();
		for (String cat : dependencies.getCategories()) {
			MultiSelectionFieldModel<Dependency> dependencyGroup = dependencies.getContents(cat);
			CheckBoxesSection<Dependency> checkboxesSection = new CheckBoxesSection<>(owner,
					dependencyGroup.getCheckBoxModels()).columns(columns);
			CheckboxExpandableSection<Dependency> expandable = new CheckboxExpandableSection<>(owner, dependencyGroup.getLabel(), checkboxesSection);
			expandable.createContents(dependencyArea);

			// Always expanded as it only shows selections. If there are no
			// selections, the expandable
			// section itself is hidden
			expandable.getExpansionState().setValue(false);

			sectionsToRefresh.put(cat, expandable);
		}
		this.filter.addListener((exp, value) -> {
			// PT 143003753: there is a bit of lag when deleting characters in text filter that produce a lot of
			// results. Consequently running this asynchronously.
			Display.getCurrent().asyncExec(() -> {
				for (String cat : dependencies.getCategories()) {
					CheckboxExpandableSection<Dependency> expandable = sectionsToRefresh.get(cat);
					if (expandable != null) {
						onFilter(expandable, expandable.getCheckBoxSection(), cat);
					}
				}
			});
		});
	}

	private void onFilter(ExpandableSection expandable, CheckBoxesSection<Dependency> checkboxesSection, String cat) {
		Filter<Dependency> filter = this.filter.getValue();
		checkboxesSection.applyFilter(filter);
		boolean isTrivialFilter = filter==null || filter.isTrivial();
		if (checkboxesSection.isCreated()) {
			boolean hasVisible = checkboxesSection.hasVisible();
			expandable.setVisible(hasVisible);
			if (hasVisible) {
				expandable.getExpansionState().setValue(!isTrivialFilter);
			}
		}
		layout();
	}

	private void layout() {
		if (dependencyArea != null && !dependencyArea.isDisposed()) {
			dependencyArea.layout(true);
			dependencyArea.getParent().layout(true);
		}
	}

	static class CheckboxExpandableSection<T> extends ExpandableSection {

		private CheckBoxesSection<T> checkBoxSection;
		public CheckboxExpandableSection(IPageWithSections owner, String title, CheckBoxesSection<T> checkBoxSection) {
			super(owner, title, checkBoxSection);
			this.checkBoxSection = checkBoxSection;
		}

		public CheckBoxesSection<T> getCheckBoxSection() {
			return checkBoxSection;
		}

	}
}


// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See License.txt in the repository root.

package com.microsoft.tfs.client.eclipse.project;

import java.text.MessageFormat;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.runtime.CoreException;

import com.microsoft.tfs.client.common.repository.TFSRepository;
import com.microsoft.tfs.client.eclipse.TFSRepositoryProvider;
import com.microsoft.tfs.client.eclipse.util.TeamUtils;
import com.microsoft.tfs.util.Check;

public class ProjectCloseListener implements IResourceChangeListener {
    private final Log log = LogFactory.getLog(ProjectCloseListener.class);

    private final ProjectRepositoryManager projectManager;

    public ProjectCloseListener(final ProjectRepositoryManager projectManager) {
        Check.notNull(projectManager, "projectManager"); //$NON-NLS-1$

        this.projectManager = projectManager;
    }

    @Override
    public void resourceChanged(final IResourceChangeEvent event) {
        if (event.getType() != IResourceChangeEvent.PRE_CLOSE || !(event.getResource() instanceof IProject)) {
            return;
        }

        final IProject project = (IProject) event.getResource();

        if (!project.isOpen()) {
            /* Sanity check */
            log.error(
                MessageFormat.format(
                    "Project Manager received close notification for project {0} (already closed)", //$NON-NLS-1$
                    project.getName()));

            return;
        }

        /* Exit if we don't manage this project */
        String providerName;
        try {
            providerName = project.getPersistentProperty(TeamUtils.PROVIDER_PROP_KEY);
        } catch (final CoreException e) {
            log.warn(
                MessageFormat.format(
                    "Could not query repository manager for project {0} (when handling close notification)", //$NON-NLS-1$
                    project.getName()),
                e);
            return;
        }

        if (providerName == null || !providerName.equals(TFSRepositoryProvider.PROVIDER_ID)) {
            return;
        }

        /*
         * If this is the only project for this connection, it will be
         * disconnected, thus we need to prompt for unsaved WIT changes.
         */
        final TFSRepository repository = projectManager.getRepository(project);

        if (repository != null) {
            final IProject[] allRepositoryProjects = projectManager.getProjectsForRepository(repository);

            if (allRepositoryProjects.length == 1 && allRepositoryProjects[0] == project) {
                /*
                 * Note: we have to ignore the cancel button here, there is no
                 * way to prevent the close from occurring.
                 */
                ProjectManagerDataProviderFactory.getDataProvider().promptForDisconnect();
            }
        }

        projectManager.close(project);
    }
}


/*
 * 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 org.apache.nifi.remote.cluster;

public class NodeInformation {

    private final String siteToSiteHostname;
    private final Integer siteToSitePort;
    private final Integer siteToSiteHttpApiPort;
    private final int apiPort;
    private final boolean isSiteToSiteSecure;
    private final int totalFlowFiles;

    public NodeInformation(final String siteToSiteHostname, final Integer siteToSitePort, final Integer siteToSiteHttpApiPort,
            final int apiPort, final boolean isSiteToSiteSecure, final int totalFlowFiles) {
        this.siteToSiteHostname = siteToSiteHostname;
        this.siteToSitePort = siteToSitePort;
        this.siteToSiteHttpApiPort = siteToSiteHttpApiPort;
        this.apiPort = apiPort;
        this.isSiteToSiteSecure = isSiteToSiteSecure;
        this.totalFlowFiles = totalFlowFiles;
    }

    public String getSiteToSiteHostname() {
        return siteToSiteHostname;
    }

    public int getAPIPort() {
        return apiPort;
    }

    public Integer getSiteToSitePort() {
        return siteToSitePort;
    }

    public Integer getSiteToSiteHttpApiPort() {
        return siteToSiteHttpApiPort;
    }

    public boolean isSiteToSiteSecure() {
        return isSiteToSiteSecure;
    }

    public int getTotalFlowFiles() {
        return totalFlowFiles;
    }

    @Override
    public boolean equals(final Object obj) {
        if (obj == this) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (!(obj instanceof NodeInformation)) {
            return false;
        }

        final NodeInformation other = (NodeInformation) obj;
        if (!siteToSiteHostname.equals(other.siteToSiteHostname)) {
            return false;
        }
        if (siteToSitePort == null && other.siteToSitePort != null) {
            return false;
        }
        if (siteToSitePort != null && other.siteToSitePort == null) {
            return false;
        } else if (siteToSitePort != null && siteToSitePort.intValue() != other.siteToSitePort.intValue()) {
            return false;
        }

        if (siteToSiteHttpApiPort == null && other.siteToSiteHttpApiPort != null) {
            return false;
        }
        if (siteToSiteHttpApiPort != null && other.siteToSiteHttpApiPort == null) {
            return false;
        } else if (siteToSiteHttpApiPort != null && siteToSiteHttpApiPort.intValue() != other.siteToSiteHttpApiPort.intValue()) {
            return false;
        }

        if (apiPort != other.apiPort) {
            return false;
        }
        if (isSiteToSiteSecure != other.isSiteToSiteSecure) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        return 83832 + siteToSiteHostname.hashCode() + (siteToSitePort == null ? 8 : siteToSitePort.hashCode()) + apiPort + (isSiteToSiteSecure ? 3829 : 0);
    }

    @Override
    public String toString() {
        return "Node[" + siteToSiteHostname + ":" + apiPort + "]";
    }
}