gt
stringclasses
1 value
context
stringlengths
2.05k
161k
/* * The MIT License (MIT) * * Copyright 2017 Alexander Orlov <alexander.orlov@loxal.net>. All rights reserved. * Copyright (c) [2016] [ <ether.camp> ] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package org.ethereum.net.rlpx.discover; import org.ethereum.net.rlpx.*; import org.ethereum.net.rlpx.discover.table.KademliaOptions; import org.ethereum.net.swarm.Util; import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; import java.net.InetSocketAddress; import java.util.List; import java.util.concurrent.TimeUnit; /** * The instance of this class responsible for discovery messages exchange with the specified Node * It also manages itself regarding inclusion/eviction from Kademlia table * * Created by Anton Nashatyrev on 14.07.2015. */ public class NodeHandler { private static final org.slf4j.Logger logger = LoggerFactory.getLogger("discover"); private static final long PingTimeout = 15000; //KademliaOptions.REQ_TIMEOUT; private static final int WARN_PACKET_SIZE = 1400; private static volatile int msgInCount = 0, msgOutCount = 0; private static boolean initialLogging = true; private final NodeManager nodeManager; Node node; private NodeStatistics nodeStatistics; private State state; private boolean waitForPong = false; private long pingSent; private int pingTrials = 3; private NodeHandler replaceCandidate; public NodeHandler(final Node node, final NodeManager nodeManager) { this.node = node; this.nodeManager = nodeManager; changeState(State.Discovered); } // gradually reducing log level for dumping discover messages // they are not so informative when everything is already up and running // but could be interesting when discovery just starts private void logMessage(final Message msg, final boolean inbound) { final String s = String.format("%s[%s (%s)] %s", inbound ? " ===> " : "<=== ", msg.getClass().getSimpleName(), msg.getPacket().length, this); if (msgInCount > 1024) { logger.trace(s); } else { logger.debug(s); } if (!inbound && msg.getPacket().length > WARN_PACKET_SIZE) { logger.warn("Sending UDP packet exceeding safe size of {} bytes, actual: {} bytes", WARN_PACKET_SIZE, msg.getPacket().length); logger.warn(s); } if (initialLogging) { if (msgOutCount == 0) { logger.info("Pinging discovery nodes..."); } if (msgInCount == 0 && inbound) { logger.info("Received response."); } if (inbound && msg instanceof NeighborsMessage) { logger.info("New peers discovered."); initialLogging = false; } } if (inbound) msgInCount++; else msgOutCount++; } private InetSocketAddress getInetSocketAddress() { return new InetSocketAddress(node.getHost(), node.getPort()); } public Node getNode() { return node; } public State getState() { return state; } public NodeStatistics getNodeStatistics() { if (nodeStatistics == null) { nodeStatistics = new NodeStatistics(node); } return nodeStatistics; } private void challengeWith(final NodeHandler replaceCandidate) { this.replaceCandidate = replaceCandidate; changeState(State.EvictCandidate); } // Manages state transfers private void changeState(State newState) { final State oldState = state; if (newState == State.Discovered) { // will wait for Pong to assume this alive sendPing(); } if (!node.isDiscoveryNode()) { if (newState == State.Alive) { final Node evictCandidate = nodeManager.table.addNode(this.node); if (evictCandidate == null) { newState = State.Active; } else { final NodeHandler evictHandler = nodeManager.getNodeHandler(evictCandidate); if (evictHandler.state != State.EvictCandidate) { evictHandler.challengeWith(this); } } } if (newState == State.Active) { if (oldState == State.Alive) { // new node won the challenge nodeManager.table.addNode(node); } else if (oldState == State.EvictCandidate) { // nothing to do here the node is already in the table } else { // wrong state transition } } if (newState == State.NonActive) { if (oldState == State.EvictCandidate) { // lost the challenge // Removing ourselves from the table nodeManager.table.dropNode(node); // Congratulate the winner replaceCandidate.changeState(State.Active); } else if (oldState == State.Alive) { // ok the old node was better, nothing to do here } else { // wrong state transition } } } if (newState == State.EvictCandidate) { // trying to survive, sending ping and waiting for pong sendPing(); } state = newState; stateChanged(oldState, newState); } private void stateChanged(final State oldState, final State newState) { logger.trace("State change " + oldState + " -> " + newState + ": " + this); nodeManager.stateChanged(this, oldState, newState); } void handlePing(final PingMessage msg) { logMessage(msg, true); // logMessage(" ===> [PING] " + this); getNodeStatistics().discoverInPing.add(); if (!nodeManager.table.getNode().equals(node)) { sendPong(msg.getMdc()); } } void handlePong(final PongMessage msg) { logMessage(msg, true); // logMessage(" ===> [PONG] " + this); if (waitForPong) { waitForPong = false; getNodeStatistics().discoverInPong.add(); getNodeStatistics().discoverMessageLatency.add(Util.curTime() - pingSent); getNodeStatistics().lastPongReplyTime.set(Util.curTime()); changeState(State.Alive); } } void handleNeighbours(final NeighborsMessage msg) { logMessage(msg, true); // logMessage(" ===> [NEIGHBOURS] " + this + ", Count: " + msg.getNodes().size()); getNodeStatistics().discoverInNeighbours.add(); for (final Node n : msg.getNodes()) { nodeManager.getNodeHandler(n); } } void handleFindNode(final FindNodeMessage msg) { logMessage(msg, true); // logMessage(" ===> [FIND_NODE] " + this); getNodeStatistics().discoverInFind.add(); final List<Node> closest = nodeManager.table.getClosestNodes(msg.getTarget()); final Node publicHomeNode = nodeManager.getPublicHomeNode(); if (publicHomeNode != null) { if (closest.size() == KademliaOptions.BUCKET_SIZE) closest.remove(closest.size() - 1); closest.add(publicHomeNode); } sendNeighbours(closest); } private void handleTimedOut() { waitForPong = false; if (--pingTrials > 0) { sendPing(); } else { if (state == State.Discovered) { changeState(State.Dead); } else if (state == State.EvictCandidate) { changeState(State.NonActive); } else { // TODO just influence to reputation } } } private void sendPing() { if (waitForPong) { logger.trace("<=/= [PING] (Waiting for pong) " + this); } // logMessage("<=== [PING] " + this); final Message ping = PingMessage.create(nodeManager.table.getNode(), getNode(), nodeManager.key); logMessage(ping, false); waitForPong = true; pingSent = Util.curTime(); sendMessage(ping); getNodeStatistics().discoverOutPing.add(); if (nodeManager.getPongTimer().isShutdown()) return; nodeManager.getPongTimer().schedule(() -> { try { if (waitForPong) { waitForPong = false; handleTimedOut(); } } catch (final Throwable t) { logger.error("Unhandled exception", t); } }, PingTimeout, TimeUnit.MILLISECONDS); } private void sendPong(final byte[] mdc) { // logMessage("<=== [PONG] " + this); final Message pong = PongMessage.create(mdc, node, nodeManager.key); logMessage(pong, false); sendMessage(pong); getNodeStatistics().discoverOutPong.add(); } private void sendNeighbours(final List<Node> neighbours) { // logMessage("<=== [NEIGHBOURS] " + this); final NeighborsMessage neighbors = NeighborsMessage.create(neighbours, nodeManager.key); logMessage(neighbors, false); sendMessage(neighbors); getNodeStatistics().discoverOutNeighbours.add(); } void sendFindNode(final byte[] target) { // logMessage("<=== [FIND_NODE] " + this); final Message findNode = FindNodeMessage.create(target, nodeManager.key); logMessage(findNode, false); sendMessage(findNode); getNodeStatistics().discoverOutFind.add(); } private void sendMessage(final Message msg) { nodeManager.sendOutbound(new DiscoveryEvent(msg, getInetSocketAddress())); } @Override public String toString() { return "NodeHandler[state: " + state + ", node: " + node.getHost() + ":" + node.getPort() + ", id=" + (node.getId().length > 0 ? Hex.toHexString(node.getId(), 0, 4) : "empty") + "]"; } public enum State { /** * The new node was just discovered either by receiving it with Neighbours * message or by receiving Ping from a new node * In either case we are sending Ping and waiting for Pong * If the Pong is received the node becomes {@link #Alive} * If the Pong was timed out the node becomes {@link #Dead} */ Discovered, /** * The node didn't send the Pong message back withing acceptable timeout * This is the final state */ Dead, /** * The node responded with Pong and is now the candidate for inclusion to the table * If the table has bucket space for this node it is added to table and becomes {@link #Active} * If the table bucket is full this node is challenging with the old node from the bucket * if it wins then old node is dropped, and this node is added and becomes {@link #Active} * else this node becomes {@link #NonActive} */ Alive, /** * The node is included in the table. It may become {@link #EvictCandidate} if a new node * wants to become Active but the table bucket is full. */ Active, /** * This node is in the table but is currently challenging with a new Node candidate * to survive in the table bucket * If it wins then returns back to {@link #Active} state, else is evicted from the table * and becomes {@link #NonActive} */ EvictCandidate, /** * Veteran. It was Alive and even Active but is now retired due to loosing the challenge * with another Node. * For no this is the final state * It's an option for future to return veterans back to the table */ NonActive } }
package com.reactnativenavigation.viewcontrollers.stack; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import com.reactnativenavigation.R; import com.reactnativenavigation.options.FabOptions; import com.reactnativenavigation.options.Options; import com.reactnativenavigation.utils.UiUtils; import com.reactnativenavigation.utils.ViewExtensionsKt; import com.reactnativenavigation.viewcontrollers.viewcontroller.ViewController; import com.reactnativenavigation.views.stack.fab.Fab; import com.reactnativenavigation.views.stack.fab.FabMenu; import androidx.annotation.NonNull; import androidx.coordinatorlayout.widget.CoordinatorLayout; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; import static com.github.clans.fab.FloatingActionButton.SIZE_MINI; import static com.github.clans.fab.FloatingActionButton.SIZE_NORMAL; import static com.reactnativenavigation.utils.ObjectUtils.perform; public class FabPresenter { private static final int DURATION = 200; private ViewGroup viewGroup; private Fab fab; private FabMenu fabMenu; public void applyOptions(FabOptions options, @NonNull ViewController<?> component, @NonNull ViewGroup viewGroup) { this.viewGroup = viewGroup; if (options.id.hasValue()) { if (fabMenu != null && fabMenu.getFabId().equals(options.id.get())) { fabMenu.bringToFront(); applyFabMenuOptions(component, fabMenu, options); setParams(component, fabMenu, options); } else if (fab != null && fab.getFabId().equals(options.id.get())) { fab.bringToFront(); setParams(component, fab, options); applyFabOptions(component, fab, options); fab.setOnClickListener(v -> component.sendOnNavigationButtonPressed(options.id.get())); } else { createFab(component, options); } } else { removeFab(); removeFabMenu(); } } public void mergeOptions(FabOptions options, @NonNull ViewController<?> component, @NonNull ViewGroup viewGroup) { this.viewGroup = viewGroup; if (options.id.hasValue()) { if (fabMenu != null && fabMenu.getFabId().equals(options.id.get())) { mergeParams(fabMenu, options); fabMenu.bringToFront(); mergeFabMenuOptions(component, fabMenu, options); } else if (fab != null && fab.getFabId().equals(options.id.get())) { mergeParams(fab, options); fab.bringToFront(); mergeFabOptions(component, fab, options); fab.setOnClickListener(v -> component.sendOnNavigationButtonPressed(options.id.get())); } else { createFab(component, options); } } } private void createFab(ViewController<?> component, FabOptions options) { ViewExtensionsKt.removeFromParent(fabMenu); ViewExtensionsKt.removeFromParent(fab); if (options.actionsArray.size() > 0) { fabMenu = new FabMenu(viewGroup.getContext(), options.id.get()); setParams(component, fabMenu, options); applyFabMenuOptions(component, fabMenu, options); viewGroup.addView(fabMenu); } else { fab = new Fab(viewGroup.getContext(), options.id.get()); setParams(component, fab, options); applyFabOptions(component, fab, options); viewGroup.addView(fab); fab.setOnClickListener(v -> component.sendOnNavigationButtonPressed(options.id.get())); UiUtils.doOnLayout(fab, () -> { fab.setPivotX(fab.getWidth() / 2f); fab.setPivotY(fab.getHeight() / 2f); }); } } private void removeFabMenu() { if (fabMenu != null) { fabMenu.hideMenuButton(true); viewGroup.removeView(fabMenu); fabMenu = null; } } private void removeFab() { if (fab != null) { animateHide(() -> { viewGroup.removeView(fab); fab = null; }); } } public void animateHide(Runnable onAnimationEnd) { fab.animate() .scaleX(0f) .scaleY(0f) .setDuration(DURATION) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { onAnimationEnd.run(); } }); } private void setParams(ViewController<?> component, View fab, FabOptions options) { CoordinatorLayout.LayoutParams lp = new CoordinatorLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT); lp.rightMargin = (int) viewGroup.getContext().getResources().getDimension(R.dimen.margin); lp.leftMargin = (int) viewGroup.getContext().getResources().getDimension(R.dimen.margin); lp.bottomMargin = component.getBottomInset() + (int) viewGroup.getContext().getResources().getDimension(R.dimen.margin); fab.setTag(R.id.fab_bottom_margin, (int) viewGroup.getContext().getResources().getDimension(R.dimen.margin)); lp.gravity = Gravity.BOTTOM; if (options.alignHorizontally.hasValue()) { if ("right".equals(options.alignHorizontally.get())) { lp.gravity |= Gravity.RIGHT; } if ("left".equals(options.alignHorizontally.get())) { lp.gravity |= Gravity.LEFT; } } else { lp.gravity |= Gravity.RIGHT; } fab.setLayoutParams(lp); } private void mergeParams(View fab, FabOptions options) { CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) perform( fab, new CoordinatorLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT), View::getLayoutParams ); fab.setTag(R.id.fab_bottom_margin, lp.leftMargin); lp.gravity = Gravity.BOTTOM; if (options.alignHorizontally.hasValue()) { if ("right".equals(options.alignHorizontally.get())) { lp.gravity |= Gravity.RIGHT; } if ("left".equals(options.alignHorizontally.get())) { lp.gravity |= Gravity.RIGHT; } } else { lp.gravity |= Gravity.RIGHT; } fab.setLayoutParams(lp); } private void applyFabOptions(ViewController<?> component, Fab fab, FabOptions options) { if (options.visible.isTrueOrUndefined()) { fab.setScaleX(0.6f); fab.setScaleY(0.6f); fab.animate() .scaleX(1f) .scaleY(1f) .setDuration(DURATION) .start(); } if (options.visible.isFalse()) { fab.animate() .scaleX(0f) .scaleY(0f) .setDuration(DURATION) .start(); } if (options.backgroundColor.hasValue()) { fab.setColorNormal(options.backgroundColor.get()); } if (options.clickColor.hasValue()) { fab.setColorPressed(options.clickColor.get()); } if (options.rippleColor.hasValue()) { fab.setColorRipple(options.rippleColor.get()); } if (options.icon.hasValue()) { fab.applyIcon(options.icon.get(), options.iconColor); } if (options.size.hasValue()) { fab.setButtonSize("mini".equals(options.size.get()) ? SIZE_MINI : SIZE_NORMAL); } if (options.hideOnScroll.isTrue()) { fab.enableCollapse(component.getScrollEventListener()); } if (options.hideOnScroll.isFalseOrUndefined()) { fab.disableCollapse(); } } private void mergeFabOptions(ViewController<?> component, Fab fab, FabOptions options) { if (options.visible.isTrue()) { fab.show(true); } if (options.visible.isFalse()) { fab.hide(true); } if (options.backgroundColor.hasValue()) { fab.setColorNormal(options.backgroundColor.get()); } if (options.clickColor.hasValue()) { fab.setColorPressed(options.clickColor.get()); } if (options.rippleColor.hasValue()) { fab.setColorRipple(options.rippleColor.get()); } if (options.icon.hasValue()) { fab.applyIcon(options.icon.get(), options.iconColor); } if (options.size.hasValue()) { fab.setButtonSize("mini".equals(options.size.get()) ? SIZE_MINI : SIZE_NORMAL); } if (options.hideOnScroll.isTrue()) { fab.enableCollapse(component.getScrollEventListener()); } if (options.hideOnScroll.isFalse()) { fab.disableCollapse(); } } private void applyFabMenuOptions(ViewController<?> component, FabMenu fabMenu, FabOptions options) { if (options.visible.isTrueOrUndefined()) { fabMenu.showMenuButton(true); } if (options.visible.isFalse()) { fabMenu.hideMenuButton(true); } if (options.backgroundColor.hasValue()) { fabMenu.setMenuButtonColorNormal(options.backgroundColor.get()); } if (options.clickColor.hasValue()) { fabMenu.setMenuButtonColorPressed(options.clickColor.get()); } if (options.rippleColor.hasValue()) { fabMenu.setMenuButtonColorRipple(options.rippleColor.get()); } for (Fab fabStored : fabMenu.getActions()) { fabMenu.removeMenuButton(fabStored); } fabMenu.getActions().clear(); for (FabOptions fabOption : options.actionsArray) { Fab fab = new Fab(viewGroup.getContext(), fabOption.id.get()); applyFabOptions(component, fab, fabOption); fab.setOnClickListener(v -> component.sendOnNavigationButtonPressed(options.id.get())); fabMenu.getActions().add(fab); fabMenu.addMenuButton(fab); } if (options.hideOnScroll.isTrue()) { fabMenu.enableCollapse(component.getScrollEventListener()); } if (options.hideOnScroll.isFalseOrUndefined()) { fabMenu.disableCollapse(); } } private void mergeFabMenuOptions(ViewController<?> component, FabMenu fabMenu, FabOptions options) { if (options.visible.isTrue()) { fabMenu.showMenuButton(true); } if (options.visible.isFalse()) { fabMenu.hideMenuButton(true); } if (options.backgroundColor.hasValue()) { fabMenu.setMenuButtonColorNormal(options.backgroundColor.get()); } if (options.clickColor.hasValue()) { fabMenu.setMenuButtonColorPressed(options.clickColor.get()); } if (options.rippleColor.hasValue()) { fabMenu.setMenuButtonColorRipple(options.rippleColor.get()); } if (options.actionsArray.size() > 0) { for (Fab fabStored : fabMenu.getActions()) { fabMenu.removeMenuButton(fabStored); } fabMenu.getActions().clear(); for (FabOptions fabOption : options.actionsArray) { Fab fab = new Fab(viewGroup.getContext(), fabOption.id.get()); applyFabOptions(component, fab, fabOption); fab.setOnClickListener(v -> component.sendOnNavigationButtonPressed(options.id.get())); fabMenu.getActions().add(fab); fabMenu.addMenuButton(fab); } } if (options.hideOnScroll.isTrue()) { fabMenu.enableCollapse(component.getScrollEventListener()); } if (options.hideOnScroll.isFalse()) { fabMenu.disableCollapse(); } } public void onConfigurationChanged( Options options) { FabOptions fabOptions = options.fabOptions; if(fab!=null){ if (fabOptions.backgroundColor.hasValue()) { fab.setColorNormal(fabOptions.backgroundColor.get()); } if (fabOptions.clickColor.hasValue()) { fab.setColorPressed(fabOptions.clickColor.get()); } if (fabOptions.rippleColor.hasValue()) { fab.setColorRipple(fabOptions.rippleColor.get()); } if (fabOptions.icon.hasValue()) { fab.applyIcon(fabOptions.icon.get(), fabOptions.iconColor); } } if(fabMenu!=null){ if (fabOptions.backgroundColor.hasValue()) { fabMenu.setMenuButtonColorNormal(fabOptions.backgroundColor.get()); } if (fabOptions.clickColor.hasValue()) { fabMenu.setMenuButtonColorPressed(fabOptions.clickColor.get()); } if (fabOptions.rippleColor.hasValue()) { fabMenu.setMenuButtonColorRipple(fabOptions.rippleColor.get()); } } } }
/* * 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 com.appeligo.util; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.HashMap; import java.util.Set; import java.util.TreeSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class ActiveCache<K,V> implements Map<K,V> { private static final Log log = LogFactory.getLog(ActiveCache.class); protected static final int DEFAULT_MIN_CACHED = 1000; protected static final int DEFAULT_MAX_CACHED = 1500; private Map<K,ActiveObject<K,V>> map; private Set<ActiveObject<K,V>> activeSet; private int minCached; private int maxCached; public ActiveCache() { this(DEFAULT_MIN_CACHED, DEFAULT_MAX_CACHED); } public ActiveCache(int minCached, int maxCached) { map = new HashMap<K,ActiveObject<K,V>>(); activeSet = new TreeSet<ActiveObject<K,V>>(); this.minCached = minCached; this.maxCached = maxCached; } public void clear() { map.clear(); activeSet.clear(); } private void trimCache() { int size = size(); log.debug("Trimming...size is currently="+size+", maxCached="+maxCached+ ", minCached="+minCached+", trimming out "+(size-minCached)); assert(size == activeSet.size()) : "activeSet and map sizes don't match!"; Iterator<ActiveObject<K,V>> iter = activeSet.iterator(); while ((size-- > minCached) && iter.hasNext()) { ActiveObject<K,V> ao = iter.next(); ActiveObject<K,V> removed = map.remove(ao.getKey()); iter.remove(); } } public V get(Object key) { ActiveObject<K,V> ao = map.get(key); if (ao != null) { activeSet.remove(ao); V value = ao.getValue(); ao.setLastAccessed(System.currentTimeMillis()); activeSet.add(ao); return value; } return null; } public V put(K key, V value) { ActiveObject<K,V> ao = new ActiveObject<K,V>(key, value); activeSet.add(ao); ActiveObject<K,V> previous = map.put(key, ao); if (size() > maxCached) { trimCache(); } if (previous != null) { activeSet.remove(previous); return previous.getValue(); } return null; } public boolean containsKey(Object key) { return map.containsKey(key); } public boolean containsValue(Object value) { Collection<ActiveObject<K,V>> aos = map.values(); for (ActiveObject<K,V> ao : aos) { if (ao.getValue().equals(value)) { return true; } } return false; } public Set<Map.Entry<K,V>> entrySet() { Set<Map.Entry<K,V>> set = new HashSet<Map.Entry<K,V>>(); Set<Map.Entry<K,ActiveObject<K,V>>> aoEntries = map.entrySet(); for (Map.Entry<K,ActiveObject<K,V>> ao : aoEntries) { set.add(new Entry<K,V>(ao.getKey(),ao.getValue().getValue())); } return set; } public boolean isEmpty() { return map.isEmpty(); } public Set<K> keySet() { return map.keySet(); } public void putAll(Map<? extends K, ? extends V> t) { Set entries = t.entrySet(); for (Object object : entries) { Map.Entry<K,V> entry = (Map.Entry<K,V>)object; put(entry.getKey(), entry.getValue()); } if (size() > maxCached) { trimCache(); } } public V remove(Object key) { ActiveObject<K,V> ao = map.remove(key); activeSet.remove(ao); return ao.getValue(); } public int size() { return map.size(); } public Collection<V> values() { ArrayList<V> rtn = new ArrayList<V>(size()); Collection<ActiveObject<K,V>> aos = map.values(); for (ActiveObject<K,V> ao : aos) { rtn.add(ao.getValue()); } return rtn; } private static class ActiveObject<K,V> implements Comparable<ActiveObject<K,V>> { private K key; private V value; private long lastAccessed; public ActiveObject(K key, V value) { this.key = key; this.value = value; lastAccessed = System.currentTimeMillis(); } public K getKey() { return key; } public V getValue() { return value; } public boolean equals() { return key.equals(key) && (value == value) && (lastAccessed == lastAccessed); } /** * Return a hashcode representing this Object. <code>ActiveObject</code>'s hash * code is calculated by <code>(int) (lastAccessed ^ (lastAccessed &gt;&gt; 32))</code>. * * @return this Object's hash code */ public int hashCode() { return (int) (lastAccessed ^ (lastAccessed >>> 32)); } public int compareTo(ActiveObject<K,V> right) { if (lastAccessed < right.lastAccessed) { return -1; } else if (lastAccessed > right.lastAccessed) { return 1; } else { try { return ((Comparable<K>)key).compareTo(right.key); } catch (ClassCastException e) { return key.toString().compareTo(right.key.toString()); } } } public long getLastAccessed() { return lastAccessed; } public void setLastAccessed(long lastAccessed) { this.lastAccessed = lastAccessed; } public String toString() { return key.toString(); } } private static class Entry<K,V> implements Map.Entry<K,V> { private K key; private V value; Entry(K key, V value) { this.key = key; this.value = value; } public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { V previous = this.value; this.value = value; return previous; } public boolean equals() { return (key == key || (key != null && key.equals(key))) && (value == value || (value != null && value.equals(value))); } public int hashCode() { return key.hashCode(); } } }
/* * Copyright 2010 The Closure Compiler 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.javascript.jscomp; import com.google.common.base.Preconditions; import com.google.common.collect.HashMultiset; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multiset; import com.google.javascript.jscomp.CompilerOptions.AliasTransformation; import com.google.javascript.jscomp.CompilerOptions.AliasTransformationHandler; import com.google.javascript.rhino.IR; import com.google.javascript.rhino.JSDocInfo; import com.google.javascript.rhino.JSDocInfoBuilder; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.SourcePosition; import com.google.javascript.rhino.Token; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * Process aliases in goog.scope blocks. * * <pre> * goog.scope(function() { * var dom = goog.dom; * var DIV = dom.TagName.DIV; * * dom.createElement(DIV); * }); * </pre> * * should become * * <pre> * goog.dom.createElement(goog.dom.TagName.DIV); * </pre> * * The advantage of using goog.scope is that the compiler will *guarantee* * the anonymous function will be inlined, even if it can't prove * that it's semantically correct to do so. For example, consider this case: * * <pre> * goog.scope(function() { * goog.getBar = function () { return alias; }; * ... * var alias = foo.bar; * }) * </pre> * * <p>In theory, the compiler can't inline 'alias' unless it can prove that * goog.getBar is called only after 'alias' is defined. In practice, the * compiler will inline 'alias' anyway, at the risk of 'fixing' bad code. * * @author robbyw@google.com (Robby Walker) */ class ScopedAliases implements HotSwapCompilerPass { /** Name used to denote an scoped function block used for aliasing. */ static final String SCOPING_METHOD_NAME = "goog.scope"; private final AbstractCompiler compiler; private final PreprocessorSymbolTable preprocessorSymbolTable; private final AliasTransformationHandler transformationHandler; // Errors static final DiagnosticType GOOG_SCOPE_MUST_BE_ALONE = DiagnosticType.error( "JSC_GOOG_SCOPE_MUST_BE_ALONE", "The call to goog.scope must be alone in a single statement."); static final DiagnosticType GOOG_SCOPE_MUST_BE_IN_GLOBAL_SCOPE = DiagnosticType.error( "JSC_GOOG_SCOPE_MUST_BE_IN_GLOBAL_SCOPE", "The call to goog.scope must be in the global scope."); static final DiagnosticType GOOG_SCOPE_HAS_BAD_PARAMETERS = DiagnosticType.error( "JSC_GOOG_SCOPE_HAS_BAD_PARAMETERS", "The call to goog.scope must take only a single parameter. It must" + " be an anonymous function that itself takes no parameters."); static final DiagnosticType GOOG_SCOPE_REFERENCES_THIS = DiagnosticType.error( "JSC_GOOG_SCOPE_REFERENCES_THIS", "The body of a goog.scope function cannot reference 'this'."); static final DiagnosticType GOOG_SCOPE_USES_RETURN = DiagnosticType.error( "JSC_GOOG_SCOPE_USES_RETURN", "The body of a goog.scope function cannot use 'return'."); static final DiagnosticType GOOG_SCOPE_USES_THROW = DiagnosticType.error( "JSC_GOOG_SCOPE_USES_THROW", "The body of a goog.scope function cannot use 'throw'."); static final DiagnosticType GOOG_SCOPE_ALIAS_REDEFINED = DiagnosticType.error( "JSC_GOOG_SCOPE_ALIAS_REDEFINED", "The alias {0} is assigned a value more than once."); static final DiagnosticType GOOG_SCOPE_ALIAS_CYCLE = DiagnosticType.error( "JSC_GOOG_SCOPE_ALIAS_CYCLE", "The aliases {0} has a cycle."); static final DiagnosticType GOOG_SCOPE_NON_ALIAS_LOCAL = DiagnosticType.error( "JSC_GOOG_SCOPE_NON_ALIAS_LOCAL", "The local variable {0} is in a goog.scope and is not an alias."); static final DiagnosticType GOOG_SCOPE_INVALID_VARIABLE = DiagnosticType.error( "JSC_GOOG_SCOPE_INVALID_VARIABLE", "The variable {0} cannot be declared in this scope"); private Multiset<String> scopedAliasNames = HashMultiset.create(); ScopedAliases(AbstractCompiler compiler, @Nullable PreprocessorSymbolTable preprocessorSymbolTable, AliasTransformationHandler transformationHandler) { this.compiler = compiler; this.preprocessorSymbolTable = preprocessorSymbolTable; this.transformationHandler = transformationHandler; } @Override public void process(Node externs, Node root) { hotSwapScript(root, null); } @Override public void hotSwapScript(Node root, Node originalRoot) { Traversal traversal = new Traversal(); NodeTraversal.traverseEs6(compiler, root, traversal); if (!traversal.hasErrors()) { // Apply the aliases. List<AliasUsage> aliasWorkQueue = new ArrayList<>(traversal.getAliasUsages()); while (!aliasWorkQueue.isEmpty()) { List<AliasUsage> newQueue = new ArrayList<>(); for (AliasUsage aliasUsage : aliasWorkQueue) { if (aliasUsage.referencesOtherAlias()) { newQueue.add(aliasUsage); } else { aliasUsage.applyAlias(); } } // Prevent an infinite loop. if (newQueue.size() == aliasWorkQueue.size()) { Var cycleVar = newQueue.get(0).aliasVar; compiler.report(JSError.make( cycleVar.getNode(), GOOG_SCOPE_ALIAS_CYCLE, cycleVar.getName())); break; } else { aliasWorkQueue = newQueue; } } // Remove the alias definitions. for (Node aliasDefinition : traversal.getAliasDefinitionsInOrder()) { if (NodeUtil.isNameDeclaration(aliasDefinition.getParent()) && aliasDefinition.getParent().hasOneChild()) { aliasDefinition.getParent().detach(); } else { aliasDefinition.detach(); } } // Collapse the scopes. for (Node scopeCall : traversal.getScopeCalls()) { Node expressionWithScopeCall = scopeCall.getParent(); Node scopeClosureBlock = scopeCall.getLastChild().getLastChild(); scopeClosureBlock.detach(); expressionWithScopeCall.getParent().replaceChild( expressionWithScopeCall, scopeClosureBlock); NodeUtil.tryMergeBlock(scopeClosureBlock); } if (!traversal.getAliasUsages().isEmpty() || !traversal.getAliasDefinitionsInOrder().isEmpty() || !traversal.getScopeCalls().isEmpty()) { compiler.reportCodeChange(); } } } private abstract static class AliasUsage { final Var aliasVar; final Node aliasReference; AliasUsage(Var aliasVar, Node aliasReference) { this.aliasVar = aliasVar; this.aliasReference = aliasReference; } /** Checks to see if this references another alias. */ public boolean referencesOtherAlias() { Node aliasDefinition = aliasVar.getInitialValue(); Node root = NodeUtil.getRootOfQualifiedName(aliasDefinition); Var otherAliasVar = aliasVar.getScope().getOwnSlot(root.getString()); return otherAliasVar != null; } public abstract void applyAlias(); } private static class AliasedNode extends AliasUsage { AliasedNode(Var aliasVar, Node aliasReference) { super(aliasVar, aliasReference); } @Override public void applyAlias() { Node aliasDefinition = aliasVar.getInitialValue(); Node replacement = aliasDefinition.cloneTree(); replacement.useSourceInfoFromForTree(aliasReference); if (aliasReference.getToken() == Token.STRING_KEY) { Preconditions.checkState(!aliasReference.hasChildren()); aliasReference.addChildToFront(replacement); } else { aliasReference.getParent().replaceChild(aliasReference, replacement); } } } private static class AliasedTypeNode extends AliasUsage { AliasedTypeNode(Var aliasVar, Node aliasReference) { super(aliasVar, aliasReference); } @Override public void applyAlias() { Node aliasDefinition = aliasVar.getInitialValue(); String aliasName = aliasVar.getName(); String typeName = aliasReference.getString(); if (typeName.startsWith("$jscomp.scope.")) { // Already visited. return; } String aliasExpanded = Preconditions.checkNotNull(aliasDefinition.getQualifiedName()); Preconditions.checkState(typeName.startsWith(aliasName), "%s must start with %s", typeName, aliasName); String replacement = aliasExpanded + typeName.substring(aliasName.length()); aliasReference.setString(replacement); } } private class Traversal extends NodeTraversal.AbstractPostOrderCallback implements NodeTraversal.ScopedCallback { // The job of this class is to collect these three data sets. // The order of this list determines the order that aliases are applied. private final List<Node> aliasDefinitionsInOrder = new ArrayList<>(); private final List<Node> scopeCalls = new ArrayList<>(); private final List<AliasUsage> aliasUsages = new ArrayList<>(); // This map is temporary and cleared for each scope. private final Map<String, Var> aliases = new HashMap<>(); // Also temporary and cleared for each scope. private final Set<Node> injectedDecls = new HashSet<>(); // Suppose you create an alias. // var x = goog.x; // As a side-effect, this means you can shadow the namespace 'goog' // in inner scopes. When we inline the namespaces, we have to rename // these shadows. // // Fortunately, we already have a name uniquifier that runs during tree // normalization (before optimizations). We run it here on a limited // set of variables, but only as a last resort (because this will screw // up warning messages downstream). private final Set<String> forbiddenLocals = new HashSet<>( ImmutableSet.of("$jscomp")); private boolean hasNamespaceShadows = false; private boolean hasErrors = false; private AliasTransformation transformation = null; // The body of the function that is passed to goog.scope. // Set when the traversal enters the body, and set back to null when it exits. private Node scopeFunctionBody = null; Collection<Node> getAliasDefinitionsInOrder() { return aliasDefinitionsInOrder; } private List<AliasUsage> getAliasUsages() { return aliasUsages; } List<Node> getScopeCalls() { return scopeCalls; } boolean hasErrors() { return hasErrors; } /** * Returns true if this NodeTraversal is currently within a goog.scope function body */ private boolean inGoogScopeBody() { return scopeFunctionBody != null; } /** * Returns true if n is the goog.scope function body */ private boolean isGoogScopeFunctionBody(Node n) { return inGoogScopeBody() && n == scopeFunctionBody; } private boolean isCallToScopeMethod(Node n) { return n.isCall() && n.getFirstChild().matchesQualifiedName(SCOPING_METHOD_NAME); } /** * @param scopeRoot the Node which is the root of the current scope * @return the goog.scope() CALL node containing the scopeRoot, or null if scopeRoot is not * in a goog.scope() call. */ private Node findScopeMethodCall(Node scopeRoot) { Node n = scopeRoot.getGrandparent(); if (isCallToScopeMethod(n)) { return n; } return null; } @Override public void enterScope(NodeTraversal t) { if (t.inGlobalHoistScope()) { return; } if (inGoogScopeBody()) { Scope hoistedScope = t.getClosestHoistScope(); if (isGoogScopeFunctionBody(hoistedScope.getRootNode())) { findAliases(t, hoistedScope); } } Node scopeMethodCall = findScopeMethodCall(t.getScope().getRootNode()); if (scopeMethodCall != null) { transformation = transformationHandler.logAliasTransformation( scopeMethodCall.getSourceFileName(), getSourceRegion(scopeMethodCall)); findAliases(t, t.getScope()); scopeFunctionBody = scopeMethodCall.getLastChild().getLastChild(); } } @Override public void exitScope(NodeTraversal t) { if (isGoogScopeFunctionBody(t.getScopeRoot())) { scopeFunctionBody = null; renameNamespaceShadows(t); injectedDecls.clear(); aliases.clear(); forbiddenLocals.clear(); transformation = null; hasNamespaceShadows = false; } else if (inGoogScopeBody()) { findNamespaceShadows(t); reportInvalidVariables(t); } } private void reportInvalidVariables(NodeTraversal t) { Node scopeRoot = t.getScopeRoot(); Node enclosingFunctionBody = t.getEnclosingFunction().getLastChild(); if (isGoogScopeFunctionBody(enclosingFunctionBody) && scopeRoot.isBlock() && !scopeRoot.getParent().isFunction()) { for (Var v : t.getScope().getVarIterable()) { Node parent = v.getNameNode().getParent(); if (NodeUtil.isFunctionDeclaration(parent)) { // Disallow block-scoped function declarations that leak into the goog.scope // function body. Technically they shouldn't leak in ES6 but the browsers don't agree // on that yet. report(t, v.getNode(), GOOG_SCOPE_INVALID_VARIABLE, v.getName()); } } } } private SourcePosition<AliasTransformation> getSourceRegion(Node n) { Node testNode = n; Node next = null; for (; next != null || testNode.isScript();) { next = testNode.getNext(); testNode = testNode.getParent(); } int endLine = next == null ? Integer.MAX_VALUE : next.getLineno(); int endChar = next == null ? Integer.MAX_VALUE : next.getCharno(); SourcePosition<AliasTransformation> pos = new SourcePosition<AliasTransformation>() {}; pos.setPositionInformation( n.getLineno(), n.getCharno(), endLine, endChar); return pos; } private void report(NodeTraversal t, Node n, DiagnosticType error, String... arguments) { compiler.report(t.makeError(n, error, arguments)); hasErrors = true; } private void findAliases(NodeTraversal t, Scope scope) { for (Var v : scope.getVarIterable()) { Node n = v.getNode(); Node parent = n.getParent(); // We use isBlock to avoid variables declared in loop headers. boolean isVar = NodeUtil.isNameDeclaration(parent) && parent.getParent().isBlock(); boolean isFunctionDecl = NodeUtil.isFunctionDeclaration(parent); if (isVar && n.getFirstChild() != null && n.getFirstChild().isQualifiedName()) { recordAlias(v); } else if (v.isBleedingFunction()) { // Bleeding functions already get a BAD_PARAMETERS error, so just // do nothing. } else if (parent.getToken() == Token.PARAM_LIST) { // Parameters of the scope function also get a BAD_PARAMETERS // error. } else if (isVar || isFunctionDecl || NodeUtil.isClassDeclaration(parent)) { boolean isHoisted = NodeUtil.isHoistedFunctionDeclaration(parent); Node grandparent = parent.getParent(); Node value = v.getInitialValue(); Node varNode = null; // Pull out inline type declaration if present. if (n.getJSDocInfo() != null) { JSDocInfoBuilder builder = JSDocInfoBuilder.maybeCopyFrom(parent.getJSDocInfo()); if (isFunctionDecl) { // Fix inline return type. builder.recordReturnType(n.getJSDocInfo().getType()); } else { builder.recordType(n.getJSDocInfo().getType()); } parent.setJSDocInfo(builder.build()); n.setJSDocInfo(null); } // Grab the docinfo before we do any AST manipulation. JSDocInfo varDocInfo = v.getJSDocInfo(); String name = n.getString(); int nameCount = scopedAliasNames.count(name); scopedAliasNames.add(name); String globalName = "$jscomp.scope." + name + (nameCount == 0 ? "" : ("$jscomp$" + nameCount)); compiler.ensureLibraryInjected("base", false); // First, we need to free up the function expression (EXPR) // to be used in another expression. if (isFunctionDecl || NodeUtil.isClassDeclaration(parent)) { // Replace "function NAME() { ... }" with "var NAME;". // Replace "class NAME { ... }" with "var NAME;". // We can't keep the local name on the function expression, // because IE is buggy and will leak the name into the global // scope. This is covered in more detail here: // http://wiki.ecmascript.org/lib/exe/fetch.php?id=resources:resources&cache=cache&media=resources:jscriptdeviationsfromes3.pdf // // This will only cause problems if this is a hoisted, recursive // function, and the programmer is using the hoisting. Node newName; if (isFunctionDecl) { newName = IR.name(""); } else { newName = IR.empty(); } newName.useSourceInfoFrom(n); value.replaceChild(n, newName); varNode = IR.var(n).useSourceInfoFrom(n); grandparent.replaceChild(parent, varNode); } else { if (value != null) { // If this is a VAR, we can just detach the expression and // the tree will still be valid. value.detach(); } varNode = parent; } // Add $jscomp.scope.name = EXPR; // Make sure we copy over all the jsdoc and debug info. if (value != null || varDocInfo != null) { Node newDecl = NodeUtil.newQNameDeclaration( compiler, globalName, value, varDocInfo) .useSourceInfoIfMissingFromForTree(n); newDecl.getFirstFirstChild().useSourceInfoFrom(n); newDecl.getFirstFirstChild().setOriginalName(name); if (isHoisted) { grandparent.addChildToFront(newDecl); } else { grandparent.addChildBefore(newDecl, varNode); } injectedDecls.add(newDecl.getFirstChild()); } // Rewrite "var name = EXPR;" to "var name = $jscomp.scope.name;" v.getNameNode().addChildToFront( NodeUtil.newQName( compiler, globalName, n, name)); recordAlias(v); } else { // Do not other kinds of local symbols, like catch params. report(t, n, GOOG_SCOPE_NON_ALIAS_LOCAL, n.getString()); } } } private void recordAlias(Var aliasVar) { String name = aliasVar.getName(); aliases.put(name, aliasVar); String qualifiedName = aliasVar.getInitialValue().getQualifiedName(); transformation.addAlias(name, qualifiedName); int rootIndex = qualifiedName.indexOf('.'); if (rootIndex != -1) { String qNameRoot = qualifiedName.substring(0, rootIndex); if (!aliases.containsKey(qNameRoot)) { forbiddenLocals.add(qNameRoot); } } } /** Find out if there are any local shadows of namespaces. */ private void findNamespaceShadows(NodeTraversal t) { if (hasNamespaceShadows) { return; } Scope scope = t.getScope(); for (Var v : scope.getVarIterable()) { if (forbiddenLocals.contains(v.getName())) { hasNamespaceShadows = true; return; } } } /** * Rename any local shadows of namespaces. * This should be a very rare occurrence, so only do this traversal * if we know that we need it. */ private void renameNamespaceShadows(NodeTraversal t) { if (hasNamespaceShadows) { MakeDeclaredNamesUnique.Renamer renamer = new MakeDeclaredNamesUnique.WhitelistedRenamer( new MakeDeclaredNamesUnique.ContextualRenamer(), forbiddenLocals); for (String s : forbiddenLocals) { renamer.addDeclaredName(s, false); } MakeDeclaredNamesUnique uniquifier = new MakeDeclaredNamesUnique(renamer); Node parent = t.getScopeRoot().getParent(); NodeTraversal.traverseEs6(compiler, parent, uniquifier); } } private void validateScopeCall(NodeTraversal t, Node n, Node parent) { if (preprocessorSymbolTable != null) { preprocessorSymbolTable.addReference(n.getFirstChild()); } if (!parent.isExprResult()) { report(t, n, GOOG_SCOPE_MUST_BE_ALONE); } if (t.getEnclosingFunction() != null) { report(t, n, GOOG_SCOPE_MUST_BE_IN_GLOBAL_SCOPE); } if (n.getChildCount() != 2) { // The goog.scope call should have exactly 1 parameter. The first // child is the "goog.scope" and the second should be the parameter. report(t, n, GOOG_SCOPE_HAS_BAD_PARAMETERS); } else { Node anonymousFnNode = n.getSecondChild(); if (!anonymousFnNode.isFunction() || NodeUtil.getName(anonymousFnNode) != null || NodeUtil.getFunctionParameters(anonymousFnNode).hasChildren()) { report(t, anonymousFnNode, GOOG_SCOPE_HAS_BAD_PARAMETERS); } else { scopeCalls.add(n); } } } @Override public void visit(NodeTraversal t, Node n, Node parent) { if (isCallToScopeMethod(n)) { validateScopeCall(t, n, n.getParent()); } if (!inGoogScopeBody()) { return; } Token type = n.getToken(); boolean isObjLitShorthand = type == Token.STRING_KEY && !n.hasChildren(); Var aliasVar = null; if (type == Token.NAME || isObjLitShorthand) { String name = n.getString(); Var lexicalVar = t.getScope().getVar(name); if (lexicalVar != null && lexicalVar == aliases.get(name)) { aliasVar = lexicalVar; // For nodes that are referencing the aliased type, set the original name so it // can be accessed later in tools such as the CodePrinter or refactoring tools. if (compiler.getOptions().preservesDetailedSourceInfo() && n.isName()) { n.setOriginalName(name); } } } if (isGoogScopeFunctionBody(t.getEnclosingFunction().getLastChild())) { if (aliasVar != null && !isObjLitShorthand && NodeUtil.isLValue(n)) { if (aliasVar.getNode() == n) { aliasDefinitionsInOrder.add(n); // Return early, to ensure that we don't record a definition // twice. return; } else { report(t, n, GOOG_SCOPE_ALIAS_REDEFINED, n.getString()); } } if (type == Token.RETURN) { report(t, n, GOOG_SCOPE_USES_RETURN); } else if (type == Token.THIS) { report(t, n, GOOG_SCOPE_REFERENCES_THIS); } else if (type == Token.THROW) { report(t, n, GOOG_SCOPE_USES_THROW); } } // Validate all descendent scopes of the goog.scope block. if (inGoogScopeBody()) { // Check if this name points to an alias. if (aliasVar != null) { // Note, to support the transitive case, it's important we don't // clone aliasedNode here. For example, // var g = goog; var d = g.dom; d.createElement('DIV'); // The node in aliasedNode (which is "g") will be replaced in the // changes pass above with "goog". If we cloned here, we'd end up // with <code>g.dom.createElement('DIV')</code>. aliasUsages.add(new AliasedNode(aliasVar, n)); } // When we inject declarations, we duplicate jsdoc. Make sure // we only process that jsdoc once. JSDocInfo info = n.getJSDocInfo(); if (info != null && !injectedDecls.contains(n)) { for (Node node : info.getTypeNodes()) { fixTypeNode(node); } } } } private void fixTypeNode(Node typeNode) { if (typeNode.isString()) { String name = typeNode.getString(); int endIndex = name.indexOf('.'); if (endIndex == -1) { endIndex = name.length(); } String baseName = name.substring(0, endIndex); Var aliasVar = aliases.get(baseName); if (aliasVar != null) { aliasUsages.add(new AliasedTypeNode(aliasVar, typeNode)); } // For nodes that are referencing the aliased type, set the original name so it // can be accessed later in tools such as the CodePrinter or refactoring tools. if (compiler.getOptions().preservesDetailedSourceInfo()) { typeNode.setOriginalName(name); } } for (Node child = typeNode.getFirstChild(); child != null; child = child.getNext()) { fixTypeNode(child); } } } }
/* * Copyright 2015-2017 Richard Linsdale. * * 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 uk.theretiredprogrammer.photogallery.dataobjects; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import org.openide.util.Lookup; import org.openide.util.lookup.ServiceProvider; import static uk.theretiredprogrammer.photogallery.dataobjects.Albumgrouppermission.AlbumgrouppermissionField; import uk.theretiredprogrammer.nbpcglibrary.api.*; import uk.theretiredprogrammer.nbpcglibrary.common.*; import uk.theretiredprogrammer.nbpcglibrary.data.entity.*; import uk.theretiredprogrammer.nbpcglibrary.data.entityreferences.*; /** * The Albumgrouppermission Entity. * * (Class generated by NetBeans Platform Code Generator tools using script.xml. * Do not edit this file. Apply any changes to the definition file and * regenerate all files.) * * @author Richard Linsdale (richard at theretiredprogrammer.uk) */ public class Albumgrouppermission extends Entity<Integer, Albumgrouppermission, Album, AlbumgrouppermissionField> { /** * the Albumgrouppermission field identifiers */ public enum AlbumgrouppermissionField { /** * the permission field */ PERMISSION, /** * the album field */ ALBUM, /** * the groups collection */ GROUPS, } private final Rules entityRules = new Rules(); private String permission = ""; private String permissionOriginal; private final Rules permissionRules = new Rules(); private final EntityReference<Integer, Album, AlbumRoot> album; private int id = 0; private String createdby = ""; private final Timestamp createdon = new Timestamp(); private String updatedby = ""; private final Timestamp updatedon = new Timestamp(); private final EntityReferenceFilterSet<Integer, Group, Albumgrouppermission> groups; /** * Constructor - Albumgrouppermission. * * @param id the unique id for this entity * @param em - the entity manager for this entity type */ public Albumgrouppermission(int id, Albumgrouppermission.EM em) { super("Albumgrouppermission[" + Integer.toString(id) + "]", "thumb_up", em); this.id = id; album = new EntityReference<>("Albumgrouppermission>Album", Album.getEM()); addRule(album.getDefinedRule()); groups = new EntityReferenceFilterSet<>(instanceDescription() + ">Groups", "albumgrouppermission", getId(), Group.EM.class); groups.load(); checkRulesAtLoad(); } @Override public boolean isPersistent() { return id > 0; } @Override public final Integer getPK() { return getId(); } /** * Get all rules for this entity * * @return the set of rules */ public final Rules getEntityRules() { return entityRules; } @Override public final String instanceDescription() { return "".equals(permission) ? LogBuilder.instanceDescription(this, Integer.toString(getId())) : LogBuilder.instanceDescription(this, Integer.toString(getId()) + "-" + permission); } /** * Get the permission field rules. * * @return the permission */ public Rules getPermissionRules() { return permissionRules; } /** * Get the permission. * * @return the permission */ public final String getPermission() { return permission; } /** * Define the Permission. * * @param permission the permission */ public void setPermission(String permission) { if (!this.permission.equals(permission)) { ensureEditing(); this.permission = permission; fireFieldChange(AlbumgrouppermissionField.PERMISSION); fireNameAndOrTitleChangeOnPermission(); } } private void fireNameAndOrTitleChangeOnPermission() { nameListenerFire(); titleListenerFire(); } /** * Get the parent Entity associated with this entity. * * @return the Album entity */ public Album getParent() { return album.get(); } /** * Set the parent (Album) Entity associated with this entity. Called from * the parent entity as part of the addAlbumgrouppermission method * * @param e the parent album entity */ protected void linkToParent(Album e) { ensureEditing(); if (album.set(e.getPK())) { fireFieldChange(AlbumgrouppermissionField.ALBUM); fireNameAndOrTitleChangeOnAlbum(); } } /** * Clear the parent (Album) Entity associated with this entity. Called from * the parent entity as part of the removeAlbumgrouppermission method */ protected void unlinkFromParent() { ensureEditing(); if (album.set()) { fireFieldChange(AlbumgrouppermissionField.ALBUM); fireNameAndOrTitleChangeOnAlbum(); } } private void fireNameAndOrTitleChangeOnAlbum() { } /** * Get the id. * * @return the id */ public final int getId() { return id; } /** * Get the createdby. * * @return the createdby */ public final String getCreatedby() { return createdby; } /** * Get the createdon. * * @return the createdon */ public final Timestamp getCreatedon() { return createdon; } /** * Get the updatedby. * * @return the updatedby */ public final String getUpdatedby() { return updatedby; } /** * Get the updatedon. * * @return the updatedon */ public final Timestamp getUpdatedon() { return updatedon; } /** * Add a Group to this entity. * * @param e the group */ public void addGroup(Group e) { e.linkToParent(this); groups.add(e); } /** * Remove a Group from this entity. * * @param e the group */ public void removeGroup(Group e) { e.unlinkFromParent(); groups.remove(e); } /** * Add set listener to groups collections * * @param listener the set change listener to add */ public void addGroupSetChangeListener(Listener<SetChangeEventParams> listener) { groups.addSetListener(listener); } /** * remove set listener to groups collections * * @param listener the set change listener to add */ public void removeGroupSetChangeListener(Listener<SetChangeEventParams> listener) { groups.removeSetListener(listener); } /** * Add set listener to all groups (and parent) collections * * @param listener the set change listener to add */ public static void addGroupsSetChangeListeners(Listener<SetChangeEventParams> listener) { Albumgrouppermission.getAllAlbumgrouppermissions().stream().forEach((albumgrouppermission) -> { ((Albumgrouppermission) albumgrouppermission).addGroupSetChangeListener(listener); }); Album.addAlbumgrouppermissionsSetChangeListeners(listener); } /** * Remove set listener from all groups (and parent) collections * * @param listener the set change listener to remove */ public static void removeGroupsSetChangeListeners(Listener<SetChangeEventParams> listener) { Albumgrouppermission.getAllAlbumgrouppermissions().stream().forEach((albumgrouppermission) -> { ((Albumgrouppermission) albumgrouppermission).removeGroupSetChangeListener(listener); }); Album.removeAlbumgrouppermissionsSetChangeListeners(listener); } /** * Get List of groups associated with entity. * * @return list of groups */ public List<Group> getGroups() { return groups.get(); } @Override protected final void entitySaveState() { permissionOriginal = permission; album.saveState(); } @Override protected final void entityRestoreState() { permission = permissionOriginal; album.restoreState(); groups.restoreState(); } @Override protected final void entityRemove() { getGroups().stream().forEach((group) -> { group.remove(); }); getParent().removeAlbumgrouppermission(this); } @Override protected final void entityLoad(EntityFields data) { permission = (String) data.get("permission"); album.set((Integer) data.get("album")); id = (Integer) data.get("id"); createdby = (String) data.get("createdby"); try { createdon.setDateUsingSQLString((String) data.get("createdon")); } catch (BadFormatException ex) { throw new LogicException("Load reported bad Timestamp format - should never happen!!"); } updatedby = (String) data.get("updatedby"); try { updatedon.setDateUsingSQLString((String) data.get("updatedon")); } catch (BadFormatException ex) { throw new LogicException("Load reported bad Timestamp format - should never happen!!"); } } @Override protected final void entityCopy(Albumgrouppermission from) { permission = from.getPermission(); } @Override protected final void entityDiffs(EntityFields data) { if (!permission.equals(permissionOriginal)) { data.put("permission", permission); } if (album.isDirty()) { int idrefAlbum = album.getPK(); if (idrefAlbum < 0) { album.get().save(); idrefAlbum = album.get().getPK(); } data.put("album", idrefAlbum); } } @Override protected final void entityValues(EntityFields data) { data.put("permission", permission); int idrefAlbum = album.getPK(); if (idrefAlbum < 0) { album.get().save(); idrefAlbum = album.get().getPK(); } data.put("album", idrefAlbum); } /** * Get the Albumgrouppermission Entity Manager * * @return the Albumgrouppermission Entity Manager */ public static Albumgrouppermission.EM getEM() { return Lookup.getDefault().lookup(Albumgrouppermission.EM.class); } /** * The Albumgrouppermission Entity Manager */ @ServiceProvider(service = Albumgrouppermission.EM.class) public static class EM extends EntityManager<Integer, Albumgrouppermission, Album> { private static int tpk = -1; /** * Constructor. */ public EM() { super("Albumgrouppermission"); } @Override protected final void link2parent(Albumgrouppermission e, Album parent) { parent.addAlbumgrouppermission(e); } @Override protected final Albumgrouppermission createNewEntity() { return new Albumgrouppermission(tpk--, this); } @Override protected final Albumgrouppermission createNewEntity(Integer pk) { return new Albumgrouppermission(pk, this); } @Override protected final EntityPersistenceProvider createEntityPersistenceProvider() { return EntityPersistenceProviderManager.getEntityPersistenceProvider("photogallery", "Albumgrouppermission"); } @Override protected boolean isPersistent(Integer pkey) { return pkey > 0; } } /** * Get the set of all Albumgrouppermissions. * * @return the set of all Albumgrouppermissions */ public static List<Entity> getAllAlbumgrouppermissions() { List<Entity> list = new ArrayList<>(); Album.getAllAlbums().stream().forEach((parent) -> { list.addAll(((Album) parent).getAlbumgrouppermissions()); }); return list; } @Override public String getDisplayName() { return MessageFormat.format("{0}", formatPermission()); } @Override public String getDisplayTitle() { return getDisplayName(); } @Override public String getSortKey() { return getDisplayTitle(); } /** * Get the formatted text version of permission field * * @return the formatted String */ public String formatPermission() { return getPermission(); } /** * Get the formatted text version of album field * * @return the formatted String */ public String formatAlbum() { return getParent() != null ? getParent().getDisplayName() : "undefined"; } /** * Get the formatted text version of id field * * @return the formatted String */ public String formatId() { return Integer.toString(getId()); } /** * Get the formatted text version of createdby field * * @return the formatted String */ public String formatCreatedby() { return getCreatedby(); } /** * Get the formatted text version of createdon field * * @return the formatted String */ public String formatCreatedon() { return getCreatedon().toString(); } /** * Get the formatted text version of updatedby field * * @return the formatted String */ public String formatUpdatedby() { return getUpdatedby(); } /** * Get the formatted text version of updatedon field * * @return the formatted String */ public String formatUpdatedon() { return getUpdatedon().toString(); } /** * Get the formatted text version of id field left padded with zeros if less * than minimum size. * * @param minDigits minimum size * @return the formatted String */ public String formatId(int minDigits) { return StringX.padLeft(formatId(), minDigits, '0'); } /** * Get the formatted text version of createdby field left padded with zeros * if less than minimum size. * * @param minChars minimum size * @return the formatted String */ public String formatCreatedby(int minChars) { return StringX.padLeftIfInt(formatCreatedby(), minChars, '0'); } /** * Get the formatted text version of updatedby field left padded with zeros * if less than minimum size. * * @param minChars minimum size * @return the formatted String */ public String formatUpdatedby(int minChars) { return StringX.padLeftIfInt(formatUpdatedby(), minChars, '0'); } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.search.aggregations.bucket.terms; import org.apache.lucene.index.AtomicReaderContext; import org.apache.lucene.index.DocValues; import org.apache.lucene.index.RandomAccessOrds; import org.apache.lucene.index.SortedDocValues; import org.apache.lucene.util.ArrayUtil; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.LongBitSet; import org.apache.lucene.util.RamUsageEstimator; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.common.lease.Releasables; import org.elasticsearch.common.text.Text; import org.elasticsearch.common.util.IntArray; import org.elasticsearch.common.util.LongHash; import org.elasticsearch.index.fielddata.AbstractRandomAccessOrds; import org.elasticsearch.index.fielddata.ordinals.GlobalOrdinalMapping; import org.elasticsearch.search.aggregations.Aggregator; import org.elasticsearch.search.aggregations.AggregatorFactories; import org.elasticsearch.search.aggregations.InternalAggregation; import org.elasticsearch.search.aggregations.InternalAggregations; import org.elasticsearch.search.aggregations.bucket.terms.InternalTerms.Bucket; import org.elasticsearch.search.aggregations.bucket.terms.support.BucketPriorityQueue; import org.elasticsearch.search.aggregations.bucket.terms.support.IncludeExclude; import org.elasticsearch.search.aggregations.support.AggregationContext; import org.elasticsearch.search.aggregations.support.ValuesSource; import java.io.IOException; import java.util.Arrays; /** * An aggregator of string values that relies on global ordinals in order to build buckets. */ public class GlobalOrdinalsStringTermsAggregator extends AbstractStringTermsAggregator { protected final ValuesSource.Bytes.WithOrdinals.FieldData valuesSource; protected final IncludeExclude includeExclude; protected RandomAccessOrds globalOrds; // TODO: cache the acceptedglobalValues per aggregation definition. // We can't cache this yet in ValuesSource, since ValuesSource is reused per field for aggs during the execution. // If aggs with same field, but different include/exclude are defined, then the last defined one will override the // first defined one. // So currently for each instance of this aggregator the acceptedglobalValues will be computed, this is unnecessary // especially if this agg is on a second layer or deeper. protected LongBitSet acceptedGlobalOrdinals; protected Collector collector; public GlobalOrdinalsStringTermsAggregator(String name, AggregatorFactories factories, ValuesSource.Bytes.WithOrdinals.FieldData valuesSource, long estimatedBucketCount, long maxOrd, InternalOrder order, BucketCountThresholds bucketCountThresholds, IncludeExclude includeExclude, AggregationContext aggregationContext, Aggregator parent, SubAggCollectionMode collectionMode, boolean showTermDocCountError) { super(name, factories, maxOrd, aggregationContext, parent, order, bucketCountThresholds, collectionMode, showTermDocCountError); this.valuesSource = valuesSource; this.includeExclude = includeExclude; } protected long getBucketOrd(long termOrd) { return termOrd; } @Override public boolean shouldCollect() { return true; } protected Collector newCollector(final RandomAccessOrds ords) { final SortedDocValues singleValues = DocValues.unwrapSingleton(ords); if (singleValues != null) { return new Collector() { @Override public void collect(int doc) throws IOException { final int ord = singleValues.getOrd(doc); if (ord >= 0) { collectExistingBucket(doc, ord); } } }; } else { return new Collector() { public void collect(int doc) throws IOException { ords.setDocument(doc); final int numOrds = ords.cardinality(); for (int i = 0; i < numOrds; i++) { final long globalOrd = ords.ordAt(i); collectExistingBucket(doc, globalOrd); } } }; } } @Override public void setNextReader(AtomicReaderContext reader) { globalOrds = valuesSource.globalOrdinalsValues(); if (acceptedGlobalOrdinals != null) { globalOrds = new FilteredOrdinals(globalOrds, acceptedGlobalOrdinals); } else if (includeExclude != null) { acceptedGlobalOrdinals = includeExclude.acceptedGlobalOrdinals(globalOrds, valuesSource); globalOrds = new FilteredOrdinals(globalOrds, acceptedGlobalOrdinals); } collector = newCollector(globalOrds); } @Override public void collect(int doc, long owningBucketOrdinal) throws IOException { assert owningBucketOrdinal == 0; collector.collect(doc); } protected static void copy(BytesRef from, BytesRef to) { if (to.bytes.length < from.length) { to.bytes = new byte[ArrayUtil.oversize(from.length, RamUsageEstimator.NUM_BYTES_BYTE)]; } to.offset = 0; to.length = from.length; System.arraycopy(from.bytes, from.offset, to.bytes, 0, from.length); } @Override public InternalAggregation buildAggregation(long owningBucketOrdinal) { if (globalOrds == null) { // no context in this reader return buildEmptyAggregation(); } final int size; if (bucketCountThresholds.getMinDocCount() == 0) { // if minDocCount == 0 then we can end up with more buckets then maxBucketOrd() returns size = (int) Math.min(globalOrds.getValueCount(), bucketCountThresholds.getShardSize()); } else { size = (int) Math.min(maxBucketOrd(), bucketCountThresholds.getShardSize()); } long otherDocCount = 0; BucketPriorityQueue ordered = new BucketPriorityQueue(size, order.comparator(this)); OrdBucket spare = new OrdBucket(-1, 0, null, showTermDocCountError, 0); for (long globalTermOrd = 0; globalTermOrd < globalOrds.getValueCount(); ++globalTermOrd) { if (includeExclude != null && !acceptedGlobalOrdinals.get(globalTermOrd)) { continue; } final long bucketOrd = getBucketOrd(globalTermOrd); final int bucketDocCount = bucketOrd < 0 ? 0 : bucketDocCount(bucketOrd); if (bucketCountThresholds.getMinDocCount() > 0 && bucketDocCount == 0) { continue; } otherDocCount += bucketDocCount; spare.globalOrd = globalTermOrd; spare.bucketOrd = bucketOrd; spare.docCount = bucketDocCount; if (bucketCountThresholds.getShardMinDocCount() <= spare.docCount) { spare = (OrdBucket) ordered.insertWithOverflow(spare); if (spare == null) { spare = new OrdBucket(-1, 0, null, showTermDocCountError, 0); } } } // Get the top buckets final InternalTerms.Bucket[] list = new InternalTerms.Bucket[ordered.size()]; long survivingBucketOrds[] = new long[ordered.size()]; for (int i = ordered.size() - 1; i >= 0; --i) { final OrdBucket bucket = (OrdBucket) ordered.pop(); survivingBucketOrds[i] = bucket.bucketOrd; BytesRef scratch = new BytesRef(); copy(globalOrds.lookupOrd(bucket.globalOrd), scratch); list[i] = new StringTerms.Bucket(scratch, bucket.docCount, null, showTermDocCountError, 0); list[i].bucketOrd = bucket.bucketOrd; otherDocCount -= list[i].docCount; } //replay any deferred collections runDeferredCollections(survivingBucketOrds); //Now build the aggs for (int i = 0; i < list.length; i++) { Bucket bucket = list[i]; bucket.aggregations = bucket.docCount == 0 ? bucketEmptyAggregations() : bucketAggregations(bucket.bucketOrd); bucket.docCountError = 0; } return new StringTerms(name, order, bucketCountThresholds.getRequiredSize(), bucketCountThresholds.getShardSize(), bucketCountThresholds.getMinDocCount(), Arrays.asList(list), showTermDocCountError, 0, otherDocCount); } /** * This is used internally only, just for compare using global ordinal instead of term bytes in the PQ */ static class OrdBucket extends InternalTerms.Bucket { long globalOrd; OrdBucket(long globalOrd, long docCount, InternalAggregations aggregations, boolean showDocCountError, long docCountError) { super(docCount, aggregations, showDocCountError, docCountError); this.globalOrd = globalOrd; } @Override int compareTerm(Terms.Bucket other) { return Long.compare(globalOrd, ((OrdBucket) other).globalOrd); } @Override public String getKey() { throw new UnsupportedOperationException(); } @Override public Text getKeyAsText() { throw new UnsupportedOperationException(); } @Override Object getKeyAsObject() { throw new UnsupportedOperationException(); } @Override Bucket newBucket(long docCount, InternalAggregations aggs, long docCountError) { throw new UnsupportedOperationException(); } @Override public Number getKeyAsNumber() { throw new UnsupportedOperationException(); } } private static interface Collector { void collect(int doc) throws IOException; } /** * Variant of {@link GlobalOrdinalsStringTermsAggregator} that rebases hashes in order to make them dense. Might be * useful in case few hashes are visited. */ public static class WithHash extends GlobalOrdinalsStringTermsAggregator { private final LongHash bucketOrds; public WithHash(String name, AggregatorFactories factories, ValuesSource.Bytes.WithOrdinals.FieldData valuesSource, long estimatedBucketCount, long maxOrd, InternalOrder order, BucketCountThresholds bucketCountThresholds, IncludeExclude includeExclude, AggregationContext aggregationContext, Aggregator parent, SubAggCollectionMode collectionMode, boolean showTermDocCountError) { // Set maxOrd to estimatedBucketCount! To be conservative with memory. super(name, factories, valuesSource, estimatedBucketCount, estimatedBucketCount, order, bucketCountThresholds, includeExclude, aggregationContext, parent, collectionMode, showTermDocCountError); bucketOrds = new LongHash(estimatedBucketCount, aggregationContext.bigArrays()); } protected Collector newCollector(final RandomAccessOrds ords) { final SortedDocValues singleValues = DocValues.unwrapSingleton(ords); if (singleValues != null) { return new Collector() { @Override public void collect(int doc) throws IOException { final int globalOrd = singleValues.getOrd(doc); if (globalOrd >= 0) { long bucketOrd = bucketOrds.add(globalOrd); if (bucketOrd < 0) { bucketOrd = -1 - bucketOrd; collectExistingBucket(doc, bucketOrd); } else { collectBucket(doc, bucketOrd); } } } }; } else { return new Collector() { public void collect(int doc) throws IOException { ords.setDocument(doc); final int numOrds = ords.cardinality(); for (int i = 0; i < numOrds; i++) { final long globalOrd = ords.ordAt(i); long bucketOrd = bucketOrds.add(globalOrd); if (bucketOrd < 0) { bucketOrd = -1 - bucketOrd; collectExistingBucket(doc, bucketOrd); } else { collectBucket(doc, bucketOrd); } } } }; } } @Override protected long getBucketOrd(long termOrd) { return bucketOrds.find(termOrd); } @Override protected void doClose() { Releasables.close(bucketOrds); } } /** * Variant of {@link GlobalOrdinalsStringTermsAggregator} that resolves global ordinals post segment collection * instead of on the fly for each match.This is beneficial for low cardinality fields, because it can reduce * the amount of look-ups significantly. */ public static class LowCardinality extends GlobalOrdinalsStringTermsAggregator { private final IntArray segmentDocCounts; private RandomAccessOrds segmentOrds; public LowCardinality(String name, AggregatorFactories factories, ValuesSource.Bytes.WithOrdinals.FieldData valuesSource, long estimatedBucketCount, long maxOrd, InternalOrder order, BucketCountThresholds bucketCountThresholds, AggregationContext aggregationContext, Aggregator parent, SubAggCollectionMode collectionMode, boolean showTermDocCountError) { super(name, factories, valuesSource, estimatedBucketCount, maxOrd, order, bucketCountThresholds, null, aggregationContext, parent, collectionMode, showTermDocCountError); assert factories == null || factories.count() == 0; this.segmentDocCounts = bigArrays.newIntArray(maxOrd + 1, true); } // bucketOrd is ord + 1 to avoid a branch to deal with the missing ord protected Collector newCollector(final RandomAccessOrds ords) { final SortedDocValues singleValues = DocValues.unwrapSingleton(segmentOrds); if (singleValues != null) { return new Collector() { @Override public void collect(int doc) throws IOException { final int ord = singleValues.getOrd(doc); segmentDocCounts.increment(ord + 1, 1); } }; } else { return new Collector() { public void collect(int doc) throws IOException { segmentOrds.setDocument(doc); final int numOrds = segmentOrds.cardinality(); for (int i = 0; i < numOrds; i++) { final long segmentOrd = segmentOrds.ordAt(i); segmentDocCounts.increment(segmentOrd + 1, 1); } } }; } } @Override public void setNextReader(AtomicReaderContext reader) { if (segmentOrds != null) { mapSegmentCountsToGlobalCounts(); } globalOrds = valuesSource.globalOrdinalsValues(); segmentOrds = valuesSource.ordinalsValues(); collector = newCollector(segmentOrds); } @Override protected void doPostCollection() { if (segmentOrds != null) { mapSegmentCountsToGlobalCounts(); } } @Override protected void doClose() { Releasables.close(segmentDocCounts); } private void mapSegmentCountsToGlobalCounts() { // There is no public method in Ordinals.Docs that allows for this mapping... // This is the cleanest way I can think of so far GlobalOrdinalMapping mapping; if (globalOrds instanceof GlobalOrdinalMapping) { mapping = (GlobalOrdinalMapping) globalOrds; } else { assert globalOrds.getValueCount() == segmentOrds.getValueCount(); mapping = null; } for (long i = 1; i < segmentDocCounts.size(); i++) { // We use set(...) here, because we need to reset the slow to 0. // segmentDocCounts get reused over the segments and otherwise counts would be too high. final int inc = segmentDocCounts.set(i, 0); if (inc == 0) { continue; } final long ord = i - 1; // remember we do +1 when counting final long globalOrd = mapping == null ? ord : mapping.getGlobalOrd(ord); try { incrementBucketDocCount(globalOrd, inc); } catch (IOException e) { throw ExceptionsHelper.convertToElastic(e); } } } } private static final class FilteredOrdinals extends AbstractRandomAccessOrds { private final RandomAccessOrds inner; private final LongBitSet accepted; private int cardinality; private long[] ords = new long[0]; private FilteredOrdinals(RandomAccessOrds inner, LongBitSet accepted) { this.inner = inner; this.accepted = accepted; } @Override public long getValueCount() { return inner.getValueCount(); } @Override public long ordAt(int index) { return ords[index]; } @Override public void doSetDocument(int docId) { inner.setDocument(docId); final int innerCardinality = inner.cardinality(); ords = ArrayUtil.grow(ords, innerCardinality); cardinality = 0; for (int slot = 0; slot < innerCardinality; slot++) { long ord = inner.ordAt(slot); if (accepted.get(ord)) { ords[cardinality++] = ord; } } } @Override public int cardinality() { return cardinality; } @Override public BytesRef lookupOrd(long ord) { return inner.lookupOrd(ord); } } }
/* * Copyright 2016-2019 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.vault.authentication; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.vault.authentication.AppRoleTokens.AbsentSecretId; import org.springframework.vault.authentication.AppRoleTokens.Provided; import org.springframework.vault.authentication.AppRoleTokens.Pull; import org.springframework.vault.support.VaultToken; /** * Authentication options for {@link AppRoleAuthentication}. * <p> * Authentication options provide the path, roleId and pull/push mode. * {@link AppRoleAuthentication} can be constructed using {@link #builder()}. Instances of * this class are immutable once constructed. * * @author Mark Paluch * @author Vincent Le Nair * @author Christophe Tafani-Dereeper * @see AppRoleAuthentication * @see #builder() */ public class AppRoleAuthenticationOptions { public static final String DEFAULT_APPROLE_AUTHENTICATION_PATH = "approle"; /** * Path of the approle authentication backend mount. */ private final String path; /** * The RoleId. */ private final RoleId roleId; /** * The Bind SecretId. */ private final SecretId secretId; /** * Role name used to get roleId and secretID */ @Nullable private final String appRole; /** * Unwrapping endpoint to cater for functionality across various Vault versions. */ private final UnwrappingEndpoints unwrappingEndpoints; /** * Token associated for pull mode (retrieval of secretId/roleId). * @deprecated since 2.0, use {@link RoleId#pull(VaultToken)}/ * {@link SecretId#pull(VaultToken)} to configure pull mode for roleId/secretId. */ @Nullable @Deprecated private final VaultToken initialToken; private AppRoleAuthenticationOptions(String path, RoleId roleId, SecretId secretId, @Nullable String appRole, UnwrappingEndpoints unwrappingEndpoints, @Nullable VaultToken initialToken) { this.path = path; this.roleId = roleId; this.secretId = secretId; this.appRole = appRole; this.unwrappingEndpoints = unwrappingEndpoints; this.initialToken = initialToken; } /** * @return a new {@link AppRoleAuthenticationOptionsBuilder}. */ public static AppRoleAuthenticationOptionsBuilder builder() { return new AppRoleAuthenticationOptionsBuilder(); } /** * @return the mount path. */ public String getPath() { return path; } /** * @return the RoleId. */ public RoleId getRoleId() { return roleId; } /** * @return the bound SecretId. */ public SecretId getSecretId() { return secretId; } /** * @return the bound AppRole. * @since 1.1 */ @Nullable public String getAppRole() { return appRole; } /** * @return the endpoint configuration. * @since 2.2 */ public UnwrappingEndpoints getUnwrappingEndpoints() { return unwrappingEndpoints; } /** * @return the initial token for roleId/secretId retrieval in pull mode. * @since 1.1 * @deprecated since 2.0, use {@link #getRoleId()}/{@link #getSecretId()} to obtain * configuration modes (pull/wrapped) for an AppRole token. */ @Nullable @Deprecated public VaultToken getInitialToken() { return initialToken; } /** * Builder for {@link AppRoleAuthenticationOptions}. */ public static class AppRoleAuthenticationOptionsBuilder { private String path = DEFAULT_APPROLE_AUTHENTICATION_PATH; @Nullable private String providedRoleId; @Nullable private RoleId roleId; @Nullable private String providedSecretId; @Nullable private SecretId secretId; @Nullable private String appRole; private UnwrappingEndpoints unwrappingEndpoints = UnwrappingEndpoints.SysWrapping; @Nullable @Deprecated private VaultToken initialToken; AppRoleAuthenticationOptionsBuilder() { } /** * Configure the mount path. * * @param path must not be empty or {@literal null}. * @return {@code this} {@link AppRoleAuthenticationOptionsBuilder}. * @see #DEFAULT_APPROLE_AUTHENTICATION_PATH */ public AppRoleAuthenticationOptionsBuilder path(String path) { Assert.hasText(path, "Path must not be empty"); this.path = path; return this; } /** * Configure the RoleId. * * @param roleId must not be empty or {@literal null}. * @return {@code this} {@link AppRoleAuthenticationOptionsBuilder}. * @since 2.0 */ public AppRoleAuthenticationOptionsBuilder roleId(RoleId roleId) { Assert.notNull(roleId, "RoleId must not be null"); this.roleId = roleId; return this; } /** * Configure the RoleId. * * @param roleId must not be empty or {@literal null}. * @return {@code this} {@link AppRoleAuthenticationOptionsBuilder}. * @deprecated since 2.0, use {@link #roleId(AppRoleAuthenticationOptions.RoleId)}. */ @Deprecated public AppRoleAuthenticationOptionsBuilder roleId(String roleId) { Assert.hasText(roleId, "RoleId must not be empty"); this.providedRoleId = roleId; return this; } /** * Configure a {@code secretId}. * * @param secretId must not be empty or {@literal null}. * @return {@code this} {@link AppRoleAuthenticationOptionsBuilder}. * @since 2.0 */ public AppRoleAuthenticationOptionsBuilder secretId(SecretId secretId) { Assert.notNull(secretId, "SecretId must not be null"); this.secretId = secretId; return this; } /** * Configure a {@code secretId}. * * @param secretId must not be empty or {@literal null}. * @return {@code this} {@link AppRoleAuthenticationOptionsBuilder}. * @deprecated since 2.0, use {@link #secretId(AppRoleAuthenticationOptions.SecretId)}. */ @Deprecated public AppRoleAuthenticationOptionsBuilder secretId(String secretId) { Assert.hasText(secretId, "SecretId must not be empty"); this.providedSecretId = secretId; return this; } /** * Configure a {@code appRole}. * * @param appRole must not be empty or {@literal null}. * @return {@code this} {@link AppRoleAuthenticationOptionsBuilder}. * @since 1.1 */ public AppRoleAuthenticationOptionsBuilder appRole(String appRole) { Assert.hasText(appRole, "AppRole must not be empty"); this.appRole = appRole; return this; } /** * Configure the {@link UnwrappingEndpoints} to use. * * @param endpoints must not be {@literal null}. * @return {@code this} {@link AppRoleAuthenticationOptionsBuilder} * @since 2.2 */ public AppRoleAuthenticationOptionsBuilder unwrappingEndpoints( UnwrappingEndpoints endpoints) { Assert.notNull(endpoints, "UnwrappingEndpoints must not be empty"); this.unwrappingEndpoints = endpoints; return this; } /** * Configure a {@code initialToken}. * * @param initialToken must not be empty or {@literal null}. * @return {@code this} {@link AppRoleAuthenticationOptionsBuilder}. * @since 1.1 * @deprecated since 2.0, use * {@link #roleId(AppRoleAuthenticationOptions.RoleId)}/{@link #secretId(AppRoleAuthenticationOptions.SecretId)} * to configure pull mode. */ @Deprecated public AppRoleAuthenticationOptionsBuilder initialToken(VaultToken initialToken) { Assert.notNull(initialToken, "InitialToken must not be null"); this.initialToken = initialToken; return this; } /** * Build a new {@link AppRoleAuthenticationOptions} instance. Requires * {@link #roleId(String)} for push mode or {@link #appRole(String)} and * {@link #initialToken(VaultToken)} for pull mode to be configured. * * @return a new {@link AppRoleAuthenticationOptions}. */ public AppRoleAuthenticationOptions build() { Assert.hasText(path, "Path must not be empty"); if (secretId == null) { if (providedSecretId != null) { secretId(SecretId.provided(providedSecretId)); } else if (initialToken != null) { secretId(SecretId.pull(initialToken)); } else { secretId(SecretId.absent()); } } if (roleId == null) { if (providedRoleId != null) { roleId(RoleId.provided(providedRoleId)); } else { Assert.notNull(initialToken, "AppRole authentication configured for pull mode. InitialToken must not be null (pull mode)"); roleId(RoleId.pull(initialToken)); } } if (roleId instanceof Pull || secretId instanceof Pull) { Assert.notNull(appRole, "AppRole authentication configured for pull mode. AppRole must not be null."); } return new AppRoleAuthenticationOptions(path, roleId, secretId, appRole, unwrappingEndpoints, initialToken); } } /** * RoleId type encapsulating how the roleId is actually obtained. Provides factory * methods to obtain a {@link RoleId} by wrapping, pull-mode or whether to use a * string literal. * * @since 2.0 */ public interface RoleId { /** * Create a {@link RoleId} object that obtains its value from unwrapping a * response using the {@link VaultToken initial token} from a Cubbyhole. * * @param initialToken must not be {@literal null}. * @return {@link RoleId} object that obtains its value from unwrapping a response * using the {@link VaultToken initial token}. * @see org.springframework.vault.client.VaultResponses#unwrap(String, Class) */ static RoleId wrapped(VaultToken initialToken) { Assert.notNull(initialToken, "Initial token must not be null"); return new AppRoleTokens.Wrapped(initialToken); } /** * Create a {@link RoleId} that obtains its value using pull-mode, specifying a * {@link VaultToken initial token}. The token policy must allow reading the * roleId from {@code auth/approle/role/(role-name)/role-id}. * * @param initialToken must not be {@literal null}. * @return {@link RoleId} that obtains its value using pull-mode. */ static RoleId pull(VaultToken initialToken) { Assert.notNull(initialToken, "Initial token must not be null"); return new AppRoleTokens.Pull(initialToken); } /** * Create a {@link RoleId} that encapsulates a static {@code roleId}. * * @param roleId must not be {@literal null} or empty. * @return {@link RoleId} that encapsulates a static {@code roleId}. */ static RoleId provided(String roleId) { Assert.hasText(roleId, "RoleId must not be null or empty"); return new Provided(roleId); } } /** * SecretId type encapsulating how the secretId is actually obtained. Provides factory * methods to obtain a {@link SecretId} by wrapping, pull-mode or whether to use a * string literal. * * @since 2.0 */ public interface SecretId { /** * Create a {@link SecretId} object that obtains its value from unwrapping a * response using the {@link VaultToken initial token} from a Cubbyhole. * * @param initialToken must not be {@literal null}. * @return {@link SecretId} object that obtains its value from unwrapping a * response using the {@link VaultToken initial token}. * @see org.springframework.vault.client.VaultResponses#unwrap(String, Class) */ static SecretId wrapped(VaultToken initialToken) { Assert.notNull(initialToken, "Initial token must not be null"); return new AppRoleTokens.Wrapped(initialToken); } /** * Create a {@link SecretId} that obtains its value using pull-mode, specifying a * {@link VaultToken initial token}. The token policy must allow reading the * SecretId from {@code auth/approle/role/(role-name)/secret-id}. * * @param initialToken must not be {@literal null}. * @return {@link SecretId} that obtains its value using pull-mode. */ static SecretId pull(VaultToken initialToken) { Assert.notNull(initialToken, "Initial token must not be null"); return new AppRoleTokens.Pull(initialToken); } /** * Create a {@link SecretId} that encapsulates a static {@code secretId}. * * @param secretId must not be {@literal null} or empty. * @return {@link SecretId} that encapsulates a static {@code SecretId}. */ static SecretId provided(String secretId) { Assert.hasText(secretId, "SecretId must not be null or empty"); return new Provided(secretId); } /** * Create a {@link SecretId} that represents an absent secretId. Using this object * will not send a secretId during AppRole login. * * @return a {@link SecretId} that represents an absent secretId */ static SecretId absent() { return AbsentSecretId.INSTANCE; } } }
/* * Copyright 2015 Jean-Michel Tanguy. * * 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.auxeanne.data.db; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Cacheable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import org.eclipse.persistence.annotations.Multitenant; /** * Entity mapping the database. * * @author Jean-Michel Tanguy */ @Entity @Table(name = "record_audit") @XmlRootElement @Cacheable(false) @Multitenant() public class RecordAudit implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "RECORD_AUDIT_GEN") @TableGenerator(name = "RECORD_AUDIT_GEN", allocationSize = 100, initialValue = 1, pkColumnValue = "RecordAudit") @Basic(optional = false) @Column(name = "log_id_") private Long log_id_; // @Column(name = "record_id_") private Long id; @Lob @Column(name = "data_") private byte[] data; @Lob @Column(name = "document_") private byte[] document; @Column(name = "record_type_") private int recordType; @Column(name = "reference_") private Long reference_; @Column(name = "link_") private Long link_; @Size(max = 255) @Column(name = "value_") private String value; @Column(name = "numeric_") private BigDecimal numeric; @Column(name = "date_") @Temporal(TemporalType.TIMESTAMP) private Date date; // @Column(name = "execution_") @Temporal(TemporalType.TIMESTAMP) private Date execution; @Column(name = "action_") private String action; @Column(name = "by_") private String by; // mapping to default tenant column for master management @Column(name = "TENANT_ID", insertable = false, updatable = false) private String tenantId; public String getTenantId() { return tenantId; } public RecordAudit() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public byte[] getData() { return data; } public void setData(byte[] data) { this.data = data; } public byte[] getDocument() { return document; } public void setDocument(byte[] document) { this.document = document; } public int getRecordType() { return recordType; } public void setRecordType(int recordType) { this.recordType = recordType; } public long getReference_() { return reference_; } public void setReference_(long reference_) { this.reference_ = reference_; } public long getLink_() { return link_; } public void setLink_(long link_) { this.link_ = link_; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public BigDecimal getNumeric() { return numeric; } public void setNumeric(BigDecimal numeric) { this.numeric = numeric; } public Date getExecution() { return execution; } public void setExecution(Date execution) { this.execution = execution; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public String getBy() { return by; } public void setBy(String by) { this.by = by; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof RecordAudit)) { return false; } RecordAudit other = (RecordAudit) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "RecordAudit[ id=" + id + " ]"; } public Long getLog_id_() { return log_id_; } public void setLog_id_(Long log_id_) { this.log_id_ = log_id_; } }
/* * * 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.airavata.gsi.ssh.api.job; import org.apache.airavata.gsi.ssh.api.CommandOutput; import org.apache.airavata.gsi.ssh.util.CommonUtils; import org.apache.airavata.gsi.ssh.x2012.x12.*; import org.apache.xmlbeans.XmlException; import java.util.List; /** * This class define a job with required parameters, based on this configuration API is generating a Pbs script and * submit the job to the computing resource */ public class JobDescriptor { private JobDescriptorDocument jobDescriptionDocument; public JobDescriptor() { jobDescriptionDocument = JobDescriptorDocument.Factory.newInstance(); jobDescriptionDocument.addNewJobDescriptor(); } public JobDescriptor(JobDescriptorDocument jobDescriptorDocument) { this.jobDescriptionDocument = jobDescriptorDocument; } public JobDescriptor(CommandOutput commandOutput) { jobDescriptionDocument = JobDescriptorDocument.Factory.newInstance(); jobDescriptionDocument.addNewJobDescriptor(); } public String toXML() { return jobDescriptionDocument.xmlText(); } public JobDescriptorDocument getJobDescriptorDocument() { return this.jobDescriptionDocument; } public static JobDescriptor fromXML(String xml) throws XmlException { JobDescriptorDocument parse = JobDescriptorDocument.Factory .parse(xml); JobDescriptor jobDescriptor = new JobDescriptor(parse); return jobDescriptor; } //todo write bunch of setter getters to set and get jobdescription parameters public void setWorkingDirectory(String workingDirectory) { this.getJobDescriptorDocument().getJobDescriptor().setWorkingDirectory(workingDirectory); } public String getWorkingDirectory() { return this.getJobDescriptorDocument().getJobDescriptor().getWorkingDirectory(); } public void setShellName(String shellName) { this.getJobDescriptorDocument().getJobDescriptor().setShellName(shellName); } public void setJobName(String name) { this.getJobDescriptorDocument().getJobDescriptor().setJobName(name); } public void setExecutablePath(String name) { this.getJobDescriptorDocument().getJobDescriptor().setExecutablePath(name); } public void setAllEnvExport(boolean name) { this.getJobDescriptorDocument().getJobDescriptor().setAllEnvExport(name); } public void setMailOptions(String name) { this.getJobDescriptorDocument().getJobDescriptor().setMailOptions(name); } public void setStandardOutFile(String name) { this.getJobDescriptorDocument().getJobDescriptor().setStandardOutFile(name); } public void setStandardErrorFile(String name) { this.getJobDescriptorDocument().getJobDescriptor().setStandardErrorFile(name); } public void setNodes(int name) { this.getJobDescriptorDocument().getJobDescriptor().setNodes(name); } public void setProcessesPerNode(int name) { this.getJobDescriptorDocument().getJobDescriptor().setProcessesPerNode(name); } public String getOutputDirectory() { return this.getJobDescriptorDocument().getJobDescriptor().getOutputDirectory(); } public String getInputDirectory() { return this.getJobDescriptorDocument().getJobDescriptor().getInputDirectory(); } public void setOutputDirectory(String name) { this.getJobDescriptorDocument().getJobDescriptor().setOutputDirectory(name); } public void setInputDirectory(String name) { this.getJobDescriptorDocument().getJobDescriptor().setInputDirectory(name); } /** * Users can pass the minute count for maxwalltime * @param minutes */ public void setMaxWallTime(String minutes) { this.getJobDescriptorDocument().getJobDescriptor().setMaxWallTime( CommonUtils.maxWallTimeCalculator(Integer.parseInt(minutes))); } public void setAcountString(String name) { this.getJobDescriptorDocument().getJobDescriptor().setAcountString(name); } public void setInputValues(List<String> inputValue) { InputList inputList = this.getJobDescriptorDocument().getJobDescriptor().addNewInputs(); inputList.setInputArray(inputValue.toArray(new String[inputValue.size()])); } public void setJobID(String jobID) { this.getJobDescriptorDocument().getJobDescriptor().setJobID(jobID); } public void setQueueName(String queueName) { this.getJobDescriptorDocument().getJobDescriptor().setQueueName(queueName); } public void setStatus(String queueName) { this.getJobDescriptorDocument().getJobDescriptor().setStatus(queueName); } public void setAfterAnyList(String[] afterAnyList) { AfterAnyList afterAny = this.getJobDescriptorDocument().getJobDescriptor().addNewAfterAny(); afterAny.setAfterAnyArray(afterAnyList); } public void setAfterOKList(String[] afterOKList) { AfterOKList afterAnyList = this.getJobDescriptorDocument().getJobDescriptor().addNewAfterOKList(); afterAnyList.setAfterOKListArray(afterOKList); } public void setCTime(String cTime) { this.getJobDescriptorDocument().getJobDescriptor().setCTime(cTime); } public void setQTime(String qTime) { this.getJobDescriptorDocument().getJobDescriptor().setQTime(qTime); } public void setMTime(String mTime) { this.getJobDescriptorDocument().getJobDescriptor().setMTime(mTime); } public void setSTime(String sTime) { this.getJobDescriptorDocument().getJobDescriptor().setSTime(sTime); } public void setCompTime(String compTime) { this.getJobDescriptorDocument().getJobDescriptor().setCompTime(compTime); } public void setOwner(String owner) { this.getJobDescriptorDocument().getJobDescriptor().setOwner(owner); } public void setExecuteNode(String executeNode) { this.getJobDescriptorDocument().getJobDescriptor().setExecuteNode(executeNode); } public void setEllapsedTime(String ellapsedTime) { this.getJobDescriptorDocument().getJobDescriptor().setEllapsedTime(ellapsedTime); } public void setUsedCPUTime(String usedCPUTime) { this.getJobDescriptorDocument().getJobDescriptor().setUsedCPUTime(usedCPUTime); } public void setCPUCount(int usedCPUTime) { this.getJobDescriptorDocument().getJobDescriptor().setCpuCount(usedCPUTime); } public void setUsedMemory(String usedMemory) { this.getJobDescriptorDocument().getJobDescriptor().setUsedMem(usedMemory); } public void setVariableList(String variableList) { this.getJobDescriptorDocument().getJobDescriptor().setVariableList(variableList); } public void setSubmitArgs(String submitArgs) { this.getJobDescriptorDocument().getJobDescriptor().setSubmitArgs(submitArgs); } public void setPreJobCommands(String[] commands){ if(this.getJobDescriptorDocument().getJobDescriptor().getPreJobCommands() == null){ this.getJobDescriptorDocument().getJobDescriptor().addNewPreJobCommands(); } this.getJobDescriptorDocument().getJobDescriptor().getPreJobCommands().setCommandArray(commands); } public void setPostJobCommands(String[] commands){ if(this.getJobDescriptorDocument().getJobDescriptor().getPostJobCommands() == null){ this.getJobDescriptorDocument().getJobDescriptor().addNewPostJobCommands(); } this.getJobDescriptorDocument().getJobDescriptor().getPostJobCommands().setCommandArray(commands); } public void addPreJobCommand(String command){ if(this.getJobDescriptorDocument().getJobDescriptor().getPreJobCommands() == null){ this.getJobDescriptorDocument().getJobDescriptor().addNewPreJobCommands(); } this.getJobDescriptorDocument().getJobDescriptor().getPreJobCommands().addCommand(command); } public void addPostJobCommand(String command){ if(this.getJobDescriptorDocument().getJobDescriptor().getPostJobCommands() == null){ this.getJobDescriptorDocument().getJobDescriptor().addNewPostJobCommands(); } this.getJobDescriptorDocument().getJobDescriptor().getPostJobCommands().addCommand(command); } public void setPartition(String partition){ this.getJobDescriptorDocument().getJobDescriptor().setPartition(partition); } public void setUserName(String userName){ this.getJobDescriptorDocument().getJobDescriptor().setUserName(userName); } public void setNodeList(String nodeList){ this.getJobDescriptorDocument().getJobDescriptor().setNodeList(nodeList); } public void setJobSubmitter(String jobSubmitter){ this.getJobDescriptorDocument().getJobDescriptor().setJobSubmitterCommand(jobSubmitter); } public String getNodeList(){ return this.getJobDescriptorDocument().getJobDescriptor().getNodeList(); } public String getExecutablePath() { return this.getJobDescriptorDocument().getJobDescriptor().getExecutablePath(); } public boolean getAllEnvExport() { return this.getJobDescriptorDocument().getJobDescriptor().getAllEnvExport(); } public String getMailOptions() { return this.getJobDescriptorDocument().getJobDescriptor().getMailOptions(); } public String getStandardOutFile() { return this.getJobDescriptorDocument().getJobDescriptor().getStandardOutFile(); } public String getStandardErrorFile() { return this.getJobDescriptorDocument().getJobDescriptor().getStandardErrorFile(); } public int getNodes(int name) { return this.getJobDescriptorDocument().getJobDescriptor().getNodes(); } public int getCPUCount(int name) { return this.getJobDescriptorDocument().getJobDescriptor().getCpuCount(); } public int getProcessesPerNode() { return this.getJobDescriptorDocument().getJobDescriptor().getProcessesPerNode(); } public String getMaxWallTime() { return this.getJobDescriptorDocument().getJobDescriptor().getMaxWallTime(); } public String getAcountString() { return this.getJobDescriptorDocument().getJobDescriptor().getAcountString(); } public String[] getInputValues() { return this.getJobDescriptorDocument().getJobDescriptor().getInputs().getInputArray(); } public String getJobID() { return this.getJobDescriptorDocument().getJobDescriptor().getJobID(); } public String getQueueName() { return this.getJobDescriptorDocument().getJobDescriptor().getQueueName(); } public String getStatus() { return this.getJobDescriptorDocument().getJobDescriptor().getStatus(); } public String[] getAfterAnyList() { return this.getJobDescriptorDocument().getJobDescriptor().getAfterAny().getAfterAnyArray(); } public String[] getAfterOKList() { return this.getJobDescriptorDocument().getJobDescriptor().getAfterOKList().getAfterOKListArray(); } public String getCTime() { return this.getJobDescriptorDocument().getJobDescriptor().getCTime(); } public String getQTime() { return this.getJobDescriptorDocument().getJobDescriptor().getQTime(); } public String getMTime() { return this.getJobDescriptorDocument().getJobDescriptor().getMTime(); } public String getSTime() { return this.getJobDescriptorDocument().getJobDescriptor().getSTime(); } public String getCompTime() { return this.getJobDescriptorDocument().getJobDescriptor().getCompTime(); } public String getOwner() { return this.getJobDescriptorDocument().getJobDescriptor().getOwner(); } public String getExecuteNode() { return this.getJobDescriptorDocument().getJobDescriptor().getExecuteNode(); } public String getEllapsedTime() { return this.getJobDescriptorDocument().getJobDescriptor().getEllapsedTime(); } public String getUsedCPUTime() { return this.getJobDescriptorDocument().getJobDescriptor().getUsedCPUTime(); } public String getUsedMemory() { return this.getJobDescriptorDocument().getJobDescriptor().getUsedMem(); } public void getShellName() { this.getJobDescriptorDocument().getJobDescriptor().getShellName(); } public String getJobName() { return this.getJobDescriptorDocument().getJobDescriptor().getJobName(); } public String getJobId() { return this.getJobDescriptorDocument().getJobDescriptor().getJobID(); } public String getVariableList() { return this.getJobDescriptorDocument().getJobDescriptor().getJobID(); } public String getSubmitArgs() { return this.getJobDescriptorDocument().getJobDescriptor().getJobID(); } public String[] getPostJobCommands(){ if(this.getJobDescriptorDocument().getJobDescriptor().getPostJobCommands() != null) { return this.getJobDescriptorDocument().getJobDescriptor().getPostJobCommands().getCommandArray(); } return null; } public String[] getPreJobCommands(){ if(this.getJobDescriptorDocument().getJobDescriptor().getPreJobCommands() != null) { return this.getJobDescriptorDocument().getJobDescriptor().getPreJobCommands().getCommandArray(); } return null; } public String getJobSubmitterCommand(){ return this.getJobDescriptorDocument().getJobDescriptor().getJobSubmitterCommand(); } public String getPartition(){ return this.getJobDescriptorDocument().getJobDescriptor().getPartition(); } public String getUserName(){ return this.getJobDescriptorDocument().getJobDescriptor().getUserName(); } public void setCallBackIp(String ip){ this.jobDescriptionDocument.getJobDescriptor().setCallBackIp(ip); } public void setCallBackPort(String ip){ this.jobDescriptionDocument.getJobDescriptor().setCallBackPort(ip); } public String getCallBackIp(){ return this.jobDescriptionDocument.getJobDescriptor().getCallBackIp(); } public String getCallBackPort(){ return this.jobDescriptionDocument.getJobDescriptor().getCallBackPort(); } }
/* * 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.processors.standard; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.nifi.annotation.behavior.EventDriven; import org.apache.nifi.annotation.behavior.InputRequirement; import org.apache.nifi.annotation.behavior.SideEffectFree; import org.apache.nifi.annotation.behavior.SupportsBatching; import org.apache.nifi.annotation.behavior.WritesAttribute; import org.apache.nifi.annotation.documentation.CapabilityDescription; import org.apache.nifi.annotation.documentation.Tags; import org.apache.nifi.annotation.lifecycle.OnScheduled; import org.apache.nifi.components.AllowableValue; import org.apache.nifi.components.PropertyDescriptor; import org.apache.nifi.components.ValidationContext; import org.apache.nifi.components.ValidationResult; import org.apache.nifi.flowfile.FlowFile; import org.apache.nifi.flowfile.attributes.CoreAttributes; import org.apache.nifi.logging.ComponentLog; import org.apache.nifi.processor.AbstractProcessor; import org.apache.nifi.processor.ProcessContext; import org.apache.nifi.processor.ProcessSession; import org.apache.nifi.processor.Relationship; import org.apache.nifi.processor.exception.ProcessException; import org.apache.nifi.processor.io.OutputStreamCallback; import org.apache.nifi.processor.util.StandardValidators; import org.apache.nifi.processors.standard.util.jolt.TransformFactory; import org.apache.nifi.processors.standard.util.jolt.TransformUtils; import org.apache.nifi.util.StopWatch; import org.apache.nifi.util.StringUtils; import org.apache.nifi.util.file.classloader.ClassLoaderUtils; import com.bazaarvoice.jolt.JoltTransform; import com.bazaarvoice.jolt.JsonUtils; @EventDriven @SideEffectFree @SupportsBatching @Tags({"json", "jolt", "transform", "shiftr", "chainr", "defaultr", "removr","cardinality","sort"}) @InputRequirement(InputRequirement.Requirement.INPUT_REQUIRED) @WritesAttribute(attribute = "mime.type",description = "Always set to application/json") @CapabilityDescription("Applies a list of Jolt specifications to the flowfile JSON payload. A new FlowFile is created " + "with transformed content and is routed to the 'success' relationship. If the JSON transform " + "fails, the original FlowFile is routed to the 'failure' relationship.") public class JoltTransformJSON extends AbstractProcessor { public static final AllowableValue SHIFTR = new AllowableValue("jolt-transform-shift", "Shift", "Shift input JSON/data to create the output JSON."); public static final AllowableValue CHAINR = new AllowableValue("jolt-transform-chain", "Chain", "Execute list of Jolt transformations."); public static final AllowableValue DEFAULTR = new AllowableValue("jolt-transform-default", "Default", " Apply default values to the output JSON."); public static final AllowableValue REMOVR = new AllowableValue("jolt-transform-remove", "Remove", " Remove values from input data to create the output JSON."); public static final AllowableValue CARDINALITY = new AllowableValue("jolt-transform-card", "Cardinality", "Change the cardinality of input elements to create the output JSON."); public static final AllowableValue SORTR = new AllowableValue("jolt-transform-sort", "Sort", "Sort input json key values alphabetically. Any specification set is ignored."); public static final AllowableValue CUSTOMR = new AllowableValue("jolt-transform-custom", "Custom", "Custom Transformation. Requires Custom Transformation Class Name"); public static final AllowableValue MODIFIER_DEFAULTR = new AllowableValue("jolt-transform-modify-default", "Modify - Default", "Writes when key is missing or value is null"); public static final AllowableValue MODIFIER_OVERWRITER = new AllowableValue("jolt-transform-modify-overwrite", "Modify - Overwrite", " Always overwrite value"); public static final AllowableValue MODIFIER_DEFINER = new AllowableValue("jolt-transform-modify-define", "Modify - Define", "Writes when key is missing"); public static final PropertyDescriptor JOLT_TRANSFORM = new PropertyDescriptor.Builder() .name("jolt-transform") .displayName("Jolt Transformation DSL") .description("Specifies the Jolt Transformation that should be used with the provided specification.") .required(true) .allowableValues(CARDINALITY, CHAINR, DEFAULTR, MODIFIER_DEFAULTR, MODIFIER_DEFINER, MODIFIER_OVERWRITER, REMOVR, SHIFTR, SORTR, CUSTOMR) .defaultValue(CHAINR.getValue()) .build(); public static final PropertyDescriptor JOLT_SPEC = new PropertyDescriptor.Builder() .name("jolt-spec") .displayName("Jolt Specification") .description("Jolt Specification for transform of JSON data. This value is ignored if the Jolt Sort Transformation is selected.") .expressionLanguageSupported(true) .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) .required(false) .build(); public static final PropertyDescriptor CUSTOM_CLASS = new PropertyDescriptor.Builder() .name("jolt-custom-class") .displayName("Custom Transformation Class Name") .description("Fully Qualified Class Name for Custom Transformation") .required(false) .expressionLanguageSupported(false) .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) .build(); public static final PropertyDescriptor MODULES = new PropertyDescriptor.Builder() .name("jolt-custom-modules") .displayName("Custom Module Directory") .description("Comma-separated list of paths to files and/or directories which contain modules containing custom transformations (that are not included on NiFi's classpath).") .required(false) .expressionLanguageSupported(false) .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) .build(); static final PropertyDescriptor TRANSFORM_CACHE_SIZE = new PropertyDescriptor.Builder() .name("Transform Cache Size") .description("Compiling a Jolt Transform can be fairly expensive. Ideally, this will be done only once. However, if the Expression Language is used in the transform, we may need " + "a new Transform for each FlowFile. This value controls how many of those Transforms we cache in memory in order to avoid having to compile the Transform each time.") .expressionLanguageSupported(false) .addValidator(StandardValidators.POSITIVE_INTEGER_VALIDATOR) .defaultValue("1") .required(true) .build(); public static final Relationship REL_SUCCESS = new Relationship.Builder() .name("success") .description("The FlowFile with transformed content will be routed to this relationship") .build(); public static final Relationship REL_FAILURE = new Relationship.Builder() .name("failure") .description("If a FlowFile fails processing for any reason (for example, the FlowFile is not valid JSON), it will be routed to this relationship") .build(); private final static List<PropertyDescriptor> properties; private final static Set<Relationship> relationships; private volatile ClassLoader customClassLoader; private final static String DEFAULT_CHARSET = "UTF-8"; // Cache is guarded by synchronizing on 'this'. private volatile int maxTransformsToCache = 10; private final Map<String, JoltTransform> transformCache = new LinkedHashMap<String, JoltTransform>() { @Override protected boolean removeEldestEntry(Map.Entry<String, JoltTransform> eldest) { final boolean evict = size() > maxTransformsToCache; if (evict) { getLogger().debug("Removing Jolt Transform from cache because cache is full"); } return evict; } }; static { final List<PropertyDescriptor> _properties = new ArrayList<>(); _properties.add(JOLT_TRANSFORM); _properties.add(CUSTOM_CLASS); _properties.add(MODULES); _properties.add(JOLT_SPEC); _properties.add(TRANSFORM_CACHE_SIZE); properties = Collections.unmodifiableList(_properties); final Set<Relationship> _relationships = new HashSet<>(); _relationships.add(REL_SUCCESS); _relationships.add(REL_FAILURE); relationships = Collections.unmodifiableSet(_relationships); } @Override public Set<Relationship> getRelationships() { return relationships; } @Override protected List<PropertyDescriptor> getSupportedPropertyDescriptors() { return properties; } @Override protected Collection<ValidationResult> customValidate(ValidationContext validationContext) { final List<ValidationResult> results = new ArrayList<>(super.customValidate(validationContext)); final String transform = validationContext.getProperty(JOLT_TRANSFORM).getValue(); final String customTransform = validationContext.getProperty(CUSTOM_CLASS).getValue(); final String modulePath = validationContext.getProperty(MODULES).isSet()? validationContext.getProperty(MODULES).getValue() : null; if(!validationContext.getProperty(JOLT_SPEC).isSet() || StringUtils.isEmpty(validationContext.getProperty(JOLT_SPEC).getValue())){ if(!SORTR.getValue().equals(transform)) { final String message = "A specification is required for this transformation"; results.add(new ValidationResult.Builder().valid(false) .explanation(message) .build()); } } else { final ClassLoader customClassLoader; try { if (modulePath != null) { customClassLoader = ClassLoaderUtils.getCustomClassLoader(modulePath, this.getClass().getClassLoader(), getJarFilenameFilter()); } else { customClassLoader = this.getClass().getClassLoader(); } final String specValue = validationContext.getProperty(JOLT_SPEC).getValue(); final String invalidExpressionMsg = validationContext.newExpressionLanguageCompiler().validateExpression(specValue,true); if (validationContext.isExpressionLanguagePresent(specValue) && invalidExpressionMsg != null) { final String customMessage = "The expression language used withing this specification is invalid"; results.add(new ValidationResult.Builder().valid(false) .explanation(customMessage) .build()); } else { //for validation we want to be able to ensure the spec is syntactically correct and not try to resolve variables since they may not exist yet Object specJson = SORTR.getValue().equals(transform) ? null : JsonUtils.jsonToObject(specValue.replaceAll("\\$\\{}","\\\\\\\\\\$\\{"), DEFAULT_CHARSET); if (CUSTOMR.getValue().equals(transform)) { if (StringUtils.isEmpty(customTransform)) { final String customMessage = "A custom transformation class should be provided. "; results.add(new ValidationResult.Builder().valid(false) .explanation(customMessage) .build()); } else { TransformFactory.getCustomTransform(customClassLoader, customTransform, specJson); } } else { TransformFactory.getTransform(customClassLoader, transform, specJson); } } } catch (final Exception e) { getLogger().info("Processor is not valid - " + e.toString()); String message = "Specification not valid for the selected transformation." ; results.add(new ValidationResult.Builder().valid(false) .explanation(message) .build()); } } return results; } @Override public void onTrigger(final ProcessContext context, ProcessSession session) throws ProcessException { final FlowFile original = session.get(); if (original == null) { return; } final ComponentLog logger = getLogger(); final StopWatch stopWatch = new StopWatch(true); final Object inputJson; try (final InputStream in = session.read(original)) { inputJson = JsonUtils.jsonToObject(in); } catch (final Exception e) { logger.error("Failed to transform {}; routing to failure", new Object[] {original, e}); session.transfer(original, REL_FAILURE); return; } final String jsonString; final ClassLoader originalContextClassLoader = Thread.currentThread().getContextClassLoader(); try { final JoltTransform transform = getTransform(context, original); if (customClassLoader != null) { Thread.currentThread().setContextClassLoader(customClassLoader); } final Object transformedJson = TransformUtils.transform(transform,inputJson); jsonString = JsonUtils.toJsonString(transformedJson); } catch (final Exception ex) { logger.error("Unable to transform {} due to {}", new Object[] {original, ex.toString(), ex}); session.transfer(original, REL_FAILURE); return; } finally { if (customClassLoader != null && originalContextClassLoader != null) { Thread.currentThread().setContextClassLoader(originalContextClassLoader); } } FlowFile transformed = session.write(original, new OutputStreamCallback() { @Override public void process(OutputStream out) throws IOException { out.write(jsonString.getBytes(DEFAULT_CHARSET)); } }); final String transformType = context.getProperty(JOLT_TRANSFORM).getValue(); transformed = session.putAttribute(transformed, CoreAttributes.MIME_TYPE.key(), "application/json"); session.transfer(transformed, REL_SUCCESS); session.getProvenanceReporter().modifyContent(transformed,"Modified With " + transformType ,stopWatch.getElapsed(TimeUnit.MILLISECONDS)); logger.info("Transformed {}", new Object[]{original}); } private JoltTransform getTransform(final ProcessContext context, final FlowFile flowFile) throws Exception { final String specString; if (context.getProperty(JOLT_SPEC).isSet() && !StringUtils.isEmpty(context.getProperty(JOLT_SPEC).getValue())) { specString = context.getProperty(JOLT_SPEC).evaluateAttributeExpressions(flowFile).getValue(); } else { specString = null; } // Get the transform from our cache, if it exists. JoltTransform transform = null; synchronized (this) { transform = transformCache.get(specString); } if (transform != null) { return transform; } // If no transform for our spec, create the transform. final Object specJson; if (context.getProperty(JOLT_SPEC).isSet() && !SORTR.getValue().equals(context.getProperty(JOLT_TRANSFORM).getValue())) { specJson = JsonUtils.jsonToObject(specString, DEFAULT_CHARSET); } else { specJson = null; } if (CUSTOMR.getValue().equals(context.getProperty(JOLT_TRANSFORM).getValue())) { transform = TransformFactory.getCustomTransform(customClassLoader, context.getProperty(CUSTOM_CLASS).getValue(), specJson); } else { transform = TransformFactory.getTransform(customClassLoader, context.getProperty(JOLT_TRANSFORM).getValue(), specJson); } // Check again for the transform in our cache, since it's possible that another thread has // already populated it. If absent from the cache, populate the cache. Otherwise, use the // value from the cache. synchronized (this) { final JoltTransform existingTransform = transformCache.get(specString); if (existingTransform == null) { transformCache.put(specString, transform); } else { transform = existingTransform; } } return transform; } @OnScheduled public synchronized void setup(final ProcessContext context) { transformCache.clear(); maxTransformsToCache = context.getProperty(TRANSFORM_CACHE_SIZE).asInteger(); try { if (context.getProperty(MODULES).isSet()) { customClassLoader = ClassLoaderUtils.getCustomClassLoader(context.getProperty(MODULES).getValue(), this.getClass().getClassLoader(), getJarFilenameFilter()); } else { customClassLoader = this.getClass().getClassLoader(); } } catch (final Exception ex) { getLogger().error("Unable to setup processor", ex); } } protected FilenameFilter getJarFilenameFilter(){ return (dir, name) -> (name != null && name.endsWith(".jar")); } }
/* * 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.facebook.presto.sql.planner.optimizations; import com.facebook.presto.Session; import com.facebook.presto.common.QualifiedObjectName; import com.facebook.presto.common.type.Type; import com.facebook.presto.metadata.FunctionAndTypeManager; import com.facebook.presto.metadata.Metadata; import com.facebook.presto.spi.WarningCollector; import com.facebook.presto.spi.function.FunctionHandle; import com.facebook.presto.spi.relation.CallExpression; import com.facebook.presto.spi.relation.ConstantExpression; import com.facebook.presto.spi.relation.InputReferenceExpression; import com.facebook.presto.spi.relation.LambdaDefinitionExpression; import com.facebook.presto.spi.relation.RowExpression; import com.facebook.presto.spi.relation.RowExpressionVisitor; import com.facebook.presto.spi.relation.SpecialFormExpression; import com.facebook.presto.spi.relation.SpecialFormExpression.Form; import com.facebook.presto.spi.relation.VariableReferenceExpression; import com.facebook.presto.sql.parser.SqlParser; import com.facebook.presto.sql.planner.TypeProvider; import com.facebook.presto.sql.tree.Expression; import com.facebook.presto.sql.tree.NodeRef; import com.google.common.collect.ComparisonChain; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Ordering; import io.airlift.slice.Slice; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import static com.facebook.presto.common.function.OperatorType.EQUAL; import static com.facebook.presto.common.function.OperatorType.GREATER_THAN; import static com.facebook.presto.common.function.OperatorType.GREATER_THAN_OR_EQUAL; import static com.facebook.presto.common.function.OperatorType.IS_DISTINCT_FROM; import static com.facebook.presto.common.function.OperatorType.LESS_THAN; import static com.facebook.presto.common.function.OperatorType.LESS_THAN_OR_EQUAL; import static com.facebook.presto.common.function.OperatorType.NOT_EQUAL; import static com.facebook.presto.common.type.BooleanType.BOOLEAN; import static com.facebook.presto.spi.relation.SpecialFormExpression.Form.AND; import static com.facebook.presto.spi.relation.SpecialFormExpression.Form.OR; import static com.facebook.presto.sql.analyzer.ExpressionAnalyzer.getExpressionTypes; import static com.facebook.presto.sql.analyzer.TypeSignatureProvider.fromTypes; import static com.facebook.presto.sql.relational.SqlToRowExpressionTranslator.translate; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.ImmutableList.toImmutableList; import static java.lang.Integer.min; import static java.util.Collections.emptyList; import static java.util.Objects.requireNonNull; public class ExpressionEquivalence { private static final Ordering<RowExpression> ROW_EXPRESSION_ORDERING = Ordering.from(new RowExpressionComparator()); private final Metadata metadata; private final SqlParser sqlParser; private final CanonicalizationVisitor canonicalizationVisitor; public ExpressionEquivalence(Metadata metadata, SqlParser sqlParser) { this.metadata = requireNonNull(metadata, "metadata is null"); this.sqlParser = requireNonNull(sqlParser, "sqlParser is null"); this.canonicalizationVisitor = new CanonicalizationVisitor(metadata.getFunctionAndTypeManager()); } public boolean areExpressionsEquivalent(Session session, Expression leftExpression, Expression rightExpression, TypeProvider types) { Map<VariableReferenceExpression, Integer> variableInput = new HashMap<>(); int inputId = 0; for (VariableReferenceExpression variable : types.allVariables()) { variableInput.put(variable, inputId); inputId++; } RowExpression leftRowExpression = toRowExpression(session, leftExpression, variableInput, types); RowExpression rightRowExpression = toRowExpression(session, rightExpression, variableInput, types); RowExpression canonicalizedLeft = leftRowExpression.accept(canonicalizationVisitor, null); RowExpression canonicalizedRight = rightRowExpression.accept(canonicalizationVisitor, null); return canonicalizedLeft.equals(canonicalizedRight); } public boolean areExpressionsEquivalent(RowExpression leftExpression, RowExpression rightExpression) { RowExpression canonicalizedLeft = leftExpression.accept(canonicalizationVisitor, null); RowExpression canonicalizedRight = rightExpression.accept(canonicalizationVisitor, null); return canonicalizedLeft.equals(canonicalizedRight); } private RowExpression toRowExpression(Session session, Expression expression, Map<VariableReferenceExpression, Integer> variableInput, TypeProvider types) { // replace qualified names with input references since row expressions do not support these // determine the type of every expression Map<NodeRef<Expression>, Type> expressionTypes = getExpressionTypes( session, metadata, sqlParser, types, expression, emptyList(), /* parameters have already been replaced */ WarningCollector.NOOP); // convert to row expression return translate(expression, expressionTypes, variableInput, metadata.getFunctionAndTypeManager(), session); } private static class CanonicalizationVisitor implements RowExpressionVisitor<RowExpression, Void> { private final FunctionAndTypeManager functionAndTypeManager; public CanonicalizationVisitor(FunctionAndTypeManager functionAndTypeManager) { this.functionAndTypeManager = requireNonNull(functionAndTypeManager, "functionManager is null"); } @Override public RowExpression visitCall(CallExpression call, Void context) { call = new CallExpression( call.getDisplayName(), call.getFunctionHandle(), call.getType(), call.getArguments().stream() .map(expression -> expression.accept(this, context)) .collect(toImmutableList())); QualifiedObjectName callName = functionAndTypeManager.getFunctionMetadata(call.getFunctionHandle()).getName(); if (callName.equals(EQUAL.getFunctionName()) || callName.equals(NOT_EQUAL.getFunctionName()) || callName.equals(IS_DISTINCT_FROM.getFunctionName())) { // sort arguments return new CallExpression( call.getDisplayName(), call.getFunctionHandle(), call.getType(), ROW_EXPRESSION_ORDERING.sortedCopy(call.getArguments())); } if (callName.equals(GREATER_THAN.getFunctionName()) || callName.equals(GREATER_THAN_OR_EQUAL.getFunctionName())) { // convert greater than to less than FunctionHandle functionHandle = functionAndTypeManager.resolveOperator( callName.equals(GREATER_THAN.getFunctionName()) ? LESS_THAN : LESS_THAN_OR_EQUAL, swapPair(fromTypes(call.getArguments().stream().map(RowExpression::getType).collect(toImmutableList())))); return new CallExpression( call.getDisplayName(), functionHandle, call.getType(), swapPair(call.getArguments())); } return call; } public static List<RowExpression> flattenNestedSpecialForms(SpecialFormExpression specialForm) { Form form = specialForm.getForm(); ImmutableList.Builder<RowExpression> newArguments = ImmutableList.builder(); for (RowExpression argument : specialForm.getArguments()) { if (argument instanceof SpecialFormExpression && form.equals(((SpecialFormExpression) argument).getForm())) { // same special form type, so flatten the args newArguments.addAll(flattenNestedSpecialForms((SpecialFormExpression) argument)); } else { newArguments.add(argument); } } return newArguments.build(); } @Override public RowExpression visitConstant(ConstantExpression constant, Void context) { return constant; } @Override public RowExpression visitInputReference(InputReferenceExpression node, Void context) { return node; } @Override public RowExpression visitLambda(LambdaDefinitionExpression lambda, Void context) { return new LambdaDefinitionExpression(lambda.getArgumentTypes(), lambda.getArguments(), lambda.getBody().accept(this, context)); } @Override public RowExpression visitVariableReference(VariableReferenceExpression reference, Void context) { return reference; } @Override public RowExpression visitSpecialForm(SpecialFormExpression specialForm, Void context) { specialForm = new SpecialFormExpression( specialForm.getForm(), specialForm.getType(), specialForm.getArguments().stream() .map(expression -> expression.accept(this, context)) .collect(toImmutableList())); if (specialForm.getForm() == AND || specialForm.getForm() == OR) { // if we have nested calls (of the same type) flatten them List<RowExpression> flattenedArguments = flattenNestedSpecialForms(specialForm); // only consider distinct arguments Set<RowExpression> distinctArguments = ImmutableSet.copyOf(flattenedArguments); if (distinctArguments.size() == 1) { return Iterables.getOnlyElement(distinctArguments); } // canonicalize the argument order (i.e., sort them) List<RowExpression> sortedArguments = ROW_EXPRESSION_ORDERING.sortedCopy(distinctArguments); return new SpecialFormExpression(specialForm.getForm(), BOOLEAN, sortedArguments); } return specialForm; } } private static class RowExpressionComparator implements Comparator<RowExpression> { private final Comparator<Object> classComparator = Ordering.arbitrary(); private final ListComparator<RowExpression> argumentComparator = new ListComparator<>(this); @Override public int compare(RowExpression left, RowExpression right) { int result = classComparator.compare(left.getClass(), right.getClass()); if (result != 0) { return result; } if (left instanceof CallExpression) { CallExpression leftCall = (CallExpression) left; CallExpression rightCall = (CallExpression) right; return ComparisonChain.start() .compare(leftCall.getFunctionHandle().toString(), rightCall.getFunctionHandle().toString()) .compare(leftCall.getArguments(), rightCall.getArguments(), argumentComparator) .result(); } if (left instanceof ConstantExpression) { ConstantExpression leftConstant = (ConstantExpression) left; ConstantExpression rightConstant = (ConstantExpression) right; result = leftConstant.getType().getTypeSignature().toString().compareTo(right.getType().getTypeSignature().toString()); if (result != 0) { return result; } Object leftValue = leftConstant.getValue(); Object rightValue = rightConstant.getValue(); if (leftValue == null) { if (rightValue == null) { return 0; } else { return -1; } } else if (rightValue == null) { return 1; } Class<?> javaType = leftConstant.getType().getJavaType(); if (javaType == boolean.class) { return ((Boolean) leftValue).compareTo((Boolean) rightValue); } if (javaType == byte.class || javaType == short.class || javaType == int.class || javaType == long.class) { return Long.compare(((Number) leftValue).longValue(), ((Number) rightValue).longValue()); } if (javaType == float.class || javaType == double.class) { return Double.compare(((Number) leftValue).doubleValue(), ((Number) rightValue).doubleValue()); } if (javaType == Slice.class) { return ((Slice) leftValue).compareTo((Slice) rightValue); } // value is some random type (say regex), so we just randomly choose a greater value // todo: support all known type return -1; } if (left instanceof InputReferenceExpression) { return Integer.compare(((InputReferenceExpression) left).getField(), ((InputReferenceExpression) right).getField()); } if (left instanceof LambdaDefinitionExpression) { LambdaDefinitionExpression leftLambda = (LambdaDefinitionExpression) left; LambdaDefinitionExpression rightLambda = (LambdaDefinitionExpression) right; return ComparisonChain.start() .compare( leftLambda.getArgumentTypes(), rightLambda.getArgumentTypes(), new ListComparator<>(Comparator.comparing(Object::toString))) .compare( leftLambda.getArguments(), rightLambda.getArguments(), new ListComparator<>(Comparator.<String>naturalOrder())) .compare(leftLambda.getBody(), rightLambda.getBody(), this) .result(); } if (left instanceof VariableReferenceExpression) { VariableReferenceExpression leftVariableReference = (VariableReferenceExpression) left; VariableReferenceExpression rightVariableReference = (VariableReferenceExpression) right; return ComparisonChain.start() .compare(leftVariableReference.getName(), rightVariableReference.getName()) .compare(leftVariableReference.getType(), rightVariableReference.getType(), Comparator.comparing(Object::toString)) .result(); } if (left instanceof SpecialFormExpression) { SpecialFormExpression leftSpecialForm = (SpecialFormExpression) left; SpecialFormExpression rightSpecialForm = (SpecialFormExpression) right; return ComparisonChain.start() .compare(leftSpecialForm.getForm(), rightSpecialForm.getForm()) .compare(leftSpecialForm.getType(), rightSpecialForm.getType(), Comparator.comparing(Object::toString)) .compare(leftSpecialForm.getArguments(), rightSpecialForm.getArguments(), argumentComparator) .result(); } throw new IllegalArgumentException("Unsupported RowExpression type " + left.getClass().getSimpleName()); } } private static class ListComparator<T> implements Comparator<List<T>> { private final Comparator<T> elementComparator; public ListComparator(Comparator<T> elementComparator) { this.elementComparator = requireNonNull(elementComparator, "elementComparator is null"); } @Override public int compare(List<T> left, List<T> right) { int compareLength = min(left.size(), right.size()); for (int i = 0; i < compareLength; i++) { int result = elementComparator.compare(left.get(i), right.get(i)); if (result != 0) { return result; } } return Integer.compare(left.size(), right.size()); } } private static <T> List<T> swapPair(List<T> pair) { requireNonNull(pair, "pair is null"); checkArgument(pair.size() == 2, "Expected pair to have two elements"); return ImmutableList.of(pair.get(1), pair.get(0)); } }
// The MIT License (MIT) // // Copyright (c) <2014> <Michael Single> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.List; public class FreqResponseGenerator extends LookupGenerator { /** * @param args */ protected static int angMin; protected static int angMax; protected static double angInc; public static void main(String[] args) { // TODO Auto-generated method stub // TODO Auto-generated method stub FreqResponseGenerator lGen = new FreqResponseGenerator(); if (args.length > 0) ipPath = args[0]; if (args.length > 1) opPath = args[1]; if (args.length > 2) uvWid = Integer.parseInt(args[2]); uvHgh = uvWid; float lInc = (float)5e-3; // in microns if (args.length > 3) lInc = (float)(Integer.parseInt(args[3])*1e-3); if (args.length > 4) angMin = (Integer.parseInt(args[4])); if (args.length > 5) angMax = (Integer.parseInt(args[5])); if (args.length > 6) angInc = (Double.parseDouble(args[6])); if (args.length > 7) lGen.thetaI = (Integer.parseInt(args[7])) * Math.PI/180; if (args.length > 8) lGen.phiI = (Integer.parseInt(args[8])) * Math.PI/180; if (args.length > 9) lGen.phiR = (Integer.parseInt(args[9])) * Math.PI/180; else { System.out.println("Not continuing as all the parametes are not provided"); return ; } //LMAX = 1732e-3; List<Double> scalingFactors = lGen.readScalingFactors(ipPath+"extrema.txt"); lGen.setImgCnt(scalingFactors.size()/4/2); double[] minR = lGen.getMinReal(scalingFactors); double[] maxR = lGen.getMaxReal(scalingFactors); double[] minI = lGen.getMinImag(scalingFactors); double[] maxI = lGen.getMaxImag(scalingFactors); lGen.setDH(scalingFactors); lGen.initFFT(); lGen.loadFFTImages(minR, maxR, minI, maxI); lGen.setUpExpoAndFftOrigin(); lGen.initFactos(); //float lInc = (float)5e-3; // in microns lGen.prepareColorTables(lInc); //lGen.thetaI = (float)(Math.PI * 75.0/180.0); //lGen.phiI = (float)(Math.PI * 0.0/180.0); //lGen.phiR = (float)(Math.PI * 0.0/180.0); //vAngInc = 0.01f; String fileName = opPath; PrintStream opFile = null; try { opFile = new PrintStream(new BufferedOutputStream(new FileOutputStream(fileName))); opFile.println("angMin = " + angMin ); opFile.println("angMax = " + angMax ); opFile.println("angInc = " + angInc ); //opFile.println("lInc = " + LMAX -LMIN)*1e3 ); opFile.println("lMin = " + LMIN*1e3 ); opFile.println("lMax = " + LMAX*1e3 ); opFile.print("response= [ "); } catch (Exception e) { System.out.println("failed to write Response"); } lGen.numAng = (int)(Math.ceil((double)(angMax - angMin)/ angInc)); lGen.response = new float[lGen.numAng]; for (int lIdx = 0; lIdx < lGen.lambdaCnt; ++lIdx) { lGen.genFreqResponse(lIdx); lGen.writeFrequencyResponse(opFile, lIdx); } try { opFile.println("];"); opFile.close(); } catch (Exception e) { System.out.println("failed to write Response"); } } protected float[] response; protected int numAng; protected double thetaI; protected double phiI; protected double phiR; protected void writeFrequencyResponse(PrintStream opFile, int i) { try{ if( i != 0) opFile.println("; ..."); for(int v = 0; v < numAng; ++v) opFile.print(response[v] +", "); opFile.flush(); } catch (Exception e) { System.out.println("failed to write Response"); } System.out.println("Finished writing for " +i); } protected void genFreqResponse(int lIdx) { //for (int lIdx = 0; lIdx < this.lambdaCnt; ++lIdx) { //int midAngIdx = (numAng-1)/2; // -1 because of zero indexing // correct it for proper division //float vAngInc = 180.0f/ (numAng-1); for (int angIdx=0; angIdx < numAng; ++angIdx) { //float thetaR = (float)(Math.PI * (angIdx-midAngIdx)*vAngInc/180.0f ); float thetaR = (float)(Math.PI * (angMin + angInc*angIdx)/180.0f ); // here we made it positive so that angles are measured similarly for viewing and incidence // note , viewing is done at 180 degrees apart in PHI float k1X = (float)( Math.sin(thetaI)*Math.cos(phiI) ); float k1Y = (float)( Math.sin(thetaI)*Math.sin(phiI) ); float k1Z = - (float)( Math.cos(thetaI)); float k2X = (float)(Math.sin(thetaR)*Math.cos(phiR) ); float k2Y = (float)( Math.sin(thetaR)*Math.sin(phiR)); float k2Z = (float)( Math.cos(thetaR) ); float uu = k1X - k2X; float vv = k1Y - k2Y; float ww = k1Z - k2Z; double fftMagSqr = getFFTMagSqr_At(uu,vv,ww, lIdx); // to avoid response on obtuse angles if (angMin + angInc*angIdx > 90.0 || angMin + angInc*angIdx < -90.0) fftMagSqr = 0.0; response[angIdx] = (float)(fftMagSqr * gainAt(k1X, k1Y, k1Z, k2X, k2Y, k2Z) ); // no need for color tables yet } } } protected double gainAt(float k1X, float k1Y,float k1Z,float k2X, float k2Y, float k2Z) { float gF = 1 - (k1X*k2X + k1Y*k2Y + k1Z*k2Z ); gF = gF*gF; float ww = k1Z - k2Z; if (k1Z > 0.0 || k2Z < 0.0) { return 0.0; // This side is not visible } ww = ww * ww; if (ww < Math.pow(10.0,-4.0)) { // return 0.0; // Shadowing Function } gF = gF / k2Z; gF = gF / ww; double fFac = getFresnelFactor(k1X, k1Y, k1Z, k2X, k2Y, k2Z); //return fFac*gF; return 1.0; } protected double getFresnelFactor(float k1X, float k1Y,float k1Z,float k2X, float k2Y, float k2Z) { double nSkin = 1.5; double nK = 0.0; double hVecX = - k1X + k2X; double hVecY = - k1Y + k2Y; double hVecZ = - k1Z + k2Z; double normH; normH = Math.sqrt(hVecX*hVecX + hVecY*hVecY + hVecZ*hVecZ); hVecX /= normH; hVecY /= normH; hVecZ /= normH; double cosTheta = hVecX*k2X + hVecY*k2Y + hVecZ*k2Z; double fF = (nSkin - 1.0); fF = fF * fF; double R0 = fF + nK*nK; if (cosTheta > 0.999) fF = R0; else fF = fF + 4*nSkin*Math.pow(1- cosTheta,5.0) + nK*nK; // do this division if its not on relative scale // fF = fF/ ((nSkin + 1.0)* (nSkin + 1.0) + nK*nK); return fF/R0; } protected double getFFTMagSqr_At(float uu0, float vv0, float ww0, int lIdx) { double uu = (uu0 * dH)/ currLambda[lIdx]; double vv = (vv0 * dH)/ currLambda[lIdx]; // following call loads FFT values at given indices in temp buffers ie tmpRE, tmpIM // get indices in pixel units loadFFTValuesFor(vv, uu, imgCnt); double sumRealOverP = 0.0f; double sumImagOverP = 0.0f; for (int n = 0; n < imgCnt; ++n) { sumRealOverP += (Math.pow(2.0 * Math.PI, n) * (tmpRE[n] / Math.pow( currLambda[lIdx], n)) / facto[n]); sumImagOverP += (Math.pow(2.0 * Math.PI, n) * (tmpIM[n] / Math.pow( currLambda[lIdx], n)) / facto[n]); } return (sumRealOverP*sumRealOverP + sumImagOverP*sumImagOverP ); } }
/* Copyright (c) 2013-2016 Boundless and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/org/documents/edl-v10.html * * Contributors: * David Winslow (Boundless) - initial implementation */ package org.locationtech.geogig.storage.impl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.locationtech.geogig.model.ObjectId; import org.locationtech.geogig.model.impl.RevObjectTestSupport; import org.locationtech.geogig.repository.Platform; import org.locationtech.geogig.storage.GraphDatabase; import org.locationtech.geogig.storage.GraphDatabase.Direction; import org.locationtech.geogig.storage.GraphDatabase.GraphEdge; import org.locationtech.geogig.storage.GraphDatabase.GraphNode; import org.locationtech.geogig.test.TestPlatform; import com.google.common.collect.ImmutableList; /** * Abstract test suite for {@link GraphDatabase} implementations. * <p> * Create a concrete subclass of this test suite and implement {@link #createInjector()} so that * {@code GraphDtabase.class} is bound to your implementation instance as a singleton. */ public abstract class GraphDatabaseTest { protected GraphDatabase database; protected TestPlatform platform; @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); @Before public void setUp() throws Exception { File root = tmpFolder.getRoot(); tmpFolder.newFolder(".geogig"); platform = new TestPlatform(root); platform.setUserHome(tmpFolder.newFolder("fake_home")); database = createDatabase(platform); database.open(); } @After public void tearDown() throws Exception { if (database != null) { database.close(); } } protected abstract GraphDatabase createDatabase(Platform platform) throws Exception; @Test public void testNodes() throws IOException { ObjectId rootId = RevObjectTestSupport.hashString("root"); ImmutableList<ObjectId> parents = ImmutableList.of(); database.put(rootId, parents); ObjectId commit1 = RevObjectTestSupport.hashString("c1"); parents = ImmutableList.of(rootId); database.put(commit1, parents); ObjectId commit2 = RevObjectTestSupport.hashString("c2"); parents = ImmutableList.of(commit1); database.put(commit2, parents); ImmutableList<ObjectId> children = database.getChildren(commit2); parents = database.getParents(commit2); assertTrue(database.exists(commit2)); assertEquals("Size of " + children, 0, children.size()); assertEquals(1, parents.size()); assertEquals(commit1, parents.get(0)); children = database.getChildren(commit1); parents = database.getParents(commit1); assertTrue(database.exists(commit1)); assertEquals(1, children.size()); assertEquals(commit2, children.get(0)); assertEquals(1, parents.size()); assertEquals(rootId, parents.get(0)); children = database.getChildren(rootId); parents = database.getParents(rootId); assertTrue(database.exists(rootId)); assertEquals(1, children.size()); assertEquals(commit1, children.get(0)); assertEquals(0, parents.size()); } @Test public void testMapNode() throws IOException { ObjectId commitId = RevObjectTestSupport.hashString("commitId"); ObjectId mappedId = RevObjectTestSupport.hashString("mapped"); database.put(commitId, new ImmutableList.Builder<ObjectId>().build()); database.map(mappedId, commitId); ObjectId mapping = database.getMapping(mappedId); assertEquals(commitId + " : " + mappedId + " : " + mapping, commitId, mapping); // update mapping ObjectId commitId2 = RevObjectTestSupport.hashString("commitId2"); database.map(mappedId, commitId2); mapping = database.getMapping(mappedId); assertEquals(commitId2 + " : " + mappedId + " : " + mapping, commitId2, mapping); } @Test public void testDepth() throws IOException { // Create the following revision graph // x o - root commit // | |\ // | | o - commit1 // | | | // | | o - commit2 // | | |\ // | | | o - commit3 // | | | |\ // | | | | o - commit4 // | | | | | // | | | o | - commit5 // | | | |/ // | | | o - commit6 // | | | // | o | - commit7 // | | | // | | o - commit8 // | |/ // | o - commit9 // | // o - commit10 // | // o - commit11 ObjectId rootId = RevObjectTestSupport.hashString("root commit"); ImmutableList<ObjectId> parents = ImmutableList.of(); database.put(rootId, parents); ObjectId commit1 = RevObjectTestSupport.hashString("commit1"); parents = ImmutableList.of(rootId); database.put(commit1, parents); ObjectId commit2 = RevObjectTestSupport.hashString("commit2"); parents = ImmutableList.of(commit1); database.put(commit2, parents); ObjectId commit3 = RevObjectTestSupport.hashString("commit3"); parents = ImmutableList.of(commit2); database.put(commit3, parents); ObjectId commit4 = RevObjectTestSupport.hashString("commit4"); parents = ImmutableList.of(commit3); database.put(commit4, parents); ObjectId commit5 = RevObjectTestSupport.hashString("commit5"); parents = ImmutableList.of(commit3); database.put(commit5, parents); ObjectId commit6 = RevObjectTestSupport.hashString("commit6"); parents = ImmutableList.of(commit5, commit4); database.put(commit6, parents); ObjectId commit7 = RevObjectTestSupport.hashString("commit7"); parents = ImmutableList.of(rootId); database.put(commit7, parents); ObjectId commit8 = RevObjectTestSupport.hashString("commit8"); parents = ImmutableList.of(commit2); database.put(commit8, parents); ObjectId commit9 = RevObjectTestSupport.hashString("commit9"); parents = ImmutableList.of(commit7, commit8); database.put(commit9, parents); ObjectId commit10 = RevObjectTestSupport.hashString("commit10"); parents = ImmutableList.of(); database.put(commit10, parents); ObjectId commit11 = RevObjectTestSupport.hashString("commit11"); parents = ImmutableList.of(commit10); database.put(commit11, parents); assertEquals(0, database.getDepth(rootId)); assertEquals(2, database.getDepth(commit9)); assertEquals(3, database.getDepth(commit8)); assertEquals(5, database.getDepth(commit6)); assertEquals(4, database.getDepth(commit4)); assertEquals(1, database.getDepth(commit11)); } @Test public void testProperties() throws IOException { ObjectId rootId = RevObjectTestSupport.hashString("root"); ImmutableList<ObjectId> parents = ImmutableList.of(); database.put(rootId, parents); database.setProperty(rootId, GraphDatabase.SPARSE_FLAG, "true"); assertTrue(database.getNode(rootId).isSparse()); } @Test public void testEdges() throws IOException { ObjectId rootId = RevObjectTestSupport.hashString("root"); database.put(rootId, ImmutableList.of()); ObjectId commit1 = RevObjectTestSupport.hashString("c1"); database.put(commit1, ImmutableList.of(rootId)); ObjectId commit2 = RevObjectTestSupport.hashString("c2"); database.put(commit2, ImmutableList.of(commit1, rootId)); GraphNode node; List<GraphEdge> edges; node = database.getNode(commit2); assertNotNull(node); edges = ImmutableList.copyOf(node.getEdges(Direction.IN)); assertTrue(edges.isEmpty()); edges = ImmutableList.copyOf(node.getEdges(Direction.OUT)); assertEquals(2, edges.size()); assertEquals(commit1, edges.get(0).getToNode().getIdentifier()); assertEquals(rootId, edges.get(1).getToNode().getIdentifier()); node = database.getNode(commit1); assertNotNull(node); edges = ImmutableList.copyOf(node.getEdges(Direction.IN)); assertEquals(1, edges.size()); edges = ImmutableList.copyOf(node.getEdges(Direction.OUT)); assertEquals(1, edges.size()); } @Test public void testTruncate() throws IOException { ObjectId rootId = RevObjectTestSupport.hashString("root"); database.put(rootId, ImmutableList.of()); ObjectId commit1 = RevObjectTestSupport.hashString("c1"); database.put(commit1, ImmutableList.of(rootId)); ObjectId commit2 = RevObjectTestSupport.hashString("c2"); database.put(commit2, ImmutableList.of(commit1, rootId)); assertTrue(database.exists(rootId)); assertTrue(database.exists(commit1)); assertTrue(database.exists(commit2)); assertNotNull(database.getNode(rootId)); assertNotNull(database.getNode(commit1)); assertNotNull(database.getNode(commit2)); assertEquals(1, database.getDepth(commit2)); database.truncate(); // not using getNode for assertions cause it's contract is not well defined for an invalid // argument and implementations behave differently. Created an issue to fix it. // assertNull(database.getNode(rootId)); // assertNull(database.getNode(commit1)); // assertNull(database.getNode(commit2)); // assertEquals(0, database.getDepth(commit2)); assertFalse(database.exists(rootId)); assertFalse(database.exists(commit1)); assertFalse(database.exists(commit2)); } @Test public void testGetChildren() { ObjectId rootId = RevObjectTestSupport.hashString("root"); database.put(rootId, ImmutableList.of()); ObjectId commit1 = RevObjectTestSupport.hashString("c1"); database.put(commit1, ImmutableList.of(rootId)); ObjectId commit2 = RevObjectTestSupport.hashString("c2"); database.put(commit2, ImmutableList.of(commit1, rootId)); ImmutableList<ObjectId> children = database.getChildren(rootId); assertEquals(2, children.size()); assertTrue(children.contains(commit1)); assertTrue(children.contains(commit2)); children = database.getChildren(commit1); assertEquals(1, children.size()); assertTrue(children.contains(commit2)); children = database.getChildren(commit2); assertEquals(0, children.size()); children = database.getChildren(RevObjectTestSupport.hashString("nonexistent")); assertEquals(0, children.size()); } @Test public void testGetParents() { ObjectId rootId = RevObjectTestSupport.hashString("root"); database.put(rootId, ImmutableList.of()); ObjectId commit1 = RevObjectTestSupport.hashString("c1"); database.put(commit1, ImmutableList.of(rootId)); ObjectId commit2 = RevObjectTestSupport.hashString("c2"); database.put(commit2, ImmutableList.of(commit1, rootId)); ImmutableList<ObjectId> parents = database.getParents(rootId); assertEquals(0, parents.size()); parents = database.getParents(commit1); assertEquals(1, parents.size()); assertTrue(parents.contains(rootId)); parents = database.getParents(commit2); assertEquals(2, parents.size()); assertTrue(parents.contains(rootId)); assertTrue(parents.contains(commit1)); parents = database.getParents(RevObjectTestSupport.hashString("nonexistent")); assertEquals(0, parents.size()); } @Test public void testUpdateNode() { ObjectId nodeId = RevObjectTestSupport.hashString("node"); ObjectId nodeParent = RevObjectTestSupport.hashString("nodeParent"); boolean updated = database.put(nodeId, ImmutableList.of()); assertTrue(updated); GraphNode node = database.getNode(nodeId); assertFalse(node.getEdges(Direction.BOTH).hasNext()); updated = database.put(nodeId, ImmutableList.of(nodeParent)); assertTrue(updated); node = database.getNode(nodeId); Iterator<GraphEdge> edges = node.getEdges(Direction.BOTH); assertTrue(edges.hasNext()); GraphEdge edge = edges.next(); assertEquals(nodeId, edge.getFromNode().getIdentifier()); assertEquals(nodeParent, edge.getToNode().getIdentifier()); updated = database.put(nodeId, ImmutableList.of(nodeParent)); assertFalse(updated); } @Test public void testSparseNode() { ObjectId nodeId = RevObjectTestSupport.hashString("node"); database.put(nodeId, ImmutableList.of()); GraphNode node = database.getNode(nodeId); assertFalse(node.isSparse()); database.setProperty(nodeId, GraphDatabase.SPARSE_FLAG, "true"); node = database.getNode(nodeId); assertTrue(node.isSparse()); database.setProperty(nodeId, GraphDatabase.SPARSE_FLAG, "false"); node = database.getNode(nodeId); assertFalse(node.isSparse()); } }
/******************************************************************************* * * Copyright (C) 2015-2021 the BBoxDB project * * 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.bboxdb.test.distribution; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.bboxdb.commons.math.Hyperrectangle; import org.bboxdb.distribution.membership.BBoxDBInstance; import org.bboxdb.distribution.partitioner.SpacePartitionerCache; import org.bboxdb.distribution.partitioner.regionsplit.tuplesink.AbstractTupleSink; import org.bboxdb.distribution.partitioner.regionsplit.tuplesink.LocalTupleSink; import org.bboxdb.distribution.partitioner.regionsplit.tuplesink.NetworkTupleSink; import org.bboxdb.distribution.partitioner.regionsplit.tuplesink.TupleRedistributor; import org.bboxdb.distribution.placement.ResourceAllocationException; import org.bboxdb.distribution.region.DistributionRegion; import org.bboxdb.distribution.zookeeper.DistributionGroupAdapter; import org.bboxdb.distribution.zookeeper.TupleStoreAdapter; import org.bboxdb.distribution.zookeeper.ZookeeperClientFactory; import org.bboxdb.distribution.zookeeper.ZookeeperException; import org.bboxdb.misc.BBoxDBException; import org.bboxdb.storage.StorageManagerException; import org.bboxdb.storage.entity.DeletedTuple; import org.bboxdb.storage.entity.DistributionGroupConfiguration; import org.bboxdb.storage.entity.DistributionGroupConfigurationBuilder; import org.bboxdb.storage.entity.Tuple; import org.bboxdb.storage.entity.TupleStoreConfiguration; import org.bboxdb.storage.entity.TupleStoreName; import org.bboxdb.storage.tuplestore.manager.TupleStoreManagerRegistry; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.Mockito; public class TestTupleSink { /** * The tablename */ private static final TupleStoreName TABLENAME = new TupleStoreName("region_mytable"); /** * The distribution region */ private static final String TEST_GROUP = "region"; /** * The distribution group adapter */ private static DistributionGroupAdapter distributionGroupZookeeperAdapter; /** * The tuple store adapter */ private static TupleStoreAdapter tupleStoreAdapter; @BeforeClass public static void before() throws ZookeeperException, BBoxDBException, ResourceAllocationException { distributionGroupZookeeperAdapter = ZookeeperClientFactory.getZookeeperClient().getDistributionGroupAdapter(); tupleStoreAdapter = ZookeeperClientFactory.getZookeeperClient().getTupleStoreAdapter(); final DistributionGroupConfiguration configuration = DistributionGroupConfigurationBuilder .create(2) .withReplicationFactor((short) 0) .withPlacementStrategy("org.bboxdb.distribution.placement.DummyResourcePlacementStrategy", "") .build(); distributionGroupZookeeperAdapter.deleteDistributionGroup(TEST_GROUP); distributionGroupZookeeperAdapter.createDistributionGroup(TEST_GROUP, configuration); } /** * Redistribute a tuple without any registered regions * @throws Exception */ @Test(expected=StorageManagerException.class) public void testTupleWithoutRegions() throws Exception { final TupleRedistributor tupleRedistributor = createTupleRedistributor(); final Tuple tuple1 = new Tuple("abc", Hyperrectangle.FULL_SPACE, "".getBytes()); tupleRedistributor.redistributeTuple(tuple1); } /** * Register region two times * @throws BBoxDBException * @throws InterruptedException * @throws Exception */ @Test(expected=StorageManagerException.class) public void testRegisterRegionDuplicate() throws StorageManagerException, InterruptedException, BBoxDBException { final DistributionRegion distributionRegion = new DistributionRegion( TEST_GROUP, Hyperrectangle.createFullCoveringDimensionBoundingBox(3)); final TupleRedistributor tupleRedistributor = createTupleRedistributor(); tupleRedistributor.registerRegion(distributionRegion, new ArrayList<>()); tupleRedistributor.registerRegion(distributionRegion, new ArrayList<>()); } /** * Get the tuple redistributor * @return * @throws BBoxDBException * @throws InterruptedException */ protected TupleRedistributor createTupleRedistributor() throws InterruptedException, BBoxDBException { final TupleStoreName tupleStoreName = new TupleStoreName(TABLENAME.getFullname()); final TupleStoreManagerRegistry tupleStoreManagerRegistry = new TupleStoreManagerRegistry(); tupleStoreManagerRegistry.init(); return new TupleRedistributor(tupleStoreManagerRegistry, tupleStoreName); } /** * Test the tuple redistribution * @throws Exception */ @Test(timeout=60000) public void testTupleRedistribution1() throws Exception { final DistributionRegion distributionRegion1 = new DistributionRegion( TEST_GROUP, DistributionRegion.ROOT_NODE_ROOT_POINTER, new Hyperrectangle(0.0, 1.0, 0.0, 1.0, 0.0, 1.0), 1); final TupleRedistributor tupleRedistributor = createTupleRedistributor(); final AbstractTupleSink tupleSink1 = Mockito.mock(AbstractTupleSink.class); tupleRedistributor.registerRegion(distributionRegion1, Arrays.asList(tupleSink1)); final Tuple tuple1 = new Tuple("abc", new Hyperrectangle(0.0, 1.0, 0.0, 1.0, 0.0, 1.0), "".getBytes()); tupleRedistributor.redistributeTuple(tuple1); (Mockito.verify(tupleSink1, Mockito.times(1))).sinkTuple(Mockito.any(Tuple.class)); tupleRedistributor.redistributeTuple(tuple1); (Mockito.verify(tupleSink1, Mockito.times(2))).sinkTuple(Mockito.any(Tuple.class)); System.out.println(tupleRedistributor.getStatistics()); } /** * Test the tuple redistribution * @throws Exception */ @Test(timeout=60000) public void testTupleRedistribution2() throws Exception { final DistributionRegion distributionRegion1 = new DistributionRegion( TEST_GROUP, DistributionRegion.ROOT_NODE_ROOT_POINTER, new Hyperrectangle(0.0, 1.0, 0.0, 1.0, 0.0, 1.0), 1); final DistributionRegion distributionRegion2 = new DistributionRegion( TEST_GROUP, DistributionRegion.ROOT_NODE_ROOT_POINTER, new Hyperrectangle(5.0, 6.0, 5.0, 6.0, 5.0, 6.0), 1); final TupleRedistributor tupleRedistributor = createTupleRedistributor(); final AbstractTupleSink tupleSink1 = Mockito.mock(AbstractTupleSink.class); tupleRedistributor.registerRegion(distributionRegion1, Arrays.asList(tupleSink1)); final AbstractTupleSink tupleSink2 = Mockito.mock(AbstractTupleSink.class); tupleRedistributor.registerRegion(distributionRegion2, Arrays.asList(tupleSink2)); final Tuple tuple1 = new Tuple("abc", new Hyperrectangle(0.0, 1.0, 0.0, 1.0, 0.0, 1.0), "".getBytes()); tupleRedistributor.redistributeTuple(tuple1); (Mockito.verify(tupleSink1, Mockito.times(1))).sinkTuple(Mockito.any(Tuple.class)); (Mockito.verify(tupleSink2, Mockito.never())).sinkTuple(Mockito.any(Tuple.class)); final Tuple tuple2 = new Tuple("abc", new Hyperrectangle(5.0, 6.0, 5.0, 6.0, 5.0, 6.0), "".getBytes()); tupleRedistributor.redistributeTuple(tuple2); (Mockito.verify(tupleSink1, Mockito.times(1))).sinkTuple(Mockito.any(Tuple.class)); (Mockito.verify(tupleSink2, Mockito.times(1))).sinkTuple(Mockito.any(Tuple.class)); final Tuple tuple3 = new Tuple("abc", new Hyperrectangle(0.0, 6.0, 0.0, 6.0, 0.0, 6.0), "".getBytes()); tupleRedistributor.redistributeTuple(tuple3); (Mockito.verify(tupleSink1, Mockito.atLeast(2))).sinkTuple(Mockito.any(Tuple.class)); (Mockito.verify(tupleSink2, Mockito.atLeast(2))).sinkTuple(Mockito.any(Tuple.class)); final Tuple tuple4 = new DeletedTuple("abc"); tupleRedistributor.redistributeTuple(tuple4); (Mockito.verify(tupleSink1, Mockito.atLeast(3))).sinkTuple(Mockito.any(Tuple.class)); (Mockito.verify(tupleSink2, Mockito.atLeast(3))).sinkTuple(Mockito.any(Tuple.class)); System.out.println(tupleRedistributor.getStatistics()); } /** * Test the tuple sinks * @throws StorageManagerException * @throws BBoxDBException * @throws ZookeeperException * @throws InterruptedException */ @Test(timeout=60000) public void testTupleSink() throws StorageManagerException, BBoxDBException, ZookeeperException, InterruptedException { final DistributionRegion distributionRegion = SpacePartitionerCache .getInstance() .getSpacePartitionerForGroupName(TEST_GROUP) .getRootNode(); tupleStoreAdapter.deleteTable(TABLENAME); tupleStoreAdapter.writeTuplestoreConfiguration(TABLENAME, new TupleStoreConfiguration()); final List<BBoxDBInstance> systems = Arrays.asList( new BBoxDBInstance("10.0.0.1:10000"), new BBoxDBInstance("10.0.0.2:10000"), ZookeeperClientFactory.getLocalInstanceName()); distributionRegion.setSystems(systems); final TupleRedistributor tupleRedistributor = createTupleRedistributor(); tupleRedistributor.registerRegion(distributionRegion); final Map<DistributionRegion, List<AbstractTupleSink>> map = tupleRedistributor.getRegionMap(); Assert.assertEquals(1, map.size()); final long networkSinks = map.values() .stream() .flatMap(e -> e.stream()) .filter(s -> s instanceof NetworkTupleSink) .count(); Assert.assertEquals(2, networkSinks); final long localSinks = map.values() .stream() .flatMap(e -> e.stream()) .filter(s -> s instanceof LocalTupleSink) .count(); Assert.assertEquals(1, localSinks); } }
/* * Copyright (c) 2014 Remel Pugh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dabay6.libraries.androidshared.ui.dialogs; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.res.Resources; import android.os.Build.VERSION_CODES; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.DatePicker; import android.widget.TimePicker; import com.dabay6.libraries.androidshared.R; import com.dabay6.libraries.androidshared.R.id; import com.dabay6.libraries.androidshared.logging.Logger; import com.dabay6.libraries.androidshared.util.AndroidUtils; import com.dabay6.libraries.androidshared.view.ViewsFinder; import java.util.Calendar; /** * DateTimePickerDialogFragment * * @author Remel Pugh * @version 1.0 */ @SuppressWarnings("unused") public class DateTimePickerDialogFragment extends BaseDialogFragment { private final static String TAG = Logger.makeTag(DateTimePickerDialogFragment.class); private DatePicker datePicker; private OnDateTimePickerListener onDateTimePickerListener; private TimePicker timePicker; /** * Default constructor. */ public DateTimePickerDialogFragment() { } /** * Creates a new instance of the {@link DateTimePickerDialogFragment}. */ public static DateTimePickerDialogFragment newInstance() { return newInstance(null); } /** * Creates a new instance of the {@link DateTimePickerDialogFragment}. * * @return A {@link DateTimePickerDialogFragment}. */ public static DateTimePickerDialogFragment newInstance(final Long milliseconds) { return newInstance(milliseconds, null, null); } /** * @param milliseconds * @param minDateTime * @param maxDateTime * @return */ public static DateTimePickerDialogFragment newInstance(final Long milliseconds, final Long minDateTime, final Long maxDateTime) { final Bundle arguments = new Bundle(); final DateTimePickerDialogFragment fragment = new DateTimePickerDialogFragment(); if (milliseconds != null) { arguments.putLong("milliseconds", milliseconds); } if (minDateTime != null) { arguments.putLong("minDateTime", minDateTime); } if (maxDateTime != null) { arguments.putLong("maxDateTime", maxDateTime); } fragment.setArguments(arguments); return fragment; } /** * {@inheritDoc} */ @Override public void onAttach(final Activity activity) { super.onAttach(activity); try { onDateTimePickerListener = (OnDateTimePickerListener) activity; } catch (final ClassCastException ex) { throw new ClassCastException(activity.toString() + " must implement OnDateTimePickerListener"); } } /** * {@inheritDoc} */ @TargetApi(VERSION_CODES.HONEYCOMB) @Override public Dialog onCreateDialog(final Bundle savedInstanceState) { final AlertDialog.Builder builder; final Bundle arguments = getArguments(); final Context context = getActivity(); final Resources res = getActivity().getResources(); final String title = res.getString(R.string.date_time_picker_title); @SuppressLint("InflateParams") final View view = getActivity().getLayoutInflater().inflate(R.layout.util__date_time_picker, null); final ViewsFinder finder; Long milliseconds = null; finder = new ViewsFinder(view); if (arguments.containsKey("milliseconds")) { milliseconds = arguments.getLong("milliseconds"); } datePicker = finder.find(id.date_picker); timePicker = finder.find(id.time_picker); if (AndroidUtils.isAtLeastHoneycomb()) { if (arguments.containsKey("minDateTime")) { datePicker.setMinDate(arguments.getLong("minDateTime")); } if (arguments.containsKey("maxDateTime")) { datePicker.setMaxDate(arguments.getLong("maxDateTime")); } } if (milliseconds != null) { final Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(milliseconds); datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), null); timePicker.setCurrentHour(calendar.get(Calendar.HOUR_OF_DAY)); timePicker.setCurrentMinute(calendar.get(Calendar.MINUTE)); } builder = new AlertDialog.Builder(context).setTitle(title).setView(view); builder.setPositiveButton(R.string.date_time_picker_set, new OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { if (onDateTimePickerListener != null) { final Calendar calendar = Calendar.getInstance(); //noinspection MagicConstant calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(), timePicker.getCurrentHour(), timePicker.getCurrentMinute()); onDateTimePickerListener.onDateTimeSet(calendar.getTimeInMillis()); } dialog.dismiss(); } }); builder.setNegativeButton(android.R.string.cancel, new OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { if (onDateTimePickerListener != null) { onDateTimePickerListener.onDateTimeCancel(); } dialog.dismiss(); } }); builder.setNeutralButton(R.string.date_time_picker_now, new OnClickListener() { @Override public void onClick(final DialogInterface dialog, final int which) { if (onDateTimePickerListener != null) { onDateTimePickerListener.onDateTimeNow(System.currentTimeMillis()); } dialog.dismiss(); } }); return builder.create(); } /** * {@inheritDoc} */ @Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { return null; } /** * {@inheritDoc} */ @Override protected void afterViews(final Bundle savedInstanceState) { } /** * {@inheritDoc} */ @Override protected int getLayoutResourceId() { return 0; } /** * @return */ @Override protected Integer getMenuResourceId() { return null; } /** * OnDateTimePickerListener * * @author Remel Pugh * @version 1.0 */ public interface OnDateTimePickerListener { /** * */ void onDateTimeCancel(); /** * @param milliseconds The current system date/time. */ void onDateTimeNow(final long milliseconds); /** * @param milliseconds The selected date/time. */ void onDateTimeSet(final long milliseconds); } }
/* * The JTS Topology Suite is a collection of Java classes that * implement the fundamental operations required to validate a given * geo-spatial data set to a known topological specification. * * Copyright (C) 2001 Vivid Solutions * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ package com.vividsolutions.jts.geomgraph; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.vividsolutions.jts.algorithm.CGAlgorithms; import com.vividsolutions.jts.geom.*; import com.vividsolutions.jts.geom.impl.*; import com.vividsolutions.jts.io.*; import com.vividsolutions.jts.util.*; /** * @version 1.7 */ public abstract class EdgeRing { protected DirectedEdge startDe; // the directed edge which starts the list of edges for this EdgeRing private int maxNodeDegree = -1; private List edges = new ArrayList(); // the DirectedEdges making up this EdgeRing private List pts = new ArrayList(); private Label label = new Label(Location.NONE); // label stores the locations of each geometry on the face surrounded by this ring private LinearRing ring; // the ring created for this EdgeRing private boolean isHole; private EdgeRing shell; // if non-null, the ring is a hole and this EdgeRing is its containing shell private ArrayList holes = new ArrayList(); // a list of EdgeRings which are holes in this EdgeRing protected GeometryFactory geometryFactory; protected CGAlgorithms cga; public EdgeRing(DirectedEdge start, GeometryFactory geometryFactory, CGAlgorithms cga) { this.geometryFactory = geometryFactory; this.cga = cga; computePoints(start); computeRing(); } public boolean isIsolated() { return (label.getGeometryCount() == 1); } public boolean isHole() { //computePoints(); return isHole; } public Coordinate getCoordinate(int i) { return (Coordinate) pts.get(i); } public LinearRing getLinearRing() { return ring; } public Label getLabel() { return label; } public boolean isShell() { return shell == null; } public EdgeRing getShell() { return shell; } public void setShell(EdgeRing shell) { this.shell = shell; if (shell != null) shell.addHole(this); } public void addHole(EdgeRing ring) { holes.add(ring); } public Polygon toPolygon(GeometryFactory geometryFactory) { LinearRing[] holeLR = new LinearRing[holes.size()]; for (int i = 0; i < holes.size(); i++) { holeLR[i] = ((EdgeRing) holes.get(i)).getLinearRing(); } Polygon poly = geometryFactory.createPolygon(getLinearRing(), holeLR); return poly; } /** * Compute a LinearRing from the point list previously collected. * Test if the ring is a hole (i.e. if it is CCW) and set the hole flag * accordingly. */ public void computeRing() { if (ring != null) return; // don't compute more than once Coordinate[] coord = new Coordinate[pts.size()]; for (int i = 0; i < pts.size(); i++) { coord[i] = (Coordinate) pts.get(i); } ring = geometryFactory.createLinearRing(coord); isHole = cga.isCCW(ring.getCoordinates()); //Debug.println( (isHole ? "hole - " : "shell - ") + WKTWriter.toLineString(new CoordinateArraySequence(ring.getCoordinates()))); } abstract public DirectedEdge getNext(DirectedEdge de); abstract public void setEdgeRing(DirectedEdge de, EdgeRing er); /** * Returns the list of DirectedEdges that make up this EdgeRing */ public List getEdges() { return edges; } /** * Collect all the points from the DirectedEdges of this ring into a contiguous list */ protected void computePoints(DirectedEdge start) { //System.out.println("buildRing"); startDe = start; DirectedEdge de = start; boolean isFirstEdge = true; do { // Assert.isTrue(de != null, "found null Directed Edge"); if (de == null) throw new TopologyException("Found null DirectedEdge"); if (de.getEdgeRing() == this) throw new TopologyException("Directed Edge visited twice during ring-building at " + de.getCoordinate()); edges.add(de); //Debug.println(de); //Debug.println(de.getEdge()); Label label = de.getLabel(); Assert.isTrue(label.isArea()); mergeLabel(label); addPoints(de.getEdge(), de.isForward(), isFirstEdge); isFirstEdge = false; setEdgeRing(de, this); de = getNext(de); } while (de != startDe); } public int getMaxNodeDegree() { if (maxNodeDegree < 0) computeMaxNodeDegree(); return maxNodeDegree; } private void computeMaxNodeDegree() { maxNodeDegree = 0; DirectedEdge de = startDe; do { Node node = de.getNode(); int degree = ((DirectedEdgeStar) node.getEdges()).getOutgoingDegree(this); if (degree > maxNodeDegree) maxNodeDegree = degree; de = getNext(de); } while (de != startDe); maxNodeDegree *= 2; } public void setInResult() { DirectedEdge de = startDe; do { de.getEdge().setInResult(true); de = de.getNext(); } while (de != startDe); } protected void mergeLabel(Label deLabel) { mergeLabel(deLabel, 0); mergeLabel(deLabel, 1); } /** * Merge the RHS label from a DirectedEdge into the label for this EdgeRing. * The DirectedEdge label may be null. This is acceptable - it results * from a node which is NOT an intersection node between the Geometries * (e.g. the end node of a LinearRing). In this case the DirectedEdge label * does not contribute any information to the overall labelling, and is simply skipped. */ protected void mergeLabel(Label deLabel, int geomIndex) { int loc = deLabel.getLocation(geomIndex, Position.RIGHT); // no information to be had from this label if (loc == Location.NONE) return; // if there is no current RHS value, set it if (label.getLocation(geomIndex) == Location.NONE) { label.setLocation(geomIndex, loc); return; } } protected void addPoints(Edge edge, boolean isForward, boolean isFirstEdge) { Coordinate[] edgePts = edge.getCoordinates(); if (isForward) { int startIndex = 1; if (isFirstEdge) startIndex = 0; for (int i = startIndex; i < edgePts.length; i++) { pts.add(edgePts[i]); } } else { // is backward int startIndex = edgePts.length - 2; if (isFirstEdge) startIndex = edgePts.length - 1; for (int i = startIndex; i >= 0; i--) { pts.add(edgePts[i]); } } } /** * This method will cause the ring to be computed. * It will also check any holes, if they have been assigned. */ public boolean containsPoint(Coordinate p) { LinearRing shell = getLinearRing(); Envelope env = shell.getEnvelopeInternal(); if (! env.contains(p)) return false; if (! cga.isPointInRing(p, shell.getCoordinates()) ) return false; for (Iterator i = holes.iterator(); i.hasNext(); ) { EdgeRing hole = (EdgeRing) i.next(); if (hole.containsPoint(p) ) return false; } return true; } }
/* * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.swing.plaf.basic; import javax.accessibility.AccessibleContext; import javax.swing.*; import javax.swing.border.Border; import javax.swing.border.LineBorder; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; import java.io.Serializable; /** * This is a basic implementation of the <code>ComboPopup</code> interface. * * This class represents the ui for the popup portion of the combo box. * <p> * All event handling is handled by listener classes created with the * <code>createxxxListener()</code> methods and internal classes. * You can change the behavior of this class by overriding the * <code>createxxxListener()</code> methods and supplying your own * event listeners or subclassing from the ones supplied in this class. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans&trade; * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @author Tom Santos * @author Mark Davidson */ public class BasicComboPopup extends JPopupMenu implements ComboPopup { // An empty ListMode, this is used when the UI changes to allow // the JList to be gc'ed. private static class EmptyListModelClass implements ListModel<Object>, Serializable { public int getSize() { return 0; } public Object getElementAt(int index) { return null; } public void addListDataListener(ListDataListener l) {} public void removeListDataListener(ListDataListener l) {} }; static final ListModel EmptyListModel = new EmptyListModelClass(); private static Border LIST_BORDER = new LineBorder(Color.BLACK, 1); protected JComboBox comboBox; /** * This protected field is implementation specific. Do not access directly * or override. Use the accessor methods instead. * * @see #getList * @see #createList */ protected JList list; /** * This protected field is implementation specific. Do not access directly * or override. Use the create method instead * * @see #createScroller */ protected JScrollPane scroller; /** * As of Java 2 platform v1.4 this previously undocumented field is no * longer used. */ protected boolean valueIsAdjusting = false; // Listeners that are required by the ComboPopup interface /** * Implementation of all the listener classes. */ private Handler handler; /** * This protected field is implementation specific. Do not access directly * or override. Use the accessor or create methods instead. * * @see #getMouseMotionListener * @see #createMouseMotionListener */ protected MouseMotionListener mouseMotionListener; /** * This protected field is implementation specific. Do not access directly * or override. Use the accessor or create methods instead. * * @see #getMouseListener * @see #createMouseListener */ protected MouseListener mouseListener; /** * This protected field is implementation specific. Do not access directly * or override. Use the accessor or create methods instead. * * @see #getKeyListener * @see #createKeyListener */ protected KeyListener keyListener; /** * This protected field is implementation specific. Do not access directly * or override. Use the create method instead. * * @see #createListSelectionListener */ protected ListSelectionListener listSelectionListener; // Listeners that are attached to the list /** * This protected field is implementation specific. Do not access directly * or override. Use the create method instead. * * @see #createListMouseListener */ protected MouseListener listMouseListener; /** * This protected field is implementation specific. Do not access directly * or override. Use the create method instead * * @see #createListMouseMotionListener */ protected MouseMotionListener listMouseMotionListener; // Added to the combo box for bound properties /** * This protected field is implementation specific. Do not access directly * or override. Use the create method instead * * @see #createPropertyChangeListener */ protected PropertyChangeListener propertyChangeListener; // Added to the combo box model /** * This protected field is implementation specific. Do not access directly * or override. Use the create method instead * * @see #createListDataListener */ protected ListDataListener listDataListener; /** * This protected field is implementation specific. Do not access directly * or override. Use the create method instead * * @see #createItemListener */ protected ItemListener itemListener; private MouseWheelListener scrollerMouseWheelListener; /** * This protected field is implementation specific. Do not access directly * or override. */ protected Timer autoscrollTimer; protected boolean hasEntered = false; protected boolean isAutoScrolling = false; protected int scrollDirection = SCROLL_UP; protected static final int SCROLL_UP = 0; protected static final int SCROLL_DOWN = 1; //======================================== // begin ComboPopup method implementations // /** * Implementation of ComboPopup.show(). */ public void show() { comboBox.firePopupMenuWillBecomeVisible(); setListSelection(comboBox.getSelectedIndex()); Point location = getPopupLocation(); show( comboBox, location.x, location.y ); } /** * Implementation of ComboPopup.hide(). */ public void hide() { MenuSelectionManager manager = MenuSelectionManager.defaultManager(); MenuElement [] selection = manager.getSelectedPath(); for ( int i = 0 ; i < selection.length ; i++ ) { if ( selection[i] == this ) { manager.clearSelectedPath(); break; } } if (selection.length > 0) { comboBox.repaint(); } } /** * Implementation of ComboPopup.getList(). */ public JList getList() { return list; } /** * Implementation of ComboPopup.getMouseListener(). * * @return a <code>MouseListener</code> or null * @see ComboPopup#getMouseListener */ public MouseListener getMouseListener() { if (mouseListener == null) { mouseListener = createMouseListener(); } return mouseListener; } /** * Implementation of ComboPopup.getMouseMotionListener(). * * @return a <code>MouseMotionListener</code> or null * @see ComboPopup#getMouseMotionListener */ public MouseMotionListener getMouseMotionListener() { if (mouseMotionListener == null) { mouseMotionListener = createMouseMotionListener(); } return mouseMotionListener; } /** * Implementation of ComboPopup.getKeyListener(). * * @return a <code>KeyListener</code> or null * @see ComboPopup#getKeyListener */ public KeyListener getKeyListener() { if (keyListener == null) { keyListener = createKeyListener(); } return keyListener; } /** * Called when the UI is uninstalling. Since this popup isn't in the component * tree, it won't get it's uninstallUI() called. It removes the listeners that * were added in addComboBoxListeners(). */ public void uninstallingUI() { if (propertyChangeListener != null) { comboBox.removePropertyChangeListener( propertyChangeListener ); } if (itemListener != null) { comboBox.removeItemListener( itemListener ); } uninstallComboBoxModelListeners(comboBox.getModel()); uninstallKeyboardActions(); uninstallListListeners(); uninstallScrollerListeners(); // We do this, otherwise the listener the ui installs on // the model (the combobox model in this case) will keep a // reference to the list, causing the list (and us) to never get gced. list.setModel(EmptyListModel); } // // end ComboPopup method implementations //====================================== /** * Removes the listeners from the combo box model * * @param model The combo box model to install listeners * @see #installComboBoxModelListeners */ protected void uninstallComboBoxModelListeners( ComboBoxModel model ) { if (model != null && listDataListener != null) { model.removeListDataListener(listDataListener); } } protected void uninstallKeyboardActions() { // XXX - shouldn't call this method // comboBox.unregisterKeyboardAction( KeyStroke.getKeyStroke( KeyEvent.VK_ENTER, 0 ) ); } //=================================================================== // begin Initialization routines // public BasicComboPopup( JComboBox combo ) { super(); setName("ComboPopup.popup"); comboBox = combo; setLightWeightPopupEnabled( comboBox.isLightWeightPopupEnabled() ); // UI construction of the popup. list = createList(); list.setName("ComboBox.list"); configureList(); scroller = createScroller(); scroller.setName("ComboBox.scrollPane"); configureScroller(); configurePopup(); installComboBoxListeners(); installKeyboardActions(); } // Overriden PopupMenuListener notification methods to inform combo box // PopupMenuListeners. protected void firePopupMenuWillBecomeVisible() { super.firePopupMenuWillBecomeVisible(); // comboBox.firePopupMenuWillBecomeVisible() is called from BasicComboPopup.show() method // to let the user change the popup menu from the PopupMenuListener.popupMenuWillBecomeVisible() } protected void firePopupMenuWillBecomeInvisible() { super.firePopupMenuWillBecomeInvisible(); comboBox.firePopupMenuWillBecomeInvisible(); } protected void firePopupMenuCanceled() { super.firePopupMenuCanceled(); comboBox.firePopupMenuCanceled(); } /** * Creates a listener * that will watch for mouse-press and release events on the combo box. * * <strong>Warning:</strong> * When overriding this method, make sure to maintain the existing * behavior. * * @return a <code>MouseListener</code> which will be added to * the combo box or null */ protected MouseListener createMouseListener() { return getHandler(); } /** * Creates the mouse motion listener which will be added to the combo * box. * * <strong>Warning:</strong> * When overriding this method, make sure to maintain the existing * behavior. * * @return a <code>MouseMotionListener</code> which will be added to * the combo box or null */ protected MouseMotionListener createMouseMotionListener() { return getHandler(); } /** * Creates the key listener that will be added to the combo box. If * this method returns null then it will not be added to the combo box. * * @return a <code>KeyListener</code> or null */ protected KeyListener createKeyListener() { return null; } /** * Creates a list selection listener that watches for selection changes in * the popup's list. If this method returns null then it will not * be added to the popup list. * * @return an instance of a <code>ListSelectionListener</code> or null */ protected ListSelectionListener createListSelectionListener() { return null; } /** * Creates a list data listener which will be added to the * <code>ComboBoxModel</code>. If this method returns null then * it will not be added to the combo box model. * * @return an instance of a <code>ListDataListener</code> or null */ protected ListDataListener createListDataListener() { return null; } /** * Creates a mouse listener that watches for mouse events in * the popup's list. If this method returns null then it will * not be added to the combo box. * * @return an instance of a <code>MouseListener</code> or null */ protected MouseListener createListMouseListener() { return getHandler(); } /** * Creates a mouse motion listener that watches for mouse motion * events in the popup's list. If this method returns null then it will * not be added to the combo box. * * @return an instance of a <code>MouseMotionListener</code> or null */ protected MouseMotionListener createListMouseMotionListener() { return getHandler(); } /** * Creates a <code>PropertyChangeListener</code> which will be added to * the combo box. If this method returns null then it will not * be added to the combo box. * * @return an instance of a <code>PropertyChangeListener</code> or null */ protected PropertyChangeListener createPropertyChangeListener() { return getHandler(); } /** * Creates an <code>ItemListener</code> which will be added to the * combo box. If this method returns null then it will not * be added to the combo box. * <p> * Subclasses may override this method to return instances of their own * ItemEvent handlers. * * @return an instance of an <code>ItemListener</code> or null */ protected ItemListener createItemListener() { return getHandler(); } private Handler getHandler() { if (handler == null) { handler = new Handler(); } return handler; } /** * Creates the JList used in the popup to display * the items in the combo box model. This method is called when the UI class * is created. * * @return a <code>JList</code> used to display the combo box items */ protected JList createList() { return new JList( comboBox.getModel() ) { public void processMouseEvent(MouseEvent e) { if (BasicGraphicsUtils.isMenuShortcutKeyDown(e)) { // Fix for 4234053. Filter out the Control Key from the list. // ie., don't allow CTRL key deselection. Toolkit toolkit = Toolkit.getDefaultToolkit(); e = new MouseEvent((Component)e.getSource(), e.getID(), e.getWhen(), e.getModifiers() ^ toolkit.getMenuShortcutKeyMask(), e.getX(), e.getY(), e.getXOnScreen(), e.getYOnScreen(), e.getClickCount(), e.isPopupTrigger(), MouseEvent.NOBUTTON); } super.processMouseEvent(e); } }; } /** * Configures the list which is used to hold the combo box items in the * popup. This method is called when the UI class * is created. * * @see #createList */ protected void configureList() { list.setFont( comboBox.getFont() ); list.setForeground( comboBox.getForeground() ); list.setBackground( comboBox.getBackground() ); list.setSelectionForeground( UIManager.getColor( "ComboBox.selectionForeground" ) ); list.setSelectionBackground( UIManager.getColor( "ComboBox.selectionBackground" ) ); list.setBorder( null ); list.setCellRenderer( comboBox.getRenderer() ); list.setFocusable( false ); list.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); setListSelection( comboBox.getSelectedIndex() ); installListListeners(); } /** * Adds the listeners to the list control. */ protected void installListListeners() { if ((listMouseListener = createListMouseListener()) != null) { list.addMouseListener( listMouseListener ); } if ((listMouseMotionListener = createListMouseMotionListener()) != null) { list.addMouseMotionListener( listMouseMotionListener ); } if ((listSelectionListener = createListSelectionListener()) != null) { list.addListSelectionListener( listSelectionListener ); } } void uninstallListListeners() { if (listMouseListener != null) { list.removeMouseListener(listMouseListener); listMouseListener = null; } if (listMouseMotionListener != null) { list.removeMouseMotionListener(listMouseMotionListener); listMouseMotionListener = null; } if (listSelectionListener != null) { list.removeListSelectionListener(listSelectionListener); listSelectionListener = null; } handler = null; } /** * Creates the scroll pane which houses the scrollable list. */ protected JScrollPane createScroller() { JScrollPane sp = new JScrollPane( list, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER ); sp.setHorizontalScrollBar(null); return sp; } /** * Configures the scrollable portion which holds the list within * the combo box popup. This method is called when the UI class * is created. */ protected void configureScroller() { scroller.setFocusable( false ); scroller.getVerticalScrollBar().setFocusable( false ); scroller.setBorder( null ); installScrollerListeners(); } /** * Configures the popup portion of the combo box. This method is called * when the UI class is created. */ protected void configurePopup() { setLayout( new BoxLayout( this, BoxLayout.Y_AXIS ) ); setBorderPainted( true ); setBorder(LIST_BORDER); setOpaque( false ); add( scroller ); setDoubleBuffered( true ); setFocusable( false ); } private void installScrollerListeners() { scrollerMouseWheelListener = getHandler(); if (scrollerMouseWheelListener != null) { scroller.addMouseWheelListener(scrollerMouseWheelListener); } } private void uninstallScrollerListeners() { if (scrollerMouseWheelListener != null) { scroller.removeMouseWheelListener(scrollerMouseWheelListener); scrollerMouseWheelListener = null; } } /** * This method adds the necessary listeners to the JComboBox. */ protected void installComboBoxListeners() { if ((propertyChangeListener = createPropertyChangeListener()) != null) { comboBox.addPropertyChangeListener(propertyChangeListener); } if ((itemListener = createItemListener()) != null) { comboBox.addItemListener(itemListener); } installComboBoxModelListeners(comboBox.getModel()); } /** * Installs the listeners on the combo box model. Any listeners installed * on the combo box model should be removed in * <code>uninstallComboBoxModelListeners</code>. * * @param model The combo box model to install listeners * @see #uninstallComboBoxModelListeners */ protected void installComboBoxModelListeners( ComboBoxModel model ) { if (model != null && (listDataListener = createListDataListener()) != null) { model.addListDataListener(listDataListener); } } protected void installKeyboardActions() { /* XXX - shouldn't call this method. take it out for testing. ActionListener action = new ActionListener() { public void actionPerformed(ActionEvent e){ } }; comboBox.registerKeyboardAction( action, KeyStroke.getKeyStroke( KeyEvent.VK_ENTER, 0 ), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT ); */ } // // end Initialization routines //================================================================= //=================================================================== // begin Event Listenters // /** * A listener to be registered upon the combo box * (<em>not</em> its popup menu) * to handle mouse events * that affect the state of the popup menu. * The main purpose of this listener is to make the popup menu * appear and disappear. * This listener also helps * with click-and-drag scenarios by setting the selection if the mouse was * released over the list during a drag. * * <p> * <strong>Warning:</strong> * We recommend that you <em>not</em> * create subclasses of this class. * If you absolutely must create a subclass, * be sure to invoke the superclass * version of each method. * * @see BasicComboPopup#createMouseListener */ protected class InvocationMouseHandler extends MouseAdapter { /** * Responds to mouse-pressed events on the combo box. * * @param e the mouse-press event to be handled */ public void mousePressed( MouseEvent e ) { getHandler().mousePressed(e); } /** * Responds to the user terminating * a click or drag that began on the combo box. * * @param e the mouse-release event to be handled */ public void mouseReleased( MouseEvent e ) { getHandler().mouseReleased(e); } } /** * This listener watches for dragging and updates the current selection in the * list if it is dragging over the list. */ protected class InvocationMouseMotionHandler extends MouseMotionAdapter { public void mouseDragged( MouseEvent e ) { getHandler().mouseDragged(e); } } /** * As of Java 2 platform v 1.4, this class is now obsolete and is only included for * backwards API compatibility. Do not instantiate or subclass. * <p> * All the functionality of this class has been included in * BasicComboBoxUI ActionMap/InputMap methods. */ public class InvocationKeyHandler extends KeyAdapter { public void keyReleased( KeyEvent e ) {} } /** * As of Java 2 platform v 1.4, this class is now obsolete, doesn't do anything, and * is only included for backwards API compatibility. Do not call or * override. */ protected class ListSelectionHandler implements ListSelectionListener { public void valueChanged( ListSelectionEvent e ) {} } /** * As of 1.4, this class is now obsolete, doesn't do anything, and * is only included for backwards API compatibility. Do not call or * override. * <p> * The functionality has been migrated into <code>ItemHandler</code>. * * @see #createItemListener */ public class ListDataHandler implements ListDataListener { public void contentsChanged( ListDataEvent e ) {} public void intervalAdded( ListDataEvent e ) { } public void intervalRemoved( ListDataEvent e ) { } } /** * This listener hides the popup when the mouse is released in the list. */ protected class ListMouseHandler extends MouseAdapter { public void mousePressed( MouseEvent e ) { } public void mouseReleased(MouseEvent anEvent) { getHandler().mouseReleased(anEvent); } } /** * This listener changes the selected item as you move the mouse over the list. * The selection change is not committed to the model, this is for user feedback only. */ protected class ListMouseMotionHandler extends MouseMotionAdapter { public void mouseMoved( MouseEvent anEvent ) { getHandler().mouseMoved(anEvent); } } /** * This listener watches for changes to the selection in the * combo box. */ protected class ItemHandler implements ItemListener { public void itemStateChanged( ItemEvent e ) { getHandler().itemStateChanged(e); } } /** * This listener watches for bound properties that have changed in the * combo box. * <p> * Subclasses which wish to listen to combo box property changes should * call the superclass methods to ensure that the combo popup correctly * handles property changes. * * @see #createPropertyChangeListener */ protected class PropertyChangeHandler implements PropertyChangeListener { public void propertyChange( PropertyChangeEvent e ) { getHandler().propertyChange(e); } } private class AutoScrollActionHandler implements ActionListener { private int direction; AutoScrollActionHandler(int direction) { this.direction = direction; } public void actionPerformed(ActionEvent e) { if (direction == SCROLL_UP) { autoScrollUp(); } else { autoScrollDown(); } } } private class Handler implements ItemListener, MouseListener, MouseMotionListener, MouseWheelListener, PropertyChangeListener, Serializable { // // MouseListener // NOTE: this is added to both the JList and JComboBox // public void mouseClicked(MouseEvent e) { } public void mousePressed(MouseEvent e) { if (e.getSource() == list) { return; } if (!SwingUtilities.isLeftMouseButton(e) || !comboBox.isEnabled()) return; if ( comboBox.isEditable() ) { Component comp = comboBox.getEditor().getEditorComponent(); if ((!(comp instanceof JComponent)) || ((JComponent)comp).isRequestFocusEnabled()) { comp.requestFocus(); } } else if (comboBox.isRequestFocusEnabled()) { comboBox.requestFocus(); } togglePopup(); } public void mouseReleased(MouseEvent e) { if (e.getSource() == list) { if (list.getModel().getSize() > 0) { // JList mouse listener if (comboBox.getSelectedIndex() == list.getSelectedIndex()) { comboBox.getEditor().setItem(list.getSelectedValue()); } comboBox.setSelectedIndex(list.getSelectedIndex()); } comboBox.setPopupVisible(false); // workaround for cancelling an edited item (bug 4530953) if (comboBox.isEditable() && comboBox.getEditor() != null) { comboBox.configureEditor(comboBox.getEditor(), comboBox.getSelectedItem()); } return; } // JComboBox mouse listener Component source = (Component)e.getSource(); Dimension size = source.getSize(); Rectangle bounds = new Rectangle( 0, 0, size.width - 1, size.height - 1 ); if ( !bounds.contains( e.getPoint() ) ) { MouseEvent newEvent = convertMouseEvent( e ); Point location = newEvent.getPoint(); Rectangle r = new Rectangle(); list.computeVisibleRect( r ); if ( r.contains( location ) ) { if (comboBox.getSelectedIndex() == list.getSelectedIndex()) { comboBox.getEditor().setItem(list.getSelectedValue()); } comboBox.setSelectedIndex(list.getSelectedIndex()); } comboBox.setPopupVisible(false); } hasEntered = false; stopAutoScrolling(); } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } // // MouseMotionListener: // NOTE: this is added to both the List and ComboBox // public void mouseMoved(MouseEvent anEvent) { if (anEvent.getSource() == list) { Point location = anEvent.getPoint(); Rectangle r = new Rectangle(); list.computeVisibleRect( r ); if ( r.contains( location ) ) { updateListBoxSelectionForEvent( anEvent, false ); } } } public void mouseDragged( MouseEvent e ) { if (e.getSource() == list) { return; } if ( isVisible() ) { MouseEvent newEvent = convertMouseEvent( e ); Rectangle r = new Rectangle(); list.computeVisibleRect( r ); if ( newEvent.getPoint().y >= r.y && newEvent.getPoint().y <= r.y + r.height - 1 ) { hasEntered = true; if ( isAutoScrolling ) { stopAutoScrolling(); } Point location = newEvent.getPoint(); if ( r.contains( location ) ) { updateListBoxSelectionForEvent( newEvent, false ); } } else { if ( hasEntered ) { int directionToScroll = newEvent.getPoint().y < r.y ? SCROLL_UP : SCROLL_DOWN; if ( isAutoScrolling && scrollDirection != directionToScroll ) { stopAutoScrolling(); startAutoScrolling( directionToScroll ); } else if ( !isAutoScrolling ) { startAutoScrolling( directionToScroll ); } } else { if ( e.getPoint().y < 0 ) { hasEntered = true; startAutoScrolling( SCROLL_UP ); } } } } } // // PropertyChangeListener // public void propertyChange(PropertyChangeEvent e) { JComboBox comboBox = (JComboBox)e.getSource(); String propertyName = e.getPropertyName(); if ( propertyName == "model" ) { ComboBoxModel oldModel = (ComboBoxModel)e.getOldValue(); ComboBoxModel newModel = (ComboBoxModel)e.getNewValue(); uninstallComboBoxModelListeners(oldModel); installComboBoxModelListeners(newModel); list.setModel(newModel); if ( isVisible() ) { hide(); } } else if ( propertyName == "renderer" ) { list.setCellRenderer( comboBox.getRenderer() ); if ( isVisible() ) { hide(); } } else if (propertyName == "componentOrientation") { // Pass along the new component orientation // to the list and the scroller ComponentOrientation o =(ComponentOrientation)e.getNewValue(); JList list = getList(); if (list!=null && list.getComponentOrientation()!=o) { list.setComponentOrientation(o); } if (scroller!=null && scroller.getComponentOrientation()!=o) { scroller.setComponentOrientation(o); } if (o!=getComponentOrientation()) { setComponentOrientation(o); } } else if (propertyName == "lightWeightPopupEnabled") { setLightWeightPopupEnabled(comboBox.isLightWeightPopupEnabled()); } } // // ItemListener // public void itemStateChanged( ItemEvent e ) { if (e.getStateChange() == ItemEvent.SELECTED) { JComboBox comboBox = (JComboBox)e.getSource(); setListSelection(comboBox.getSelectedIndex()); } } // // MouseWheelListener // public void mouseWheelMoved(MouseWheelEvent e) { e.consume(); } } // // end Event Listeners //================================================================= /** * Overridden to unconditionally return false. */ public boolean isFocusTraversable() { return false; } //=================================================================== // begin Autoscroll methods // /** * This protected method is implementation specific and should be private. * do not call or override. */ protected void startAutoScrolling( int direction ) { // XXX - should be a private method within InvocationMouseMotionHandler // if possible. if ( isAutoScrolling ) { autoscrollTimer.stop(); } isAutoScrolling = true; if ( direction == SCROLL_UP ) { scrollDirection = SCROLL_UP; Point convertedPoint = SwingUtilities.convertPoint( scroller, new Point( 1, 1 ), list ); int top = list.locationToIndex( convertedPoint ); list.setSelectedIndex( top ); autoscrollTimer = new Timer( 100, new AutoScrollActionHandler( SCROLL_UP) ); } else if ( direction == SCROLL_DOWN ) { scrollDirection = SCROLL_DOWN; Dimension size = scroller.getSize(); Point convertedPoint = SwingUtilities.convertPoint( scroller, new Point( 1, (size.height - 1) - 2 ), list ); int bottom = list.locationToIndex( convertedPoint ); list.setSelectedIndex( bottom ); autoscrollTimer = new Timer(100, new AutoScrollActionHandler( SCROLL_DOWN)); } autoscrollTimer.start(); } /** * This protected method is implementation specific and should be private. * do not call or override. */ protected void stopAutoScrolling() { isAutoScrolling = false; if ( autoscrollTimer != null ) { autoscrollTimer.stop(); autoscrollTimer = null; } } /** * This protected method is implementation specific and should be private. * do not call or override. */ protected void autoScrollUp() { int index = list.getSelectedIndex(); if ( index > 0 ) { list.setSelectedIndex( index - 1 ); list.ensureIndexIsVisible( index - 1 ); } } /** * This protected method is implementation specific and should be private. * do not call or override. */ protected void autoScrollDown() { int index = list.getSelectedIndex(); int lastItem = list.getModel().getSize() - 1; if ( index < lastItem ) { list.setSelectedIndex( index + 1 ); list.ensureIndexIsVisible( index + 1 ); } } // // end Autoscroll methods //================================================================= //=================================================================== // begin Utility methods // /** * Gets the AccessibleContext associated with this BasicComboPopup. * The AccessibleContext will have its parent set to the ComboBox. * * @return an AccessibleContext for the BasicComboPopup * @since 1.5 */ public AccessibleContext getAccessibleContext() { AccessibleContext context = super.getAccessibleContext(); context.setAccessibleParent(comboBox); return context; } /** * This is is a utility method that helps event handlers figure out where to * send the focus when the popup is brought up. The standard implementation * delegates the focus to the editor (if the combo box is editable) or to * the JComboBox if it is not editable. */ protected void delegateFocus( MouseEvent e ) { if ( comboBox.isEditable() ) { Component comp = comboBox.getEditor().getEditorComponent(); if ((!(comp instanceof JComponent)) || ((JComponent)comp).isRequestFocusEnabled()) { comp.requestFocus(); } } else if (comboBox.isRequestFocusEnabled()) { comboBox.requestFocus(); } } /** * Makes the popup visible if it is hidden and makes it hidden if it is * visible. */ protected void togglePopup() { if ( isVisible() ) { hide(); } else { show(); } } /** * Sets the list selection index to the selectedIndex. This * method is used to synchronize the list selection with the * combo box selection. * * @param selectedIndex the index to set the list */ private void setListSelection(int selectedIndex) { if ( selectedIndex == -1 ) { list.clearSelection(); } else { list.setSelectedIndex( selectedIndex ); list.ensureIndexIsVisible( selectedIndex ); } } protected MouseEvent convertMouseEvent( MouseEvent e ) { Point convertedPoint = SwingUtilities.convertPoint( (Component)e.getSource(), e.getPoint(), list ); MouseEvent newEvent = new MouseEvent( (Component)e.getSource(), e.getID(), e.getWhen(), e.getModifiers(), convertedPoint.x, convertedPoint.y, e.getXOnScreen(), e.getYOnScreen(), e.getClickCount(), e.isPopupTrigger(), MouseEvent.NOBUTTON ); return newEvent; } /** * Retrieves the height of the popup based on the current * ListCellRenderer and the maximum row count. */ protected int getPopupHeightForRowCount(int maxRowCount) { // Set the cached value of the minimum row count int minRowCount = Math.min( maxRowCount, comboBox.getItemCount() ); int height = 0; ListCellRenderer renderer = list.getCellRenderer(); Object value = null; for ( int i = 0; i < minRowCount; ++i ) { value = list.getModel().getElementAt( i ); Component c = renderer.getListCellRendererComponent( list, value, i, false, false ); height += c.getPreferredSize().height; } if (height == 0) { height = comboBox.getHeight(); } Border border = scroller.getViewportBorder(); if (border != null) { Insets insets = border.getBorderInsets(null); height += insets.top + insets.bottom; } border = scroller.getBorder(); if (border != null) { Insets insets = border.getBorderInsets(null); height += insets.top + insets.bottom; } return height; } /** * Calculate the placement and size of the popup portion of the combo box based * on the combo box location and the enclosing screen bounds. If * no transformations are required, then the returned rectangle will * have the same values as the parameters. * * @param px starting x location * @param py starting y location * @param pw starting width * @param ph starting height * @return a rectangle which represents the placement and size of the popup */ protected Rectangle computePopupBounds(int px,int py,int pw,int ph) { Toolkit toolkit = Toolkit.getDefaultToolkit(); Rectangle screenBounds; // Calculate the desktop dimensions relative to the combo box. GraphicsConfiguration gc = comboBox.getGraphicsConfiguration(); Point p = new Point(); SwingUtilities.convertPointFromScreen(p, comboBox); if (gc != null) { Insets screenInsets = toolkit.getScreenInsets(gc); screenBounds = gc.getBounds(); screenBounds.width -= (screenInsets.left + screenInsets.right); screenBounds.height -= (screenInsets.top + screenInsets.bottom); screenBounds.x += (p.x + screenInsets.left); screenBounds.y += (p.y + screenInsets.top); } else { screenBounds = new Rectangle(p, toolkit.getScreenSize()); } Rectangle rect = new Rectangle(px,py,pw,ph); if (py+ph > screenBounds.y+screenBounds.height && ph < screenBounds.height) { rect.y = -rect.height; } return rect; } /** * Calculates the upper left location of the Popup. */ private Point getPopupLocation() { Dimension popupSize = comboBox.getSize(); Insets insets = getInsets(); // reduce the width of the scrollpane by the insets so that the popup // is the same width as the combo box. popupSize.setSize(popupSize.width - (insets.right + insets.left), getPopupHeightForRowCount( comboBox.getMaximumRowCount())); Rectangle popupBounds = computePopupBounds( 0, comboBox.getBounds().height, popupSize.width, popupSize.height); Dimension scrollSize = popupBounds.getSize(); Point popupLocation = popupBounds.getLocation(); scroller.setMaximumSize( scrollSize ); scroller.setPreferredSize( scrollSize ); scroller.setMinimumSize( scrollSize ); list.revalidate(); return popupLocation; } /** * A utility method used by the event listeners. Given a mouse event, it changes * the list selection to the list item below the mouse. */ protected void updateListBoxSelectionForEvent(MouseEvent anEvent,boolean shouldScroll) { // XXX - only seems to be called from this class. shouldScroll flag is // never true Point location = anEvent.getPoint(); if ( list == null ) return; int index = list.locationToIndex(location); if ( index == -1 ) { if ( location.y < 0 ) index = 0; else index = comboBox.getModel().getSize() - 1; } if ( list.getSelectedIndex() != index ) { list.setSelectedIndex(index); if ( shouldScroll ) list.ensureIndexIsVisible(index); } } // // end Utility methods //================================================================= }
/* * 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.jclouds.azureblob.domain.internal; import java.net.URI; import java.util.Date; import java.util.Map; import org.jclouds.azureblob.domain.BlobProperties; import org.jclouds.azureblob.domain.BlobType; import org.jclouds.azureblob.domain.LeaseStatus; import org.jclouds.azureblob.domain.MutableBlobProperties; import org.jclouds.http.HttpUtils; import org.jclouds.io.MutableContentMetadata; import org.jclouds.io.payloads.BaseMutableContentMetadata; import com.google.common.collect.Maps; /** * Allows you to manipulate metadata. */ public class MutableBlobPropertiesImpl implements MutableBlobProperties { private BlobType type = BlobType.BLOCK_BLOB; private LeaseStatus leaseStatus = LeaseStatus.UNLOCKED; private String name; private String container; private URI url; private Date lastModified; private String eTag; private MutableContentMetadata contentMetadata; private Map<String, String> metadata = Maps.newHashMap(); public MutableBlobPropertiesImpl() { super(); this.contentMetadata = new BaseMutableContentMetadata(); } public MutableBlobPropertiesImpl(BlobProperties from) { this.contentMetadata = new BaseMutableContentMetadata(); this.name = from.getName(); this.container = from.getContainer(); this.url = from.getUrl(); this.lastModified = from.getLastModified(); this.eTag = from.getETag(); this.metadata.putAll(from.getMetadata()); HttpUtils.copy(from.getContentMetadata(), this.contentMetadata); } /** *{@inheritDoc} */ @Override public BlobType getType() { return type; } /** * Set the blob type. */ public void setType(BlobType type) { this.type = type; } /** *{@inheritDoc} */ @Override public String getName() { return name; } /** *{@inheritDoc} */ @Override public Date getLastModified() { return lastModified; } /** *{@inheritDoc} */ @Override public String getETag() { return eTag; } /** *{@inheritDoc} */ @Override public int compareTo(BlobProperties o) { return (this == o) ? 0 : getName().compareTo(o.getName()); } /** *{@inheritDoc} */ @Override public Map<String, String> getMetadata() { return metadata; } /** *{@inheritDoc} */ @Override public LeaseStatus getLeaseStatus() { return leaseStatus; } /** *{@inheritDoc} */ @Override public void setETag(String eTag) { this.eTag = eTag; } /** *{@inheritDoc} */ @Override public void setName(String name) { this.name = name; } /** *{@inheritDoc} */ @Override public void setLastModified(Date lastModified) { this.lastModified = lastModified; } /** *{@inheritDoc} */ @Override public void setMetadata(Map<String, String> metadata) { this.metadata = metadata; } public void setUrl(URI url) { this.url = url; } public URI getUrl() { return url; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((url == null) ? 0 : url.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; MutableBlobPropertiesImpl other = (MutableBlobPropertiesImpl) obj; if (url == null) { if (other.url != null) return false; } else if (!url.equals(other.url)) return false; return true; } @Override public String toString() { return String .format( "[name=%s, container=%s, url=%s, contentMetadata=%s, eTag=%s, lastModified=%s, leaseStatus=%s, metadata=%s, type=%s]", name, container, url, contentMetadata, eTag, lastModified, leaseStatus, metadata, type); } /** * {@inheritDoc} */ @Override public MutableContentMetadata getContentMetadata() { return contentMetadata; } /** * {@inheritDoc} */ @Override public void setContentMetadata(MutableContentMetadata contentMetadata) { this.contentMetadata = contentMetadata; } /** *{@inheritDoc} */ @Override public String getContainer() { return container; } /** *{@inheritDoc} */ @Override public void setContainer(String container) { this.container = container; } }
package com.v5ent.game.entities; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Json; import com.v5ent.game.inventory.InventoryItem; import com.v5ent.game.pfa.MyNode; import com.v5ent.game.utils.Assets; /*** * Role contains:Character and NPC * It extends from Sprite,thus,owns transformation and draw */ public class Role extends Sprite{ private static final String TAG = Role.class.getSimpleName(); private static Json json = new Json(); // private Vector2 velocity; private float speed = 4*32f; private String entityId; /** path is arrived **/ private boolean isArrived = false; private boolean isSelected = false; private boolean isEntryBattle = false; public int battleZoneSteps = 0; private boolean isVisible = true; /** Animations **/ public Animation idleLeftAnimation; public Animation idleRightAnimation; public Animation idleUpAnimation; public Animation idleDownAnimation; private Animation walkLeftAnimation; private Animation walkRightAnimation; private Animation walkUpAnimation; private Animation walkDownAnimation; private Animation attackLeftAnimation; private Animation attackRightAnimation; private Animation attackUpAnimation; private Animation attackDownAnimation; /**temp position**/ protected Vector2 nextPosition; private State currentState = State.IDLE; private Direction currentDir = Direction.LEFT; protected float frameTime = 0f; /**just for draw */ public TextureRegion currentFrame = null; public Array<MyNode> path = new Array<MyNode>(true,10); // move to aim private Vector2 movingTarget; //InventoryItem private String questConfigPath; private String currentQuestID; private String itemTypeID = "NONE"; /** battle **/ private int healthPoint = 100; private int magicPoint = 100; private int attackPoint = 100; private int defensePoint = 100; private int hitDamageTotal = 100; private int goldPoint = 100; private int level = 1; // role inventory private Array<InventoryItem.ItemTypeID> inventory = new Array<InventoryItem.ItemTypeID>(); public Animation getAnimation(State animationType) { if(animationType==State.IDLE || animationType==State.FIXED){ switch (currentDir) { case UP: return idleUpAnimation; case RIGHT: return idleRightAnimation; case DOWN: return idleDownAnimation; case LEFT: return idleLeftAnimation; default: break; } } if(animationType==State.WALKING){ switch (currentDir) { case UP: return walkUpAnimation; case RIGHT: return walkRightAnimation; case DOWN: return walkDownAnimation; case LEFT: return walkLeftAnimation; default: break; } } return null; } public enum State { FIXED,IDLE, WALKING,ATTACK } public enum Direction { UP,RIGHT,DOWN,LEFT; } public Role(String entityId){ init(entityId); } public void init(String entityId){ this.entityId = entityId; this.nextPosition = new Vector2(); this.movingTarget = new Vector2(); Assets.AssetRole assetRole = Assets.instance.assetRoles.get(entityId); if(assetRole!=null){ this.idleLeftAnimation = assetRole.idleLeftAnimation; this.idleRightAnimation = assetRole.idleRightAnimation; this.idleUpAnimation = assetRole.idleUpAnimation; this.idleDownAnimation = assetRole.idleDownAnimation; this.walkLeftAnimation = assetRole.walkLeftAnimation; this.walkRightAnimation = assetRole.walkRightAnimation; this.walkUpAnimation = assetRole.walkUpAnimation; this.walkDownAnimation = assetRole.walkDownAnimation; this.attackLeftAnimation = assetRole.attackLeftAnimation; this.attackRightAnimation = assetRole.attackRightAnimation; this.attackUpAnimation = assetRole.attackUpAnimation; this.attackDownAnimation = assetRole.attackDownAnimation; currentFrame =idleRightAnimation.getKeyFrame(0); // Define sprite size to be 1m x 1m in game world this.setSize(currentFrame.getRegionWidth(), currentFrame.getRegionHeight()); // Set origin to sprite's center this.setOrigin(this.getWidth() / 2.0f, 0); //inventory initInventory("items/"+entityId+".json"); } Gdx.app.debug(TAG, "Construction :"+entityId ); } /** * load from json config */ public void initInventory(String itemsPath){ if(Gdx.files.internal(itemsPath).exists()) { Array<InventoryItem.ItemTypeID> list = json.fromJson(Array.class, Gdx.files.internal(itemsPath)); //inventory for (int i = 0; i < list.size; i++) { inventory.add(list.get(i)); } } } /** * if walking,just move to center * @param delta */ public void update(float delta) { if(this.currentState==State.WALKING){ calcNextPosition(delta); if(isEntryBattle){ battleZoneSteps++; } if(Math.abs(this.nextPosition.x-this.movingTarget.x*32f)<speed*delta && Math.abs(this.nextPosition.y-this.movingTarget.y*32f)<speed*delta){ this.setPosInMap(movingTarget); if(path!=null&&path.size>0){ MyNode nextPoint = path.pop(); moveTo(nextPoint.getX(),nextPoint.getY()); }else{ isArrived = true; this.currentState= State.IDLE; } } } frameTime = (frameTime + delta) % 4; // Want to avoid overflow updateCurrentFrame(); } /** * get correct frame from state and direction */ public void updateCurrentFrame() { // Look into the appropriate variable when changing position if(currentState==State.IDLE || currentState==State.FIXED){ switch (currentDir) { case UP: currentFrame = idleUpAnimation.getKeyFrame(0); break; case RIGHT: currentFrame = idleRightAnimation.getKeyFrame(0); break; case DOWN: currentFrame = idleDownAnimation.getKeyFrame(0); break; case LEFT: currentFrame = idleLeftAnimation.getKeyFrame(0); break; default: break; } } if(currentState==State.WALKING){ switch (currentDir) { case UP: currentFrame = walkUpAnimation.getKeyFrame(frameTime); break; case RIGHT: currentFrame = walkRightAnimation.getKeyFrame(frameTime); break; case DOWN: currentFrame = walkDownAnimation.getKeyFrame(frameTime); break; case LEFT: currentFrame = walkLeftAnimation.getKeyFrame(frameTime); break; default: break; } } if(currentState==State.ATTACK){ switch (currentDir) { case UP: currentFrame = attackUpAnimation.getKeyFrame(frameTime); break; case RIGHT: currentFrame = attackRightAnimation.getKeyFrame(frameTime); break; case DOWN: currentFrame = attackDownAnimation.getKeyFrame(frameTime); break; case LEFT: currentFrame = attackLeftAnimation.getKeyFrame(frameTime); break; default: break; } } } @Override public void draw(Batch batch) { if(!isVisible){ return; } if(isSelected){ //Draw selected batch.draw(Assets.instance.selected,getX(),getY()-2); }else{ batch.draw(Assets.instance.shadow,getX(),getY()-2); } /*if(currentState==State.ATTACK){ // Draw image batch.draw(currentFrame.getTexture(), getX()-32, getY(),getOriginX(), getOriginY(), getWidth()*2,getHeight(), getScaleX(), getScaleY(), getRotation(), currentFrame.getRegionX(), currentFrame.getRegionY(), currentFrame.getRegionWidth(), currentFrame.getRegionHeight(),false, false); }else{*/ // Draw image batch.draw(currentFrame.getTexture(), getX(), getY(),getOriginX(), getOriginY(), getWidth(),getHeight(), getScaleX(), getScaleY(), getRotation(), currentFrame.getRegionX(), currentFrame.getRegionY(), currentFrame.getRegionWidth(), currentFrame.getRegionHeight(),false, false); /*}*/ // Reset color to white batch.setColor(1, 1, 1, 1); } /** * move every delta time on speed * @param deltaTime */ public void calcNextPosition(float deltaTime) { float testX = this.getX(); float testY = this.getY(); speed *= (deltaTime); Vector2 v = new Vector2(movingTarget.x*32f-testX,movingTarget.y*32f-testY).nor(); nextPosition.x = testX + v.x*speed; nextPosition.y = testY + v.y*speed; // Gdx.app.debug(TAG, "nextPosition:"+nextPosition); // velocity speed *=(1 / deltaTime); setPosition(nextPosition.x, nextPosition.y); } public Vector2 getPosInMap(){ return new Vector2(MathUtils.floor(getX() / 32),MathUtils.floor(getY() / 32)); } public void setPosInMap(Vector2 point){ this.setPosition(point.x*32f,point.y*32f); movingTarget = point.cpy(); } public String getEntityId() { return entityId; } public boolean isArrived() { return isArrived; } public void setArrived(boolean arrived) { isArrived = arrived; } public String getItemTypeID() { return itemTypeID; } public void setItemTypeID(String itemTypeID) { this.itemTypeID = itemTypeID; } public Array<InventoryItem.ItemTypeID> getInventory() { return inventory; } public void setInventory(Array<InventoryItem.ItemTypeID> inventory) { this.inventory = inventory; } public boolean isSelected() { return isSelected; } public void setSelected(boolean selected) { isSelected = selected; } public boolean isVisible() { return isVisible; } public void setVisible(boolean visible) { isVisible = visible; } /** * move Role to x,y * @param x * @param y */ public void moveTo(int x,int y){ int gapX = x - MathUtils.floor(getX()/32); int gapY = y - MathUtils.floor(getY()/32); if(Math.abs(gapX)<Math.abs(gapY)){ if(gapY<0){ this.currentDir = Direction.DOWN; }else{ this.currentDir = Direction.UP; } }else{ if(gapX<0){ this.currentDir = Direction.LEFT; }else{ this.currentDir = Direction.RIGHT; } } this.currentState = State.WALKING; movingTarget = new Vector2(x,y); isArrived = false; } public void clearPathAndStop(){ // this.setPosInMap(new Vector2(x,y)); if(path!=null&&path.size>0){ path.clear(); } isArrived = true; this.currentState= State.IDLE; } public void followPath(Array<MyNode> newPath){ if(this.path.size<=0){ //remove current point newPath.pop(); } this.path.clear(); for(MyNode node:newPath){ this.path.add(node); } if(this.path.size>0) { MyNode nextPoint = this.path.pop(); moveTo(nextPoint.getX(), nextPoint.getY()); } } public State getState() { return currentState; } public void setState(State currentState) { this.currentState = currentState; } public Direction getCurrentDir() { return currentDir; } public void setCurrentDir(Direction currentDir) { this.currentDir = currentDir; } public int getDefensePoint() { return defensePoint; } public void setDefensePoint(int defensePoint) { this.defensePoint = defensePoint; } public int getAttackPoint() { return attackPoint; } public void setAttackPoint(int attackPoint) { this.attackPoint = attackPoint; } public int getHealthPoint() { return healthPoint; } public void setHealthPoint(int healthPoint) { this.healthPoint = healthPoint; } public int getMagicPoint() { return magicPoint; } public void setMagicPoint(int magicPoint) { this.magicPoint = magicPoint; } public int getHitDamageTotal() { return hitDamageTotal; } public void setHitDamageTotal(int hitDamageTotal) { this.hitDamageTotal = hitDamageTotal; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public int getGoldPoint() { return goldPoint; } public void setGoldPoint(int goldPoint) { this.goldPoint = goldPoint; } public boolean isEntryBattle() { return isEntryBattle; } public void setEntryBattle(boolean entryBattle) { isEntryBattle = entryBattle; } }
package net.steamcrafted.loadtoast; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.Log; import android.util.TypedValue; import android.view.View; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.DecelerateInterpolator; import android.view.animation.LinearInterpolator; import android.widget.ImageView; import com.nineoldandroids.animation.Animator; import com.nineoldandroids.animation.AnimatorListenerAdapter; import com.nineoldandroids.animation.ValueAnimator; /** * Created by Wannes2 on 23/04/2015. */ public class LoadToastView extends ImageView { private String mText = ""; private Paint textPaint = new Paint(); private Paint backPaint = new Paint(); private Paint iconBackPaint = new Paint(); private Paint loaderPaint = new Paint(); private Paint successPaint = new Paint(); private Paint errorPaint = new Paint(); private Paint borderPaint = new Paint(); private Rect iconBounds; private Rect mTextBounds = new Rect(); private RectF spinnerRect = new RectF(); private int MAX_TEXT_WIDTH = 100; // in DP private int BASE_TEXT_SIZE = 20; private int IMAGE_WIDTH = 40; private int TOAST_HEIGHT = 48; private int LINE_WIDTH = 3; private float WIDTH_SCALE = 0f; private int MARQUE_STEP = 1; private long prevUpdate = 0; private Drawable completeicon; private Drawable failedicon; private ValueAnimator va; private ValueAnimator cmp; private boolean success = true; private boolean outOfBounds = false; private boolean mLtr = true; private Path toastPath = new Path(); private AccelerateDecelerateInterpolator easeinterpol = new AccelerateDecelerateInterpolator(); private MaterialProgressDrawable spinnerDrawable; private int borderOffset = dpToPx(1); public LoadToastView(Context context) { super(context); textPaint.setTextSize(15); textPaint.setColor(Color.BLACK); textPaint.setAntiAlias(true); backPaint.setColor(Color.WHITE); backPaint.setAntiAlias(true); iconBackPaint.setColor(Color.BLUE); iconBackPaint.setAntiAlias(true); loaderPaint.setStrokeWidth(dpToPx(4)); loaderPaint.setAntiAlias(true); loaderPaint.setColor(fetchPrimaryColor()); loaderPaint.setStyle(Paint.Style.STROKE); borderPaint.setAntiAlias(true); borderPaint.setStrokeWidth(borderOffset * 2); borderPaint.setColor(Color.TRANSPARENT); borderPaint.setStyle(Paint.Style.STROKE); successPaint.setColor(getResources().getColor(R.color.color_success)); errorPaint.setColor(getResources().getColor(R.color.color_error)); successPaint.setAntiAlias(true); errorPaint.setAntiAlias(true); MAX_TEXT_WIDTH = dpToPx(MAX_TEXT_WIDTH); BASE_TEXT_SIZE = dpToPx(BASE_TEXT_SIZE); IMAGE_WIDTH = dpToPx(IMAGE_WIDTH); TOAST_HEIGHT = dpToPx(TOAST_HEIGHT); LINE_WIDTH = dpToPx(LINE_WIDTH); MARQUE_STEP = dpToPx(MARQUE_STEP); int padding = (TOAST_HEIGHT - IMAGE_WIDTH)/2; iconBounds = new Rect(TOAST_HEIGHT + MAX_TEXT_WIDTH - padding, padding, TOAST_HEIGHT + MAX_TEXT_WIDTH - padding + IMAGE_WIDTH, IMAGE_WIDTH + padding); //loadicon = getResources().getDrawable(R.mipmap.ic_launcher); //loadicon.setBounds(iconBounds); completeicon = getResources().getDrawable(R.drawable.ic_navigation_check); completeicon.setBounds(iconBounds); failedicon = getResources().getDrawable(R.drawable.ic_error); failedicon.setBounds(iconBounds); va = ValueAnimator.ofFloat(0,1); va.setDuration(6000); va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { //WIDTH_SCALE = valueAnimator.getAnimatedFraction(); postInvalidate(); } }); va.setRepeatMode(ValueAnimator.INFINITE); va.setRepeatCount(9999999); va.setInterpolator(new LinearInterpolator()); va.start(); initSpinner(); calculateBounds(); } private void initSpinner(){ spinnerDrawable = new MaterialProgressDrawable(getContext(), this); spinnerDrawable.setStartEndTrim(0, .5f); spinnerDrawable.setProgressRotation(.5f); int mDiameter = TOAST_HEIGHT; int mProgressStokeWidth = LINE_WIDTH; spinnerDrawable.setSizeParameters(mDiameter, mDiameter, (mDiameter - mProgressStokeWidth * 2) / 4, mProgressStokeWidth, mProgressStokeWidth * 4, mProgressStokeWidth * 2); spinnerDrawable.setBackgroundColor(Color.TRANSPARENT); spinnerDrawable.setColorSchemeColors(loaderPaint.getColor()); spinnerDrawable.setVisible(true, false); spinnerDrawable.setAlpha(255); setImageDrawable(null); setImageDrawable(spinnerDrawable); spinnerDrawable.start(); } public void setTextColor(int color){ textPaint.setColor(color); } public void setTextDirection(boolean isLeftToRight){ mLtr = isLeftToRight; } public void setBackgroundColor(int color){ backPaint.setColor(color); iconBackPaint.setColor(color); } public void setProgressColor(int color){ loaderPaint.setColor(color); spinnerDrawable.setColorSchemeColors(color); } public void setBorderColor(int color){ borderPaint.setColor(color); } public void setBorderWidthPx(int widthPx){ borderOffset = widthPx / 2; borderPaint.setStrokeWidth(borderOffset * 2); } public void setBorderWidthRes(int resourceId){ setBorderWidthPx(getResources().getDimensionPixelSize(resourceId)); } public void setBorderWidthDp(int width){ setBorderWidthPx(dpToPx(width)); } public void show(){ spinnerDrawable.stop(); spinnerDrawable.start(); WIDTH_SCALE = 0f; if(cmp != null){ cmp.removeAllUpdateListeners(); cmp.removeAllListeners(); } } public void success(){ success = true; done(); } public void error(){ success = false; done(); } private void done(){ cmp = ValueAnimator.ofFloat(0,1); cmp.setDuration(600); cmp.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { WIDTH_SCALE = 2f*(valueAnimator.getAnimatedFraction()); //Log.d("lt", "ws " + WIDTH_SCALE); postInvalidate(); } }); cmp.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationCancel(Animator animation) { super.onAnimationCancel(animation); cleanup(); } @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); cleanup(); } }); cmp.setInterpolator(new DecelerateInterpolator()); cmp.start(); } private int fetchPrimaryColor() { int color = Color.rgb(155, 155, 155); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ TypedValue typedValue = new TypedValue(); TypedArray a = getContext().obtainStyledAttributes(typedValue.data, new int[]{android.R.attr.colorAccent}); color = a.getColor(0, color); a.recycle(); } return color; } private int dpToPx(int dp){ return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()); } public void setText(String text) { mText = text; calculateBounds(); } private void calculateBounds() { outOfBounds = false; prevUpdate = 0; textPaint.setTextSize(BASE_TEXT_SIZE); textPaint.getTextBounds(mText, 0, mText.length(), mTextBounds); if(mTextBounds.width() > MAX_TEXT_WIDTH){ int textSize = BASE_TEXT_SIZE; while(textSize > dpToPx(13) && mTextBounds.width() > MAX_TEXT_WIDTH){ textSize--; //Log.d("bounds", "width " + mTextBounds.width() + " max " + MAX_TEXT_WIDTH); textPaint.setTextSize(textSize); textPaint.getTextBounds(mText, 0, mText.length(), mTextBounds); } if(mTextBounds.width() > MAX_TEXT_WIDTH){ outOfBounds = true; /** float keep = (float)MAX_TEXT_WIDTH / (float)mTextBounds.width(); int charcount = (int)(mText.length() * keep); //Log.d("calc", "keep " + charcount + " per " + keep + " len " + mText.length()); mText = mText.substring(0, charcount); textPaint.getTextBounds(mText, 0, mText.length(), mTextBounds); **/ } } } @Override protected void onDraw(Canvas c){ float ws = Math.max(1f - WIDTH_SCALE, 0f); // If there is nothing to display, just draw a circle if(mText.length() == 0) ws = 0; float translateLoad = (1f-ws)*(IMAGE_WIDTH+MAX_TEXT_WIDTH); float leftMargin = translateLoad/2; float textOpactity = Math.max(0, ws * 10f - 9f); textPaint.setAlpha((int)(textOpactity * 255)); spinnerRect.set(iconBounds.left + dpToPx(4) - translateLoad/2, iconBounds.top + dpToPx(4), iconBounds.right - dpToPx(4) - translateLoad/2, iconBounds.bottom - dpToPx(4)); int circleOffset = (int)(TOAST_HEIGHT*2*(Math.sqrt(2)-1)/3); int th = TOAST_HEIGHT; int pd = (TOAST_HEIGHT - IMAGE_WIDTH)/2; int iconoffset = (int)(IMAGE_WIDTH*2*(Math.sqrt(2)-1)/3); int iw = IMAGE_WIDTH; float totalWidth = leftMargin * 2 + th + ws*(IMAGE_WIDTH + MAX_TEXT_WIDTH) - translateLoad; toastPath.reset(); toastPath.moveTo(leftMargin + th / 2, 0); toastPath.rLineTo(ws*(IMAGE_WIDTH + MAX_TEXT_WIDTH), 0); toastPath.rCubicTo(circleOffset, 0, th / 2, th / 2 - circleOffset, th / 2, th / 2); toastPath.rLineTo(-pd, 0); toastPath.rCubicTo(0, -iconoffset, -iw / 2 + iconoffset, -iw / 2, -iw / 2, -iw / 2); toastPath.rCubicTo(-iconoffset, 0, -iw / 2, iw / 2 - iconoffset, -iw / 2, iw / 2); toastPath.rCubicTo(0, iconoffset, iw / 2 - iconoffset, iw / 2, iw / 2, iw / 2); toastPath.rCubicTo(iconoffset, 0, iw / 2, -iw / 2 + iconoffset, iw / 2, -iw / 2); toastPath.rLineTo(pd, 0); toastPath.rCubicTo(0, circleOffset, circleOffset - th / 2, th / 2, -th / 2, th / 2); toastPath.rLineTo(ws*(-IMAGE_WIDTH - MAX_TEXT_WIDTH), 0); toastPath.rCubicTo(-circleOffset, 0, -th / 2, -th / 2 + circleOffset, -th / 2, -th / 2); toastPath.rCubicTo(0, -circleOffset, -circleOffset + th / 2, -th / 2, th / 2, -th / 2); c.drawCircle(spinnerRect.centerX(), spinnerRect.centerY(), iconBounds.height() / 1.9f, backPaint); c.drawPath(toastPath, backPaint); int thb = th - borderOffset*2; toastPath.reset(); toastPath.moveTo(leftMargin + th / 2, borderOffset); toastPath.rLineTo(ws*(IMAGE_WIDTH + MAX_TEXT_WIDTH), 0); toastPath.rCubicTo(circleOffset, 0, thb / 2, thb / 2 - circleOffset, thb / 2, thb / 2); toastPath.rCubicTo(0, circleOffset, circleOffset - thb / 2, thb / 2, -thb / 2, thb / 2); toastPath.rLineTo(ws*(-IMAGE_WIDTH - MAX_TEXT_WIDTH), 0); toastPath.rCubicTo(-circleOffset, 0, -thb / 2, -thb / 2 + circleOffset, -thb / 2, -thb / 2); toastPath.rCubicTo(0, -circleOffset, -circleOffset + thb / 2, -thb / 2, thb / 2, -thb / 2); c.drawPath(toastPath, borderPaint); toastPath.reset(); float prog = va.getAnimatedFraction() * 6.0f; float progrot = prog % 2.0f; float proglength = easeinterpol.getInterpolation(prog % 3f / 3f)*3f - .75f; if(proglength > .75f){ proglength = .75f - (prog % 3f - 1.5f); progrot += (prog % 3f - 1.5f)/1.5f * 2f; } if(mText.length() == 0){ ws = Math.max(1f - WIDTH_SCALE, 0f); } c.save(); c.translate((totalWidth - TOAST_HEIGHT)/2, 0); super.onDraw(c); c.restore(); if(WIDTH_SCALE > 1f){ Drawable icon = (success) ? completeicon : failedicon; float circleProg = WIDTH_SCALE - 1f; textPaint.setAlpha((int)(128 * circleProg + 127)); int paddingicon = (int)((1f-(.25f + (.75f * circleProg))) * TOAST_HEIGHT/2); int completeoff = (int)((1f-circleProg) * TOAST_HEIGHT/8); icon.setBounds((int)spinnerRect.left + paddingicon, (int)spinnerRect.top + paddingicon + completeoff, (int)spinnerRect.right - paddingicon, (int)spinnerRect.bottom - paddingicon + completeoff); c.drawCircle(leftMargin + TOAST_HEIGHT/2, (1f-circleProg) * TOAST_HEIGHT/8 + TOAST_HEIGHT/2, (.25f + (.75f * circleProg)) * TOAST_HEIGHT/2, (success) ? successPaint : errorPaint); c.save(); c.rotate(90*(1f-circleProg), leftMargin + TOAST_HEIGHT/2, TOAST_HEIGHT/2); icon.draw(c); c.restore(); prevUpdate = 0; return; } int yPos = (int) ((th / 2) - ((textPaint.descent() + textPaint.ascent()) / 2)) ; if(outOfBounds){ float shift = 0; if(prevUpdate == 0){ prevUpdate = System.currentTimeMillis(); }else{ shift = ((float)(System.currentTimeMillis() - prevUpdate) / 16f) * MARQUE_STEP; if(shift - MAX_TEXT_WIDTH > mTextBounds.width()){ prevUpdate = 0; } } c.clipRect(th / 2, 0, th/2 + MAX_TEXT_WIDTH, TOAST_HEIGHT); if (!mLtr || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && getTextDirection() == TEXT_DIRECTION_ANY_RTL)) { c.drawText(mText, th / 2 - mTextBounds.width() + shift, yPos, textPaint); }else{ c.drawText(mText, th / 2 - shift + MAX_TEXT_WIDTH, yPos, textPaint); } }else{ c.drawText(mText, 0, mText.length(), th / 2 + (MAX_TEXT_WIDTH - mTextBounds.width()) / 2, yPos, textPaint); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec)); } /** * Determines the width of this view * @param measureSpec A measureSpec packed into an int * @return The width of the view, honoring constraints from measureSpec */ private int measureWidth(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { // We were told how big to be result = specSize; } else { // Measure the text result = IMAGE_WIDTH + MAX_TEXT_WIDTH + TOAST_HEIGHT; if (specMode == MeasureSpec.AT_MOST) { // Respect AT_MOST value if that was what is called for by measureSpec result = Math.min(result, specSize); } } return result; } /** * Determines the height of this view * @param measureSpec A measureSpec packed into an int * @return The height of the view, honoring constraints from measureSpec */ private int measureHeight(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { // We were told how big to be result = specSize; } else { // Measure the text (beware: ascent is a negative number) result = TOAST_HEIGHT; if (specMode == MeasureSpec.AT_MOST) { // Respect AT_MOST value if that was what is called for by measureSpec result = Math.min(result, specSize); } } return result; } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); Log.d(getClass().getSimpleName(), "detached"); cleanup(); } public void cleanup(){ if(cmp != null){ cmp.removeAllUpdateListeners(); cmp.removeAllListeners(); } if(va != null){ va.removeAllUpdateListeners(); va.removeAllListeners(); } spinnerDrawable.stop(); } }
/** * Copyright (C) 2008 Google Inc. * * 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.elasticsearch.common.inject.multibindings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import org.elasticsearch.common.inject.*; import org.elasticsearch.common.inject.binder.LinkedBindingBuilder; import org.elasticsearch.common.inject.internal.Errors; import org.elasticsearch.common.inject.spi.Dependency; import org.elasticsearch.common.inject.spi.HasDependencies; import org.elasticsearch.common.inject.spi.Message; import org.elasticsearch.common.inject.util.Types; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; /** * An API to bind multiple values separately, only to later inject them as a * complete collection. Multibinder is intended for use in your application's * module: * <pre><code> * public class SnacksModule extends AbstractModule { * protected void configure() { * Multibinder&lt;Snack&gt; multibinder * = Multibinder.newSetBinder(binder(), Snack.class); * multibinder.addBinding().toInstance(new Twix()); * multibinder.addBinding().toProvider(SnickersProvider.class); * multibinder.addBinding().to(Skittles.class); * } * }</code></pre> * <p/> * <p>With this binding, a {@link Set}{@code <Snack>} can now be injected: * <pre><code> * class SnackMachine { * {@literal @}Inject * public SnackMachine(Set&lt;Snack&gt; snacks) { ... } * }</code></pre> * <p/> * <p>Create multibindings from different modules is supported. For example, it * is okay to have both {@code CandyModule} and {@code ChipsModule} to both * create their own {@code Multibinder<Snack>}, and to each contribute bindings * to the set of snacks. When that set is injected, it will contain elements * from both modules. * <p/> * <p>Elements are resolved at set injection time. If an element is bound to a * provider, that provider's get method will be called each time the set is * injected (unless the binding is also scoped). * <p/> * <p>Annotations are be used to create different sets of the same element * type. Each distinct annotation gets its own independent collection of * elements. * <p/> * <p><strong>Elements must be distinct.</strong> If multiple bound elements * have the same value, set injection will fail. * <p/> * <p><strong>Elements must be non-null.</strong> If any set element is null, * set injection will fail. * * @author jessewilson@google.com (Jesse Wilson) */ public abstract class Multibinder<T> { private Multibinder() { } /** * Returns a new multibinder that collects instances of {@code type} in a {@link Set} that is * itself bound with no binding annotation. */ public static <T> Multibinder<T> newSetBinder(Binder binder, TypeLiteral<T> type) { binder = binder.skipSources(RealMultibinder.class, Multibinder.class); RealMultibinder<T> result = new RealMultibinder<>(binder, type, "", Key.get(Multibinder.<T>setOf(type))); binder.install(result); return result; } /** * Returns a new multibinder that collects instances of {@code type} in a {@link Set} that is * itself bound with no binding annotation. */ public static <T> Multibinder<T> newSetBinder(Binder binder, Class<T> type) { return newSetBinder(binder, TypeLiteral.get(type)); } /** * Returns a new multibinder that collects instances of {@code type} in a {@link Set} that is * itself bound with {@code annotation}. */ public static <T> Multibinder<T> newSetBinder( Binder binder, TypeLiteral<T> type, Annotation annotation) { binder = binder.skipSources(RealMultibinder.class, Multibinder.class); RealMultibinder<T> result = new RealMultibinder<>(binder, type, annotation.toString(), Key.get(Multibinder.<T>setOf(type), annotation)); binder.install(result); return result; } /** * Returns a new multibinder that collects instances of {@code type} in a {@link Set} that is * itself bound with {@code annotation}. */ public static <T> Multibinder<T> newSetBinder( Binder binder, Class<T> type, Annotation annotation) { return newSetBinder(binder, TypeLiteral.get(type), annotation); } /** * Returns a new multibinder that collects instances of {@code type} in a {@link Set} that is * itself bound with {@code annotationType}. */ public static <T> Multibinder<T> newSetBinder(Binder binder, TypeLiteral<T> type, Class<? extends Annotation> annotationType) { binder = binder.skipSources(RealMultibinder.class, Multibinder.class); RealMultibinder<T> result = new RealMultibinder<>(binder, type, "@" + annotationType.getName(), Key.get(Multibinder.<T>setOf(type), annotationType)); binder.install(result); return result; } /** * Returns a new multibinder that collects instances of {@code type} in a {@link Set} that is * itself bound with {@code annotationType}. */ public static <T> Multibinder<T> newSetBinder(Binder binder, Class<T> type, Class<? extends Annotation> annotationType) { return newSetBinder(binder, TypeLiteral.get(type), annotationType); } @SuppressWarnings("unchecked") // wrapping a T in a Set safely returns a Set<T> private static <T> TypeLiteral<Set<T>> setOf(TypeLiteral<T> elementType) { Type type = Types.setOf(elementType.getType()); return (TypeLiteral<Set<T>>) TypeLiteral.get(type); } /** * Returns a binding builder used to add a new element in the set. Each * bound element must have a distinct value. Bound providers will be * evaluated each time the set is injected. * <p/> * <p>It is an error to call this method without also calling one of the * {@code to} methods on the returned binding builder. * <p/> * <p>Scoping elements independently is supported. Use the {@code in} method * to specify a binding scope. */ public abstract LinkedBindingBuilder<T> addBinding(); /** * The actual multibinder plays several roles: * <p/> * <p>As a Multibinder, it acts as a factory for LinkedBindingBuilders for * each of the set's elements. Each binding is given an annotation that * identifies it as a part of this set. * <p/> * <p>As a Module, it installs the binding to the set itself. As a module, * this implements equals() and hashcode() in order to trick Guice into * executing its configure() method only once. That makes it so that * multiple multibinders can be created for the same target collection, but * only one is bound. Since the list of bindings is retrieved from the * injector itself (and not the multibinder), each multibinder has access to * all contributions from all multibinders. * <p/> * <p>As a Provider, this constructs the set instances. * <p/> * <p>We use a subclass to hide 'implements Module, Provider' from the public * API. */ static final class RealMultibinder<T> extends Multibinder<T> implements Module, Provider<Set<T>>, HasDependencies { private final TypeLiteral<T> elementType; private final String setName; private final Key<Set<T>> setKey; /* the target injector's binder. non-null until initialization, null afterwards */ private Binder binder; /* a provider for each element in the set. null until initialization, non-null afterwards */ private List<Provider<T>> providers; private Set<Dependency<?>> dependencies; private RealMultibinder(Binder binder, TypeLiteral<T> elementType, String setName, Key<Set<T>> setKey) { this.binder = checkNotNull(binder, "binder"); this.elementType = checkNotNull(elementType, "elementType"); this.setName = checkNotNull(setName, "setName"); this.setKey = checkNotNull(setKey, "setKey"); } @Override @SuppressWarnings("unchecked") public void configure(Binder binder) { checkConfiguration(!isInitialized(), "Multibinder was already initialized"); binder.bind(setKey).toProvider(this); } @Override public LinkedBindingBuilder<T> addBinding() { checkConfiguration(!isInitialized(), "Multibinder was already initialized"); return binder.bind(Key.get(elementType, new RealElement(setName))); } /** * Invoked by Guice at Injector-creation time to prepare providers for each * element in this set. At this time the set's size is known, but its * contents are only evaluated when get() is invoked. */ @Inject void initialize(Injector injector) { providers = Lists.newArrayList(); List<Dependency<?>> dependencies = Lists.newArrayList(); for (Binding<?> entry : injector.findBindingsByType(elementType)) { if (keyMatches(entry.getKey())) { @SuppressWarnings("unchecked") // protected by findBindingsByType() Binding<T> binding = (Binding<T>) entry; providers.add(binding.getProvider()); dependencies.add(Dependency.get(binding.getKey())); } } this.dependencies = ImmutableSet.copyOf(dependencies); this.binder = null; } private boolean keyMatches(Key<?> key) { return key.getTypeLiteral().equals(elementType) && key.getAnnotation() instanceof Element && ((Element) key.getAnnotation()).setName().equals(setName); } private boolean isInitialized() { return binder == null; } @Override public Set<T> get() { checkConfiguration(isInitialized(), "Multibinder is not initialized"); Set<T> result = new LinkedHashSet<>(); for (Provider<T> provider : providers) { final T newValue = provider.get(); checkConfiguration(newValue != null, "Set injection failed due to null element"); checkConfiguration(result.add(newValue), "Set injection failed due to duplicated element \"%s\"", newValue); } return Collections.unmodifiableSet(result); } String getSetName() { return setName; } Key<Set<T>> getSetKey() { return setKey; } @Override public Set<Dependency<?>> getDependencies() { return dependencies; } @Override public boolean equals(Object o) { return o instanceof RealMultibinder && ((RealMultibinder<?>) o).setKey.equals(setKey); } @Override public int hashCode() { return setKey.hashCode(); } @Override public String toString() { return new StringBuilder() .append(setName) .append(setName.length() > 0 ? " " : "") .append("Multibinder<") .append(elementType) .append(">") .toString(); } } static void checkConfiguration(boolean condition, String format, Object... args) { if (condition) { return; } throw new ConfigurationException(ImmutableSet.of(new Message(Errors.format(format, args)))); } static <T> T checkNotNull(T reference, String name) { if (reference != null) { return reference; } NullPointerException npe = new NullPointerException(name); throw new ConfigurationException(ImmutableSet.of( new Message(ImmutableList.of(), npe.toString(), npe))); } }
package edu.isi.wubble.jgn.superroom; import static edu.isi.wubble.jgn.message.InvokeMessage.createMsg; import static edu.isi.wubble.jgn.rpg.RPGPhysics.PICKER; import static edu.isi.wubble.jgn.rpg.RPGPhysics.SHOOTER; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.URL; import java.util.Collection; import java.util.HashMap; import java.util.concurrent.Callable; import java.util.logging.Level; import java.util.logging.Logger; import java.util.prefs.Preferences; import com.captiveimagination.jgn.JGN; import com.captiveimagination.jgn.clientserver.JGNConnection; import com.captiveimagination.jgn.clientserver.JGNConnectionListener; import com.captiveimagination.jgn.clientserver.JGNServer; import com.captiveimagination.jgn.event.MessageListener; import com.captiveimagination.jgn.message.Message; import com.captiveimagination.jgn.synchronization.message.Synchronize3DMessage; import com.jme.math.Quaternion; import com.jme.math.Vector3f; import com.jme.system.GameSettings; import com.jme.system.PreferencesGameSettings; import com.jme.util.GameTaskQueueManager; import com.jme.util.resource.ResourceLocatorTool; import com.jme.util.resource.SimpleResourceLocator; import com.jmex.game.StandardGame; import com.jmex.game.state.GameStateManager; import edu.isi.wubble.jgn.db.DatabaseManager; import edu.isi.wubble.jgn.message.GameStatusMessage; import edu.isi.wubble.jgn.message.HiddenUpdateMessage; import edu.isi.wubble.jgn.message.InvokeMessage; import edu.isi.wubble.jgn.message.WorldUpdateMessage; public class Server implements JGNConnectionListener,MessageListener { public static StandardGame.GameType SERVER_TYPE; private static Server _server; protected HashMap<Short,JGNConnection> _openConnections; protected HashMap<Short,Integer> _playerToGame; protected long _gameStartTime; protected JGNServer _jgnServer; private StandardGame _game; private SuperRoomState _room; private Object _lock; public static Server inst() { if (_server == null) { _server = new Server(); } return _server; } private Server() { _openConnections = new HashMap<Short,JGNConnection>(); _lock = new Object(); try { URL modelURL = ClassLoader.getSystemResource("media/models/"); URL textureURL = ClassLoader.getSystemResource("media/textures/"); ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, new SimpleResourceLocator(textureURL)); ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_MODEL, new SimpleResourceLocator(modelURL)); } catch (Exception e) { e.printStackTrace(); } JGN.register(WorldUpdateMessage.class); JGN.register(HiddenUpdateMessage.class); JGN.register(InvokeMessage.class); JGN.register(GameStatusMessage.class); JGN.register(Vector3f.class); JGN.register(Quaternion.class); } public void setup(int numGames) throws Exception { GameSettings gs = new PreferencesGameSettings(Preferences.userRoot().node("Wubble Server")); gs.setWidth(1024); gs.setHeight(768); gs.setFramerate(70); GameTaskQueueManager.getManager(); _game = new StandardGame("Wubble RPG Server", SERVER_TYPE, gs); _game.start(); _room = createState("Room0"); _room.setActive(true); GameStateManager.getInstance().attachChild(_room); // // Initialize networking // InetSocketAddress serverReliable = new InetSocketAddress(InetAddress.getLocalHost(), 9100); // InetSocketAddress serverFast = new InetSocketAddress(InetAddress.getLocalHost(), 9200); // _jgnServer = new JGNServer(serverReliable, serverFast); // // JGN.createThread(_jgnServer).start(); // // _jgnServer.getFastServer().setConnectionTimeout(60000); // _jgnServer.getReliableServer().setConnectionTimeout(60000); // // _jgnServer.addMessageListener(this); // _jgnServer.addClientConnectionListener(this); // // InvokeMessage.SetServer(_jgnServer); } private SuperRoomState createState(final String name) { Callable<SuperRoomState> callable = new Callable<SuperRoomState>() { public SuperRoomState call() throws Exception { SuperRoomState state = new SuperRoomState(); return state; } }; try { return GameTaskQueueManager.getManager().update(callable).get(); } catch (Exception e) { e.printStackTrace(); } return null; } public void connected(JGNConnection connection) { // if (_openConnections.size() == 0) { // DatabaseManager.inst().connect(); // } // // short playerId = connection.getPlayerId(); // System.out.println("client: " + playerId + " connected"); // _openConnections.put(playerId, connection); // // // send the freshly connected player a list of available // // games so that he can choose the one he would like to // // connect to. // GameStatusMessage msg = generateGameMessage(); // _server.sendTo(msg, playerId); } public void disconnected(JGNConnection connection) { // short playerId = connection.getPlayerId(); // System.out.println("client: " + playerId + " disconnected"); // // _openConnections.remove(connection.getPlayerId()); // Integer gameId = _playerToGame.remove(playerId); // if (gameId == null) // return; // // SuperPhysics game = _rpgPhysics[gameId]; // game.removeUser(playerId); } public void messageCertified(Message message) { } public void messageFailed(Message message) { } public void messageSent(Message message) { } /** * dispatch the message based on the sending player's id * this should automatically route players messages to the * correct instance of the game. */ public void messageReceived(Message message) { // short playerId = message.getPlayerId(); // Integer gameIndex = _playerToGame.get(playerId); // if (gameIndex == null) { // unknownMsgReceived(message); // return; // } // // SuperPhysics state = _rpgPhysics[gameIndex]; // if ("InvokeMessage".equals(message.getClass().getSimpleName())) { // InvokeMessage invoke = (InvokeMessage) message; // invoke.callMethod(state); // } else { // System.out.println("recieved: " + message); // } } private void unknownMsgReceived(Message message) { // if ("InvokeMessage".equals(message.getClass().getSimpleName())) { // InvokeMessage msg = (InvokeMessage) message; // msg.callMethod(this); // } else { // System.out.println("uknown received: " + message); // } } // public void refresh(Short id) { // _jgnServer.sendTo(generateGameMessage(), id); // } /** * called by the client when they decide to join a game. * @param id * @param gameId * @param role */ public void joinGame(Short id, String userName, String password, Integer gameId, Integer role) { // synchronized (_lock) { // SuperPhysics rpg = _rpgPhysics[gameId]; // if (rpg == null) // return; // // if (rpg.getPlayerName(role) != null) { // // send message to user telling them sorry. // InvokeMessage msg = createMsg("failure", new Object[] { "Game slot is already taken." }); // msg.sendTo(id); // return; // } // // if (!rpg.isActive()) // rpg.startSession(); // // if (rpg.login(id, userName, password, role)) { // // send success (this will remap the MessageListener to the correct game state) // _playerToGame.put(id, gameId); // // InvokeMessage msg = createMsg("success", null); // msg.sendTo(id); // } else { // // send message to user telling them incorrect password // InvokeMessage msg = createMsg("failure", new Object[] { "Incorrect user name or password." }); // msg.sendTo(id); // } // } } public void quit() { try { _jgnServer.close(); } catch (Exception e) { e.printStackTrace(); } } // public void sendToAll(Collection<Short> allIds, Synchronize3DMessage m) { // for (Short id : allIds) { // _server.sendTo(m, id); // } // } // // public void sendTo(Short id, Synchronize3DMessage m) { // _server.sendTo(m, id); // } public static void main(String[] args) { if (args.length != 1) { System.out.println("usage: please indicate <graphical/headless>"); return; } System.out.println("Received: " + args[0]); if (args[0].equals("graphical")) { Server.SERVER_TYPE = StandardGame.GameType.GRAPHICAL; } else { Server.SERVER_TYPE = StandardGame.GameType.HEADLESS; } Logger.getLogger("").setLevel(Level.WARNING); Server.inst(); try { Server.inst().setup(1); } catch (Exception e) { e.printStackTrace(); } } }
/** Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file 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 asteroidtracker; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.nio.charset.Charset; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.amazon.speech.slu.Intent; import com.amazon.speech.slu.Slot; import com.amazon.speech.speechlet.IntentRequest; import com.amazon.speech.speechlet.LaunchRequest; import com.amazon.speech.speechlet.Session; import com.amazon.speech.speechlet.SessionEndedRequest; import com.amazon.speech.speechlet.SessionStartedRequest; import com.amazon.speech.speechlet.Speechlet; import com.amazon.speech.speechlet.SpeechletException; import com.amazon.speech.speechlet.SpeechletResponse; import com.amazon.speech.ui.OutputSpeech; import com.amazon.speech.ui.PlainTextOutputSpeech; import com.amazon.speech.ui.SsmlOutputSpeech; import com.amazon.speech.ui.Reprompt; import com.amazon.speech.ui.SimpleCard; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.text.DecimalFormat; import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class AsteroidTrackerSpeechlet implements Speechlet { private static final Logger log = LoggerFactory.getLogger(AsteroidTrackerSpeechlet.class); /** * URL prefix to download history content from Wikipedia. */ private static final String URL_PREFIX = "https://api.nasa.gov/neo/rest/v1/feed?"; private static final String URL_START_DATE = "start_date="; private static final String URL_END_DATE = "&end_date="; private static final String URL_POSTFIX = "&detailed=false&api_key=DEMO_KEY"; /** * Constant defining number of events to be read at one time. */ private static final int PAGINATION_SIZE = 1; /** * Length of the delimiter between individual events. */ private static final int DELIMITER_SIZE = 2; /** * Constant defining session attribute key for the event index. */ private static final String SESSION_INDEX = "index"; /** * Constant defining session attribute key for the event text key for date of events. */ private static final String SESSION_TEXT = "text"; /** * Constant defining session attribute key for the intent slot key for the date of events. */ private static final String SLOT_DAY = "day"; /** * Size of events from Wikipedia response. */ private static final int SIZE_OF_EVENTS = 10; /** * Array of month names. */ private static final String[] MONTH_NAMES = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; private static final String INFORMATION_TEXT = "With Asteroid Tracker, you can get near earth object events for any day of the year." + " For example, you could say give me events for today, or give events for July fourth, 2015." + " So, which day do you want?"; @Override public void onSessionStarted(final SessionStartedRequest request, final Session session) throws SpeechletException { log.info("onSessionStarted requestId={}, sessionId={}", request.getRequestId(), session.getSessionId()); // any initialization logic goes here } @Override public SpeechletResponse onLaunch(final LaunchRequest request, final Session session) throws SpeechletException { log.info("onLaunch requestId={}, sessionId={}", request.getRequestId(), session.getSessionId()); return getWelcomeResponse(); } @Override public SpeechletResponse onIntent(final IntentRequest request, final Session session) throws SpeechletException { log.info("onIntent requestId={}, sessionId={}", request.getRequestId(), session.getSessionId()); Intent intent = request.getIntent(); String intentName = intent.getName(); if ("GetFirstEventIntent".equals(intentName)) { return handleFirstEventRequest(intent, session); } else if ("AMAZON.YesIntent".equals(intentName)) { return handleNextEventRequest(session); } else if ("AMAZON.HelpIntent".equals(intentName)) { return newAskResponse(INFORMATION_TEXT, false, INFORMATION_TEXT, false); } else if ("AMAZON.StopIntent".equals(intentName)) { PlainTextOutputSpeech outputSpeech = new PlainTextOutputSpeech(); outputSpeech.setText("Goodbye"); return SpeechletResponse.newTellResponse(outputSpeech); } else if ("AMAZON.CancelIntent".equals(intentName)) { PlainTextOutputSpeech outputSpeech = new PlainTextOutputSpeech(); outputSpeech.setText("Goodbye"); return SpeechletResponse.newTellResponse(outputSpeech); } else { throw new SpeechletException("Invalid Intent"); } } @Override public void onSessionEnded(final SessionEndedRequest request, final Session session) throws SpeechletException { log.info("onSessionEnded requestId={}, sessionId={}", request.getRequestId(), session.getSessionId()); // any session cleanup logic would go here } /** * Function to handle the onLaunch skill behavior. * * @return SpeechletResponse object with voice/card response to return to the user */ private SpeechletResponse getWelcomeResponse() { String speechOutput = "Welcome to Asteroid Tracker. What day do you want events for?"; return newAskResponse(speechOutput, false, INFORMATION_TEXT, false); } /** * Function to accept an intent containing a Day slot (date object) and return the Calendar * representation of that slot value. If the user provides a date, then use that, otherwise use * today. The date is in server time, not in the user's time zone. So "today" for the user may * actually be tomorrow. * * @param intent * the intent object containing the day slot * @return the Calendar representation of that date */ private Calendar getCalendar(Intent intent) { Slot daySlot = intent.getSlot(SLOT_DAY); Date date; Calendar calendar = Calendar.getInstance(); if (daySlot != null && daySlot.getValue() != null) { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-d"); try { date = dateFormat.parse(daySlot.getValue()); } catch (ParseException e) { return null; } calendar.setTime(date); return calendar; } else { return null; } } private String buildSpeechOutputMarkup(String output) { return "<speak>" + output + "</speak>"; } /** * Prepares the speech to reply to the user. Obtain events from NeoWs for the date specified * by the user (or for today's date, if no date is specified), and return those events in both * speech and SimpleCard format. * * @param intent * the intent object which contains the date slot * @param session * the session object * @return SpeechletResponse object with voice/card response to return to the user */ private SpeechletResponse handleFirstEventRequest(Intent intent, Session session) { Calendar calendar = getCalendar(intent); String speechOutput; if(calendar == null) { speechOutput = "Invalid date, please try again. For example, you could say give me events for today, or give events for July fourth, 2015."; // Create the plain text output SsmlOutputSpeech outputSpeech = new SsmlOutputSpeech(); outputSpeech.setSsml(buildSpeechOutputMarkup(speechOutput)); return SpeechletResponse.newTellResponse(outputSpeech); } Date datetime = calendar.getTime(); String month = MONTH_NAMES[calendar.get(Calendar.MONTH)]; String date = Integer.toString(calendar.get(Calendar.DATE)); String year = Integer.toString(calendar.get(Calendar.YEAR)); String speechPrefixContent = "<p>For " + month + " " + date + ", " + year + "</p> "; String cardPrefixContent = "For " + month + " " + date + ", "+ year + ", "; String cardTitle = "Asteroids on " + month + " " + date+ ", " + year + ", "; ArrayList<String> events = getAsteroidInfo(new SimpleDateFormat("yyyy-MM-dd").format(datetime)); if (events.isEmpty()) { speechOutput = "There is a problem connecting to the NASA A.P.I at this time." + " Please try again later."; // Create the plain text output SsmlOutputSpeech outputSpeech = new SsmlOutputSpeech(); outputSpeech.setSsml(buildSpeechOutputMarkup(speechOutput)); return SpeechletResponse.newTellResponse(outputSpeech); } else { StringBuilder speechOutputBuilder = new StringBuilder(); speechOutputBuilder.append(speechPrefixContent); StringBuilder cardOutputBuilder = new StringBuilder(); cardOutputBuilder.append(cardPrefixContent); for (int i = 0; i < PAGINATION_SIZE; i++) { if (events.size() > i) { speechOutputBuilder.append("<p>"); speechOutputBuilder.append(events.get(i)); speechOutputBuilder.append("</p> "); cardOutputBuilder.append(events.get(i)); cardOutputBuilder.append("\n"); } } speechOutputBuilder.append(" Want more asteroid information?"); cardOutputBuilder.append(" Want more asteroid information?"); speechOutput = speechOutputBuilder.toString(); // Create the Simple card content. SimpleCard card = new SimpleCard(); card.setTitle(cardTitle); card.setContent(cardOutputBuilder.toString()); // After reading the first event, set the count to 1 and add the events // to the session attributes session.setAttribute(SESSION_INDEX, PAGINATION_SIZE); session.setAttribute(SESSION_TEXT, events); SpeechletResponse response = newAskResponse(buildSpeechOutputMarkup(speechOutput), true, INFORMATION_TEXT, false); response.setCard(card); return response; } } /** * Prepares the speech to reply to the user. Obtains the list of events as well as the current * index from the session attributes. After getting the next set of events, increment the index * and store it back in session attributes. This allows us to obtain new events without making * repeated network calls, by storing values (events, index) during the interaction with the * user. * * @param session * object containing session attributes with events list and index * @return SpeechletResponse object with voice/card response to return to the user */ private SpeechletResponse handleNextEventRequest(Session session) { String cardTitle = "More asteroid events on this day"; ArrayList<String> events = (ArrayList<String>) session.getAttribute(SESSION_TEXT); int index = (Integer) session.getAttribute(SESSION_INDEX); String speechOutput = ""; String cardOutput = ""; if (events == null) { speechOutput = INFORMATION_TEXT; } else if (index >= events.size()) { speechOutput = "There are no more events for this date. Try another date by saying, " + " get events for February third, 2014."; } else { StringBuilder speechOutputBuilder = new StringBuilder(); StringBuilder cardOutputBuilder = new StringBuilder(); for (int i = 0; i < PAGINATION_SIZE && index < events.size(); i++) { speechOutputBuilder.append("<p>"); speechOutputBuilder.append(events.get(index)); speechOutputBuilder.append("</p> "); cardOutputBuilder.append(events.get(index)); cardOutputBuilder.append(" "); index++; } if (index < events.size()) { speechOutputBuilder.append(" Want more events?"); cardOutputBuilder.append(" Want more events?"); } else { speechOutputBuilder.append(" There are no more events for today, would you like to get events for another day?"); cardOutputBuilder.append(" There are no more events for today, would you like to get events for another day?"); } session.setAttribute(SESSION_INDEX, index); speechOutput = speechOutputBuilder.toString(); cardOutput = cardOutputBuilder.toString(); } // Create the Simple card content. SimpleCard card = new SimpleCard(); card.setTitle(cardTitle); card.setContent(cardOutput.toString()); SpeechletResponse response = newAskResponse(buildSpeechOutputMarkup(speechOutput), true, INFORMATION_TEXT, false); response.setCard(card); return response; } /** * Download JSON-formatted list of events from NeoWs API, for a defined day/date, and return a * String array of the events, with each event representing an element in the array. * * @param month * the month to get events for, example: April * @param date * the date to get events for, example: 7 * @return String array of events for that date, 1 event per element of the array */ private ArrayList<String> getAsteroidInfo(String date) { InputStreamReader inputStream = null; BufferedReader bufferedReader = null; String text = ""; try { String line; URL url = new URL(URL_PREFIX + URL_START_DATE + date + URL_END_DATE + date + URL_POSTFIX); inputStream = new InputStreamReader(url.openStream(), Charset.forName("US-ASCII")); bufferedReader = new BufferedReader(inputStream); StringBuilder builder = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { builder.append(line); } text = builder.toString(); } catch (IOException e) { // reset text variable to a blank string text = ""; } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(bufferedReader); } return parseJson(text, date); } /** * Parse JSON-formatted list of events/births/deaths from Wikipedia, extract list of events and * split the events into a String array of individual events. Run Regex matchers to make the * list pretty by adding a comma after the year to add a pause, and by removing a unicode char. * * @param text * the JSON formatted list of events/births/deaths for a certain date * @return String array of events for that date, 1 event per element of the array */ private ArrayList<String> parseJson(String text, String date) { ArrayList<String> events = new ArrayList<String>(); if (text.isEmpty()) { return events; } JsonParser parser = new JsonParser(); JsonObject object = parser.parse(text).getAsJsonObject(); JsonArray asteroidArray = object.get("near_earth_objects").getAsJsonObject().get(date).getAsJsonArray(); for (int i = 0; i < object.get("element_count").getAsInt(); i++) { JsonObject thisAsteroid = asteroidArray.get(i).getAsJsonObject(); String asteroidName = thisAsteroid.get("name").getAsString(); float absoluteMagnitude = thisAsteroid.get("absolute_magnitude_h").getAsFloat(); JsonObject estimatedDiameterKilometers = thisAsteroid.get("estimated_diameter").getAsJsonObject().get("kilometers").getAsJsonObject(); float minimumDiameter = estimatedDiameterKilometers.get("estimated_diameter_min").getAsFloat(); float maximumDiameter = estimatedDiameterKilometers.get("estimated_diameter_max").getAsFloat(); boolean isDangerousObject = thisAsteroid.get("is_potentially_hazardous_asteroid").getAsString() == "false"; JsonObject closeApproachData= thisAsteroid.get("close_approach_data").getAsJsonArray().get(0).getAsJsonObject(); float speed = closeApproachData.get("relative_velocity").getAsJsonObject().get("kilometers_per_hour").getAsFloat(); Number missDistance = closeApproachData.get("miss_distance").getAsJsonObject().get("kilometers").getAsNumber(); String orbitingBody = closeApproachData.get("orbiting_body").getAsString(); DecimalFormat df = new DecimalFormat("#.##"); String asteroidIdText = "Asteroid " + i + ", name is " + asteroidName + ","; String magnitudeText = "The absolute magnitude is " + absoluteMagnitude; String sizeText = ", the estimated diameter is from " + df.format(minimumDiameter) + " to " + df.format(maximumDiameter) + " kilometers,"; String dangerousnessText; if (isDangerousObject) { dangerousnessText = "This object is dangerous!"; } else { dangerousnessText = "This object is not dangerous,"; } String speedText = "It is traveling at " + df.format(speed) + " kilometers per hour"; String distanceText = " at a distance of " + missDistance + " kilometers"; String orbitingBodyText = " and is orbiting " + orbitingBody; String eventText = asteroidIdText + magnitudeText + sizeText + dangerousnessText + speedText + distanceText + orbitingBodyText; events.add(eventText); } return events; } /** * Wrapper for creating the Ask response from the input strings. * * @param stringOutput * the output to be spoken * @param isOutputSsml * whether the output text is of type SSML * @param repromptText * the reprompt for if the user doesn't reply or is misunderstood. * @param isRepromptSsml * whether the reprompt text is of type SSML * @return SpeechletResponse the speechlet response */ private SpeechletResponse newAskResponse(String stringOutput, boolean isOutputSsml, String repromptText, boolean isRepromptSsml) { OutputSpeech outputSpeech, repromptOutputSpeech; if (isOutputSsml) { outputSpeech = new SsmlOutputSpeech(); ((SsmlOutputSpeech) outputSpeech).setSsml(stringOutput); } else { outputSpeech = new PlainTextOutputSpeech(); ((PlainTextOutputSpeech) outputSpeech).setText(stringOutput); } if (isRepromptSsml) { repromptOutputSpeech = new SsmlOutputSpeech(); ((SsmlOutputSpeech) repromptOutputSpeech).setSsml(repromptText); } else { repromptOutputSpeech = new PlainTextOutputSpeech(); ((PlainTextOutputSpeech) repromptOutputSpeech).setText(repromptText); } Reprompt reprompt = new Reprompt(); reprompt.setOutputSpeech(repromptOutputSpeech); return SpeechletResponse.newAskResponse(outputSpeech, reprompt); } }
/* * Copyright 2000-2014 JetBrains s.r.o. * * 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.jetbrains.python.inspections; import com.intellij.codeInsight.FileModificationService; import com.intellij.codeInsight.controlflow.ControlFlowUtil; import com.intellij.codeInsight.controlflow.Instruction; import com.intellij.codeInspection.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.Function; import com.jetbrains.python.PyBundle; import com.jetbrains.python.PyNames; import com.jetbrains.python.codeInsight.controlflow.ControlFlowCache; import com.jetbrains.python.codeInsight.controlflow.ReadWriteInstruction; import com.jetbrains.python.codeInsight.controlflow.ScopeOwner; import com.jetbrains.python.codeInsight.dataflow.scope.Scope; import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil; import com.jetbrains.python.inspections.quickfix.AddFieldQuickFix; import com.jetbrains.python.inspections.quickfix.PyRemoveParameterQuickFix; import com.jetbrains.python.inspections.quickfix.PyRemoveStatementQuickFix; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.impl.PyAugAssignmentStatementNavigator; import com.jetbrains.python.psi.impl.PyBuiltinCache; import com.jetbrains.python.psi.impl.PyForStatementNavigator; import com.jetbrains.python.psi.impl.PyImportStatementNavigator; import com.jetbrains.python.psi.resolve.PyResolveContext; import com.jetbrains.python.psi.search.PyOverridingMethodsSearch; import com.jetbrains.python.psi.search.PySuperMethodsSearch; import org.jetbrains.annotations.NotNull; import java.util.*; /** * @author oleg */ public class PyUnusedLocalInspectionVisitor extends PyInspectionVisitor { private final boolean myIgnoreTupleUnpacking; private final boolean myIgnoreLambdaParameters; private final boolean myIgnoreRangeIterationVariables; private final HashSet<PsiElement> myUnusedElements; private final HashSet<PsiElement> myUsedElements; public PyUnusedLocalInspectionVisitor(@NotNull ProblemsHolder holder, @NotNull LocalInspectionToolSession session, boolean ignoreTupleUnpacking, boolean ignoreLambdaParameters, boolean ignoreRangeIterationVariables) { super(holder, session); myIgnoreTupleUnpacking = ignoreTupleUnpacking; myIgnoreLambdaParameters = ignoreLambdaParameters; myIgnoreRangeIterationVariables = ignoreRangeIterationVariables; myUnusedElements = new HashSet<PsiElement>(); myUsedElements = new HashSet<PsiElement>(); } @Override public void visitPyFunction(final PyFunction node) { processScope(node); } @Override public void visitPyLambdaExpression(final PyLambdaExpression node) { processScope(node); } @Override public void visitPyClass(PyClass node) { processScope(node); } private void processScope(final ScopeOwner owner) { if (owner.getContainingFile() instanceof PyExpressionCodeFragment || callsLocals(owner)) { return; } if (!(owner instanceof PyClass)) { collectAllWrites(owner); } collectUsedReads(owner); } private void collectAllWrites(ScopeOwner owner) { final Instruction[] instructions = ControlFlowCache.getControlFlow(owner).getInstructions(); for (Instruction instruction : instructions) { final PsiElement element = instruction.getElement(); if (element instanceof PyFunction && owner instanceof PyFunction) { if (PyKnownDecoratorUtil.hasUnknownDecorator((PyFunction)element, myTypeEvalContext)) { continue; } if (!myUsedElements.contains(element)) { myUnusedElements.add(element); } } else if (instruction instanceof ReadWriteInstruction) { final ReadWriteInstruction readWriteInstruction = (ReadWriteInstruction)instruction; final ReadWriteInstruction.ACCESS access = readWriteInstruction.getAccess(); if (!access.isWriteAccess()) { continue; } final String name = readWriteInstruction.getName(); // Ignore empty, wildcards, global and nonlocal names final Scope scope = ControlFlowCache.getScope(owner); if (name == null || "_".equals(name) || scope.isGlobal(name) || scope.isNonlocal(name)) { continue; } // Ignore elements out of scope if (element == null || !PsiTreeUtil.isAncestor(owner, element, false)) { continue; } // Ignore arguments of import statement if (PyImportStatementNavigator.getImportStatementByElement(element) != null) { continue; } if (PyAugAssignmentStatementNavigator.getStatementByTarget(element) != null) { continue; } if (!myUsedElements.contains(element)) { myUnusedElements.add(element); } } } } private void collectUsedReads(final ScopeOwner owner) { final Instruction[] instructions = ControlFlowCache.getControlFlow(owner).getInstructions(); for (int i = 0; i < instructions.length; i++) { final Instruction instruction = instructions[i]; if (instruction instanceof ReadWriteInstruction) { final ReadWriteInstruction readWriteInstruction = (ReadWriteInstruction)instruction; final ReadWriteInstruction.ACCESS access = readWriteInstruction.getAccess(); if (!access.isReadAccess()) { continue; } final String name = readWriteInstruction.getName(); if (name == null) { continue; } final PsiElement element = instruction.getElement(); // Ignore elements out of scope if (element == null || !PsiTreeUtil.isAncestor(owner, element, false)) { continue; } final int startInstruction; if (access.isWriteAccess()) { final PyAugAssignmentStatement augAssignmentStatement = PyAugAssignmentStatementNavigator.getStatementByTarget(element); startInstruction = ControlFlowUtil.findInstructionNumberByElement(instructions, augAssignmentStatement); } else { startInstruction = i; } // Check if the element is declared out of scope, mark all out of scope write accesses as used if (element instanceof PyReferenceExpression) { final PyReferenceExpression ref = (PyReferenceExpression)element; final ScopeOwner declOwner = ScopeUtil.getDeclarationScopeOwner(ref, name); if (declOwner != null && declOwner != owner) { Collection<PsiElement> writeElements = ScopeUtil.getReadWriteElements(name, declOwner, false, true); for (PsiElement e : writeElements) { myUsedElements.add(e); myUnusedElements.remove(e); } } } ControlFlowUtil.iteratePrev(startInstruction, instructions, new Function<Instruction, ControlFlowUtil.Operation>() { public ControlFlowUtil.Operation fun(final Instruction inst) { final PsiElement element = inst.getElement(); // Mark function as used if (element instanceof PyFunction) { if (name.equals(((PyFunction)element).getName())){ myUsedElements.add(element); myUnusedElements.remove(element); return ControlFlowUtil.Operation.CONTINUE; } } // Mark write access as used else if (inst instanceof ReadWriteInstruction) { final ReadWriteInstruction rwInstruction = (ReadWriteInstruction)inst; if (rwInstruction.getAccess().isWriteAccess() && name.equals(rwInstruction.getName())) { // For elements in scope if (element != null && PsiTreeUtil.isAncestor(owner, element, false)) { myUsedElements.add(element); myUnusedElements.remove(element); } return ControlFlowUtil.Operation.CONTINUE; } } return ControlFlowUtil.Operation.NEXT; } }); } } } static class DontPerformException extends RuntimeException {} private static boolean callsLocals(final ScopeOwner owner) { try { owner.acceptChildren(new PyRecursiveElementVisitor(){ @Override public void visitPyCallExpression(final PyCallExpression node) { final PyExpression callee = node.getCallee(); if (callee != null && "locals".equals(callee.getName())){ throw new DontPerformException(); } node.acceptChildren(this); // look at call expr in arguments } @Override public void visitPyFunction(final PyFunction node) { // stop here } }); } catch (DontPerformException e) { return true; } return false; } void registerProblems() { final PyInspectionExtension[] filters = Extensions.getExtensions(PyInspectionExtension.EP_NAME); // Register problems final Set<PyFunction> functionsWithInheritors = new HashSet<PyFunction>(); final Map<PyFunction, Boolean> emptyFunctions = new HashMap<PyFunction, Boolean>(); for (PsiElement element : myUnusedElements) { boolean ignoreUnused = false; for (PyInspectionExtension filter : filters) { if (filter.ignoreUnused(element)) { ignoreUnused = true; } } if (ignoreUnused) continue; if (element instanceof PyFunction) { // Local function final PsiElement nameIdentifier = ((PyFunction)element).getNameIdentifier(); registerWarning(nameIdentifier == null ? element : nameIdentifier, PyBundle.message("INSP.unused.locals.local.function.isnot.used", ((PyFunction)element).getName()), new PyRemoveStatementQuickFix()); } else if (element instanceof PyClass) { // Local class final PyClass cls = (PyClass)element; final PsiElement name = cls.getNameIdentifier(); registerWarning(name != null ? name : element, PyBundle.message("INSP.unused.locals.local.class.isnot.used", cls.getName()), new PyRemoveStatementQuickFix()); } else { // Local variable or parameter String name = element.getText(); if (element instanceof PyNamedParameter || element.getParent() instanceof PyNamedParameter) { PyNamedParameter namedParameter = element instanceof PyNamedParameter ? (PyNamedParameter) element : (PyNamedParameter) element.getParent(); name = namedParameter.getName(); // When function is inside a class, first parameter may be either self or cls which is always 'used'. if (namedParameter.isSelf()) { continue; } if (myIgnoreLambdaParameters && PsiTreeUtil.getParentOfType(element, PyCallable.class) instanceof PyLambdaExpression) { continue; } boolean mayBeField = false; PyClass containingClass = null; PyParameterList paramList = PsiTreeUtil.getParentOfType(element, PyParameterList.class); if (paramList != null && paramList.getParent() instanceof PyFunction) { final PyFunction func = (PyFunction) paramList.getParent(); containingClass = func.getContainingClass(); if (PyNames.INIT.equals(func.getName()) && containingClass != null) { if (!namedParameter.isKeywordContainer() && !namedParameter.isPositionalContainer()) { mayBeField = true; } } else if (ignoreUnusedParameters(func, functionsWithInheritors)) { continue; } if (func.asMethod() != null) { Boolean isEmpty = emptyFunctions.get(func); if (isEmpty == null) { isEmpty = isEmptyFunction(func); emptyFunctions.put(func, isEmpty); } if (isEmpty && !mayBeField) { continue; } } } boolean canRemove = !(PsiTreeUtil.getPrevSiblingOfType(element, PyParameter.class) instanceof PySingleStarParameter) || PsiTreeUtil.getNextSiblingOfType(element, PyParameter.class) != null; final List<LocalQuickFix> fixes = new ArrayList<LocalQuickFix>(); if (mayBeField) { fixes.add(new AddFieldQuickFix(name, name, containingClass.getName(), false)); } if (canRemove) { fixes.add(new PyRemoveParameterQuickFix()); } registerWarning(element, PyBundle.message("INSP.unused.locals.parameter.isnot.used", name), fixes.toArray(new LocalQuickFix[fixes.size()])); } else { if (myIgnoreTupleUnpacking && isTupleUnpacking(element)) { continue; } final PyForStatement forStatement = PyForStatementNavigator.getPyForStatementByIterable(element); if (forStatement != null) { if (!myIgnoreRangeIterationVariables || !isRangeIteration(forStatement)) { registerProblem(element, PyBundle.message("INSP.unused.locals.local.variable.isnot.used", name), ProblemHighlightType.LIKE_UNUSED_SYMBOL, null, new ReplaceWithWildCard()); } } else { registerWarning(element, PyBundle.message("INSP.unused.locals.local.variable.isnot.used", name), new PyRemoveStatementQuickFix()); } } } } } private boolean isRangeIteration(PyForStatement forStatement) { final PyExpression source = forStatement.getForPart().getSource(); if (!(source instanceof PyCallExpression)) { return false; } PyCallExpression expr = (PyCallExpression) source; if (expr.isCalleeText("range", "xrange")) { final PyCallable callee = expr.resolveCalleeFunction(PyResolveContext.noImplicits().withTypeEvalContext(myTypeEvalContext)); if (callee != null && PyBuiltinCache.getInstance(forStatement).isBuiltin(callee)) { return true; } } return false; } private static boolean ignoreUnusedParameters(PyFunction func, Set<PyFunction> functionsWithInheritors) { if (functionsWithInheritors.contains(func)) { return true; } if (PySuperMethodsSearch.search(func).findFirst() != null || PyOverridingMethodsSearch.search(func, true).findFirst() != null) { functionsWithInheritors.add(func); return true; } return false; } private boolean isTupleUnpacking(PsiElement element) { if (!(element instanceof PyTargetExpression)) { return false; } // Handling of the star expressions PsiElement parent = element.getParent(); if (parent instanceof PyStarExpression){ element = parent; parent = element.getParent(); } if (parent instanceof PyTupleExpression) { // if all the items of the tuple are unused, we still highlight all of them; if some are unused, we ignore final PyTupleExpression tuple = (PyTupleExpression)parent; for (PyExpression expression : tuple.getElements()) { if (expression instanceof PyStarExpression){ if (!myUnusedElements.contains(((PyStarExpression)expression).getExpression())){ return true; } } else if (!myUnusedElements.contains(expression)) { return true; } } } return false; } private void registerWarning(@NotNull final PsiElement element, final String msg, LocalQuickFix... quickfixes) { registerProblem(element, msg, ProblemHighlightType.LIKE_UNUSED_SYMBOL, null, quickfixes); } private static class ReplaceWithWildCard implements LocalQuickFix { @NotNull public String getName() { return PyBundle.message("INSP.unused.locals.replace.with.wildcard"); } public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) { if (!FileModificationService.getInstance().preparePsiElementForWrite(descriptor.getPsiElement())) { return; } replace(descriptor.getPsiElement()); } private void replace(final PsiElement psiElement) { final PyFile pyFile = (PyFile) PyElementGenerator.getInstance(psiElement.getProject()).createDummyFile(LanguageLevel.getDefault(), "for _ in tuples:\n pass" ); final PyExpression target = ((PyForStatement)pyFile.getStatements().get(0)).getForPart().getTarget(); CommandProcessor.getInstance().executeCommand(psiElement.getProject(), new Runnable() { public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { if (target != null) { psiElement.replace(target); } } }); } }, getName(), null); } @NotNull public String getFamilyName() { return getName(); } } private static boolean isEmptyFunction(@NotNull PyFunction f) { final PyStatementList statementList = f.getStatementList(); final PyStatement[] statements = statementList.getStatements(); if (statements.length == 0) { return true; } else if (statements.length == 1) { if (isStringLiteral(statements[0]) || isPassOrRaiseOrEmptyReturn(statements[0])) { return true; } } else if (statements.length == 2) { if (isStringLiteral(statements[0]) && (isPassOrRaiseOrEmptyReturn(statements[1]))) { return true; } } return false; } private static boolean isPassOrRaiseOrEmptyReturn(PyStatement stmt) { if (stmt instanceof PyPassStatement || stmt instanceof PyRaiseStatement) { return true; } if (stmt instanceof PyReturnStatement && ((PyReturnStatement)stmt).getExpression() == null) { return true; } return false; } private static boolean isStringLiteral(PyStatement stmt) { if (stmt instanceof PyExpressionStatement) { final PyExpression expr = ((PyExpressionStatement)stmt).getExpression(); if (expr instanceof PyStringLiteralExpression) { return true; } } return false; } }
/* The contents of this file are subject to the license and copyright terms * detailed in the license directory at the root of the source tree (also * available online at http://fedora-commons.org/license/). */ package org.fcrepo.client.utility.export; import java.io.File; import java.io.FileOutputStream; import java.util.List; import java.util.StringTokenizer; import org.fcrepo.client.FedoraClient; import org.fcrepo.client.utility.AutoFinder; import org.fcrepo.common.Constants; import org.fcrepo.server.access.FedoraAPIAMTOM; import org.fcrepo.server.management.FedoraAPIMMTOM; import org.fcrepo.server.types.gen.ArrayOfString; import org.fcrepo.server.types.gen.FieldSearchQuery; import org.fcrepo.server.types.gen.FieldSearchResult; import org.fcrepo.server.types.gen.ObjectFields; import org.fcrepo.server.types.gen.RepositoryInfo; /** * Utility to initiate an export of one or more objects. This class provides * static utility methods, and it is also called by command line utilities. This * class calls AutoExporter.class which is responsible for making the API-M SOAP * calls for the export. * * @version $Id$ */ public class Export implements Constants { // FIXME: this isn't export-specific... it doesn't belong here public static String getDuration(long millis) { long tsec = millis / 1000; long h = tsec / 60 / 60; long m = (tsec - h * 60 * 60) / 60; long s = tsec - h * 60 * 60 - m * 60; StringBuffer out = new StringBuffer(); if (h > 0) { out.append(h + " hour"); if (h > 1) { out.append('s'); } } if (m > 0) { if (h > 0) { out.append(", "); } out.append(m + " minute"); if (m > 1) { out.append('s'); } } if (s > 0 || h == 0 && m == 0) { if (h > 0 || m > 0) { out.append(", "); } out.append(s + " second"); if (s != 1) { out.append('s'); } } return out.toString(); } public static void one(FedoraAPIAMTOM apia, FedoraAPIMMTOM apim, String pid, String format, String exportContext, File dir) throws Exception { String suffix; if (format.equals(ATOM_ZIP1_1.uri)) { suffix = ".zip"; } else { suffix = ".xml"; } String fName = pid.replaceAll(":", "_") + suffix; File file = new File(dir, fName); System.out.println("Exporting " + pid + " to " + file.getPath()); AutoExporter.export(apia, apim, pid, format, exportContext, new FileOutputStream(file)); } public static int multi(FedoraAPIAMTOM apia, FedoraAPIMMTOM apim, String format, String exportContext, File dir) throws Exception { int count = 0; // prepare the FieldSearch query FieldSearchQuery query = new FieldSearchQuery(); query.setTerms(null); ArrayOfString resultFields = new ArrayOfString(); resultFields.getItem().add("pid"); // get the first chunk of search results FieldSearchResult result = AutoFinder.findObjects(apia, resultFields, 100, query); while (result != null && result.getResultList() != null) { List<ObjectFields> ofs = result.getResultList().getObjectFields(); // export all objects from this chunk of search results for (ObjectFields element : ofs) { String pid = element.getPid().getValue(); one(apia, apim, pid, format, exportContext, dir); count++; } // get the next chunk of search results, if any String token = null; try { token = result.getListSession().getValue().getToken(); } catch (Throwable th) { } if (token != null) { result = AutoFinder.resumeFindObjects(apia, token); } else { result = null; } } return count; } /** * Print error message and show usage for command-line interface. */ public static void badArgs(String msg) { System.err.println("Command: fedora-export"); System.err.println(); System.err.println("Summary: Exports one or more objects from a Fedora repository."); System.err.println(); System.err.println("Syntax:"); System.err.println(" fedora-export host:port user password pid|ftyps format econtext path protocol [context]"); System.err.println(); System.err.println("Where:"); System.err.println(" host is the repository hostname."); System.err.println(" port is the repository port number."); System.err.println(" user is the id of the repository user."); System.err.println(" password is the password of repository user."); System.err.println(" pid | ftyps is the id of the object to export from the source repository OR the types of objects."); System.err.println(" format is the XML format to export "); System.err.println(" ('" + FOXML1_1.uri + "',"); System.err.println(" '" + FOXML1_0.uri + "',"); System.err.println(" '" + METS_EXT1_1.uri + "',"); System.err.println(" '" + METS_EXT1_0.uri + "',"); System.err.println(" '" + ATOM1_1.uri + "',"); System.err.println(" '" + ATOM_ZIP1_1.uri + "',"); System.err.println(" or 'default')"); System.err.println(" econtext is the export context (which indicates what use case"); System.err.println(" the output should be prepared for."); System.err.println(" ('public', 'migrate', 'archive' or 'default')"); System.err.println(" path is the directory to export the object."); System.err.println(" protocol is the how to connect to repository, either http or https."); System.err.println(" context is an optional parameter for specifying the context name under "); System.err.println(" which the Fedora server is deployed. The default is fedora."); System.err.println(); System.err.println("Examples:"); System.err.println("fedora-export myrepo.com:8443 user pw demo:1 " + FOXML1_1.uri + " migrate . https"); System.err.println(); System.err.println(" Exports demo:1 for migration in FOXML format "); System.err.println(" using the secure https protocol (SSL)."); System.err.println(" (from myrepo.com:80 to the current directory)."); System.err.println(); System.err.println("fedora-export myrepo.com:80 user pw DMO default default /tmp/fedoradump http"); System.err.println(); System.err.println(" Exports all objects in the default export format and context "); System.err.println(" (from myrepo.com:80 to directory /tmp/fedoradump)."); System.err.println(); System.err.println("fedora-export myrepo.com:80 user pw DMO default default /tmp/fedoradump http my-fedora"); System.err.println(); System.err.println(" Exports all objects in the default export format and context "); System.err.println(" (from myrepo.com:80 to directory /tmp/fedoradump)."); System.err.println(" from a Fedora server running under http://myrepo:80/my-fedora instead of http://myrepo:80/fedora "); System.err.println(); System.err.println("ERROR : " + msg); System.exit(1); } /** * Command-line interface for doing exports. */ public static void main(String[] args) { System.setProperty("java.awt.headless", "true"); try { // USAGE: fedora-export host:port user password pid|ftyps format econtext path protocol [context] if (args.length < 8 || args.length > 9) { Export.badArgs("Wrong number of arguments."); } String[] hp = args[0].split(":"); if (hp.length != 2) { Export.badArgs("First arg must be of the form 'host:port'"); } //SDP - HTTPS String protocol = args[7]; if (!protocol.equals("http") && !protocol.equals("https")) { Export.badArgs("protocol arg must be 'http' or 'https'"); } String context = Constants.FEDORA_DEFAULT_APP_CONTEXT; if (args.length == 9 && !args[8].equals("")) { context = args[8]; } // ****************************************** // NEW: use new client utility class String baseURL = protocol + "://" + hp[0] + ":" + Integer.parseInt(hp[1]) + "/" + context; FedoraClient fc = new FedoraClient(baseURL, args[1], args[2]); FedoraAPIAMTOM sourceRepoAPIA = fc.getAPIAMTOM(); FedoraAPIMMTOM sourceRepoAPIM = fc.getAPIMMTOM(); //******************************************* String exportFormat = args[4]; String exportContext = args[5]; if (!exportFormat.equals(FOXML1_1.uri) && !exportFormat.equals(FOXML1_0.uri) && !exportFormat.equals(METS_EXT1_1.uri) && !exportFormat.equals(METS_EXT1_0.uri) && !exportFormat.equals(ATOM1_1.uri) && !exportFormat.equals(ATOM_ZIP1_1.uri) && !exportFormat.equals("default")) { Export.badArgs(exportFormat + " is not a valid export format."); } if (!exportContext.equals("public") && !exportContext.equals("migrate") && !exportContext.equals("archive") && !exportContext.equals("default")) { Export .badArgs("econtext arg must be 'public', 'migrate', 'archive', or 'default'"); } RepositoryInfo repoinfo = sourceRepoAPIA.describeRepository(); StringTokenizer stoken = new StringTokenizer(repoinfo.getRepositoryVersion(), "."); int majorVersion = new Integer(stoken.nextToken()).intValue(); if (majorVersion < 2 // pre-2.0 repo && !exportFormat.equals(METS_EXT1_0.uri) && !exportFormat.equals("default")) { Export.badArgs("format arg must be '" + METS_EXT1_0.uri + "' or 'default' for pre-2.0 repository."); } if (exportFormat.equals("default")) { exportFormat = null; } if (exportContext.equals("default")) { exportContext = null; } if (args[3].indexOf(":") == -1) { // assume args[3] is FTYPS... so multi-export int count = Export.multi(sourceRepoAPIA, sourceRepoAPIM, exportFormat, exportContext, //args[4], // format //args[5], // export context new File(args[6])); // path System.out.print("Exported " + count + " objects."); } else { // assume args[3] is a PID...they only want to export one object Export.one(sourceRepoAPIA, sourceRepoAPIM, args[3], // PID exportFormat, exportContext, //args[4], // format //args[5], // export context new File(args[6])); // path System.out.println("Exported " + args[3]); } } catch (Exception e) { System.err.print("Error : " + e); if (e.getMessage() == null) { e.printStackTrace(); } else { System.err.print(e.getMessage()); } } } }
/* * Copyright 2000-2016 JetBrains s.r.o. * * 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.intellij.refactoring.introduceParameter; import com.intellij.analysis.AnalysisScope; import com.intellij.codeInsight.AnnotationUtil; import com.intellij.codeInsight.ChangeContextUtil; import com.intellij.codeInsight.generation.GenerateMembersUtil; import com.intellij.lang.findUsages.DescriptiveNameUtil; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.Ref; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.searches.MethodReferencesSearch; import com.intellij.psi.search.searches.OverridingMethodsSearch; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.refactoring.BaseRefactoringProcessor; import com.intellij.refactoring.IntroduceParameterRefactoring; import com.intellij.refactoring.RefactoringBundle; import com.intellij.refactoring.changeSignature.ChangeSignatureProcessor; import com.intellij.refactoring.introduceVariable.IntroduceVariableBase; import com.intellij.refactoring.listeners.RefactoringEventData; import com.intellij.refactoring.util.*; import com.intellij.refactoring.util.duplicates.MethodDuplicatesHandler; import com.intellij.refactoring.util.occurrences.ExpressionOccurrenceManager; import com.intellij.refactoring.util.occurrences.LocalVariableOccurrenceManager; import com.intellij.refactoring.util.occurrences.OccurrenceManager; import com.intellij.refactoring.util.usageInfo.DefaultConstructorImplicitUsageInfo; import com.intellij.refactoring.util.usageInfo.NoConstructorClassUsageInfo; import com.intellij.usageView.UsageInfo; import com.intellij.usageView.UsageViewDescriptor; import com.intellij.usageView.UsageViewUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.HashSet; import com.intellij.util.containers.MultiMap; import gnu.trove.TIntArrayList; import gnu.trove.TIntProcedure; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.Set; /** * @author dsl * @since 07.05.2002 */ public class IntroduceParameterProcessor extends BaseRefactoringProcessor implements IntroduceParameterData { private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.introduceParameter.IntroduceParameterProcessor"); private final PsiMethod myMethodToReplaceIn; private final PsiMethod myMethodToSearchFor; private PsiExpression myParameterInitializer; private final PsiExpression myExpressionToSearch; private final PsiLocalVariable myLocalVariable; private final boolean myRemoveLocalVariable; private final String myParameterName; private final boolean myReplaceAllOccurrences; private int myReplaceFieldsWithGetters; private final boolean myDeclareFinal; private final boolean myGenerateDelegate; private PsiType myForcedType; private final TIntArrayList myParametersToRemove; private final PsiManager myManager; private JavaExpressionWrapper myInitializerWrapper; private boolean myHasConflicts; /** * if expressionToSearch is null, search for localVariable */ public IntroduceParameterProcessor(@NotNull Project project, PsiMethod methodToReplaceIn, @NotNull PsiMethod methodToSearchFor, PsiExpression parameterInitializer, PsiExpression expressionToSearch, PsiLocalVariable localVariable, boolean removeLocalVariable, String parameterName, boolean replaceAllOccurrences, int replaceFieldsWithGetters, boolean declareFinal, boolean generateDelegate, PsiType forcedType, @NotNull TIntArrayList parametersToRemove) { super(project); myMethodToReplaceIn = methodToReplaceIn; myMethodToSearchFor = methodToSearchFor; myParameterInitializer = parameterInitializer; myExpressionToSearch = expressionToSearch; myLocalVariable = localVariable; myRemoveLocalVariable = removeLocalVariable; myParameterName = parameterName; myReplaceAllOccurrences = replaceAllOccurrences; myReplaceFieldsWithGetters = replaceFieldsWithGetters; myDeclareFinal = declareFinal; myGenerateDelegate = generateDelegate; myForcedType = forcedType; myManager = PsiManager.getInstance(project); myParametersToRemove = parametersToRemove; myInitializerWrapper = expressionToSearch == null ? null : new JavaExpressionWrapper(expressionToSearch); } public void setParameterInitializer(PsiExpression parameterInitializer) { myParameterInitializer = parameterInitializer; } @NotNull protected UsageViewDescriptor createUsageViewDescriptor(@NotNull UsageInfo[] usages) { return new IntroduceParameterViewDescriptor(myMethodToSearchFor); } @NotNull public PsiType getForcedType() { return myForcedType; } public void setForcedType(PsiType forcedType) { myForcedType = forcedType; } public int getReplaceFieldsWithGetters() { return myReplaceFieldsWithGetters; } public void setReplaceFieldsWithGetters(int replaceFieldsWithGetters) { myReplaceFieldsWithGetters = replaceFieldsWithGetters; } @NotNull protected UsageInfo[] findUsages() { ArrayList<UsageInfo> result = new ArrayList<>(); PsiMethod[] overridingMethods = OverridingMethodsSearch.search(myMethodToSearchFor).toArray(PsiMethod.EMPTY_ARRAY); for (PsiMethod overridingMethod : overridingMethods) { result.add(new UsageInfo(overridingMethod)); } if (!myGenerateDelegate) { PsiReference[] refs = MethodReferencesSearch.search(myMethodToSearchFor, GlobalSearchScope.projectScope(myProject), true).toArray(PsiReference.EMPTY_ARRAY); for (PsiReference ref1 : refs) { PsiElement ref = ref1.getElement(); if (ref instanceof PsiMethod && ((PsiMethod)ref).isConstructor()) { DefaultConstructorImplicitUsageInfo implicitUsageInfo = new DefaultConstructorImplicitUsageInfo((PsiMethod)ref, ((PsiMethod)ref).getContainingClass(), myMethodToSearchFor); result.add(implicitUsageInfo); } else if (ref instanceof PsiClass) { result.add(new NoConstructorClassUsageInfo((PsiClass)ref)); } else if (!IntroduceParameterUtil.insideMethodToBeReplaced(ref, myMethodToReplaceIn)) { result.add(new ExternalUsageInfo(ref)); } else { result.add(new ChangedMethodCallInfo(ref)); } } } if (myReplaceAllOccurrences) { for (PsiElement expr : getOccurrences()) { result.add(new InternalUsageInfo(expr)); } } else { if (myExpressionToSearch != null && myExpressionToSearch.isValid()) { result.add(new InternalUsageInfo(myExpressionToSearch)); } } final UsageInfo[] usageInfos = result.toArray(new UsageInfo[result.size()]); return UsageViewUtil.removeDuplicatedUsages(usageInfos); } protected PsiElement[] getOccurrences() { final OccurrenceManager occurrenceManager; if (myLocalVariable == null) { occurrenceManager = new ExpressionOccurrenceManager(myExpressionToSearch, myMethodToReplaceIn, null); } else { occurrenceManager = new LocalVariableOccurrenceManager(myLocalVariable, null); } return occurrenceManager.getOccurrences(); } public boolean hasConflicts() { return myHasConflicts; } private static class ReferencedElementsCollector extends JavaRecursiveElementWalkingVisitor { private final Set<PsiElement> myResult = new HashSet<>(); @Override public void visitReferenceExpression(PsiReferenceExpression expression) { visitReferenceElement(expression); } @Override public void visitReferenceElement(PsiJavaCodeReferenceElement reference) { super.visitReferenceElement(reference); final PsiElement element = reference.resolve(); if (element != null) { myResult.add(element); } } } protected boolean preprocessUsages(@NotNull Ref<UsageInfo[]> refUsages) { UsageInfo[] usagesIn = refUsages.get(); MultiMap<PsiElement, String> conflicts = new MultiMap<>(); AnySameNameVariables anySameNameVariables = new AnySameNameVariables(); myMethodToReplaceIn.accept(anySameNameVariables); final Pair<PsiElement, String> conflictPair = anySameNameVariables.getConflict(); if (conflictPair != null) { conflicts.putValue(conflictPair.first, conflictPair.second); } if (!myGenerateDelegate) { detectAccessibilityConflicts(usagesIn, conflicts); } if (myParameterInitializer != null && !myMethodToReplaceIn.hasModifierProperty(PsiModifier.PRIVATE)) { final AnySupers anySupers = new AnySupers(); myParameterInitializer.accept(anySupers); if (anySupers.isResult()) { for (UsageInfo usageInfo : usagesIn) { if (!(usageInfo.getElement() instanceof PsiMethod) && !(usageInfo instanceof InternalUsageInfo)) { if (!PsiTreeUtil.isAncestor(myMethodToReplaceIn.getContainingClass(), usageInfo.getElement(), false)) { String message = RefactoringBundle.message("parameter.initializer.contains.0.but.not.all.calls.to.method.are.in.its.class", CommonRefactoringUtil.htmlEmphasize(PsiKeyword.SUPER)); conflicts.putValue(myParameterInitializer, message); break; } } } } } for (IntroduceParameterMethodUsagesProcessor processor : IntroduceParameterMethodUsagesProcessor.EP_NAME.getExtensions()) { processor.findConflicts(this, refUsages.get(), conflicts); } myHasConflicts = !conflicts.isEmpty(); return showConflicts(conflicts, usagesIn); } private void detectAccessibilityConflicts(final UsageInfo[] usageArray, MultiMap<PsiElement, String> conflicts) { if (myParameterInitializer != null) { final ReferencedElementsCollector collector = new ReferencedElementsCollector(); myParameterInitializer.accept(collector); final Set<PsiElement> result = collector.myResult; if (!result.isEmpty()) { for (final UsageInfo usageInfo : usageArray) { if (usageInfo instanceof ExternalUsageInfo && IntroduceParameterUtil.isMethodUsage(usageInfo)) { final PsiElement place = usageInfo.getElement(); for (PsiElement element : result) { if (element instanceof PsiField && myReplaceFieldsWithGetters != IntroduceParameterRefactoring.REPLACE_FIELDS_WITH_GETTERS_NONE) { //check getter access instead final PsiClass psiClass = ((PsiField)element).getContainingClass(); LOG.assertTrue(psiClass != null); final PsiMethod method = psiClass.findMethodBySignature(GenerateMembersUtil.generateGetterPrototype((PsiField)element), true); if (method != null){ element = method; } } if (element instanceof PsiMember && !JavaPsiFacade.getInstance(myProject).getResolveHelper().isAccessible((PsiMember)element, place, null)) { String message = RefactoringBundle.message( "0.is.not.accessible.from.1.value.for.introduced.parameter.in.that.method.call.will.be.incorrect", RefactoringUIUtil.getDescription(element, true), RefactoringUIUtil.getDescription(ConflictsUtil.getContainer(place), true)); conflicts.putValue(element, message); } } } } } } } public static class AnySupers extends JavaRecursiveElementWalkingVisitor { private boolean myResult; @Override public void visitSuperExpression(PsiSuperExpression expression) { myResult = true; } public boolean isResult() { return myResult; } @Override public void visitReferenceExpression(PsiReferenceExpression expression) { visitElement(expression); } } public class AnySameNameVariables extends JavaRecursiveElementWalkingVisitor { private Pair<PsiElement, String> conflict; public Pair<PsiElement, String> getConflict() { return conflict; } @Override public void visitVariable(PsiVariable variable) { if (variable == myLocalVariable) return; if (variable instanceof PsiParameter && ((PsiParameter)variable).getDeclarationScope() == myMethodToReplaceIn) { if (getParametersToRemove().contains(myMethodToReplaceIn.getParameterList().getParameterIndex((PsiParameter)variable))){ return; } } if (myParameterName.equals(variable.getName())) { String descr = RefactoringBundle.message("there.is.already.a.0.it.will.conflict.with.an.introduced.parameter", RefactoringUIUtil.getDescription(variable, true)); conflict = Pair.create(variable, CommonRefactoringUtil.capitalize(descr)); } } @Override public void visitReferenceExpression(PsiReferenceExpression expression) { } @Override public void visitElement(PsiElement element) { if(conflict != null) return; super.visitElement(element); } } @Nullable @Override protected String getRefactoringId() { return "refactoring.introduceParameter"; } @Nullable @Override protected RefactoringEventData getBeforeData() { RefactoringEventData data = new RefactoringEventData(); data.addElements(new PsiElement[] {myLocalVariable, myExpressionToSearch}); return data; } @Nullable @Override protected RefactoringEventData getAfterData(@NotNull UsageInfo[] usages) { final PsiParameter parameter = JavaIntroduceParameterMethodUsagesProcessor.getAnchorParameter(myMethodToReplaceIn); final RefactoringEventData afterData = new RefactoringEventData(); afterData.addElement(parameter); return afterData; } protected void performRefactoring(@NotNull UsageInfo[] usages) { try { PsiElementFactory factory = JavaPsiFacade.getInstance(myManager.getProject()).getElementFactory(); PsiType initializerType = getInitializerType(myForcedType, myParameterInitializer, myLocalVariable); setForcedType(initializerType); // Converting myParameterInitializer if (myParameterInitializer == null) { LOG.assertTrue(myLocalVariable != null); myParameterInitializer = factory.createExpressionFromText(myLocalVariable.getName(), myLocalVariable); } else if (myParameterInitializer instanceof PsiArrayInitializerExpression){ final PsiExpression newExprArrayInitializer = RefactoringUtil.createNewExpressionFromArrayInitializer((PsiArrayInitializerExpression)myParameterInitializer, initializerType); myParameterInitializer = (PsiExpression)myParameterInitializer.replace(newExprArrayInitializer); } myInitializerWrapper = new JavaExpressionWrapper(myParameterInitializer); // Changing external occurrences (the tricky part) IntroduceParameterUtil.processUsages(usages, this); if (myGenerateDelegate) { generateDelegate(myMethodToReplaceIn); if (myMethodToReplaceIn != myMethodToSearchFor) { final PsiMethod method = generateDelegate(myMethodToSearchFor); if (method.getContainingClass().isInterface()) { final PsiCodeBlock block = method.getBody(); if (block != null) { block.delete(); } } } } // Changing signature of initial method // (signature of myMethodToReplaceIn will be either changed now or have already been changed) LOG.assertTrue(initializerType.isValid()); final FieldConflictsResolver fieldConflictsResolver = new FieldConflictsResolver(myParameterName, myMethodToReplaceIn.getBody()); IntroduceParameterUtil.changeMethodSignatureAndResolveFieldConflicts(new UsageInfo(myMethodToReplaceIn), usages, this); if (myMethodToSearchFor != myMethodToReplaceIn) { IntroduceParameterUtil.changeMethodSignatureAndResolveFieldConflicts(new UsageInfo(myMethodToSearchFor), usages, this); } else if (myGenerateDelegate && myMethodToReplaceIn.findSuperMethods().length == 0) { final PsiAnnotation annotation = AnnotationUtil.findAnnotation(myMethodToReplaceIn, true, Override.class.getName()); if (annotation != null) { annotation.delete(); } } ChangeContextUtil.clearContextInfo(myParameterInitializer); // Replacing expression occurrences for (UsageInfo usage : usages) { if (usage instanceof ChangedMethodCallInfo) { PsiElement element = usage.getElement(); processChangedMethodCall(element); } else if (usage instanceof InternalUsageInfo) { PsiElement element = usage.getElement(); if (element instanceof PsiExpression) { element = RefactoringUtil.outermostParenthesizedExpression((PsiExpression)element); } if (element != null) { if (element.getParent() instanceof PsiExpressionStatement) { element.getParent().delete(); } else { PsiExpression newExpr = factory.createExpressionFromText(myParameterName, element); IntroduceVariableBase.replace((PsiExpression)element, newExpr, myProject); } } } } if(myLocalVariable != null && myRemoveLocalVariable) { myLocalVariable.normalizeDeclaration(); myLocalVariable.getParent().delete(); } fieldConflictsResolver.fix(); } catch (IncorrectOperationException ex) { LOG.error(ex); } if (isReplaceDuplicates()) { ApplicationManager.getApplication().invokeLater(() -> processMethodsDuplicates(), ModalityState.NON_MODAL, myProject.getDisposed()); } } protected boolean isReplaceDuplicates() { return true; } private void processMethodsDuplicates() { final Runnable runnable = () -> { if (!myMethodToReplaceIn.isValid()) return; MethodDuplicatesHandler.invokeOnScope(myProject, Collections.singleton(myMethodToReplaceIn), new AnalysisScope(myMethodToReplaceIn.getContainingFile()), true); }; ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> ApplicationManager.getApplication().runReadAction(runnable), "Search method duplicates...", true, myProject); } private PsiMethod generateDelegate(final PsiMethod methodToReplaceIn) throws IncorrectOperationException { final PsiMethod delegate = (PsiMethod)methodToReplaceIn.copy(); final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(myManager.getProject()).getElementFactory(); ChangeSignatureProcessor.makeEmptyBody(elementFactory, delegate); final PsiCallExpression callExpression = ChangeSignatureProcessor.addDelegatingCallTemplate(delegate, delegate.getName()); final PsiExpressionList argumentList = callExpression.getArgumentList(); assert argumentList != null; final PsiParameter[] psiParameters = methodToReplaceIn.getParameterList().getParameters(); final PsiParameter anchorParameter = getAnchorParameter(methodToReplaceIn); if (psiParameters.length == 0) { argumentList.add(myParameterInitializer); } else { if (anchorParameter == null) { argumentList.add(myParameterInitializer); } for (int i = 0; i < psiParameters.length; i++) { PsiParameter psiParameter = psiParameters[i]; if (!myParametersToRemove.contains(i)) { final PsiExpression expression = elementFactory.createExpressionFromText(psiParameter.getName(), delegate); argumentList.add(expression); } if (psiParameter == anchorParameter) { argumentList.add(myParameterInitializer); } } } return (PsiMethod)methodToReplaceIn.getContainingClass().addBefore(delegate, methodToReplaceIn); } static PsiType getInitializerType(PsiType forcedType, PsiExpression parameterInitializer, PsiLocalVariable localVariable) { final PsiType initializerType; if (forcedType == null) { if (parameterInitializer == null) { if (localVariable != null) { initializerType = localVariable.getType(); } else { LOG.assertTrue(false); initializerType = null; } } else { if (localVariable == null) { initializerType = RefactoringUtil.getTypeByExpressionWithExpectedType(parameterInitializer); } else { initializerType = localVariable.getType(); } } } else { initializerType = forcedType; } return initializerType; } private void processChangedMethodCall(PsiElement element) throws IncorrectOperationException { if (element.getParent() instanceof PsiMethodCallExpression) { PsiMethodCallExpression methodCall = (PsiMethodCallExpression)element.getParent(); if (myMethodToReplaceIn == myMethodToSearchFor && PsiTreeUtil.isAncestor(methodCall, myParameterInitializer, false)) return; PsiElementFactory factory = JavaPsiFacade.getInstance(methodCall.getProject()).getElementFactory(); PsiExpression expression = factory.createExpressionFromText(myParameterName, null); final PsiExpressionList argList = methodCall.getArgumentList(); final PsiExpression[] exprs = argList.getExpressions(); boolean first = false; PsiElement anchor = null; if (myMethodToSearchFor.isVarArgs()) { final int oldParamCount = myMethodToSearchFor.getParameterList().getParametersCount() - 1; if (exprs.length >= oldParamCount) { if (oldParamCount > 1) { anchor = exprs[oldParamCount - 2]; } else { first = true; anchor = null; } } else { anchor = exprs[exprs.length -1]; } } else if (exprs.length > 0) { anchor = exprs[exprs.length - 1]; } if (anchor != null) { argList.addAfter(expression, anchor); } else { if (first && exprs.length > 0) { argList.addBefore(expression, exprs[0]); } else { argList.add(expression); } } removeParametersFromCall(argList); } else { LOG.error(element.getParent()); } } private void removeParametersFromCall(final PsiExpressionList argList) { final PsiExpression[] exprs = argList.getExpressions(); myParametersToRemove.forEachDescending(new TIntProcedure() { public boolean execute(final int paramNum) { if (paramNum < exprs.length) { try { exprs[paramNum].delete(); } catch (IncorrectOperationException e) { LOG.error(e); } } return true; } }); } protected String getCommandName() { return RefactoringBundle.message("introduce.parameter.command", DescriptiveNameUtil.getDescriptiveName(myMethodToReplaceIn)); } @Nullable private static PsiParameter getAnchorParameter(PsiMethod methodToReplaceIn) { PsiParameterList parameterList = methodToReplaceIn.getParameterList(); final PsiParameter anchorParameter; final PsiParameter[] parameters = parameterList.getParameters(); final int length = parameters.length; if (!methodToReplaceIn.isVarArgs()) { anchorParameter = length > 0 ? parameters[length-1] : null; } else { LOG.assertTrue(length > 0); LOG.assertTrue(parameters[length-1].isVarArgs()); anchorParameter = length > 1 ? parameters[length-2] : null; } return anchorParameter; } public PsiMethod getMethodToReplaceIn() { return myMethodToReplaceIn; } @NotNull public PsiMethod getMethodToSearchFor() { return myMethodToSearchFor; } public JavaExpressionWrapper getParameterInitializer() { return myInitializerWrapper; } @NotNull public String getParameterName() { return myParameterName; } public boolean isDeclareFinal() { return myDeclareFinal; } public boolean isGenerateDelegate() { return myGenerateDelegate; } @NotNull public TIntArrayList getParametersToRemove() { return myParametersToRemove; } @NotNull public Project getProject() { return myProject; } }
/** * 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.pulsar.metadata.impl; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; import com.google.common.annotations.VisibleForTesting; import com.google.common.util.concurrent.RateLimiter; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.io.IOException; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import lombok.extern.slf4j.Slf4j; import org.apache.bookkeeper.stats.NullStatsLogger; import org.apache.bookkeeper.stats.OpStatsLogger; import org.apache.bookkeeper.stats.StatsLogger; import org.apache.bookkeeper.util.MathUtils; import org.apache.bookkeeper.zookeeper.BoundExponentialBackoffRetryPolicy; import org.apache.bookkeeper.zookeeper.RetryPolicy; import org.apache.bookkeeper.zookeeper.ZooKeeperWatcherBase; import org.apache.zookeeper.AddWatchMode; import org.apache.zookeeper.AsyncCallback.ACLCallback; import org.apache.zookeeper.AsyncCallback.Children2Callback; import org.apache.zookeeper.AsyncCallback.ChildrenCallback; import org.apache.zookeeper.AsyncCallback.DataCallback; import org.apache.zookeeper.AsyncCallback.MultiCallback; import org.apache.zookeeper.AsyncCallback.StatCallback; import org.apache.zookeeper.AsyncCallback.StringCallback; import org.apache.zookeeper.AsyncCallback.VoidCallback; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.Op; import org.apache.zookeeper.OpResult; import org.apache.zookeeper.Transaction; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.EventType; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; /** * Provide a zookeeper client to handle session expire. */ @Slf4j public class PulsarZooKeeperClient extends ZooKeeper implements Watcher, AutoCloseable { private static final int DEFAULT_RETRY_EXECUTOR_THREAD_COUNT = 1; // ZooKeeper client connection variables private final String connectString; private final int sessionTimeoutMs; private final boolean allowReadOnlyMode; // state for the zookeeper client private final AtomicReference<ZooKeeper> zk = new AtomicReference<ZooKeeper>(); private final AtomicBoolean closed = new AtomicBoolean(false); private final ZooKeeperWatcherBase watcherManager; private final ScheduledExecutorService retryExecutor; private final ExecutorService connectExecutor; // rate limiter private final RateLimiter rateLimiter; // retry polices private final RetryPolicy connectRetryPolicy; private final RetryPolicy operationRetryPolicy; // Stats Logger private final OpStatsLogger createStats; private final OpStatsLogger getStats; private final OpStatsLogger setStats; private final OpStatsLogger deleteStats; private final OpStatsLogger getChildrenStats; private final OpStatsLogger existsStats; private final OpStatsLogger multiStats; private final OpStatsLogger getACLStats; private final OpStatsLogger setACLStats; private final OpStatsLogger syncStats; private final OpStatsLogger createClientStats; private final Callable<ZooKeeper> clientCreator = new Callable<ZooKeeper>() { @Override public ZooKeeper call() throws Exception { try { return ZooWorker.syncCallWithRetries(null, new ZooWorker.ZooCallable<ZooKeeper>() { @Override public ZooKeeper call() throws KeeperException, InterruptedException { log.info("Reconnecting zookeeper {}.", connectString); // close the previous one closeZkHandle(); ZooKeeper newZk; try { newZk = createZooKeeper(); } catch (IOException ie) { log.error("Failed to create zookeeper instance to " + connectString, ie); throw KeeperException.create(KeeperException.Code.CONNECTIONLOSS); } waitForConnection(); zk.set(newZk); log.info("ZooKeeper session {} is created to {}.", Long.toHexString(newZk.getSessionId()), connectString); return newZk; } @Override public String toString() { return String.format("ZooKeeper Client Creator (%s)", connectString); } }, connectRetryPolicy, rateLimiter, createClientStats); } catch (Exception e) { log.error("Gave up reconnecting to ZooKeeper : ", e); Runtime.getRuntime().exit(-1); return null; } } }; @VisibleForTesting static PulsarZooKeeperClient createConnectedZooKeeperClient( String connectString, int sessionTimeoutMs, Set<Watcher> childWatchers, RetryPolicy operationRetryPolicy) throws KeeperException, InterruptedException, IOException { return PulsarZooKeeperClient.newBuilder() .connectString(connectString) .sessionTimeoutMs(sessionTimeoutMs) .watchers(childWatchers) .operationRetryPolicy(operationRetryPolicy) .build(); } /** * A builder to build retryable zookeeper client. */ public static class Builder { String connectString = null; int sessionTimeoutMs = 10000; Set<Watcher> watchers = null; RetryPolicy connectRetryPolicy = null; RetryPolicy operationRetryPolicy = null; StatsLogger statsLogger = NullStatsLogger.INSTANCE; int retryExecThreadCount = DEFAULT_RETRY_EXECUTOR_THREAD_COUNT; double requestRateLimit = 0; boolean allowReadOnlyMode = false; private Builder() {} public Builder connectString(String connectString) { this.connectString = connectString; return this; } public Builder sessionTimeoutMs(int sessionTimeoutMs) { this.sessionTimeoutMs = sessionTimeoutMs; return this; } public Builder watchers(Set<Watcher> watchers) { this.watchers = watchers; return this; } public Builder connectRetryPolicy(RetryPolicy retryPolicy) { this.connectRetryPolicy = retryPolicy; return this; } public Builder operationRetryPolicy(RetryPolicy retryPolicy) { this.operationRetryPolicy = retryPolicy; return this; } public Builder statsLogger(StatsLogger statsLogger) { this.statsLogger = statsLogger; return this; } public Builder requestRateLimit(double requestRateLimit) { this.requestRateLimit = requestRateLimit; return this; } public Builder retryThreadCount(int numThreads) { this.retryExecThreadCount = numThreads; return this; } public Builder allowReadOnlyMode(boolean allowReadOnlyMode) { this.allowReadOnlyMode = allowReadOnlyMode; return this; } public PulsarZooKeeperClient build() throws IOException, KeeperException, InterruptedException { requireNonNull(connectString); checkArgument(sessionTimeoutMs > 0); requireNonNull(statsLogger); checkArgument(retryExecThreadCount > 0); if (null == connectRetryPolicy) { // Session expiry event is received by client only when zk quorum is well established. // All other connection loss retries happen at zk client library transparently. // Hence, we don't need to wait before retrying. connectRetryPolicy = new BoundExponentialBackoffRetryPolicy(0, 0, Integer.MAX_VALUE); } if (null == operationRetryPolicy) { operationRetryPolicy = new BoundExponentialBackoffRetryPolicy(sessionTimeoutMs, sessionTimeoutMs, 0); } // Create a watcher manager StatsLogger watcherStatsLogger = statsLogger.scope("watcher"); ZooKeeperWatcherBase watcherManager = null == watchers ? new ZooKeeperWatcherBase(sessionTimeoutMs, watcherStatsLogger) : new ZooKeeperWatcherBase(sessionTimeoutMs, watchers, watcherStatsLogger); PulsarZooKeeperClient client = new PulsarZooKeeperClient( connectString, sessionTimeoutMs, watcherManager, connectRetryPolicy, operationRetryPolicy, statsLogger, retryExecThreadCount, requestRateLimit, allowReadOnlyMode ); // Wait for connection to be established. try { watcherManager.waitForConnection(); } catch (KeeperException ke) { client.close(); throw ke; } catch (InterruptedException ie) { Thread.currentThread().interrupt(); client.close(); throw ie; } return client; } } public static Builder newBuilder() { return new Builder(); } protected PulsarZooKeeperClient(String connectString, int sessionTimeoutMs, ZooKeeperWatcherBase watcherManager, RetryPolicy connectRetryPolicy, RetryPolicy operationRetryPolicy, StatsLogger statsLogger, int retryExecThreadCount, double rate, boolean allowReadOnlyMode) throws IOException { super(connectString, sessionTimeoutMs, watcherManager, allowReadOnlyMode); this.connectString = connectString; this.sessionTimeoutMs = sessionTimeoutMs; this.allowReadOnlyMode = allowReadOnlyMode; this.watcherManager = watcherManager; this.connectRetryPolicy = connectRetryPolicy; this.operationRetryPolicy = operationRetryPolicy; this.rateLimiter = rate > 0 ? RateLimiter.create(rate) : null; this.retryExecutor = Executors.newScheduledThreadPool(retryExecThreadCount, new ThreadFactoryBuilder().setNameFormat("ZKC-retry-executor-%d").build()); this.connectExecutor = Executors.newSingleThreadExecutor( new ThreadFactoryBuilder().setNameFormat("ZKC-connect-executor-%d").build()); // added itself to the watcher watcherManager.addChildWatcher(this); // Stats StatsLogger scopedStatsLogger = statsLogger.scope("zk"); createClientStats = scopedStatsLogger.getOpStatsLogger("create_client"); createStats = scopedStatsLogger.getOpStatsLogger("create"); getStats = scopedStatsLogger.getOpStatsLogger("get_data"); setStats = scopedStatsLogger.getOpStatsLogger("set_data"); deleteStats = scopedStatsLogger.getOpStatsLogger("delete"); getChildrenStats = scopedStatsLogger.getOpStatsLogger("get_children"); existsStats = scopedStatsLogger.getOpStatsLogger("exists"); multiStats = scopedStatsLogger.getOpStatsLogger("multi"); getACLStats = scopedStatsLogger.getOpStatsLogger("get_acl"); setACLStats = scopedStatsLogger.getOpStatsLogger("set_acl"); syncStats = scopedStatsLogger.getOpStatsLogger("sync"); } @Override public void close() throws InterruptedException { closed.set(true); connectExecutor.shutdown(); retryExecutor.shutdown(); closeZkHandle(); } private void closeZkHandle() throws InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { super.close(); } else { zkHandle.close(); } } public void waitForConnection() throws KeeperException, InterruptedException { watcherManager.waitForConnection(); } protected ZooKeeper createZooKeeper() throws IOException { return new ZooKeeper(connectString, sessionTimeoutMs, watcherManager, allowReadOnlyMode); } @Override public void process(WatchedEvent event) { if (event.getType() == EventType.None && event.getState() == KeeperState.Expired) { onExpired(); } } private void onExpired() { if (closed.get()) { // we don't schedule any tries if the client is closed. return; } log.info("ZooKeeper session {} is expired from {}.", Long.toHexString(getSessionId()), connectString); try { connectExecutor.submit(clientCreator); } catch (RejectedExecutionException ree) { if (!closed.get()) { log.error("ZooKeeper reconnect task is rejected : ", ree); } } catch (Exception t) { log.error("Failed to submit zookeeper reconnect task due to runtime exception : ", t); } } /** * A runnable that retries zookeeper operations. */ abstract static class ZkRetryRunnable implements Runnable { final ZooWorker worker; final RateLimiter rateLimiter; final Runnable that; ZkRetryRunnable(RetryPolicy retryPolicy, RateLimiter rateLimiter, OpStatsLogger statsLogger) { this.worker = new ZooWorker(retryPolicy, statsLogger); this.rateLimiter = rateLimiter; that = this; } @Override public void run() { if (null != rateLimiter) { rateLimiter.acquire(); } zkRun(); } abstract void zkRun(); } // inherits from ZooKeeper client for all operations @Override public long getSessionId() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return super.getSessionId(); } return zkHandle.getSessionId(); } @Override public byte[] getSessionPasswd() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return super.getSessionPasswd(); } return zkHandle.getSessionPasswd(); } @Override public int getSessionTimeout() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return super.getSessionTimeout(); } return zkHandle.getSessionTimeout(); } @Override public void addAuthInfo(String scheme, byte[] auth) { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { super.addAuthInfo(scheme, auth); return; } zkHandle.addAuthInfo(scheme, auth); } private void backOffAndRetry(Runnable r, long nextRetryWaitTimeMs) { try { retryExecutor.schedule(r, nextRetryWaitTimeMs, TimeUnit.MILLISECONDS); } catch (RejectedExecutionException ree) { if (!closed.get()) { log.error("ZooKeeper Operation {} is rejected : ", r, ree); } } } private boolean allowRetry(ZooWorker worker, int rc) { return worker.allowRetry(rc) && !closed.get(); } @Override public synchronized void register(Watcher watcher) { watcherManager.addChildWatcher(watcher); } @Override public List<OpResult> multi(final Iterable<Op> ops) throws InterruptedException, KeeperException { return ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<List<OpResult>>() { @Override public String toString() { return "multi"; } @Override public List<OpResult> call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return PulsarZooKeeperClient.super.multi(ops); } return zkHandle.multi(ops); } }, operationRetryPolicy, rateLimiter, multiStats); } @Override public void multi(final Iterable<Op> ops, final MultiCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, createStats) { final MultiCallback multiCb = new MultiCallback() { @Override public void processResult(int rc, String path, Object ctx, List<OpResult> results) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, results); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { PulsarZooKeeperClient.super.multi(ops, multiCb, worker); } else { zkHandle.multi(ops, multiCb, worker); } } @Override public String toString() { return "multi"; } }; // execute it immediately proc.run(); } @Override @Deprecated public Transaction transaction() { // since there is no reference about which client that the transaction could use // so just use ZooKeeper instance directly. // you'd better to use {@link #multi}. ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return super.transaction(); } return zkHandle.transaction(); } @Override public List<ACL> getACL(final String path, final Stat stat) throws KeeperException, InterruptedException { return ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<List<ACL>>() { @Override public String toString() { return String.format("getACL (%s, stat = %s)", path, stat); } @Override public List<ACL> call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return PulsarZooKeeperClient.super.getACL(path, stat); } return zkHandle.getACL(path, stat); } }, operationRetryPolicy, rateLimiter, getACLStats); } @Override public void getACL(final String path, final Stat stat, final ACLCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getACLStats) { final ACLCallback aclCb = new ACLCallback() { @Override public void processResult(int rc, String path, Object ctx, List<ACL> acl, Stat stat) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, acl, stat); } } }; @Override public String toString() { return String.format("getACL (%s, stat = %s)", path, stat); } @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { PulsarZooKeeperClient.super.getACL(path, stat, aclCb, worker); } else { zkHandle.getACL(path, stat, aclCb, worker); } } }; // execute it immediately proc.run(); } @Override public Stat setACL(final String path, final List<ACL> acl, final int version) throws KeeperException, InterruptedException { return ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<Stat>() { @Override public String toString() { return String.format("setACL (%s, acl = %s, version = %d)", path, acl, version); } @Override public Stat call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return PulsarZooKeeperClient.super.setACL(path, acl, version); } return zkHandle.setACL(path, acl, version); } }, operationRetryPolicy, rateLimiter, setACLStats); } @Override public void setACL(final String path, final List<ACL> acl, final int version, final StatCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, setACLStats) { final StatCallback stCb = new StatCallback() { @Override public void processResult(int rc, String path, Object ctx, Stat stat) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, stat); } } }; @Override public String toString() { return String.format("setACL (%s, acl = %s, version = %d)", path, acl, version); } @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { PulsarZooKeeperClient.super.setACL(path, acl, version, stCb, worker); } else { zkHandle.setACL(path, acl, version, stCb, worker); } } }; // execute it immediately proc.run(); } @Override public void sync(final String path, final VoidCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, syncStats) { final VoidCallback vCb = new VoidCallback() { @Override public void processResult(int rc, String path, Object ctx) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context); } } }; @Override public String toString() { return String.format("sync (%s)", path); } @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { PulsarZooKeeperClient.super.sync(path, vCb, worker); } else { zkHandle.sync(path, vCb, worker); } } }; // execute it immediately proc.run(); } @Override public States getState() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return PulsarZooKeeperClient.super.getState(); } else { return zkHandle.getState(); } } @Override public String toString() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return PulsarZooKeeperClient.super.toString(); } else { return zkHandle.toString(); } } @Override public String create(final String path, final byte[] data, final List<ACL> acl, final CreateMode createMode) throws KeeperException, InterruptedException { return ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<String>() { @Override public String call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return PulsarZooKeeperClient.super.create(path, data, acl, createMode); } return zkHandle.create(path, data, acl, createMode); } @Override public String toString() { return String.format("create (%s, acl = %s, mode = %s)", path, acl, createMode); } }, operationRetryPolicy, rateLimiter, createStats); } @Override public void create(final String path, final byte[] data, final List<ACL> acl, final CreateMode createMode, final StringCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, createStats) { final StringCallback createCb = new StringCallback() { @Override public void processResult(int rc, String path, Object ctx, String name) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, name); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { PulsarZooKeeperClient.super.create(path, data, acl, createMode, createCb, worker); } else { zkHandle.create(path, data, acl, createMode, createCb, worker); } } @Override public String toString() { return String.format("create (%s, acl = %s, mode = %s)", path, acl, createMode); } }; // execute it immediately proc.run(); } @Override public void delete(final String path, final int version) throws KeeperException, InterruptedException { ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<Void>() { @Override public Void call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { PulsarZooKeeperClient.super.delete(path, version); } else { zkHandle.delete(path, version); } return null; } @Override public String toString() { return String.format("delete (%s, version = %d)", path, version); } }, operationRetryPolicy, rateLimiter, deleteStats); } @Override public void delete(final String path, final int version, final VoidCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, deleteStats) { final VoidCallback deleteCb = new VoidCallback() { @Override public void processResult(int rc, String path, Object ctx) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { PulsarZooKeeperClient.super.delete(path, version, deleteCb, worker); } else { zkHandle.delete(path, version, deleteCb, worker); } } @Override public String toString() { return String.format("delete (%s, version = %d)", path, version); } }; // execute it immediately proc.run(); } @Override public Stat exists(final String path, final Watcher watcher) throws KeeperException, InterruptedException { return ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<Stat>() { @Override public Stat call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return PulsarZooKeeperClient.super.exists(path, watcher); } return zkHandle.exists(path, watcher); } @Override public String toString() { return String.format("exists (%s, watcher = %s)", path, watcher); } }, operationRetryPolicy, rateLimiter, existsStats); } @Override public Stat exists(final String path, final boolean watch) throws KeeperException, InterruptedException { return ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<Stat>() { @Override public Stat call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return PulsarZooKeeperClient.super.exists(path, watch); } return zkHandle.exists(path, watch); } @Override public String toString() { return String.format("exists (%s, watcher = %s)", path, watch); } }, operationRetryPolicy, rateLimiter, existsStats); } @Override public void exists(final String path, final Watcher watcher, final StatCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, existsStats) { final StatCallback stCb = new StatCallback() { @Override public void processResult(int rc, String path, Object ctx, Stat stat) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, stat); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { PulsarZooKeeperClient.super.exists(path, watcher, stCb, worker); } else { zkHandle.exists(path, watcher, stCb, worker); } } @Override public String toString() { return String.format("exists (%s, watcher = %s)", path, watcher); } }; // execute it immediately proc.run(); } @Override public void exists(final String path, final boolean watch, final StatCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, existsStats) { final StatCallback stCb = new StatCallback() { @Override public void processResult(int rc, String path, Object ctx, Stat stat) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, stat); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { PulsarZooKeeperClient.super.exists(path, watch, stCb, worker); } else { zkHandle.exists(path, watch, stCb, worker); } } @Override public String toString() { return String.format("exists (%s, watcher = %s)", path, watch); } }; // execute it immediately proc.run(); } @Override public byte[] getData(final String path, final Watcher watcher, final Stat stat) throws KeeperException, InterruptedException { return ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<byte[]>() { @Override public byte[] call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return PulsarZooKeeperClient.super.getData(path, watcher, stat); } return zkHandle.getData(path, watcher, stat); } @Override public String toString() { return String.format("getData (%s, watcher = %s)", path, watcher); } }, operationRetryPolicy, rateLimiter, getStats); } @Override public byte[] getData(final String path, final boolean watch, final Stat stat) throws KeeperException, InterruptedException { return ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<byte[]>() { @Override public byte[] call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return PulsarZooKeeperClient.super.getData(path, watch, stat); } return zkHandle.getData(path, watch, stat); } @Override public String toString() { return String.format("getData (%s, watcher = %s)", path, watch); } }, operationRetryPolicy, rateLimiter, getStats); } @Override public void getData(final String path, final Watcher watcher, final DataCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getStats) { final DataCallback dataCb = new DataCallback() { @Override public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, data, stat); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { PulsarZooKeeperClient.super.getData(path, watcher, dataCb, worker); } else { zkHandle.getData(path, watcher, dataCb, worker); } } @Override public String toString() { return String.format("getData (%s, watcher = %s)", path, watcher); } }; // execute it immediately proc.run(); } @Override public void getData(final String path, final boolean watch, final DataCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getStats) { final DataCallback dataCb = new DataCallback() { @Override public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, data, stat); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { PulsarZooKeeperClient.super.getData(path, watch, dataCb, worker); } else { zkHandle.getData(path, watch, dataCb, worker); } } @Override public String toString() { return String.format("getData (%s, watcher = %s)", path, watch); } }; // execute it immediately proc.run(); } @Override public Stat setData(final String path, final byte[] data, final int version) throws KeeperException, InterruptedException { return ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<Stat>() { @Override public Stat call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return PulsarZooKeeperClient.super.setData(path, data, version); } return zkHandle.setData(path, data, version); } @Override public String toString() { return String.format("setData (%s, version = %d)", path, version); } }, operationRetryPolicy, rateLimiter, setStats); } @Override public void setData(final String path, final byte[] data, final int version, final StatCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, setStats) { final StatCallback stCb = new StatCallback() { @Override public void processResult(int rc, String path, Object ctx, Stat stat) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, stat); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { PulsarZooKeeperClient.super.setData(path, data, version, stCb, worker); } else { zkHandle.setData(path, data, version, stCb, worker); } } @Override public String toString() { return String.format("setData (%s, version = %d)", path, version); } }; // execute it immediately proc.run(); } @Override public void addWatch(String basePath, Watcher watcher, AddWatchMode mode) throws KeeperException, InterruptedException { ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<Void>() { @Override public Void call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { PulsarZooKeeperClient.super.addWatch(basePath, watcher, mode); } else { zkHandle.addWatch(basePath, watcher, mode); } return null; } @Override public String toString() { return String.format("addWatch (%s, mode = %s)", basePath, mode); } }, operationRetryPolicy, rateLimiter, setStats); } @Override public void addWatch(String basePath, Watcher watcher, AddWatchMode mode, VoidCallback cb, Object ctx) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, setStats) { final VoidCallback vCb = new VoidCallback() { @Override public void processResult(int rc, String path, Object ctx) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { vCb.processResult(rc, basePath, ctx); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { PulsarZooKeeperClient.super.addWatch(basePath, watcher, mode, cb, ctx); } else { zkHandle.addWatch(basePath, watcher, mode, cb, ctx); } } @Override public String toString() { return String.format("setData (%s, mode = %s)", basePath, mode.name()); } }; // execute it immediately proc.run(); } @Override public List<String> getChildren(final String path, final Watcher watcher, final Stat stat) throws KeeperException, InterruptedException { return ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<List<String>>() { @Override public List<String> call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return PulsarZooKeeperClient.super.getChildren(path, watcher, stat); } return zkHandle.getChildren(path, watcher, stat); } @Override public String toString() { return String.format("getChildren (%s, watcher = %s)", path, watcher); } }, operationRetryPolicy, rateLimiter, getChildrenStats); } @Override public List<String> getChildren(final String path, final boolean watch, final Stat stat) throws KeeperException, InterruptedException { return ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<List<String>>() { @Override public List<String> call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return PulsarZooKeeperClient.super.getChildren(path, watch, stat); } return zkHandle.getChildren(path, watch, stat); } @Override public String toString() { return String.format("getChildren (%s, watcher = %s)", path, watch); } }, operationRetryPolicy, rateLimiter, getChildrenStats); } @Override public void getChildren(final String path, final Watcher watcher, final Children2Callback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getChildrenStats) { final Children2Callback childCb = new Children2Callback() { @Override public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, children, stat); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { PulsarZooKeeperClient.super.getChildren(path, watcher, childCb, worker); } else { zkHandle.getChildren(path, watcher, childCb, worker); } } @Override public String toString() { return String.format("getChildren (%s, watcher = %s)", path, watcher); } }; // execute it immediately proc.run(); } @Override public void getChildren(final String path, final boolean watch, final Children2Callback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getChildrenStats) { final Children2Callback childCb = new Children2Callback() { @Override public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, children, stat); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { PulsarZooKeeperClient.super.getChildren(path, watch, childCb, worker); } else { zkHandle.getChildren(path, watch, childCb, worker); } } @Override public String toString() { return String.format("getChildren (%s, watcher = %s)", path, watch); } }; // execute it immediately proc.run(); } @Override public List<String> getChildren(final String path, final Watcher watcher) throws KeeperException, InterruptedException { return ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<List<String>>() { @Override public List<String> call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return PulsarZooKeeperClient.super.getChildren(path, watcher); } return zkHandle.getChildren(path, watcher); } @Override public String toString() { return String.format("getChildren (%s, watcher = %s)", path, watcher); } }, operationRetryPolicy, rateLimiter, getChildrenStats); } @Override public List<String> getChildren(final String path, final boolean watch) throws KeeperException, InterruptedException { return ZooWorker.syncCallWithRetries(this, new ZooWorker.ZooCallable<List<String>>() { @Override public List<String> call() throws KeeperException, InterruptedException { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { return PulsarZooKeeperClient.super.getChildren(path, watch); } return zkHandle.getChildren(path, watch); } @Override public String toString() { return String.format("getChildren (%s, watcher = %s)", path, watch); } }, operationRetryPolicy, rateLimiter, getChildrenStats); } @Override public void getChildren(final String path, final Watcher watcher, final ChildrenCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getChildrenStats) { final ChildrenCallback childCb = new ChildrenCallback() { @Override public void processResult(int rc, String path, Object ctx, List<String> children) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, children); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { PulsarZooKeeperClient.super.getChildren(path, watcher, childCb, worker); } else { zkHandle.getChildren(path, watcher, childCb, worker); } } @Override public String toString() { return String.format("getChildren (%s, watcher = %s)", path, watcher); } }; // execute it immediately proc.run(); } @Override public void getChildren(final String path, final boolean watch, final ChildrenCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getChildrenStats) { final ChildrenCallback childCb = new ChildrenCallback() { @Override public void processResult(int rc, String path, Object ctx, List<String> children) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, children); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { PulsarZooKeeperClient.super.getChildren(path, watch, childCb, worker); } else { zkHandle.getChildren(path, watch, childCb, worker); } } @Override public String toString() { return String.format("getChildren (%s, watcher = %s)", path, watch); } }; // execute it immediately proc.run(); } @Slf4j static final class ZooWorker { int attempts = 0; long startTimeNanos; long elapsedTimeMs = 0L; final RetryPolicy retryPolicy; final OpStatsLogger statsLogger; ZooWorker(RetryPolicy retryPolicy, OpStatsLogger statsLogger) { this.retryPolicy = retryPolicy; this.statsLogger = statsLogger; this.startTimeNanos = MathUtils.nowInNano(); } public boolean allowRetry(int rc) { elapsedTimeMs = MathUtils.elapsedMSec(startTimeNanos); if (!ZooWorker.isRecoverableException(rc)) { if (KeeperException.Code.OK.intValue() == rc) { statsLogger.registerSuccessfulEvent(MathUtils.elapsedMicroSec(startTimeNanos), TimeUnit.MICROSECONDS); } else { statsLogger.registerFailedEvent(MathUtils.elapsedMicroSec(startTimeNanos), TimeUnit.MICROSECONDS); } return false; } ++attempts; return retryPolicy.allowRetry(attempts, elapsedTimeMs); } public long nextRetryWaitTime() { return retryPolicy.nextRetryWaitTime(attempts, elapsedTimeMs); } /** * Check whether the given result code is recoverable by retry. * * @param rc result code * @return true if given result code is recoverable. */ public static boolean isRecoverableException(int rc) { return KeeperException.Code.CONNECTIONLOSS.intValue() == rc || KeeperException.Code.OPERATIONTIMEOUT.intValue() == rc || KeeperException.Code.SESSIONMOVED.intValue() == rc || KeeperException.Code.SESSIONEXPIRED.intValue() == rc; } /** * Check whether the given exception is recoverable by retry. * * @param exception given exception * @return true if given exception is recoverable. */ public static boolean isRecoverableException(KeeperException exception) { return isRecoverableException(exception.code().intValue()); } interface ZooCallable<T> { /** * Be compatible with ZooKeeper interface. * * @return value * @throws InterruptedException * @throws KeeperException */ T call() throws InterruptedException, KeeperException; } /** * Execute a sync zookeeper operation with a given retry policy. * * @param client * ZooKeeper client. * @param proc * Synchronous zookeeper operation wrapped in a {@link Callable}. * @param retryPolicy * Retry policy to execute the synchronous operation. * @param rateLimiter * Rate limiter for zookeeper calls * @param statsLogger * Stats Logger for zookeeper client. * @return result of the zookeeper operation * @throws KeeperException any non-recoverable exception or recoverable exception exhausted all retires. * @throws InterruptedException the operation is interrupted. */ public static<T> T syncCallWithRetries(PulsarZooKeeperClient client, ZooWorker.ZooCallable<T> proc, RetryPolicy retryPolicy, RateLimiter rateLimiter, OpStatsLogger statsLogger) throws KeeperException, InterruptedException { T result = null; boolean isDone = false; int attempts = 0; long startTimeNanos = MathUtils.nowInNano(); while (!isDone) { try { if (null != client) { client.waitForConnection(); } log.debug("Execute {} at {} retry attempt.", proc, attempts); if (null != rateLimiter) { rateLimiter.acquire(); } result = proc.call(); isDone = true; statsLogger.registerSuccessfulEvent(MathUtils.elapsedMicroSec(startTimeNanos), TimeUnit.MICROSECONDS); } catch (KeeperException e) { ++attempts; boolean rethrow = true; long elapsedTime = MathUtils.elapsedMSec(startTimeNanos); if (((null != client && isRecoverableException(e)) || null == client) && retryPolicy.allowRetry(attempts, elapsedTime)) { rethrow = false; } if (rethrow) { statsLogger.registerFailedEvent(MathUtils.elapsedMicroSec(startTimeNanos), TimeUnit.MICROSECONDS); log.debug("Stopped executing {} after {} attempts.", proc, attempts); throw e; } TimeUnit.MILLISECONDS.sleep(retryPolicy.nextRetryWaitTime(attempts, elapsedTime)); } } return result; } } }
/** * 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 com.alibaba.jstorm.cluster; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.curator.framework.CuratorFramework; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.Watcher.Event.EventType; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import backtype.storm.Config; import com.alibaba.jstorm.cache.JStormCache; import com.alibaba.jstorm.callback.ClusterStateCallback; import com.alibaba.jstorm.callback.WatcherCallBack; import com.alibaba.jstorm.utils.JStormUtils; import com.alibaba.jstorm.utils.PathUtils; import com.alibaba.jstorm.zk.Zookeeper; /** * All ZK interface implementation * * @author yannian.mu * */ public class DistributedClusterState implements ClusterState { private static Logger LOG = LoggerFactory.getLogger(DistributedClusterState.class); private Zookeeper zkobj = new Zookeeper(); private CuratorFramework zk; private WatcherCallBack watcher; /** * why run all callbacks, when receive one event */ private ConcurrentHashMap<UUID, ClusterStateCallback> callbacks = new ConcurrentHashMap<UUID, ClusterStateCallback>(); private Map<Object, Object> conf; private AtomicBoolean active; private JStormCache zkCache; public DistributedClusterState(Map<Object, Object> _conf) throws Exception { conf = _conf; // just mkdir STORM_ZOOKEEPER_ROOT dir CuratorFramework _zk = mkZk(); String path = String.valueOf(conf.get(Config.STORM_ZOOKEEPER_ROOT)); zkobj.mkdirs(_zk, path); _zk.close(); active = new AtomicBoolean(true); watcher = new WatcherCallBack() { @Override public void execute(KeeperState state, EventType type, String path) { if (active.get()) { if (!(state.equals(KeeperState.SyncConnected))) { LOG.warn("Received event " + state + ":" + type + ":" + path + " with disconnected Zookeeper."); } else { LOG.info("Received event " + state + ":" + type + ":" + path); } if (!type.equals(EventType.None)) { for (Entry<UUID, ClusterStateCallback> e : callbacks.entrySet()) { ClusterStateCallback fn = e.getValue(); fn.execute(type, path); } } } } }; zk = null; zk = mkZk(watcher); } @SuppressWarnings("unchecked") private CuratorFramework mkZk() throws IOException { return zkobj.mkClient(conf, (List<String>) conf.get(Config.STORM_ZOOKEEPER_SERVERS), conf.get(Config.STORM_ZOOKEEPER_PORT), ""); } @SuppressWarnings("unchecked") private CuratorFramework mkZk(WatcherCallBack watcher) throws NumberFormatException, IOException { return zkobj.mkClient(conf, (List<String>) conf.get(Config.STORM_ZOOKEEPER_SERVERS), conf.get(Config.STORM_ZOOKEEPER_PORT), String.valueOf(conf.get(Config.STORM_ZOOKEEPER_ROOT)), watcher); } @Override public void close() { this.active.set(false); zk.close(); } @Override public void delete_node(String path) throws Exception { if (zkCache != null) { zkCache.remove(path); } zkobj.deletereRcursive(zk, path); } @Override public List<String> get_children(String path, boolean watch) throws Exception { return zkobj.getChildren(zk, path, watch); } @Override public byte[] get_data(String path, boolean watch) throws Exception { byte[] ret = null; if (watch == false && zkCache != null) { ret = (byte[]) zkCache.get(path); } if (ret != null) { return ret; } ret = zkobj.getData(zk, path, watch); if (zkCache != null) { zkCache.put(path, ret); } return ret; } /** * warning, get_version don't use zkCache avoid to conflict with get_data * @param path * @param watch * @return * @throws Exception */ @Override public Integer get_version(String path, boolean watch) throws Exception { Integer ret = zkobj.getVersion(zk, path, watch); return ret; } @Override public byte[] get_data_sync(String path, boolean watch) throws Exception { byte[] ret = null; ret = zkobj.getData(zk, path, watch); if (zkCache != null && ret != null) { zkCache.put(path, ret); } return ret; } @Override public void sync_path(String path) throws Exception { zkobj.syncPath(zk, path); } @Override public void mkdirs(String path) throws Exception { zkobj.mkdirs(zk, path); } @Override public void set_data(String path, byte[] data) throws Exception { if (data.length > (JStormUtils.SIZE_1_K * 800)) { throw new Exception("Writing 800k+ data into ZK is not allowed!, data size is " + data.length); } if (zkobj.exists(zk, path, false)) { zkobj.setData(zk, path, data); } else { zkobj.mkdirs(zk, PathUtils.parent_path(path)); zkobj.createNode(zk, path, data, CreateMode.PERSISTENT); } if (zkCache != null) { zkCache.put(path, data); } } @Override public void set_ephemeral_node(String path, byte[] data) throws Exception { zkobj.mkdirs(zk, PathUtils.parent_path(path)); if (zkobj.exists(zk, path, false)) { zkobj.setData(zk, path, data); } else { zkobj.createNode(zk, path, data, CreateMode.EPHEMERAL); } if (zkCache != null) { zkCache.put(path, data); } } @Override public UUID register(ClusterStateCallback callback) { UUID id = UUID.randomUUID(); this.callbacks.put(id, callback); return id; } @Override public ClusterStateCallback unregister(UUID id) { return this.callbacks.remove(id); } @Override public boolean node_existed(String path, boolean watch) throws Exception { // TODO Auto-generated method stub return zkobj.existsNode(zk, path, watch); } @Override public void tryToBeLeader(String path, byte[] host) throws Exception { // TODO Auto-generated method stub zkobj.createNode(zk, path, host, CreateMode.EPHEMERAL); } public JStormCache getZkCache() { return zkCache; } public void setZkCache(JStormCache zkCache) { this.zkCache = zkCache; } }
/* * 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.catalina.authenticator; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.Principal; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.connector.Request; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.codec.binary.Base64; /** * An <b>Authenticator</b> and <b>Valve</b> implementation of HTTP BASIC * Authentication, as outlined in RFC 2617: "HTTP Authentication: Basic * and Digest Access Authentication." * * @author Craig R. McClanahan */ public class BasicAuthenticator extends AuthenticatorBase { private static final Log log = LogFactory.getLog(BasicAuthenticator.class); // --------------------------------------------------------- Public Methods /** * Authenticate the user making this request, based on the specified * login configuration. Return <code>true</code> if any specified * constraint has been satisfied, or <code>false</code> if we have * created a response challenge already. * * @param request Request we are processing * @param response Response we are creating * * @exception IOException if an input/output error occurs */ @Override public boolean authenticate(Request request, HttpServletResponse response) throws IOException { // Have we already authenticated someone? Principal principal = request.getUserPrincipal(); String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE); if (principal != null) { if (log.isDebugEnabled()) { log.debug("Already authenticated '" + principal.getName() + "'"); } // Associate the session with any existing SSO session if (ssoId != null) { associate(ssoId, request.getSessionInternal(true)); } return (true); } // Is there an SSO session against which we can try to reauthenticate? if (ssoId != null) { if (log.isDebugEnabled()) { log.debug("SSO Id " + ssoId + " set; attempting " + "reauthentication"); } /* Try to reauthenticate using data cached by SSO. If this fails, either the original SSO logon was of DIGEST or SSL (which we can't reauthenticate ourselves because there is no cached username and password), or the realm denied the user's reauthentication for some reason. In either case we have to prompt the user for a logon */ if (reauthenticateFromSSO(ssoId, request)) { return true; } } // Validate any credentials already included with this request MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders() .getValue("authorization"); if (authorization != null) { authorization.toBytes(); ByteChunk authorizationBC = authorization.getByteChunk(); BasicCredentials credentials = null; try { credentials = new BasicCredentials(authorizationBC); String username = credentials.getUsername(); String password = credentials.getPassword(); principal = context.getRealm().authenticate(username, password); if (principal != null) { register(request, response, principal, HttpServletRequest.BASIC_AUTH, username, password); return (true); } } catch (IllegalArgumentException iae) { if (log.isDebugEnabled()) { log.debug("Invalid Authorization" + iae.getMessage()); } } } // the request could not be authenticated, so reissue the challenge StringBuilder value = new StringBuilder(16); value.append("Basic realm=\""); value.append(getRealmName(context)); value.append('\"'); response.setHeader(AUTH_HEADER_NAME, value.toString()); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return (false); } @Override protected String getAuthMethod() { return HttpServletRequest.BASIC_AUTH; } /** * Parser for an HTTP Authorization header for BASIC authentication * as per RFC 2617 section 2, and the Base64 encoded credentials as * per RFC 2045 section 6.8. */ protected static class BasicCredentials { // the only authentication method supported by this parser // note: we include single white space as its delimiter private static final String METHOD = "basic "; private ByteChunk authorization; private int initialOffset; private int base64blobOffset; private int base64blobLength; private String username = null; private String password = null; /** * Parse the HTTP Authorization header for BASIC authentication * as per RFC 2617 section 2, and the Base64 encoded credentials * as per RFC 2045 section 6.8. * * @param input The header value to parse in-place * * @throws IllegalArgumentException If the header does not conform * to RFC 2617 */ public BasicCredentials(ByteChunk input) throws IllegalArgumentException { authorization = input; initialOffset = input.getOffset(); parseMethod(); byte[] decoded = parseBase64(); parseCredentials(decoded); } /** * Trivial accessor. * * @return the decoded username token as a String, which is * never be <code>null</code>, but can be empty. */ public String getUsername() { return username; } /** * Trivial accessor. * * @return the decoded password token as a String, or <code>null</code> * if no password was found in the credentials. */ public String getPassword() { return password; } /* * The authorization method string is case-insensitive and must * hae at least one space character as a delimiter. */ private void parseMethod() throws IllegalArgumentException { if (authorization.startsWithIgnoreCase(METHOD, 0)) { // step past the auth method name base64blobOffset = initialOffset + METHOD.length(); base64blobLength = authorization.getLength() - METHOD.length(); } else { // is this possible, or permitted? throw new IllegalArgumentException( "Authorization header method is not \"Basic\""); } } /* * Decode the base64-user-pass token, which RFC 2617 states * can be longer than the 76 characters per line limit defined * in RFC 2045. The base64 decoder will ignore embedded line * break characters as well as surplus surrounding white space. */ private byte[] parseBase64() throws IllegalArgumentException { byte[] decoded = Base64.decodeBase64( authorization.getBuffer(), base64blobOffset, base64blobLength); // restore original offset authorization.setOffset(initialOffset); if (decoded == null) { throw new IllegalArgumentException( "Basic Authorization credentials are not Base64"); } return decoded; } /* * Extract the mandatory username token and separate it from the * optional password token. Tolerate surplus surrounding white space. */ private void parseCredentials(byte[] decoded) throws IllegalArgumentException { int colon = -1; for (int i = 0; i < decoded.length; i++) { if (decoded[i] == ':') { colon = i; break; } } if (colon < 0) { username = new String(decoded, StandardCharsets.ISO_8859_1); // password will remain null! } else { username = new String( decoded, 0, colon, StandardCharsets.ISO_8859_1); password = new String( decoded, colon + 1, decoded.length - colon - 1, StandardCharsets.ISO_8859_1); // tolerate surplus white space around credentials if (password.length() > 1) { password = password.trim(); } } // tolerate surplus white space around credentials if (username.length() > 1) { username = username.trim(); } } } }
/* * Copyright 2012-present Facebook, Inc. * * 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.facebook.buck.shell; import static com.facebook.buck.testutil.MoreAsserts.assertIterablesEquals; import static java.util.Collections.singleton; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertThat; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.BuildTargetFactory; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.DefaultBuildTargetSourcePath; import com.facebook.buck.rules.DefaultSourcePathResolver; import com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer; import com.facebook.buck.rules.FakeBuildContext; import com.facebook.buck.rules.FakeBuildRule; import com.facebook.buck.rules.FakeBuildableContext; import com.facebook.buck.rules.FakeSourcePath; import com.facebook.buck.rules.PathSourcePath; import com.facebook.buck.rules.RuleKey; import com.facebook.buck.rules.SingleThreadedBuildRuleResolver; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.rules.SourcePathResolver; import com.facebook.buck.rules.SourcePathRuleFinder; import com.facebook.buck.rules.TargetGraph; import com.facebook.buck.rules.keys.DefaultRuleKeyFactory; import com.facebook.buck.step.Step; import com.facebook.buck.step.TestExecutionContext; import com.facebook.buck.testutil.FakeProjectFilesystem; import com.facebook.buck.testutil.MoreAsserts; import com.facebook.buck.util.HumanReadableException; import com.facebook.buck.util.cache.FileHashCache; import com.facebook.buck.util.cache.FileHashCacheMode; import com.facebook.buck.util.cache.impl.DefaultFileHashCache; import com.facebook.buck.util.cache.impl.StackedFileHashCache; import com.google.common.collect.ImmutableList; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class ExportFileTest { private ProjectFilesystem projectFilesystem; private BuildTarget target; @Rule public ExpectedException expectedException = ExpectedException.none(); @Before public void createFixtures() throws InterruptedException { projectFilesystem = FakeProjectFilesystem.createJavaOnlyFilesystem(); target = BuildTargetFactory.newInstance(projectFilesystem.getRootPath(), "//:example.html"); } @Test public void shouldSetSrcAndOutToNameParameterIfNeitherAreSet() throws Exception { BuildRuleResolver resolver = new SingleThreadedBuildRuleResolver( TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()); SourcePathResolver pathResolver = DefaultSourcePathResolver.from(new SourcePathRuleFinder(resolver)); ExportFile exportFile = new ExportFileBuilder(target).build(resolver, projectFilesystem); List<Step> steps = exportFile.getBuildSteps( FakeBuildContext.withSourcePathResolver(pathResolver) .withBuildCellRootPath(projectFilesystem.getRootPath()), new FakeBuildableContext()); MoreAsserts.assertSteps( "The output directory should be created and then the file should be copied there.", ImmutableList.of( "mkdir -p " + Paths.get("buck-out/gen"), "rm -f -r " + Paths.get("buck-out/gen/example.html"), "cp " + projectFilesystem.resolve("example.html") + " " + Paths.get("buck-out/gen/example.html")), steps, TestExecutionContext.newInstance()); assertEquals( projectFilesystem.getBuckPaths().getGenDir().resolve("example.html"), pathResolver.getRelativePath(exportFile.getSourcePathToOutput())); } @Test public void shouldSetOutToNameParamValueIfSrcIsSet() throws Exception { BuildRuleResolver resolver = new SingleThreadedBuildRuleResolver( TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()); SourcePathResolver pathResolver = DefaultSourcePathResolver.from(new SourcePathRuleFinder(resolver)); ExportFile exportFile = new ExportFileBuilder(target).setOut("fish").build(resolver, projectFilesystem); List<Step> steps = exportFile.getBuildSteps( FakeBuildContext.withSourcePathResolver(pathResolver) .withBuildCellRootPath(projectFilesystem.getRootPath()), new FakeBuildableContext()); MoreAsserts.assertSteps( "The output directory should be created and then the file should be copied there.", ImmutableList.of( "mkdir -p " + Paths.get("buck-out/gen"), "rm -f -r " + Paths.get("buck-out/gen/fish"), "cp " + projectFilesystem.resolve("example.html") + " " + Paths.get("buck-out/gen/fish")), steps, TestExecutionContext.newInstance()); assertEquals( projectFilesystem.getBuckPaths().getGenDir().resolve("fish"), pathResolver.getRelativePath(exportFile.getSourcePathToOutput())); } @Test public void shouldSetOutAndSrcAndNameParametersSeparately() throws Exception { BuildRuleResolver resolver = new SingleThreadedBuildRuleResolver( TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()); SourcePathResolver pathResolver = DefaultSourcePathResolver.from(new SourcePathRuleFinder(resolver)); ExportFile exportFile = new ExportFileBuilder(target) .setSrc(PathSourcePath.of(projectFilesystem, Paths.get("chips"))) .setOut("fish") .build(resolver, projectFilesystem); List<Step> steps = exportFile.getBuildSteps( FakeBuildContext.withSourcePathResolver(pathResolver) .withBuildCellRootPath(projectFilesystem.getRootPath()), new FakeBuildableContext()); MoreAsserts.assertSteps( "The output directory should be created and then the file should be copied there.", ImmutableList.of( "mkdir -p " + Paths.get("buck-out/gen"), "rm -f -r " + Paths.get("buck-out/gen/fish"), "cp " + projectFilesystem.resolve("chips") + " " + Paths.get("buck-out/gen/fish")), steps, TestExecutionContext.newInstance()); assertEquals( projectFilesystem.getBuckPaths().getGenDir().resolve("fish"), pathResolver.getRelativePath(exportFile.getSourcePathToOutput())); } @Test public void shouldSetInputsFromSourcePaths() throws Exception { ExportFileBuilder builder = new ExportFileBuilder(target).setSrc(FakeSourcePath.of("chips")).setOut("cake"); BuildRuleResolver resolver = new SingleThreadedBuildRuleResolver( TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()); SourcePathResolver pathResolver = DefaultSourcePathResolver.from(new SourcePathRuleFinder(resolver)); ExportFile exportFile = builder.build(resolver, projectFilesystem); assertIterablesEquals( singleton(Paths.get("chips")), pathResolver.filterInputsToCompareToOutput(exportFile.getSource())); resolver = new SingleThreadedBuildRuleResolver( TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()); pathResolver = DefaultSourcePathResolver.from(new SourcePathRuleFinder(resolver)); FakeBuildRule rule = resolver.addToIndex(new FakeBuildRule(BuildTargetFactory.newInstance("//example:one"))); builder.setSrc(DefaultBuildTargetSourcePath.of(rule.getBuildTarget())); exportFile = builder.build(resolver, projectFilesystem); assertThat( pathResolver.filterInputsToCompareToOutput(exportFile.getSource()), Matchers.empty()); resolver = new SingleThreadedBuildRuleResolver( TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()); pathResolver = DefaultSourcePathResolver.from(new SourcePathRuleFinder(resolver)); builder.setSrc(null); exportFile = builder.build(resolver, projectFilesystem); assertIterablesEquals( singleton(projectFilesystem.getPath("example.html")), pathResolver.filterInputsToCompareToOutput(exportFile.getSource())); } @Test public void getOutputName() throws Exception { ExportFile exportFile = new ExportFileBuilder(target) .setOut("cake") .build( new SingleThreadedBuildRuleResolver( TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()), projectFilesystem); assertEquals("cake", exportFile.getOutputName()); } @Test public void modifyingTheContentsOfTheFileChangesTheRuleKey() throws Exception { Path root = Files.createTempDirectory("root"); FakeProjectFilesystem filesystem = new FakeProjectFilesystem(root); Path temp = Paths.get("example_file"); FileHashCache hashCache = new StackedFileHashCache( ImmutableList.of( DefaultFileHashCache.createDefaultFileHashCache( filesystem, FileHashCacheMode.DEFAULT))); SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder( new SingleThreadedBuildRuleResolver( TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer())); SourcePathResolver resolver = DefaultSourcePathResolver.from(ruleFinder); DefaultRuleKeyFactory ruleKeyFactory = new DefaultRuleKeyFactory(0, hashCache, resolver, ruleFinder); filesystem.writeContentsToPath("I like cheese", temp); ExportFileBuilder builder = new ExportFileBuilder(BuildTargetFactory.newInstance("//some:file")) .setSrc(PathSourcePath.of(filesystem, temp)); ExportFile rule = builder.build( new SingleThreadedBuildRuleResolver( TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()), filesystem); RuleKey original = ruleKeyFactory.build(rule); filesystem.writeContentsToPath("I really like cheese", temp); // Create a new rule. The FileHashCache held by the existing rule will retain a reference to the // previous content of the file, so we need to create an identical rule. rule = builder.build( new SingleThreadedBuildRuleResolver( TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()), filesystem); hashCache = new StackedFileHashCache( ImmutableList.of( DefaultFileHashCache.createDefaultFileHashCache( filesystem, FileHashCacheMode.DEFAULT))); ruleFinder = new SourcePathRuleFinder( new SingleThreadedBuildRuleResolver( TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer())); resolver = DefaultSourcePathResolver.from(ruleFinder); ruleKeyFactory = new DefaultRuleKeyFactory(0, hashCache, resolver, ruleFinder); RuleKey refreshed = ruleKeyFactory.build(rule); assertNotEquals(original, refreshed); } @Test public void referenceModeUsesUnderlyingSourcePath() throws Exception { BuildRuleResolver resolver = new SingleThreadedBuildRuleResolver( TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()); SourcePathResolver pathResolver = DefaultSourcePathResolver.from(new SourcePathRuleFinder(resolver)); SourcePath src = FakeSourcePath.of(projectFilesystem, "source"); ExportFile exportFile = new ExportFileBuilder(target) .setMode(ExportFileDescription.Mode.REFERENCE) .setSrc(src) .build(resolver, projectFilesystem); assertThat( pathResolver.getRelativePath(exportFile.getSourcePathToOutput()), Matchers.equalTo(pathResolver.getRelativePath(src))); } @Test public void referenceModeRequiresSameFilesystem() throws Exception { BuildRuleResolver resolver = new SingleThreadedBuildRuleResolver( TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()); ProjectFilesystem differentFilesystem = new FakeProjectFilesystem(); SourcePath src = FakeSourcePath.of(differentFilesystem, "source"); expectedException.expect(HumanReadableException.class); expectedException.expectMessage(Matchers.containsString("must use `COPY` mode")); new ExportFileBuilder(target) .setMode(ExportFileDescription.Mode.REFERENCE) .setSrc(src) .build(resolver, projectFilesystem); } @Test public void referenceModeDoesNotAcceptOutParameter() throws Exception { BuildRuleResolver resolver = new SingleThreadedBuildRuleResolver( TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()); expectedException.expect(HumanReadableException.class); expectedException.expectMessage(Matchers.containsString("must not set `out`")); new ExportFileBuilder(target) .setOut("out") .setMode(ExportFileDescription.Mode.REFERENCE) .build(resolver, projectFilesystem); } }
/* * 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.commons.beanutils2.bugs; import org.apache.commons.beanutils2.PropertyUtils; import org.apache.commons.beanutils2.bugs.other.Jira18BeanFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Test case for Jira issue# BEANUTILS-18. * <p>This test case demonstrates the issue. * * @see <a href="https://issues.apache.org/jira/browse/BEANUTILS-18">https://issues.apache.org/jira/browse/BEANUTILS-18</a> */ public class Jira18TestCase extends TestCase { private final Log log = LogFactory.getLog(Jira18TestCase.class); private Object bean; /** * Create a test case with the specified name. * * @param name The name of the test */ public Jira18TestCase(final String name) { super(name); } /** * Run the Test. * * @param args Arguments */ public static void main(final String[] args) { junit.textui.TestRunner.run(suite()); } /** * Create a test suite for this test. * * @return a test suite */ public static Test suite() { return new TestSuite(Jira18TestCase.class); } /** * Sets up. * * @throws java.lang.Exception */ @Override protected void setUp() throws Exception { super.setUp(); bean = Jira18BeanFactory.createBean(); } /** * Tear Down. * * @throws java.lang.Exception */ @Override protected void tearDown() throws Exception { super.tearDown(); } /** * Test {@link PropertyUtils#isReadable(Object, String)} * for simple properties. */ public void testIssue_BEANUTILS_18_PropertyUtils_isReadable() { boolean result = false; try { result = PropertyUtils.isReadable(bean, "simple"); } catch (final Throwable t) { log.error("ERROR " + t, t); fail("Threw exception: " + t); } assertFalse("PropertyUtils.isReadable(bean, \"simple\") returned true", result); } /** * Test {@link PropertyUtils#isWriteable(Object, String)} * for simple properties. */ public void testIssue_BEANUTILS_18_PropertyUtils_isWriteable() { boolean result = false; try { result = PropertyUtils.isWriteable(bean, "simple"); } catch (final Throwable t) { log.error("ERROR " + t, t); fail("Threw exception: " + t); } assertFalse("PropertyUtils.isWriteable(bean, \"simple\") returned true", result); } /** * Test {@link PropertyUtils#isReadable(Object, String)} * for indexed properties. */ public void testIssue_BEANUTILS_18_PropertyUtils_isReadable_Indexed() { boolean result = false; try { result = PropertyUtils.isReadable(bean, "indexed"); } catch (final Throwable t) { log.error("ERROR " + t, t); fail("Threw exception: " + t); } assertFalse("PropertyUtils.isReadable(bean, \"indexed\") returned true", result); } /** * Test {@link PropertyUtils#isWriteable(Object, String)} * for indexed properties. */ public void testIssue_BEANUTILS_18_PropertyUtils_isWriteable_Indexed() { boolean result = false; try { result = PropertyUtils.isWriteable(bean, "indexed"); } catch (final Throwable t) { log.error("ERROR " + t, t); fail("Threw exception: " + t); } assertFalse("PropertyUtils.isWriteable(bean, \"indexed\") returned true", result); } /** * Test {@link PropertyUtils#isReadable(Object, String)} * for Mapped properties. */ public void testIssue_BEANUTILS_18_PropertyUtils_isReadable_Mapped() { boolean result = false; try { result = PropertyUtils.isReadable(bean, "mapped"); } catch (final Throwable t) { log.error("ERROR " + t, t); fail("Threw exception: " + t); } assertFalse("PropertyUtils.isReadable(bean, \"mapped\") returned true", result); } /** * Test {@link PropertyUtils#isWriteable(Object, String)} * for Mapped properties. */ public void testIssue_BEANUTILS_18_PropertyUtils_isWriteable_Mapped() { boolean result = false; try { result = PropertyUtils.isWriteable(bean, "mapped"); } catch (final Throwable t) { log.error("ERROR " + t, t); fail("Threw exception: " + t); } assertFalse("PropertyUtils.isWriteable(bean, \"mapped\") returned true", result); } /** * Test {@link PropertyUtils#getProperty(Object, String)} * for simple properties. */ public void testIssue_BEANUTILS_18_PropertyUtils_getProperty() { boolean threwNoSuchMethodException = false; Object result = null; try { result = PropertyUtils.getProperty(bean, "simple"); } catch (final NoSuchMethodException ex) { threwNoSuchMethodException = true; // expected result } catch (final Throwable t) { log.error("ERROR " + t, t); fail("Threw exception: " + t); } assertTrue("Expected NoSuchMethodException but returned '" + result + "'", threwNoSuchMethodException); } /** * Test {@link PropertyUtils#setProperty(Object, String, Object)} * for simple properties. */ public void testIssue_BEANUTILS_18_PropertyUtils_setProperty() { boolean threwNoSuchMethodException = false; try { PropertyUtils.setProperty(bean, "simple", "BAR"); } catch (final NoSuchMethodException ex) { threwNoSuchMethodException = true; // expected result } catch (final Throwable t) { log.error("ERROR " + t, t); fail("Threw exception: " + t); } assertTrue("Expected NoSuchMethodException", threwNoSuchMethodException); } /** * Test {@link PropertyUtils#getProperty(Object, String)} * for indexed properties. */ public void testIssue_BEANUTILS_18_PropertyUtils_getProperty_Indexed() { boolean threwNoSuchMethodException = false; Object result = null; try { result = PropertyUtils.getProperty(bean, "indexed[0]"); } catch (final NoSuchMethodException ex) { threwNoSuchMethodException = true; // expected result } catch (final Throwable t) { log.error("ERROR " + t, t); fail("Threw exception: " + t); } assertTrue("Expected NoSuchMethodException but returned '" + result + "'", threwNoSuchMethodException); } /** * Test {@link PropertyUtils#setProperty(Object, String, Object)} * for indexed properties. */ public void testIssue_BEANUTILS_18_PropertyUtils_setProperty_Indexed() { boolean threwNoSuchMethodException = false; try { PropertyUtils.setProperty(bean, "indexed[0]", "BAR"); } catch (final NoSuchMethodException ex) { threwNoSuchMethodException = true; // expected result } catch (final Throwable t) { log.error("ERROR " + t, t); fail("Threw exception: " + t); } assertTrue("Expected NoSuchMethodException", threwNoSuchMethodException); } /** * Test {@link PropertyUtils#getProperty(Object, String)} * for mapped properties. */ public void testIssue_BEANUTILS_18_PropertyUtils_getProperty_Mapped() { boolean threwNoSuchMethodException = false; Object result = null; try { result = PropertyUtils.getProperty(bean, "mapped(foo-key)"); } catch (final NoSuchMethodException ex) { threwNoSuchMethodException = true; // expected result } catch (final Throwable t) { log.error("ERROR " + t, t); fail("Threw exception: " + t); } assertTrue("Expected NoSuchMethodException but returned '" + result + "'", threwNoSuchMethodException); } /** * Test {@link PropertyUtils#setProperty(Object, String, Object)} * for mapped properties. */ public void testIssue_BEANUTILS_18_PropertyUtils_setProperty_Mapped() { boolean threwNoSuchMethodException = false; try { PropertyUtils.setProperty(bean, "mapped(foo-key)", "BAR"); } catch (final NoSuchMethodException ex) { threwNoSuchMethodException = true; // expected result } catch (final Throwable t) { log.error("ERROR " + t, t); fail("Threw exception: " + t); } assertTrue("Expected NoSuchMethodException", threwNoSuchMethodException); } }
/** * Copyright (c) 2014-2015, Data Geekery GmbH, contact@datageekery.com * * 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.jooq.lambda; import org.junit.Test; import java.util.function.DoublePredicate; import java.util.function.IntPredicate; import java.util.function.LongPredicate; import java.util.function.Predicate; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.Stream; import static org.junit.Assert.*; /** * @author Lukas Eder */ public class CheckedPredicateTest { @Test public void testCheckedPredicate() { Predicate<Object> test = Unchecked.predicate( t -> { throw new Exception("" + t); } ); assertPredicate(test, UncheckedException.class); } @Test public void testCheckedPredicateWithCustomHandler() { Predicate<Object> test = Unchecked.predicate( t -> { throw new Exception("" + t); }, e -> { throw new IllegalStateException(e); } ); assertPredicate(test, IllegalStateException.class); } @Test public void testCheckedIntPredicate() { IntPredicate test = Unchecked.intPredicate( i -> { throw new Exception("" + i); } ); assertIntPredicate(test, UncheckedException.class); } @Test public void testCheckedIntPredicateWithCustomHandler() { IntPredicate test = Unchecked.intPredicate( i -> { throw new Exception("" + i); }, e -> { throw new IllegalStateException(e); } ); assertIntPredicate(test, IllegalStateException.class); } @Test public void testCheckedLongPredicate() { LongPredicate test = Unchecked.longPredicate( l -> { throw new Exception("" + l); } ); assertLongPredicate(test, UncheckedException.class); } @Test public void testCheckedLongPredicateWithCustomHandler() { LongPredicate test = Unchecked.longPredicate( l -> { throw new Exception("" + l); }, e -> { throw new IllegalStateException(e); } ); assertLongPredicate(test, IllegalStateException.class); } @Test public void testCheckedDoublePredicate() { DoublePredicate test = Unchecked.doublePredicate( d -> { throw new Exception("" + d); } ); assertDoublePredicate(test, UncheckedException.class); } @Test public void testCheckedDoublePredicateWithCustomHandler() { DoublePredicate test = Unchecked.doublePredicate( d -> { throw new Exception("" + d); }, e -> { throw new IllegalStateException(e); } ); assertDoublePredicate(test, IllegalStateException.class); } private <E extends RuntimeException> void assertPredicate(Predicate<Object> test, Class<E> type) { assertNotNull(test); try { test.test(null); fail(); } catch (RuntimeException e) { assertException(type, e, "null"); } try { Stream.of("a", "b", "c").filter(test); } catch (RuntimeException e) { assertException(type, e, "a"); } } private <E extends RuntimeException> void assertIntPredicate(IntPredicate test, Class<E> type) { assertNotNull(test); try { test.test(0); fail(); } catch (RuntimeException e) { assertException(type, e, "0"); } try { IntStream.of(1, 2, 3).filter(test); } catch (RuntimeException e) { assertException(type, e, "1"); } } private <E extends RuntimeException> void assertLongPredicate(LongPredicate test, Class<E> type) { assertNotNull(test); try { test.test(0L); fail(); } catch (RuntimeException e) { assertException(type, e, "0"); } try { LongStream.of(1L, 2L, 3L).filter(test); } catch (RuntimeException e) { assertException(type, e, "1"); } } private <E extends RuntimeException> void assertDoublePredicate(DoublePredicate test, Class<E> type) { assertNotNull(test); try { test.test(0.0); fail(); } catch (RuntimeException e) { assertException(type, e, "0.0"); } try { DoubleStream.of(1.0, 2.0, 3.0).filter(test); } catch (RuntimeException e) { assertException(type, e, "1.0"); } } private <E extends RuntimeException> void assertException(Class<E> type, RuntimeException e, String message) { assertEquals(type, e.getClass()); assertEquals(Exception.class, e.getCause().getClass()); assertEquals(message, e.getCause().getMessage()); } }
/* * Copyright 2021 Google LLC * * 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 com.google.cloud.securitycenter.settings.v1beta1; import static com.google.cloud.securitycenter.settings.v1beta1.SecurityCenterSettingsServiceClient.ListComponentsPagedResponse; import static com.google.cloud.securitycenter.settings.v1beta1.SecurityCenterSettingsServiceClient.ListDetectorsPagedResponse; import com.google.api.gax.core.NoCredentialsProvider; import com.google.api.gax.grpc.GaxGrpcProperties; import com.google.api.gax.grpc.testing.LocalChannelProvider; import com.google.api.gax.grpc.testing.MockGrpcService; import com.google.api.gax.grpc.testing.MockServiceHelper; import com.google.api.gax.rpc.ApiClientHeaderProvider; import com.google.api.gax.rpc.InvalidArgumentException; import com.google.common.collect.Lists; import com.google.protobuf.AbstractMessage; import com.google.protobuf.Empty; import com.google.protobuf.FieldMask; import com.google.protobuf.Timestamp; import io.grpc.StatusRuntimeException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.UUID; import javax.annotation.Generated; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; @Generated("by gapic-generator-java") public class SecurityCenterSettingsServiceClientTest { private static MockSecurityCenterSettingsService mockSecurityCenterSettingsService; private static MockServiceHelper mockServiceHelper; private LocalChannelProvider channelProvider; private SecurityCenterSettingsServiceClient client; @BeforeClass public static void startStaticServer() { mockSecurityCenterSettingsService = new MockSecurityCenterSettingsService(); mockServiceHelper = new MockServiceHelper( UUID.randomUUID().toString(), Arrays.<MockGrpcService>asList(mockSecurityCenterSettingsService)); mockServiceHelper.start(); } @AfterClass public static void stopServer() { mockServiceHelper.stop(); } @Before public void setUp() throws IOException { mockServiceHelper.reset(); channelProvider = mockServiceHelper.createChannelProvider(); SecurityCenterSettingsServiceSettings settings = SecurityCenterSettingsServiceSettings.newBuilder() .setTransportChannelProvider(channelProvider) .setCredentialsProvider(NoCredentialsProvider.create()) .build(); client = SecurityCenterSettingsServiceClient.create(settings); } @After public void tearDown() throws Exception { client.close(); } @Test public void getServiceAccountTest() throws Exception { ServiceAccount expectedResponse = ServiceAccount.newBuilder() .setName(ServiceAccountName.of("[ORGANIZATION]").toString()) .setServiceAccount("serviceAccount1079137720") .build(); mockSecurityCenterSettingsService.addResponse(expectedResponse); ServiceAccountName name = ServiceAccountName.of("[ORGANIZATION]"); ServiceAccount actualResponse = client.getServiceAccount(name); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockSecurityCenterSettingsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); GetServiceAccountRequest actualRequest = ((GetServiceAccountRequest) actualRequests.get(0)); Assert.assertEquals(name.toString(), actualRequest.getName()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void getServiceAccountExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockSecurityCenterSettingsService.addException(exception); try { ServiceAccountName name = ServiceAccountName.of("[ORGANIZATION]"); client.getServiceAccount(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void getServiceAccountTest2() throws Exception { ServiceAccount expectedResponse = ServiceAccount.newBuilder() .setName(ServiceAccountName.of("[ORGANIZATION]").toString()) .setServiceAccount("serviceAccount1079137720") .build(); mockSecurityCenterSettingsService.addResponse(expectedResponse); String name = "name3373707"; ServiceAccount actualResponse = client.getServiceAccount(name); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockSecurityCenterSettingsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); GetServiceAccountRequest actualRequest = ((GetServiceAccountRequest) actualRequests.get(0)); Assert.assertEquals(name, actualRequest.getName()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void getServiceAccountExceptionTest2() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockSecurityCenterSettingsService.addException(exception); try { String name = "name3373707"; client.getServiceAccount(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void getSettingsTest() throws Exception { Settings expectedResponse = Settings.newBuilder() .setName(SettingsName.ofOrganizationName("[ORGANIZATION]").toString()) .setBillingSettings(BillingSettings.newBuilder().build()) .setOrgServiceAccount("orgServiceAccount-1736642116") .setSinkSettings(SinkSettings.newBuilder().build()) .putAllComponentSettings(new HashMap<String, ComponentSettings>()) .putAllDetectorGroupSettings(new HashMap<String, Settings.DetectorGroupSettings>()) .setEtag("etag3123477") .setUpdateTime(Timestamp.newBuilder().build()) .build(); mockSecurityCenterSettingsService.addResponse(expectedResponse); SettingsName name = SettingsName.ofOrganizationName("[ORGANIZATION]"); Settings actualResponse = client.getSettings(name); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockSecurityCenterSettingsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); GetSettingsRequest actualRequest = ((GetSettingsRequest) actualRequests.get(0)); Assert.assertEquals(name.toString(), actualRequest.getName()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void getSettingsExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockSecurityCenterSettingsService.addException(exception); try { SettingsName name = SettingsName.ofOrganizationName("[ORGANIZATION]"); client.getSettings(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void getSettingsTest2() throws Exception { Settings expectedResponse = Settings.newBuilder() .setName(SettingsName.ofOrganizationName("[ORGANIZATION]").toString()) .setBillingSettings(BillingSettings.newBuilder().build()) .setOrgServiceAccount("orgServiceAccount-1736642116") .setSinkSettings(SinkSettings.newBuilder().build()) .putAllComponentSettings(new HashMap<String, ComponentSettings>()) .putAllDetectorGroupSettings(new HashMap<String, Settings.DetectorGroupSettings>()) .setEtag("etag3123477") .setUpdateTime(Timestamp.newBuilder().build()) .build(); mockSecurityCenterSettingsService.addResponse(expectedResponse); String name = "name3373707"; Settings actualResponse = client.getSettings(name); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockSecurityCenterSettingsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); GetSettingsRequest actualRequest = ((GetSettingsRequest) actualRequests.get(0)); Assert.assertEquals(name, actualRequest.getName()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void getSettingsExceptionTest2() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockSecurityCenterSettingsService.addException(exception); try { String name = "name3373707"; client.getSettings(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void updateSettingsTest() throws Exception { Settings expectedResponse = Settings.newBuilder() .setName(SettingsName.ofOrganizationName("[ORGANIZATION]").toString()) .setBillingSettings(BillingSettings.newBuilder().build()) .setOrgServiceAccount("orgServiceAccount-1736642116") .setSinkSettings(SinkSettings.newBuilder().build()) .putAllComponentSettings(new HashMap<String, ComponentSettings>()) .putAllDetectorGroupSettings(new HashMap<String, Settings.DetectorGroupSettings>()) .setEtag("etag3123477") .setUpdateTime(Timestamp.newBuilder().build()) .build(); mockSecurityCenterSettingsService.addResponse(expectedResponse); Settings settings = Settings.newBuilder().build(); FieldMask updateMask = FieldMask.newBuilder().build(); Settings actualResponse = client.updateSettings(settings, updateMask); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockSecurityCenterSettingsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); UpdateSettingsRequest actualRequest = ((UpdateSettingsRequest) actualRequests.get(0)); Assert.assertEquals(settings, actualRequest.getSettings()); Assert.assertEquals(updateMask, actualRequest.getUpdateMask()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void updateSettingsExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockSecurityCenterSettingsService.addException(exception); try { Settings settings = Settings.newBuilder().build(); FieldMask updateMask = FieldMask.newBuilder().build(); client.updateSettings(settings, updateMask); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void resetSettingsTest() throws Exception { Empty expectedResponse = Empty.newBuilder().build(); mockSecurityCenterSettingsService.addResponse(expectedResponse); ResetSettingsRequest request = ResetSettingsRequest.newBuilder() .setName(SettingsName.ofOrganizationName("[ORGANIZATION]").toString()) .setEtag("etag3123477") .build(); client.resetSettings(request); List<AbstractMessage> actualRequests = mockSecurityCenterSettingsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); ResetSettingsRequest actualRequest = ((ResetSettingsRequest) actualRequests.get(0)); Assert.assertEquals(request.getName(), actualRequest.getName()); Assert.assertEquals(request.getEtag(), actualRequest.getEtag()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void resetSettingsExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockSecurityCenterSettingsService.addException(exception); try { ResetSettingsRequest request = ResetSettingsRequest.newBuilder() .setName(SettingsName.ofOrganizationName("[ORGANIZATION]").toString()) .setEtag("etag3123477") .build(); client.resetSettings(request); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void batchGetSettingsTest() throws Exception { BatchGetSettingsResponse expectedResponse = BatchGetSettingsResponse.newBuilder().addAllSettings(new ArrayList<Settings>()).build(); mockSecurityCenterSettingsService.addResponse(expectedResponse); BatchGetSettingsRequest request = BatchGetSettingsRequest.newBuilder() .setParent(OrganizationName.of("[ORGANIZATION]").toString()) .addAllNames(new ArrayList<String>()) .build(); BatchGetSettingsResponse actualResponse = client.batchGetSettings(request); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockSecurityCenterSettingsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); BatchGetSettingsRequest actualRequest = ((BatchGetSettingsRequest) actualRequests.get(0)); Assert.assertEquals(request.getParent(), actualRequest.getParent()); Assert.assertEquals(request.getNamesList(), actualRequest.getNamesList()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void batchGetSettingsExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockSecurityCenterSettingsService.addException(exception); try { BatchGetSettingsRequest request = BatchGetSettingsRequest.newBuilder() .setParent(OrganizationName.of("[ORGANIZATION]").toString()) .addAllNames(new ArrayList<String>()) .build(); client.batchGetSettings(request); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void calculateEffectiveSettingsTest() throws Exception { Settings expectedResponse = Settings.newBuilder() .setName(SettingsName.ofOrganizationName("[ORGANIZATION]").toString()) .setBillingSettings(BillingSettings.newBuilder().build()) .setOrgServiceAccount("orgServiceAccount-1736642116") .setSinkSettings(SinkSettings.newBuilder().build()) .putAllComponentSettings(new HashMap<String, ComponentSettings>()) .putAllDetectorGroupSettings(new HashMap<String, Settings.DetectorGroupSettings>()) .setEtag("etag3123477") .setUpdateTime(Timestamp.newBuilder().build()) .build(); mockSecurityCenterSettingsService.addResponse(expectedResponse); SettingsName name = SettingsName.ofOrganizationName("[ORGANIZATION]"); Settings actualResponse = client.calculateEffectiveSettings(name); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockSecurityCenterSettingsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); CalculateEffectiveSettingsRequest actualRequest = ((CalculateEffectiveSettingsRequest) actualRequests.get(0)); Assert.assertEquals(name.toString(), actualRequest.getName()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void calculateEffectiveSettingsExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockSecurityCenterSettingsService.addException(exception); try { SettingsName name = SettingsName.ofOrganizationName("[ORGANIZATION]"); client.calculateEffectiveSettings(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void calculateEffectiveSettingsTest2() throws Exception { Settings expectedResponse = Settings.newBuilder() .setName(SettingsName.ofOrganizationName("[ORGANIZATION]").toString()) .setBillingSettings(BillingSettings.newBuilder().build()) .setOrgServiceAccount("orgServiceAccount-1736642116") .setSinkSettings(SinkSettings.newBuilder().build()) .putAllComponentSettings(new HashMap<String, ComponentSettings>()) .putAllDetectorGroupSettings(new HashMap<String, Settings.DetectorGroupSettings>()) .setEtag("etag3123477") .setUpdateTime(Timestamp.newBuilder().build()) .build(); mockSecurityCenterSettingsService.addResponse(expectedResponse); String name = "name3373707"; Settings actualResponse = client.calculateEffectiveSettings(name); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockSecurityCenterSettingsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); CalculateEffectiveSettingsRequest actualRequest = ((CalculateEffectiveSettingsRequest) actualRequests.get(0)); Assert.assertEquals(name, actualRequest.getName()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void calculateEffectiveSettingsExceptionTest2() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockSecurityCenterSettingsService.addException(exception); try { String name = "name3373707"; client.calculateEffectiveSettings(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void batchCalculateEffectiveSettingsTest() throws Exception { BatchCalculateEffectiveSettingsResponse expectedResponse = BatchCalculateEffectiveSettingsResponse.newBuilder() .addAllSettings(new ArrayList<Settings>()) .build(); mockSecurityCenterSettingsService.addResponse(expectedResponse); BatchCalculateEffectiveSettingsRequest request = BatchCalculateEffectiveSettingsRequest.newBuilder() .setParent(OrganizationName.of("[ORGANIZATION]").toString()) .addAllRequests(new ArrayList<CalculateEffectiveSettingsRequest>()) .build(); BatchCalculateEffectiveSettingsResponse actualResponse = client.batchCalculateEffectiveSettings(request); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockSecurityCenterSettingsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); BatchCalculateEffectiveSettingsRequest actualRequest = ((BatchCalculateEffectiveSettingsRequest) actualRequests.get(0)); Assert.assertEquals(request.getParent(), actualRequest.getParent()); Assert.assertEquals(request.getRequestsList(), actualRequest.getRequestsList()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void batchCalculateEffectiveSettingsExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockSecurityCenterSettingsService.addException(exception); try { BatchCalculateEffectiveSettingsRequest request = BatchCalculateEffectiveSettingsRequest.newBuilder() .setParent(OrganizationName.of("[ORGANIZATION]").toString()) .addAllRequests(new ArrayList<CalculateEffectiveSettingsRequest>()) .build(); client.batchCalculateEffectiveSettings(request); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void getComponentSettingsTest() throws Exception { ComponentSettings expectedResponse = ComponentSettings.newBuilder() .setName( ComponentSettingsName.ofOrganizationComponentName("[ORGANIZATION]", "[COMPONENT]") .toString()) .setState(ComponentEnablementState.forNumber(0)) .setProjectServiceAccount("projectServiceAccount79138097") .putAllDetectorSettings(new HashMap<String, ComponentSettings.DetectorSettings>()) .setEtag("etag3123477") .setUpdateTime(Timestamp.newBuilder().build()) .build(); mockSecurityCenterSettingsService.addResponse(expectedResponse); ComponentSettingsName name = ComponentSettingsName.ofOrganizationComponentName("[ORGANIZATION]", "[COMPONENT]"); ComponentSettings actualResponse = client.getComponentSettings(name); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockSecurityCenterSettingsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); GetComponentSettingsRequest actualRequest = ((GetComponentSettingsRequest) actualRequests.get(0)); Assert.assertEquals(name.toString(), actualRequest.getName()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void getComponentSettingsExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockSecurityCenterSettingsService.addException(exception); try { ComponentSettingsName name = ComponentSettingsName.ofOrganizationComponentName("[ORGANIZATION]", "[COMPONENT]"); client.getComponentSettings(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void getComponentSettingsTest2() throws Exception { ComponentSettings expectedResponse = ComponentSettings.newBuilder() .setName( ComponentSettingsName.ofOrganizationComponentName("[ORGANIZATION]", "[COMPONENT]") .toString()) .setState(ComponentEnablementState.forNumber(0)) .setProjectServiceAccount("projectServiceAccount79138097") .putAllDetectorSettings(new HashMap<String, ComponentSettings.DetectorSettings>()) .setEtag("etag3123477") .setUpdateTime(Timestamp.newBuilder().build()) .build(); mockSecurityCenterSettingsService.addResponse(expectedResponse); String name = "name3373707"; ComponentSettings actualResponse = client.getComponentSettings(name); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockSecurityCenterSettingsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); GetComponentSettingsRequest actualRequest = ((GetComponentSettingsRequest) actualRequests.get(0)); Assert.assertEquals(name, actualRequest.getName()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void getComponentSettingsExceptionTest2() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockSecurityCenterSettingsService.addException(exception); try { String name = "name3373707"; client.getComponentSettings(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void updateComponentSettingsTest() throws Exception { ComponentSettings expectedResponse = ComponentSettings.newBuilder() .setName( ComponentSettingsName.ofOrganizationComponentName("[ORGANIZATION]", "[COMPONENT]") .toString()) .setState(ComponentEnablementState.forNumber(0)) .setProjectServiceAccount("projectServiceAccount79138097") .putAllDetectorSettings(new HashMap<String, ComponentSettings.DetectorSettings>()) .setEtag("etag3123477") .setUpdateTime(Timestamp.newBuilder().build()) .build(); mockSecurityCenterSettingsService.addResponse(expectedResponse); ComponentSettings componentSettings = ComponentSettings.newBuilder().build(); FieldMask updateMask = FieldMask.newBuilder().build(); ComponentSettings actualResponse = client.updateComponentSettings(componentSettings, updateMask); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockSecurityCenterSettingsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); UpdateComponentSettingsRequest actualRequest = ((UpdateComponentSettingsRequest) actualRequests.get(0)); Assert.assertEquals(componentSettings, actualRequest.getComponentSettings()); Assert.assertEquals(updateMask, actualRequest.getUpdateMask()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void updateComponentSettingsExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockSecurityCenterSettingsService.addException(exception); try { ComponentSettings componentSettings = ComponentSettings.newBuilder().build(); FieldMask updateMask = FieldMask.newBuilder().build(); client.updateComponentSettings(componentSettings, updateMask); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void resetComponentSettingsTest() throws Exception { Empty expectedResponse = Empty.newBuilder().build(); mockSecurityCenterSettingsService.addResponse(expectedResponse); ResetComponentSettingsRequest request = ResetComponentSettingsRequest.newBuilder() .setName( ComponentSettingsName.ofOrganizationComponentName("[ORGANIZATION]", "[COMPONENT]") .toString()) .setEtag("etag3123477") .build(); client.resetComponentSettings(request); List<AbstractMessage> actualRequests = mockSecurityCenterSettingsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); ResetComponentSettingsRequest actualRequest = ((ResetComponentSettingsRequest) actualRequests.get(0)); Assert.assertEquals(request.getName(), actualRequest.getName()); Assert.assertEquals(request.getEtag(), actualRequest.getEtag()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void resetComponentSettingsExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockSecurityCenterSettingsService.addException(exception); try { ResetComponentSettingsRequest request = ResetComponentSettingsRequest.newBuilder() .setName( ComponentSettingsName.ofOrganizationComponentName("[ORGANIZATION]", "[COMPONENT]") .toString()) .setEtag("etag3123477") .build(); client.resetComponentSettings(request); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void calculateEffectiveComponentSettingsTest() throws Exception { ComponentSettings expectedResponse = ComponentSettings.newBuilder() .setName( ComponentSettingsName.ofOrganizationComponentName("[ORGANIZATION]", "[COMPONENT]") .toString()) .setState(ComponentEnablementState.forNumber(0)) .setProjectServiceAccount("projectServiceAccount79138097") .putAllDetectorSettings(new HashMap<String, ComponentSettings.DetectorSettings>()) .setEtag("etag3123477") .setUpdateTime(Timestamp.newBuilder().build()) .build(); mockSecurityCenterSettingsService.addResponse(expectedResponse); ComponentSettingsName name = ComponentSettingsName.ofOrganizationComponentName("[ORGANIZATION]", "[COMPONENT]"); ComponentSettings actualResponse = client.calculateEffectiveComponentSettings(name); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockSecurityCenterSettingsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); CalculateEffectiveComponentSettingsRequest actualRequest = ((CalculateEffectiveComponentSettingsRequest) actualRequests.get(0)); Assert.assertEquals(name.toString(), actualRequest.getName()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void calculateEffectiveComponentSettingsExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockSecurityCenterSettingsService.addException(exception); try { ComponentSettingsName name = ComponentSettingsName.ofOrganizationComponentName("[ORGANIZATION]", "[COMPONENT]"); client.calculateEffectiveComponentSettings(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void calculateEffectiveComponentSettingsTest2() throws Exception { ComponentSettings expectedResponse = ComponentSettings.newBuilder() .setName( ComponentSettingsName.ofOrganizationComponentName("[ORGANIZATION]", "[COMPONENT]") .toString()) .setState(ComponentEnablementState.forNumber(0)) .setProjectServiceAccount("projectServiceAccount79138097") .putAllDetectorSettings(new HashMap<String, ComponentSettings.DetectorSettings>()) .setEtag("etag3123477") .setUpdateTime(Timestamp.newBuilder().build()) .build(); mockSecurityCenterSettingsService.addResponse(expectedResponse); String name = "name3373707"; ComponentSettings actualResponse = client.calculateEffectiveComponentSettings(name); Assert.assertEquals(expectedResponse, actualResponse); List<AbstractMessage> actualRequests = mockSecurityCenterSettingsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); CalculateEffectiveComponentSettingsRequest actualRequest = ((CalculateEffectiveComponentSettingsRequest) actualRequests.get(0)); Assert.assertEquals(name, actualRequest.getName()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void calculateEffectiveComponentSettingsExceptionTest2() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockSecurityCenterSettingsService.addException(exception); try { String name = "name3373707"; client.calculateEffectiveComponentSettings(name); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void listDetectorsTest() throws Exception { Detector responsesElement = Detector.newBuilder().build(); ListDetectorsResponse expectedResponse = ListDetectorsResponse.newBuilder() .setNextPageToken("") .addAllDetectors(Arrays.asList(responsesElement)) .build(); mockSecurityCenterSettingsService.addResponse(expectedResponse); OrganizationName parent = OrganizationName.of("[ORGANIZATION]"); ListDetectorsPagedResponse pagedListResponse = client.listDetectors(parent); List<Detector> resources = Lists.newArrayList(pagedListResponse.iterateAll()); Assert.assertEquals(1, resources.size()); Assert.assertEquals(expectedResponse.getDetectorsList().get(0), resources.get(0)); List<AbstractMessage> actualRequests = mockSecurityCenterSettingsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); ListDetectorsRequest actualRequest = ((ListDetectorsRequest) actualRequests.get(0)); Assert.assertEquals(parent.toString(), actualRequest.getParent()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void listDetectorsExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockSecurityCenterSettingsService.addException(exception); try { OrganizationName parent = OrganizationName.of("[ORGANIZATION]"); client.listDetectors(parent); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void listDetectorsTest2() throws Exception { Detector responsesElement = Detector.newBuilder().build(); ListDetectorsResponse expectedResponse = ListDetectorsResponse.newBuilder() .setNextPageToken("") .addAllDetectors(Arrays.asList(responsesElement)) .build(); mockSecurityCenterSettingsService.addResponse(expectedResponse); String parent = "parent-995424086"; ListDetectorsPagedResponse pagedListResponse = client.listDetectors(parent); List<Detector> resources = Lists.newArrayList(pagedListResponse.iterateAll()); Assert.assertEquals(1, resources.size()); Assert.assertEquals(expectedResponse.getDetectorsList().get(0), resources.get(0)); List<AbstractMessage> actualRequests = mockSecurityCenterSettingsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); ListDetectorsRequest actualRequest = ((ListDetectorsRequest) actualRequests.get(0)); Assert.assertEquals(parent, actualRequest.getParent()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void listDetectorsExceptionTest2() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockSecurityCenterSettingsService.addException(exception); try { String parent = "parent-995424086"; client.listDetectors(parent); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void listComponentsTest() throws Exception { String responsesElement = "responsesElement-318365110"; ListComponentsResponse expectedResponse = ListComponentsResponse.newBuilder() .setNextPageToken("") .addAllComponents(Arrays.asList(responsesElement)) .build(); mockSecurityCenterSettingsService.addResponse(expectedResponse); OrganizationName parent = OrganizationName.of("[ORGANIZATION]"); ListComponentsPagedResponse pagedListResponse = client.listComponents(parent); List<String> resources = Lists.newArrayList(pagedListResponse.iterateAll()); Assert.assertEquals(1, resources.size()); Assert.assertEquals(expectedResponse.getComponentsList().get(0), resources.get(0)); List<AbstractMessage> actualRequests = mockSecurityCenterSettingsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); ListComponentsRequest actualRequest = ((ListComponentsRequest) actualRequests.get(0)); Assert.assertEquals(parent.toString(), actualRequest.getParent()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void listComponentsExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockSecurityCenterSettingsService.addException(exception); try { OrganizationName parent = OrganizationName.of("[ORGANIZATION]"); client.listComponents(parent); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } @Test public void listComponentsTest2() throws Exception { String responsesElement = "responsesElement-318365110"; ListComponentsResponse expectedResponse = ListComponentsResponse.newBuilder() .setNextPageToken("") .addAllComponents(Arrays.asList(responsesElement)) .build(); mockSecurityCenterSettingsService.addResponse(expectedResponse); String parent = "parent-995424086"; ListComponentsPagedResponse pagedListResponse = client.listComponents(parent); List<String> resources = Lists.newArrayList(pagedListResponse.iterateAll()); Assert.assertEquals(1, resources.size()); Assert.assertEquals(expectedResponse.getComponentsList().get(0), resources.get(0)); List<AbstractMessage> actualRequests = mockSecurityCenterSettingsService.getRequests(); Assert.assertEquals(1, actualRequests.size()); ListComponentsRequest actualRequest = ((ListComponentsRequest) actualRequests.get(0)); Assert.assertEquals(parent, actualRequest.getParent()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); } @Test public void listComponentsExceptionTest2() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT); mockSecurityCenterSettingsService.addException(exception); try { String parent = "parent-995424086"; client.listComponents(parent); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception. } } }
/* * Copyright (C) 2014 The Android Open Source Project * * 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 pe.asomapps.udacity.goubiquitous; import android.annotation.TargetApi; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.wearable.watchface.CanvasWatchFaceService; import android.support.wearable.watchface.WatchFaceStyle; import android.text.format.Time; import android.view.SurfaceHolder; import android.view.WindowInsets; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.wearable.DataApi; import com.google.android.gms.wearable.DataEvent; import com.google.android.gms.wearable.DataEventBuffer; import com.google.android.gms.wearable.DataMap; import com.google.android.gms.wearable.DataMapItem; import com.google.android.gms.wearable.Wearable; import java.lang.ref.WeakReference; import java.text.DateFormatSymbols; import java.util.TimeZone; import java.util.concurrent.TimeUnit; /** * Digital watch face with seconds. In ambient mode, the seconds aren't displayed. On devices with * low-bit ambient mode, the text is drawn without anti-aliasing in ambient mode. */ public class WeatherWatchFace extends CanvasWatchFaceService { private static final Typeface NORMAL_TYPEFACE = Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL); /** * Update rate in milliseconds for interactive mode. We update once a second since seconds are * displayed in interactive mode. */ private static final long INTERACTIVE_UPDATE_RATE_MS = TimeUnit.SECONDS.toMillis(1); /** * Handler message id for updating the time periodically in interactive mode. */ private static final int MSG_UPDATE_TIME = 0; @Override public Engine onCreateEngine() { return new Engine(); } private static class EngineHandler extends Handler { private final WeakReference<WeatherWatchFace.Engine> mWeakReference; public EngineHandler(WeatherWatchFace.Engine reference) { mWeakReference = new WeakReference<>(reference); } @Override public void handleMessage(Message msg) { WeatherWatchFace.Engine engine = mWeakReference.get(); if (engine != null) { switch (msg.what) { case MSG_UPDATE_TIME: engine.handleUpdateTimeMessage(); break; } } } } private class Engine extends CanvasWatchFaceService.Engine implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, DataApi.DataListener { final Handler mUpdateTimeHandler = new EngineHandler(this); boolean mRegisteredTimeZoneReceiver = false; boolean isRound, mAmbient; Time mTime; private String[] mDayNames, mMonthNames; private float mTimeYOffset = -1, mDateYOffset, mSeparatorYOffset, mWeatherYOffset; private float defaultOffset; private Paint mBackgroundPaint, mTimePaint, mSecondsPaint, mDatePaint, mMaxPaint, mMinPaint; private GoogleApiClient googleClient; private String lastMaxTemp; private String lastMinTemp; private Bitmap mWeatherIconBitmap; private Bitmap mWeatherIconGrayBitmap; final BroadcastReceiver mTimeZoneReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { mTime.clear(intent.getStringExtra("time-zone")); mTime.setToNow(); } }; /** * Whether the display supports fewer bits for each color in ambient mode. When true, we * disable anti-aliasing in ambient mode. */ boolean mLowBitAmbient; @Override public void onCreate(SurfaceHolder holder) { super.onCreate(holder); googleClient = new GoogleApiClient.Builder(WeatherWatchFace.this).addApi(Wearable.API).addConnectionCallbacks(this).addOnConnectionFailedListener(this).build(); setWatchFaceStyle(new WatchFaceStyle.Builder(WeatherWatchFace.this) .setCardPeekMode(WatchFaceStyle.PEEK_MODE_VARIABLE) .setBackgroundVisibility(WatchFaceStyle.BACKGROUND_VISIBILITY_INTERRUPTIVE) .setShowSystemUiTime(false) .setAcceptsTapEvents(true) .build()); mTime = new Time(); //Get day and month names DateFormatSymbols symbols = new DateFormatSymbols(); mDayNames = symbols.getShortWeekdays(); mMonthNames = symbols.getShortMonths(); } @Override public void onDestroy() { mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME); super.onDestroy(); } @Override public void onApplyWindowInsets(WindowInsets insets) { super.onApplyWindowInsets(insets); isRound = insets.isRound(); } @Override public void onPropertiesChanged(Bundle properties) { super.onPropertiesChanged(properties); mLowBitAmbient = properties.getBoolean(PROPERTY_LOW_BIT_AMBIENT, false); } @Override public void onTimeTick() { super.onTimeTick(); invalidate(); } @Override public void onAmbientModeChanged(boolean inAmbientMode) { super.onAmbientModeChanged(inAmbientMode); if (mAmbient != inAmbientMode) { mAmbient = inAmbientMode; if (mLowBitAmbient) { mTimePaint.setAntiAlias(!inAmbientMode); } invalidate(); } // Whether the timer should be running depends on whether we're visible (as well as // whether we're in ambient mode), so we may need to start or stop the timer. updateTimer(); } @Override public void onDraw(Canvas canvas, Rect bounds) { mTime.setToNow(); initValues(); paintBackground(canvas, bounds); paintDateTime(canvas, bounds); paintWeather(canvas, bounds); paintExtras(canvas, bounds); } /** * Create the tools and values to be used to * locate and draw the information in the watch face */ @TargetApi(Build.VERSION_CODES.M) private void initValues() { if (mTimeYOffset >= 0) { return; } Resources resources = WeatherWatchFace.this.getResources(); mBackgroundPaint = new Paint(); mBackgroundPaint.setColor(resources.getColor(R.color.sunshine_background, getTheme())); defaultOffset = resources.getDimension(R.dimen.default_margin_top); int whiteColor = resources.getColor(R.color.digital_text, getTheme()); int grayColor = resources.getColor(R.color.graydigital_text, getTheme()); float textSizeTime = resources.getDimension(R.dimen.text_size_time); mTimePaint = createTextPaint(whiteColor, textSizeTime); int marginTop = isRound? R.dimen.time_margin_top_round: R.dimen.time_margin_top; mTimeYOffset = resources.getDimension(marginTop) + textSizeTime; float textSizeSeconds = resources.getDimension(R.dimen.text_size_seconds); mSecondsPaint = createTextPaint(grayColor, textSizeSeconds); float textSizeDate = resources.getDimension(R.dimen.text_size_date); mDatePaint = createTextPaint(whiteColor, textSizeDate); mDateYOffset = defaultOffset + mTimeYOffset + textSizeDate; mSeparatorYOffset = defaultOffset + mDateYOffset; float textSizeWeather = resources.getDimension(R.dimen.text_size_weather); mMaxPaint = createTextPaint(whiteColor, textSizeWeather); mMinPaint = createTextPaint(grayColor, textSizeWeather); mWeatherYOffset = defaultOffset + mSeparatorYOffset + textSizeWeather; } private Paint createTextPaint(int textColor, float textSize) { Paint paint = new Paint(); paint.setColor(textColor); paint.setTypeface(NORMAL_TYPEFACE); paint.setAntiAlias(true); paint.setTextSize(textSize); return paint; } /** * Draw background from the watch face. * This can be updated to draw an image or animation if needed later on */ private void paintBackground(Canvas canvas, Rect bounds) { if (isInAmbientMode()) { canvas.drawColor(Color.BLACK); } else { canvas.drawRect(0, 0, bounds.width(), bounds.height(), mBackgroundPaint); } } /** * Draw additional content that is not part of the information displayed */ private void paintExtras(Canvas canvas, Rect bounds) { canvas.drawRect(bounds.centerX() - defaultOffset, mSeparatorYOffset, bounds.centerX() + defaultOffset, mSeparatorYOffset + 1, mSecondsPaint); } /** * Draw the information from the date and time into the watch face */ private void paintDateTime(Canvas canvas, Rect bounds) { float centerX = bounds.centerX(); String timeGeneral = String.format("%02d:%02d", mTime.hour, mTime.minute); float timeXOffset = mTimePaint.measureText(timeGeneral) / 2; canvas.drawText(timeGeneral, centerX - timeXOffset, mTimeYOffset, mTimePaint); if (!isInAmbientMode()) { String timeSeconds = String.format(":%02d", mTime.second); canvas.drawText(timeSeconds, centerX + timeXOffset, mTimeYOffset, mSecondsPaint); } String date = String.format("%s, %s %02d %04d", mDayNames[mTime.weekDay+1].toUpperCase(), mMonthNames[mTime.month].toUpperCase(), mTime.monthDay, mTime.year); float dateXOffset = mDatePaint.measureText(date) / 2; canvas.drawText(date, centerX - dateXOffset, mDateYOffset, mDatePaint); } /** * Draw the information from the weather into the watch face */ private void paintWeather(Canvas canvas, Rect bounds) { float centerX = bounds.centerX(); float maxXOffset = 0; if (lastMaxTemp!=null){ maxXOffset = mTimePaint.measureText(lastMaxTemp) / 2; canvas.drawText(lastMaxTemp, centerX - maxXOffset, mWeatherYOffset, mMaxPaint); } if (lastMinTemp!=null) { canvas.drawText(lastMinTemp, centerX + maxXOffset + defaultOffset, mWeatherYOffset, mMinPaint); } if (!isInAmbientMode()) { if (mWeatherIconBitmap!=null){ float iconXOffset = centerX - (defaultOffset + maxXOffset + mWeatherIconBitmap.getWidth()); float iconYOffset = mWeatherYOffset - (defaultOffset+ mWeatherIconBitmap.getHeight())/2; canvas.drawBitmap(mWeatherIconBitmap, iconXOffset, iconYOffset, null); } } else { if (mWeatherIconGrayBitmap!=null) { float iconXOffset = centerX - (defaultOffset + maxXOffset + mWeatherIconGrayBitmap.getWidth()); float iconYOffset = mWeatherYOffset - (defaultOffset+ mWeatherIconGrayBitmap.getHeight())/2; canvas.drawBitmap(mWeatherIconGrayBitmap, iconXOffset, iconYOffset, null); } } } /** * Starts the {@link #mUpdateTimeHandler} timer if it should be running and isn't currently * or stops it if it shouldn't be running but currently is. */ private void updateTimer() { mUpdateTimeHandler.removeMessages(MSG_UPDATE_TIME); if (shouldTimerBeRunning()) { mUpdateTimeHandler.sendEmptyMessage(MSG_UPDATE_TIME); } } /** * Returns whether the {@link #mUpdateTimeHandler} timer should be running. The timer should * only run when we're visible and in interactive mode. */ private boolean shouldTimerBeRunning() { return isVisible() && !isInAmbientMode(); } /** * Handle updating the time periodically in interactive mode. */ private void handleUpdateTimeMessage() { invalidate(); if (shouldTimerBeRunning()) { long timeMs = System.currentTimeMillis(); long delayMs = INTERACTIVE_UPDATE_RATE_MS - (timeMs % INTERACTIVE_UPDATE_RATE_MS); mUpdateTimeHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIME, delayMs); } } @Override public void onVisibilityChanged(boolean visible) { super.onVisibilityChanged(visible); if (visible) { connectGoogleApiClient(); registerReceiver(); // Update time zone in case it changed while we weren't visible. mTime.clear(TimeZone.getDefault().getID()); mTime.setToNow(); } else { releaseGoogleApiClient(); unregisterReceiver(); } // Whether the timer should be running depends on whether we're visible (as well as // whether we're in ambient mode), so we may need to start or stop the timer. updateTimer(); } private void connectGoogleApiClient() { if (googleClient != null && !googleClient.isConnected()) { googleClient.connect(); } } private void releaseGoogleApiClient() { if (googleClient != null && googleClient.isConnected()) { Wearable.DataApi.removeListener(googleClient, this); googleClient.disconnect(); } } private void registerReceiver() { if (mRegisteredTimeZoneReceiver) { return; } mRegisteredTimeZoneReceiver = true; IntentFilter filter = new IntentFilter(Intent.ACTION_TIMEZONE_CHANGED); WeatherWatchFace.this.registerReceiver(mTimeZoneReceiver, filter); } private void unregisterReceiver() { if (!mRegisteredTimeZoneReceiver) { return; } mRegisteredTimeZoneReceiver = false; WeatherWatchFace.this.unregisterReceiver(mTimeZoneReceiver); } @Override public void onConnected(@Nullable Bundle bundle) { Wearable.DataApi.addListener(googleClient, Engine.this); } @Override public void onConnectionSuspended(int i) { } @Override public void onDataChanged(DataEventBuffer dataEventBuffer) { for (DataEvent event:dataEventBuffer){ if (event.getType()==DataEvent.TYPE_CHANGED){ DataMap dataMap = DataMapItem.fromDataItem(event.getDataItem()).getDataMap(); String path = event.getDataItem().getUri().getPath(); if (path.equals("/sunshine_weather")){ lastMaxTemp = dataMap.getString("maxTemp"); lastMinTemp = dataMap.getString("minTemp"); int weatherId = dataMap.getInt("weatherId"); int resId = Utility.getArtResourceForWeatherCondition(weatherId); if (resId>=0){ mWeatherIconBitmap = BitmapFactory.decodeResource(getResources(), resId); int size = Double.valueOf(WeatherWatchFace.this.getResources().getDimension(R.dimen.weather_icon_size)).intValue(); mWeatherIconBitmap = Bitmap.createScaledBitmap(mWeatherIconBitmap, size, size, false); initGrayBackgroundBitmap(); } invalidate(); } } } } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } /** * Generate gray bitmap from the current weather icon */ private void initGrayBackgroundBitmap() { mWeatherIconGrayBitmap = Bitmap.createBitmap( mWeatherIconBitmap.getWidth(), mWeatherIconBitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(mWeatherIconGrayBitmap); Paint grayPaint = new Paint(); ColorMatrix colorMatrix = new ColorMatrix(); colorMatrix.setSaturation(0); ColorMatrixColorFilter filter = new ColorMatrixColorFilter(colorMatrix); grayPaint.setColorFilter(filter); canvas.drawBitmap(mWeatherIconBitmap, 0, 0, grayPaint); } } }
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets 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 io.druid.indexing.kafka.supervisor; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Charsets; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.metamx.common.Granularity; import com.metamx.common.ISE; import io.druid.data.input.impl.DimensionSchema; import io.druid.data.input.impl.DimensionsSpec; import io.druid.data.input.impl.JSONParseSpec; import io.druid.data.input.impl.JSONPathFieldSpec; import io.druid.data.input.impl.JSONPathSpec; import io.druid.data.input.impl.StringDimensionSchema; import io.druid.data.input.impl.StringInputRowParser; import io.druid.data.input.impl.TimestampSpec; import io.druid.granularity.QueryGranularities; import io.druid.indexing.common.TaskInfoProvider; import io.druid.indexing.common.TaskLocation; import io.druid.indexing.common.TaskStatus; import io.druid.indexing.common.task.RealtimeIndexTask; import io.druid.indexing.common.task.Task; import io.druid.indexing.kafka.KafkaDataSourceMetadata; import io.druid.indexing.kafka.KafkaIOConfig; import io.druid.indexing.kafka.KafkaIndexTask; import io.druid.indexing.kafka.KafkaIndexTaskClient; import io.druid.indexing.kafka.KafkaIndexTaskClientFactory; import io.druid.indexing.kafka.KafkaPartitions; import io.druid.indexing.kafka.KafkaTuningConfig; import io.druid.indexing.kafka.test.TestBroker; import io.druid.indexing.overlord.IndexerMetadataStorageCoordinator; import io.druid.indexing.overlord.TaskMaster; import io.druid.indexing.overlord.TaskQueue; import io.druid.indexing.overlord.TaskRunner; import io.druid.indexing.overlord.TaskRunnerListener; import io.druid.indexing.overlord.TaskRunnerWorkItem; import io.druid.indexing.overlord.TaskStorage; import io.druid.indexing.overlord.supervisor.SupervisorReport; import io.druid.jackson.DefaultObjectMapper; import io.druid.query.aggregation.AggregatorFactory; import io.druid.query.aggregation.CountAggregatorFactory; import io.druid.segment.indexing.DataSchema; import io.druid.segment.indexing.RealtimeIOConfig; import io.druid.segment.indexing.granularity.UniformGranularitySpec; import io.druid.segment.realtime.FireDepartment; import org.apache.curator.test.TestingCluster; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerRecord; import org.easymock.Capture; import org.easymock.CaptureType; import org.easymock.EasyMock; import org.easymock.EasyMockSupport; import org.joda.time.DateTime; import org.joda.time.Duration; import org.joda.time.Interval; import org.joda.time.Period; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.Executor; import static org.easymock.EasyMock.anyObject; import static org.easymock.EasyMock.anyString; import static org.easymock.EasyMock.capture; import static org.easymock.EasyMock.eq; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expectLastCall; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.reset; @RunWith(Parameterized.class) public class KafkaSupervisorTest extends EasyMockSupport { private static final ObjectMapper objectMapper = new DefaultObjectMapper(); private static final String KAFKA_TOPIC = "testTopic"; private static final String DATASOURCE = "testDS"; private static final int NUM_PARTITIONS = 3; private static final int TEST_CHAT_THREADS = 3; private static final long TEST_CHAT_RETRIES = 9L; private static final Period TEST_HTTP_TIMEOUT = new Period("PT10S"); private static final Period TEST_SHUTDOWN_TIMEOUT = new Period("PT80S"); private int numThreads; private TestingCluster zkServer; private TestBroker kafkaServer; private KafkaSupervisor supervisor; private String kafkaHost; private DataSchema dataSchema; private KafkaSupervisorTuningConfig tuningConfig; private TaskStorage taskStorage; private TaskMaster taskMaster; private TaskRunner taskRunner; private IndexerMetadataStorageCoordinator indexerMetadataStorageCoordinator; private KafkaIndexTaskClient taskClient; private TaskQueue taskQueue; @Rule public final TemporaryFolder tempFolder = new TemporaryFolder(); @Parameterized.Parameters(name = "numThreads = {0}") public static Iterable<Object[]> constructorFeeder() { return ImmutableList.of(new Object[]{1}, new Object[]{8}); } public KafkaSupervisorTest(int numThreads) { this.numThreads = numThreads; } @Before public void setUp() throws Exception { taskStorage = createMock(TaskStorage.class); taskMaster = createMock(TaskMaster.class); taskRunner = createMock(TaskRunner.class); indexerMetadataStorageCoordinator = createMock(IndexerMetadataStorageCoordinator.class); taskClient = createMock(KafkaIndexTaskClient.class); taskQueue = createMock(TaskQueue.class); zkServer = new TestingCluster(1); zkServer.start(); kafkaServer = new TestBroker( zkServer.getConnectString(), tempFolder.newFolder(), 1, ImmutableMap.of("num.partitions", String.valueOf(NUM_PARTITIONS)) ); kafkaServer.start(); kafkaHost = String.format("localhost:%d", kafkaServer.getPort()); dataSchema = getDataSchema(DATASOURCE); tuningConfig = new KafkaSupervisorTuningConfig( 1000, 50000, new Period("P1Y"), new File("/test"), null, null, true, false, null, numThreads, TEST_CHAT_THREADS, TEST_CHAT_RETRIES, TEST_HTTP_TIMEOUT, TEST_SHUTDOWN_TIMEOUT ); } @After public void tearDown() throws Exception { kafkaServer.close(); kafkaServer = null; zkServer.stop(); zkServer = null; supervisor = null; } @Test public void testNoInitialState() throws Exception { supervisor = getSupervisor(1, 1, true, "PT1H", null); addSomeEvents(1); Capture<KafkaIndexTask> captured = Capture.newInstance(); expect(taskMaster.getTaskQueue()).andReturn(Optional.of(taskQueue)).anyTimes(); expect(taskMaster.getTaskRunner()).andReturn(Optional.of(taskRunner)).anyTimes(); expect(taskStorage.getActiveTasks()).andReturn(ImmutableList.<Task>of()).anyTimes(); expect(indexerMetadataStorageCoordinator.getDataSourceMetadata(DATASOURCE)).andReturn( new KafkaDataSourceMetadata( null ) ).anyTimes(); expect(taskQueue.add(capture(captured))).andReturn(true); taskRunner.registerListener(anyObject(TaskRunnerListener.class), anyObject(Executor.class)); replayAll(); supervisor.start(); supervisor.runInternal(); verifyAll(); KafkaIndexTask task = captured.getValue(); Assert.assertEquals(dataSchema, task.getDataSchema()); Assert.assertEquals(KafkaTuningConfig.copyOf(tuningConfig), task.getTuningConfig()); KafkaIOConfig taskConfig = task.getIOConfig(); Assert.assertEquals(kafkaHost, taskConfig.getConsumerProperties().get("bootstrap.servers")); Assert.assertEquals("myCustomValue", taskConfig.getConsumerProperties().get("myCustomKey")); Assert.assertEquals("sequenceName-0", taskConfig.getBaseSequenceName()); Assert.assertTrue("isUseTransaction", taskConfig.isUseTransaction()); Assert.assertFalse("pauseAfterRead", taskConfig.isPauseAfterRead()); Assert.assertFalse("minimumMessageTime", taskConfig.getMinimumMessageTime().isPresent()); Assert.assertEquals(KAFKA_TOPIC, taskConfig.getStartPartitions().getTopic()); Assert.assertEquals(0L, (long) taskConfig.getStartPartitions().getPartitionOffsetMap().get(0)); Assert.assertEquals(0L, (long) taskConfig.getStartPartitions().getPartitionOffsetMap().get(1)); Assert.assertEquals(0L, (long) taskConfig.getStartPartitions().getPartitionOffsetMap().get(2)); Assert.assertEquals(KAFKA_TOPIC, taskConfig.getEndPartitions().getTopic()); Assert.assertEquals(Long.MAX_VALUE, (long) taskConfig.getEndPartitions().getPartitionOffsetMap().get(0)); Assert.assertEquals(Long.MAX_VALUE, (long) taskConfig.getEndPartitions().getPartitionOffsetMap().get(1)); Assert.assertEquals(Long.MAX_VALUE, (long) taskConfig.getEndPartitions().getPartitionOffsetMap().get(2)); } @Test public void testMultiTask() throws Exception { supervisor = getSupervisor(1, 2, true, "PT1H", null); addSomeEvents(1); Capture<KafkaIndexTask> captured = Capture.newInstance(CaptureType.ALL); expect(taskMaster.getTaskQueue()).andReturn(Optional.of(taskQueue)).anyTimes(); expect(taskMaster.getTaskRunner()).andReturn(Optional.<TaskRunner>absent()).anyTimes(); expect(taskStorage.getActiveTasks()).andReturn(ImmutableList.<Task>of()).anyTimes(); expect(indexerMetadataStorageCoordinator.getDataSourceMetadata(DATASOURCE)).andReturn( new KafkaDataSourceMetadata( null ) ).anyTimes(); expect(taskQueue.add(capture(captured))).andReturn(true).times(2); replayAll(); supervisor.start(); supervisor.runInternal(); verifyAll(); KafkaIndexTask task1 = captured.getValues().get(0); Assert.assertEquals(2, task1.getIOConfig().getStartPartitions().getPartitionOffsetMap().size()); Assert.assertEquals(2, task1.getIOConfig().getEndPartitions().getPartitionOffsetMap().size()); Assert.assertEquals(0L, (long) task1.getIOConfig().getStartPartitions().getPartitionOffsetMap().get(0)); Assert.assertEquals(Long.MAX_VALUE, (long) task1.getIOConfig().getEndPartitions().getPartitionOffsetMap().get(0)); Assert.assertEquals(0L, (long) task1.getIOConfig().getStartPartitions().getPartitionOffsetMap().get(2)); Assert.assertEquals(Long.MAX_VALUE, (long) task1.getIOConfig().getEndPartitions().getPartitionOffsetMap().get(2)); KafkaIndexTask task2 = captured.getValues().get(1); Assert.assertEquals(1, task2.getIOConfig().getStartPartitions().getPartitionOffsetMap().size()); Assert.assertEquals(1, task2.getIOConfig().getEndPartitions().getPartitionOffsetMap().size()); Assert.assertEquals(0L, (long) task2.getIOConfig().getStartPartitions().getPartitionOffsetMap().get(1)); Assert.assertEquals(Long.MAX_VALUE, (long) task2.getIOConfig().getEndPartitions().getPartitionOffsetMap().get(1)); } @Test public void testReplicas() throws Exception { supervisor = getSupervisor(2, 1, true, "PT1H", null); addSomeEvents(1); Capture<KafkaIndexTask> captured = Capture.newInstance(CaptureType.ALL); expect(taskMaster.getTaskQueue()).andReturn(Optional.of(taskQueue)).anyTimes(); expect(taskMaster.getTaskRunner()).andReturn(Optional.<TaskRunner>absent()).anyTimes(); expect(taskStorage.getActiveTasks()).andReturn(ImmutableList.<Task>of()).anyTimes(); expect(indexerMetadataStorageCoordinator.getDataSourceMetadata(DATASOURCE)).andReturn( new KafkaDataSourceMetadata( null ) ).anyTimes(); expect(taskQueue.add(capture(captured))).andReturn(true).times(2); replayAll(); supervisor.start(); supervisor.runInternal(); verifyAll(); KafkaIndexTask task1 = captured.getValues().get(0); Assert.assertEquals(3, task1.getIOConfig().getStartPartitions().getPartitionOffsetMap().size()); Assert.assertEquals(3, task1.getIOConfig().getEndPartitions().getPartitionOffsetMap().size()); Assert.assertEquals(0L, (long) task1.getIOConfig().getStartPartitions().getPartitionOffsetMap().get(0)); Assert.assertEquals(0L, (long) task1.getIOConfig().getStartPartitions().getPartitionOffsetMap().get(1)); Assert.assertEquals(0L, (long) task1.getIOConfig().getStartPartitions().getPartitionOffsetMap().get(2)); KafkaIndexTask task2 = captured.getValues().get(1); Assert.assertEquals(3, task2.getIOConfig().getStartPartitions().getPartitionOffsetMap().size()); Assert.assertEquals(3, task2.getIOConfig().getEndPartitions().getPartitionOffsetMap().size()); Assert.assertEquals(0L, (long) task2.getIOConfig().getStartPartitions().getPartitionOffsetMap().get(0)); Assert.assertEquals(0L, (long) task2.getIOConfig().getStartPartitions().getPartitionOffsetMap().get(1)); Assert.assertEquals(0L, (long) task2.getIOConfig().getStartPartitions().getPartitionOffsetMap().get(2)); } @Test public void testLateMessageRejectionPeriod() throws Exception { supervisor = getSupervisor(2, 1, true, "PT1H", new Period("PT1H")); addSomeEvents(1); Capture<KafkaIndexTask> captured = Capture.newInstance(CaptureType.ALL); expect(taskMaster.getTaskQueue()).andReturn(Optional.of(taskQueue)).anyTimes(); expect(taskMaster.getTaskRunner()).andReturn(Optional.<TaskRunner>absent()).anyTimes(); expect(taskStorage.getActiveTasks()).andReturn(ImmutableList.<Task>of()).anyTimes(); expect(indexerMetadataStorageCoordinator.getDataSourceMetadata(DATASOURCE)).andReturn( new KafkaDataSourceMetadata( null ) ).anyTimes(); expect(taskQueue.add(capture(captured))).andReturn(true).times(2); replayAll(); supervisor.start(); supervisor.runInternal(); verifyAll(); KafkaIndexTask task1 = captured.getValues().get(0); KafkaIndexTask task2 = captured.getValues().get(1); Assert.assertTrue( "minimumMessageTime", task1.getIOConfig().getMinimumMessageTime().get().plusMinutes(59).isBeforeNow() ); Assert.assertTrue( "minimumMessageTime", task1.getIOConfig().getMinimumMessageTime().get().plusMinutes(61).isAfterNow() ); Assert.assertEquals( task1.getIOConfig().getMinimumMessageTime().get(), task2.getIOConfig().getMinimumMessageTime().get() ); } @Test /** * Test generating the starting offsets from the partition high water marks in Kafka. */ public void testLatestOffset() throws Exception { supervisor = getSupervisor(1, 1, false, "PT1H", null); addSomeEvents(1100); Capture<KafkaIndexTask> captured = Capture.newInstance(); expect(taskMaster.getTaskQueue()).andReturn(Optional.of(taskQueue)).anyTimes(); expect(taskMaster.getTaskRunner()).andReturn(Optional.<TaskRunner>absent()).anyTimes(); expect(taskStorage.getActiveTasks()).andReturn(ImmutableList.<Task>of()).anyTimes(); expect(indexerMetadataStorageCoordinator.getDataSourceMetadata(DATASOURCE)).andReturn( new KafkaDataSourceMetadata( null ) ).anyTimes(); expect(taskQueue.add(capture(captured))).andReturn(true); replayAll(); supervisor.start(); supervisor.runInternal(); verifyAll(); KafkaIndexTask task = captured.getValue(); Assert.assertEquals(1100L, (long) task.getIOConfig().getStartPartitions().getPartitionOffsetMap().get(0)); Assert.assertEquals(1100L, (long) task.getIOConfig().getStartPartitions().getPartitionOffsetMap().get(1)); Assert.assertEquals(1100L, (long) task.getIOConfig().getStartPartitions().getPartitionOffsetMap().get(2)); } @Test /** * Test generating the starting offsets from the partition data stored in druid_dataSource which contains the * offsets of the last built segments. */ public void testDatasourceMetadata() throws Exception { supervisor = getSupervisor(1, 1, true, "PT1H", null); addSomeEvents(100); Capture<KafkaIndexTask> captured = Capture.newInstance(); expect(taskMaster.getTaskQueue()).andReturn(Optional.of(taskQueue)).anyTimes(); expect(taskMaster.getTaskRunner()).andReturn(Optional.<TaskRunner>absent()).anyTimes(); expect(taskStorage.getActiveTasks()).andReturn(ImmutableList.<Task>of()).anyTimes(); expect(indexerMetadataStorageCoordinator.getDataSourceMetadata(DATASOURCE)).andReturn( new KafkaDataSourceMetadata( new KafkaPartitions(KAFKA_TOPIC, ImmutableMap.of(0, 10L, 1, 20L, 2, 30L)) ) ).anyTimes(); expect(taskQueue.add(capture(captured))).andReturn(true); replayAll(); supervisor.start(); supervisor.runInternal(); verifyAll(); KafkaIndexTask task = captured.getValue(); KafkaIOConfig taskConfig = task.getIOConfig(); Assert.assertEquals(String.format("sequenceName-0", DATASOURCE), taskConfig.getBaseSequenceName()); Assert.assertEquals(10L, (long) taskConfig.getStartPartitions().getPartitionOffsetMap().get(0)); Assert.assertEquals(20L, (long) taskConfig.getStartPartitions().getPartitionOffsetMap().get(1)); Assert.assertEquals(30L, (long) taskConfig.getStartPartitions().getPartitionOffsetMap().get(2)); } @Test(expected = ISE.class) public void testBadMetadataOffsets() throws Exception { supervisor = getSupervisor(1, 1, true, "PT1H", null); addSomeEvents(1); expect(taskMaster.getTaskRunner()).andReturn(Optional.<TaskRunner>absent()).anyTimes(); expect(taskStorage.getActiveTasks()).andReturn(ImmutableList.<Task>of()).anyTimes(); expect(indexerMetadataStorageCoordinator.getDataSourceMetadata(DATASOURCE)).andReturn( new KafkaDataSourceMetadata( new KafkaPartitions(KAFKA_TOPIC, ImmutableMap.of(0, 10L, 1, 20L, 2, 30L)) ) ).anyTimes(); replayAll(); supervisor.start(); supervisor.runInternal(); } @Test public void testKillIncompatibleTasks() throws Exception { supervisor = getSupervisor(2, 1, true, "PT1H", null); addSomeEvents(1); Task id1 = createKafkaIndexTask( // unexpected # of partitions (kill) "id1", DATASOURCE, "index_kafka_testDS__some_other_sequenceName", new KafkaPartitions("topic", ImmutableMap.of(0, 0L)), new KafkaPartitions("topic", ImmutableMap.of(0, 10L)), null ); Task id2 = createKafkaIndexTask( // correct number of partitions and ranges (don't kill) "id2", DATASOURCE, "sequenceName-0", new KafkaPartitions("topic", ImmutableMap.of(0, 0L, 1, 0L, 2, 0L)), new KafkaPartitions("topic", ImmutableMap.of(0, 333L, 1, 333L, 2, 333L)), null ); Task id3 = createKafkaIndexTask( // unexpected range on partition 2 (kill) "id3", DATASOURCE, "index_kafka_testDS__some_other_sequenceName", new KafkaPartitions("topic", ImmutableMap.of(0, 0L, 1, 0L, 2, 1L)), new KafkaPartitions("topic", ImmutableMap.of(0, 333L, 1, 333L, 2, 330L)), null ); Task id4 = createKafkaIndexTask( // different datasource (don't kill) "id4", "other-datasource", "index_kafka_testDS_d927edff33c4b3f", new KafkaPartitions("topic", ImmutableMap.of(0, 0L)), new KafkaPartitions("topic", ImmutableMap.of(0, 10L)), null ); Task id5 = new RealtimeIndexTask( // non KafkaIndexTask (don't kill) "id5", null, new FireDepartment( dataSchema, new RealtimeIOConfig(null, null, null), null ), null ); List<Task> existingTasks = ImmutableList.of(id1, id2, id3, id4, id5); expect(taskMaster.getTaskQueue()).andReturn(Optional.of(taskQueue)).anyTimes(); expect(taskMaster.getTaskRunner()).andReturn(Optional.of(taskRunner)).anyTimes(); expect(taskRunner.getRunningTasks()).andReturn(Collections.EMPTY_LIST).anyTimes(); expect(taskStorage.getActiveTasks()).andReturn(existingTasks).anyTimes(); expect(taskStorage.getStatus("id1")).andReturn(Optional.of(TaskStatus.running("id1"))).anyTimes(); expect(taskStorage.getStatus("id2")).andReturn(Optional.of(TaskStatus.running("id2"))).anyTimes(); expect(taskStorage.getStatus("id3")).andReturn(Optional.of(TaskStatus.running("id3"))).anyTimes(); expect(taskStorage.getTask("id1")).andReturn(Optional.of(id1)).anyTimes(); expect(taskStorage.getTask("id2")).andReturn(Optional.of(id2)).anyTimes(); expect(taskStorage.getTask("id3")).andReturn(Optional.of(id3)).anyTimes(); expect(taskClient.getStatusAsync(anyString())).andReturn(Futures.immediateFuture(KafkaIndexTask.Status.NOT_STARTED)) .anyTimes(); expect(taskClient.getStartTimeAsync(anyString())).andReturn(Futures.immediateFuture(DateTime.now())).anyTimes(); expect(indexerMetadataStorageCoordinator.getDataSourceMetadata(DATASOURCE)).andReturn( new KafkaDataSourceMetadata( null ) ).anyTimes(); taskRunner.registerListener(anyObject(TaskRunnerListener.class), anyObject(Executor.class)); taskQueue.shutdown("id1"); taskQueue.shutdown("id3"); expect(taskQueue.add(anyObject(Task.class))).andReturn(true); replayAll(); supervisor.start(); supervisor.runInternal(); verifyAll(); } @Test public void testKillBadPartitionAssignment() throws Exception { supervisor = getSupervisor(1, 2, true, "PT1H", null); addSomeEvents(1); Task id1 = createKafkaIndexTask( "id1", DATASOURCE, "sequenceName-0", new KafkaPartitions("topic", ImmutableMap.of(0, 0L, 2, 0L)), new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 2, Long.MAX_VALUE)), null ); Task id2 = createKafkaIndexTask( "id2", DATASOURCE, "sequenceName-1", new KafkaPartitions("topic", ImmutableMap.of(1, 0L)), new KafkaPartitions("topic", ImmutableMap.of(1, Long.MAX_VALUE)), null ); Task id3 = createKafkaIndexTask( "id3", DATASOURCE, "sequenceName-0", new KafkaPartitions("topic", ImmutableMap.of(0, 0L, 1, 0L, 2, 0L)), new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)), null ); Task id4 = createKafkaIndexTask( "id4", DATASOURCE, "sequenceName-0", new KafkaPartitions("topic", ImmutableMap.of(0, 0L, 1, 0L)), new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE)), null ); Task id5 = createKafkaIndexTask( "id5", DATASOURCE, "sequenceName-0", new KafkaPartitions("topic", ImmutableMap.of(1, 0L, 2, 0L)), new KafkaPartitions("topic", ImmutableMap.of(1, Long.MAX_VALUE, 2, Long.MAX_VALUE)), null ); List<Task> existingTasks = ImmutableList.of(id1, id2, id3, id4, id5); expect(taskMaster.getTaskQueue()).andReturn(Optional.of(taskQueue)).anyTimes(); expect(taskMaster.getTaskRunner()).andReturn(Optional.of(taskRunner)).anyTimes(); expect(taskRunner.getRunningTasks()).andReturn(Collections.EMPTY_LIST).anyTimes(); expect(taskStorage.getActiveTasks()).andReturn(existingTasks).anyTimes(); expect(taskStorage.getStatus("id1")).andReturn(Optional.of(TaskStatus.running("id1"))).anyTimes(); expect(taskStorage.getStatus("id2")).andReturn(Optional.of(TaskStatus.running("id2"))).anyTimes(); expect(taskStorage.getStatus("id3")).andReturn(Optional.of(TaskStatus.running("id3"))).anyTimes(); expect(taskStorage.getStatus("id4")).andReturn(Optional.of(TaskStatus.running("id4"))).anyTimes(); expect(taskStorage.getStatus("id5")).andReturn(Optional.of(TaskStatus.running("id5"))).anyTimes(); expect(taskStorage.getTask("id1")).andReturn(Optional.of(id1)).anyTimes(); expect(taskStorage.getTask("id2")).andReturn(Optional.of(id2)).anyTimes(); expect(taskStorage.getTask("id3")).andReturn(Optional.of(id3)).anyTimes(); expect(taskStorage.getTask("id4")).andReturn(Optional.of(id3)).anyTimes(); expect(taskStorage.getTask("id5")).andReturn(Optional.of(id3)).anyTimes(); expect(taskClient.getStatusAsync(anyString())).andReturn(Futures.immediateFuture(KafkaIndexTask.Status.NOT_STARTED)) .anyTimes(); expect(taskClient.getStartTimeAsync(anyString())).andReturn(Futures.immediateFuture(DateTime.now())).anyTimes(); expect(indexerMetadataStorageCoordinator.getDataSourceMetadata(DATASOURCE)).andReturn( new KafkaDataSourceMetadata( null ) ).anyTimes(); taskRunner.registerListener(anyObject(TaskRunnerListener.class), anyObject(Executor.class)); taskQueue.shutdown("id3"); taskQueue.shutdown("id4"); taskQueue.shutdown("id5"); replayAll(); supervisor.start(); supervisor.runInternal(); verifyAll(); } @Test public void testRequeueTaskWhenFailed() throws Exception { supervisor = getSupervisor(2, 2, true, "PT1H", null); addSomeEvents(1); Capture<Task> captured = Capture.newInstance(CaptureType.ALL); expect(taskMaster.getTaskQueue()).andReturn(Optional.of(taskQueue)).anyTimes(); expect(taskMaster.getTaskRunner()).andReturn(Optional.of(taskRunner)).anyTimes(); expect(taskRunner.getRunningTasks()).andReturn(Collections.EMPTY_LIST).anyTimes(); expect(taskStorage.getActiveTasks()).andReturn(ImmutableList.<Task>of()).anyTimes(); expect(taskClient.getStatusAsync(anyString())).andReturn(Futures.immediateFuture(KafkaIndexTask.Status.NOT_STARTED)) .anyTimes(); expect(taskClient.getStartTimeAsync(anyString())).andReturn(Futures.immediateFuture(DateTime.now())).anyTimes(); expect(indexerMetadataStorageCoordinator.getDataSourceMetadata(DATASOURCE)).andReturn( new KafkaDataSourceMetadata( null ) ).anyTimes(); expect(taskQueue.add(capture(captured))).andReturn(true).times(4); taskRunner.registerListener(anyObject(TaskRunnerListener.class), anyObject(Executor.class)); replayAll(); supervisor.start(); supervisor.runInternal(); verifyAll(); List<Task> tasks = captured.getValues(); // test that running the main loop again checks the status of the tasks that were created and does nothing if they // are all still running reset(taskStorage); expect(taskStorage.getActiveTasks()).andReturn(tasks).anyTimes(); for (Task task : tasks) { expect(taskStorage.getStatus(task.getId())).andReturn(Optional.of(TaskStatus.running(task.getId()))).anyTimes(); expect(taskStorage.getTask(task.getId())).andReturn(Optional.of(task)).anyTimes(); } replay(taskStorage); supervisor.runInternal(); verifyAll(); // test that a task failing causes a new task to be re-queued with the same parameters Capture<Task> aNewTaskCapture = Capture.newInstance(); List<Task> imStillAlive = tasks.subList(0, 3); KafkaIndexTask iHaveFailed = (KafkaIndexTask) tasks.get(3); reset(taskStorage); reset(taskQueue); expect(taskStorage.getActiveTasks()).andReturn(imStillAlive).anyTimes(); for (Task task : imStillAlive) { expect(taskStorage.getStatus(task.getId())).andReturn(Optional.of(TaskStatus.running(task.getId()))).anyTimes(); expect(taskStorage.getTask(task.getId())).andReturn(Optional.of(task)).anyTimes(); } expect(taskStorage.getStatus(iHaveFailed.getId())).andReturn(Optional.of(TaskStatus.failure(iHaveFailed.getId()))); expect(taskStorage.getTask(iHaveFailed.getId())).andReturn(Optional.of((Task) iHaveFailed)).anyTimes(); expect(taskQueue.add(capture(aNewTaskCapture))).andReturn(true); replay(taskStorage); replay(taskQueue); supervisor.runInternal(); verifyAll(); Assert.assertNotEquals(iHaveFailed.getId(), aNewTaskCapture.getValue().getId()); Assert.assertEquals( iHaveFailed.getIOConfig().getBaseSequenceName(), ((KafkaIndexTask) aNewTaskCapture.getValue()).getIOConfig().getBaseSequenceName() ); } @Test public void testRequeueAdoptedTaskWhenFailed() throws Exception { supervisor = getSupervisor(2, 1, true, "PT1H", null); addSomeEvents(1); DateTime now = DateTime.now(); Task id1 = createKafkaIndexTask( "id1", DATASOURCE, "sequenceName-0", new KafkaPartitions("topic", ImmutableMap.of(0, 0L, 2, 0L)), new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 2, Long.MAX_VALUE)), now ); List<Task> existingTasks = ImmutableList.of(id1); Capture<Task> captured = Capture.newInstance(); expect(taskMaster.getTaskQueue()).andReturn(Optional.of(taskQueue)).anyTimes(); expect(taskMaster.getTaskRunner()).andReturn(Optional.of(taskRunner)).anyTimes(); expect(taskRunner.getRunningTasks()).andReturn(Collections.EMPTY_LIST).anyTimes(); expect(taskStorage.getActiveTasks()).andReturn(existingTasks).anyTimes(); expect(taskStorage.getStatus("id1")).andReturn(Optional.of(TaskStatus.running("id1"))).anyTimes(); expect(taskStorage.getTask("id1")).andReturn(Optional.of(id1)).anyTimes(); expect(taskClient.getStatusAsync("id1")).andReturn(Futures.immediateFuture(KafkaIndexTask.Status.READING)); expect(taskClient.getStartTimeAsync("id1")).andReturn(Futures.immediateFuture(now)).anyTimes(); expect(taskQueue.add(capture(captured))).andReturn(true); expect(indexerMetadataStorageCoordinator.getDataSourceMetadata(DATASOURCE)).andReturn( new KafkaDataSourceMetadata( null ) ).anyTimes(); taskRunner.registerListener(anyObject(TaskRunnerListener.class), anyObject(Executor.class)); replayAll(); supervisor.start(); supervisor.runInternal(); verifyAll(); // check that replica tasks are created with the same minimumMessageTime as tasks inherited from another supervisor Assert.assertEquals(now, ((KafkaIndexTask) captured.getValue()).getIOConfig().getMinimumMessageTime().get()); // test that a task failing causes a new task to be re-queued with the same parameters String runningTaskId = captured.getValue().getId(); Capture<Task> aNewTaskCapture = Capture.newInstance(); KafkaIndexTask iHaveFailed = (KafkaIndexTask) existingTasks.get(0); reset(taskStorage); reset(taskQueue); reset(taskClient); expect(taskStorage.getActiveTasks()).andReturn(ImmutableList.of(captured.getValue())).anyTimes(); expect(taskStorage.getStatus(iHaveFailed.getId())).andReturn(Optional.of(TaskStatus.failure(iHaveFailed.getId()))); expect(taskStorage.getStatus(runningTaskId)).andReturn(Optional.of(TaskStatus.running(runningTaskId))).anyTimes(); expect(taskStorage.getTask(iHaveFailed.getId())).andReturn(Optional.of((Task) iHaveFailed)).anyTimes(); expect(taskStorage.getTask(runningTaskId)).andReturn(Optional.of(captured.getValue())).anyTimes(); expect(taskClient.getStatusAsync(runningTaskId)).andReturn(Futures.immediateFuture(KafkaIndexTask.Status.READING)); expect(taskClient.getStartTimeAsync(runningTaskId)).andReturn(Futures.immediateFuture(now)).anyTimes(); expect(taskQueue.add(capture(aNewTaskCapture))).andReturn(true); replay(taskStorage); replay(taskQueue); replay(taskClient); supervisor.runInternal(); verifyAll(); Assert.assertNotEquals(iHaveFailed.getId(), aNewTaskCapture.getValue().getId()); Assert.assertEquals( iHaveFailed.getIOConfig().getBaseSequenceName(), ((KafkaIndexTask) aNewTaskCapture.getValue()).getIOConfig().getBaseSequenceName() ); // check that failed tasks are recreated with the same minimumMessageTime as the task it replaced, even if that // task came from another supervisor Assert.assertEquals(now, ((KafkaIndexTask) aNewTaskCapture.getValue()).getIOConfig().getMinimumMessageTime().get()); } @Test public void testQueueNextTasksOnSuccess() throws Exception { supervisor = getSupervisor(2, 2, true, "PT1H", null); addSomeEvents(1); Capture<Task> captured = Capture.newInstance(CaptureType.ALL); expect(taskMaster.getTaskQueue()).andReturn(Optional.of(taskQueue)).anyTimes(); expect(taskMaster.getTaskRunner()).andReturn(Optional.of(taskRunner)).anyTimes(); expect(taskRunner.getRunningTasks()).andReturn(Collections.EMPTY_LIST).anyTimes(); expect(taskStorage.getActiveTasks()).andReturn(ImmutableList.<Task>of()).anyTimes(); expect(taskClient.getStatusAsync(anyString())).andReturn(Futures.immediateFuture(KafkaIndexTask.Status.NOT_STARTED)) .anyTimes(); expect(taskClient.getStartTimeAsync(anyString())).andReturn(Futures.immediateFuture(DateTime.now())).anyTimes(); expect(indexerMetadataStorageCoordinator.getDataSourceMetadata(DATASOURCE)).andReturn( new KafkaDataSourceMetadata( null ) ).anyTimes(); expect(taskQueue.add(capture(captured))).andReturn(true).times(4); taskRunner.registerListener(anyObject(TaskRunnerListener.class), anyObject(Executor.class)); replayAll(); supervisor.start(); supervisor.runInternal(); verifyAll(); List<Task> tasks = captured.getValues(); reset(taskStorage); expect(taskStorage.getActiveTasks()).andReturn(tasks).anyTimes(); for (Task task : tasks) { expect(taskStorage.getStatus(task.getId())).andReturn(Optional.of(TaskStatus.running(task.getId()))).anyTimes(); expect(taskStorage.getTask(task.getId())).andReturn(Optional.of(task)).anyTimes(); } replay(taskStorage); supervisor.runInternal(); verifyAll(); // test that a task succeeding causes a new task to be re-queued with the next offset range and causes any replica // tasks to be shutdown Capture<Task> newTasksCapture = Capture.newInstance(CaptureType.ALL); Capture<String> shutdownTaskIdCapture = Capture.newInstance(); List<Task> imStillRunning = tasks.subList(1, 4); KafkaIndexTask iAmSuccess = (KafkaIndexTask) tasks.get(0); reset(taskStorage); reset(taskQueue); reset(taskClient); expect(taskStorage.getActiveTasks()).andReturn(imStillRunning).anyTimes(); for (Task task : imStillRunning) { expect(taskStorage.getStatus(task.getId())).andReturn(Optional.of(TaskStatus.running(task.getId()))).anyTimes(); expect(taskStorage.getTask(task.getId())).andReturn(Optional.of(task)).anyTimes(); } expect(taskStorage.getStatus(iAmSuccess.getId())).andReturn(Optional.of(TaskStatus.success(iAmSuccess.getId()))); expect(taskStorage.getTask(iAmSuccess.getId())).andReturn(Optional.of((Task) iAmSuccess)).anyTimes(); expect(taskQueue.add(capture(newTasksCapture))).andReturn(true).times(2); expect(taskClient.stopAsync(capture(shutdownTaskIdCapture), eq(false))).andReturn(Futures.immediateFuture(true)); replay(taskStorage); replay(taskQueue); replay(taskClient); supervisor.runInternal(); verifyAll(); // make sure we killed the right task (sequenceName for replicas are the same) Assert.assertTrue(shutdownTaskIdCapture.getValue().contains(iAmSuccess.getIOConfig().getBaseSequenceName())); } @Test public void testBeginPublishAndQueueNextTasks() throws Exception { final TaskLocation location = new TaskLocation("testHost", 1234); supervisor = getSupervisor(2, 2, true, "PT1M", null); addSomeEvents(100); Capture<Task> captured = Capture.newInstance(CaptureType.ALL); expect(taskMaster.getTaskQueue()).andReturn(Optional.of(taskQueue)).anyTimes(); expect(taskMaster.getTaskRunner()).andReturn(Optional.of(taskRunner)).anyTimes(); expect(taskRunner.getRunningTasks()).andReturn(Collections.EMPTY_LIST).anyTimes(); expect(taskStorage.getActiveTasks()).andReturn(ImmutableList.<Task>of()).anyTimes(); expect(indexerMetadataStorageCoordinator.getDataSourceMetadata(DATASOURCE)).andReturn( new KafkaDataSourceMetadata( null ) ).anyTimes(); expect(taskQueue.add(capture(captured))).andReturn(true).times(4); taskRunner.registerListener(anyObject(TaskRunnerListener.class), anyObject(Executor.class)); replayAll(); supervisor.start(); supervisor.runInternal(); verifyAll(); List<Task> tasks = captured.getValues(); Collection workItems = new ArrayList<>(); for (Task task : tasks) { workItems.add(new TestTaskRunnerWorkItem(task.getId(), null, location)); } reset(taskStorage, taskRunner, taskClient, taskQueue); captured = Capture.newInstance(CaptureType.ALL); expect(taskStorage.getActiveTasks()).andReturn(tasks).anyTimes(); for (Task task : tasks) { expect(taskStorage.getStatus(task.getId())).andReturn(Optional.of(TaskStatus.running(task.getId()))).anyTimes(); expect(taskStorage.getTask(task.getId())).andReturn(Optional.of(task)).anyTimes(); } expect(taskRunner.getRunningTasks()).andReturn(workItems).anyTimes(); expect(taskClient.getStatusAsync(anyString())) .andReturn(Futures.immediateFuture(KafkaIndexTask.Status.READING)) .anyTimes(); expect(taskClient.getStartTimeAsync(EasyMock.contains("sequenceName-0"))) .andReturn(Futures.immediateFuture(DateTime.now().minusMinutes(2))) .andReturn(Futures.immediateFuture(DateTime.now())); expect(taskClient.getStartTimeAsync(EasyMock.contains("sequenceName-1"))) .andReturn(Futures.immediateFuture(DateTime.now())) .times(2); expect(taskClient.pauseAsync(EasyMock.contains("sequenceName-0"))) .andReturn(Futures.immediateFuture((Map<Integer, Long>) ImmutableMap.of(0, 10L, 1, 20L, 2, 30L))) .andReturn(Futures.immediateFuture((Map<Integer, Long>) ImmutableMap.of(0, 10L, 1, 15L, 2, 35L))); expect( taskClient.setEndOffsetsAsync( EasyMock.contains("sequenceName-0"), EasyMock.eq(ImmutableMap.of(0, 10L, 1, 20L, 2, 35L)), EasyMock.eq(true) ) ).andReturn(Futures.immediateFuture(true)).times(2); expect(taskQueue.add(capture(captured))).andReturn(true).times(2); replay(taskStorage, taskRunner, taskClient, taskQueue); supervisor.runInternal(); verifyAll(); for (Task task : captured.getValues()) { KafkaIndexTask kafkaIndexTask = (KafkaIndexTask) task; Assert.assertEquals(dataSchema, kafkaIndexTask.getDataSchema()); Assert.assertEquals(KafkaTuningConfig.copyOf(tuningConfig), kafkaIndexTask.getTuningConfig()); KafkaIOConfig taskConfig = kafkaIndexTask.getIOConfig(); Assert.assertEquals("sequenceName-0", taskConfig.getBaseSequenceName()); Assert.assertTrue("isUseTransaction", taskConfig.isUseTransaction()); Assert.assertFalse("pauseAfterRead", taskConfig.isPauseAfterRead()); Assert.assertEquals(KAFKA_TOPIC, taskConfig.getStartPartitions().getTopic()); Assert.assertEquals(10L, (long) taskConfig.getStartPartitions().getPartitionOffsetMap().get(0)); Assert.assertEquals(20L, (long) taskConfig.getStartPartitions().getPartitionOffsetMap().get(1)); Assert.assertEquals(35L, (long) taskConfig.getStartPartitions().getPartitionOffsetMap().get(2)); } } @Test public void testDiscoverExistingPublishingTask() throws Exception { final TaskLocation location = new TaskLocation("testHost", 1234); supervisor = getSupervisor(1, 1, true, "PT1H", null); addSomeEvents(1); Task task = createKafkaIndexTask( "id1", DATASOURCE, "sequenceName-0", new KafkaPartitions("topic", ImmutableMap.of(0, 0L, 1, 0L, 2, 0L)), new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)), null ); Collection workItems = new ArrayList<>(); workItems.add(new TestTaskRunnerWorkItem(task.getId(), null, location)); Capture<KafkaIndexTask> captured = Capture.newInstance(); expect(taskMaster.getTaskQueue()).andReturn(Optional.of(taskQueue)).anyTimes(); expect(taskMaster.getTaskRunner()).andReturn(Optional.of(taskRunner)).anyTimes(); expect(taskRunner.getRunningTasks()).andReturn(workItems).anyTimes(); expect(taskStorage.getActiveTasks()).andReturn(ImmutableList.of(task)).anyTimes(); expect(taskStorage.getStatus("id1")).andReturn(Optional.of(TaskStatus.running("id1"))).anyTimes(); expect(taskStorage.getTask("id1")).andReturn(Optional.of(task)).anyTimes(); expect(indexerMetadataStorageCoordinator.getDataSourceMetadata(DATASOURCE)).andReturn( new KafkaDataSourceMetadata( null ) ).anyTimes(); expect(taskClient.getStatusAsync("id1")).andReturn(Futures.immediateFuture(KafkaIndexTask.Status.PUBLISHING)); expect(taskClient.getCurrentOffsetsAsync("id1", false)) .andReturn(Futures.immediateFuture((Map<Integer, Long>) ImmutableMap.of(0, 10L, 1, 20L, 2, 30L))); expect(taskClient.getCurrentOffsets("id1", true)).andReturn(ImmutableMap.of(0, 10L, 1, 20L, 2, 30L)); expect(taskQueue.add(capture(captured))).andReturn(true); taskRunner.registerListener(anyObject(TaskRunnerListener.class), anyObject(Executor.class)); replayAll(); supervisor.start(); supervisor.runInternal(); SupervisorReport report = supervisor.getStatus(); verifyAll(); Assert.assertEquals(DATASOURCE, report.getId()); Assert.assertTrue(report.getPayload() instanceof KafkaSupervisorReport.KafkaSupervisorReportPayload); KafkaSupervisorReport.KafkaSupervisorReportPayload payload = (KafkaSupervisorReport.KafkaSupervisorReportPayload) report.getPayload(); Assert.assertEquals(DATASOURCE, payload.getDataSource()); Assert.assertEquals(3600L, (long) payload.getDurationSeconds()); Assert.assertEquals(NUM_PARTITIONS, (int) payload.getPartitions()); Assert.assertEquals(1, (int) payload.getReplicas()); Assert.assertEquals(KAFKA_TOPIC, payload.getTopic()); Assert.assertEquals(0, payload.getActiveTasks().size()); Assert.assertEquals(1, payload.getPublishingTasks().size()); TaskReportData publishingReport = payload.getPublishingTasks().get(0); Assert.assertEquals("id1", publishingReport.getId()); Assert.assertEquals(ImmutableMap.of(0, 0L, 1, 0L, 2, 0L), publishingReport.getStartingOffsets()); Assert.assertEquals(ImmutableMap.of(0, 10L, 1, 20L, 2, 30L), publishingReport.getCurrentOffsets()); KafkaIndexTask capturedTask = captured.getValue(); Assert.assertEquals(dataSchema, capturedTask.getDataSchema()); Assert.assertEquals(KafkaTuningConfig.copyOf(tuningConfig), capturedTask.getTuningConfig()); KafkaIOConfig capturedTaskConfig = capturedTask.getIOConfig(); Assert.assertEquals(kafkaHost, capturedTaskConfig.getConsumerProperties().get("bootstrap.servers")); Assert.assertEquals("myCustomValue", capturedTaskConfig.getConsumerProperties().get("myCustomKey")); Assert.assertEquals("sequenceName-0", capturedTaskConfig.getBaseSequenceName()); Assert.assertTrue("isUseTransaction", capturedTaskConfig.isUseTransaction()); Assert.assertFalse("pauseAfterRead", capturedTaskConfig.isPauseAfterRead()); // check that the new task was created with starting offsets matching where the publishing task finished Assert.assertEquals(KAFKA_TOPIC, capturedTaskConfig.getStartPartitions().getTopic()); Assert.assertEquals(10L, (long) capturedTaskConfig.getStartPartitions().getPartitionOffsetMap().get(0)); Assert.assertEquals(20L, (long) capturedTaskConfig.getStartPartitions().getPartitionOffsetMap().get(1)); Assert.assertEquals(30L, (long) capturedTaskConfig.getStartPartitions().getPartitionOffsetMap().get(2)); Assert.assertEquals(KAFKA_TOPIC, capturedTaskConfig.getEndPartitions().getTopic()); Assert.assertEquals(Long.MAX_VALUE, (long) capturedTaskConfig.getEndPartitions().getPartitionOffsetMap().get(0)); Assert.assertEquals(Long.MAX_VALUE, (long) capturedTaskConfig.getEndPartitions().getPartitionOffsetMap().get(1)); Assert.assertEquals(Long.MAX_VALUE, (long) capturedTaskConfig.getEndPartitions().getPartitionOffsetMap().get(2)); } @Test public void testDiscoverExistingPublishingTaskWithDifferentPartitionAllocation() throws Exception { final TaskLocation location = new TaskLocation("testHost", 1234); supervisor = getSupervisor(1, 1, true, "PT1H", null); addSomeEvents(1); Task task = createKafkaIndexTask( "id1", DATASOURCE, "sequenceName-0", new KafkaPartitions("topic", ImmutableMap.of(0, 0L, 2, 0L)), new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 2, Long.MAX_VALUE)), null ); Collection workItems = new ArrayList<>(); workItems.add(new TestTaskRunnerWorkItem(task.getId(), null, location)); Capture<KafkaIndexTask> captured = Capture.newInstance(); expect(taskMaster.getTaskQueue()).andReturn(Optional.of(taskQueue)).anyTimes(); expect(taskMaster.getTaskRunner()).andReturn(Optional.of(taskRunner)).anyTimes(); expect(taskRunner.getRunningTasks()).andReturn(workItems).anyTimes(); expect(taskStorage.getActiveTasks()).andReturn(ImmutableList.of(task)).anyTimes(); expect(taskStorage.getStatus("id1")).andReturn(Optional.of(TaskStatus.running("id1"))).anyTimes(); expect(taskStorage.getTask("id1")).andReturn(Optional.of(task)).anyTimes(); expect(indexerMetadataStorageCoordinator.getDataSourceMetadata(DATASOURCE)).andReturn( new KafkaDataSourceMetadata( null ) ).anyTimes(); expect(taskClient.getStatusAsync("id1")).andReturn(Futures.immediateFuture(KafkaIndexTask.Status.PUBLISHING)); expect(taskClient.getCurrentOffsetsAsync("id1", false)) .andReturn(Futures.immediateFuture((Map<Integer, Long>) ImmutableMap.of(0, 10L, 2, 30L))); expect(taskClient.getCurrentOffsets("id1", true)).andReturn(ImmutableMap.of(0, 10L, 2, 30L)); expect(taskQueue.add(capture(captured))).andReturn(true); taskRunner.registerListener(anyObject(TaskRunnerListener.class), anyObject(Executor.class)); replayAll(); supervisor.start(); supervisor.runInternal(); SupervisorReport report = supervisor.getStatus(); verifyAll(); Assert.assertEquals(DATASOURCE, report.getId()); Assert.assertTrue(report.getPayload() instanceof KafkaSupervisorReport.KafkaSupervisorReportPayload); KafkaSupervisorReport.KafkaSupervisorReportPayload payload = (KafkaSupervisorReport.KafkaSupervisorReportPayload) report.getPayload(); Assert.assertEquals(DATASOURCE, payload.getDataSource()); Assert.assertEquals(3600L, (long) payload.getDurationSeconds()); Assert.assertEquals(NUM_PARTITIONS, (int) payload.getPartitions()); Assert.assertEquals(1, (int) payload.getReplicas()); Assert.assertEquals(KAFKA_TOPIC, payload.getTopic()); Assert.assertEquals(0, payload.getActiveTasks().size()); Assert.assertEquals(1, payload.getPublishingTasks().size()); TaskReportData publishingReport = payload.getPublishingTasks().get(0); Assert.assertEquals("id1", publishingReport.getId()); Assert.assertEquals(ImmutableMap.of(0, 0L, 2, 0L), publishingReport.getStartingOffsets()); Assert.assertEquals(ImmutableMap.of(0, 10L, 2, 30L), publishingReport.getCurrentOffsets()); KafkaIndexTask capturedTask = captured.getValue(); Assert.assertEquals(dataSchema, capturedTask.getDataSchema()); Assert.assertEquals(KafkaTuningConfig.copyOf(tuningConfig), capturedTask.getTuningConfig()); KafkaIOConfig capturedTaskConfig = capturedTask.getIOConfig(); Assert.assertEquals(kafkaHost, capturedTaskConfig.getConsumerProperties().get("bootstrap.servers")); Assert.assertEquals("myCustomValue", capturedTaskConfig.getConsumerProperties().get("myCustomKey")); Assert.assertEquals("sequenceName-0", capturedTaskConfig.getBaseSequenceName()); Assert.assertTrue("isUseTransaction", capturedTaskConfig.isUseTransaction()); Assert.assertFalse("pauseAfterRead", capturedTaskConfig.isPauseAfterRead()); // check that the new task was created with starting offsets matching where the publishing task finished Assert.assertEquals(KAFKA_TOPIC, capturedTaskConfig.getStartPartitions().getTopic()); Assert.assertEquals(10L, (long) capturedTaskConfig.getStartPartitions().getPartitionOffsetMap().get(0)); Assert.assertEquals(0L, (long) capturedTaskConfig.getStartPartitions().getPartitionOffsetMap().get(1)); Assert.assertEquals(30L, (long) capturedTaskConfig.getStartPartitions().getPartitionOffsetMap().get(2)); Assert.assertEquals(KAFKA_TOPIC, capturedTaskConfig.getEndPartitions().getTopic()); Assert.assertEquals(Long.MAX_VALUE, (long) capturedTaskConfig.getEndPartitions().getPartitionOffsetMap().get(0)); Assert.assertEquals(Long.MAX_VALUE, (long) capturedTaskConfig.getEndPartitions().getPartitionOffsetMap().get(1)); Assert.assertEquals(Long.MAX_VALUE, (long) capturedTaskConfig.getEndPartitions().getPartitionOffsetMap().get(2)); } @Test public void testDiscoverExistingPublishingAndReadingTask() throws Exception { final TaskLocation location1 = new TaskLocation("testHost", 1234); final TaskLocation location2 = new TaskLocation("testHost2", 145); final DateTime startTime = new DateTime(); supervisor = getSupervisor(1, 1, true, "PT1H", null); addSomeEvents(1); Task id1 = createKafkaIndexTask( "id1", DATASOURCE, "sequenceName-0", new KafkaPartitions("topic", ImmutableMap.of(0, 0L, 1, 0L, 2, 0L)), new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)), null ); Task id2 = createKafkaIndexTask( "id2", DATASOURCE, "sequenceName-0", new KafkaPartitions("topic", ImmutableMap.of(0, 10L, 1, 20L, 2, 30L)), new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)), null ); Collection workItems = new ArrayList<>(); workItems.add(new TestTaskRunnerWorkItem(id1.getId(), null, location1)); workItems.add(new TestTaskRunnerWorkItem(id2.getId(), null, location2)); expect(taskMaster.getTaskQueue()).andReturn(Optional.of(taskQueue)).anyTimes(); expect(taskMaster.getTaskRunner()).andReturn(Optional.of(taskRunner)).anyTimes(); expect(taskRunner.getRunningTasks()).andReturn(workItems).anyTimes(); expect(taskStorage.getActiveTasks()).andReturn(ImmutableList.of(id1, id2)).anyTimes(); expect(taskStorage.getStatus("id1")).andReturn(Optional.of(TaskStatus.running("id1"))).anyTimes(); expect(taskStorage.getStatus("id2")).andReturn(Optional.of(TaskStatus.running("id2"))).anyTimes(); expect(taskStorage.getTask("id1")).andReturn(Optional.of(id1)).anyTimes(); expect(taskStorage.getTask("id2")).andReturn(Optional.of(id2)).anyTimes(); expect(indexerMetadataStorageCoordinator.getDataSourceMetadata(DATASOURCE)).andReturn( new KafkaDataSourceMetadata( null ) ).anyTimes(); expect(taskClient.getStatusAsync("id1")).andReturn(Futures.immediateFuture(KafkaIndexTask.Status.PUBLISHING)); expect(taskClient.getStatusAsync("id2")).andReturn(Futures.immediateFuture(KafkaIndexTask.Status.READING)); expect(taskClient.getStartTimeAsync("id2")).andReturn(Futures.immediateFuture(startTime)); expect(taskClient.getCurrentOffsetsAsync("id1", false)) .andReturn(Futures.immediateFuture((Map<Integer, Long>) ImmutableMap.of(0, 10L, 1, 20L, 2, 30L))); expect(taskClient.getCurrentOffsets("id1", true)).andReturn(ImmutableMap.of(0, 10L, 1, 20L, 2, 30L)); expect(taskClient.getCurrentOffsetsAsync("id2", false)) .andReturn(Futures.immediateFuture((Map<Integer, Long>) ImmutableMap.of(0, 40L, 1, 50L, 2, 60L))); taskRunner.registerListener(anyObject(TaskRunnerListener.class), anyObject(Executor.class)); replayAll(); supervisor.start(); supervisor.runInternal(); SupervisorReport report = supervisor.getStatus(); verifyAll(); Assert.assertEquals(DATASOURCE, report.getId()); Assert.assertTrue(report.getPayload() instanceof KafkaSupervisorReport.KafkaSupervisorReportPayload); KafkaSupervisorReport.KafkaSupervisorReportPayload payload = (KafkaSupervisorReport.KafkaSupervisorReportPayload) report.getPayload(); Assert.assertEquals(DATASOURCE, payload.getDataSource()); Assert.assertEquals(3600L, (long) payload.getDurationSeconds()); Assert.assertEquals(NUM_PARTITIONS, (int) payload.getPartitions()); Assert.assertEquals(1, (int) payload.getReplicas()); Assert.assertEquals(KAFKA_TOPIC, payload.getTopic()); Assert.assertEquals(1, payload.getActiveTasks().size()); Assert.assertEquals(1, payload.getPublishingTasks().size()); TaskReportData activeReport = payload.getActiveTasks().get(0); TaskReportData publishingReport = payload.getPublishingTasks().get(0); Assert.assertEquals("id2", activeReport.getId()); Assert.assertEquals(startTime, activeReport.getStartTime()); Assert.assertEquals(ImmutableMap.of(0, 10L, 1, 20L, 2, 30L), activeReport.getStartingOffsets()); Assert.assertEquals(ImmutableMap.of(0, 40L, 1, 50L, 2, 60L), activeReport.getCurrentOffsets()); Assert.assertEquals("id1", publishingReport.getId()); Assert.assertEquals(ImmutableMap.of(0, 0L, 1, 0L, 2, 0L), publishingReport.getStartingOffsets()); Assert.assertEquals(ImmutableMap.of(0, 10L, 1, 20L, 2, 30L), publishingReport.getCurrentOffsets()); } @Test public void testKillUnresponsiveTasksWhileGettingStartTime() throws Exception { supervisor = getSupervisor(2, 2, true, "PT1H", null); addSomeEvents(1); Capture<Task> captured = Capture.newInstance(CaptureType.ALL); expect(taskMaster.getTaskQueue()).andReturn(Optional.of(taskQueue)).anyTimes(); expect(taskMaster.getTaskRunner()).andReturn(Optional.of(taskRunner)).anyTimes(); expect(taskRunner.getRunningTasks()).andReturn(Collections.EMPTY_LIST).anyTimes(); expect(taskStorage.getActiveTasks()).andReturn(ImmutableList.<Task>of()).anyTimes(); expect(indexerMetadataStorageCoordinator.getDataSourceMetadata(DATASOURCE)).andReturn( new KafkaDataSourceMetadata( null ) ).anyTimes(); expect(taskQueue.add(capture(captured))).andReturn(true).times(4); taskRunner.registerListener(anyObject(TaskRunnerListener.class), anyObject(Executor.class)); replayAll(); supervisor.start(); supervisor.runInternal(); verifyAll(); List<Task> tasks = captured.getValues(); reset(taskStorage, taskClient, taskQueue); expect(taskStorage.getActiveTasks()).andReturn(tasks).anyTimes(); for (Task task : tasks) { expect(taskStorage.getStatus(task.getId())).andReturn(Optional.of(TaskStatus.running(task.getId()))).anyTimes(); expect(taskStorage.getTask(task.getId())).andReturn(Optional.of(task)).anyTimes(); expect(taskClient.getStatusAsync(task.getId())) .andReturn(Futures.immediateFuture(KafkaIndexTask.Status.NOT_STARTED)); expect(taskClient.getStartTimeAsync(task.getId())) .andReturn(Futures.<DateTime>immediateFailedFuture(new RuntimeException())); taskQueue.shutdown(task.getId()); } replay(taskStorage, taskClient, taskQueue); supervisor.runInternal(); verifyAll(); } @Test public void testKillUnresponsiveTasksWhilePausing() throws Exception { final TaskLocation location = new TaskLocation("testHost", 1234); supervisor = getSupervisor(2, 2, true, "PT1M", null); addSomeEvents(100); Capture<Task> captured = Capture.newInstance(CaptureType.ALL); expect(taskMaster.getTaskQueue()).andReturn(Optional.of(taskQueue)).anyTimes(); expect(taskMaster.getTaskRunner()).andReturn(Optional.of(taskRunner)).anyTimes(); expect(taskRunner.getRunningTasks()).andReturn(Collections.EMPTY_LIST).anyTimes(); expect(taskStorage.getActiveTasks()).andReturn(ImmutableList.<Task>of()).anyTimes(); expect(indexerMetadataStorageCoordinator.getDataSourceMetadata(DATASOURCE)).andReturn( new KafkaDataSourceMetadata( null ) ).anyTimes(); expect(taskQueue.add(capture(captured))).andReturn(true).times(4); taskRunner.registerListener(anyObject(TaskRunnerListener.class), anyObject(Executor.class)); replayAll(); supervisor.start(); supervisor.runInternal(); verifyAll(); List<Task> tasks = captured.getValues(); Collection workItems = new ArrayList<>(); for (Task task : tasks) { workItems.add(new TestTaskRunnerWorkItem(task.getId(), null, location)); } reset(taskStorage, taskRunner, taskClient, taskQueue); captured = Capture.newInstance(CaptureType.ALL); expect(taskStorage.getActiveTasks()).andReturn(tasks).anyTimes(); for (Task task : tasks) { expect(taskStorage.getStatus(task.getId())).andReturn(Optional.of(TaskStatus.running(task.getId()))).anyTimes(); expect(taskStorage.getTask(task.getId())).andReturn(Optional.of(task)).anyTimes(); } expect(taskRunner.getRunningTasks()).andReturn(workItems).anyTimes(); expect(taskClient.getStatusAsync(anyString())) .andReturn(Futures.immediateFuture(KafkaIndexTask.Status.READING)) .anyTimes(); expect(taskClient.getStartTimeAsync(EasyMock.contains("sequenceName-0"))) .andReturn(Futures.immediateFuture(DateTime.now().minusMinutes(2))) .andReturn(Futures.immediateFuture(DateTime.now())); expect(taskClient.getStartTimeAsync(EasyMock.contains("sequenceName-1"))) .andReturn(Futures.immediateFuture(DateTime.now())) .times(2); expect(taskClient.pauseAsync(EasyMock.contains("sequenceName-0"))) .andReturn(Futures.<Map<Integer, Long>>immediateFailedFuture(new RuntimeException())).times(2); taskQueue.shutdown(EasyMock.contains("sequenceName-0")); expectLastCall().times(2); expect(taskQueue.add(capture(captured))).andReturn(true).times(2); replay(taskStorage, taskRunner, taskClient, taskQueue); supervisor.runInternal(); verifyAll(); for (Task task : captured.getValues()) { KafkaIOConfig taskConfig = ((KafkaIndexTask) task).getIOConfig(); Assert.assertEquals(0L, (long) taskConfig.getStartPartitions().getPartitionOffsetMap().get(0)); Assert.assertEquals(0L, (long) taskConfig.getStartPartitions().getPartitionOffsetMap().get(2)); } } @Test public void testKillUnresponsiveTasksWhileSettingEndOffsets() throws Exception { final TaskLocation location = new TaskLocation("testHost", 1234); supervisor = getSupervisor(2, 2, true, "PT1M", null); addSomeEvents(100); Capture<Task> captured = Capture.newInstance(CaptureType.ALL); expect(taskMaster.getTaskQueue()).andReturn(Optional.of(taskQueue)).anyTimes(); expect(taskMaster.getTaskRunner()).andReturn(Optional.of(taskRunner)).anyTimes(); expect(taskRunner.getRunningTasks()).andReturn(Collections.EMPTY_LIST).anyTimes(); expect(taskStorage.getActiveTasks()).andReturn(ImmutableList.<Task>of()).anyTimes(); expect(indexerMetadataStorageCoordinator.getDataSourceMetadata(DATASOURCE)).andReturn( new KafkaDataSourceMetadata( null ) ).anyTimes(); expect(taskQueue.add(capture(captured))).andReturn(true).times(4); taskRunner.registerListener(anyObject(TaskRunnerListener.class), anyObject(Executor.class)); replayAll(); supervisor.start(); supervisor.runInternal(); verifyAll(); List<Task> tasks = captured.getValues(); Collection workItems = new ArrayList<>(); for (Task task : tasks) { workItems.add(new TestTaskRunnerWorkItem(task.getId(), null, location)); } reset(taskStorage, taskRunner, taskClient, taskQueue); captured = Capture.newInstance(CaptureType.ALL); expect(taskStorage.getActiveTasks()).andReturn(tasks).anyTimes(); for (Task task : tasks) { expect(taskStorage.getStatus(task.getId())).andReturn(Optional.of(TaskStatus.running(task.getId()))).anyTimes(); expect(taskStorage.getTask(task.getId())).andReturn(Optional.of(task)).anyTimes(); } expect(taskRunner.getRunningTasks()).andReturn(workItems).anyTimes(); expect(taskClient.getStatusAsync(anyString())) .andReturn(Futures.immediateFuture(KafkaIndexTask.Status.READING)) .anyTimes(); expect(taskClient.getStartTimeAsync(EasyMock.contains("sequenceName-0"))) .andReturn(Futures.immediateFuture(DateTime.now().minusMinutes(2))) .andReturn(Futures.immediateFuture(DateTime.now())); expect(taskClient.getStartTimeAsync(EasyMock.contains("sequenceName-1"))) .andReturn(Futures.immediateFuture(DateTime.now())) .times(2); expect(taskClient.pauseAsync(EasyMock.contains("sequenceName-0"))) .andReturn(Futures.immediateFuture((Map<Integer, Long>) ImmutableMap.of(0, 10L, 1, 20L, 2, 30L))) .andReturn(Futures.immediateFuture((Map<Integer, Long>) ImmutableMap.of(0, 10L, 1, 15L, 2, 35L))); expect( taskClient.setEndOffsetsAsync( EasyMock.contains("sequenceName-0"), EasyMock.eq(ImmutableMap.of(0, 10L, 1, 20L, 2, 35L)), EasyMock.eq(true) ) ).andReturn(Futures.<Boolean>immediateFailedFuture(new RuntimeException())).times(2); taskQueue.shutdown(EasyMock.contains("sequenceName-0")); expectLastCall().times(2); expect(taskQueue.add(capture(captured))).andReturn(true).times(2); replay(taskStorage, taskRunner, taskClient, taskQueue); supervisor.runInternal(); verifyAll(); for (Task task : captured.getValues()) { KafkaIOConfig taskConfig = ((KafkaIndexTask) task).getIOConfig(); Assert.assertEquals(0L, (long) taskConfig.getStartPartitions().getPartitionOffsetMap().get(0)); Assert.assertEquals(0L, (long) taskConfig.getStartPartitions().getPartitionOffsetMap().get(2)); } } @Test(expected = IllegalStateException.class) public void testStopNotStarted() throws Exception { supervisor = getSupervisor(1, 1, true, "PT1H", null); supervisor.stop(false); } @Test public void testStop() throws Exception { expect(taskMaster.getTaskRunner()).andReturn(Optional.of(taskRunner)).anyTimes(); taskClient.close(); taskRunner.unregisterListener(String.format("KafkaSupervisor-%s", DATASOURCE)); replayAll(); supervisor = getSupervisor(1, 1, true, "PT1H", null); supervisor.start(); supervisor.stop(false); verifyAll(); } @Test public void testStopGracefully() throws Exception { final TaskLocation location1 = new TaskLocation("testHost", 1234); final TaskLocation location2 = new TaskLocation("testHost2", 145); final DateTime startTime = new DateTime(); supervisor = getSupervisor(2, 1, true, "PT1H", null); addSomeEvents(1); Task id1 = createKafkaIndexTask( "id1", DATASOURCE, "sequenceName-0", new KafkaPartitions("topic", ImmutableMap.of(0, 0L, 1, 0L, 2, 0L)), new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)), null ); Task id2 = createKafkaIndexTask( "id2", DATASOURCE, "sequenceName-0", new KafkaPartitions("topic", ImmutableMap.of(0, 10L, 1, 20L, 2, 30L)), new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)), null ); Task id3 = createKafkaIndexTask( "id3", DATASOURCE, "sequenceName-0", new KafkaPartitions("topic", ImmutableMap.of(0, 10L, 1, 20L, 2, 30L)), new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)), null ); Collection workItems = new ArrayList<>(); workItems.add(new TestTaskRunnerWorkItem(id1.getId(), null, location1)); workItems.add(new TestTaskRunnerWorkItem(id2.getId(), null, location2)); expect(taskMaster.getTaskQueue()).andReturn(Optional.of(taskQueue)).anyTimes(); expect(taskMaster.getTaskRunner()).andReturn(Optional.of(taskRunner)).anyTimes(); expect(taskRunner.getRunningTasks()).andReturn(workItems).anyTimes(); expect(taskStorage.getActiveTasks()).andReturn(ImmutableList.of(id1, id2, id3)).anyTimes(); expect(taskStorage.getStatus("id1")).andReturn(Optional.of(TaskStatus.running("id1"))).anyTimes(); expect(taskStorage.getStatus("id2")).andReturn(Optional.of(TaskStatus.running("id2"))).anyTimes(); expect(taskStorage.getStatus("id3")).andReturn(Optional.of(TaskStatus.running("id3"))).anyTimes(); expect(taskStorage.getTask("id1")).andReturn(Optional.of(id1)).anyTimes(); expect(taskStorage.getTask("id2")).andReturn(Optional.of(id2)).anyTimes(); expect(taskStorage.getTask("id3")).andReturn(Optional.of(id3)).anyTimes(); expect(indexerMetadataStorageCoordinator.getDataSourceMetadata(DATASOURCE)).andReturn( new KafkaDataSourceMetadata( null ) ).anyTimes(); expect(taskClient.getStatusAsync("id1")).andReturn(Futures.immediateFuture(KafkaIndexTask.Status.PUBLISHING)); expect(taskClient.getStatusAsync("id2")).andReturn(Futures.immediateFuture(KafkaIndexTask.Status.READING)); expect(taskClient.getStatusAsync("id3")).andReturn(Futures.immediateFuture(KafkaIndexTask.Status.READING)); expect(taskClient.getStartTimeAsync("id2")).andReturn(Futures.immediateFuture(startTime)); expect(taskClient.getStartTimeAsync("id3")).andReturn(Futures.immediateFuture(startTime)); expect(taskClient.getCurrentOffsets("id1", true)).andReturn(ImmutableMap.of(0, 10L, 1, 20L, 2, 30L)); taskRunner.registerListener(anyObject(TaskRunnerListener.class), anyObject(Executor.class)); replayAll(); supervisor.start(); supervisor.runInternal(); verifyAll(); reset(taskRunner, taskClient, taskQueue); expect(taskRunner.getRunningTasks()).andReturn(workItems).anyTimes(); expect(taskClient.pauseAsync("id2")) .andReturn(Futures.immediateFuture((Map<Integer, Long>) ImmutableMap.of(0, 15L, 1, 25L, 2, 30L))); expect(taskClient.setEndOffsetsAsync("id2", ImmutableMap.of(0, 15L, 1, 25L, 2, 30L), true)) .andReturn(Futures.immediateFuture(true)); taskQueue.shutdown("id3"); expectLastCall().times(2); replay(taskRunner, taskClient, taskQueue); supervisor.gracefulShutdownInternal(); verifyAll(); } @Test public void testResetNoTasks() throws Exception { supervisor = getSupervisor(1, 1, true, "PT1H", null); expect(taskMaster.getTaskQueue()).andReturn(Optional.of(taskQueue)).anyTimes(); expect(taskMaster.getTaskRunner()).andReturn(Optional.of(taskRunner)).anyTimes(); expect(taskRunner.getRunningTasks()).andReturn(Collections.EMPTY_LIST).anyTimes(); expect(taskStorage.getActiveTasks()).andReturn(ImmutableList.<Task>of()).anyTimes(); taskRunner.registerListener(anyObject(TaskRunnerListener.class), anyObject(Executor.class)); replayAll(); supervisor.start(); supervisor.runInternal(); verifyAll(); reset(indexerMetadataStorageCoordinator); expect(indexerMetadataStorageCoordinator.deleteDataSourceMetadata(DATASOURCE)).andReturn(true); replay(indexerMetadataStorageCoordinator); supervisor.resetInternal(); verifyAll(); } @Test public void testResetRunningTasks() throws Exception { final TaskLocation location1 = new TaskLocation("testHost", 1234); final TaskLocation location2 = new TaskLocation("testHost2", 145); final DateTime startTime = new DateTime(); supervisor = getSupervisor(2, 1, true, "PT1H", null); addSomeEvents(1); Task id1 = createKafkaIndexTask( "id1", DATASOURCE, "sequenceName-0", new KafkaPartitions("topic", ImmutableMap.of(0, 0L, 1, 0L, 2, 0L)), new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)), null ); Task id2 = createKafkaIndexTask( "id2", DATASOURCE, "sequenceName-0", new KafkaPartitions("topic", ImmutableMap.of(0, 10L, 1, 20L, 2, 30L)), new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)), null ); Task id3 = createKafkaIndexTask( "id3", DATASOURCE, "sequenceName-0", new KafkaPartitions("topic", ImmutableMap.of(0, 10L, 1, 20L, 2, 30L)), new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)), null ); Collection workItems = new ArrayList<>(); workItems.add(new TestTaskRunnerWorkItem(id1.getId(), null, location1)); workItems.add(new TestTaskRunnerWorkItem(id2.getId(), null, location2)); expect(taskMaster.getTaskQueue()).andReturn(Optional.of(taskQueue)).anyTimes(); expect(taskMaster.getTaskRunner()).andReturn(Optional.of(taskRunner)).anyTimes(); expect(taskRunner.getRunningTasks()).andReturn(workItems).anyTimes(); expect(taskStorage.getActiveTasks()).andReturn(ImmutableList.of(id1, id2, id3)).anyTimes(); expect(taskStorage.getStatus("id1")).andReturn(Optional.of(TaskStatus.running("id1"))).anyTimes(); expect(taskStorage.getStatus("id2")).andReturn(Optional.of(TaskStatus.running("id2"))).anyTimes(); expect(taskStorage.getStatus("id3")).andReturn(Optional.of(TaskStatus.running("id3"))).anyTimes(); expect(taskStorage.getTask("id1")).andReturn(Optional.of(id1)).anyTimes(); expect(taskStorage.getTask("id2")).andReturn(Optional.of(id2)).anyTimes(); expect(taskStorage.getTask("id3")).andReturn(Optional.of(id3)).anyTimes(); expect(indexerMetadataStorageCoordinator.getDataSourceMetadata(DATASOURCE)).andReturn( new KafkaDataSourceMetadata( null ) ).anyTimes(); expect(taskClient.getStatusAsync("id1")).andReturn(Futures.immediateFuture(KafkaIndexTask.Status.PUBLISHING)); expect(taskClient.getStatusAsync("id2")).andReturn(Futures.immediateFuture(KafkaIndexTask.Status.READING)); expect(taskClient.getStatusAsync("id3")).andReturn(Futures.immediateFuture(KafkaIndexTask.Status.READING)); expect(taskClient.getStartTimeAsync("id2")).andReturn(Futures.immediateFuture(startTime)); expect(taskClient.getStartTimeAsync("id3")).andReturn(Futures.immediateFuture(startTime)); expect(taskClient.getCurrentOffsets("id1", true)).andReturn(ImmutableMap.of(0, 10L, 1, 20L, 2, 30L)); taskRunner.registerListener(anyObject(TaskRunnerListener.class), anyObject(Executor.class)); replayAll(); supervisor.start(); supervisor.runInternal(); verifyAll(); reset(taskQueue, indexerMetadataStorageCoordinator); expect(indexerMetadataStorageCoordinator.deleteDataSourceMetadata(DATASOURCE)).andReturn(true); taskQueue.shutdown("id2"); taskQueue.shutdown("id3"); replay(taskQueue, indexerMetadataStorageCoordinator); supervisor.resetInternal(); verifyAll(); } private void addSomeEvents(int numEventsPerPartition) throws Exception { try (final KafkaProducer<byte[], byte[]> kafkaProducer = kafkaServer.newProducer()) { for (int i = 0; i < NUM_PARTITIONS; i++) { for (int j = 0; j < numEventsPerPartition; j++) { kafkaProducer.send( new ProducerRecord<byte[], byte[]>( KAFKA_TOPIC, i, null, String.format("event-%d", j).getBytes() ) ).get(); } } } } private KafkaSupervisor getSupervisor( int replicas, int taskCount, boolean useEarliestOffset, String duration, Period lateMessageRejectionPeriod ) { KafkaSupervisorIOConfig kafkaSupervisorIOConfig = new KafkaSupervisorIOConfig( KAFKA_TOPIC, replicas, taskCount, new Period(duration), ImmutableMap.of("myCustomKey", "myCustomValue", "bootstrap.servers", kafkaHost), new Period("P1D"), new Period("PT30S"), useEarliestOffset, new Period("PT30M"), lateMessageRejectionPeriod ); KafkaIndexTaskClientFactory taskClientFactory = new KafkaIndexTaskClientFactory(null, null) { @Override public KafkaIndexTaskClient build( TaskInfoProvider taskInfoProvider, String dataSource, int numThreads, Duration httpTimeout, long numRetries ) { Assert.assertEquals(TEST_CHAT_THREADS, numThreads); Assert.assertEquals(TEST_HTTP_TIMEOUT.toStandardDuration(), httpTimeout); Assert.assertEquals(TEST_CHAT_RETRIES, numRetries); return taskClient; } }; return new TestableKafkaSupervisor( taskStorage, taskMaster, indexerMetadataStorageCoordinator, taskClientFactory, objectMapper, new KafkaSupervisorSpec( dataSchema, tuningConfig, kafkaSupervisorIOConfig, null, taskStorage, taskMaster, indexerMetadataStorageCoordinator, taskClientFactory, objectMapper ) ); } private DataSchema getDataSchema(String dataSource) { List<DimensionSchema> dimensions = new ArrayList<>(); dimensions.add(StringDimensionSchema.create("dim1")); dimensions.add(StringDimensionSchema.create("dim2")); return new DataSchema( dataSource, objectMapper.convertValue( new StringInputRowParser( new JSONParseSpec( new TimestampSpec("timestamp", "iso", null), new DimensionsSpec( dimensions, null, null ), new JSONPathSpec(true, ImmutableList.<JSONPathFieldSpec>of()), ImmutableMap.<String, Boolean>of() ), Charsets.UTF_8.name() ), Map.class ), new AggregatorFactory[]{new CountAggregatorFactory("rows")}, new UniformGranularitySpec( Granularity.HOUR, QueryGranularities.NONE, ImmutableList.<Interval>of() ), objectMapper ); } private KafkaIndexTask createKafkaIndexTask( String id, String dataSource, String sequenceName, KafkaPartitions startPartitions, KafkaPartitions endPartitions, DateTime minimumMessageTime ) { return new KafkaIndexTask( id, null, getDataSchema(dataSource), tuningConfig, new KafkaIOConfig( sequenceName, startPartitions, endPartitions, ImmutableMap.<String, String>of(), true, false, minimumMessageTime ), ImmutableMap.<String, Object>of(), null ); } private class TestTaskRunnerWorkItem extends TaskRunnerWorkItem { private TaskLocation location; public TestTaskRunnerWorkItem(String taskId, ListenableFuture<TaskStatus> result, TaskLocation location) { super(taskId, result); this.location = location; } @Override public TaskLocation getLocation() { return location; } } private class TestableKafkaSupervisor extends KafkaSupervisor { public TestableKafkaSupervisor( TaskStorage taskStorage, TaskMaster taskMaster, IndexerMetadataStorageCoordinator indexerMetadataStorageCoordinator, KafkaIndexTaskClientFactory taskClientFactory, ObjectMapper mapper, KafkaSupervisorSpec spec ) { super(taskStorage, taskMaster, indexerMetadataStorageCoordinator, taskClientFactory, mapper, spec); } @Override protected String generateSequenceName(int groupId) { return String.format("sequenceName-%d", groupId); } } }
/** * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "{}" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright {yyyy} {name of copyright owner} * * 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.deleidos.rtws.master.core.jmx; import java.io.InputStream; import java.util.Enumeration; import java.util.HashMap; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import javax.xml.transform.stream.StreamSource; import org.junit.*; import com.deleidos.rtws.commons.config.PropertiesUtils; import com.deleidos.rtws.master.core.beans.ClusterDefinition; import com.deleidos.rtws.master.core.exception.QueueRateException; import com.deleidos.rtws.master.core.jmx.IngestQueueRateCalculator; import com.deleidos.rtws.master.core.jmx.MqDataGatheringBean; import com.deleidos.rtws.master.core.jmx.QueueRateScalingMonitor; import static org.mockito.Matchers.*; import static org.mockito.Mockito.*; public class QueueRateCalculatorTest { private String basedir; ClusterDefinition config; /*@Test public void testCalculateQueueRateFromBroker() throws Exception { MqDataGatheringBean gatheringBean = mock(MqDataGatheringBean.class); QueueRateScalingMonitor queueRateScalingMonitor = new QueueRateScalingMonitor(); IngestQueueRateCalculator queueRateCalculator = new IngestQueueRateCalculator(); String[] enqueName = { "BrokerViewMBean.TotalEnqueueCount" }; String[] dequeName = { "BrokerViewMBean.TotalDequeueCount" }; String[] backlogName = { "BrokerViewMBean.TotalMessageCount" }; String simpleName = "BrokerViewMBean"; queueRateScalingMonitor.setDataStorageHistory(10); queueRateScalingMonitor.setQueueRateStorageHistory(10); queueRateScalingMonitor.setMqDataGatheringBean(gatheringBean); queueRateScalingMonitor.setQueueRateCalculator(queueRateCalculator); queueRateScalingMonitor.setEnqueName(enqueName); queueRateScalingMonitor.setDequeName(dequeName); queueRateScalingMonitor.setBackLogName(backlogName); queueRateScalingMonitor.initialize(); HashMap<String, Long> dataTable = new HashMap<String, Long>(); HashMap<String, Long> read1 = new HashMap<String, Long>(); read1.put("BrokerViewMBean.TotalEnqueueCount", 500L); read1.put("BrokerViewMBean.TotalDequeueCount", 50L); read1.put("BrokerViewMBean.TotalMessageCount", 5L); when(gatheringBean.getJMXStatics()).thenReturn(read1); queueRateScalingMonitor.sample(); HashMap<String, Long> read2 = new HashMap<String, Long>(); read2.put("BrokerViewMBean.TotalEnqueueCount", 1000L); read2.put("BrokerViewMBean.TotalDequeueCount", 100L); read2.put("BrokerViewMBean.TotalMessageCount", 10L); when(gatheringBean.getJMXStatics()).thenReturn(read2); queueRateScalingMonitor.sample(); HashMap<String, Long> read3 = new HashMap<String, Long>(); read3.put("BrokerViewMBean.TotalEnqueueCount", 1500L); read3.put("BrokerViewMBean.TotalDequeueCount", 150L); read3.put("BrokerViewMBean.TotalMessageCount", 15L); when(gatheringBean.getJMXStatics()).thenReturn(read3); queueRateScalingMonitor.sample(); Assert.assertEquals(9.54, queueRateScalingMonitor.computeLoadFactor(), 0.001); queueRateScalingMonitor.dispose(); } */ @Test public void testCalculateQueueRateFromQueue() throws Exception { MqDataGatheringBean gatheringBean = mock(MqDataGatheringBean.class); QueueRateScalingMonitor queueRateScalingMonitor = new QueueRateScalingMonitor(); IngestQueueRateCalculator queueRateCalculator = new IngestQueueRateCalculator(); String[] enqueName = { "DestinationViewMBean.EnqueueCount" }; String[] dequeName = { "DestinationViewMBean.DequeueCount" }; String[] backlogName = { "DestinationViewMBean.QueueCount" }; String consumerCountName = "DestinationViewMBean.ConsumerCount"; String simpleName = "DestinationViewMBean"; queueRateScalingMonitor.setDataStorageHistory(10); queueRateScalingMonitor.setQueueRateStorageHistory(10); queueRateScalingMonitor.setMqDataGatheringBean(gatheringBean); queueRateScalingMonitor.setQueueRateCalculator(queueRateCalculator); queueRateScalingMonitor.setEnqueName(enqueName); queueRateScalingMonitor.setDequeName(dequeName); queueRateScalingMonitor.setBackLogName(backlogName); queueRateScalingMonitor.setConsumerName(consumerCountName); queueRateScalingMonitor.initialize(); HashMap<String, Long> dataTable = new HashMap<String, Long>(); HashMap<String, Long> read1 = new HashMap<String, Long>(); read1.put("DestinationViewMBean.EnqueueCount", 500L); read1.put("DestinationViewMBean.DequeueCount", 50L); read1.put("DestinationViewMBean.QueueCount", 5L); read1.put("DestinationViewMBean.ConsumerCount", 1L); when(gatheringBean.getJMXStatics()).thenReturn(read1); queueRateScalingMonitor.sample(); HashMap<String, Long> read2 = new HashMap<String, Long>(); read2.put("DestinationViewMBean.EnqueueCount", 1000L); read2.put("DestinationViewMBean.DequeueCount", 100L); read2.put("DestinationViewMBean.QueueCount", 10L); read2.put("DestinationViewMBean.ConsumerCount", 2L); when(gatheringBean.getJMXStatics()).thenReturn(read2); queueRateScalingMonitor.sample(); HashMap<String, Long> read3 = new HashMap<String, Long>(); read3.put("DestinationViewMBean.EnqueueCount", 1500L); read3.put("DestinationViewMBean.DequeueCount", 150L); read3.put("DestinationViewMBean.QueueCount", 15L); read3.put("DestinationViewMBean.ConsumerCount", 2L); when(gatheringBean.getJMXStatics()).thenReturn(read3); queueRateScalingMonitor.sample(); System.out.println("Factor: " + queueRateScalingMonitor.computeLoadFactor()); //Assert.assertEquals(9.54, queueRateScalingMonitor.computeLoadFactor(), 0.001); queueRateScalingMonitor.dispose(); } @Test public void testCalculateQueueRateWithZeroBackLog() throws Exception { MqDataGatheringBean gatheringBean = mock(MqDataGatheringBean.class); QueueRateScalingMonitor queueRateScalingMonitor = new QueueRateScalingMonitor(); IngestQueueRateCalculator queueRateCalculator = new IngestQueueRateCalculator(); String[] enqueName = { "DestinationViewMBean.EnqueueCount" }; String[] dequeName = { "DestinationViewMBean.DequeueCount" }; String[] backlogName = { "DestinationViewMBean.QueueCount" }; String consumerCountName = "DestinationViewMBean.ConsumerCount"; String simpleName = "DestinationViewMBean"; queueRateScalingMonitor.setDataStorageHistory(10); queueRateScalingMonitor.setQueueRateStorageHistory(10); queueRateScalingMonitor.setMqDataGatheringBean(gatheringBean); queueRateScalingMonitor.setQueueRateCalculator(queueRateCalculator); queueRateScalingMonitor.setEnqueName(enqueName); queueRateScalingMonitor.setDequeName(dequeName); queueRateScalingMonitor.setBackLogName(backlogName); queueRateScalingMonitor.setConsumerName(consumerCountName); queueRateScalingMonitor.initialize(); HashMap<String, Long> dataTable = new HashMap<String, Long>(); HashMap<String, Long> read1 = new HashMap<String, Long>(); read1.put("DestinationViewMBean.EnqueueCount", 500L); read1.put("DestinationViewMBean.DequeueCount", 50L); read1.put("DestinationViewMBean.QueueCount", 5L); read1.put("DestinationViewMBean.ConsumerCount", 1L); when(gatheringBean.getJMXStatics()).thenReturn(read1); queueRateScalingMonitor.sample(); HashMap<String, Long> read2 = new HashMap<String, Long>(); read2.put("DestinationViewMBean.EnqueueCount", 1000L); read2.put("DestinationViewMBean.DequeueCount", 100L); read2.put("DestinationViewMBean.QueueCount", 10L); read2.put("DestinationViewMBean.ConsumerCount", 2L); when(gatheringBean.getJMXStatics()).thenReturn(read2); queueRateScalingMonitor.sample(); HashMap<String, Long> read3 = new HashMap<String, Long>(); read3.put("DestinationViewMBean.EnqueueCount", 1500L); read3.put("DestinationViewMBean.DequeueCount", 150L); read3.put("DestinationViewMBean.QueueCount", 0L); read3.put("DestinationViewMBean.ConsumerCount", 2L); when(gatheringBean.getJMXStatics()).thenReturn(read3); queueRateScalingMonitor.sample(); System.out.println("Factor: " + queueRateScalingMonitor.computeLoadFactor()); //Assert.assertEquals(9.54, queueRateScalingMonitor.computeLoadFactor(), 0.001); queueRateScalingMonitor.dispose(); } @Test public void testCalculateLoadFactorWithOneSample() throws Exception { MqDataGatheringBean gatheringBean = mock(MqDataGatheringBean.class); QueueRateScalingMonitor queueRateScalingMonitor = new QueueRateScalingMonitor(); IngestQueueRateCalculator queueRateCalculator = new IngestQueueRateCalculator(); String[] enqueName = { "DestinationViewMBean.EnqueueCount" }; String[] dequeName = { "DestinationViewMBean.DequeueCount" }; String[] backlogName = { "DestinationViewMBean.QueueCount" }; String consumerCountName = "DestinationViewMBean.ConsumerCount"; String simpleName = "DestinationViewMBean"; queueRateScalingMonitor.setDataStorageHistory(10); queueRateScalingMonitor.setQueueRateStorageHistory(10); queueRateScalingMonitor.setMqDataGatheringBean(gatheringBean); queueRateScalingMonitor.setQueueRateCalculator(queueRateCalculator); queueRateScalingMonitor.setEnqueName(enqueName); queueRateScalingMonitor.setDequeName(dequeName); queueRateScalingMonitor.setBackLogName(backlogName); queueRateScalingMonitor.setConsumerName(consumerCountName); queueRateScalingMonitor.initialize(); HashMap<String, Long> dataTable = new HashMap<String, Long>(); HashMap<String, Long> read1 = new HashMap<String, Long>(); read1.put("DestinationViewMBean.EnqueueCount", 500L); read1.put("DestinationViewMBean.DequeueCount", 50L); read1.put("DestinationViewMBean.QueueCount", 5L); read1.put("DestinationViewMBean.ConsumerCount", 1L); when(gatheringBean.getJMXStatics()).thenReturn(read1); queueRateScalingMonitor.sample(); Assert.assertEquals(1.00, queueRateScalingMonitor.computeLoadFactor(), 0.001); queueRateScalingMonitor.dispose(); } }
/* * 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. */ /* * (C) Copyright IBM Corp. 1999 All Rights Reserved. * Copyright 1997 The Open Group Research Institute. All rights reserved. */ package sun.security.krb5.internal; import sun.security.krb5.*; import sun.security.util.*; import java.util.Vector; import java.io.IOException; import java.math.BigInteger; /** * Implements the ASN.1 Authenticator type. * * <xmp> * Authenticator ::= [APPLICATION 2] SEQUENCE { * authenticator-vno [0] INTEGER (5), * crealm [1] Realm, * cname [2] PrincipalName, * cksum [3] Checksum OPTIONAL, * cusec [4] Microseconds, * ctime [5] KerberosTime, * subkey [6] EncryptionKey OPTIONAL, * seq-number [7] UInt32 OPTIONAL, * authorization-data [8] AuthorizationData OPTIONAL * } * </xmp> * * <p> * This definition reflects the Network Working Group RFC 4120 * specification available at * <a href="http://www.ietf.org/rfc/rfc4120.txt"> * http://www.ietf.org/rfc/rfc4120.txt</a>. */ public class Authenticator { public int authenticator_vno; public Realm crealm; public PrincipalName cname; Checksum cksum; //optional public int cusec; public KerberosTime ctime; EncryptionKey subKey; //optional Integer seqNumber; //optional public AuthorizationData authorizationData; //optional public Authenticator ( Realm new_crealm, PrincipalName new_cname, Checksum new_cksum, int new_cusec, KerberosTime new_ctime, EncryptionKey new_subKey, Integer new_seqNumber, AuthorizationData new_authorizationData ) { authenticator_vno = Krb5.AUTHNETICATOR_VNO; crealm = new_crealm; cname = new_cname; cksum = new_cksum; cusec = new_cusec; ctime = new_ctime; subKey = new_subKey; seqNumber = new_seqNumber; authorizationData = new_authorizationData; } public Authenticator(byte[] data) throws Asn1Exception, IOException, KrbApErrException, RealmException { init(new DerValue(data)); } public Authenticator(DerValue encoding) throws Asn1Exception,IOException, KrbApErrException, RealmException { init(encoding); } /** * Initializes an Authenticator object. * @param encoding a single DER-encoded value. * @exception Asn1Exception if an error occurs while decoding an ASN1 encoded data. * @exception IOException if an I/O error occurs while reading encoded data. * @exception KrbApErrException if the value read from the DER-encoded data * stream does not match the pre-defined value. * @exception RealmException if an error occurs while parsing a Realm object. */ private void init(DerValue encoding) throws Asn1Exception, IOException, KrbApErrException, RealmException { DerValue der, subDer; //may not be the correct error code for a tag //mismatch on an encrypted structure if (((encoding.getTag() & (byte)0x1F) != (byte)0x02) || (encoding.isApplication() != true) || (encoding.isConstructed() != true)) throw new Asn1Exception(Krb5.ASN1_BAD_ID); der = encoding.getData().getDerValue(); if (der.getTag() != DerValue.tag_Sequence) throw new Asn1Exception(Krb5.ASN1_BAD_ID); subDer = der.getData().getDerValue(); if ((subDer.getTag() & (byte)0x1F) != (byte)0x00) throw new Asn1Exception(Krb5.ASN1_BAD_ID); authenticator_vno = subDer.getData().getBigInteger().intValue(); if (authenticator_vno != 5) throw new KrbApErrException(Krb5.KRB_AP_ERR_BADVERSION); crealm = Realm.parse(der.getData(), (byte)0x01, false); cname = PrincipalName.parse(der.getData(), (byte)0x02, false); cksum = Checksum.parse(der.getData(), (byte)0x03, true); subDer = der.getData().getDerValue(); if ((subDer.getTag() & (byte)0x1F) == 0x04) { cusec = subDer.getData().getBigInteger().intValue(); } else throw new Asn1Exception(Krb5.ASN1_BAD_ID); ctime = KerberosTime.parse(der.getData(), (byte)0x05, false); if (der.getData().available() > 0) { subKey = EncryptionKey.parse(der.getData(), (byte)0x06, true); } else { subKey = null; seqNumber = null; authorizationData = null; } if (der.getData().available() > 0) { if ((der.getData().peekByte() & 0x1F) == 0x07) { subDer = der.getData().getDerValue(); if ((subDer.getTag() & (byte)0x1F) == (byte)0x07) seqNumber = new Integer(subDer.getData().getBigInteger().intValue()); } } else { seqNumber = null; authorizationData = null; } if (der.getData().available() > 0) { authorizationData = AuthorizationData.parse(der.getData(), (byte)0x08, true); } else authorizationData = null; if (der.getData().available() > 0) throw new Asn1Exception(Krb5.ASN1_BAD_ID); } /** * Encodes an Authenticator object. * @return byte array of encoded Authenticator object. * @exception Asn1Exception if an error occurs while decoding an ASN1 encoded data. * @exception IOException if an I/O error occurs while reading encoded data. */ public byte[] asn1Encode() throws Asn1Exception, IOException { Vector<DerValue> v = new Vector<DerValue> (); DerOutputStream temp = new DerOutputStream(); temp.putInteger(BigInteger.valueOf(authenticator_vno)); v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x00), temp.toByteArray())); v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x01), crealm.asn1Encode())); v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x02), cname.asn1Encode())); if (cksum != null) v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x03), cksum.asn1Encode())); temp = new DerOutputStream(); temp.putInteger(BigInteger.valueOf(cusec)); v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x04), temp.toByteArray())); v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x05), ctime.asn1Encode())); if (subKey != null) v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x06), subKey.asn1Encode())); if (seqNumber != null) { temp = new DerOutputStream(); // encode as an unsigned integer (UInt32) temp.putInteger(BigInteger.valueOf(seqNumber.longValue())); v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x07), temp.toByteArray())); } if (authorizationData != null) v.addElement(new DerValue(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x08), authorizationData.asn1Encode())); DerValue der[] = new DerValue[v.size()]; v.copyInto(der); temp = new DerOutputStream(); temp.putSequence(der); DerOutputStream out = new DerOutputStream(); out.write(DerValue.createTag(DerValue.TAG_APPLICATION, true, (byte)0x02), temp); return out.toByteArray(); } public final Checksum getChecksum() { return cksum; } public final Integer getSeqNumber() { return seqNumber; } public final EncryptionKey getSubKey() { return subKey; } }
/* * 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.phoenix.hbase.index.covered; import static org.apache.phoenix.query.BaseTest.setUpConfigForMiniCluster; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.IOException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Queue; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.Coprocessor; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.regionserver.Region; import org.apache.hadoop.hbase.util.Bytes; import org.apache.phoenix.util.EnvironmentEdge; import org.apache.phoenix.util.EnvironmentEdgeManager; import org.apache.phoenix.end2end.NeedsOwnMiniClusterTest; import org.apache.phoenix.hbase.index.IndexTestingUtils; import org.apache.phoenix.hbase.index.Indexer; import org.apache.phoenix.hbase.index.TableName; import org.apache.phoenix.hbase.index.covered.update.ColumnReference; import org.apache.phoenix.hbase.index.scanner.Scanner; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; /** * End-to-End test of just the {@link NonTxIndexBuilder}, but with a simple * {@link IndexCodec} and BatchCache implementation. */ @Category(NeedsOwnMiniClusterTest.class) public class EndToEndCoveredColumnsIndexBuilderIT { public class TestState { private HTable table; private long ts; private VerifyingIndexCodec codec; /** * @param primary * @param codec * @param ts */ public TestState(HTable primary, VerifyingIndexCodec codec, long ts) { this.table = primary; this.ts = ts; this.codec = codec; } } private static final HBaseTestingUtility UTIL = new HBaseTestingUtility(); private static final byte[] row = Bytes.toBytes("row"); private static final byte[] family = Bytes.toBytes("FAM"); private static final byte[] qual = Bytes.toBytes("qual"); private static final HColumnDescriptor FAM1 = new HColumnDescriptor(family); @Rule public TableName TestTable = new TableName(); private TestState state; @BeforeClass public static void setupCluster() throws Exception { Configuration conf = UTIL.getConfiguration(); setUpConfigForMiniCluster(conf); IndexTestingUtils.setupConfig(conf); // disable version checking, so we can test against whatever version of HBase happens to be // installed (right now, its generally going to be SNAPSHOT versions). conf.setBoolean(Indexer.CHECK_VERSION_CONF_KEY, false); UTIL.startMiniCluster(); } @AfterClass public static void shutdownCluster() throws Exception { UTIL.shutdownMiniCluster(); } @Before public void setup() throws Exception { this.state = setupTest(TestTable.getTableNameString()); } private interface TableStateVerifier { /** * Verify that the state of the table is correct. Should fail the unit test if it isn't as * expected. * @param state */ public void verify(TableState state); } /** * {@link TableStateVerifier} that ensures the kvs returned from the table match the passed * {@link KeyValue}s when querying on the given columns. */ private class ListMatchingVerifier implements TableStateVerifier { private List<Cell> expectedKvs; private ColumnReference[] columns; private String msg; public ListMatchingVerifier(String msg, List<Cell> kvs, ColumnReference... columns) { this.expectedKvs = kvs; this.columns = columns; this.msg = msg; } @Override public void verify(TableState state) { try { Scanner kvs = ((LocalTableState) state).getIndexedColumnsTableState(Arrays.asList(columns), false).getFirst(); int count = 0; Cell kv; while ((kv = kvs.next()) != null) { Cell next = expectedKvs.get(count++); assertEquals( msg + ": Unexpected kv in table state!\nexpected v1: " + Bytes.toString(next.getValue()) + "\nactual v1:" + Bytes.toString(kv.getValue()), next, kv); } assertEquals(msg + ": Didn't find enough kvs in table state!", expectedKvs.size(), count); } catch (IOException e) { fail(msg + ": Got an exception while reading local table state! " + e.getMessage()); } } } private class VerifyingIndexCodec extends CoveredIndexCodecForTesting { private Queue<TableStateVerifier> verifiers = new ArrayDeque<TableStateVerifier>(); @Override public Iterable<IndexUpdate> getIndexDeletes(TableState state, IndexMetaData context) { verify(state); return super.getIndexDeletes(state, context); } @Override public Iterable<IndexUpdate> getIndexUpserts(TableState state, IndexMetaData context) { verify(state); return super.getIndexUpserts(state, context); } private void verify(TableState state) { TableStateVerifier verifier = verifiers.poll(); if (verifier == null) return; verifier.verify(state); } } /** * Test that we see the expected values in a {@link TableState} when doing single puts against a * region. * @throws Exception on failure */ @Test public void testExpectedResultsInTableStateForSinglePut() throws Exception { //just do a simple Put to start with long ts = state.ts; Put p = new Put(row, ts); p.add(family, qual, Bytes.toBytes("v1")); // get all the underlying kvs for the put final List<Cell> expectedKvs = new ArrayList<Cell>(); final List<Cell> allKvs = new ArrayList<Cell>(); allKvs.addAll(p.getFamilyMap().get(family)); // setup the verifier for the data we expect to write // first call shouldn't have anything in the table final ColumnReference familyRef = new ColumnReference(EndToEndCoveredColumnsIndexBuilderIT.family, ColumnReference.ALL_QUALIFIERS); VerifyingIndexCodec codec = state.codec; codec.verifiers.add(new ListMatchingVerifier("cleanup state 1", expectedKvs, familyRef)); codec.verifiers.add(new ListMatchingVerifier("put state 1", allKvs, familyRef)); // do the actual put (no indexing will actually be done) HTable primary = state.table; primary.put(p); primary.flushCommits(); // now we do another put to the same row. We should see just the old row state, followed by the // new + old p = new Put(row, ts + 1); p.add(family, qual, Bytes.toBytes("v2")); expectedKvs.addAll(allKvs); // add them first b/c the ts is newer allKvs.addAll(0, p.get(family, qual)); codec.verifiers.add(new ListMatchingVerifier("cleanup state 2", expectedKvs, familyRef)); codec.verifiers.add(new ListMatchingVerifier("put state 2", allKvs, familyRef)); // do the actual put primary.put(p); primary.flushCommits(); // cleanup after ourselves cleanup(state); } /** * Similar to {@link #testExpectedResultsInTableStateForSinglePut()}, but against batches of puts. * Previous implementations managed batches by playing current state against each element in the * batch, rather than combining all the per-row updates into a single mutation for the batch. This * test ensures that we see the correct expected state. * @throws Exception on failure */ @Test public void testExpectedResultsInTableStateForBatchPuts() throws Exception { long ts = state.ts; // build up a list of puts to make, all on the same row Put p1 = new Put(row, ts); p1.add(family, qual, Bytes.toBytes("v1")); Put p2 = new Put(row, ts + 1); p2.add(family, qual, Bytes.toBytes("v2")); // setup all the verifiers we need. This is just the same as above, but will be called twice // since we need to iterate the batch. // get all the underlying kvs for the put final List<Cell> allKvs = new ArrayList<Cell>(2); allKvs.addAll(p2.getFamilyCellMap().get(family)); allKvs.addAll(p1.getFamilyCellMap().get(family)); // setup the verifier for the data we expect to write // both puts should be put into a single batch final ColumnReference familyRef = new ColumnReference(EndToEndCoveredColumnsIndexBuilderIT.family, ColumnReference.ALL_QUALIFIERS); VerifyingIndexCodec codec = state.codec; // no previous state in the table codec.verifiers.add(new ListMatchingVerifier("cleanup state 1", Collections .<Cell> emptyList(), familyRef)); codec.verifiers.add(new ListMatchingVerifier("put state 1", p1.getFamilyCellMap().get(family), familyRef)); codec.verifiers.add(new ListMatchingVerifier("cleanup state 2", p1.getFamilyCellMap().get(family), familyRef)); // kvs from both puts should be in the table now codec.verifiers.add(new ListMatchingVerifier("put state 2", allKvs, familyRef)); // do the actual put (no indexing will actually be done) HTable primary = state.table; primary.setAutoFlush(false); primary.put(Arrays.asList(p1, p2)); primary.flushCommits(); // cleanup after ourselves cleanup(state); } /** * @param tableName name of the table to create for the test * @return the supporting state for the test */ private TestState setupTest(String tableName) throws IOException { byte[] tableNameBytes = Bytes.toBytes(tableName); @SuppressWarnings("deprecation") HTableDescriptor desc = new HTableDescriptor(tableNameBytes); desc.addFamily(FAM1); // add the necessary simple options to create the builder Map<String, String> indexerOpts = new HashMap<String, String>(); // just need to set the codec - we are going to set it later, but we need something here or the // initializer blows up. indexerOpts.put(NonTxIndexBuilder.CODEC_CLASS_NAME_KEY, CoveredIndexCodecForTesting.class.getName()); Indexer.enableIndexing(desc, NonTxIndexBuilder.class, indexerOpts, Coprocessor.PRIORITY_USER); // create the table HBaseAdmin admin = UTIL.getHBaseAdmin(); admin.createTable(desc); HTable primary = new HTable(UTIL.getConfiguration(), tableNameBytes); // overwrite the codec so we can verify the current state Region region = UTIL.getMiniHBaseCluster().getRegions(tableNameBytes).get(0); Indexer indexer = (Indexer) region.getCoprocessorHost().findCoprocessor(Indexer.class.getName()); NonTxIndexBuilder builder = (NonTxIndexBuilder) indexer.getBuilderForTesting(); VerifyingIndexCodec codec = new VerifyingIndexCodec(); builder.setIndexCodecForTesting(codec); // setup the Puts we want to write final long ts = System.currentTimeMillis(); EnvironmentEdge edge = new EnvironmentEdge() { @Override public long currentTime() { return ts; } }; EnvironmentEdgeManager.injectEdge(edge); return new TestState(primary, codec, ts); } /** * Cleanup the test based on the passed state. * @param state */ private void cleanup(TestState state) throws IOException { EnvironmentEdgeManager.reset(); state.table.close(); UTIL.deleteTable(state.table.getTableName()); } }
/* * 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.spark.util.kvstore; import java.io.File; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import com.google.common.collect.ImmutableSet; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.SystemUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.rocksdb.RocksIterator; import static org.junit.Assert.*; import static org.junit.Assume.assumeFalse; public class RocksDBSuite { private RocksDB db; private File dbpath; @After public void cleanup() throws Exception { if (db != null) { db.close(); } if (dbpath != null) { FileUtils.deleteQuietly(dbpath); } } @Before public void setup() throws Exception { assumeFalse(SystemUtils.IS_OS_MAC_OSX && SystemUtils.OS_ARCH.equals("aarch64")); dbpath = File.createTempFile("test.", ".rdb"); dbpath.delete(); db = new RocksDB(dbpath); } @Test public void testReopenAndVersionCheckDb() throws Exception { db.close(); db = null; assertTrue(dbpath.exists()); db = new RocksDB(dbpath); assertEquals(RocksDB.STORE_VERSION, db.serializer.deserializeLong(db.db().get(RocksDB.STORE_VERSION_KEY))); db.db().put(RocksDB.STORE_VERSION_KEY, db.serializer.serialize(RocksDB.STORE_VERSION + 1)); db.close(); db = null; try { db = new RocksDB(dbpath); fail("Should have failed version check."); } catch (UnsupportedStoreVersionException e) { // Expected. } } @Test public void testObjectWriteReadDelete() throws Exception { CustomType1 t = createCustomType1(1); try { db.read(CustomType1.class, t.key); fail("Expected exception for non-existent object."); } catch (NoSuchElementException nsee) { // Expected. } db.write(t); assertEquals(t, db.read(t.getClass(), t.key)); assertEquals(1L, db.count(t.getClass())); db.delete(t.getClass(), t.key); try { db.read(t.getClass(), t.key); fail("Expected exception for deleted object."); } catch (NoSuchElementException nsee) { // Expected. } // Look into the actual DB and make sure that all the keys related to the type have been // removed. assertEquals(0, countKeys(t.getClass())); } @Test public void testMultipleObjectWriteReadDelete() throws Exception { CustomType1 t1 = createCustomType1(1); CustomType1 t2 = createCustomType1(2); t2.id = t1.id; db.write(t1); db.write(t2); assertEquals(t1, db.read(t1.getClass(), t1.key)); assertEquals(t2, db.read(t2.getClass(), t2.key)); assertEquals(2L, db.count(t1.getClass())); // There should be one "id" index entry with two values. assertEquals(2, db.count(t1.getClass(), "id", t1.id)); // Delete the first entry; now there should be 3 remaining keys, since one of the "name" // index entries should have been removed. db.delete(t1.getClass(), t1.key); // Make sure there's a single entry in the "id" index now. assertEquals(1, db.count(t2.getClass(), "id", t2.id)); // Delete the remaining entry, make sure all data is gone. db.delete(t2.getClass(), t2.key); assertEquals(0, countKeys(t2.getClass())); } @Test public void testMultipleTypesWriteReadDelete() throws Exception { CustomType1 t1 = createCustomType1(1); IntKeyType t2 = new IntKeyType(); t2.key = 2; t2.id = "2"; t2.values = Arrays.asList("value1", "value2"); ArrayKeyIndexType t3 = new ArrayKeyIndexType(); t3.key = new int[] { 42, 84 }; t3.id = new String[] { "id1", "id2" }; db.write(t1); db.write(t2); db.write(t3); assertEquals(t1, db.read(t1.getClass(), t1.key)); assertEquals(t2, db.read(t2.getClass(), t2.key)); assertEquals(t3, db.read(t3.getClass(), t3.key)); // There should be one "id" index with a single entry for each type. assertEquals(1, db.count(t1.getClass(), "id", t1.id)); assertEquals(1, db.count(t2.getClass(), "id", t2.id)); assertEquals(1, db.count(t3.getClass(), "id", t3.id)); // Delete the first entry; this should not affect the entries for the second type. db.delete(t1.getClass(), t1.key); assertEquals(0, countKeys(t1.getClass())); assertEquals(1, db.count(t2.getClass(), "id", t2.id)); assertEquals(1, db.count(t3.getClass(), "id", t3.id)); // Delete the remaining entries, make sure all data is gone. db.delete(t2.getClass(), t2.key); assertEquals(0, countKeys(t2.getClass())); db.delete(t3.getClass(), t3.key); assertEquals(0, countKeys(t3.getClass())); } @Test public void testMetadata() throws Exception { assertNull(db.getMetadata(CustomType1.class)); CustomType1 t = createCustomType1(1); db.setMetadata(t); assertEquals(t, db.getMetadata(CustomType1.class)); db.setMetadata(null); assertNull(db.getMetadata(CustomType1.class)); } @Test public void testUpdate() throws Exception { CustomType1 t = createCustomType1(1); db.write(t); t.name = "anotherName"; db.write(t); assertEquals(1, db.count(t.getClass())); assertEquals(1, db.count(t.getClass(), "name", "anotherName")); assertEquals(0, db.count(t.getClass(), "name", "name")); } @Test public void testRemoveAll() throws Exception { for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { ArrayKeyIndexType o = new ArrayKeyIndexType(); o.key = new int[] { i, j, 0 }; o.id = new String[] { "things" }; db.write(o); o = new ArrayKeyIndexType(); o.key = new int[] { i, j, 1 }; o.id = new String[] { "more things" }; db.write(o); } } ArrayKeyIndexType o = new ArrayKeyIndexType(); o.key = new int[] { 2, 2, 2 }; o.id = new String[] { "things" }; db.write(o); assertEquals(9, db.count(ArrayKeyIndexType.class)); db.removeAllByIndexValues( ArrayKeyIndexType.class, KVIndex.NATURAL_INDEX_NAME, ImmutableSet.of(new int[] {0, 0, 0}, new int[] { 2, 2, 2 })); assertEquals(7, db.count(ArrayKeyIndexType.class)); db.removeAllByIndexValues( ArrayKeyIndexType.class, "id", ImmutableSet.of(new String[] { "things" })); assertEquals(4, db.count(ArrayKeyIndexType.class)); db.removeAllByIndexValues( ArrayKeyIndexType.class, "id", ImmutableSet.of(new String[] { "more things" })); assertEquals(0, db.count(ArrayKeyIndexType.class)); } @Test public void testSkip() throws Exception { for (int i = 0; i < 10; i++) { db.write(createCustomType1(i)); } KVStoreIterator<CustomType1> it = db.view(CustomType1.class).closeableIterator(); assertTrue(it.hasNext()); assertTrue(it.skip(5)); assertEquals("key5", it.next().key); assertTrue(it.skip(3)); assertEquals("key9", it.next().key); assertFalse(it.hasNext()); } @Test public void testNegativeIndexValues() throws Exception { List<Integer> expected = Arrays.asList(-100, -50, 0, 50, 100); expected.forEach(i -> { try { db.write(createCustomType1(i)); } catch (Exception e) { throw new RuntimeException(e); } }); List<Integer> results = StreamSupport .stream(db.view(CustomType1.class).index("int").spliterator(), false) .map(e -> e.num) .collect(Collectors.toList()); assertEquals(expected, results); } @Test public void testCloseRocksDBIterator() throws Exception { // SPARK-31929: test when RocksDB.close() is called, related RocksDBIterators // are closed. And files opened by iterators are also closed. File dbPathForCloseTest = File .createTempFile( "test_db_close.", ".rdb"); dbPathForCloseTest.delete(); RocksDB dbForCloseTest = new RocksDB(dbPathForCloseTest); for (int i = 0; i < 8192; i++) { dbForCloseTest.write(createCustomType1(i)); } String key = dbForCloseTest .view(CustomType1.class).iterator().next().key; assertEquals("key0", key); Iterator<CustomType1> it0 = dbForCloseTest .view(CustomType1.class).max(1).iterator(); while (it0.hasNext()) { it0.next(); } System.gc(); Iterator<CustomType1> it1 = dbForCloseTest .view(CustomType1.class).iterator(); assertEquals("key0", it1.next().key); try (KVStoreIterator<CustomType1> it2 = dbForCloseTest .view(CustomType1.class).closeableIterator()) { assertEquals("key0", it2.next().key); } dbForCloseTest.close(); assertTrue(dbPathForCloseTest.exists()); FileUtils.deleteQuietly(dbPathForCloseTest); assertTrue(!dbPathForCloseTest.exists()); } private CustomType1 createCustomType1(int i) { CustomType1 t = new CustomType1(); t.key = "key" + i; t.id = "id" + i; t.name = "name" + i; t.num = i; t.child = "child" + i; return t; } private int countKeys(Class<?> type) throws Exception { byte[] prefix = db.getTypeInfo(type).keyPrefix(); int count = 0; RocksIterator it = db.db().newIterator(); it.seek(prefix); while (it.isValid()) { byte[] key = it.key(); if (RocksDBIterator.startsWith(key, prefix)) { count++; } it.next(); } return count; } }
package com.rahul.media.activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.provider.MediaStore; import android.support.v4.content.FileProvider; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Toast; import com.msupport.MSupport; import com.msupport.MSupportConstants; import com.rahul.media.R; import com.rahul.media.adapters.ImageListRecycleAdapter; import com.rahul.media.adapters.ImagePreviewAdapter; import com.rahul.media.model.CustomGallery; import com.rahul.media.model.Define; import com.rahul.media.utils.BitmapDecoder; import com.rahul.media.utils.MediaUtility; import com.rahul.media.utils.ViewPagerSwipeLess; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import crop.Crop; /** * Class to pick image from camera * Created by rahul on 22/5/15. */ public class CameraPickActivity extends AppCompatActivity { private static final int ACTION_REQUEST_CAMERA = 201; private ViewPagerSwipeLess mPager; private HashMap<String, CustomGallery> dataT; private ImagePreviewAdapter imagePreviewAdapter; private ImageListRecycleAdapter mImageListAdapter; private Uri userPhotoUri; private boolean isCrop, isSquareCrop; private int pickCount = 1; private AlertDialog alertDialog; private int aspectX, aspectY; private void showAlertDialog(Context mContext, String text) { alertDialog = new AlertDialog.Builder(mContext) .setMessage(text) .setCancelable(false). setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { alertDialog.dismiss(); } }).create(); alertDialog.show(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_camera_preview); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setBackgroundColor(Define.ACTIONBAR_COLOR); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mPager = (ViewPagerSwipeLess) findViewById(R.id.pager); dataT = new HashMap<>(); imagePreviewAdapter = new ImagePreviewAdapter(CameraPickActivity.this, dataT); mPager.setAdapter(imagePreviewAdapter); mImageListAdapter = new ImageListRecycleAdapter(this, dataT); RecyclerView mRecycleView = (RecyclerView) findViewById(R.id.image_hlistview); mRecycleView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)); mRecycleView.setAdapter(mImageListAdapter); mImageListAdapter.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mPager.setCurrentItem(position); } }); try { aspectX = getIntent().getIntExtra("aspect_x", 1); aspectY = getIntent().getIntExtra("aspect_y", 1); } catch (Exception ignored) { } try { isCrop = getIntent().getExtras().getBoolean("crop"); isSquareCrop = getIntent().getExtras().getBoolean("isSquareCrop"); } catch (Exception e) { e.printStackTrace(); } pickCount = getIntent().getIntExtra("pickCount", Define.MIN_MEDIA_COUNT); openCamera(false); } @Override public void onBackPressed() { Intent data2 = new Intent(); setResult(RESULT_CANCELED, data2); super.onBackPressed(); } private void openCamera(boolean isPermission) { String[] permissionSet = {MSupportConstants.WRITE_EXTERNAL_STORAGE, MSupportConstants.CAMERA}; if (isPermission) { cameraIntent(); } else { boolean isCameraPermissionGranted; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { isCameraPermissionGranted = MSupport.checkMultiplePermission(CameraPickActivity.this, permissionSet, MSupportConstants.REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS); } else isCameraPermissionGranted = true; if (isCameraPermissionGranted) { cameraIntent(); } } } private void cameraIntent() { if (dataT.size() == pickCount) { showAlertDialog(CameraPickActivity.this, "You can select max " + pickCount + " images."); } else try { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(getPackageManager()) != null) { Uri imageFile = MediaUtility.createImageFile(CameraPickActivity.this); userPhotoUri = FileProvider.getUriForFile(CameraPickActivity.this, Define.MEDIA_PROVIDER, new File(imageFile.getPath())); if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.M) { // only for gingerbread and newer versions takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, userPhotoUri); userPhotoUri = imageFile; } else { userPhotoUri = imageFile; takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, userPhotoUri); } startActivityForResult(takePictureIntent, ACTION_REQUEST_CAMERA); } } catch (Exception e) { e.printStackTrace(); showAlertDialog(CameraPickActivity.this, "Device does not support camera."); } } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MSupportConstants.REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: { ArrayList<String> deniedPermissionList = new ArrayList<>(); boolean isAllPermissionGranted = true; for (int i = 0; i < grantResults.length; i++) { int results = grantResults[i]; String permission = permissions[i]; if (results != PackageManager.PERMISSION_GRANTED) { isAllPermissionGranted = false; deniedPermissionList.add(MSupportConstants.getPermissionRationaleMessage(permission)); } } if (isAllPermissionGranted) { openCamera(true); } else { String message = "Requested Permission not granted"; if (!deniedPermissionList.isEmpty()) { message = "You need to grant access to " + deniedPermissionList.get(0); for (int i = 1; i < deniedPermissionList.size(); i++) { message = message + ", " + deniedPermissionList.get(i); } message = message + " to access app features"; } Toast.makeText(CameraPickActivity.this, message, Toast.LENGTH_SHORT).show(); finish(); } } } } private class ProcessImageView extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(Void... params) { CustomGallery item = new CustomGallery(); item.sdcardPath = userPhotoUri.getPath(); item.sdCardUri = userPhotoUri; item.sdcardPath = BitmapDecoder.getBitmap(userPhotoUri.getPath(), CameraPickActivity.this); item.sdCardUri = (Uri.parse(item.sdcardPath)); dataT.put(item.sdcardPath, item); return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); imagePreviewAdapter.customNotify(dataT); mImageListAdapter.customNotify(dataT); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (requestCode == ACTION_REQUEST_CAMERA) { if (pickCount == 1) { dataT.clear(); } if (userPhotoUri != null) { new ProcessImageView().execute(); } } else if (requestCode == Crop.REQUEST_CROP) { try { Uri mTargetImageUri = (Uri) data.getExtras().get(MediaStore.EXTRA_OUTPUT); if (mTargetImageUri != null) { String imagePath = mImageListAdapter.mItems.get(mPager.getCurrentItem()).sdcardPath; CustomGallery item = new CustomGallery(); item.sdcardPath = mTargetImageUri.getPath(); item.sdCardUri = mTargetImageUri; dataT.remove(imagePath); dataT.put(mTargetImageUri.getPath(), item); imagePreviewAdapter.customNotify(dataT); mImageListAdapter.customNotify(dataT); } } catch (Exception e) { String invalidImageText = (String) data.getExtras().get("invalid_image"); if (invalidImageText != null) showAlertDialog(CameraPickActivity.this, invalidImageText); } } } else { if (dataT == null || dataT.size() == 0) { Intent data2 = new Intent(); setResult(RESULT_CANCELED, data2); finish(); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_camera, menu); menu.findItem(R.id.action_crop).setVisible(isCrop); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_ok) { ArrayList<CustomGallery> mArrayList = new ArrayList<>(dataT.values()); if (mArrayList.size() > 0) { ArrayList<String> allPath = new ArrayList<>(); for (int i = 0; i < mArrayList.size(); i++) { allPath.add(mArrayList.get(i).sdcardPath); } Intent data = new Intent().putStringArrayListExtra(Define.INTENT_PATH, allPath); setResult(RESULT_OK, data); finish(); } else { showAlertDialog(CameraPickActivity.this, "Please select an image."); } } else if (id == android.R.id.home) { Intent data = new Intent(); setResult(RESULT_CANCELED, data); finish(); } else if (id == R.id.action_camera) { openCamera(false); } else if (id == R.id.action_crop) { if (imagePreviewAdapter != null && imagePreviewAdapter.getCount() > 0) { String imagePath = mImageListAdapter.mItems.get(mPager.getCurrentItem()).sdcardPath; Uri destination; try { destination = MediaUtility.createImageFile(CameraPickActivity.this); if (isSquareCrop) { Crop.of((Uri.parse("file://" + imagePath)), destination). asSquare().start(CameraPickActivity.this); } else { Crop.of((Uri.parse("file://" + imagePath)), destination). withAspect(aspectX, aspectY). start(CameraPickActivity.this); } } catch (IOException e) { e.printStackTrace(); } } } return super.onOptionsItemSelected(item); } }
/* * 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. */ /* * This code was generated by https://github.com/google/apis-client-generator/ * (build: 2016-05-27 16:00:31 UTC) * on 2016-06-03 at 19:46:25 UTC * Modify at your own risk. */ package com.appspot.smart_wish_list.smartwishlist.model; /** * Model definition for SmartWishListNotificationTriggerData. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the smartwishlist. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class SmartWishListNotificationTriggerData extends com.google.api.client.json.GenericJson { /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean autoUpdate; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean availability; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Double creationDate; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean enabled; /** * Item data message. * The value may be {@code null}. */ @com.google.api.client.util.Key private SmartWishListItemData item; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Double priceDrop; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Double priceDropPercentage; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Double priceThreshold; /** * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean soldByAmazon; /** * The value may be {@code null}. */ @com.google.api.client.util.Key @com.google.api.client.json.JsonString private java.lang.Long wishListIndex; /** * @return value or {@code null} for none */ public java.lang.Boolean getAutoUpdate() { return autoUpdate; } /** * @param autoUpdate autoUpdate or {@code null} for none */ public SmartWishListNotificationTriggerData setAutoUpdate(java.lang.Boolean autoUpdate) { this.autoUpdate = autoUpdate; return this; } /** * @return value or {@code null} for none */ public java.lang.Boolean getAvailability() { return availability; } /** * @param availability availability or {@code null} for none */ public SmartWishListNotificationTriggerData setAvailability(java.lang.Boolean availability) { this.availability = availability; return this; } /** * @return value or {@code null} for none */ public java.lang.Double getCreationDate() { return creationDate; } /** * @param creationDate creationDate or {@code null} for none */ public SmartWishListNotificationTriggerData setCreationDate(java.lang.Double creationDate) { this.creationDate = creationDate; return this; } /** * @return value or {@code null} for none */ public java.lang.Boolean getEnabled() { return enabled; } /** * @param enabled enabled or {@code null} for none */ public SmartWishListNotificationTriggerData setEnabled(java.lang.Boolean enabled) { this.enabled = enabled; return this; } /** * Item data message. * @return value or {@code null} for none */ public SmartWishListItemData getItem() { return item; } /** * Item data message. * @param item item or {@code null} for none */ public SmartWishListNotificationTriggerData setItem(SmartWishListItemData item) { this.item = item; return this; } /** * @return value or {@code null} for none */ public java.lang.Double getPriceDrop() { return priceDrop; } /** * @param priceDrop priceDrop or {@code null} for none */ public SmartWishListNotificationTriggerData setPriceDrop(java.lang.Double priceDrop) { this.priceDrop = priceDrop; return this; } /** * @return value or {@code null} for none */ public java.lang.Double getPriceDropPercentage() { return priceDropPercentage; } /** * @param priceDropPercentage priceDropPercentage or {@code null} for none */ public SmartWishListNotificationTriggerData setPriceDropPercentage(java.lang.Double priceDropPercentage) { this.priceDropPercentage = priceDropPercentage; return this; } /** * @return value or {@code null} for none */ public java.lang.Double getPriceThreshold() { return priceThreshold; } /** * @param priceThreshold priceThreshold or {@code null} for none */ public SmartWishListNotificationTriggerData setPriceThreshold(java.lang.Double priceThreshold) { this.priceThreshold = priceThreshold; return this; } /** * @return value or {@code null} for none */ public java.lang.Boolean getSoldByAmazon() { return soldByAmazon; } /** * @param soldByAmazon soldByAmazon or {@code null} for none */ public SmartWishListNotificationTriggerData setSoldByAmazon(java.lang.Boolean soldByAmazon) { this.soldByAmazon = soldByAmazon; return this; } /** * @return value or {@code null} for none */ public java.lang.Long getWishListIndex() { return wishListIndex; } /** * @param wishListIndex wishListIndex or {@code null} for none */ public SmartWishListNotificationTriggerData setWishListIndex(java.lang.Long wishListIndex) { this.wishListIndex = wishListIndex; return this; } @Override public SmartWishListNotificationTriggerData set(String fieldName, Object value) { return (SmartWishListNotificationTriggerData) super.set(fieldName, value); } @Override public SmartWishListNotificationTriggerData clone() { return (SmartWishListNotificationTriggerData) super.clone(); } }
/* * 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.facebook.presto.jdbc; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.URL; import java.sql.Array; import java.sql.Blob; import java.sql.Clob; import java.sql.Date; import java.sql.NClob; import java.sql.ParameterMetaData; import java.sql.PreparedStatement; import java.sql.Ref; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.RowId; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.sql.SQLXML; import java.sql.Time; import java.sql.Timestamp; import java.util.Calendar; public class PrestoPreparedStatement extends PrestoStatement implements PreparedStatement { PrestoPreparedStatement(PrestoConnection connection, String sql) throws SQLException { super(connection); } @Override public ResultSet executeQuery() throws SQLException { throw new NotImplementedException("PreparedStatement", "executeQuery"); } @Override public int executeUpdate() throws SQLException { throw new NotImplementedException("PreparedStatement", "executeUpdate"); } @Override public void setNull(int parameterIndex, int sqlType) throws SQLException { throw new NotImplementedException("PreparedStatement", "setNull"); } @Override public void setBoolean(int parameterIndex, boolean x) throws SQLException { throw new NotImplementedException("PreparedStatement", "setBoolean"); } @Override public void setByte(int parameterIndex, byte x) throws SQLException { throw new NotImplementedException("PreparedStatement", "setByte"); } @Override public void setShort(int parameterIndex, short x) throws SQLException { throw new NotImplementedException("PreparedStatement", "setShort"); } @Override public void setInt(int parameterIndex, int x) throws SQLException { throw new NotImplementedException("PreparedStatement", "setInt"); } @Override public void setLong(int parameterIndex, long x) throws SQLException { throw new NotImplementedException("PreparedStatement", "setLong"); } @Override public void setFloat(int parameterIndex, float x) throws SQLException { throw new NotImplementedException("PreparedStatement", "setFloat"); } @Override public void setDouble(int parameterIndex, double x) throws SQLException { throw new NotImplementedException("PreparedStatement", "setDouble"); } @Override public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException { throw new NotImplementedException("PreparedStatement", "setBigDecimal"); } @Override public void setString(int parameterIndex, String x) throws SQLException { throw new NotImplementedException("PreparedStatement", "setString"); } @Override public void setBytes(int parameterIndex, byte[] x) throws SQLException { throw new NotImplementedException("PreparedStatement", "setBytes"); } @Override public void setDate(int parameterIndex, Date x) throws SQLException { throw new NotImplementedException("PreparedStatement", "setDate"); } @Override public void setTime(int parameterIndex, Time x) throws SQLException { throw new NotImplementedException("PreparedStatement", "setTime"); } @Override public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException { throw new NotImplementedException("PreparedStatement", "setTimestamp"); } @Override public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException { throw new NotImplementedException("PreparedStatement", "setAsciiStream"); } @Override public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException { throw new SQLFeatureNotSupportedException("setUnicodeStream"); } @Override public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException { throw new NotImplementedException("PreparedStatement", "setBinaryStream"); } @Override public void clearParameters() throws SQLException { throw new NotImplementedException("PreparedStatement", "clearParameters"); } @Override public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException { throw new NotImplementedException("PreparedStatement", "setObject"); } @Override public void setObject(int parameterIndex, Object x) throws SQLException { throw new NotImplementedException("PreparedStatement", "setObject"); } @Override public boolean execute() throws SQLException { throw new NotImplementedException("PreparedStatement", "execute"); } @Override public void addBatch() throws SQLException { throw new NotImplementedException("PreparedStatement", "addBatch"); } @Override public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException { throw new NotImplementedException("PreparedStatement", "setCharacterStream"); } @Override public void setRef(int parameterIndex, Ref x) throws SQLException { throw new SQLFeatureNotSupportedException("setRef"); } @Override public void setBlob(int parameterIndex, Blob x) throws SQLException { throw new SQLFeatureNotSupportedException("setBlob"); } @Override public void setClob(int parameterIndex, Clob x) throws SQLException { throw new SQLFeatureNotSupportedException("setClob"); } @Override public void setArray(int parameterIndex, Array x) throws SQLException { throw new SQLFeatureNotSupportedException("setArray"); } @Override public ResultSetMetaData getMetaData() throws SQLException { throw new SQLFeatureNotSupportedException("getMetaData"); } @Override public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException { throw new NotImplementedException("PreparedStatement", "setDate"); } @Override public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException { throw new NotImplementedException("PreparedStatement", "setTime"); } @Override public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException { throw new NotImplementedException("PreparedStatement", "setTimestamp"); } @Override public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException { throw new NotImplementedException("PreparedStatement", "setNull"); } @Override public void setURL(int parameterIndex, URL x) throws SQLException { throw new SQLFeatureNotSupportedException("setURL"); } @Override public ParameterMetaData getParameterMetaData() throws SQLException { throw new NotImplementedException("PreparedStatement", "getParameterMetaData"); } @Override public void setRowId(int parameterIndex, RowId x) throws SQLException { throw new SQLFeatureNotSupportedException("setRowId"); } @Override public void setNString(int parameterIndex, String value) throws SQLException { throw new SQLFeatureNotSupportedException("setNString"); } @Override public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException { throw new SQLFeatureNotSupportedException("setNCharacterStream"); } @Override public void setNClob(int parameterIndex, NClob value) throws SQLException { throw new SQLFeatureNotSupportedException("setNClob"); } @Override public void setClob(int parameterIndex, Reader reader, long length) throws SQLException { throw new SQLFeatureNotSupportedException("setClob"); } @Override public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException { throw new SQLFeatureNotSupportedException("setBlob"); } @Override public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException { throw new SQLFeatureNotSupportedException("setNClob"); } @Override public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException { throw new SQLFeatureNotSupportedException("setSQLXML"); } @Override public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException { throw new SQLFeatureNotSupportedException("setObject"); } @Override public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { throw new NotImplementedException("PreparedStatement", "setAsciiStream"); } @Override public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException { throw new NotImplementedException("PreparedStatement", "setBinaryStream"); } @Override public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException { throw new NotImplementedException("PreparedStatement", "setCharacterStream"); } @Override public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException { throw new SQLFeatureNotSupportedException("setAsciiStream"); } @Override public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { throw new SQLFeatureNotSupportedException("setBinaryStream"); } @Override public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException { throw new SQLFeatureNotSupportedException("setCharacterStream"); } @Override public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException { throw new SQLFeatureNotSupportedException("setNCharacterStream"); } @Override public void setClob(int parameterIndex, Reader reader) throws SQLException { throw new SQLFeatureNotSupportedException("setClob"); } @Override public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException { throw new SQLFeatureNotSupportedException("setBlob"); } @Override public void setNClob(int parameterIndex, Reader reader) throws SQLException { throw new SQLFeatureNotSupportedException("setNClob"); } @Override public void addBatch(String sql) throws SQLException { throw new SQLException("This method cannot be called on PreparedStatement"); } }
package livestreamerJGUI; import java.awt.Toolkit; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.DefaultComboBoxModel; import javax.swing.JOptionPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; public class LivestreamerJGUI extends javax.swing.JFrame { private static LivestreamerJGUI instance; private static final String DEFAULT_QUALITY_SETTING = "defaultQuality"; public static LivestreamerJGUI getInstance() { return instance; } private LivestreamerJGUI() { initComponents(); String defaultQuality = PreferenceHandler.getInstance().get(DEFAULT_QUALITY_SETTING); if(defaultQuality != null) { this.tfQuality.setText(defaultQuality); this.dropQuality.setSelectedItem(Quality.valueOf(defaultQuality)); } else { this.tfQuality.setText(((DefaultComboBoxModel<Quality>)this.dropQuality.getModel()).getElementAt(this.dropQuality.getSelectedIndex()).toString()); } SwingUtilities.getRootPane(this).setDefaultButton(bGo); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { fd = new javax.swing.JFileChooser(); selectGroup = new javax.swing.ButtonGroup(); bFile = new javax.swing.JButton(); labelFile = new javax.swing.JLabel(); rbRecord = new javax.swing.JRadioButton(); rbWatch = new javax.swing.JRadioButton(); bGo = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); taOutput = new javax.swing.JTextArea(); labelOutput = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); jSeparator2 = new javax.swing.JSeparator(); labelStreamUrl = new javax.swing.JLabel(); bStop = new javax.swing.JButton(); tfStreamUrl = new javax.swing.JTextField(); tfQuality = new javax.swing.JTextField(); labelQuality = new javax.swing.JLabel(); tfFile = new javax.swing.JTextField(); dropFavorites = new javax.swing.JComboBox<String>(); cbFavorites = new javax.swing.JCheckBox(); bOpenEditFavDialog = new javax.swing.JButton(); bBrowseTwitch = new javax.swing.JButton(); dropQuality = new javax.swing.JComboBox(); bSetSelectedQualityAsDefault = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("livestreamerJGUI" +BuildInfo.version); setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("images/icon.png"))); setMinimumSize(new java.awt.Dimension(626, 481)); setResizable(false); bFile.setText("File"); bFile.setEnabled(false); bFile.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bFileActionPerformed(evt); } }); labelFile.setText("File name:"); labelFile.setEnabled(false); selectGroup.add(rbRecord); rbRecord.setText("Record to file"); rbRecord.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { rbRecordActionPerformed(evt); } }); selectGroup.add(rbWatch); rbWatch.setSelected(true); rbWatch.setText("Watch stream in player (Default: VLC)"); rbWatch.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { rbWatchActionPerformed(evt); } }); bGo.setText("GO!"); bGo.setMaximumSize(new java.awt.Dimension(70, 35)); bGo.setMinimumSize(new java.awt.Dimension(70, 35)); bGo.setPreferredSize(new java.awt.Dimension(55, 23)); bGo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bGoActionPerformed(evt); } }); taOutput.setEditable(false); taOutput.setColumns(20); taOutput.setLineWrap(true); taOutput.setRows(5); taOutput.setWrapStyleWord(true); jScrollPane1.setViewportView(taOutput); labelOutput.setText("Output:"); labelStreamUrl.setText("Stream URL:"); bStop.setText("Stop"); bStop.setEnabled(false); bStop.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bStopActionPerformed(evt); } }); tfQuality.setToolTipText("Leave empty and ceck output if you are unsure about available bitrates."); labelQuality.setText("Quality:"); tfFile.setEditable(false); tfFile.setEnabled(false); dropFavorites.setEnabled(false); cbFavorites.setText("Favorites:"); cbFavorites.setToolTipText(""); cbFavorites.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cbFavoritesActionPerformed(evt); } }); bOpenEditFavDialog.setText("Edit Favorites"); bOpenEditFavDialog.setEnabled(false); bOpenEditFavDialog.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bOpenEditFavDialogActionPerformed(evt); } }); bBrowseTwitch.setText("Browse Twitch"); bBrowseTwitch.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bBrowseTwitchActionPerformed(evt); } }); dropQuality.setMaximumRowCount(16); dropQuality.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); DefaultComboBoxModel<Quality> aModel = new DefaultComboBoxModel(); for(Quality q : Quality.values()) { aModel.addElement(q); } dropQuality.setModel(aModel); dropQuality.setSelectedItem(Quality.best); dropQuality.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { dropQualityActionPerformed(evt); } }); bSetSelectedQualityAsDefault.setText("Set quality as default"); bSetSelectedQualityAsDefault.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bSetSelectedQualityAsDefaultActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator2) .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(bFile) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(labelFile) .addComponent(tfFile, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(labelOutput) .addComponent(rbRecord) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(labelStreamUrl) .addComponent(cbFavorites, javax.swing.GroupLayout.Alignment.TRAILING)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addComponent(dropFavorites, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(bOpenEditFavDialog)) .addGroup(layout.createSequentialGroup() .addComponent(tfStreamUrl, javax.swing.GroupLayout.DEFAULT_SIZE, 311, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(bBrowseTwitch))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(labelQuality)) .addComponent(rbWatch)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(tfQuality) .addComponent(dropQuality, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(bSetSelectedQualityAsDefault, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(bGo, javax.swing.GroupLayout.DEFAULT_SIZE, 70, Short.MAX_VALUE) .addComponent(bStop, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(bSetSelectedQualityAsDefault, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(rbWatch) .addComponent(bGo, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(dropFavorites, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(cbFavorites) .addComponent(bOpenEditFavDialog) .addComponent(dropQuality, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(labelStreamUrl) .addComponent(tfStreamUrl, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(tfQuality, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(labelQuality) .addComponent(bBrowseTwitch)) .addGap(18, 18, 18)) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(bStop, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(rbRecord) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(labelFile) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(bFile) .addComponent(tfFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(26, 26, 26) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(labelOutput) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents ArrayList<String> favoritesList = new ArrayList<String>(); private void toggleRec(){ if (rbWatch.isEnabled()){ rbWatch.setEnabled(false); rbRecord.setEnabled(false); if (!cbFavorites.isSelected()) tfStreamUrl.setEnabled(false); else { dropFavorites.setEnabled(false); bOpenEditFavDialog.setEnabled(false); } tfQuality.setEnabled(false); bFile.setEnabled(false); tfFile.setEnabled(false); cbFavorites.setEnabled(false); bBrowseTwitch.setEnabled(false); bSetSelectedQualityAsDefault.setEnabled(false); dropQuality.setEnabled(false); } else{ rbWatch.setEnabled(true); rbRecord.setEnabled(true); if (!cbFavorites.isSelected()) tfStreamUrl.setEnabled(true); else { dropFavorites.setEnabled(true); bOpenEditFavDialog.setEnabled(true); } tfQuality.setEnabled(true); bFile.setEnabled(true); tfFile.setEnabled(true); cbFavorites.setEnabled(true); bBrowseTwitch.setEnabled(true); bSetSelectedQualityAsDefault.setEnabled(true); dropQuality.setEnabled(true); } } private void toggleWatch(){ if (rbRecord.isEnabled()){ rbWatch.setEnabled(false); rbRecord.setEnabled(false); if (!cbFavorites.isSelected()) tfStreamUrl.setEnabled(false); else { dropFavorites.setEnabled(false); bOpenEditFavDialog.setEnabled(false); } tfQuality.setEnabled(false); bFile.setEnabled(false); tfFile.setEnabled(false); cbFavorites.setEnabled(false); bBrowseTwitch.setEnabled(false); bSetSelectedQualityAsDefault.setEnabled(false); dropQuality.setEnabled(false); } else{ rbWatch.setEnabled(true); rbRecord.setEnabled(true); if (!cbFavorites.isSelected()) tfStreamUrl.setEnabled(true); else { dropFavorites.setEnabled(true); bOpenEditFavDialog.setEnabled(true); } tfQuality.setEnabled(true); cbFavorites.setEnabled(true); bBrowseTwitch.setEnabled(true); bSetSelectedQualityAsDefault.setEnabled(true); dropQuality.setEnabled(true); } } private String addFileExtIfNecessary(String file,String ext) { if(file.lastIndexOf('.') == -1) { file = ext; return file; } return ""; } private boolean filterCheck = false; private String fileName = "no"; private void bFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bFileActionPerformed if (!filterCheck) { FileFilter ft = new FileNameExtensionFilter("Transport Streams (*.ts)", "ts"); fd.setAcceptAllFileFilterUsed(false); fd.addChoosableFileFilter( ft ); filterCheck = true; } int returnVal = fd.showOpenDialog( this ); String fileExt = ".ts"; if (returnVal == javax.swing.JFileChooser.APPROVE_OPTION) { String extCheck = fd.getSelectedFile().getPath() + addFileExtIfNecessary(fd.getSelectedFile().getName(),fileExt); tfFile.setText(extCheck); fileName = tfFile.getText(); } }//GEN-LAST:event_bFileActionPerformed private void rbRecordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbRecordActionPerformed bFile.setEnabled(true); tfFile.setEnabled(true); tfFile.setEnabled(true); labelFile.setEnabled(true); }//GEN-LAST:event_rbRecordActionPerformed private void rbWatchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbWatchActionPerformed fileName = "no"; tfFile.setText(""); bFile.setEnabled(false); tfFile.setEnabled(false); labelFile.setEnabled(false); }//GEN-LAST:event_rbWatchActionPerformed LivestreamerExe le = new LivestreamerExe(); private void bGoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bGoActionPerformed bGo.setEnabled(false); taOutput.setText(""); if (rbWatch.isSelected()) { if (cbFavorites.isSelected()) { String[] cl = { "livestreamer", dropFavorites.getSelectedItem().toString(), tfQuality.getText()}; le.runLivestreamer(cl, taOutput); } else { String[] cl = { "livestreamer", tfStreamUrl.getText(), tfQuality.getText()}; le.runLivestreamer(cl, taOutput); } bStop.setEnabled(true); toggleWatch(); new Thread() { public void run() { try{ le.getProc().waitFor(); } catch (Exception err){ } bGo.setEnabled(true); bStop.setEnabled(false); toggleWatch(); } }.start(); le.nullProc(); } if (rbRecord.isSelected() && !"no".equals(fileName)) { if (cbFavorites.isSelected()) { String[] cl = { "livestreamer", dropFavorites.getSelectedItem().toString(), tfQuality.getText(), "-o", fileName}; le.runLivestreamer(cl, taOutput); } else { String[] cl = { "livestreamer", tfStreamUrl.getText(), tfQuality.getText(), "-o", fileName}; le.runLivestreamer(cl, taOutput); } bStop.setEnabled(true); toggleRec(); new Thread() { public void run() { try{ le.getProc().waitFor(); } catch (Exception err){ } bGo.setEnabled(true); bStop.setEnabled(false); toggleRec(); } }.start(); le.nullProc(); } if (rbRecord.isSelected() && "no".equals(fileName)) { JOptionPane.showMessageDialog(this,"Please choose a filename"); bGo.setEnabled(true); bStop.setEnabled(false); } }//GEN-LAST:event_bGoActionPerformed public JTextArea getTaOutput() { return taOutput; } private void bStopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bStopActionPerformed le.killLivestreamer(); bGo.setEnabled(true); bStop.setEnabled(false); }//GEN-LAST:event_bStopActionPerformed private void cbFavoritesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbFavoritesActionPerformed favoritesList.clear(); dropFavorites.removeAllItems(); if (dropFavorites.isEnabled()) { dropFavorites.setEnabled(false); tfStreamUrl.setEnabled(true); bOpenEditFavDialog.setEnabled(false); setBrowseTwitchButtonEnabled(true); } else { refreshFavoriteList(); dropFavorites.setEnabled(true); bOpenEditFavDialog.setEnabled(true); tfStreamUrl.setEnabled(false); setBrowseTwitchButtonEnabled(false); } }//GEN-LAST:event_cbFavoritesActionPerformed private void bOpenEditFavDialogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bOpenEditFavDialogActionPerformed AddFavoriteDialog.main(null); this.setEditDialogButtonEnabled(false); }//GEN-LAST:event_bOpenEditFavDialogActionPerformed private void bBrowseTwitchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bBrowseTwitchActionPerformed TwitchPicker.main(null); this.setBrowseTwitchButtonEnabled(false); }//GEN-LAST:event_bBrowseTwitchActionPerformed private void dropQualityActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dropQualityActionPerformed Quality q = ((DefaultComboBoxModel<Quality>)dropQuality.getModel()).getElementAt(dropQuality.getSelectedIndex()); this.tfQuality.setText(q.toString()); }//GEN-LAST:event_dropQualityActionPerformed private void bSetSelectedQualityAsDefaultActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bSetSelectedQualityAsDefaultActionPerformed PreferenceHandler.getInstance().set(DEFAULT_QUALITY_SETTING, dropQuality.getSelectedItem().toString()); }//GEN-LAST:event_bSetSelectedQualityAsDefaultActionPerformed public void setEditDialogButtonEnabled(boolean b) { bOpenEditFavDialog.setEnabled(b); } public void setBrowseTwitchButtonEnabled(boolean b) { bBrowseTwitch.setEnabled(b); } public void refreshFavoriteList() { favoritesList.clear(); dropFavorites.removeAllItems(); try { BufferedReader br = new BufferedReader(new FileReader("favorites.txt")); while (br.ready()) { favoritesList.add(br.readLine()); } br.close(); } catch (FileNotFoundException ex) { Logger.getLogger(LivestreamerJGUI.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(LivestreamerJGUI.class.getName()).log(Level.SEVERE, null, ex); } for (int x = 0; x < favoritesList.size(); x++) { dropFavorites.insertItemAt(favoritesList.get(x), x); } } public void setURLFieldText(String url) { this.tfStreamUrl.setText(url); } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch (UnsupportedLookAndFeelException | ClassNotFoundException | InstantiationException | IllegalAccessException e) { } instance = new LivestreamerJGUI(); instance.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton bBrowseTwitch; private javax.swing.JButton bFile; private javax.swing.JButton bGo; private javax.swing.JButton bOpenEditFavDialog; private javax.swing.JButton bSetSelectedQualityAsDefault; private javax.swing.JButton bStop; private javax.swing.JCheckBox cbFavorites; private javax.swing.JComboBox<String> dropFavorites; private javax.swing.JComboBox dropQuality; private javax.swing.JFileChooser fd; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JLabel labelFile; private javax.swing.JLabel labelOutput; private javax.swing.JLabel labelQuality; private javax.swing.JLabel labelStreamUrl; private javax.swing.JRadioButton rbRecord; private javax.swing.JRadioButton rbWatch; private javax.swing.ButtonGroup selectGroup; private javax.swing.JTextArea taOutput; private javax.swing.JTextField tfFile; private javax.swing.JTextField tfQuality; private javax.swing.JTextField tfStreamUrl; // End of variables declaration//GEN-END:variables }
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.util; import static com.google.common.base.Preconditions.checkState; import org.spongepowered.despector.ast.generic.ClassSignature; import org.spongepowered.despector.ast.generic.ClassTypeSignature; import org.spongepowered.despector.ast.generic.GenericClassTypeSignature; import org.spongepowered.despector.ast.generic.MethodSignature; import org.spongepowered.despector.ast.generic.TypeArgument; import org.spongepowered.despector.ast.generic.TypeParameter; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.generic.TypeVariableSignature; import org.spongepowered.despector.ast.generic.VoidTypeSignature; import org.spongepowered.despector.ast.generic.WildcardType; import java.util.List; /** * A parser for various generic signatures. */ public final class SignatureParser { private static final String VALID_PRIM = "BSIJFDCZ"; /** * Parses the given class signature. */ public static ClassSignature parse(String signature) { Parser parser = new Parser(signature); ClassSignature struct = new ClassSignature(); if (signature.startsWith("<")) { parser.skip(1); parseFormalTypeParameters(parser, struct.getParameters()); } GenericClassTypeSignature superclass = parseClassTypeSignature(parser, ""); struct.setSuperclassSignature(superclass); while (parser.hasNext()) { GenericClassTypeSignature sig = parseClassTypeSignature(parser, ""); struct.getInterfaceSignatures().add(sig); } return struct; } /** * Parses the given method signature. */ public static MethodSignature parseMethod(String signature) { Parser parser = new Parser(signature); MethodSignature sig = new MethodSignature(); if (parser.check('<')) { parseFormalTypeParameters(parser, sig.getTypeParameters()); } parser.expect('('); while (!parser.check(')')) { sig.getParameters().add(parseTypeSignature(parser)); } if (parser.check('V')) { sig.setReturnType(VoidTypeSignature.VOID); } else { sig.setReturnType(parseTypeSignature(parser)); } // TODO throws signature return sig; } private static void parseFormalTypeParameters(Parser parser, List<TypeParameter> type_params) { while (parser.peek() != '>') { String identifier = parser.nextIdentifier(); parser.expect(':'); TypeSignature class_bound = null; if (parser.peek() != ':') { class_bound = parseFieldTypeSignature(parser); } TypeParameter param = new TypeParameter(identifier, class_bound); type_params.add(param); while (parser.peek() == ':') { parser.skip(1); param.getInterfaceBounds().add(parseFieldTypeSignature(parser)); } } parser.skip(1); } public static TypeSignature parseFieldTypeSignature(String sig) { Parser parser = new Parser(sig); return parseFieldTypeSignature(parser); } private static TypeSignature parseTypeSignature(Parser parser) { char next = parser.peek(); if (VALID_PRIM.indexOf(next) != -1) { parser.skip(1); return ClassTypeSignature.of(String.valueOf(next)); } return parseFieldTypeSignature(parser); } private static TypeSignature parseFieldTypeSignature(Parser parser) { StringBuilder ident = new StringBuilder(); while (parser.check('[')) { ident.append('['); } char next = parser.peek(); if (ident.length() > 0) { if (VALID_PRIM.indexOf(next) != -1) { ident.append(next); parser.skip(1); return ClassTypeSignature.of(ident.toString()); } } if (next == 'T') { parser.skip(1); ident.append('T'); ident.append(parser.nextIdentifier()); ident.append(';'); TypeVariableSignature sig = new TypeVariableSignature(ident.toString()); parser.expect(';'); return sig; } checkState(next == 'L'); return parseClassTypeSignature(parser, ident.toString()); } public static GenericClassTypeSignature parseClassTypeSignature(String sig) { Parser parser = new Parser(sig); return parseClassTypeSignature(parser, ""); } private static GenericClassTypeSignature parseClassTypeSignature(Parser parser, String prefix) { StringBuilder ident = new StringBuilder(prefix); parser.expect('L'); ident.append("L"); ident.append(parser.nextIdentifier()); while (parser.check('/')) { ident.append('/'); ident.append(parser.nextIdentifier()); } ident.append(";"); GenericClassTypeSignature sig = new GenericClassTypeSignature(ident.toString()); if (parser.check('<')) { while (!parser.check('>')) { char wild = parser.peek(); WildcardType wildcard = null; if (wild == '*') { sig.getArguments().add(new TypeArgument(WildcardType.STAR, null)); parser.skip(1); continue; } else if (wild == '+') { parser.skip(1); wildcard = WildcardType.EXTENDS; } else if (wild == '-') { parser.skip(1); wildcard = WildcardType.SUPER; } else { wildcard = WildcardType.NONE; } sig.getArguments().add(new TypeArgument(wildcard, parseFieldTypeSignature(parser))); } } while (parser.peek() == '.') { parser.pop(); StringBuilder child = new StringBuilder(); child.append("L"); child.append(parser.nextIdentifier()); while (parser.check('/')) { child.append('/'); child.append(parser.nextIdentifier()); } child.append(";"); sig = new GenericClassTypeSignature(sig, child.toString()); if (parser.check('<')) { while (!parser.check('>')) { char wild = parser.peek(); WildcardType wildcard = null; if (wild == '*') { sig.getArguments().add(new TypeArgument(WildcardType.STAR, null)); parser.skip(1); continue; } else if (wild == '+') { parser.skip(1); wildcard = WildcardType.EXTENDS; } else if (wild == '-') { parser.skip(1); wildcard = WildcardType.SUPER; } else { wildcard = WildcardType.NONE; } sig.getArguments().add(new TypeArgument(wildcard, parseFieldTypeSignature(parser))); } } } parser.expect(';'); return sig; } /** * A helper for parsing. */ private static class Parser { private int index; private String buffer; public Parser(String data) { this.buffer = data; this.index = 0; } public boolean hasNext() { return this.index < this.buffer.length(); } public void skip(int n) { this.index += n; } public char peek() { return this.buffer.charAt(this.index); } public char pop() { return this.buffer.charAt(this.index++); } public boolean check(char n) { if (peek() == n) { this.index++; return true; } return false; } public void expect(char n) { if (peek() != n) { throw new IllegalStateException("Expected '" + n + "' at char " + this.index + " in \"" + this.buffer + "\""); } this.index++; } public String nextIdentifier() { StringBuilder ident = new StringBuilder(); int start = this.index; for (; this.index < this.buffer.length(); this.index++) { char next = this.buffer.charAt(this.index); if (Character.isAlphabetic(next) || next == '_' || next == '$' || (this.index > start && next >= '0' && next <= '9')) { ident.append(next); } else { break; } } if (ident.length() == 0) { throw new IllegalStateException("Expected identifier at char " + this.index + " in \"" + this.buffer + "\""); } return ident.toString(); } } private SignatureParser() { } }
/** * Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.analytics.math.interpolation; import static com.opengamma.analytics.math.matrix.MatrixAlgebraFactory.OG_ALGEBRA; import java.util.Arrays; import com.opengamma.analytics.math.linearalgebra.Decomposition; import com.opengamma.analytics.math.linearalgebra.LUDecompositionCommons; import com.opengamma.analytics.math.linearalgebra.LUDecompositionResult; import com.opengamma.analytics.math.matrix.DoubleMatrix1D; import com.opengamma.analytics.math.matrix.DoubleMatrix2D; /** * Abstract class of solving cubic spline problem. Implementation depends on endpoint conditions "solve" for 1-dimensional problem and "solveMultiDim" for * multi-dimensional problem should be implemented in inherited classes "getKnotsMat1D" is overridden in certain cases */ abstract class CubicSplineSolver { private final Decomposition<LUDecompositionResult> _luObj = new LUDecompositionCommons(); /** * One-dimensional cubic spline. If (xValues length) = (yValues length), Not-A-Knot endpoint conditions are used If (xValues length) + 2 = (yValues length), * Clamped endpoint conditions are used * * @param xValues * X values of data * @param yValues * Y values of data * @return Coefficient matrix whose i-th row vector is (a_0,a_1,...) for i-th intervals, where a_0,a_1,... are coefficients of f(x) = a_0 + a_1 x^1 + .... * Note that the degree of polynomial is NOT necessarily 3 */ public abstract DoubleMatrix2D solve(double[] xValues, double[] yValues); /** * One-dimensional cubic spline. If (xValues length) = (yValues length), Not-A-Knot endpoint conditions are used If (xValues length) + 2 = (yValues length), * Clamped endpoint conditions are used * * @param xValues * X values of data * @param yValues * Y values of data * @return Array of matrices: the 0-th element is Coefficient Matrix (same as the solve method above), the i-th element is \frac{\partial a^{i-1}_j}{\partial * yValues_k} where a_0^i,a_1^i,... are coefficients of f^i(x) = a_0^i + a_1^i (x - xValues_{i}) + .... with x \in [xValues_{i}, xValues_{i+1}] */ public abstract DoubleMatrix2D[] solveWithSensitivity(double[] xValues, double[] yValues); /** * Multi-dimensional cubic spline. If (xValues length) = (yValuesMatrix NumberOfColumn), Not-A-Knot endpoint conditions are used If (xValues length) + 2 = * (yValuesMatrix NumberOfColumn), Clamped endpoint conditions are used * * @param xValues * X values of data * @param yValuesMatrix * Y values of data, where NumberOfRow defines dimension of the spline * @return A set of coefficient matrices whose i-th row vector is (a_0,a_1,...) for the i-th interval, where a_0,a_1,... are coefficients of f(x) = a_0 + a_1 * x^1 + .... Each matrix corresponds to an interpolation (xValues, yValuesMatrix RowVector) Note that the degree of polynomial is NOT necessarily 3 */ public abstract DoubleMatrix2D[] solveMultiDim(double[] xValues, DoubleMatrix2D yValuesMatrix); /** * @param xValues * X values of data * @return X values of knots (Note that these are NOT necessarily xValues if nDataPts=2,3) */ public DoubleMatrix1D getKnotsMat1D(final double[] xValues) { return new DoubleMatrix1D(xValues); } /** * @param xValues * X values of Data * @return {xValues[1]-xValues[0], xValues[2]-xValues[1],...} xValues (and corresponding yValues) should be sorted before calling this method */ protected double[] getDiffs(final double[] xValues) { final int nDataPts = xValues.length; final double[] res = new double[nDataPts - 1]; for (int i = 0; i < nDataPts - 1; ++i) { res[i] = xValues[i + 1] - xValues[i]; } return res; } /** * @param xValues * X values of Data * @param yValues * Y values of Data * @param intervals * {xValues[1]-xValues[0], xValues[2]-xValues[1],...} * @param solnVector * Values of second derivative at knots * @return Coefficient matrix whose i-th row vector is {a_0,a_1,...} for i-th intervals, where a_0,a_1,... are coefficients of f(x) = a_0 + a_1 x^1 + .... */ protected DoubleMatrix2D getCommonSplineCoeffs(final double[] xValues, final double[] yValues, final double[] intervals, final double[] solnVector) { final int nDataPts = xValues.length; final double[][] res = new double[nDataPts - 1][4]; for (int i = 0; i < nDataPts - 1; ++i) { res[i][0] = solnVector[i + 1] / 6. / intervals[i] - solnVector[i] / 6. / intervals[i]; res[i][1] = 0.5 * solnVector[i]; res[i][2] = yValues[i + 1] / intervals[i] - yValues[i] / intervals[i] - intervals[i] * solnVector[i] / 2. - intervals[i] * solnVector[i + 1] / 6. + intervals[i] * solnVector[i] / 6.; res[i][3] = yValues[i]; } return new DoubleMatrix2D(res); } /** * @param intervals * {xValues[1]-xValues[0], xValues[2]-xValues[1],...} * @param solnMatrix * Sensitivity of second derivatives (x 0.5) * @return Array of i coefficient matrices \frac{\partial a^i_j}{\partial y_k} */ protected DoubleMatrix2D[] getCommonSensitivityCoeffs(final double[] intervals, final double[][] solnMatrix) { final int nDataPts = intervals.length + 1; final double[][][] res = new double[nDataPts - 1][4][nDataPts]; for (int i = 0; i < nDataPts - 1; ++i) { res[i][3][i] = 1.; res[i][2][i + 1] = 1. / intervals[i]; res[i][2][i] = -1. / intervals[i]; for (int k = 0; k < nDataPts; ++k) { res[i][0][k] = solnMatrix[i + 1][k] / 6. / intervals[i] - solnMatrix[i][k] / 6. / intervals[i]; res[i][1][k] = 0.5 * solnMatrix[i][k]; res[i][2][k] += -intervals[i] * solnMatrix[i][k] / 2. - intervals[i] * solnMatrix[i + 1][k] / 6. + intervals[i] * solnMatrix[i][k] / 6.; } } final DoubleMatrix2D[] resMat = new DoubleMatrix2D[nDataPts - 1]; for (int i = 0; i < nDataPts - 1; ++i) { resMat[i] = new DoubleMatrix2D(res[i]); } return resMat; } /** * Cubic spline and its node sensitivity are respectively obtained by solving a linear problem Ax=b where A is a square matrix and x,b are vector and AN=L * where N,L are matrices. * * @param xValues * X values of data * @param yValues * Y values of data * @param intervals * {xValues[1]-xValues[0], xValues[2]-xValues[1],...} * @param toBeInv * The matrix A * @param commonVector * The vector b * @param commonVecSensitivity * The matrix L * @return Coefficient matrices of interpolant (x) and its node sensitivity (N) */ protected DoubleMatrix2D[] getCommonCoefficientWithSensitivity(final double[] xValues, final double[] yValues, final double[] intervals, final double[][] toBeInv, final double[] commonVector, final double[][] commonVecSensitivity) { final int nDataPts = xValues.length; final DoubleMatrix1D[] soln = this.combinedMatrixEqnSolver(toBeInv, commonVector, commonVecSensitivity); final DoubleMatrix2D[] res = new DoubleMatrix2D[nDataPts]; res[0] = getCommonSplineCoeffs(xValues, yValues, intervals, soln[0].getData()); final double[][] solnMatrix = new double[nDataPts][nDataPts]; for (int i = 0; i < nDataPts; ++i) { for (int j = 0; j < nDataPts; ++j) { solnMatrix[i][j] = soln[j + 1].getData()[i]; } } final DoubleMatrix2D[] tmp = getCommonSensitivityCoeffs(intervals, solnMatrix); System.arraycopy(tmp, 0, res, 1, nDataPts - 1); return res; } /** * Cubic spline is obtained by solving a linear problem Ax=b where A is a square matrix and x,b are vector. * * @param intervals * the intervals * @return Endpoint-independent part of the matrix A */ protected double[][] getCommonMatrixElements(final double[] intervals) { final int nDataPts = intervals.length + 1; final double[][] res = new double[nDataPts][nDataPts]; for (int i = 0; i < nDataPts; ++i) { Arrays.fill(res[i], 0.); } for (int i = 1; i < nDataPts - 1; ++i) { res[i][i - 1] = intervals[i - 1]; res[i][i] = 2. * (intervals[i - 1] + intervals[i]); res[i][i + 1] = intervals[i]; } return res; } /** * Cubic spline is obtained by solving a linear problem Ax=b where A is a square matrix and x,b are vector. * * @param yValues * Y values of Data * @param intervals * {xValues[1]-xValues[0], xValues[2]-xValues[1],...} * @return Endpoint-independent part of vector b */ protected double[] getCommonVectorElements(final double[] yValues, final double[] intervals) { final int nDataPts = yValues.length; final double[] res = new double[nDataPts]; Arrays.fill(res, 0.); for (int i = 1; i < nDataPts - 1; ++i) { res[i] = 6. * yValues[i + 1] / intervals[i] - 6. * yValues[i] / intervals[i] - 6. * yValues[i] / intervals[i - 1] + 6. * yValues[i - 1] / intervals[i - 1]; } return res; } /** * Node sensitivity is obtained by solving a linear problem AN = L where A,N,L are matrices. * * @param intervals * {xValues[1]-xValues[0], xValues[2]-xValues[1],...} * @return The matrix L */ protected double[][] getCommonVectorSensitivity(final double[] intervals) { final int nDataPts = intervals.length + 1; final double[][] res = new double[nDataPts][nDataPts]; for (int i = 0; i < nDataPts; ++i) { Arrays.fill(res[i], 0.); } for (int i = 1; i < nDataPts - 1; ++i) { res[i][i - 1] = 6. / intervals[i - 1]; res[i][i] = -6. / intervals[i] - 6. / intervals[i - 1]; res[i][i + 1] = 6. / intervals[i]; } return res; } /** * Cubic spline is obtained by solving a linear problem Ax=b where A is a square matrix and x,b are vector This can be done by LU decomposition. * * @param doubMat * Matrix A * @param doubVec * Vector B * @return Solution to the linear equation, x */ protected double[] matrixEqnSolver(final double[][] doubMat, final double[] doubVec) { final LUDecompositionResult result = _luObj.evaluate(new DoubleMatrix2D(doubMat)); final double[][] lMat = result.getL().getData(); final double[][] uMat = result.getU().getData(); final double[] doubVecMod = ((DoubleMatrix1D) OG_ALGEBRA.multiply(result.getP(), new DoubleMatrix1D(doubVec))).getData(); return backSubstitution(uMat, forwardSubstitution(lMat, doubVecMod)); } /** * Cubic spline and its node sensitivity are respectively obtained by solving a linear problem Ax=b where A is a square matrix and x,b are vector and AN=L * where N,L are matrices. * * @param doubMat1 * The matrix A * @param doubVec * The vector b * @param doubMat2 * The matrix L * @return The solutions to the linear systems, x,N */ protected DoubleMatrix1D[] combinedMatrixEqnSolver(final double[][] doubMat1, final double[] doubVec, final double[][] doubMat2) { final int nDataPts = doubVec.length; final LUDecompositionResult result = _luObj.evaluate(new DoubleMatrix2D(doubMat1)); final double[][] lMat = result.getL().getData(); final double[][] uMat = result.getU().getData(); final DoubleMatrix2D pMat = result.getP(); final double[] doubVecMod = ((DoubleMatrix1D) OG_ALGEBRA.multiply(pMat, new DoubleMatrix1D(doubVec))).getData(); final DoubleMatrix2D doubMat2Matrix = new DoubleMatrix2D(doubMat2); final DoubleMatrix1D[] res = new DoubleMatrix1D[nDataPts + 1]; res[0] = new DoubleMatrix1D(backSubstitution(uMat, forwardSubstitution(lMat, doubVecMod))); for (int i = 0; i < nDataPts; ++i) { final double[] doubMat2Colum = doubMat2Matrix.getColumnVector(i).getData(); final double[] doubVecMod2 = ((DoubleMatrix1D) OG_ALGEBRA.multiply(pMat, new DoubleMatrix1D(doubMat2Colum))).getData(); res[i + 1] = new DoubleMatrix1D(backSubstitution(uMat, forwardSubstitution(lMat, doubVecMod2))); } return res; } /** * Linear problem Ax=b is solved by forward substitution if A is lower triangular * * @param lMat * Lower triangular matrix * @param doubVec * Vector b * @return Solution to the linear equation, x */ private double[] forwardSubstitution(final double[][] lMat, final double[] doubVec) { final int size = lMat.length; final double[] res = new double[size]; for (int i = 0; i < size; ++i) { double tmp = doubVec[i] / lMat[i][i]; for (int j = 0; j < i; ++j) { tmp -= lMat[i][j] * res[j] / lMat[i][i]; } res[i] = tmp; } return res; } /** * Linear problem Ax=b is solved by backward substitution if A is upper triangular * * @param uMat * Upper triangular matrix * @param doubVec * Vector b * @return Solution to the linear equation, x */ private double[] backSubstitution(final double[][] uMat, final double[] doubVec) { final int size = uMat.length; final double[] res = new double[size]; for (int i = size - 1; i > -1; --i) { double tmp = doubVec[i] / uMat[i][i]; for (int j = i + 1; j < size; ++j) { tmp -= uMat[i][j] * res[j] / uMat[i][i]; } res[i] = tmp; } return res; } }
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.kinesisanalytics.model; import java.io.Serializable; import javax.annotation.Generated; /** * <p/> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/kinesisanalytics-2015-08-14/DiscoverInputSchema" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DiscoverInputSchemaResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * Schema inferred from the streaming source. It identifies the format of the data in the streaming source and how * each data element maps to corresponding columns in the in-application stream that you can create. * </p> */ private SourceSchema inputSchema; /** * <p> * An array of elements, where each element corresponds to a row in a stream record (a stream record can have more * than one row). * </p> */ private java.util.List<java.util.List<String>> parsedInputRecords; /** * <p> * Stream data that was modified by the processor specified in the <code>InputProcessingConfiguration</code> * parameter. * </p> */ private java.util.List<String> processedInputRecords; /** * <p> * Raw stream data that was sampled to infer the schema. * </p> */ private java.util.List<String> rawInputRecords; /** * <p> * Schema inferred from the streaming source. It identifies the format of the data in the streaming source and how * each data element maps to corresponding columns in the in-application stream that you can create. * </p> * * @param inputSchema * Schema inferred from the streaming source. It identifies the format of the data in the streaming source * and how each data element maps to corresponding columns in the in-application stream that you can create. */ public void setInputSchema(SourceSchema inputSchema) { this.inputSchema = inputSchema; } /** * <p> * Schema inferred from the streaming source. It identifies the format of the data in the streaming source and how * each data element maps to corresponding columns in the in-application stream that you can create. * </p> * * @return Schema inferred from the streaming source. It identifies the format of the data in the streaming source * and how each data element maps to corresponding columns in the in-application stream that you can create. */ public SourceSchema getInputSchema() { return this.inputSchema; } /** * <p> * Schema inferred from the streaming source. It identifies the format of the data in the streaming source and how * each data element maps to corresponding columns in the in-application stream that you can create. * </p> * * @param inputSchema * Schema inferred from the streaming source. It identifies the format of the data in the streaming source * and how each data element maps to corresponding columns in the in-application stream that you can create. * @return Returns a reference to this object so that method calls can be chained together. */ public DiscoverInputSchemaResult withInputSchema(SourceSchema inputSchema) { setInputSchema(inputSchema); return this; } /** * <p> * An array of elements, where each element corresponds to a row in a stream record (a stream record can have more * than one row). * </p> * * @return An array of elements, where each element corresponds to a row in a stream record (a stream record can * have more than one row). */ public java.util.List<java.util.List<String>> getParsedInputRecords() { return parsedInputRecords; } /** * <p> * An array of elements, where each element corresponds to a row in a stream record (a stream record can have more * than one row). * </p> * * @param parsedInputRecords * An array of elements, where each element corresponds to a row in a stream record (a stream record can have * more than one row). */ public void setParsedInputRecords(java.util.Collection<java.util.List<String>> parsedInputRecords) { if (parsedInputRecords == null) { this.parsedInputRecords = null; return; } this.parsedInputRecords = new java.util.ArrayList<java.util.List<String>>(parsedInputRecords); } /** * <p> * An array of elements, where each element corresponds to a row in a stream record (a stream record can have more * than one row). * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setParsedInputRecords(java.util.Collection)} or {@link #withParsedInputRecords(java.util.Collection)} if * you want to override the existing values. * </p> * * @param parsedInputRecords * An array of elements, where each element corresponds to a row in a stream record (a stream record can have * more than one row). * @return Returns a reference to this object so that method calls can be chained together. */ public DiscoverInputSchemaResult withParsedInputRecords(java.util.List<String>... parsedInputRecords) { if (this.parsedInputRecords == null) { setParsedInputRecords(new java.util.ArrayList<java.util.List<String>>(parsedInputRecords.length)); } for (java.util.List<String> ele : parsedInputRecords) { this.parsedInputRecords.add(ele); } return this; } /** * <p> * An array of elements, where each element corresponds to a row in a stream record (a stream record can have more * than one row). * </p> * * @param parsedInputRecords * An array of elements, where each element corresponds to a row in a stream record (a stream record can have * more than one row). * @return Returns a reference to this object so that method calls can be chained together. */ public DiscoverInputSchemaResult withParsedInputRecords(java.util.Collection<java.util.List<String>> parsedInputRecords) { setParsedInputRecords(parsedInputRecords); return this; } /** * <p> * Stream data that was modified by the processor specified in the <code>InputProcessingConfiguration</code> * parameter. * </p> * * @return Stream data that was modified by the processor specified in the <code>InputProcessingConfiguration</code> * parameter. */ public java.util.List<String> getProcessedInputRecords() { return processedInputRecords; } /** * <p> * Stream data that was modified by the processor specified in the <code>InputProcessingConfiguration</code> * parameter. * </p> * * @param processedInputRecords * Stream data that was modified by the processor specified in the <code>InputProcessingConfiguration</code> * parameter. */ public void setProcessedInputRecords(java.util.Collection<String> processedInputRecords) { if (processedInputRecords == null) { this.processedInputRecords = null; return; } this.processedInputRecords = new java.util.ArrayList<String>(processedInputRecords); } /** * <p> * Stream data that was modified by the processor specified in the <code>InputProcessingConfiguration</code> * parameter. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setProcessedInputRecords(java.util.Collection)} or * {@link #withProcessedInputRecords(java.util.Collection)} if you want to override the existing values. * </p> * * @param processedInputRecords * Stream data that was modified by the processor specified in the <code>InputProcessingConfiguration</code> * parameter. * @return Returns a reference to this object so that method calls can be chained together. */ public DiscoverInputSchemaResult withProcessedInputRecords(String... processedInputRecords) { if (this.processedInputRecords == null) { setProcessedInputRecords(new java.util.ArrayList<String>(processedInputRecords.length)); } for (String ele : processedInputRecords) { this.processedInputRecords.add(ele); } return this; } /** * <p> * Stream data that was modified by the processor specified in the <code>InputProcessingConfiguration</code> * parameter. * </p> * * @param processedInputRecords * Stream data that was modified by the processor specified in the <code>InputProcessingConfiguration</code> * parameter. * @return Returns a reference to this object so that method calls can be chained together. */ public DiscoverInputSchemaResult withProcessedInputRecords(java.util.Collection<String> processedInputRecords) { setProcessedInputRecords(processedInputRecords); return this; } /** * <p> * Raw stream data that was sampled to infer the schema. * </p> * * @return Raw stream data that was sampled to infer the schema. */ public java.util.List<String> getRawInputRecords() { return rawInputRecords; } /** * <p> * Raw stream data that was sampled to infer the schema. * </p> * * @param rawInputRecords * Raw stream data that was sampled to infer the schema. */ public void setRawInputRecords(java.util.Collection<String> rawInputRecords) { if (rawInputRecords == null) { this.rawInputRecords = null; return; } this.rawInputRecords = new java.util.ArrayList<String>(rawInputRecords); } /** * <p> * Raw stream data that was sampled to infer the schema. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setRawInputRecords(java.util.Collection)} or {@link #withRawInputRecords(java.util.Collection)} if you * want to override the existing values. * </p> * * @param rawInputRecords * Raw stream data that was sampled to infer the schema. * @return Returns a reference to this object so that method calls can be chained together. */ public DiscoverInputSchemaResult withRawInputRecords(String... rawInputRecords) { if (this.rawInputRecords == null) { setRawInputRecords(new java.util.ArrayList<String>(rawInputRecords.length)); } for (String ele : rawInputRecords) { this.rawInputRecords.add(ele); } return this; } /** * <p> * Raw stream data that was sampled to infer the schema. * </p> * * @param rawInputRecords * Raw stream data that was sampled to infer the schema. * @return Returns a reference to this object so that method calls can be chained together. */ public DiscoverInputSchemaResult withRawInputRecords(java.util.Collection<String> rawInputRecords) { setRawInputRecords(rawInputRecords); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getInputSchema() != null) sb.append("InputSchema: ").append(getInputSchema()).append(","); if (getParsedInputRecords() != null) sb.append("ParsedInputRecords: ").append(getParsedInputRecords()).append(","); if (getProcessedInputRecords() != null) sb.append("ProcessedInputRecords: ").append(getProcessedInputRecords()).append(","); if (getRawInputRecords() != null) sb.append("RawInputRecords: ").append(getRawInputRecords()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DiscoverInputSchemaResult == false) return false; DiscoverInputSchemaResult other = (DiscoverInputSchemaResult) obj; if (other.getInputSchema() == null ^ this.getInputSchema() == null) return false; if (other.getInputSchema() != null && other.getInputSchema().equals(this.getInputSchema()) == false) return false; if (other.getParsedInputRecords() == null ^ this.getParsedInputRecords() == null) return false; if (other.getParsedInputRecords() != null && other.getParsedInputRecords().equals(this.getParsedInputRecords()) == false) return false; if (other.getProcessedInputRecords() == null ^ this.getProcessedInputRecords() == null) return false; if (other.getProcessedInputRecords() != null && other.getProcessedInputRecords().equals(this.getProcessedInputRecords()) == false) return false; if (other.getRawInputRecords() == null ^ this.getRawInputRecords() == null) return false; if (other.getRawInputRecords() != null && other.getRawInputRecords().equals(this.getRawInputRecords()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getInputSchema() == null) ? 0 : getInputSchema().hashCode()); hashCode = prime * hashCode + ((getParsedInputRecords() == null) ? 0 : getParsedInputRecords().hashCode()); hashCode = prime * hashCode + ((getProcessedInputRecords() == null) ? 0 : getProcessedInputRecords().hashCode()); hashCode = prime * hashCode + ((getRawInputRecords() == null) ? 0 : getRawInputRecords().hashCode()); return hashCode; } @Override public DiscoverInputSchemaResult clone() { try { return (DiscoverInputSchemaResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
/* * 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.cassandra.index.sasi; import java.util.*; import java.util.concurrent.Callable; import java.util.function.BiFunction; import com.googlecode.concurrenttrees.common.Iterables; import org.apache.cassandra.config.*; import org.apache.cassandra.cql3.Operator; import org.apache.cassandra.cql3.statements.IndexTarget; import org.apache.cassandra.db.*; import org.apache.cassandra.db.compaction.CompactionManager; import org.apache.cassandra.db.compaction.OperationType; import org.apache.cassandra.db.filter.RowFilter; import org.apache.cassandra.db.lifecycle.Tracker; import org.apache.cassandra.db.marshal.AbstractType; import org.apache.cassandra.db.partitions.PartitionIterator; import org.apache.cassandra.db.partitions.PartitionUpdate; import org.apache.cassandra.db.rows.Row; import org.apache.cassandra.dht.Murmur3Partitioner; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.exceptions.InvalidRequestException; import org.apache.cassandra.index.Index; import org.apache.cassandra.index.IndexRegistry; import org.apache.cassandra.index.SecondaryIndexBuilder; import org.apache.cassandra.index.TargetParser; import org.apache.cassandra.index.sasi.conf.ColumnIndex; import org.apache.cassandra.index.sasi.conf.IndexMode; import org.apache.cassandra.index.sasi.disk.OnDiskIndexBuilder.Mode; import org.apache.cassandra.index.sasi.disk.PerSSTableIndexWriter; import org.apache.cassandra.index.sasi.plan.QueryPlan; import org.apache.cassandra.index.transactions.IndexTransaction; import org.apache.cassandra.io.sstable.Descriptor; import org.apache.cassandra.io.sstable.format.SSTableFlushObserver; import org.apache.cassandra.io.sstable.format.SSTableReader; import org.apache.cassandra.notifications.*; import org.apache.cassandra.schema.IndexMetadata; import org.apache.cassandra.utils.FBUtilities; import org.apache.cassandra.utils.Pair; import org.apache.cassandra.utils.concurrent.OpOrder; public class SASIIndex implements Index, INotificationConsumer { private static class SASIIndexBuildingSupport implements IndexBuildingSupport { public SecondaryIndexBuilder getIndexBuildTask(ColumnFamilyStore cfs, Set<Index> indexes, Collection<SSTableReader> sstablesToRebuild) { NavigableMap<SSTableReader, Map<ColumnDefinition, ColumnIndex>> sstables = new TreeMap<>((a, b) -> { return Integer.compare(a.descriptor.generation, b.descriptor.generation); }); indexes.stream() .filter((i) -> i instanceof SASIIndex) .forEach((i) -> { SASIIndex sasi = (SASIIndex) i; sstablesToRebuild.stream() .filter((sstable) -> !sasi.index.hasSSTable(sstable)) .forEach((sstable) -> { Map<ColumnDefinition, ColumnIndex> toBuild = sstables.get(sstable); if (toBuild == null) sstables.put(sstable, (toBuild = new HashMap<>())); toBuild.put(sasi.index.getDefinition(), sasi.index); }); }); return new SASIIndexBuilder(cfs, sstables); } } private static final SASIIndexBuildingSupport INDEX_BUILDER_SUPPORT = new SASIIndexBuildingSupport(); private final ColumnFamilyStore baseCfs; private final IndexMetadata config; private final ColumnIndex index; public SASIIndex(ColumnFamilyStore baseCfs, IndexMetadata config) { this.baseCfs = baseCfs; this.config = config; ColumnDefinition column = TargetParser.parse(baseCfs.metadata, config).left; this.index = new ColumnIndex(baseCfs.metadata.getKeyValidator(), column, config); Tracker tracker = baseCfs.getTracker(); tracker.subscribe(this); SortedMap<SSTableReader, Map<ColumnDefinition, ColumnIndex>> toRebuild = new TreeMap<>((a, b) -> Integer.compare(a.descriptor.generation, b.descriptor.generation)); for (SSTableReader sstable : index.init(tracker.getView().liveSSTables())) { Map<ColumnDefinition, ColumnIndex> perSSTable = toRebuild.get(sstable); if (perSSTable == null) toRebuild.put(sstable, (perSSTable = new HashMap<>())); perSSTable.put(index.getDefinition(), index); } CompactionManager.instance.submitIndexBuild(new SASIIndexBuilder(baseCfs, toRebuild)); } public static Map<String, String> validateOptions(Map<String, String> options, CFMetaData cfm) { if (!(cfm.partitioner instanceof Murmur3Partitioner)) throw new ConfigurationException("SASI only supports Murmur3Partitioner."); String targetColumn = options.get("target"); if (targetColumn == null) throw new ConfigurationException("unknown target column"); Pair<ColumnDefinition, IndexTarget.Type> target = TargetParser.parse(cfm, targetColumn); if (target == null) throw new ConfigurationException("failed to retrieve target column for: " + targetColumn); if (target.left.isComplex()) throw new ConfigurationException("complex columns are not yet supported by SASI"); IndexMode.validateAnalyzer(options); IndexMode mode = IndexMode.getMode(target.left, options); if (mode.mode == Mode.SPARSE) { if (mode.isLiteral) throw new ConfigurationException("SPARSE mode is only supported on non-literal columns."); if (mode.isAnalyzed) throw new ConfigurationException("SPARSE mode doesn't support analyzers."); } return Collections.emptyMap(); } public void register(IndexRegistry registry) { registry.registerIndex(this); } public IndexMetadata getIndexMetadata() { return config; } public Callable<?> getInitializationTask() { return null; } public Callable<?> getMetadataReloadTask(IndexMetadata indexMetadata) { return null; } public Callable<?> getBlockingFlushTask() { return null; // SASI indexes are flushed along side memtable } public Callable<?> getInvalidateTask() { return getTruncateTask(FBUtilities.timestampMicros()); } public Callable<?> getTruncateTask(long truncatedAt) { return () -> { index.dropData(truncatedAt); return null; }; } public boolean shouldBuildBlocking() { return true; } public Optional<ColumnFamilyStore> getBackingTable() { return Optional.empty(); } public boolean indexes(PartitionColumns columns) { return columns.contains(index.getDefinition()); } public boolean dependsOn(ColumnDefinition column) { return index.getDefinition().compareTo(column) == 0; } public boolean supportsExpression(ColumnDefinition column, Operator operator) { return dependsOn(column) && index.supports(operator); } public AbstractType<?> customExpressionValueType() { return null; } public RowFilter getPostIndexQueryFilter(RowFilter filter) { return filter.withoutExpressions(); } public long getEstimatedResultRows() { // this is temporary (until proper QueryPlan is integrated into Cassandra) // and allows us to priority SASI indexes if any in the query since they // are going to be more efficient, to query and intersect, than built-in indexes. return Long.MIN_VALUE; } public void validate(PartitionUpdate update) throws InvalidRequestException {} public Indexer indexerFor(DecoratedKey key, PartitionColumns columns, int nowInSec, OpOrder.Group opGroup, IndexTransaction.Type transactionType) { return new Indexer() { public void begin() {} public void partitionDelete(DeletionTime deletionTime) {} public void rangeTombstone(RangeTombstone tombstone) {} public void insertRow(Row row) { if (isNewData()) adjustMemtableSize(index.index(key, row), opGroup); } public void updateRow(Row oldRow, Row newRow) { insertRow(newRow); } public void removeRow(Row row) {} public void finish() {} // we are only interested in the data from Memtable // everything else is going to be handled by SSTableWriter observers private boolean isNewData() { return transactionType == IndexTransaction.Type.UPDATE; } public void adjustMemtableSize(long additionalSpace, OpOrder.Group opGroup) { baseCfs.getTracker().getView().getCurrentMemtable().getAllocator().onHeap().allocate(additionalSpace, opGroup); } }; } public Searcher searcherFor(ReadCommand command) throws InvalidRequestException { CFMetaData config = command.metadata(); ColumnFamilyStore cfs = Schema.instance.getColumnFamilyStoreInstance(config.cfId); return controller -> new QueryPlan(cfs, command, DatabaseDescriptor.getRangeRpcTimeout()).execute(controller); } public SSTableFlushObserver getFlushObserver(Descriptor descriptor, OperationType opType) { return newWriter(baseCfs.metadata.getKeyValidator(), descriptor, Collections.singletonMap(index.getDefinition(), index), opType); } public BiFunction<PartitionIterator, ReadCommand, PartitionIterator> postProcessorFor(ReadCommand command) { return (partitionIterator, readCommand) -> partitionIterator; } public IndexBuildingSupport getBuildTaskSupport() { return INDEX_BUILDER_SUPPORT; } public void handleNotification(INotification notification, Object sender) { // unfortunately, we can only check the type of notification via instanceof :( if (notification instanceof SSTableAddedNotification) { SSTableAddedNotification notice = (SSTableAddedNotification) notification; index.update(Collections.<SSTableReader>emptyList(), Iterables.toList(notice.added)); } else if (notification instanceof SSTableListChangedNotification) { SSTableListChangedNotification notice = (SSTableListChangedNotification) notification; index.update(notice.removed, notice.added); } else if (notification instanceof MemtableRenewedNotification) { index.switchMemtable(); } else if (notification instanceof MemtableSwitchedNotification) { index.switchMemtable(((MemtableSwitchedNotification) notification).memtable); } else if (notification instanceof MemtableDiscardedNotification) { index.discardMemtable(((MemtableDiscardedNotification) notification).memtable); } } public ColumnIndex getIndex() { return index; } protected static PerSSTableIndexWriter newWriter(AbstractType<?> keyValidator, Descriptor descriptor, Map<ColumnDefinition, ColumnIndex> indexes, OperationType opType) { return new PerSSTableIndexWriter(keyValidator, descriptor, opType, indexes); } }
package org.apache.lucene.index; /* * 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. */ import java.io.IOException; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.MockAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.FieldType; import org.apache.lucene.document.TextField; import org.apache.lucene.search.BooleanClause.Occur; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.CollectionStatistics; import org.apache.lucene.search.Explanation; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.PhraseQuery; import org.apache.lucene.search.Scorer; import org.apache.lucene.search.SimpleCollector; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TermStatistics; import org.apache.lucene.search.similarities.TFIDFSimilarity; import org.apache.lucene.store.Directory; import org.apache.lucene.store.MockDirectoryWrapper; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.LuceneTestCase; public class TestOmitTf extends LuceneTestCase { public static class SimpleSimilarity extends TFIDFSimilarity { @Override public float decodeNormValue(long norm) { return norm; } @Override public long encodeNormValue(float f) { return (long) f; } @Override public float queryNorm(float sumOfSquaredWeights) { return 1.0f; } @Override public float coord(int overlap, int maxOverlap) { return 1.0f; } @Override public float lengthNorm(FieldInvertState state) { return state.getBoost(); } @Override public float tf(float freq) { return freq; } @Override public float sloppyFreq(int distance) { return 2.0f; } @Override public float idf(long docFreq, long numDocs) { return 1.0f; } @Override public Explanation idfExplain(CollectionStatistics collectionStats, TermStatistics[] termStats) { return new Explanation(1.0f, "Inexplicable"); } @Override public float scorePayload(int doc, int start, int end, BytesRef payload) { return 1.0f; } } private static final FieldType omitType = new FieldType(TextField.TYPE_NOT_STORED); private static final FieldType normalType = new FieldType(TextField.TYPE_NOT_STORED); static { omitType.setIndexOptions(IndexOptions.DOCS); } // Tests whether the DocumentWriter correctly enable the // omitTermFreqAndPositions bit in the FieldInfo public void testOmitTermFreqAndPositions() throws Exception { Directory ram = newDirectory(); Analyzer analyzer = new MockAnalyzer(random()); IndexWriter writer = new IndexWriter(ram, newIndexWriterConfig(analyzer)); Document d = new Document(); // this field will have Tf Field f1 = newField("f1", "This field has term freqs", normalType); d.add(f1); // this field will NOT have Tf Field f2 = newField("f2", "This field has NO Tf in all docs", omitType); d.add(f2); writer.addDocument(d); writer.forceMerge(1); // now we add another document which has term freq for field f2 and not for f1 and verify if the SegmentMerger // keep things constant d = new Document(); // Reverse f1 = newField("f1", "This field has term freqs", omitType); d.add(f1); f2 = newField("f2", "This field has NO Tf in all docs", normalType); d.add(f2); writer.addDocument(d); // force merge writer.forceMerge(1); // flush writer.close(); SegmentReader reader = getOnlySegmentReader(DirectoryReader.open(ram)); FieldInfos fi = reader.getFieldInfos(); assertEquals("OmitTermFreqAndPositions field bit should be set.", IndexOptions.DOCS, fi.fieldInfo("f1").getIndexOptions()); assertEquals("OmitTermFreqAndPositions field bit should be set.", IndexOptions.DOCS, fi.fieldInfo("f2").getIndexOptions()); reader.close(); ram.close(); } // Tests whether merging of docs that have different // omitTermFreqAndPositions for the same field works public void testMixedMerge() throws Exception { Directory ram = newDirectory(); Analyzer analyzer = new MockAnalyzer(random()); IndexWriter writer = new IndexWriter( ram, newIndexWriterConfig(analyzer). setMaxBufferedDocs(3). setMergePolicy(newLogMergePolicy(2)) ); Document d = new Document(); // this field will have Tf Field f1 = newField("f1", "This field has term freqs", normalType); d.add(f1); // this field will NOT have Tf Field f2 = newField("f2", "This field has NO Tf in all docs", omitType); d.add(f2); for(int i=0;i<30;i++) writer.addDocument(d); // now we add another document which has term freq for field f2 and not for f1 and verify if the SegmentMerger // keep things constant d = new Document(); // Reverese f1 = newField("f1", "This field has term freqs", omitType); d.add(f1); f2 = newField("f2", "This field has NO Tf in all docs", normalType); d.add(f2); for(int i=0;i<30;i++) writer.addDocument(d); // force merge writer.forceMerge(1); // flush writer.close(); SegmentReader reader = getOnlySegmentReader(DirectoryReader.open(ram)); FieldInfos fi = reader.getFieldInfos(); assertEquals("OmitTermFreqAndPositions field bit should be set.", IndexOptions.DOCS, fi.fieldInfo("f1").getIndexOptions()); assertEquals("OmitTermFreqAndPositions field bit should be set.", IndexOptions.DOCS, fi.fieldInfo("f2").getIndexOptions()); reader.close(); ram.close(); } // Make sure first adding docs that do not omitTermFreqAndPositions for // field X, then adding docs that do omitTermFreqAndPositions for that same // field, public void testMixedRAM() throws Exception { Directory ram = newDirectory(); Analyzer analyzer = new MockAnalyzer(random()); IndexWriter writer = new IndexWriter( ram, newIndexWriterConfig(analyzer). setMaxBufferedDocs(10). setMergePolicy(newLogMergePolicy(2)) ); Document d = new Document(); // this field will have Tf Field f1 = newField("f1", "This field has term freqs", normalType); d.add(f1); // this field will NOT have Tf Field f2 = newField("f2", "This field has NO Tf in all docs", omitType); d.add(f2); for(int i=0;i<5;i++) writer.addDocument(d); for(int i=0;i<20;i++) writer.addDocument(d); // force merge writer.forceMerge(1); // flush writer.close(); SegmentReader reader = getOnlySegmentReader(DirectoryReader.open(ram)); FieldInfos fi = reader.getFieldInfos(); assertEquals("OmitTermFreqAndPositions field bit should not be set.", IndexOptions.DOCS_AND_FREQS_AND_POSITIONS, fi.fieldInfo("f1").getIndexOptions()); assertEquals("OmitTermFreqAndPositions field bit should be set.", IndexOptions.DOCS, fi.fieldInfo("f2").getIndexOptions()); reader.close(); ram.close(); } private void assertNoPrx(Directory dir) throws Throwable { final String[] files = dir.listAll(); for(int i=0;i<files.length;i++) { assertFalse(files[i].endsWith(".prx")); assertFalse(files[i].endsWith(".pos")); } } // Verifies no *.prx exists when all fields omit term freq: public void testNoPrxFile() throws Throwable { Directory ram = newDirectory(); if (ram instanceof MockDirectoryWrapper) { // we verify some files get deleted ((MockDirectoryWrapper)ram).setEnableVirusScanner(false); } Analyzer analyzer = new MockAnalyzer(random()); IndexWriter writer = new IndexWriter(ram, newIndexWriterConfig(analyzer) .setMaxBufferedDocs(3) .setMergePolicy(newLogMergePolicy())); LogMergePolicy lmp = (LogMergePolicy) writer.getConfig().getMergePolicy(); lmp.setMergeFactor(2); lmp.setNoCFSRatio(0.0); Document d = new Document(); Field f1 = newField("f1", "This field has term freqs", omitType); d.add(f1); for(int i=0;i<30;i++) writer.addDocument(d); writer.commit(); assertNoPrx(ram); // now add some documents with positions, and check // there is no prox after full merge d = new Document(); f1 = newTextField("f1", "This field has positions", Field.Store.NO); d.add(f1); for(int i=0;i<30;i++) writer.addDocument(d); // force merge writer.forceMerge(1); // flush writer.close(); assertNoPrx(ram); ram.close(); } // Test scores with one field with Term Freqs and one without, otherwise with equal content public void testBasic() throws Exception { Directory dir = newDirectory(); Analyzer analyzer = new MockAnalyzer(random()); IndexWriter writer = new IndexWriter( dir, newIndexWriterConfig(analyzer) .setMaxBufferedDocs(2) .setSimilarity(new SimpleSimilarity()) .setMergePolicy(newLogMergePolicy(2)) ); StringBuilder sb = new StringBuilder(265); String term = "term"; for(int i = 0; i<30; i++){ Document d = new Document(); sb.append(term).append(" "); String content = sb.toString(); Field noTf = newField("noTf", content + (i%2==0 ? "" : " notf"), omitType); d.add(noTf); Field tf = newField("tf", content + (i%2==0 ? " tf" : ""), normalType); d.add(tf); writer.addDocument(d); //System.out.println(d); } writer.forceMerge(1); // flush writer.close(); /* * Verify the index */ IndexReader reader = DirectoryReader.open(dir); IndexSearcher searcher = newSearcher(reader); searcher.setSimilarity(new SimpleSimilarity()); Term a = new Term("noTf", term); Term b = new Term("tf", term); Term c = new Term("noTf", "notf"); Term d = new Term("tf", "tf"); TermQuery q1 = new TermQuery(a); TermQuery q2 = new TermQuery(b); TermQuery q3 = new TermQuery(c); TermQuery q4 = new TermQuery(d); PhraseQuery pq = new PhraseQuery(); pq.add(a); pq.add(c); try { searcher.search(pq, 10); fail("did not hit expected exception"); } catch (Exception e) { Throwable cause = e; // If the searcher uses an executor service, the IAE is wrapped into other exceptions while (cause.getCause() != null) { cause = cause.getCause(); } assertTrue("Expected an IAE, got " + cause, cause instanceof IllegalStateException); } searcher.search(q1, new CountingHitCollector() { private Scorer scorer; @Override public final void setScorer(Scorer scorer) { this.scorer = scorer; } @Override public final void collect(int doc) throws IOException { //System.out.println("Q1: Doc=" + doc + " score=" + score); float score = scorer.score(); assertTrue("got score=" + score, score==1.0f); super.collect(doc); } }); //System.out.println(CountingHitCollector.getCount()); searcher.search(q2, new CountingHitCollector() { private Scorer scorer; @Override public final void setScorer(Scorer scorer) { this.scorer = scorer; } @Override public final void collect(int doc) throws IOException { //System.out.println("Q2: Doc=" + doc + " score=" + score); float score = scorer.score(); assertEquals(1.0f+doc, score, 0.00001f); super.collect(doc); } }); //System.out.println(CountingHitCollector.getCount()); searcher.search(q3, new CountingHitCollector() { private Scorer scorer; @Override public final void setScorer(Scorer scorer) { this.scorer = scorer; } @Override public final void collect(int doc) throws IOException { //System.out.println("Q1: Doc=" + doc + " score=" + score); float score = scorer.score(); assertTrue(score==1.0f); assertFalse(doc%2==0); super.collect(doc); } }); //System.out.println(CountingHitCollector.getCount()); searcher.search(q4, new CountingHitCollector() { private Scorer scorer; @Override public final void setScorer(Scorer scorer) { this.scorer = scorer; } @Override public final void collect(int doc) throws IOException { float score = scorer.score(); //System.out.println("Q1: Doc=" + doc + " score=" + score); assertTrue(score==1.0f); assertTrue(doc%2==0); super.collect(doc); } }); //System.out.println(CountingHitCollector.getCount()); BooleanQuery bq = new BooleanQuery(); bq.add(q1,Occur.MUST); bq.add(q4,Occur.MUST); searcher.search(bq, new CountingHitCollector() { @Override public final void collect(int doc) throws IOException { //System.out.println("BQ: Doc=" + doc + " score=" + score); super.collect(doc); } }); assertEquals(15, CountingHitCollector.getCount()); reader.close(); dir.close(); } public static class CountingHitCollector extends SimpleCollector { static int count=0; static int sum=0; private int docBase = -1; CountingHitCollector(){count=0;sum=0;} @Override public void collect(int doc) throws IOException { count++; sum += doc + docBase; // use it to avoid any possibility of being merged away } public static int getCount() { return count; } public static int getSum() { return sum; } @Override protected void doSetNextReader(LeafReaderContext context) throws IOException { docBase = context.docBase; } } /** test that when freqs are omitted, that totalTermFreq and sumTotalTermFreq are -1 */ public void testStats() throws Exception { Directory dir = newDirectory(); RandomIndexWriter iw = new RandomIndexWriter(random(), dir, newIndexWriterConfig(new MockAnalyzer(random()))); Document doc = new Document(); FieldType ft = new FieldType(TextField.TYPE_NOT_STORED); ft.setIndexOptions(IndexOptions.DOCS); ft.freeze(); Field f = newField("foo", "bar", ft); doc.add(f); iw.addDocument(doc); IndexReader ir = iw.getReader(); iw.close(); assertEquals(-1, ir.totalTermFreq(new Term("foo", new BytesRef("bar")))); assertEquals(-1, ir.getSumTotalTermFreq("foo")); ir.close(); dir.close(); } }
/* * Copyright 2002-2011 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.core.io; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.net.URLConnection; import org.springframework.util.Assert; import org.springframework.util.StringUtils; /** * {@link Resource} implementation for <code>java.net.URL</code> locators. * Obviously supports resolution as URL, and also as File in case of * the "file:" protocol. * * @author Juergen Hoeller * @since 1.0 * @see java.net.URL */ public class UrlResource extends AbstractFileResolvingResource { /** * Original URL, used for actual access. */ private final URL url; /** * Cleaned URL (with normalized path), used for comparisons. */ private final URL cleanedUrl; /** * Original URI, if available; used for URI and File access. */ private final URI uri; /** * Create a new UrlResource. * @param url a URL */ public UrlResource(URL url) { Assert.notNull(url, "URL must not be null"); this.url = url; this.cleanedUrl = getCleanedUrl(this.url, url.toString()); this.uri = null; } /** * Create a new UrlResource. * @param uri a URI * @throws MalformedURLException if the given URL path is not valid */ public UrlResource(URI uri) throws MalformedURLException { Assert.notNull(uri, "URI must not be null"); this.url = uri.toURL(); this.cleanedUrl = getCleanedUrl(this.url, uri.toString()); this.uri = uri; } /** * Create a new UrlResource. * @param path a URL path * @throws MalformedURLException if the given URL path is not valid */ public UrlResource(String path) throws MalformedURLException { Assert.notNull(path, "Path must not be null"); this.url = new URL(path); this.cleanedUrl = getCleanedUrl(this.url, path); this.uri = null; } /** * Determine a cleaned URL for the given original URL. * @param originalUrl the original URL * @param originalPath the original URL path * @return the cleaned URL * @see org.springframework.util.StringUtils#cleanPath */ private URL getCleanedUrl(URL originalUrl, String originalPath) { try { return new URL(StringUtils.cleanPath(originalPath)); } catch (MalformedURLException ex) { // Cleaned URL path cannot be converted to URL // -> take original URL. return originalUrl; } } /** * This implementation opens an InputStream for the given URL. * It sets the "UseCaches" flag to <code>false</code>, * mainly to avoid jar file locking on Windows. * @see java.net.URL#openConnection() * @see java.net.URLConnection#setUseCaches(boolean) * @see java.net.URLConnection#getInputStream() */ public InputStream getInputStream() throws IOException { URLConnection con = this.url.openConnection(); con.setUseCaches(false); try { return con.getInputStream(); } catch (IOException ex) { // Close the HTTP connection (if applicable). if (con instanceof HttpURLConnection) { ((HttpURLConnection) con).disconnect(); } throw ex; } } /** * This implementation returns the underlying URL reference. */ @Override public URL getURL() throws IOException { return this.url; } /** * This implementation returns the underlying URI directly, * if possible. */ @Override public URI getURI() throws IOException { if (this.uri != null) { return this.uri; } else { return super.getURI(); } } /** * This implementation returns a File reference for the underlying URL/URI, * provided that it refers to a file in the file system. * @see org.springframework.util.ResourceUtils#getFile(java.net.URL, String) */ @Override public File getFile() throws IOException { if (this.uri != null) { return super.getFile(this.uri); } else { return super.getFile(); } } /** * This implementation creates a UrlResource, applying the given path * relative to the path of the underlying URL of this resource descriptor. * @see java.net.URL#URL(java.net.URL, String) */ @Override public Resource createRelative(String relativePath) throws MalformedURLException { if (relativePath.startsWith("/")) { relativePath = relativePath.substring(1); } return new UrlResource(new URL(this.url, relativePath)); } /** * This implementation returns the name of the file that this URL refers to. * @see java.net.URL#getFile() * @see java.io.File#getName() */ @Override public String getFilename() { return new File(this.url.getFile()).getName(); } /** * This implementation returns a description that includes the URL. */ public String getDescription() { return "URL [" + this.url + "]"; } /** * This implementation compares the underlying URL references. */ @Override public boolean equals(Object obj) { return (obj == this || (obj instanceof UrlResource && this.cleanedUrl.equals(((UrlResource) obj).cleanedUrl))); } /** * This implementation returns the hash code of the underlying URL reference. */ @Override public int hashCode() { return this.cleanedUrl.hashCode(); } }
package org.jboss.resteasy.client; import org.jboss.resteasy.client.core.BaseClientResponse; import org.jboss.resteasy.client.core.ClientInterceptorRepositoryImpl; import org.jboss.resteasy.client.core.ClientMessageBodyWriterContext; import org.jboss.resteasy.core.interception.ClientExecutionContextImpl; import org.jboss.resteasy.specimpl.MultivaluedMapImpl; import org.jboss.resteasy.specimpl.UriBuilderImpl; import org.jboss.resteasy.spi.Link; import org.jboss.resteasy.spi.LinkHeader; import org.jboss.resteasy.spi.ProviderFactoryDelegate; import org.jboss.resteasy.spi.ResteasyProviderFactory; import org.jboss.resteasy.spi.StringConverter; import org.jboss.resteasy.util.Encode; import org.jboss.resteasy.util.GenericType; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.RuntimeDelegate; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.jboss.resteasy.util.HttpHeaderNames.*; /** * Create a hand coded request to send to the server. You call methods like accept(), body(), pathParameter() * etc. to create the state of the request. Then you call a get(), post(), etc. method to execute the request. * After an execution of a request, the internal state remains the same. You can invoke the request again. * You can clear the request with the clear() method. * * @author <a href="mailto:sduskis@gmail.com">Solomon Duskis</a> * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @version $Revision: 1 $ */ @SuppressWarnings("unchecked") public class ClientRequest extends ClientInterceptorRepositoryImpl implements Cloneable { protected ResteasyProviderFactory providerFactory; protected UriBuilderImpl uri; protected ClientExecutor executor; protected MultivaluedMap<String, Object> headers; protected MultivaluedMap<String, String> queryParameters; protected MultivaluedMap<String, String> formParameters; protected MultivaluedMap<String, String> pathParameters; protected MultivaluedMap<String, String> matrixParameters; protected Object body; protected Class bodyType; protected Type bodyGenericType; protected Annotation[] bodyAnnotations; protected MediaType bodyContentType; protected boolean followRedirects; protected String httpMethod; protected String finalUri; protected List<String> pathParameterList; protected LinkHeader linkHeader; protected Map<String, Object> attributes = new HashMap<String, Object>(); private static String defaultExecutorClasss = "org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor"; /** * Set the default executor class name. * * @param classname */ public static void setDefaultExecutorClass(String classname) { defaultExecutorClasss = classname; } public static ClientExecutor getDefaultExecutor() { try { Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(defaultExecutorClasss); return (ClientExecutor) clazz.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } public ClientRequest(String uriTemplate) { this(uriTemplate, getDefaultExecutor()); } public ClientRequest(String uriTemplate, ClientExecutor executor) { this(getBuilder(uriTemplate), executor); } public ClientRequest(UriBuilder uri, ClientExecutor executor) { this(uri, executor, ResteasyProviderFactory.getInstance()); } public ClientRequest(UriBuilder uri, ClientExecutor executor, ResteasyProviderFactory providerFactory) { this.uri = (UriBuilderImpl) uri; this.executor = executor; if (providerFactory instanceof ProviderFactoryDelegate) { this.providerFactory = ((ProviderFactoryDelegate) providerFactory) .getDelegate(); } else { this.providerFactory = providerFactory; } } /** * Clear this request's state so that it can be re-used */ public void clear() { headers = null; queryParameters = null; formParameters = null; pathParameters = null; matrixParameters = null; body = null; bodyType = null; bodyGenericType = null; bodyAnnotations = null; bodyContentType = null; httpMethod = null; finalUri = null; pathParameterList = null; linkHeader = null; } private static UriBuilder getBuilder(String uriTemplate) { return new UriBuilderImpl().uriTemplate(uriTemplate); } public boolean followRedirects() { return followRedirects; } public Map<String, Object> getAttributes() { return attributes; } public ClientRequest followRedirects(boolean followRedirects) { this.followRedirects = followRedirects; return this; } public ClientRequest accept(MediaType accepts) { return header(ACCEPT, accepts.toString()); } public ClientRequest accept(String accept) { String curr = (String) getHeadersAsObjects().getFirst(ACCEPT); if (curr != null) curr += "," + accept; else curr = accept; getHeadersAsObjects().putSingle(ACCEPT, curr); return this; } protected String toString(Object object) { if (object instanceof String) return (String) object; StringConverter converter = providerFactory.getStringConverter(object .getClass()); if (converter != null) return converter.toString(object); else return object.toString(); } protected String toHeaderString(Object object) { StringConverter converter = providerFactory.getStringConverter(object .getClass()); if (converter != null) return converter.toString(object); RuntimeDelegate.HeaderDelegate delegate = providerFactory .createHeaderDelegate(object.getClass()); if (delegate != null) return delegate.toString(object); else return object.toString(); } public ClientRequest addLink(Link link) { if (linkHeader == null) { linkHeader = new LinkHeader(); } linkHeader.getLinks().add(link); return this; } public ClientRequest addLink(String title, String rel, String href, String type) { Link link = new Link(title, rel, href, type, null); return addLink(link); } public ClientRequest formParameter(String parameterName, Object value) { getFormParameters().add(parameterName, toString(value)); return this; } public ClientRequest queryParameter(String parameterName, Object value) { getQueryParameters().add(parameterName, toString(value)); return this; } public ClientRequest matrixParameter(String parameterName, Object value) { getMatrixParameters().add(parameterName, toString(value)); return this; } public ClientRequest header(String headerName, Object value) { getHeadersAsObjects().add(headerName, value); return this; } public ClientRequest cookie(String cookieName, Object value) { return cookie(new Cookie(cookieName, toString(value))); } public ClientRequest cookie(Cookie cookie) { return header(HttpHeaders.COOKIE, cookie); } public ClientRequest pathParameter(String parameterName, Object value) { getPathParameters().add(parameterName, toString(value)); return this; } public ClientRequest pathParameters(Object... values) { for (Object value : values) { getPathParameterList().add(toString(value)); } return this; } public ClientRequest body(String contentType, Object data) { return body(MediaType.valueOf(contentType), data, data.getClass(), null, null); } public ClientRequest body(MediaType contentType, Object data) { return body(contentType, data, data.getClass(), null, null); } public ClientRequest body(MediaType contentType, Object data, GenericType genericType) { return body(contentType, data, genericType.getType(), genericType .getGenericType(), null); } public ClientRequest body(MediaType contentType, Object data, Type genericType) { return body(contentType, data, data.getClass(), genericType, null); } public ClientRequest body(MediaType contentType, Object data, Class type, Type genericType, Annotation[] annotations) { this.body = data; this.bodyContentType = contentType; this.bodyGenericType = genericType; this.bodyType = type; this.bodyAnnotations = annotations; return this; } public ResteasyProviderFactory getProviderFactory() { return providerFactory; } public ClientExecutor getExecutor() { return executor; } /** * @return a copy of all header objects converted to a string */ public MultivaluedMap<String, String> getHeaders() { MultivaluedMap<String, String> rtn = new MultivaluedMapImpl<String, String>(); if (headers == null) return rtn; for (Map.Entry<String, List<Object>> entry : headers.entrySet()) { for (Object obj : entry.getValue()) { rtn.add(entry.getKey(), toHeaderString(obj)); } } return rtn; } public MultivaluedMap<String, Object> getHeadersAsObjects() { if (headers == null) headers = new MultivaluedMapImpl<String, Object>(); return headers; } public MultivaluedMap<String, String> getQueryParameters() { if (queryParameters == null) queryParameters = new MultivaluedMapImpl<String, String>(); return queryParameters; } public MultivaluedMap<String, String> getFormParameters() { if (formParameters == null) formParameters = new MultivaluedMapImpl<String, String>(); return formParameters; } public MultivaluedMap<String, String> getPathParameters() { if (pathParameters == null) pathParameters = new MultivaluedMapImpl<String, String>(); return pathParameters; } public List<String> getPathParameterList() { if (pathParameterList == null) pathParameterList = new ArrayList<String>(); return pathParameterList; } public MultivaluedMap<String, String> getMatrixParameters() { if (matrixParameters == null) matrixParameters = new MultivaluedMapImpl<String, String>(); return matrixParameters; } public Object getBody() { return body; } public Class getBodyType() { return bodyType; } public Type getBodyGenericType() { return bodyGenericType; } public Annotation[] getBodyAnnotations() { return bodyAnnotations; } public MediaType getBodyContentType() { return bodyContentType; } public String getHttpMethod() { return httpMethod; } public void setHttpMethod(String httpMethod) { this.httpMethod = httpMethod; } public ClientResponse execute() throws Exception { if (linkHeader != null) header("Link", linkHeader); if (getReaderInterceptorList().isEmpty()) setReaderInterceptors(providerFactory .getClientMessageBodyReaderInterceptorRegistry().bindForList( null, null)); if (getExecutionInterceptorList().isEmpty()) { setExecutionInterceptors(providerFactory .getClientExecutionInterceptorRegistry().bindForList(null, null)); } BaseClientResponse response = null; if (getExecutionInterceptorList().isEmpty()) { response = (BaseClientResponse) executor.execute(this); } else { ClientExecutionContextImpl ctx = new ClientExecutionContextImpl( getExecutionInterceptorList(), executor, this); response = (BaseClientResponse) ctx.proceed(); } response.setAttributes(attributes); response.setMessageBodyReaderInterceptors(getReaderInterceptors()); return response; } public void writeRequestBody(MultivaluedMap<String, Object> headers, OutputStream outputStream) throws IOException { if (body == null) { return; } if (getWriterInterceptorList().isEmpty()) { setWriterInterceptors(providerFactory .getClientMessageBodyWriterInterceptorRegistry().bindForList( null, null)); } MessageBodyWriter writer = providerFactory .getMessageBodyWriter(bodyType, bodyGenericType, bodyAnnotations, bodyContentType); if (writer == null) { throw new RuntimeException("could not find writer for content-type " + bodyContentType + " type: " + bodyType.getName()); } new ClientMessageBodyWriterContext(getWriterInterceptors(), writer, body, bodyType, bodyGenericType, bodyAnnotations, bodyContentType, headers, outputStream, attributes).proceed(); } public ClientResponse get() throws Exception { return httpMethod("GET"); } /** * Tries to automatically unmarshal to target type. * * @param returnType * @param <T> * @return * @throws Exception */ public <T> T getTarget(Class<T> returnType) throws Exception { BaseClientResponse<T> response = (BaseClientResponse<T>) get(returnType); if (response.getStatus() == 204) return null; if (response.getStatus() != 200) throw new ClientResponseFailure(response); T obj = response.getEntity(); if (obj instanceof InputStream) { response.setWasReleased(true); } return obj; } /** * Templates the returned ClientResponse for easy access to returned entity * * @param returnType * @param <T> * @return * @throws Exception */ public <T> ClientResponse<T> get(Class<T> returnType) throws Exception { BaseClientResponse response = (BaseClientResponse) get(); response.setReturnType(returnType); return response; } public <T> ClientResponse<T> get(Class<T> returnType, Type genericType) throws Exception { BaseClientResponse response = (BaseClientResponse) get(); response.setReturnType(returnType); response.setGenericReturnType(genericType); return response; } public <T> ClientResponse<T> get(GenericType type) throws Exception { BaseClientResponse response = (BaseClientResponse) get(); response.setReturnType(type.getType()); response.setGenericReturnType(type.getGenericType()); return response; } public ClientResponse head() throws Exception { return httpMethod("HEAD"); } public ClientResponse put() throws Exception { return httpMethod("PUT"); } public <T> ClientResponse<T> put(Class<T> returnType) throws Exception { BaseClientResponse response = (BaseClientResponse) put(); response.setReturnType(returnType); return response; } public <T> ClientResponse<T> put(Class<T> returnType, Type genericType) throws Exception { BaseClientResponse response = (BaseClientResponse) put(); response.setReturnType(returnType); response.setGenericReturnType(genericType); return response; } public <T> ClientResponse<T> put(GenericType type) throws Exception { BaseClientResponse response = (BaseClientResponse) put(); response.setReturnType(type.getType()); response.setGenericReturnType(type.getGenericType()); return response; } public ClientResponse post() throws Exception { return httpMethod("POST"); } public <T> ClientResponse<T> post(Class<T> returnType) throws Exception { BaseClientResponse response = (BaseClientResponse) post(); response.setReturnType(returnType); return response; } public <T> T postTarget(Class<T> returnType) throws Exception { BaseClientResponse<T> response = (BaseClientResponse<T>) post(returnType); if (response.getStatus() == 204) return null; if (response.getStatus() != 200) throw new ClientResponseFailure(response); T obj = response.getEntity(); if (obj instanceof InputStream) { response.setWasReleased(true); } return obj; } public <T> ClientResponse<T> post(Class<T> returnType, Type genericType) throws Exception { BaseClientResponse response = (BaseClientResponse) post(); response.setReturnType(returnType); response.setGenericReturnType(genericType); return response; } public <T> ClientResponse<T> post(GenericType type) throws Exception { BaseClientResponse response = (BaseClientResponse) post(); response.setReturnType(type.getType()); response.setGenericReturnType(type.getGenericType()); return response; } /** * Automatically does POST/Create pattern. Will throw a ClientResponseFailure * if status is something other than 201 * * @return Link to created resource * @throws Exception, ClientResponseFailure */ public Link create() throws Exception, ClientResponseFailure { BaseClientResponse response = (BaseClientResponse) post(); if (response.getStatus() != 201) throw new ClientResponseFailure(response); return response.getLocation(); } public ClientResponse delete() throws Exception { return httpMethod("DELETE"); } public <T> ClientResponse<T> delete(Class<T> returnType) throws Exception { BaseClientResponse response = (BaseClientResponse) delete(); response.setReturnType(returnType); return response; } public <T> ClientResponse<T> delete(Class<T> returnType, Type genericType) throws Exception { BaseClientResponse response = (BaseClientResponse) delete(); response.setReturnType(returnType); response.setGenericReturnType(genericType); return response; } public <T> ClientResponse<T> delete(GenericType type) throws Exception { BaseClientResponse response = (BaseClientResponse) delete(); response.setReturnType(type.getType()); response.setGenericReturnType(type.getGenericType()); return response; } public ClientResponse options() throws Exception { return httpMethod("OPTIONS"); } public <T> ClientResponse<T> options(Class<T> returnType) throws Exception { BaseClientResponse response = (BaseClientResponse) options(); response.setReturnType(returnType); return response; } public <T> ClientResponse<T> options(Class<T> returnType, Type genericType) throws Exception { BaseClientResponse response = (BaseClientResponse) options(); response.setReturnType(returnType); response.setGenericReturnType(genericType); return response; } public <T> ClientResponse<T> options(GenericType type) throws Exception { BaseClientResponse response = (BaseClientResponse) options(); response.setReturnType(type.getType()); response.setGenericReturnType(type.getGenericType()); return response; } public ClientResponse httpMethod(String httpMethod) throws Exception { this.httpMethod = httpMethod; return execute(); } public <T> ClientResponse<T> httpMethod(String method, Class<T> returnType) throws Exception { BaseClientResponse response = (BaseClientResponse) httpMethod(method); response.setReturnType(returnType); return response; } public <T> ClientResponse<T> httpMethod(String method, Class<T> returnType, Type genericType) throws Exception { BaseClientResponse response = (BaseClientResponse) httpMethod(method); response.setReturnType(returnType); response.setGenericReturnType(genericType); return response; } public <T> ClientResponse<T> httpMethod(String method, GenericType type) throws Exception { BaseClientResponse response = (BaseClientResponse) httpMethod(method); response.setReturnType(type.getType()); response.setGenericReturnType(type.getGenericType()); return response; } public void overrideUri(URI uri) { this.uri.uri(uri); } /** * This method populates all path, matrix, and query parameters and saves it * internally. Once its called once it returns the cached value. * * @return * @throws Exception */ public String getUri() throws Exception { if (finalUri != null) return finalUri; UriBuilderImpl builder = (UriBuilderImpl) uri.clone(); if (matrixParameters != null) { for (Map.Entry<String, List<String>> entry : matrixParameters .entrySet()) { List<String> values = entry.getValue(); for (String value : values) builder.matrixParam(entry.getKey(), value); } } if (queryParameters != null) { for (Map.Entry<String, List<String>> entry : queryParameters .entrySet()) { List<String> values = entry.getValue(); for (String value : values) builder.clientQueryParam(entry.getKey(), value); } } if (pathParameterList != null && !pathParameterList.isEmpty()) { finalUri = builder.build(pathParameterList.toArray()).toString(); } else if (pathParameters != null && !pathParameters.isEmpty()) { for (Map.Entry<String, List<String>> entry : pathParameters.entrySet()) { List<String> values = entry.getValue(); for (String value : values) { value = Encode.encodePathAsIs(value); builder.substitutePathParam(entry.getKey(), value, true); } } } if (finalUri == null) finalUri = builder.build().toString(); return finalUri; } public ClientRequest createSubsequentRequest(URI uri) { try { ClientRequest clone = (ClientRequest) this.clone(); clone.clear(); clone.uri = new UriBuilderImpl(); clone.uri.uri(uri); return clone; } catch (CloneNotSupportedException e) { // this shouldn't happen throw new RuntimeException("ClientRequest doesn't implement Clonable. Notify the RESTEasy staff right away."); } } }
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.testsuite.oauth; import org.hamcrest.CoreMatchers; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.keycloak.admin.client.resource.ClientResource; import org.keycloak.admin.client.resource.ClientScopeResource; import org.keycloak.admin.client.resource.ProtocolMappersResource; import org.keycloak.admin.client.resource.RealmResource; import org.keycloak.admin.client.resource.UserResource; import org.keycloak.common.Profile; import org.keycloak.common.util.UriUtils; import org.keycloak.jose.jws.JWSInput; import org.keycloak.models.AccountRoles; import org.keycloak.protocol.oidc.OIDCLoginProtocol; import org.keycloak.protocol.oidc.OIDCLoginProtocolFactory; import org.keycloak.protocol.oidc.mappers.AddressMapper; import org.keycloak.protocol.oidc.mappers.OIDCAttributeMapperHelper; import org.keycloak.representations.AccessToken; import org.keycloak.representations.AddressClaimSet; import org.keycloak.representations.IDToken; import org.keycloak.representations.idm.ClientRepresentation; import org.keycloak.representations.idm.ClientScopeRepresentation; import org.keycloak.representations.idm.GroupRepresentation; import org.keycloak.representations.idm.ProtocolMapperRepresentation; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.testsuite.AbstractKeycloakTest; import org.keycloak.testsuite.Assert; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.ProfileAssume; import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.arquillian.annotation.EnableFeature; import org.keycloak.testsuite.util.ClientManager; import org.keycloak.testsuite.util.OAuthClient; import org.keycloak.testsuite.util.ProtocolMapperUtil; import javax.ws.rs.core.Response; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.arrayContainingInAnyOrder; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.isEmptyOrNullString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.keycloak.testsuite.admin.AbstractAdminTest.loadJson; import static org.keycloak.testsuite.admin.ApiUtil.findClientByClientId; import static org.keycloak.testsuite.admin.ApiUtil.findClientResourceByClientId; import static org.keycloak.testsuite.admin.ApiUtil.findUserByUsernameId; import static org.keycloak.testsuite.util.ProtocolMapperUtil.createAddressMapper; import static org.keycloak.testsuite.util.ProtocolMapperUtil.createClaimMapper; import static org.keycloak.testsuite.util.ProtocolMapperUtil.createHardcodedClaim; import static org.keycloak.testsuite.util.ProtocolMapperUtil.createHardcodedRole; import static org.keycloak.testsuite.util.ProtocolMapperUtil.createRoleNameMapper; import static org.keycloak.testsuite.util.ProtocolMapperUtil.createScriptMapper; /** * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a> */ public class OIDCProtocolMappersTest extends AbstractKeycloakTest { @Rule public AssertEvents events = new AssertEvents(this); @Before public void clientConfiguration() { ClientManager.realm(adminClient.realm("test")).clientId("test-app").directAccessGrant(true); /* * Configure the default client ID. Seems like OAuthClient is keeping the state of clientID * For example: If some test case configure oauth.clientId("sample-public-client"), other tests * will faile and the clientID will always be "sample-public-client * @see AccessTokenTest#testAuthorizationNegotiateHeaderIgnored() */ oauth.clientId("test-app"); } private void deleteMappers(ProtocolMappersResource protocolMappers) { ProtocolMapperRepresentation mapper = ProtocolMapperUtil.getMapperByNameAndProtocol(protocolMappers, OIDCLoginProtocol.LOGIN_PROTOCOL, "Realm roles mapper"); if (mapper != null) { protocolMappers.delete(mapper.getId()); } mapper = ProtocolMapperUtil.getMapperByNameAndProtocol(protocolMappers, OIDCLoginProtocol.LOGIN_PROTOCOL, "Client roles mapper"); if (mapper != null) { protocolMappers.delete(mapper.getId()); } mapper = ProtocolMapperUtil.getMapperByNameAndProtocol(protocolMappers, OIDCLoginProtocol.LOGIN_PROTOCOL, "group-value"); if (mapper != null) { protocolMappers.delete(mapper.getId()); } } @Override public void addTestRealms(List<RealmRepresentation> testRealms) { RealmRepresentation realm = loadJson(getClass().getResourceAsStream("/testrealm.json"), RealmRepresentation.class); testRealms.add(realm); } @Test @EnableFeature(value = Profile.Feature.UPLOAD_SCRIPTS) // This requires also SCRIPTS feature, therefore we need to restart container public void testTokenScriptMapping() { { ClientResource app = findClientResourceByClientId(adminClient.realm("test"), "test-app"); app.getProtocolMappers().createMapper(createScriptMapper("test-script-mapper1","computed-via-script", "computed-via-script", "String", true, true, "'hello_' + user.username", false)).close(); app.getProtocolMappers().createMapper(createScriptMapper("test-script-mapper2","multiValued-via-script", "multiValued-via-script", "String", true, true, "new java.util.ArrayList(['A','B'])", true)).close(); Response response = app.getProtocolMappers().createMapper(createScriptMapper("test-script-mapper3", "syntax-error-script", "syntax-error-script", "String", true, true, "func_tion foo(){ return 'fail';} foo()", false)); assertThat(response.getStatusInfo().getFamily(), is(Response.Status.Family.CLIENT_ERROR)); response.close(); } { OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password"); AccessToken accessToken = oauth.verifyToken(response.getAccessToken()); assertEquals("hello_test-user@localhost", accessToken.getOtherClaims().get("computed-via-script")); assertEquals(Arrays.asList("A","B"), accessToken.getOtherClaims().get("multiValued-via-script")); } } @Test public void testTokenMapping() throws Exception { { UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost"); UserRepresentation user = userResource.toRepresentation(); user.singleAttribute("street", "5 Yawkey Way"); user.singleAttribute("locality", "Boston"); user.singleAttribute("region_some", "MA"); // Custom name for userAttribute name, which will be mapped to region user.singleAttribute("postal_code", "02115"); user.singleAttribute("country", "USA"); user.singleAttribute("formatted", "6 Foo Street"); user.singleAttribute("phone", "617-777-6666"); user.singleAttribute("json-attribute", "{\"a\": 1, \"b\": 2, \"c\": [{\"a\": 1, \"b\": 2}], \"d\": {\"a\": 1, \"b\": 2}}"); user.getAttributes().put("json-attribute-multi", Arrays.asList("{\"a\": 1, \"b\": 2, \"c\": [{\"a\": 1, \"b\": 2}], \"d\": {\"a\": 1, \"b\": 2}}", "{\"a\": 1, \"b\": 2, \"c\": [{\"a\": 1, \"b\": 2}], \"d\": {\"a\": 1, \"b\": 2}}")); List<String> departments = Arrays.asList("finance", "development"); user.getAttributes().put("departments", departments); userResource.update(user); ClientResource app = findClientResourceByClientId(adminClient.realm("test"), "test-app"); ProtocolMapperRepresentation mapper = createAddressMapper(true, true, true); mapper.getConfig().put(AddressMapper.getModelPropertyName(AddressClaimSet.REGION), "region_some"); mapper.getConfig().put(AddressMapper.getModelPropertyName(AddressClaimSet.COUNTRY), "country_some"); mapper.getConfig().remove(AddressMapper.getModelPropertyName(AddressClaimSet.POSTAL_CODE)); // Even if we remove protocolMapper config property, it should still default to postal_code app.getProtocolMappers().createMapper(mapper).close(); ProtocolMapperRepresentation hard = createHardcodedClaim("hard", "hard", "coded", "String", true, true); app.getProtocolMappers().createMapper(hard).close(); app.getProtocolMappers().createMapper(createHardcodedClaim("hard-nested", "nested.hard", "coded-nested", "String", true, true)).close(); app.getProtocolMappers().createMapper(createClaimMapper("custom phone", "phone", "home_phone", "String", true, true, true)).close(); app.getProtocolMappers().createMapper(createClaimMapper("nested phone", "phone", "home.phone", "String", true, true, true)).close(); app.getProtocolMappers().createMapper(createClaimMapper("dotted phone", "phone", "home\\.phone", "String", true, true, true)).close(); app.getProtocolMappers().createMapper(createClaimMapper("departments", "departments", "department", "String", true, true, true)).close(); app.getProtocolMappers().createMapper(createClaimMapper("firstDepartment", "departments", "firstDepartment", "String", true, true, false)).close(); app.getProtocolMappers().createMapper(createHardcodedRole("hard-realm", "hardcoded")).close(); app.getProtocolMappers().createMapper(createHardcodedRole("hard-app", "app.hardcoded")).close(); app.getProtocolMappers().createMapper(createRoleNameMapper("rename-app-role", "test-app.customer-user", "realm-user")).close(); app.getProtocolMappers().createMapper(createScriptMapper("test-script-mapper1","computed-via-script", "computed-via-script", "String", true, true, "'hello_' + user.username", false)).close(); app.getProtocolMappers().createMapper(createScriptMapper("test-script-mapper2","multiValued-via-script", "multiValued-via-script", "String", true, true, "new java.util.ArrayList(['A','B'])", true)).close(); app.getProtocolMappers().createMapper(createClaimMapper("json-attribute-mapper", "json-attribute", "claim-from-json-attribute", "JSON", true, true, false)).close(); app.getProtocolMappers().createMapper(createClaimMapper("json-attribute-mapper-multi", "json-attribute-multi", "claim-from-json-attribute-multi", "JSON", true, true, true)).close(); Response response = app.getProtocolMappers().createMapper(createScriptMapper("test-script-mapper3", "syntax-error-script", "syntax-error-script", "String", true, true, "func_tion foo(){ return 'fail';} foo()", false)); assertThat(response.getStatusInfo().getFamily(), is(Response.Status.Family.CLIENT_ERROR)); response.close(); } { OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password"); IDToken idToken = oauth.verifyIDToken(response.getIdToken()); assertNotNull(idToken.getAddress()); assertEquals(idToken.getName(), "Tom Brady"); assertEquals(idToken.getAddress().getStreetAddress(), "5 Yawkey Way"); assertEquals(idToken.getAddress().getLocality(), "Boston"); assertEquals(idToken.getAddress().getRegion(), "MA"); assertEquals(idToken.getAddress().getPostalCode(), "02115"); assertNull(idToken.getAddress().getCountry()); // Null because we changed userAttribute name to "country_some", but user contains "country" assertEquals(idToken.getAddress().getFormattedAddress(), "6 Foo Street"); assertNotNull(idToken.getOtherClaims().get("home_phone")); assertThat((List<String>) idToken.getOtherClaims().get("home_phone"), hasItems("617-777-6666")); assertNotNull(idToken.getOtherClaims().get("home.phone")); assertThat((List<String>) idToken.getOtherClaims().get("home.phone"), hasItems("617-777-6666")); assertEquals("coded", idToken.getOtherClaims().get("hard")); Map nested = (Map) idToken.getOtherClaims().get("nested"); assertEquals("coded-nested", nested.get("hard")); nested = (Map) idToken.getOtherClaims().get("home"); assertThat((List<String>) nested.get("phone"), hasItems("617-777-6666")); List<String> departments = (List<String>) idToken.getOtherClaims().get("department"); assertThat(departments, containsInAnyOrder("finance", "development")); Object firstDepartment = idToken.getOtherClaims().get("firstDepartment"); assertThat(firstDepartment, instanceOf(String.class)); assertThat(firstDepartment, anyOf(is("finance"), is("development"))); // Has to be the first item Map jsonClaim = (Map) idToken.getOtherClaims().get("claim-from-json-attribute"); assertThat(jsonClaim.get("a"), instanceOf(int.class)); assertThat(jsonClaim.get("c"), instanceOf(Collection.class)); assertThat(jsonClaim.get("d"), instanceOf(Map.class)); List<Map> jsonClaims = (List<Map>) idToken.getOtherClaims().get("claim-from-json-attribute-multi"); assertEquals(2, jsonClaims.size()); assertThat(jsonClaims.get(0).get("a"), instanceOf(int.class)); assertThat(jsonClaims.get(1).get("c"), instanceOf(Collection.class)); assertThat(jsonClaims.get(1).get("d"), instanceOf(Map.class)); AccessToken accessToken = oauth.verifyToken(response.getAccessToken()); assertEquals(accessToken.getName(), "Tom Brady"); assertNotNull(accessToken.getAddress()); assertEquals(accessToken.getAddress().getStreetAddress(), "5 Yawkey Way"); assertEquals(accessToken.getAddress().getLocality(), "Boston"); assertEquals(accessToken.getAddress().getRegion(), "MA"); assertEquals(accessToken.getAddress().getPostalCode(), "02115"); assertNull(idToken.getAddress().getCountry()); // Null because we changed userAttribute name to "country_some", but user contains "country" assertEquals(idToken.getAddress().getFormattedAddress(), "6 Foo Street"); assertNotNull(accessToken.getOtherClaims().get("home_phone")); assertThat((List<String>) accessToken.getOtherClaims().get("home_phone"), hasItems("617-777-6666")); assertEquals("coded", accessToken.getOtherClaims().get("hard")); nested = (Map) accessToken.getOtherClaims().get("nested"); assertEquals("coded-nested", nested.get("hard")); nested = (Map) accessToken.getOtherClaims().get("home"); assertThat((List<String>) nested.get("phone"), hasItems("617-777-6666")); departments = (List<String>) idToken.getOtherClaims().get("department"); assertEquals(2, departments.size()); assertTrue(departments.contains("finance") && departments.contains("development")); assertTrue(accessToken.getRealmAccess().getRoles().contains("hardcoded")); assertTrue(accessToken.getRealmAccess().getRoles().contains("realm-user")); Assert.assertNull(accessToken.getResourceAccess("test-app")); assertTrue(accessToken.getResourceAccess("app").getRoles().contains("hardcoded")); // Assert audiences added through AudienceResolve mapper Assert.assertThat(accessToken.getAudience(), arrayContainingInAnyOrder( "app", "account")); // Assert allowed origins Assert.assertNames(accessToken.getAllowedOrigins(), "http://localhost:8180", "https://localhost:8543"); jsonClaim = (Map) accessToken.getOtherClaims().get("claim-from-json-attribute"); assertThat(jsonClaim.get("a"), instanceOf(int.class)); assertThat(jsonClaim.get("c"), instanceOf(Collection.class)); assertThat(jsonClaim.get("d"), instanceOf(Map.class)); oauth.openLogout(); } // undo mappers { ClientResource app = findClientByClientId(adminClient.realm("test"), "test-app"); ClientRepresentation clientRepresentation = app.toRepresentation(); for (ProtocolMapperRepresentation model : clientRepresentation.getProtocolMappers()) { if (model.getName().equals("address") || model.getName().equals("hard") || model.getName().equals("hard-nested") || model.getName().equals("custom phone") || model.getName().equals("dotted phone") || model.getName().equals("departments") || model.getName().equals("firstDepartment") || model.getName().equals("nested phone") || model.getName().equals("rename-app-role") || model.getName().equals("hard-realm") || model.getName().equals("hard-app") || model.getName().equals("test-script-mapper") || model.getName().equals("json-attribute-mapper") ) { app.getProtocolMappers().delete(model.getId()); } } } events.clear(); { OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password"); IDToken idToken = oauth.verifyIDToken(response.getIdToken()); assertNull(idToken.getAddress()); assertNull(idToken.getOtherClaims().get("home_phone")); assertNull(idToken.getOtherClaims().get("hard")); assertNull(idToken.getOtherClaims().get("nested")); assertNull(idToken.getOtherClaims().get("department")); oauth.openLogout(); } events.clear(); } @Test public void testNullOrEmptyTokenMapping() throws Exception { { UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost"); UserRepresentation user = userResource.toRepresentation(); user.singleAttribute("empty", ""); user.singleAttribute("null", null); userResource.update(user); ClientResource app = findClientResourceByClientId(adminClient.realm("test"), "test-app"); app.getProtocolMappers().createMapper(createClaimMapper("empty", "empty", "empty", "String", true, true, false)).close(); app.getProtocolMappers().createMapper(createClaimMapper("null", "null", "null", "String", true, true, false)).close(); } { OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password"); IDToken idToken = oauth.verifyIDToken(response.getIdToken()); Object empty = idToken.getOtherClaims().get("empty"); assertThat((empty == null ? null : (String) empty), isEmptyOrNullString()); Object nulll = idToken.getOtherClaims().get("null"); assertNull(nulll); oauth.verifyToken(response.getAccessToken()); oauth.openLogout(); } // undo mappers { ClientResource app = findClientByClientId(adminClient.realm("test"), "test-app"); ClientRepresentation clientRepresentation = app.toRepresentation(); for (ProtocolMapperRepresentation model : clientRepresentation.getProtocolMappers()) { if (model.getName().equals("empty") || model.getName().equals("null") ) { app.getProtocolMappers().delete(model.getId()); } } } events.clear(); { OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password"); IDToken idToken = oauth.verifyIDToken(response.getIdToken()); assertNull(idToken.getAddress()); assertNull(idToken.getOtherClaims().get("empty")); assertNull(idToken.getOtherClaims().get("null")); oauth.openLogout(); } events.clear(); } @Test public void testUserRoleToAttributeMappers() throws Exception { // Add mapper for realm roles ProtocolMapperRepresentation realmMapper = ProtocolMapperUtil.createUserRealmRoleMappingMapper("pref.", "Realm roles mapper", "roles-custom.realm", true, true); ProtocolMapperRepresentation clientMapper = ProtocolMapperUtil.createUserClientRoleMappingMapper("test-app", null, "Client roles mapper", "roles-custom.test-app", true, true); ProtocolMappersResource protocolMappers = ApiUtil.findClientResourceByClientId(adminClient.realm("test"), "test-app").getProtocolMappers(); protocolMappers.createMapper(Arrays.asList(realmMapper, clientMapper)); // Login user OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password"); IDToken idToken = oauth.verifyIDToken(response.getIdToken()); // Verify attribute is filled Map<String, Object> roleMappings = (Map<String, Object>)idToken.getOtherClaims().get("roles-custom"); Assert.assertThat(roleMappings.keySet(), containsInAnyOrder("realm", "test-app")); String realmRoleMappings = (String) roleMappings.get("realm"); String testAppMappings = (String) roleMappings.get("test-app"); assertRolesString(realmRoleMappings, "pref.user", // from direct assignment in user definition "pref.offline_access" // from direct assignment in user definition ); assertRolesString(testAppMappings, "customer-user" // from direct assignment in user definition ); // Revert deleteMappers(protocolMappers); } // Test to update protocolMappers to not have roles on the default position (realm_access and resource_access properties) @Test public void testUserRolesMovedFromAccessTokenProperties() throws Exception { RealmResource realm = adminClient.realm("test"); ClientScopeResource rolesScope = ApiUtil.findClientScopeByName(realm, OIDCLoginProtocolFactory.ROLES_SCOPE); // Update builtin protocolMappers to put roles to different position (claim "custom.roles") for both realm and client roles ProtocolMapperRepresentation realmRolesMapper = null; ProtocolMapperRepresentation clientRolesMapper = null; for (ProtocolMapperRepresentation rep : rolesScope.getProtocolMappers().getMappers()) { if (OIDCLoginProtocolFactory.REALM_ROLES.equals(rep.getName())) { realmRolesMapper = rep; } else if (OIDCLoginProtocolFactory.CLIENT_ROLES.equals(rep.getName())) { clientRolesMapper = rep; } } String realmRolesTokenClaimOrig = realmRolesMapper.getConfig().get(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME); String clientRolesTokenClaimOrig = clientRolesMapper.getConfig().get(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME); realmRolesMapper.getConfig().put(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME, "custom.roles"); rolesScope.getProtocolMappers().update(realmRolesMapper.getId(), realmRolesMapper); clientRolesMapper.getConfig().put(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME, "custom.roles"); rolesScope.getProtocolMappers().update(clientRolesMapper.getId(), clientRolesMapper); // Create some hardcoded role mapper Response resp = rolesScope.getProtocolMappers().createMapper(createHardcodedRole("hard-realm", "hardcoded")); String hardcodedMapperId = ApiUtil.getCreatedId(resp); resp.close(); try { OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password"); AccessToken accessToken = oauth.verifyToken(response.getAccessToken()); // Assert roles are not on their original positions Assert.assertNull(accessToken.getRealmAccess()); Assert.assertTrue(accessToken.getResourceAccess().isEmpty()); // KEYCLOAK-8481 Assert that accessToken JSON doesn't have "realm_access" or "resource_access" fields in it String accessTokenJson = new String(new JWSInput(response.getAccessToken()).getContent(), StandardCharsets.UTF_8); Assert.assertFalse(accessTokenJson.contains("realm_access")); Assert.assertFalse(accessTokenJson.contains("resource_access")); // Assert both realm and client roles on the new position. Hardcoded role should be here as well Map<String, Object> cst1 = (Map<String, Object>) accessToken.getOtherClaims().get("custom"); List<String> roles = (List<String>) cst1.get("roles"); Assert.assertNames(roles, "offline_access", "user", "customer-user", "hardcoded", AccountRoles.VIEW_PROFILE, AccountRoles.MANAGE_ACCOUNT, AccountRoles.MANAGE_ACCOUNT_LINKS); // Assert audience Assert.assertNames(Arrays.asList(accessToken.getAudience()), "account"); } finally { // Revert rolesScope.getProtocolMappers().delete(hardcodedMapperId); realmRolesMapper.getConfig().put(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME, realmRolesTokenClaimOrig); rolesScope.getProtocolMappers().update(realmRolesMapper.getId(), realmRolesMapper); clientRolesMapper.getConfig().put(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME, clientRolesTokenClaimOrig); rolesScope.getProtocolMappers().update(clientRolesMapper.getId(), clientRolesMapper); } } @Test public void testRolesAndAllowedOriginsRemovedFromAccessToken() throws Exception { RealmResource realm = adminClient.realm("test"); ClientScopeRepresentation allowedOriginsScope = ApiUtil.findClientScopeByName(realm, OIDCLoginProtocolFactory.WEB_ORIGINS_SCOPE).toRepresentation(); ClientScopeRepresentation rolesScope = ApiUtil.findClientScopeByName(realm, OIDCLoginProtocolFactory.ROLES_SCOPE).toRepresentation(); // Remove 'roles' and 'web-origins' scope from the client ClientResource testApp = ApiUtil.findClientByClientId(realm, "test-app"); testApp.removeDefaultClientScope(allowedOriginsScope.getId()); testApp.removeDefaultClientScope(rolesScope.getId()); try { OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password"); AccessToken accessToken = oauth.verifyToken(response.getAccessToken()); // Assert web origins are not in the token Assert.assertNull(accessToken.getAllowedOrigins()); // Assert roles are not in the token Assert.assertNull(accessToken.getRealmAccess()); Assert.assertTrue(accessToken.getResourceAccess().isEmpty()); // Assert client not in the token audience. Just in "issuedFor" Assert.assertEquals("test-app", accessToken.getIssuedFor()); Assert.assertFalse(accessToken.hasAudience("test-app")); // Assert IDToken still has "test-app" as an audience IDToken idToken = oauth.verifyIDToken(response.getIdToken()); Assert.assertEquals("test-app", idToken.getIssuedFor()); Assert.assertTrue(idToken.hasAudience("test-app")); } finally { // Revert testApp.addDefaultClientScope(allowedOriginsScope.getId()); testApp.addDefaultClientScope(rolesScope.getId()); } } /** * KEYCLOAK-4205 * @throws Exception */ @Test public void testUserRoleToAttributeMappersWithMultiValuedRoles() throws Exception { // Add mapper for realm roles ProtocolMapperRepresentation realmMapper = ProtocolMapperUtil.createUserRealmRoleMappingMapper("pref.", "Realm roles mapper", "roles-custom.realm", true, true, true); ProtocolMapperRepresentation clientMapper = ProtocolMapperUtil.createUserClientRoleMappingMapper("test-app", null, "Client roles mapper", "roles-custom.test-app", true, true, true); ProtocolMappersResource protocolMappers = ApiUtil.findClientResourceByClientId(adminClient.realm("test"), "test-app").getProtocolMappers(); protocolMappers.createMapper(Arrays.asList(realmMapper, clientMapper)); // Login user OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password"); IDToken idToken = oauth.verifyIDToken(response.getIdToken()); // Verify attribute is filled Map<String, Object> roleMappings = (Map<String, Object>)idToken.getOtherClaims().get("roles-custom"); Assert.assertThat(roleMappings.keySet(), containsInAnyOrder("realm", "test-app")); Assert.assertThat(roleMappings.get("realm"), CoreMatchers.instanceOf(List.class)); Assert.assertThat(roleMappings.get("test-app"), CoreMatchers.instanceOf(List.class)); List<String> realmRoleMappings = (List<String>) roleMappings.get("realm"); List<String> testAppMappings = (List<String>) roleMappings.get("test-app"); assertRoles(realmRoleMappings, "pref.user", // from direct assignment in user definition "pref.offline_access" // from direct assignment in user definition ); assertRoles(testAppMappings, "customer-user" // from direct assignment in user definition ); // Revert deleteMappers(protocolMappers); } /** * KEYCLOAK-5259 * @throws Exception */ @Test public void testUserRoleToAttributeMappersWithFullScopeDisabled() throws Exception { // Add mapper for realm roles ProtocolMapperRepresentation realmMapper = ProtocolMapperUtil.createUserRealmRoleMappingMapper("pref.", "Realm roles mapper", "roles-custom.realm", true, true, true); ProtocolMapperRepresentation clientMapper = ProtocolMapperUtil.createUserClientRoleMappingMapper("test-app", null, "Client roles mapper", "roles-custom.test-app", true, true, true); ClientResource client = ApiUtil.findClientResourceByClientId(adminClient.realm("test"), "test-app"); // Disable full-scope-allowed ClientRepresentation rep = client.toRepresentation(); rep.setFullScopeAllowed(false); client.update(rep); ProtocolMappersResource protocolMappers = ApiUtil.findClientResourceByClientId(adminClient.realm("test"), "test-app").getProtocolMappers(); protocolMappers.createMapper(Arrays.asList(realmMapper, clientMapper)); // Login user OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password"); IDToken idToken = oauth.verifyIDToken(response.getIdToken()); // Verify attribute is filled Map<String, Object> roleMappings = (Map<String, Object>)idToken.getOtherClaims().get("roles-custom"); Assert.assertThat(roleMappings.keySet(), containsInAnyOrder("realm", "test-app")); Assert.assertThat(roleMappings.get("realm"), CoreMatchers.instanceOf(List.class)); Assert.assertThat(roleMappings.get("test-app"), CoreMatchers.instanceOf(List.class)); List<String> realmRoleMappings = (List<String>) roleMappings.get("realm"); List<String> testAppMappings = (List<String>) roleMappings.get("test-app"); assertRoles(realmRoleMappings, "pref.user" // from direct assignment in user definition ); assertRoles(testAppMappings, "customer-user" // from direct assignment in user definition ); // Revert deleteMappers(protocolMappers); rep = client.toRepresentation(); rep.setFullScopeAllowed(true); client.update(rep); } // KEYCLOAK-8148 -- Test the scenario where: // -- user is member of 2 groups // -- both groups have same role "customer-user" assigned // -- User login. Role will appear just once in the token (not twice) @Test public void testRoleMapperWithRoleInheritedFromMoreGroups() throws Exception { // Create client-mapper String clientId = "test-app"; ProtocolMapperRepresentation clientMapper = ProtocolMapperUtil.createUserClientRoleMappingMapper(clientId, null, "Client roles mapper", "roles-custom.test-app", true, true); ProtocolMappersResource protocolMappers = ApiUtil.findClientResourceByClientId(adminClient.realm("test"), clientId).getProtocolMappers(); protocolMappers.createMapper(Arrays.asList(clientMapper)); // Add user 'level2GroupUser' to the group 'level2Group2' GroupRepresentation level2Group2 = adminClient.realm("test").getGroupByPath("/topGroup/level2group2"); UserResource level2GroupUser = ApiUtil.findUserByUsernameId(adminClient.realm("test"), "level2GroupUser"); level2GroupUser.joinGroup(level2Group2.getId()); oauth.clientId(clientId); OAuthClient.AccessTokenResponse response = browserLogin("password", "level2GroupUser", "password"); IDToken idToken = oauth.verifyIDToken(response.getIdToken()); // Verify attribute is filled AND it is filled only once Map<String, Object> roleMappings = (Map<String, Object>)idToken.getOtherClaims().get("roles-custom"); Assert.assertThat(roleMappings.keySet(), containsInAnyOrder(clientId)); String testAppScopeMappings = (String) roleMappings.get(clientId); assertRolesString(testAppScopeMappings, "customer-user" // from assignment to level2group or level2group2. It is filled just once ); // Revert level2GroupUser.leaveGroup(level2Group2.getId()); deleteMappers(protocolMappers); } @Test public void testUserGroupRoleToAttributeMappers() throws Exception { // Add mapper for realm roles String clientId = "test-app"; ProtocolMapperRepresentation realmMapper = ProtocolMapperUtil.createUserRealmRoleMappingMapper("pref.", "Realm roles mapper", "roles-custom.realm", true, true); ProtocolMapperRepresentation clientMapper = ProtocolMapperUtil.createUserClientRoleMappingMapper(clientId, "ta.", "Client roles mapper", "roles-custom.test-app", true, true); ProtocolMappersResource protocolMappers = ApiUtil.findClientResourceByClientId(adminClient.realm("test"), clientId).getProtocolMappers(); protocolMappers.createMapper(Arrays.asList(realmMapper, clientMapper)); // Login user OAuthClient.AccessTokenResponse response = browserLogin("password", "rich.roles@redhat.com", "password"); IDToken idToken = oauth.verifyIDToken(response.getIdToken()); // Verify attribute is filled Map<String, Object> roleMappings = (Map<String, Object>)idToken.getOtherClaims().get("roles-custom"); Assert.assertThat(roleMappings.keySet(), containsInAnyOrder("realm", clientId)); String realmRoleMappings = (String) roleMappings.get("realm"); String testAppMappings = (String) roleMappings.get(clientId); assertRolesString(realmRoleMappings, "pref.admin", // from direct assignment to /roleRichGroup/level2group "pref.user", // from parent group of /roleRichGroup/level2group, i.e. from /roleRichGroup "pref.customer-user-premium", // from client role customer-admin-composite-role - realm role for test-app "pref.realm-composite-role", // from parent group of /roleRichGroup/level2group, i.e. from /roleRichGroup "pref.sample-realm-role" // from realm role realm-composite-role ); assertRolesString(testAppMappings, "ta.customer-user", // from direct assignment to /roleRichGroup/level2group "ta.customer-admin-composite-role", // from direct assignment to /roleRichGroup/level2group "ta.customer-admin", // from client role customer-admin-composite-role - client role for test-app "ta.sample-client-role" // from realm role realm-composite-role - client role for test-app ); // Revert deleteMappers(protocolMappers); } @Test public void testUserGroupRoleToAttributeMappersNotScopedOtherApp() throws Exception { String clientId = "test-app-authz"; ProtocolMapperRepresentation realmMapper = ProtocolMapperUtil.createUserRealmRoleMappingMapper("pref.", "Realm roles mapper", "roles-custom.realm", true, true); ProtocolMapperRepresentation clientMapper = ProtocolMapperUtil.createUserClientRoleMappingMapper(clientId, null, "Client roles mapper", "roles-custom." + clientId, true, true); ProtocolMappersResource protocolMappers = ApiUtil.findClientResourceByClientId(adminClient.realm("test"), clientId).getProtocolMappers(); protocolMappers.createMapper(Arrays.asList(realmMapper, clientMapper)); // Login user ClientManager.realm(adminClient.realm("test")).clientId(clientId).directAccessGrant(true); oauth.clientId(clientId); String oldRedirectUri = oauth.getRedirectUri(); oauth.redirectUri(UriUtils.getOrigin(oldRedirectUri) + "/test-app-authz"); OAuthClient.AccessTokenResponse response = browserLogin("secret", "rich.roles@redhat.com", "password"); IDToken idToken = oauth.verifyIDToken(response.getIdToken()); // revert redirect_uri oauth.redirectUri(oldRedirectUri); // Verify attribute is filled Map<String, Object> roleMappings = (Map<String, Object>)idToken.getOtherClaims().get("roles-custom"); Assert.assertThat(roleMappings.keySet(), containsInAnyOrder("realm")); String realmRoleMappings = (String) roleMappings.get("realm"); String testAppAuthzMappings = (String) roleMappings.get(clientId); assertRolesString(realmRoleMappings, "pref.admin", // from direct assignment to /roleRichGroup/level2group "pref.user", // from parent group of /roleRichGroup/level2group, i.e. from /roleRichGroup "pref.customer-user-premium", // from client role customer-admin-composite-role - realm role for test-app "pref.realm-composite-role", // from parent group of /roleRichGroup/level2group, i.e. from /roleRichGroup "pref.sample-realm-role" // from realm role realm-composite-role ); assertNull(testAppAuthzMappings); // There is no client role defined for test-app-authz // Revert deleteMappers(protocolMappers); } @Test public void testUserGroupRoleToAttributeMappersScoped() throws Exception { String clientId = "test-app-scope"; ProtocolMapperRepresentation realmMapper = ProtocolMapperUtil.createUserRealmRoleMappingMapper("pref.", "Realm roles mapper", "roles-custom.realm", true, true); ProtocolMapperRepresentation clientMapper = ProtocolMapperUtil.createUserClientRoleMappingMapper(clientId, null, "Client roles mapper", "roles-custom.test-app-scope", true, true); ProtocolMappersResource protocolMappers = ApiUtil.findClientResourceByClientId(adminClient.realm("test"), clientId).getProtocolMappers(); protocolMappers.createMapper(Arrays.asList(realmMapper, clientMapper)); // Login user ClientManager.realm(adminClient.realm("test")).clientId(clientId).directAccessGrant(true); oauth.clientId(clientId); OAuthClient.AccessTokenResponse response = browserLogin("password", "rich.roles@redhat.com", "password"); IDToken idToken = oauth.verifyIDToken(response.getIdToken()); // Verify attribute is filled Map<String, Object> roleMappings = (Map<String, Object>)idToken.getOtherClaims().get("roles-custom"); Assert.assertThat(roleMappings.keySet(), containsInAnyOrder("realm", clientId)); String realmRoleMappings = (String) roleMappings.get("realm"); String testAppScopeMappings = (String) roleMappings.get(clientId); assertRolesString(realmRoleMappings, "pref.admin", // from direct assignment to /roleRichGroup/level2group "pref.user", // from parent group of /roleRichGroup/level2group, i.e. from /roleRichGroup "pref.customer-user-premium" ); assertRolesString(testAppScopeMappings, "test-app-allowed-by-scope", // from direct assignment to roleRichUser, present as scope allows it "test-app-disallowed-by-scope" ); // Revert deleteMappers(protocolMappers); } @Test public void testUserGroupRoleToAttributeMappersScopedClientNotSet() throws Exception { String clientId = "test-app-scope"; ProtocolMapperRepresentation realmMapper = ProtocolMapperUtil.createUserRealmRoleMappingMapper("pref.", "Realm roles mapper", "roles-custom.realm", true, true); ProtocolMapperRepresentation clientMapper = ProtocolMapperUtil.createUserClientRoleMappingMapper(null, null, "Client roles mapper", "roles-custom.test-app-scope", true, true); ProtocolMappersResource protocolMappers = ApiUtil.findClientResourceByClientId(adminClient.realm("test"), clientId).getProtocolMappers(); protocolMappers.createMapper(Arrays.asList(realmMapper, clientMapper)); // Login user ClientManager.realm(adminClient.realm("test")).clientId(clientId).directAccessGrant(true); oauth.clientId(clientId); OAuthClient.AccessTokenResponse response = browserLogin("password", "rich.roles@redhat.com", "password"); IDToken idToken = oauth.verifyIDToken(response.getIdToken()); // Verify attribute is filled Map<String, Object> roleMappings = (Map<String, Object>)idToken.getOtherClaims().get("roles-custom"); Assert.assertThat(roleMappings.keySet(), containsInAnyOrder("realm", clientId)); String realmRoleMappings = (String) roleMappings.get("realm"); String testAppScopeMappings = (String) roleMappings.get(clientId); assertRolesString(realmRoleMappings, "pref.admin", // from direct assignment to /roleRichGroup/level2group "pref.user", // from parent group of /roleRichGroup/level2group, i.e. from /roleRichGroup "pref.customer-user-premium" ); assertRolesString(testAppScopeMappings, "test-app-allowed-by-scope", // from direct assignment to roleRichUser, present as scope allows it "test-app-disallowed-by-scope" // from direct assignment to /roleRichGroup/level2group, present as scope allows it ); // Revert deleteMappers(protocolMappers); } @Test public void testGroupAttributeUserOneGroupNoMultivalueNoAggregate() throws Exception { // get the user UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost"); UserRepresentation user = userResource.toRepresentation(); user.setAttributes(new HashMap<>()); user.getAttributes().put("group-value", Arrays.asList("user-value1", "user-value2")); userResource.update(user); // create a group1 with two values GroupRepresentation group1 = new GroupRepresentation(); group1.setName("group1"); group1.setAttributes(new HashMap<>()); group1.getAttributes().put("group-value", Arrays.asList("value1", "value2")); adminClient.realm("test").groups().add(group1); group1 = adminClient.realm("test").getGroupByPath("/group1"); userResource.joinGroup(group1.getId()); // create the attribute mapper ProtocolMappersResource protocolMappers = findClientResourceByClientId(adminClient.realm("test"), "test-app").getProtocolMappers(); protocolMappers.createMapper(createClaimMapper("group-value", "group-value", "group-value", "String", true, true, false, false)).close(); try { // test it OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password"); IDToken idToken = oauth.verifyIDToken(response.getIdToken()); assertNotNull(idToken.getOtherClaims()); assertNotNull(idToken.getOtherClaims().get("group-value")); assertTrue(idToken.getOtherClaims().get("group-value") instanceof String); assertTrue("user-value1".equals(idToken.getOtherClaims().get("group-value")) || "user-value2".equals(idToken.getOtherClaims().get("group-value"))); } finally { // revert user.getAttributes().remove("group-value"); userResource.update(user); userResource.leaveGroup(group1.getId()); adminClient.realm("test").groups().group(group1.getId()).remove(); deleteMappers(protocolMappers); } } @Test public void testGroupAttributeUserOneGroupMultivalueNoAggregate() throws Exception { // get the user UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost"); UserRepresentation user = userResource.toRepresentation(); user.setAttributes(new HashMap<>()); user.getAttributes().put("group-value", Arrays.asList("user-value1", "user-value2")); userResource.update(user); // create a group1 with two values GroupRepresentation group1 = new GroupRepresentation(); group1.setName("group1"); group1.setAttributes(new HashMap<>()); group1.getAttributes().put("group-value", Arrays.asList("value1", "value2")); adminClient.realm("test").groups().add(group1); group1 = adminClient.realm("test").getGroupByPath("/group1"); userResource.joinGroup(group1.getId()); // create the attribute mapper ProtocolMappersResource protocolMappers = findClientResourceByClientId(adminClient.realm("test"), "test-app").getProtocolMappers(); protocolMappers.createMapper(createClaimMapper("group-value", "group-value", "group-value", "String", true, true, true, false)).close(); try { // test it OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password"); IDToken idToken = oauth.verifyIDToken(response.getIdToken()); assertNotNull(idToken.getOtherClaims()); assertNotNull(idToken.getOtherClaims().get("group-value")); assertTrue(idToken.getOtherClaims().get("group-value") instanceof List); assertEquals(2, ((List) idToken.getOtherClaims().get("group-value")).size()); assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("user-value1")); assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("user-value2")); } finally { // revert user.getAttributes().remove("group-value"); userResource.update(user); userResource.leaveGroup(group1.getId()); adminClient.realm("test").groups().group(group1.getId()).remove(); deleteMappers(protocolMappers); } } @Test public void testGroupAttributeUserOneGroupMultivalueAggregate() throws Exception { // get the user UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost"); UserRepresentation user = userResource.toRepresentation(); user.setAttributes(new HashMap<>()); user.getAttributes().put("group-value", Arrays.asList("user-value1", "user-value2")); userResource.update(user); // create a group1 with two values GroupRepresentation group1 = new GroupRepresentation(); group1.setName("group1"); group1.setAttributes(new HashMap<>()); group1.getAttributes().put("group-value", Arrays.asList("value1", "value2")); adminClient.realm("test").groups().add(group1); group1 = adminClient.realm("test").getGroupByPath("/group1"); userResource.joinGroup(group1.getId()); // create the attribute mapper ProtocolMappersResource protocolMappers = findClientResourceByClientId(adminClient.realm("test"), "test-app").getProtocolMappers(); protocolMappers.createMapper(createClaimMapper("group-value", "group-value", "group-value", "String", true, true, true, true)).close(); try { // test it OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password"); IDToken idToken = oauth.verifyIDToken(response.getIdToken()); assertNotNull(idToken.getOtherClaims()); assertNotNull(idToken.getOtherClaims().get("group-value")); assertTrue(idToken.getOtherClaims().get("group-value") instanceof List); assertEquals(4, ((List) idToken.getOtherClaims().get("group-value")).size()); assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("user-value1")); assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("user-value2")); assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("value1")); assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("value2")); } finally { // revert user.getAttributes().remove("group-value"); userResource.update(user); userResource.leaveGroup(group1.getId()); adminClient.realm("test").groups().group(group1.getId()).remove(); deleteMappers(protocolMappers); } } @Test public void testGroupAttributeOneGroupNoMultivalueNoAggregate() throws Exception { // get the user UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost"); // create a group1 with two values GroupRepresentation group1 = new GroupRepresentation(); group1.setName("group1"); group1.setAttributes(new HashMap<>()); group1.getAttributes().put("group-value", Arrays.asList("value1", "value2")); adminClient.realm("test").groups().add(group1); group1 = adminClient.realm("test").getGroupByPath("/group1"); userResource.joinGroup(group1.getId()); // create the attribute mapper ProtocolMappersResource protocolMappers = findClientResourceByClientId(adminClient.realm("test"), "test-app").getProtocolMappers(); protocolMappers.createMapper(createClaimMapper("group-value", "group-value", "group-value", "String", true, true, false, false)).close(); try { // test it OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password"); IDToken idToken = oauth.verifyIDToken(response.getIdToken()); assertNotNull(idToken.getOtherClaims()); assertNotNull(idToken.getOtherClaims().get("group-value")); assertTrue(idToken.getOtherClaims().get("group-value") instanceof String); assertTrue("value1".equals(idToken.getOtherClaims().get("group-value")) || "value2".equals(idToken.getOtherClaims().get("group-value"))); } finally { // revert userResource.leaveGroup(group1.getId()); adminClient.realm("test").groups().group(group1.getId()).remove(); deleteMappers(protocolMappers); } } @Test public void testGroupAttributeOneGroupMultiValueNoAggregate() throws Exception { // get the user UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost"); // create a group1 with two values GroupRepresentation group1 = new GroupRepresentation(); group1.setName("group1"); group1.setAttributes(new HashMap<>()); group1.getAttributes().put("group-value", Arrays.asList("value1", "value2")); adminClient.realm("test").groups().add(group1); group1 = adminClient.realm("test").getGroupByPath("/group1"); userResource.joinGroup(group1.getId()); // create the attribute mapper ProtocolMappersResource protocolMappers = findClientResourceByClientId(adminClient.realm("test"), "test-app").getProtocolMappers(); protocolMappers.createMapper(createClaimMapper("group-value", "group-value", "group-value", "String", true, true, true, false)).close(); try { // test it OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password"); IDToken idToken = oauth.verifyIDToken(response.getIdToken()); assertNotNull(idToken.getOtherClaims()); assertNotNull(idToken.getOtherClaims().get("group-value")); assertTrue(idToken.getOtherClaims().get("group-value") instanceof List); assertEquals(2, ((List) idToken.getOtherClaims().get("group-value")).size()); assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("value1")); assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("value2")); } finally { // revert userResource.leaveGroup(group1.getId()); adminClient.realm("test").groups().group(group1.getId()).remove(); deleteMappers(protocolMappers); } } @Test public void testGroupAttributeOneGroupMultiValueAggregate() throws Exception { // get the user UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost"); // create a group1 with two values GroupRepresentation group1 = new GroupRepresentation(); group1.setName("group1"); group1.setAttributes(new HashMap<>()); group1.getAttributes().put("group-value", Arrays.asList("value1", "value2")); adminClient.realm("test").groups().add(group1); group1 = adminClient.realm("test").getGroupByPath("/group1"); userResource.joinGroup(group1.getId()); // create the attribute mapper ProtocolMappersResource protocolMappers = findClientResourceByClientId(adminClient.realm("test"), "test-app").getProtocolMappers(); protocolMappers.createMapper(createClaimMapper("group-value", "group-value", "group-value", "String", true, true, true, true)).close(); try { // test it OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password"); IDToken idToken = oauth.verifyIDToken(response.getIdToken()); assertNotNull(idToken.getOtherClaims()); assertNotNull(idToken.getOtherClaims().get("group-value")); assertTrue(idToken.getOtherClaims().get("group-value") instanceof List); assertEquals(2, ((List) idToken.getOtherClaims().get("group-value")).size()); assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("value1")); assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("value2")); } finally { // revert userResource.leaveGroup(group1.getId()); adminClient.realm("test").groups().group(group1.getId()).remove(); deleteMappers(protocolMappers); } } @Test public void testGroupAttributeTwoGroupNoMultivalueNoAggregate() throws Exception { // get the user UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost"); // create two groups with two values (one is the same value) GroupRepresentation group1 = new GroupRepresentation(); group1.setName("group1"); group1.setAttributes(new HashMap<>()); group1.getAttributes().put("group-value", Arrays.asList("value1", "value2")); adminClient.realm("test").groups().add(group1); group1 = adminClient.realm("test").getGroupByPath("/group1"); userResource.joinGroup(group1.getId()); GroupRepresentation group2 = new GroupRepresentation(); group2.setName("group2"); group2.setAttributes(new HashMap<>()); group2.getAttributes().put("group-value", Arrays.asList("value2", "value3")); adminClient.realm("test").groups().add(group2); group2 = adminClient.realm("test").getGroupByPath("/group2"); userResource.joinGroup(group2.getId()); // create the attribute mapper ProtocolMappersResource protocolMappers = findClientResourceByClientId(adminClient.realm("test"), "test-app").getProtocolMappers(); protocolMappers.createMapper(createClaimMapper("group-value", "group-value", "group-value", "String", true, true, false, false)).close(); try { // test it OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password"); IDToken idToken = oauth.verifyIDToken(response.getIdToken()); assertNotNull(idToken.getOtherClaims()); assertNotNull(idToken.getOtherClaims().get("group-value")); assertTrue(idToken.getOtherClaims().get("group-value") instanceof String); assertTrue("value1".equals(idToken.getOtherClaims().get("group-value")) || "value2".equals(idToken.getOtherClaims().get("group-value")) || "value3".equals(idToken.getOtherClaims().get("group-value"))); } finally { // revert userResource.leaveGroup(group1.getId()); adminClient.realm("test").groups().group(group1.getId()).remove(); userResource.leaveGroup(group2.getId()); adminClient.realm("test").groups().group(group2.getId()).remove(); deleteMappers(protocolMappers); } } @Test public void testGroupAttributeTwoGroupMultiValueNoAggregate() throws Exception { // get the user UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost"); // create two groups with two values (one is the same value) GroupRepresentation group1 = new GroupRepresentation(); group1.setName("group1"); group1.setAttributes(new HashMap<>()); group1.getAttributes().put("group-value", Arrays.asList("value1", "value2")); adminClient.realm("test").groups().add(group1); group1 = adminClient.realm("test").getGroupByPath("/group1"); userResource.joinGroup(group1.getId()); GroupRepresentation group2 = new GroupRepresentation(); group2.setName("group2"); group2.setAttributes(new HashMap<>()); group2.getAttributes().put("group-value", Arrays.asList("value2", "value3")); adminClient.realm("test").groups().add(group2); group2 = adminClient.realm("test").getGroupByPath("/group2"); userResource.joinGroup(group2.getId()); // create the attribute mapper ProtocolMappersResource protocolMappers = findClientResourceByClientId(adminClient.realm("test"), "test-app").getProtocolMappers(); protocolMappers.createMapper(createClaimMapper("group-value", "group-value", "group-value", "String", true, true, true, false)).close(); try { // test it OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password"); IDToken idToken = oauth.verifyIDToken(response.getIdToken()); assertNotNull(idToken.getOtherClaims()); assertNotNull(idToken.getOtherClaims().get("group-value")); assertTrue(idToken.getOtherClaims().get("group-value") instanceof List); assertEquals(2, ((List) idToken.getOtherClaims().get("group-value")).size()); assertTrue((((List) idToken.getOtherClaims().get("group-value")).contains("value1") && ((List) idToken.getOtherClaims().get("group-value")).contains("value2")) || (((List) idToken.getOtherClaims().get("group-value")).contains("value2") && ((List) idToken.getOtherClaims().get("group-value")).contains("value3"))); } finally { // revert userResource.leaveGroup(group1.getId()); adminClient.realm("test").groups().group(group1.getId()).remove(); userResource.leaveGroup(group2.getId()); adminClient.realm("test").groups().group(group2.getId()).remove(); deleteMappers(protocolMappers); } } @Test public void testGroupAttributeTwoGroupMultiValueAggregate() throws Exception { // get the user UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost"); // create two groups with two values (one is the same value) GroupRepresentation group1 = new GroupRepresentation(); group1.setName("group1"); group1.setAttributes(new HashMap<>()); group1.getAttributes().put("group-value", Arrays.asList("value1", "value2")); adminClient.realm("test").groups().add(group1); group1 = adminClient.realm("test").getGroupByPath("/group1"); userResource.joinGroup(group1.getId()); GroupRepresentation group2 = new GroupRepresentation(); group2.setName("group2"); group2.setAttributes(new HashMap<>()); group2.getAttributes().put("group-value", Arrays.asList("value2", "value3")); adminClient.realm("test").groups().add(group2); group2 = adminClient.realm("test").getGroupByPath("/group2"); userResource.joinGroup(group2.getId()); // create the attribute mapper ProtocolMappersResource protocolMappers = findClientResourceByClientId(adminClient.realm("test"), "test-app").getProtocolMappers(); protocolMappers.createMapper(createClaimMapper("group-value", "group-value", "group-value", "String", true, true, true, true)).close(); try { // test it OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password"); IDToken idToken = oauth.verifyIDToken(response.getIdToken()); assertNotNull(idToken.getOtherClaims()); assertNotNull(idToken.getOtherClaims().get("group-value")); assertTrue(idToken.getOtherClaims().get("group-value") instanceof List); assertEquals(3, ((List) idToken.getOtherClaims().get("group-value")).size()); assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("value1")); assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("value2")); assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("value3")); } finally { // revert userResource.leaveGroup(group1.getId()); adminClient.realm("test").groups().group(group1.getId()).remove(); userResource.leaveGroup(group2.getId()); adminClient.realm("test").groups().group(group2.getId()).remove(); deleteMappers(protocolMappers); } } private void assertRoles(List<String> actualRoleList, String ...expectedRoles){ Assert.assertNames(actualRoleList, expectedRoles); } private void assertRolesString(String actualRoleString, String...expectedRoles) { Assert.assertThat(actualRoleString.matches("^\\[.*\\]$"), is(true)); String[] roles = actualRoleString.substring(1, actualRoleString.length() - 1).split(",\\s*"); if (expectedRoles == null || expectedRoles.length == 0) { Assert.assertThat(roles, arrayContainingInAnyOrder("")); } else { Assert.assertThat(roles, arrayContainingInAnyOrder(expectedRoles)); } } private ProtocolMapperRepresentation makeMapper(String name, String mapperType, Map<String, String> config) { ProtocolMapperRepresentation rep = new ProtocolMapperRepresentation(); rep.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL); rep.setName(name); rep.setProtocolMapper(mapperType); rep.setConfig(config); return rep; } private OAuthClient.AccessTokenResponse browserLogin(String clientSecret, String username, String password) { OAuthClient.AuthorizationEndpointResponse authzEndpointResponse = oauth.doLogin(username, password); return oauth.doAccessTokenRequest(authzEndpointResponse.getCode(), clientSecret); } }
/* * Copyright (c) 2016 Google, Inc. * * 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.truth.extensions.proto; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.extensions.proto.ProtoLiteSubject.assertThat; import static com.google.common.truth.extensions.proto.ProtoLiteSubject.protoLite; import static org.junit.Assert.fail; import com.google.auto.value.AutoValue; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.google.common.truth.Expect; import com.google.common.truth.Subject; import com.google.protobuf.MessageLite; import com.google.protobuf.MessageLiteOrBuilder; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; import java.util.regex.Pattern; import javax.annotation.Nullable; /** Unit tests for {@link ProtoLiteSubject}. */ @RunWith(Parameterized.class) public class ProtoLiteSubjectTest { /** * We run (almost) all the tests for both proto2 and proto3 implementations. This class organizes * the parameters much more cleanly than a raw Object[]. */ @AutoValue public abstract static class Config { abstract MessageLite nonEmptyMessage(); abstract MessageLite equivalentNonEmptyMessage(); abstract MessageLite nonEmptyMessageOfOtherValue(); abstract MessageLite nonEmptyMessageOfOtherType(); abstract MessageLite defaultInstance(); abstract MessageLite defaultInstanceOfOtherType(); abstract Optional<MessageLite> messageWithoutRequiredFields(); public static Builder newBuilder() { return new AutoValue_ProtoLiteSubjectTest_Config.Builder(); } @AutoValue.Builder public abstract static class Builder { abstract Builder setNonEmptyMessage(MessageLite messageLite); abstract Builder setEquivalentNonEmptyMessage(MessageLite messageLite); abstract Builder setNonEmptyMessageOfOtherValue(MessageLite messageLite); abstract Builder setNonEmptyMessageOfOtherType(MessageLite messageLite); abstract Builder setDefaultInstance(MessageLite messageLite); abstract Builder setDefaultInstanceOfOtherType(MessageLite messageLite); abstract Builder setMessageWithoutRequiredFields(MessageLite messageLite); abstract Config build(); } } @Parameters(name = "{0}") public static Collection<Object[]> data() { // Missing a required_int field. TestMessageLite2WithRequiredFields withoutRequiredFields = TestMessageLite2WithRequiredFields.newBuilder().setOptionalString("foo").buildPartial(); Config proto2Config = Config.newBuilder() .setNonEmptyMessage(TestMessageLite2.newBuilder().setOptionalInt(3).build()) .setEquivalentNonEmptyMessage(TestMessageLite2.newBuilder().setOptionalInt(3).build()) .setNonEmptyMessageOfOtherValue( TestMessageLite2.newBuilder() .setOptionalInt(3) .setSubMessage( TestMessageLite2.SubMessage.newBuilder().setOptionalString("foo")) .build()) .setNonEmptyMessageOfOtherType( OtherTestMessageLite2.newBuilder().setOptionalInt(3).build()) .setDefaultInstance(TestMessageLite2.newBuilder().buildPartial()) .setDefaultInstanceOfOtherType(OtherTestMessageLite2.newBuilder().buildPartial()) .setMessageWithoutRequiredFields(withoutRequiredFields) .build(); Config proto3Config = Config.newBuilder() .setNonEmptyMessage(TestMessageLite3.newBuilder().setOptionalInt(3).build()) .setEquivalentNonEmptyMessage(TestMessageLite3.newBuilder().setOptionalInt(3).build()) .setNonEmptyMessageOfOtherValue( TestMessageLite3.newBuilder() .setOptionalInt(3) .setSubMessage( TestMessageLite3.SubMessage.newBuilder().setOptionalString("foo")) .build()) .setNonEmptyMessageOfOtherType( OtherTestMessageLite3.newBuilder().setOptionalInt(3).build()) .setDefaultInstance(TestMessageLite3.newBuilder().buildPartial()) .setDefaultInstanceOfOtherType(OtherTestMessageLite3.newBuilder().buildPartial()) .build(); return ImmutableList.of( new Object[] {"Proto 2", proto2Config}, new Object[] {"Proto 3", proto3Config}); } @Rule public final Expect expect = Expect.create(); private final Config config; public ProtoLiteSubjectTest(@SuppressWarnings("unused") String name, Config config) { this.config = config; } private ProtoLiteSubject<?, ?> expectThat(@Nullable MessageLite m) { return expect.about(protoLite()).that(m); } private Subject<?, ?> expectThat(@Nullable Object o) { return expect.that(o); } @Test public void testSubjectMethods() { expectThat(config.nonEmptyMessage()).isSameAs(config.nonEmptyMessage()); expectThat(config.nonEmptyMessage().toBuilder()).isNotSameAs(config.nonEmptyMessage()); expectThat(config.nonEmptyMessage()).isInstanceOf(MessageLite.class); expectThat(config.nonEmptyMessage().toBuilder()).isInstanceOf(MessageLite.Builder.class); expectThat(config.nonEmptyMessage()).isNotInstanceOf(MessageLite.Builder.class); expectThat(config.nonEmptyMessage().toBuilder()).isNotInstanceOf(MessageLite.class); expectThat(config.nonEmptyMessage()).isIn(Arrays.asList(config.nonEmptyMessage())); expectThat(config.nonEmptyMessage()) .isNotIn(Arrays.asList(config.nonEmptyMessageOfOtherValue())); expectThat(config.nonEmptyMessage()) .isAnyOf(config.nonEmptyMessage(), config.nonEmptyMessageOfOtherValue()); expectThat(config.nonEmptyMessage()) .isNoneOf(config.nonEmptyMessageOfOtherValue(), config.nonEmptyMessageOfOtherType()); } @Test public void testIsEqualTo_success() { expectThat(null).isEqualTo(null); expectThat(null).isNull(); expectThat(config.nonEmptyMessage()).isEqualTo(config.nonEmptyMessage()); expectThat(config.nonEmptyMessage()).isEqualTo(config.equivalentNonEmptyMessage()); expectThat(config.nonEmptyMessage()).isNotEqualTo(config.nonEmptyMessage().toBuilder()); assertThat(config.defaultInstance()).isNotEqualTo(config.defaultInstanceOfOtherType()); assertThat(config.nonEmptyMessage()).isNotEqualTo(config.nonEmptyMessageOfOtherType()); assertThat(config.nonEmptyMessage()).isNotEqualTo(config.nonEmptyMessageOfOtherValue()); } @Test public void testIsEqualTo_failure() { try { assertThat(config.nonEmptyMessage()).isEqualTo(config.nonEmptyMessageOfOtherValue()); fail("Should have failed."); } catch (AssertionError e) { expectRegex(e, ".*expected:.*\"foo\".*"); expectNoRegex(e, ".*but was:.*\"foo\".*"); } try { assertThat(config.nonEmptyMessage()).isEqualTo(config.nonEmptyMessageOfOtherType()); fail("Should have failed."); } catch (AssertionError e) { expectRegex(e, ".*expected:.*\\[Other\\]TestMessage.*but was:.*\\[\\]TestMessage.*"); } try { assertThat(config.nonEmptyMessage()).isNotEqualTo(config.equivalentNonEmptyMessage()); fail("Should have failed."); } catch (AssertionError e) { expectRegex( e, String.format( "Not true that protos are different\\.\\s*Both are \\(%s\\) <.*optional_int: 3.*>\\.", Pattern.quote(config.nonEmptyMessage().getClass().getName()))); } } @Test public void testHasAllRequiredFields_success() { expectThat(config.nonEmptyMessage()).hasAllRequiredFields(); } @Test public void testHasAllRequiredFields_failures() { if (!config.messageWithoutRequiredFields().isPresent()) { return; } try { assertThat(config.messageWithoutRequiredFields().get()).hasAllRequiredFields(); fail("Should have failed."); } catch (AssertionError e) { expectRegex( e, "Not true that <.*> has all required fields set\\.\\s*" + "\\(Lite runtime could not determine which fields were missing\\.\\)"); } } @Test public void testDefaultInstance_success() { expectThat(config.defaultInstance()).isEqualToDefaultInstance(); expectThat(config.defaultInstanceOfOtherType()).isEqualToDefaultInstance(); expectThat(config.nonEmptyMessage().getDefaultInstanceForType()).isEqualToDefaultInstance(); expectThat(null).isNotEqualToDefaultInstance(); expectThat(config.nonEmptyMessage()).isNotEqualToDefaultInstance(); } @Test public void testDefaultInstance_failure() { try { assertThat(config.nonEmptyMessage()).isEqualToDefaultInstance(); fail("Should have failed."); } catch (AssertionError e) { expectRegex( e, "Not true that <.*optional_int:\\s*3.*> is a default proto instance\\.\\s*" + "It has set values\\."); } try { assertThat(config.defaultInstance()).isNotEqualToDefaultInstance(); fail("Should have failed."); } catch (AssertionError e) { expectRegex( e, String.format( "Not true that \\(%s\\) <.*\\[empty proto\\].*> is not a default " + "proto instance\\.\\s*It has no set values\\.", Pattern.quote(config.defaultInstance().getClass().getName()))); } } @Test public void testSerializedSize_success() { int size = config.nonEmptyMessage().getSerializedSize(); expectThat(config.nonEmptyMessage()).serializedSize().isEqualTo(size); expectThat(config.defaultInstance()).serializedSize().isEqualTo(0); } @Test public void testSerializedSize_failure() { int size = config.nonEmptyMessage().getSerializedSize(); try { assertThat(config.nonEmptyMessage()).serializedSize().isGreaterThan(size); fail("Should have failed."); } catch (AssertionError e) { expectRegex( e, "Not true that sizeOf\\(<.*optional_int:\\s*3.*>\\) \\(<2>\\) " + "is greater than <2>"); } try { assertThat(config.defaultInstance()).serializedSize().isGreaterThan(0); fail("Should have failed."); } catch (AssertionError e) { expectRegex( e, "Not true that sizeOf\\(<.*\\[empty proto\\].*>\\) \\(<0>\\) " + "is greater than <0>"); } } // TODO(cgruber): These probably belong in ThrowableSubject. private void expectRegex(AssertionError e, String regex) { expect .withFailureMessage(String.format("Expected <%s> to match '%s'.", regex, e.getMessage())) .that(Pattern.compile(regex, Pattern.DOTALL).matcher(e.getMessage()).matches()) .isTrue(); } private void expectNoRegex(AssertionError e, String regex) { expect .withFailureMessage(String.format("Expected <%s> to match '%s'.", regex, e.getMessage())) .that(Pattern.compile(regex, Pattern.DOTALL).matcher(e.getMessage()).matches()) .isFalse(); } }
package shts.jp.android.nogifeed.common; import android.util.Log; import shts.jp.android.nogifeed.BuildConfig; /** * Android Log wrapper class that can use {@link String#format(String, Object...)} in logging message */ public class Logger { private static final boolean DEBUG = BuildConfig.BUILD_TYPE == "debug"; private static final String TAG = Logger.class.getSimpleName(); private static final String EMPTY = ""; /** * Send a VERBOSE log message. * @param tag * @param format * @param args * @return */ public static int v(String tag, String format, Object... args) { if (!DEBUG) return 0; return Log.v(tag, format(format, args)); } /** * Send a VERBOSE log message and log the exception. * @param tag * @param msg * @param e * @return */ public static int v(String tag, String msg, Throwable e) { if (!DEBUG) return 0; return Log.v(tag, msg, e); } /** * Send a VERBOSE log message and log the exception. * @param tag * @param format * @param e * @param args * @return */ public static int v(String tag, String format, Throwable e, Object... args) { if (!DEBUG) return 0; return Log.v(tag, format(format, args), e); } /** * Send a DEBUG log message. * @param tag * @param format * @param args * @return */ public static int d(String tag, String format, Object... args) { if (!DEBUG) return 0; return Log.d(tag, format(format, args)); } /** * Send a DEBUG log message and log the exception. * @param tag * @param msg * @param e * @return */ public static int d(String tag, String msg, Throwable e) { if (!DEBUG) return 0; return Log.d(tag, msg, e); } /** * Send a DEBUG log message and log the exception. * @param tag * @param format * @param e * @param args * @return */ public static int d(String tag, String format, Throwable e, Object... args) { if (!DEBUG) return 0; return Log.d(tag, format(format, args), e); } /** * Send a WARN log message. * @param tag * @param format * @param args * @return */ public static int w(String tag, String format, Object... args) { if (!DEBUG) return 0; return Log.w(tag, format(format, args)); } /** * Send a WARN log message and log the exception. * @param tag * @param msg * @param e * @return */ public static int w(String tag, String msg, Throwable e) { if (!DEBUG) return 0; return Log.w(tag, msg, e); } /** * Send a WARN log message and log the exception. * @param tag * @param format * @param e * @param args * @return */ public static int w(String tag, String format, Throwable e, Object... args) { if (!DEBUG) return 0; return Log.w(tag, format(format, args), e); } /** * Send a INFO log message. * @param tag * @param format * @param args * @return */ public static int i(String tag, String format, Object... args) { if (!DEBUG) return 0; return Log.i(tag, format(format, args)); } /** * Send a INFO log message and log the exception. * @param tag * @param msg * @param e * @return */ public static int i(String tag, String msg, Throwable e) { if (!DEBUG) return 0; return Log.i(tag, msg, e); } /** * Send a INFO log message and log the exception. * @param tag * @param format * @param e * @param args * @return */ public static int i(String tag, String format, Throwable e, Object... args) { if (!DEBUG) return 0; return Log.i(tag, format(format, args), e); } /** * Send a ERROR log message. * @param tag * @param format * @param args * @return */ public static int e(String tag, String format, Object... args) { if (!DEBUG) return 0; return Log.e(tag, format(format, args)); } /** * Send a ERROR log message and log the exception. * @param tag * @param msg * @param e * @return */ public static int e(String tag, String msg, Throwable e) { if (!DEBUG) return 0; return Log.e(tag, msg, e); } /** * Send a ERROR log message and log the exception. * @param tag * @param format * @param e * @param args * @return */ public static int e(String tag, String format, Throwable e, Object... args) { if (!DEBUG) return 0; return Log.e(tag, format(format, args), e); } private static String format(String format, Object... args) { try { return String.format(format == null ? EMPTY : format, args); } catch (RuntimeException e) { Logger.w(TAG, "format error. reason=%s, format=%s", e.getMessage(), format); return String.format(EMPTY, format); } } }
/** * <copyright> * * Copyright (c) 2010 SAP AG. * 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: * Reiner Hille-Doering (SAP AG) - initial API and implementation and/or initial documentation * * </copyright> */ package org.eclipse.bpmn2.impl; import com.google.gwt.user.client.rpc.GwtTransient; import org.eclipse.bpmn2.Bpmn2Package; import org.eclipse.bpmn2.Participant; import org.eclipse.bpmn2.ParticipantAssociation; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Participant Association</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.eclipse.bpmn2.impl.ParticipantAssociationImpl#getInnerParticipantRef <em>Inner Participant Ref</em>}</li> * <li>{@link org.eclipse.bpmn2.impl.ParticipantAssociationImpl#getOuterParticipantRef <em>Outer Participant Ref</em>}</li> * </ul> * * @generated */ public class ParticipantAssociationImpl extends BaseElementImpl implements ParticipantAssociation { /** * The cached value of the '{@link #getInnerParticipantRef() <em>Inner Participant Ref</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getInnerParticipantRef() * @generated * @ordered */ @GwtTransient protected Participant innerParticipantRef; /** * The cached value of the '{@link #getOuterParticipantRef() <em>Outer Participant Ref</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getOuterParticipantRef() * @generated * @ordered */ @GwtTransient protected Participant outerParticipantRef; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ParticipantAssociationImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Bpmn2Package.Literals.PARTICIPANT_ASSOCIATION; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Participant getInnerParticipantRef() { if (innerParticipantRef != null && innerParticipantRef.eIsProxy()) { InternalEObject oldInnerParticipantRef = (InternalEObject) innerParticipantRef; innerParticipantRef = (Participant) eResolveProxy(oldInnerParticipantRef); if (innerParticipantRef != oldInnerParticipantRef) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, Bpmn2Package.PARTICIPANT_ASSOCIATION__INNER_PARTICIPANT_REF, oldInnerParticipantRef, innerParticipantRef)); } } return innerParticipantRef; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Participant basicGetInnerParticipantRef() { return innerParticipantRef; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setInnerParticipantRef(Participant newInnerParticipantRef) { Participant oldInnerParticipantRef = innerParticipantRef; innerParticipantRef = newInnerParticipantRef; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bpmn2Package.PARTICIPANT_ASSOCIATION__INNER_PARTICIPANT_REF, oldInnerParticipantRef, innerParticipantRef)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Participant getOuterParticipantRef() { if (outerParticipantRef != null && outerParticipantRef.eIsProxy()) { InternalEObject oldOuterParticipantRef = (InternalEObject) outerParticipantRef; outerParticipantRef = (Participant) eResolveProxy(oldOuterParticipantRef); if (outerParticipantRef != oldOuterParticipantRef) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, Bpmn2Package.PARTICIPANT_ASSOCIATION__OUTER_PARTICIPANT_REF, oldOuterParticipantRef, outerParticipantRef)); } } return outerParticipantRef; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Participant basicGetOuterParticipantRef() { return outerParticipantRef; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setOuterParticipantRef(Participant newOuterParticipantRef) { Participant oldOuterParticipantRef = outerParticipantRef; outerParticipantRef = newOuterParticipantRef; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Bpmn2Package.PARTICIPANT_ASSOCIATION__OUTER_PARTICIPANT_REF, oldOuterParticipantRef, outerParticipantRef)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Bpmn2Package.PARTICIPANT_ASSOCIATION__INNER_PARTICIPANT_REF: if (resolve) return getInnerParticipantRef(); return basicGetInnerParticipantRef(); case Bpmn2Package.PARTICIPANT_ASSOCIATION__OUTER_PARTICIPANT_REF: if (resolve) return getOuterParticipantRef(); return basicGetOuterParticipantRef(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Bpmn2Package.PARTICIPANT_ASSOCIATION__INNER_PARTICIPANT_REF: setInnerParticipantRef((Participant) newValue); return; case Bpmn2Package.PARTICIPANT_ASSOCIATION__OUTER_PARTICIPANT_REF: setOuterParticipantRef((Participant) newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Bpmn2Package.PARTICIPANT_ASSOCIATION__INNER_PARTICIPANT_REF: setInnerParticipantRef((Participant) null); return; case Bpmn2Package.PARTICIPANT_ASSOCIATION__OUTER_PARTICIPANT_REF: setOuterParticipantRef((Participant) null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Bpmn2Package.PARTICIPANT_ASSOCIATION__INNER_PARTICIPANT_REF: return innerParticipantRef != null; case Bpmn2Package.PARTICIPANT_ASSOCIATION__OUTER_PARTICIPANT_REF: return outerParticipantRef != null; } return super.eIsSet(featureID); } } //ParticipantAssociationImpl
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.github.os72.protobuf261; import com.github.os72.protobuf261.LazyField.LazyIterator; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; /** * A class which represents an arbitrary set of fields of some message type. * This is used to implement {@link DynamicMessage}, and also to represent * extensions in {@link GeneratedMessage}. This class is package-private, * since outside users should probably be using {@link DynamicMessage}. * * @author kenton@google.com Kenton Varda */ final class FieldSet<FieldDescriptorType extends FieldSet.FieldDescriptorLite<FieldDescriptorType>> { /** * Interface for a FieldDescriptor or lite extension descriptor. This * prevents FieldSet from depending on {@link Descriptors.FieldDescriptor}. */ public interface FieldDescriptorLite<T extends FieldDescriptorLite<T>> extends Comparable<T> { int getNumber(); WireFormat.FieldType getLiteType(); WireFormat.JavaType getLiteJavaType(); boolean isRepeated(); boolean isPacked(); Internal.EnumLiteMap<?> getEnumType(); // If getLiteJavaType() == MESSAGE, this merges a message object of the // type into a builder of the type. Returns {@code to}. MessageLite.Builder internalMergeFrom( MessageLite.Builder to, MessageLite from); } private final SmallSortedMap<FieldDescriptorType, Object> fields; private boolean isImmutable; private boolean hasLazyField = false; /** Construct a new FieldSet. */ private FieldSet() { this.fields = SmallSortedMap.newFieldMap(16); } /** * Construct an empty FieldSet. This is only used to initialize * DEFAULT_INSTANCE. */ private FieldSet(final boolean dummy) { this.fields = SmallSortedMap.newFieldMap(0); makeImmutable(); } /** Construct a new FieldSet. */ public static <T extends FieldSet.FieldDescriptorLite<T>> FieldSet<T> newFieldSet() { return new FieldSet<T>(); } /** Get an immutable empty FieldSet. */ @SuppressWarnings("unchecked") public static <T extends FieldSet.FieldDescriptorLite<T>> FieldSet<T> emptySet() { return DEFAULT_INSTANCE; } @SuppressWarnings("rawtypes") private static final FieldSet DEFAULT_INSTANCE = new FieldSet(true); /** Make this FieldSet immutable from this point forward. */ @SuppressWarnings("unchecked") public void makeImmutable() { if (isImmutable) { return; } fields.makeImmutable(); isImmutable = true; } /** * Returns whether the FieldSet is immutable. This is true if it is the * {@link #emptySet} or if {@link #makeImmutable} were called. * * @return whether the FieldSet is immutable. */ public boolean isImmutable() { return isImmutable; } /** * Clones the FieldSet. The returned FieldSet will be mutable even if the * original FieldSet was immutable. * * @return the newly cloned FieldSet */ @Override public FieldSet<FieldDescriptorType> clone() { // We can't just call fields.clone because List objects in the map // should not be shared. FieldSet<FieldDescriptorType> clone = FieldSet.newFieldSet(); for (int i = 0; i < fields.getNumArrayEntries(); i++) { Map.Entry<FieldDescriptorType, Object> entry = fields.getArrayEntryAt(i); FieldDescriptorType descriptor = entry.getKey(); clone.setField(descriptor, entry.getValue()); } for (Map.Entry<FieldDescriptorType, Object> entry : fields.getOverflowEntries()) { FieldDescriptorType descriptor = entry.getKey(); clone.setField(descriptor, entry.getValue()); } clone.hasLazyField = hasLazyField; return clone; } // ================================================================= /** See {@link Message.Builder#clear()}. */ public void clear() { fields.clear(); hasLazyField = false; } /** * Get a simple map containing all the fields. */ public Map<FieldDescriptorType, Object> getAllFields() { if (hasLazyField) { SmallSortedMap<FieldDescriptorType, Object> result = SmallSortedMap.newFieldMap(16); for (int i = 0; i < fields.getNumArrayEntries(); i++) { cloneFieldEntry(result, fields.getArrayEntryAt(i)); } for (Map.Entry<FieldDescriptorType, Object> entry : fields.getOverflowEntries()) { cloneFieldEntry(result, entry); } if (fields.isImmutable()) { result.makeImmutable(); } return result; } return fields.isImmutable() ? fields : Collections.unmodifiableMap(fields); } private void cloneFieldEntry(Map<FieldDescriptorType, Object> map, Map.Entry<FieldDescriptorType, Object> entry) { FieldDescriptorType key = entry.getKey(); Object value = entry.getValue(); if (value instanceof LazyField) { map.put(key, ((LazyField) value).getValue()); } else { map.put(key, value); } } /** * Get an iterator to the field map. This iterator should not be leaked out * of the protobuf library as it is not protected from mutation when fields * is not immutable. */ public Iterator<Map.Entry<FieldDescriptorType, Object>> iterator() { if (hasLazyField) { return new LazyIterator<FieldDescriptorType>( fields.entrySet().iterator()); } return fields.entrySet().iterator(); } /** * Useful for implementing * {@link Message#hasField(Descriptors.FieldDescriptor)}. */ public boolean hasField(final FieldDescriptorType descriptor) { if (descriptor.isRepeated()) { throw new IllegalArgumentException( "hasField() can only be called on non-repeated fields."); } return fields.get(descriptor) != null; } /** * Useful for implementing * {@link Message#getField(Descriptors.FieldDescriptor)}. This method * returns {@code null} if the field is not set; in this case it is up * to the caller to fetch the field's default value. */ public Object getField(final FieldDescriptorType descriptor) { Object o = fields.get(descriptor); if (o instanceof LazyField) { return ((LazyField) o).getValue(); } return o; } /** * Useful for implementing * {@link Message.Builder#setField(Descriptors.FieldDescriptor,Object)}. */ @SuppressWarnings({"unchecked", "rawtypes"}) public void setField(final FieldDescriptorType descriptor, Object value) { if (descriptor.isRepeated()) { if (!(value instanceof List)) { throw new IllegalArgumentException( "Wrong object type used with protocol message reflection."); } // Wrap the contents in a new list so that the caller cannot change // the list's contents after setting it. final List newList = new ArrayList(); newList.addAll((List) value); for (final Object element : newList) { verifyType(descriptor.getLiteType(), element); } value = newList; } else { verifyType(descriptor.getLiteType(), value); } if (value instanceof LazyField) { hasLazyField = true; } fields.put(descriptor, value); } /** * Useful for implementing * {@link Message.Builder#clearField(Descriptors.FieldDescriptor)}. */ public void clearField(final FieldDescriptorType descriptor) { fields.remove(descriptor); if (fields.isEmpty()) { hasLazyField = false; } } /** * Useful for implementing * {@link Message#getRepeatedFieldCount(Descriptors.FieldDescriptor)}. */ public int getRepeatedFieldCount(final FieldDescriptorType descriptor) { if (!descriptor.isRepeated()) { throw new IllegalArgumentException( "getRepeatedField() can only be called on repeated fields."); } final Object value = getField(descriptor); if (value == null) { return 0; } else { return ((List<?>) value).size(); } } /** * Useful for implementing * {@link Message#getRepeatedField(Descriptors.FieldDescriptor,int)}. */ public Object getRepeatedField(final FieldDescriptorType descriptor, final int index) { if (!descriptor.isRepeated()) { throw new IllegalArgumentException( "getRepeatedField() can only be called on repeated fields."); } final Object value = getField(descriptor); if (value == null) { throw new IndexOutOfBoundsException(); } else { return ((List<?>) value).get(index); } } /** * Useful for implementing * {@link Message.Builder#setRepeatedField(Descriptors.FieldDescriptor,int,Object)}. */ @SuppressWarnings("unchecked") public void setRepeatedField(final FieldDescriptorType descriptor, final int index, final Object value) { if (!descriptor.isRepeated()) { throw new IllegalArgumentException( "getRepeatedField() can only be called on repeated fields."); } final Object list = getField(descriptor); if (list == null) { throw new IndexOutOfBoundsException(); } verifyType(descriptor.getLiteType(), value); ((List<Object>) list).set(index, value); } /** * Useful for implementing * {@link Message.Builder#addRepeatedField(Descriptors.FieldDescriptor,Object)}. */ @SuppressWarnings("unchecked") public void addRepeatedField(final FieldDescriptorType descriptor, final Object value) { if (!descriptor.isRepeated()) { throw new IllegalArgumentException( "addRepeatedField() can only be called on repeated fields."); } verifyType(descriptor.getLiteType(), value); final Object existingValue = getField(descriptor); List<Object> list; if (existingValue == null) { list = new ArrayList<Object>(); fields.put(descriptor, list); } else { list = (List<Object>) existingValue; } list.add(value); } /** * Verifies that the given object is of the correct type to be a valid * value for the given field. (For repeated fields, this checks if the * object is the right type to be one element of the field.) * * @throws IllegalArgumentException The value is not of the right type. */ private static void verifyType(final WireFormat.FieldType type, final Object value) { if (value == null) { throw new NullPointerException(); } boolean isValid = false; switch (type.getJavaType()) { case INT: isValid = value instanceof Integer ; break; case LONG: isValid = value instanceof Long ; break; case FLOAT: isValid = value instanceof Float ; break; case DOUBLE: isValid = value instanceof Double ; break; case BOOLEAN: isValid = value instanceof Boolean ; break; case STRING: isValid = value instanceof String ; break; case BYTE_STRING: isValid = value instanceof ByteString || value instanceof byte[]; break; case ENUM: // TODO(kenton): Caller must do type checking here, I guess. isValid = (value instanceof Integer || value instanceof Internal.EnumLite); break; case MESSAGE: // TODO(kenton): Caller must do type checking here, I guess. isValid = (value instanceof MessageLite) || (value instanceof LazyField); break; } if (!isValid) { // TODO(kenton): When chaining calls to setField(), it can be hard to // tell from the stack trace which exact call failed, since the whole // chain is considered one line of code. It would be nice to print // more information here, e.g. naming the field. We used to do that. // But we can't now that FieldSet doesn't use descriptors. Maybe this // isn't a big deal, though, since it would only really apply when using // reflection and generally people don't chain reflection setters. throw new IllegalArgumentException( "Wrong object type used with protocol message reflection."); } } // ================================================================= // Parsing and serialization /** * See {@link Message#isInitialized()}. Note: Since {@code FieldSet} * itself does not have any way of knowing about required fields that * aren't actually present in the set, it is up to the caller to check * that all required fields are present. */ public boolean isInitialized() { for (int i = 0; i < fields.getNumArrayEntries(); i++) { if (!isInitialized(fields.getArrayEntryAt(i))) { return false; } } for (final Map.Entry<FieldDescriptorType, Object> entry : fields.getOverflowEntries()) { if (!isInitialized(entry)) { return false; } } return true; } @SuppressWarnings("unchecked") private boolean isInitialized( final Map.Entry<FieldDescriptorType, Object> entry) { final FieldDescriptorType descriptor = entry.getKey(); if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE) { if (descriptor.isRepeated()) { for (final MessageLite element: (List<MessageLite>) entry.getValue()) { if (!element.isInitialized()) { return false; } } } else { Object value = entry.getValue(); if (value instanceof MessageLite) { if (!((MessageLite) value).isInitialized()) { return false; } } else if (value instanceof LazyField) { return true; } else { throw new IllegalArgumentException( "Wrong object type used with protocol message reflection."); } } } return true; } /** * Given a field type, return the wire type. * * @returns One of the {@code WIRETYPE_} constants defined in * {@link WireFormat}. */ static int getWireFormatForFieldType(final WireFormat.FieldType type, boolean isPacked) { if (isPacked) { return WireFormat.WIRETYPE_LENGTH_DELIMITED; } else { return type.getWireType(); } } /** * Like {@link Message.Builder#mergeFrom(Message)}, but merges from another * {@link FieldSet}. */ public void mergeFrom(final FieldSet<FieldDescriptorType> other) { for (int i = 0; i < other.fields.getNumArrayEntries(); i++) { mergeFromField(other.fields.getArrayEntryAt(i)); } for (final Map.Entry<FieldDescriptorType, Object> entry : other.fields.getOverflowEntries()) { mergeFromField(entry); } } private Object cloneIfMutable(Object value) { if (value instanceof byte[]) { byte[] bytes = (byte[]) value; byte[] copy = new byte[bytes.length]; System.arraycopy(bytes, 0, copy, 0, bytes.length); return copy; } else { return value; } } @SuppressWarnings({"unchecked", "rawtypes"}) private void mergeFromField( final Map.Entry<FieldDescriptorType, Object> entry) { final FieldDescriptorType descriptor = entry.getKey(); Object otherValue = entry.getValue(); if (otherValue instanceof LazyField) { otherValue = ((LazyField) otherValue).getValue(); } if (descriptor.isRepeated()) { Object value = getField(descriptor); if (value == null) { value = new ArrayList(); } for (Object element : (List) otherValue) { ((List) value).add(cloneIfMutable(element)); } fields.put(descriptor, value); } else if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE) { Object value = getField(descriptor); if (value == null) { fields.put(descriptor, cloneIfMutable(otherValue)); } else { // Merge the messages. value = descriptor.internalMergeFrom( ((MessageLite) value).toBuilder(), (MessageLite) otherValue) .build(); fields.put(descriptor, value); } } else { fields.put(descriptor, cloneIfMutable(otherValue)); } } // TODO(kenton): Move static parsing and serialization methods into some // other class. Probably WireFormat. /** * Read a field of any primitive type for immutable messages from a * CodedInputStream. Enums, groups, and embedded messages are not handled by * this method. * * @param input The stream from which to read. * @param type Declared type of the field. * @param checkUtf8 When true, check that the input is valid utf8. * @return An object representing the field's value, of the exact * type which would be returned by * {@link Message#getField(Descriptors.FieldDescriptor)} for * this field. */ public static Object readPrimitiveField( CodedInputStream input, final WireFormat.FieldType type, boolean checkUtf8) throws IOException { switch (type) { case DOUBLE : return input.readDouble (); case FLOAT : return input.readFloat (); case INT64 : return input.readInt64 (); case UINT64 : return input.readUInt64 (); case INT32 : return input.readInt32 (); case FIXED64 : return input.readFixed64 (); case FIXED32 : return input.readFixed32 (); case BOOL : return input.readBool (); case STRING : if (checkUtf8) { return input.readStringRequireUtf8(); } else { return input.readString(); } case BYTES : return input.readBytes (); case UINT32 : return input.readUInt32 (); case SFIXED32: return input.readSFixed32(); case SFIXED64: return input.readSFixed64(); case SINT32 : return input.readSInt32 (); case SINT64 : return input.readSInt64 (); case GROUP: throw new IllegalArgumentException( "readPrimitiveField() cannot handle nested groups."); case MESSAGE: throw new IllegalArgumentException( "readPrimitiveField() cannot handle embedded messages."); case ENUM: // We don't handle enums because we don't know what to do if the // value is not recognized. throw new IllegalArgumentException( "readPrimitiveField() cannot handle enums."); } throw new RuntimeException( "There is no way to get here, but the compiler thinks otherwise."); } /** See {@link Message#writeTo(CodedOutputStream)}. */ public void writeTo(final CodedOutputStream output) throws IOException { for (int i = 0; i < fields.getNumArrayEntries(); i++) { final Map.Entry<FieldDescriptorType, Object> entry = fields.getArrayEntryAt(i); writeField(entry.getKey(), entry.getValue(), output); } for (final Map.Entry<FieldDescriptorType, Object> entry : fields.getOverflowEntries()) { writeField(entry.getKey(), entry.getValue(), output); } } /** * Like {@link #writeTo} but uses MessageSet wire format. */ public void writeMessageSetTo(final CodedOutputStream output) throws IOException { for (int i = 0; i < fields.getNumArrayEntries(); i++) { writeMessageSetTo(fields.getArrayEntryAt(i), output); } for (final Map.Entry<FieldDescriptorType, Object> entry : fields.getOverflowEntries()) { writeMessageSetTo(entry, output); } } private void writeMessageSetTo( final Map.Entry<FieldDescriptorType, Object> entry, final CodedOutputStream output) throws IOException { final FieldDescriptorType descriptor = entry.getKey(); if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE && !descriptor.isRepeated() && !descriptor.isPacked()) { Object value = entry.getValue(); if (value instanceof LazyField) { value = ((LazyField) value).getValue(); } output.writeMessageSetExtension(entry.getKey().getNumber(), (MessageLite) value); } else { writeField(descriptor, entry.getValue(), output); } } /** * Write a single tag-value pair to the stream. * * @param output The output stream. * @param type The field's type. * @param number The field's number. * @param value Object representing the field's value. Must be of the exact * type which would be returned by * {@link Message#getField(Descriptors.FieldDescriptor)} for * this field. */ private static void writeElement(final CodedOutputStream output, final WireFormat.FieldType type, final int number, final Object value) throws IOException { // Special case for groups, which need a start and end tag; other fields // can just use writeTag() and writeFieldNoTag(). if (type == WireFormat.FieldType.GROUP) { output.writeGroup(number, (MessageLite) value); } else { output.writeTag(number, getWireFormatForFieldType(type, false)); writeElementNoTag(output, type, value); } } /** * Write a field of arbitrary type, without its tag, to the stream. * * @param output The output stream. * @param type The field's type. * @param value Object representing the field's value. Must be of the exact * type which would be returned by * {@link Message#getField(Descriptors.FieldDescriptor)} for * this field. */ private static void writeElementNoTag( final CodedOutputStream output, final WireFormat.FieldType type, final Object value) throws IOException { switch (type) { case DOUBLE : output.writeDoubleNoTag ((Double ) value); break; case FLOAT : output.writeFloatNoTag ((Float ) value); break; case INT64 : output.writeInt64NoTag ((Long ) value); break; case UINT64 : output.writeUInt64NoTag ((Long ) value); break; case INT32 : output.writeInt32NoTag ((Integer ) value); break; case FIXED64 : output.writeFixed64NoTag ((Long ) value); break; case FIXED32 : output.writeFixed32NoTag ((Integer ) value); break; case BOOL : output.writeBoolNoTag ((Boolean ) value); break; case STRING : output.writeStringNoTag ((String ) value); break; case GROUP : output.writeGroupNoTag ((MessageLite) value); break; case MESSAGE : output.writeMessageNoTag ((MessageLite) value); break; case BYTES: if (value instanceof ByteString) { output.writeBytesNoTag((ByteString) value); } else { output.writeByteArrayNoTag((byte[]) value); } break; case UINT32 : output.writeUInt32NoTag ((Integer ) value); break; case SFIXED32: output.writeSFixed32NoTag((Integer ) value); break; case SFIXED64: output.writeSFixed64NoTag((Long ) value); break; case SINT32 : output.writeSInt32NoTag ((Integer ) value); break; case SINT64 : output.writeSInt64NoTag ((Long ) value); break; case ENUM: if (value instanceof Internal.EnumLite) { output.writeEnumNoTag(((Internal.EnumLite) value).getNumber()); } else { output.writeEnumNoTag(((Integer) value).intValue()); } break; } } /** Write a single field. */ public static void writeField(final FieldDescriptorLite<?> descriptor, final Object value, final CodedOutputStream output) throws IOException { WireFormat.FieldType type = descriptor.getLiteType(); int number = descriptor.getNumber(); if (descriptor.isRepeated()) { final List<?> valueList = (List<?>)value; if (descriptor.isPacked()) { output.writeTag(number, WireFormat.WIRETYPE_LENGTH_DELIMITED); // Compute the total data size so the length can be written. int dataSize = 0; for (final Object element : valueList) { dataSize += computeElementSizeNoTag(type, element); } output.writeRawVarint32(dataSize); // Write the data itself, without any tags. for (final Object element : valueList) { writeElementNoTag(output, type, element); } } else { for (final Object element : valueList) { writeElement(output, type, number, element); } } } else { if (value instanceof LazyField) { writeElement(output, type, number, ((LazyField) value).getValue()); } else { writeElement(output, type, number, value); } } } /** * See {@link Message#getSerializedSize()}. It's up to the caller to cache * the resulting size if desired. */ public int getSerializedSize() { int size = 0; for (int i = 0; i < fields.getNumArrayEntries(); i++) { final Map.Entry<FieldDescriptorType, Object> entry = fields.getArrayEntryAt(i); size += computeFieldSize(entry.getKey(), entry.getValue()); } for (final Map.Entry<FieldDescriptorType, Object> entry : fields.getOverflowEntries()) { size += computeFieldSize(entry.getKey(), entry.getValue()); } return size; } /** * Like {@link #getSerializedSize} but uses MessageSet wire format. */ public int getMessageSetSerializedSize() { int size = 0; for (int i = 0; i < fields.getNumArrayEntries(); i++) { size += getMessageSetSerializedSize(fields.getArrayEntryAt(i)); } for (final Map.Entry<FieldDescriptorType, Object> entry : fields.getOverflowEntries()) { size += getMessageSetSerializedSize(entry); } return size; } private int getMessageSetSerializedSize( final Map.Entry<FieldDescriptorType, Object> entry) { final FieldDescriptorType descriptor = entry.getKey(); Object value = entry.getValue(); if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE && !descriptor.isRepeated() && !descriptor.isPacked()) { if (value instanceof LazyField) { return CodedOutputStream.computeLazyFieldMessageSetExtensionSize( entry.getKey().getNumber(), (LazyField) value); } else { return CodedOutputStream.computeMessageSetExtensionSize( entry.getKey().getNumber(), (MessageLite) value); } } else { return computeFieldSize(descriptor, value); } } /** * Compute the number of bytes that would be needed to encode a * single tag/value pair of arbitrary type. * * @param type The field's type. * @param number The field's number. * @param value Object representing the field's value. Must be of the exact * type which would be returned by * {@link Message#getField(Descriptors.FieldDescriptor)} for * this field. */ private static int computeElementSize( final WireFormat.FieldType type, final int number, final Object value) { int tagSize = CodedOutputStream.computeTagSize(number); if (type == WireFormat.FieldType.GROUP) { // Only count the end group tag for proto2 messages as for proto1 the end // group tag will be counted as a part of getSerializedSize(). tagSize *= 2; } return tagSize + computeElementSizeNoTag(type, value); } /** * Compute the number of bytes that would be needed to encode a * particular value of arbitrary type, excluding tag. * * @param type The field's type. * @param value Object representing the field's value. Must be of the exact * type which would be returned by * {@link Message#getField(Descriptors.FieldDescriptor)} for * this field. */ private static int computeElementSizeNoTag( final WireFormat.FieldType type, final Object value) { switch (type) { // Note: Minor violation of 80-char limit rule here because this would // actually be harder to read if we wrapped the lines. case DOUBLE : return CodedOutputStream.computeDoubleSizeNoTag ((Double )value); case FLOAT : return CodedOutputStream.computeFloatSizeNoTag ((Float )value); case INT64 : return CodedOutputStream.computeInt64SizeNoTag ((Long )value); case UINT64 : return CodedOutputStream.computeUInt64SizeNoTag ((Long )value); case INT32 : return CodedOutputStream.computeInt32SizeNoTag ((Integer )value); case FIXED64 : return CodedOutputStream.computeFixed64SizeNoTag ((Long )value); case FIXED32 : return CodedOutputStream.computeFixed32SizeNoTag ((Integer )value); case BOOL : return CodedOutputStream.computeBoolSizeNoTag ((Boolean )value); case STRING : return CodedOutputStream.computeStringSizeNoTag ((String )value); case GROUP : return CodedOutputStream.computeGroupSizeNoTag ((MessageLite)value); case BYTES : if (value instanceof ByteString) { return CodedOutputStream.computeBytesSizeNoTag((ByteString) value); } else { return CodedOutputStream.computeByteArraySizeNoTag((byte[]) value); } case UINT32 : return CodedOutputStream.computeUInt32SizeNoTag ((Integer )value); case SFIXED32: return CodedOutputStream.computeSFixed32SizeNoTag((Integer )value); case SFIXED64: return CodedOutputStream.computeSFixed64SizeNoTag((Long )value); case SINT32 : return CodedOutputStream.computeSInt32SizeNoTag ((Integer )value); case SINT64 : return CodedOutputStream.computeSInt64SizeNoTag ((Long )value); case MESSAGE: if (value instanceof LazyField) { return CodedOutputStream.computeLazyFieldSizeNoTag((LazyField) value); } else { return CodedOutputStream.computeMessageSizeNoTag((MessageLite) value); } case ENUM: if (value instanceof Internal.EnumLite) { return CodedOutputStream.computeEnumSizeNoTag( ((Internal.EnumLite) value).getNumber()); } else { return CodedOutputStream.computeEnumSizeNoTag((Integer) value); } } throw new RuntimeException( "There is no way to get here, but the compiler thinks otherwise."); } /** * Compute the number of bytes needed to encode a particular field. */ public static int computeFieldSize(final FieldDescriptorLite<?> descriptor, final Object value) { WireFormat.FieldType type = descriptor.getLiteType(); int number = descriptor.getNumber(); if (descriptor.isRepeated()) { if (descriptor.isPacked()) { int dataSize = 0; for (final Object element : (List<?>)value) { dataSize += computeElementSizeNoTag(type, element); } return dataSize + CodedOutputStream.computeTagSize(number) + CodedOutputStream.computeRawVarint32Size(dataSize); } else { int size = 0; for (final Object element : (List<?>)value) { size += computeElementSize(type, number, element); } return size; } } else { return computeElementSize(type, number, value); } } }
/* * 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 io.trino.sql.query; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import io.trino.Session; import io.trino.connector.MockConnectorFactory; import io.trino.metadata.QualifiedObjectName; import io.trino.plugin.tpch.TpchConnectorFactory; import io.trino.spi.connector.CatalogSchemaTableName; import io.trino.spi.connector.ConnectorMaterializedViewDefinition; import io.trino.spi.connector.ConnectorViewDefinition; import io.trino.spi.connector.SchemaTableName; import io.trino.spi.security.Identity; import io.trino.spi.security.ViewExpression; import io.trino.spi.type.BigintType; import io.trino.spi.type.VarcharType; import io.trino.testing.LocalQueryRunner; import io.trino.testing.TestingAccessControlManager; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.Optional; import static io.trino.plugin.tpch.TpchMetadata.TINY_SCHEMA_NAME; import static io.trino.testing.TestingAccessControlManager.TestingPrivilegeType.SELECT_COLUMN; import static io.trino.testing.TestingAccessControlManager.privilege; import static io.trino.testing.TestingSession.testSessionBuilder; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @Test(singleThreaded = true) public class TestColumnMask { private static final String CATALOG = "local"; private static final String MOCK_CATALOG = "mock"; private static final String USER = "user"; private static final String VIEW_OWNER = "view-owner"; private static final String RUN_AS_USER = "run-as-user"; private static final Session SESSION = testSessionBuilder() .setCatalog(CATALOG) .setSchema(TINY_SCHEMA_NAME) .setIdentity(Identity.forUser(USER).build()) .build(); private QueryAssertions assertions; private TestingAccessControlManager accessControl; @BeforeClass public void init() { LocalQueryRunner runner = LocalQueryRunner.builder(SESSION).build(); runner.createCatalog(CATALOG, new TpchConnectorFactory(1), ImmutableMap.of()); ConnectorViewDefinition view = new ConnectorViewDefinition( "SELECT nationkey, name FROM local.tiny.nation", Optional.empty(), Optional.empty(), ImmutableList.of(new ConnectorViewDefinition.ViewColumn("nationkey", BigintType.BIGINT.getTypeId()), new ConnectorViewDefinition.ViewColumn("name", VarcharType.createVarcharType(25).getTypeId())), Optional.empty(), Optional.of(VIEW_OWNER), false); ConnectorMaterializedViewDefinition materializedView = new ConnectorMaterializedViewDefinition( "SELECT * FROM local.tiny.nation", Optional.empty(), Optional.empty(), Optional.empty(), ImmutableList.of( new ConnectorMaterializedViewDefinition.Column("nationkey", BigintType.BIGINT.getTypeId()), new ConnectorMaterializedViewDefinition.Column("name", VarcharType.createVarcharType(25).getTypeId()), new ConnectorMaterializedViewDefinition.Column("regionkey", BigintType.BIGINT.getTypeId()), new ConnectorMaterializedViewDefinition.Column("comment", VarcharType.createVarcharType(152).getTypeId())), Optional.empty(), VIEW_OWNER, ImmutableMap.of()); ConnectorMaterializedViewDefinition freshMaterializedView = new ConnectorMaterializedViewDefinition( "SELECT * FROM local.tiny.nation", Optional.of(new CatalogSchemaTableName("local", "tiny", "nation")), Optional.empty(), Optional.empty(), ImmutableList.of( new ConnectorMaterializedViewDefinition.Column("nationkey", BigintType.BIGINT.getTypeId()), new ConnectorMaterializedViewDefinition.Column("name", VarcharType.createVarcharType(25).getTypeId()), new ConnectorMaterializedViewDefinition.Column("regionkey", BigintType.BIGINT.getTypeId()), new ConnectorMaterializedViewDefinition.Column("comment", VarcharType.createVarcharType(152).getTypeId())), Optional.empty(), VIEW_OWNER, ImmutableMap.of()); MockConnectorFactory mock = MockConnectorFactory.builder() .withGetViews((s, prefix) -> ImmutableMap.of( new SchemaTableName("default", "nation_view"), view)) .withGetMaterializedViews((s, prefix) -> ImmutableMap.of( new SchemaTableName("default", "nation_materialized_view"), materializedView, new SchemaTableName("default", "nation_fresh_materialized_view"), freshMaterializedView)) .build(); runner.createCatalog(MOCK_CATALOG, mock, ImmutableMap.of()); assertions = new QueryAssertions(runner); accessControl = assertions.getQueryRunner().getAccessControl(); } @AfterClass(alwaysRun = true) public void teardown() { assertions.close(); assertions = null; } @Test public void testSimpleMask() { accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "custkey", USER, new ViewExpression(USER, Optional.empty(), Optional.empty(), "-custkey")); assertThat(assertions.query("SELECT custkey FROM orders WHERE orderkey = 1")).matches("VALUES BIGINT '-370'"); accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "custkey", USER, new ViewExpression(USER, Optional.empty(), Optional.empty(), "NULL")); assertThat(assertions.query("SELECT custkey FROM orders WHERE orderkey = 1")).matches("VALUES CAST(NULL AS BIGINT)"); } @Test public void testMultipleMasksOnSameColumn() { accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "custkey", USER, new ViewExpression(USER, Optional.empty(), Optional.empty(), "-custkey")); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "custkey", USER, new ViewExpression(USER, Optional.empty(), Optional.empty(), "custkey * 2")); assertThat(assertions.query("SELECT custkey FROM orders WHERE orderkey = 1")).matches("VALUES BIGINT '-740'"); } @Test public void testMultipleMasksOnDifferentColumns() { accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "custkey", USER, new ViewExpression(USER, Optional.empty(), Optional.empty(), "-custkey")); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "orderstatus", USER, new ViewExpression(USER, Optional.empty(), Optional.empty(), "'X'")); assertThat(assertions.query("SELECT custkey, orderstatus FROM orders WHERE orderkey = 1")) .matches("VALUES (BIGINT '-370', 'X')"); } @Test public void testReferenceInUsingClause() { accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "orderkey", USER, new ViewExpression(USER, Optional.empty(), Optional.empty(), "IF(orderkey = 1, -orderkey)")); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "lineitem"), "orderkey", USER, new ViewExpression(USER, Optional.empty(), Optional.empty(), "IF(orderkey = 1, -orderkey)")); assertThat(assertions.query("SELECT count(*) FROM orders JOIN lineitem USING (orderkey)")).matches("VALUES BIGINT '6'"); } @Test public void testCoercibleType() { accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "clerk", USER, new ViewExpression(USER, Optional.empty(), Optional.empty(), "CAST(clerk AS VARCHAR(5))")); assertThat(assertions.query("SELECT clerk FROM orders WHERE orderkey = 1")).matches("VALUES CAST('Clerk' AS VARCHAR(15))"); } @Test public void testSubquery() { // uncorrelated accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "clerk", USER, new ViewExpression(USER, Optional.of(CATALOG), Optional.of("tiny"), "(SELECT cast(max(name) AS VARCHAR(15)) FROM nation)")); assertThat(assertions.query("SELECT clerk FROM orders WHERE orderkey = 1")).matches("VALUES CAST('VIETNAM' AS VARCHAR(15))"); // correlated accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "clerk", USER, new ViewExpression(USER, Optional.of(CATALOG), Optional.of("tiny"), "(SELECT cast(max(name) AS VARCHAR(15)) FROM nation WHERE nationkey = orderkey)")); assertThat(assertions.query("SELECT clerk FROM orders WHERE orderkey = 1")).matches("VALUES CAST('ARGENTINA' AS VARCHAR(15))"); } @Test public void testMaterializedView() { // mask materialized view columns accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(MOCK_CATALOG, "default", "nation_fresh_materialized_view"), "name", USER, new ViewExpression(USER, Optional.empty(), Optional.empty(), "reverse(name)")); accessControl.columnMask( new QualifiedObjectName(MOCK_CATALOG, "default", "nation_materialized_view"), "name", USER, new ViewExpression(USER, Optional.empty(), Optional.empty(), "reverse(name)")); assertThat(assertions.query( Session.builder(SESSION) .setIdentity(Identity.forUser(USER).build()) .build(), "SELECT name FROM mock.default.nation_fresh_materialized_view WHERE nationkey = 1")) .matches("VALUES CAST('ANITNEGRA' AS VARCHAR(25))"); assertThat(assertions.query( Session.builder(SESSION) .setIdentity(Identity.forUser(USER).build()) .build(), "SELECT name FROM mock.default.nation_materialized_view WHERE nationkey = 1")) .matches("VALUES CAST('ANITNEGRA' AS VARCHAR(25))"); } @Test public void testView() { // mask on the underlying table for view owner when running query as different user accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "nation"), "name", VIEW_OWNER, new ViewExpression(VIEW_OWNER, Optional.empty(), Optional.empty(), "reverse(name)")); assertThat(assertions.query( Session.builder(SESSION) .setIdentity(Identity.forUser(RUN_AS_USER).build()) .build(), "SELECT name FROM mock.default.nation_view WHERE nationkey = 1")) .matches("VALUES CAST('ANITNEGRA' AS VARCHAR(25))"); // mask on the underlying table for view owner when running as themselves accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "nation"), "name", VIEW_OWNER, new ViewExpression(VIEW_OWNER, Optional.of(CATALOG), Optional.of("tiny"), "reverse(name)")); assertThat(assertions.query( Session.builder(SESSION) .setIdentity(Identity.forUser(VIEW_OWNER).build()) .build(), "SELECT name FROM mock.default.nation_view WHERE nationkey = 1")) .matches("VALUES CAST('ANITNEGRA' AS VARCHAR(25))"); // mask on the underlying table for user running the query (different from view owner) should not be applied accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "nation"), "name", RUN_AS_USER, new ViewExpression(RUN_AS_USER, Optional.of(CATALOG), Optional.of("tiny"), "reverse(name)")); assertThat(assertions.query( Session.builder(SESSION) .setIdentity(Identity.forUser(RUN_AS_USER).build()) .build(), "SELECT name FROM mock.default.nation_view WHERE nationkey = 1")) .matches("VALUES CAST('ARGENTINA' AS VARCHAR(25))"); // mask on the view accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(MOCK_CATALOG, "default", "nation_view"), "name", USER, new ViewExpression(USER, Optional.of(CATALOG), Optional.of("tiny"), "reverse(name)")); assertThat(assertions.query("SELECT name FROM mock.default.nation_view WHERE nationkey = 1")).matches("VALUES CAST('ANITNEGRA' AS VARCHAR(25))"); } @Test public void testTableReferenceInWithClause() { accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "custkey", USER, new ViewExpression(USER, Optional.empty(), Optional.empty(), "-custkey")); assertThat(assertions.query("WITH t AS (SELECT custkey FROM orders WHERE orderkey = 1) SELECT * FROM t")).matches("VALUES BIGINT '-370'"); } @Test public void testOtherSchema() { accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "orderkey", USER, new ViewExpression(USER, Optional.of(CATALOG), Optional.of("sf1"), "(SELECT count(*) FROM customer)")); // count is 15000 only when evaluating against sf1 assertThat(assertions.query("SELECT max(orderkey) FROM orders")).matches("VALUES BIGINT '150000'"); } @Test public void testDifferentIdentity() { accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "orderkey", RUN_AS_USER, new ViewExpression(RUN_AS_USER, Optional.of(CATALOG), Optional.of("tiny"), "100")); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "orderkey", USER, new ViewExpression(RUN_AS_USER, Optional.of(CATALOG), Optional.of("tiny"), "(SELECT sum(orderkey) FROM orders)")); assertThat(assertions.query("SELECT max(orderkey) FROM orders")).matches("VALUES BIGINT '1500000'"); } @Test public void testRecursion() { accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "orderkey", USER, new ViewExpression(USER, Optional.of(CATALOG), Optional.of("tiny"), "(SELECT orderkey FROM orders)")); assertThatThrownBy(() -> assertions.query("SELECT orderkey FROM orders")) .hasMessageMatching(".*\\QColumn mask for 'local.tiny.orders.orderkey' is recursive\\E.*"); // different reference style to same table accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "orderkey", USER, new ViewExpression(USER, Optional.of(CATALOG), Optional.of("tiny"), "(SELECT orderkey FROM local.tiny.orders)")); assertThatThrownBy(() -> assertions.query("SELECT orderkey FROM orders")) .hasMessageMatching(".*\\QColumn mask for 'local.tiny.orders.orderkey' is recursive\\E.*"); // mutual recursion accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "orderkey", RUN_AS_USER, new ViewExpression(RUN_AS_USER, Optional.of(CATALOG), Optional.of("tiny"), "(SELECT orderkey FROM orders)")); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "orderkey", USER, new ViewExpression(RUN_AS_USER, Optional.of(CATALOG), Optional.of("tiny"), "(SELECT orderkey FROM orders)")); assertThatThrownBy(() -> assertions.query("SELECT orderkey FROM orders")) .hasMessageMatching(".*\\QColumn mask for 'local.tiny.orders.orderkey' is recursive\\E.*"); } @Test public void testLimitedScope() { accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "customer"), "custkey", USER, new ViewExpression(USER, Optional.of(CATALOG), Optional.of("tiny"), "orderkey")); assertThatThrownBy(() -> assertions.query( "SELECT (SELECT min(custkey) FROM customer WHERE customer.custkey = orders.custkey) FROM orders")) .hasMessage("line 1:34: Invalid column mask for 'local.tiny.customer.custkey': Column 'orderkey' cannot be resolved"); } @Test public void testSqlInjection() { accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "nation"), "name", USER, new ViewExpression(USER, Optional.of(CATALOG), Optional.of("tiny"), "(SELECT name FROM region WHERE regionkey = 0)")); assertThat(assertions.query( "WITH region(regionkey, name) AS (VALUES (0, 'ASIA'))" + "SELECT name FROM nation ORDER BY name LIMIT 1")) .matches("VALUES CAST('AFRICA' AS VARCHAR(25))"); // if sql-injection would work then query would return ASIA } @Test public void testInvalidMasks() { // parse error accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "orderkey", USER, new ViewExpression(RUN_AS_USER, Optional.of(CATALOG), Optional.of("tiny"), "$$$")); assertThatThrownBy(() -> assertions.query("SELECT orderkey FROM orders")) .hasMessage("line 1:22: Invalid column mask for 'local.tiny.orders.orderkey': mismatched input '$'. Expecting: <expression>"); // unknown column accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "orderkey", USER, new ViewExpression(RUN_AS_USER, Optional.of(CATALOG), Optional.of("tiny"), "unknown_column")); assertThatThrownBy(() -> assertions.query("SELECT orderkey FROM orders")) .hasMessage("line 1:22: Invalid column mask for 'local.tiny.orders.orderkey': Column 'unknown_column' cannot be resolved"); // invalid type accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "orderkey", USER, new ViewExpression(RUN_AS_USER, Optional.of(CATALOG), Optional.of("tiny"), "'foo'")); assertThatThrownBy(() -> assertions.query("SELECT orderkey FROM orders")) .hasMessage("line 1:22: Expected column mask for 'local.tiny.orders.orderkey' to be of type bigint, but was varchar(3)"); // aggregation accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "orderkey", USER, new ViewExpression(RUN_AS_USER, Optional.of(CATALOG), Optional.of("tiny"), "count(*) > 0")); assertThatThrownBy(() -> assertions.query("SELECT orderkey FROM orders")) .hasMessage("line 1:10: Column mask for 'orders.orderkey' cannot contain aggregations, window functions or grouping operations: [count(*)]"); // window function accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "orderkey", USER, new ViewExpression(RUN_AS_USER, Optional.of(CATALOG), Optional.of("tiny"), "row_number() OVER () > 0")); assertThatThrownBy(() -> assertions.query("SELECT orderkey FROM orders")) .hasMessage("line 1:22: Column mask for 'orders.orderkey' cannot contain aggregations, window functions or grouping operations: [row_number() OVER ()]"); // grouping function accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "orderkey", USER, new ViewExpression(USER, Optional.of(CATALOG), Optional.of("tiny"), "grouping(orderkey) = 0")); assertThatThrownBy(() -> assertions.query("SELECT orderkey FROM orders")) .hasMessage("line 1:20: Column mask for 'orders.orderkey' cannot contain aggregations, window functions or grouping operations: [GROUPING (orderkey)]"); } @Test public void testShowStats() { accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "orderkey", USER, new ViewExpression(USER, Optional.of(CATALOG), Optional.of("tiny"), "7")); assertThat(assertions.query("SHOW STATS FOR (SELECT * FROM orders)")) .containsAll("VALUES " + "(CAST('orderkey' AS varchar), CAST(NULL AS double), 1e0, 0e1, NULL, '7', '7')," + "(CAST('clerk' AS varchar), 15e3, 1e3, 0e1, NULL, CAST(NULL AS varchar), CAST(NULL AS varchar))," + "(NULL, NULL, NULL, NULL, 15e3, NULL, NULL)"); assertThat(assertions.query("SHOW STATS FOR (SELECT orderkey FROM orders)")) .matches("VALUES " + "(CAST('orderkey' AS varchar), CAST(NULL AS double), 1e0, 0e1, NULL, CAST('7' AS varchar), CAST('7' AS varchar))," + "(NULL, NULL, NULL, NULL, 15e3, NULL, NULL)"); assertThat(assertions.query("SHOW STATS FOR (SELECT clerk FROM orders)")) .matches("VALUES " + "(CAST('clerk' AS varchar), 15e3, 1e3, 0e1, NULL, CAST(NULL AS varchar), CAST(NULL AS varchar))," + "(NULL, NULL, NULL, NULL, 15e3, NULL, NULL)"); } @Test public void testJoin() { accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "orderkey", USER, new ViewExpression(USER, Optional.of(CATALOG), Optional.of("tiny"), "orderkey + 1")); assertThat(assertions.query("SELECT count(*) FROM orders JOIN orders USING (orderkey)")).matches("VALUES BIGINT '15000'"); // multiple masks accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "orderkey", USER, new ViewExpression(USER, Optional.empty(), Optional.empty(), "-orderkey")); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "orderkey", USER, new ViewExpression(USER, Optional.empty(), Optional.empty(), "orderkey * 2")); assertThat(assertions.query("SELECT count(*) FROM orders JOIN orders USING (orderkey)")).matches("VALUES BIGINT '15000'"); } @Test public void testColumnMaskingUsingRestrictedColumn() { accessControl.reset(); accessControl.deny(privilege("orders.custkey", SELECT_COLUMN)); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "orderkey", USER, new ViewExpression(USER, Optional.empty(), Optional.empty(), "custkey")); assertThatThrownBy(() -> assertions.query("SELECT orderkey FROM orders")) .hasMessage("Access Denied: Cannot select from columns [orderkey, custkey] in table or view local.tiny.orders"); } @Test public void testInsertWithColumnMasking() { accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "clerk", USER, new ViewExpression(USER, Optional.empty(), Optional.empty(), "clerk")); assertThatThrownBy(() -> assertions.query("INSERT INTO orders SELECT * FROM orders")) .hasMessage("Insert into table with column masks is not supported"); } @Test public void testDeleteWithColumnMasking() { accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "clerk", USER, new ViewExpression(USER, Optional.empty(), Optional.empty(), "clerk")); assertThatThrownBy(() -> assertions.query("DELETE FROM orders")) .hasMessage("line 1:1: Delete from table with column mask"); } @Test public void testUpdateWithColumnMasking() { accessControl.reset(); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "clerk", USER, new ViewExpression(USER, Optional.empty(), Optional.empty(), "clerk")); assertThatThrownBy(() -> assertions.query("UPDATE orders SET clerk = 'X'")) .hasMessage("line 1:1: Updating a table with column masks is not supported"); assertThatThrownBy(() -> assertions.query("UPDATE orders SET orderkey = -orderkey")) .hasMessage("line 1:1: Updating a table with column masks is not supported"); assertThatThrownBy(() -> assertions.query("UPDATE orders SET clerk = 'X', orderkey = -orderkey")) .hasMessage("line 1:1: Updating a table with column masks is not supported"); } @Test public void testNotReferencedAndDeniedColumnMasking() { // mask on not used varchar column accessControl.reset(); accessControl.deny(privilege("orders.clerk", SELECT_COLUMN)); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "clerk", USER, new ViewExpression(USER, Optional.empty(), Optional.empty(), "clerk")); assertThat(assertions.query("SELECT orderkey FROM orders WHERE orderkey = 1")).matches("VALUES BIGINT '1'"); // mask on long column accessControl.reset(); accessControl.deny(privilege("orders.totalprice", SELECT_COLUMN)); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "totalprice", USER, new ViewExpression(USER, Optional.empty(), Optional.empty(), "totalprice")); assertThat(assertions.query("SELECT orderkey FROM orders WHERE orderkey = 1")).matches("VALUES BIGINT '1'"); // mask on not used varchar column with subquery masking accessControl.reset(); accessControl.deny(privilege("orders.clerk", SELECT_COLUMN)); accessControl.deny(privilege("orders.orderstatus", SELECT_COLUMN)); accessControl.columnMask( new QualifiedObjectName(CATALOG, "tiny", "orders"), "clerk", USER, new ViewExpression(USER, Optional.empty(), Optional.empty(), "(SELECT orderstatus FROM local.tiny.orders)")); assertThat(assertions.query("SELECT orderkey FROM orders WHERE orderkey = 1")).matches("VALUES BIGINT '1'"); } }
/* * 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.main; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; /** * Support for command line arguments to Camel main. */ public abstract class MainCommandLineSupport extends MainSupport { protected final List<Option> options = new ArrayList<>(); public MainCommandLineSupport(Class... configurationClasses) { super(configurationClasses); } public MainCommandLineSupport() { addOption(new Option("h", "help", "Displays the help screen") { protected void doProcess(String arg, LinkedList<String> remainingArgs) { showOptions(); completed(); } }); addOption(new ParameterOption( "r", "routers", "Sets the router builder classes which will be loaded while starting the camel context", "routerBuilderClasses") { @Override protected void doProcess(String arg, String parameter, LinkedList<String> remainingArgs) { configure().setRoutesBuilderClasses(parameter); } }); addOption(new ParameterOption( "d", "duration", "Sets the time duration (seconds) that the application will run for before terminating.", "duration") { protected void doProcess(String arg, String parameter, LinkedList<String> remainingArgs) { // skip second marker to be backwards compatible if (parameter.endsWith("s") || parameter.endsWith("S")) { parameter = parameter.substring(0, parameter.length() - 1); } configure().setDurationMaxSeconds(Integer.parseInt(parameter)); } }); addOption(new ParameterOption( "dm", "durationMaxMessages", "Sets the duration of maximum number of messages that the application will process before terminating.", "durationMaxMessages") { protected void doProcess(String arg, String parameter, LinkedList<String> remainingArgs) { configure().setDurationMaxMessages(Integer.parseInt(parameter)); } }); addOption(new ParameterOption( "di", "durationIdle", "Sets the idle time duration (seconds) duration that the application can be idle before terminating.", "durationIdle") { protected void doProcess(String arg, String parameter, LinkedList<String> remainingArgs) { // skip second marker to be backwards compatible if (parameter.endsWith("s") || parameter.endsWith("S")) { parameter = parameter.substring(0, parameter.length() - 1); } configure().setDurationMaxIdleSeconds(Integer.parseInt(parameter)); } }); addOption(new Option("t", "trace", "Enables tracing") { protected void doProcess(String arg, LinkedList<String> remainingArgs) { enableTrace(); } }); addOption(new ParameterOption( "e", "exitcode", "Sets the exit code if duration was hit", "exitcode") { protected void doProcess(String arg, String parameter, LinkedList<String> remainingArgs) { configure().setDurationHitExitCode(Integer.parseInt(parameter)); } }); addOption(new ParameterOption( "pl", "propertiesLocation", "Sets location(s) to load properties, such as from classpath or file system.", "propertiesLocation") { protected void doProcess(String arg, String parameter, LinkedList<String> remainingArgs) { setPropertyPlaceholderLocations(parameter); } }); } /** * Displays the command line options. */ public void showOptions() { showOptionsHeader(); for (Option option : options) { System.out.println(option.getInformation()); } } /** * Parses the command line arguments. */ public void parseArguments(String[] arguments) { LinkedList<String> args = new LinkedList<>(Arrays.asList(arguments)); boolean valid = true; while (!args.isEmpty()) { String arg = args.removeFirst(); boolean handled = false; for (Option option : options) { if (option.processOption(arg, args)) { handled = true; break; } } if (!handled) { System.out.println("Unknown option: " + arg); System.out.println(); valid = false; break; } } if (!valid) { showOptions(); completed(); } } public void addOption(Option option) { options.add(option); } /** * Parses the command line arguments then runs the program. */ public void run(String[] args) throws Exception { parseArguments(args); run(); LOG.info("MainSupport exiting code: {}", getExitCode()); } /** * Displays the header message for the command line options. */ public void showOptionsHeader() { System.out.println("Apache Camel Runner takes the following options"); System.out.println(); } public abstract class Option { private final String abbreviation; private final String fullName; private final String description; protected Option(String abbreviation, String fullName, String description) { this.abbreviation = "-" + abbreviation; this.fullName = "-" + fullName; this.description = description; } public boolean processOption(String arg, LinkedList<String> remainingArgs) { if (arg.equalsIgnoreCase(abbreviation) || fullName.startsWith(arg)) { doProcess(arg, remainingArgs); return true; } return false; } public String getAbbreviation() { return abbreviation; } public String getDescription() { return description; } public String getFullName() { return fullName; } public String getInformation() { return " " + getAbbreviation() + " or " + getFullName() + " = " + getDescription(); } protected abstract void doProcess(String arg, LinkedList<String> remainingArgs); } public abstract class ParameterOption extends Option { private final String parameterName; protected ParameterOption(String abbreviation, String fullName, String description, String parameterName) { super(abbreviation, fullName, description); this.parameterName = parameterName; } @Override protected void doProcess(String arg, LinkedList<String> remainingArgs) { if (remainingArgs.isEmpty()) { System.err.println("Expected fileName for "); showOptions(); completed(); } else { String parameter = remainingArgs.removeFirst(); doProcess(arg, parameter, remainingArgs); } } @Override public String getInformation() { return " " + getAbbreviation() + " or " + getFullName() + " <" + parameterName + "> = " + getDescription(); } protected abstract void doProcess(String arg, String parameter, LinkedList<String> remainingArgs); } }
/** * Copyright (C) 2013 Samsung Electronics Co., Ltd. All rights reserved. * * Mobile Communication Division, * Digital Media & Communications Business, Samsung Electronics Co., Ltd. * * This software and its documentation are confidential and proprietary * information of Samsung Electronics Co., Ltd. No part of the software and * documents may be copied, reproduced, transmitted, translated, or reduced to * any electronic medium or machine-readable form without the prior written * consent of Samsung Electronics. * * Samsung Electronics makes no representations with respect to the contents, * and assumes no responsibility for any errors that might appear in the * software and documents. This publication and the contents hereof are subject * to change without notice. */ package com.samsung.chord.samples.apidemo.service; import java.io.File; import java.util.List; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.Binder; import android.os.Environment; import android.os.IBinder; import android.os.PowerManager; import android.os.StatFs; import android.util.Log; import com.samsung.chord.IChordChannel; import com.samsung.chord.IChordChannelListener; import com.samsung.chord.IChordManagerListener; import com.samsung.chord.ChordManager; import com.samsung.chord.ChordManager.INetworkListener; public class ChordApiDemoService extends Service { public static String CHORD_APITEST_CHANNEL = "com.samsung.chord.samples.apidemo.TESTCHANNEL"; private static final String TAG = "[Chord][ApiTest]"; private static final String TAGClass = "ChordService : "; private static final String CHORD_APITEST_MESSAGE_TYPE = "CHORD_APITEST_MESSAGE_TYPE"; private static final String MESSAGE_TYPE_FILE_NOTIFICATION = "FILE_NOTIFICATION_V2"; private static final long SHARE_FILE_TIMEOUT_MILISECONDS = 1000 * 60 * 5; public static final String chordFilePath = Environment.getExternalStorageDirectory() .getAbsolutePath() + "/Chord"; private ChordManager mChord = null; private String mPrivateChannelName = ""; private IChordServiceListener mListener = null; private PowerManager.WakeLock mWakeLock = null; // for notifying event to Activity public interface IChordServiceListener { void onReceiveMessage(String node, String channel, String message); void onFileWillReceive(String node, String channel, String fileName, String exchangeId); void onFileProgress(boolean bSend, String node, String channel, int progress, String exchangeId); public static final int SENT = 0; public static final int RECEIVED = 1; public static final int CANCELLED = 2; public static final int REJECTED = 3; public static final int FAILED = 4; void onFileCompleted(int reason, String node, String channel, String exchangeId, String fileName); void onNodeEvent(String node, String channel, boolean bJoined); void onNetworkDisconnected(); void onUpdateNodeInfo(String nodeName, String ipAddress); void onConnectivityChanged(); } @Override public IBinder onBind(Intent intent) { Log.d(TAG, TAGClass + "onBind()"); return mBinder; } @Override public void onCreate() { Log.d(TAG, TAGClass + "onCreate()"); super.onCreate(); } @Override public void onDestroy() { Log.d(TAG, TAGClass + "onDestroy()"); super.onDestroy(); try { release(); } catch (Exception e) { e.printStackTrace(); } } @Override public void onRebind(Intent intent) { Log.d(TAG, TAGClass + "onRebind()"); super.onRebind(intent); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, TAGClass + "onStartCommand()"); return super.onStartCommand(intent, START_NOT_STICKY, startId); } @Override public boolean onUnbind(Intent intent) { Log.d(TAG, TAGClass + "onUnbind()"); return super.onUnbind(intent); } public class ChordServiceBinder extends Binder { public ChordApiDemoService getService() { return ChordApiDemoService.this; } } private final IBinder mBinder = new ChordServiceBinder(); // Initialize chord public void initialize(IChordServiceListener listener) throws Exception { if (mChord != null) { return; } // #1. GetInstance mChord = ChordManager.getInstance(this); Log.d(TAG, TAGClass + "[Initialize] Chord Initialized"); mListener = listener; // #2. set some values before start mChord.setTempDirectory(chordFilePath); mChord.setHandleEventLooper(getMainLooper()); // Optional. // If you need listening network changed, you can set callback before // starting chord. mChord.setNetworkListener(new INetworkListener() { @Override public void onConnected(int interfaceType) { if (null != mListener) { mListener.onConnectivityChanged(); } } @Override public void onDisconnected(int interfaceType) { if (null != mListener) { mListener.onConnectivityChanged(); } } }); } // Start chord public int start(int interfaceType) { acqureWakeLock(); // #3. set some values before start return mChord.start(interfaceType, new IChordManagerListener() { @Override public void onStarted(String name, int reason) { Log.d(TAG, TAGClass + "onStarted chord"); if (null != mListener) mListener.onUpdateNodeInfo(name, mChord.getIp()); if (STARTED_BY_RECONNECTION == reason) { Log.e(TAG, TAGClass + "STARTED_BY_RECONNECTION"); return; } // if(STARTED_BY_USER == reason) : Returns result of calling // start // #4.(optional) listen for public channel IChordChannel channel = mChord.joinChannel(ChordManager.PUBLIC_CHANNEL, mChannelListener); if (null == channel) { Log.e(TAG, TAGClass + "fail to join public"); } } @Override public void onNetworkDisconnected() { Log.e(TAG, TAGClass + "onNetworkDisconnected()"); if (null != mListener) mListener.onNetworkDisconnected(); } @Override public void onError(int error) { // TODO Auto-generated method stub } }); } // This interface defines a listener for chord channel events. private IChordChannelListener mChannelListener = new IChordChannelListener() { /* * Called when a node join event is raised on the channel. * @param fromNode The node name corresponding to which the join event * has been raised. * @param fromChannel The channel on which the join event has been * raised. */ @Override public void onNodeJoined(String fromNode, String fromChannel) { Log.v(TAG, TAGClass + "onNodeJoined(), fromNode : " + fromNode + ", fromChannel : " + fromChannel); if (null != mListener) mListener.onNodeEvent(fromNode, fromChannel, true); } /* * Called when a node leave event is raised on the channel. * @param fromNode The node name corresponding to which the leave event * has been raised. * @param fromChannel The channel on which the leave event has been * raised. */ @Override public void onNodeLeft(String fromNode, String fromChannel) { Log.v(TAG, TAGClass + "onNodeLeft(), fromNode : " + fromNode + ", fromChannel : " + fromChannel); if (null != mListener) mListener.onNodeEvent(fromNode, fromChannel, false); } /* * Called when the data message received from the node. * @param fromNode The node name that the message is sent from. * @param fromChannel The channel name that is raised event. * @param payloadType User defined message type * @param payload Array of payload. */ @Override public void onDataReceived(String fromNode, String fromChannel, String payloadType, byte[][] payload) { Log.v(TAG, TAGClass + "onDataReceived()"); if (!CHORD_APITEST_MESSAGE_TYPE.equals(payloadType)) return; byte[] buf = payload[0]; if (null != mListener) mListener.onReceiveMessage(fromNode, fromChannel, new String(buf)); } /* * Called when the Share file notification is received. User can decide * to receive or reject the file. * @param fromNode The node name that the file transfer is requested by. * @param fromChannel The channel name that is raised event. * @param fileName File name * @param hash Hash value * @param fileType User defined file type * @param exchangeId Exchange ID * @param fileSize File size */ @Override public void onFileWillReceive(String fromNode, String fromChannel, String fileName, String hash, String fileType, String exchangeId, long fileSize) { Log.d(TAG, TAGClass + "[originalName : " + fileName + " from : " + fromNode + " exchangeId : " + exchangeId + " fileSize : " + fileSize + "]"); File targetdir = new File(chordFilePath); if (!targetdir.exists()) { targetdir.mkdirs(); } // Because the external storage may be unavailable, // you should verify that the volume is available before accessing it. // But also, onFileFailed with ERROR_FILE_SEND_FAILED will be called while Chord got failed to write file. StatFs stat = new StatFs(chordFilePath); long blockSize = stat.getBlockSize(); long totalBlocks = stat.getAvailableBlocks(); long availableMemory = blockSize * totalBlocks; if (availableMemory < fileSize) { rejectFile(fromChannel, exchangeId); if (null != mListener) mListener.onFileCompleted(IChordServiceListener.FAILED, fromNode, fromChannel, exchangeId, fileName); return; } if (null != mListener) mListener.onFileWillReceive(fromNode, fromChannel, fileName, exchangeId); } /* * Called when an individual chunk of the file is received. receive or * reject the file. * @param fromNode The node name that the file transfer is requested by. * @param fromChannel The channel name that is raised event. * @param fileName File name * @param hash Hash value * @param fileType User defined file type * @param exchangeId Exchange ID * @param fileSize File size * @param offset Chunk offset */ @Override public void onFileChunkReceived(String fromNode, String fromChannel, String fileName, String hash, String fileType, String exchangeId, long fileSize, long offset) { if (null != mListener) { int progress = (int)(offset * 100 / fileSize); mListener.onFileProgress(false, fromNode, fromChannel, progress, exchangeId); } } /* * Called when the file transfer is completed from the node. * @param fromNode The node name that the file transfer is requested by. * @param fromChannel The channel name that is raised event. * @param fileName File name * @param hash Hash value * @param fileType User defined file type * @param exchangeId Exchange ID * @param fileSize File size * @param tmpFilePath Temporarily stored file path it is assigned with * setTempDirectory() */ @Override public void onFileReceived(String fromNode, String fromChannel, String fileName, String hash, String fileType, String exchangeId, long fileSize, String tmpFilePath) { String savedName = fileName; int i = savedName.lastIndexOf("."); String name = savedName.substring(0, i); String ext = savedName.substring(i); Log.d(TAG, TAGClass + "onFileReceived : " + fileName); Log.d(TAG, TAGClass + "onFileReceived : " + name + " " + ext); File targetFile = new File(chordFilePath, savedName); int index = 0; while (targetFile.exists()) { savedName = name + "_" + index + ext; targetFile = new File(chordFilePath, savedName); index++; Log.d(TAG, TAGClass + "onFileReceived : " + savedName); } File srcFile = new File(tmpFilePath); srcFile.renameTo(targetFile); if (null != mListener) { mListener.onFileCompleted(IChordServiceListener.RECEIVED, fromNode, fromChannel, exchangeId, savedName); } } /* * Called when an individual chunk of the file is sent. * @param toNode The node name to which the file is sent. * @param toChannel The channel name that is raised event. * @param fileName File name * @param hash Hash value * @param fileType User defined file type * @param exchangeId Exchange ID * @param fileSize File size * @param offset Offset * @param chunkSize Chunk size */ @Override public void onFileChunkSent(String toNode, String toChannel, String fileName, String hash, String fileType, String exchangeId, long fileSize, long offset, long chunkSize) { if (null != mListener) { int progress = (int)(offset * 100 / fileSize); mListener.onFileProgress(true, toNode, toChannel, progress, exchangeId); } } /* * Called when the file transfer is completed to the node. * @param toNode The node name to which the file is sent. * @param toChannel The channel name that is raised event. * @param fileName File name * @param hash Hash value * @param fileType User defined file type * @param exchangeId Exchange ID */ @Override public void onFileSent(String toNode, String toChannel, String fileName, String hash, String fileType, String exchangeId) { if (null != mListener) { mListener.onFileCompleted(IChordServiceListener.SENT, toNode, toChannel, exchangeId, fileName); } } /* * Called when the error is occurred while the file transfer is in * progress. * @param node The node name that the error is occurred by. * @param channel The channel name that is raised event. * @param fileName File name * @param hash Hash value * @param exchangeId Exchange ID * @param reason The reason for failure could be one of * #ERROR_FILE_CANCELED #ERROR_FILE_CREATE_FAILED * #ERROR_FILE_NO_RESOURCE #ERROR_FILE_REJECTED #ERROR_FILE_SEND_FAILED * #ERROR_FILE_TIMEOUT */ @Override public void onFileFailed(String node, String channel, String fileName, String hash, String exchangeId, int reason) { switch (reason) { case ERROR_FILE_REJECTED: { Log.e(TAG, TAGClass + "onFileFailed() - REJECTED Node : " + node + ", fromChannel : " + channel); if (null != mListener) { mListener.onFileCompleted(IChordServiceListener.REJECTED, node, channel, exchangeId, fileName); } break; } case ERROR_FILE_CANCELED: { Log.e(TAG, TAGClass + "onFileFailed() - CANCELED Node : " + node + ", fromChannel : " + channel); if (null != mListener) { mListener.onFileCompleted(IChordServiceListener.CANCELLED, node, channel, exchangeId, fileName); } break; } case ERROR_FILE_CREATE_FAILED: case ERROR_FILE_NO_RESOURCE: default: Log.e(TAG, TAGClass + "onFileFailed() - " + reason + " : " + node + ", fromChannel : " + channel); if (null != mListener) { mListener.onFileCompleted(IChordServiceListener.FAILED, node, channel, exchangeId, fileName); } break; } } }; // Release chord public void release() throws Exception { if (mChord != null) { mChord.stop(); mChord.setNetworkListener(null); mChord = null; Log.d(TAG, "[UNREGISTER] Chord unregistered"); } } public String getPublicChannel() { return ChordManager.PUBLIC_CHANNEL; } public String getPrivateChannel() { return mPrivateChannelName; } // Send file to the node on the channel. public String sendFile(String toChannel, String strFilePath, String toNode) { Log.d(TAG, TAGClass + "sendFile() "); // Request the channel interface for the specific channel name. IChordChannel channel = mChord.getJoinedChannel(toChannel); if (null == channel) { Log.e(TAG, TAGClass + "sendFile() : invalid channel instance"); return null; } /* * @param toNode The node name that the file is sent to. It is * mandatory. * @param fileType User defined file type. It is mandatory. * @param filePath The absolute path of the file to be transferred. It * is mandatory. * @param timeoutMsec The time to allow the receiver to accept the * receiving data requests. */ return channel.sendFile(toNode, MESSAGE_TYPE_FILE_NOTIFICATION, strFilePath, SHARE_FILE_TIMEOUT_MILISECONDS); } // Accept to receive file. public boolean acceptFile(String fromChannel, String exchangeId) { Log.d(TAG, TAGClass + "acceptFile()"); // Request the channel interface for the specific channel name. IChordChannel channel = mChord.getJoinedChannel(fromChannel); if (null == channel) { Log.e(TAG, TAGClass + "acceptFile() : invalid channel instance"); return false; } /* * @param exchangeId Exchanged ID * @param chunkTimeoutMsec The timeout to request the chunk data. * @param chunkRetries The count that allow to retry to request chunk * data. * @param chunkSize Chunk size */ return channel.acceptFile(exchangeId, 30*1000, 2, 300 * 1024); } // Cancel file transfer while it is in progress. public boolean cancelFile(String channelName, String exchangeId) { Log.d(TAG, TAGClass + "cancelFile()"); // Request the channel interface for the specific channel name. IChordChannel channel = mChord.getJoinedChannel(channelName); if (null == channel) { Log.e(TAG, TAGClass + "cancelFile() : invalid channel instance"); return false; } // @param exchangeId Exchanged ID return channel.cancelFile(exchangeId); } // Reject to receive file. public boolean rejectFile(String fromChannel, String coreTransactionId) { Log.d(TAG, TAGClass + "rejectFile()"); // Request the channel interface for the specific channel name. IChordChannel channel = mChord.getJoinedChannel(fromChannel); if (null == channel) { Log.e(TAG, TAGClass + "cancelFile() : invalid channel instance"); return false; } // @param exchangeId Exchanged ID return channel.rejectFile(coreTransactionId); } // Requests for nodes on the channel. public List<String> getJoinedNodeList(String channelName) { Log.d(TAG, TAGClass + "getJoinedNodeList()"); // Request the channel interface for the specific channel name. IChordChannel channel = mChord.getJoinedChannel(channelName); if (null == channel) { Log.e(TAG, TAGClass + "getJoinedNodeList() : invalid channel instance-" + channelName); return null; } return channel.getJoinedNodeList(); } // Send data message to the node. public boolean sendData(String toChannel, byte[] buf, String nodeName) { if (mChord == null) { Log.v(TAG, "sendData : mChord IS NULL !!"); return false; } // Request the channel interface for the specific channel name. IChordChannel channel = mChord.getJoinedChannel(toChannel); if (null == channel) { Log.e(TAG, TAGClass + "sendData : invalid channel instance"); return false; } if (nodeName == null) { Log.v(TAG, "sendData : NODE Name IS NULL !!"); return false; } byte[][] payload = new byte[1][]; payload[0] = buf; Log.v(TAG, TAGClass + "sendData : " + new String(buf) + ", des : " + nodeName); /* * @param toNode The joined node name that the message is sent to. It is * mandatory. * @param payloadType User defined message type. It is mandatory. * @param payload The package of data to send * @return Returns true when file transfer is success. Otherwise, false * is returned */ if (false == channel.sendData(nodeName, CHORD_APITEST_MESSAGE_TYPE, payload)) { Log.e(TAG, TAGClass + "sendData : fail to sendData"); return false; } return true; } // Send data message to the all nodes on the channel. public boolean sendDataToAll(String toChannel, byte[] buf) { if (mChord == null) { Log.v(TAG, "sendDataToAll : mChord IS NULL !!"); return false; } // Request the channel interface for the specific channel name. IChordChannel channel = mChord.getJoinedChannel(toChannel); if (null == channel) { Log.e(TAG, TAGClass + "sendDataToAll : invalid channel instance"); return false; } byte[][] payload = new byte[1][]; payload[0] = buf; Log.v(TAG, TAGClass + "sendDataToAll : " + new String(buf)); /* * @param payloadType User defined message type. It is mandatory. * @param payload The package of data to send * @return Returns true when file transfer is success. Otherwise, false * is returned. */ if (false == channel.sendDataToAll(CHORD_APITEST_MESSAGE_TYPE, payload)) { Log.e(TAG, TAGClass + "sendDataToAll : fail to sendDataToAll"); return false; } return true; } /* * Set a keep-alive timeout. Node has keep-alive timeout. The timeoutMsec * determines the maximum keep-alive time to wait to leave when there is no * data from the nodes. Default time is 15000 millisecond. */ public void setNodeKeepAliveTimeout(long timeoutMsec) { Log.d(TAG, TAGClass + "setNodeKeepAliveTimeout()"); // @param timeoutMsec Timeout with millisecond. mChord.setNodeKeepAliveTimeout(timeoutMsec); } // Get an IPv4 address that the node has. public String getNodeIpAddress(String channelName, String nodeName) { Log.d(TAG, TAGClass + "getNodeIpAddress() channelName : " + channelName + ", nodeName : " + nodeName); // Request the channel interface for the specific channel name. IChordChannel channel = mChord.getJoinedChannel(channelName); if(null == channel){ Log.e(TAG, TAGClass + "getNodeIpAddress : invalid channel instance"); return ""; } /* * @param nodeName The node name to find IPv4 address. * @return Returns an IPv4 Address.When there is not the node name in * the channel, null is returned. */ return channel.getNodeIpAddress(nodeName); } // Get a list of available network interface types. public List<Integer> getAvailableInterfaceTypes() { Log.d(TAG, TAGClass + "getAvailableInterfaceTypes()"); /* * @return Returns a list of available network interface types. * #INTERFACE_TYPE_WIFI Wi-Fi #INTERFACE_TYPE_WIFIAP Wi-Fi mobile * hotspot #INTERFACE_TYPE_WIFIP2P Wi-Fi Direct */ return mChord.getAvailableInterfaceTypes(); } // Request for joined channel interfaces. public List<IChordChannel> getJoinedChannelList() { Log.d(TAG, TAGClass + "getJoinedChannelList()"); // @return Returns a list of handle for joined channel. It returns an // empty list, there is no joined channel. return mChord.getJoinedChannelList(); } // Join a desired channel with a given listener. public IChordChannel joinChannel(String channelName) { Log.d(TAG, TAGClass + "joinChannel()" + channelName); if (channelName == null || channelName.equals("")) { Log.e(TAG, TAGClass + "joinChannel > " + mPrivateChannelName + " is invalid! Default private channel join"); mPrivateChannelName = CHORD_APITEST_CHANNEL; } else { mPrivateChannelName = channelName; } /* * @param channelName Channel name. It is a mandatory input. * @param listener A listener that gets notified when there is events in * joined channel mandatory. It is a mandatory input. * @return Returns a handle of the channel if it is joined successfully, * null otherwise. */ IChordChannel channelInst = mChord.joinChannel(mPrivateChannelName, mChannelListener); if (null == channelInst) { Log.d(TAG, "fail to joinChannel! "); return null; } return channelInst; } // Leave a given channel. public void leaveChannel() { Log.d(TAG, TAGClass + "leaveChannel()"); // @param channelName Channel name mChord.leaveChannel(mPrivateChannelName); mPrivateChannelName = ""; } // Stop chord public void stop() { Log.d(TAG, TAGClass + "stop()"); releaseWakeLock(); if (mChord != null) { mChord.stop(); } } private void acqureWakeLock(){ if(null == mWakeLock){ PowerManager powerMgr = (PowerManager)getSystemService(Context.POWER_SERVICE); mWakeLock = powerMgr.newWakeLock(PowerManager.FULL_WAKE_LOCK, "ChordApiDemo Lock"); Log.d(TAG, "acqureWakeLock : new"); } if(mWakeLock.isHeld()){ Log.w(TAG, "acqureWakeLock : already acquire"); mWakeLock.release(); } Log.d(TAG, "acqureWakeLock : acquire"); mWakeLock.acquire(); } private void releaseWakeLock(){ if(null != mWakeLock && mWakeLock.isHeld()){ Log.d(TAG, "releaseWakeLock"); mWakeLock.release(); } } }
/* * #%L * AuthenticatingConnectionTest.java - mongodb-async-driver - Allanbank Consulting, Inc. * %% * Copyright (C) 2011 - 2014 Allanbank Consulting, Inc. * %% * 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. * #L% */ package com.allanbank.mongodb.client.connection.auth; import static com.allanbank.mongodb.bson.builder.BuilderFactory.start; import static com.allanbank.mongodb.client.connection.CallbackReply.cb; import static org.easymock.EasyMock.anyObject; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.eq; import static org.easymock.EasyMock.expectLastCall; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.reset; import static org.easymock.EasyMock.verify; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.allanbank.mongodb.Credential; import com.allanbank.mongodb.Durability; import com.allanbank.mongodb.MongoClientConfiguration; import com.allanbank.mongodb.MongoDbException; import com.allanbank.mongodb.bson.Document; import com.allanbank.mongodb.bson.builder.BuilderFactory; import com.allanbank.mongodb.bson.builder.DocumentBuilder; import com.allanbank.mongodb.client.Message; import com.allanbank.mongodb.client.callback.FutureReplyCallback; import com.allanbank.mongodb.client.callback.ReplyCallback; import com.allanbank.mongodb.client.connection.Connection; import com.allanbank.mongodb.client.message.Command; import com.allanbank.mongodb.client.message.Delete; import com.allanbank.mongodb.client.message.GetLastError; import com.allanbank.mongodb.error.MongoDbAuthenticationException; import com.allanbank.mongodb.util.IOUtils; /** * AuthenticatingConnectionTest provides test for the * {@link AuthenticatingConnection}. * * @copyright 2012-2014, Allanbank Consulting, Inc., All Rights Reserved */ public class AuthenticatingConnectionTest { /** An empty document for use in constructing messages. */ public static final Document EMPTY_DOC = BuilderFactory.start().build(); /** The database name used for testing. */ public static final String TEST_DB = "db"; /** The authenticate reply message. */ private DocumentBuilder myAuthReply; /** The authenticate request message. */ private DocumentBuilder myAuthRequest; /** A configuration setup to authenticate requests. */ private MongoClientConfiguration myConfig; /** The nonce reply message. */ private DocumentBuilder myNonceReply; /** The nonce request message. */ private DocumentBuilder myNonceRequest; /** * Creates the basic authenticate messages. */ @Before public void setUp() { myConfig = new MongoClientConfiguration(); myConfig.addCredential(Credential.builder().userName("allanbank") .password("super_secret_password".toCharArray()) .database(TEST_DB).authenticationType(Credential.MONGODB_CR) .build()); myNonceRequest = BuilderFactory.start(); myNonceRequest.addInteger("getnonce", 1); myNonceReply = BuilderFactory.start(); myNonceReply.addString("nonce", "deadbeef4bee"); myAuthRequest = BuilderFactory.start(); myAuthRequest.addInteger("authenticate", 1); myAuthRequest.addString("nonce", "deadbeef4bee"); myAuthRequest.addString("user", "allanbank"); myAuthRequest.addString("key", "d74c03a816dee3427c7459dce9c94e54"); myAuthReply = BuilderFactory.start(); myAuthReply.addInteger("ok", 1); } /** * Cleans up the test. */ @After public void tearDown() { myConfig = null; myNonceRequest = null; myNonceReply = null; myAuthRequest = null; myAuthReply = null; } /** * Test method for {@link AuthenticatingConnection#send} . * * @throws IOException * On a failure setting up the mocks for the test. */ @Test public void testAuthenticateFails() throws IOException { myAuthReply.reset(); myAuthReply.addInteger("ok", 0); final Message msg = new Delete(TEST_DB, "collection", EMPTY_DOC, true); final Connection mockConnection = createMock(Connection.class); // Nonce. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myNonceRequest.build())), cb(myNonceReply)); expectLastCall(); // Auth. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myAuthRequest.build())), cb(myAuthReply)); expectLastCall(); mockConnection.close(); expectLastCall(); replay(mockConnection); final AuthenticatingConnection conn = new AuthenticatingConnection( mockConnection, myConfig); try { conn.send(msg, null); fail("Should throw an exception when authentication falis."); } catch (final MongoDbAuthenticationException good) { // Good. } try { conn.send(msg, null); } catch (final MongoDbAuthenticationException good) { // Good. Ask once. Keep failing. } IOUtils.close(conn); verify(mockConnection); } /** * Test method for {@link AuthenticatingConnection#send} . * * @throws IOException * On a failure setting up the mocks for the test. */ @Test public void testAuthenticateFailsNonNumericOk() throws IOException { myAuthReply.reset(); myAuthReply.addString("ok", "foo"); final Message msg = new Delete(TEST_DB, "collection", EMPTY_DOC, true); final Connection mockConnection = createMock(Connection.class); // Nonce. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myNonceRequest.build())), cb(myNonceReply)); expectLastCall(); // Auth. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myAuthRequest.build())), cb(myAuthReply)); expectLastCall(); mockConnection.close(); expectLastCall(); replay(mockConnection); final AuthenticatingConnection conn = new AuthenticatingConnection( mockConnection, myConfig); try { conn.send(msg, null); fail("Should throw an exception when authentication falis."); } catch (final MongoDbAuthenticationException good) { // Good. } try { conn.send(msg, null); } catch (final MongoDbAuthenticationException good) { // Good. Ask once. Keep failing. } IOUtils.close(conn); verify(mockConnection); } /** * Test method for {@link AuthenticatingConnection#send} . * * @throws IOException * On a failure setting up the mocks for the test. */ @Test public void testAuthenticateFailsNoNonceInReplyDoc() throws IOException { myNonceReply.reset(); myNonceReply.addString("not_a_nonce", "foo"); final Message msg = new Delete(TEST_DB, "collection", EMPTY_DOC, true); final Connection mockConnection = createMock(Connection.class); // Nonce. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myNonceRequest.build())), cb(myNonceReply)); expectLastCall(); mockConnection.close(); expectLastCall(); replay(mockConnection); final AuthenticatingConnection conn = new AuthenticatingConnection( mockConnection, myConfig); try { conn.send(msg, null); fail("Should throw an exception when authentication falis."); } catch (final MongoDbAuthenticationException good) { // Good. } IOUtils.close(conn); verify(mockConnection); } /** * Test method for {@link AuthenticatingConnection#send} . * * @throws IOException * On a failure setting up the mocks for the test. */ @Test public void testAuthenticateFailsNoNonceReplyDoc() throws IOException { final Message msg = new Delete(TEST_DB, "collection", EMPTY_DOC, true); final Connection mockConnection = createMock(Connection.class); // Nonce. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myNonceRequest.build())), cb()); expectLastCall(); mockConnection.close(); expectLastCall(); replay(mockConnection); final AuthenticatingConnection conn = new AuthenticatingConnection( mockConnection, myConfig); try { conn.send(msg, null); fail("Should throw an exception when authentication falis."); } catch (final MongoDbAuthenticationException good) { // Good. } IOUtils.close(conn); verify(mockConnection); } /** * Test method for {@link AuthenticatingConnection#send} . * * @throws IOException * On a failure setting up the mocks for the test. */ @Test public void testAuthenticateFailsWithRetry() throws IOException { myAuthReply.reset(); myAuthReply.addInteger("ok", 0); final Message msg = new Delete(TEST_DB, "collection", EMPTY_DOC, true); final Connection mockConnection = createMock(Connection.class); // Nonce. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myNonceRequest.build())), cb(myNonceReply)); expectLastCall(); // Auth. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myAuthRequest.build())), cb(myAuthReply)); expectLastCall(); replay(mockConnection); final AuthenticatingConnection conn = new AuthenticatingConnection( mockConnection, myConfig); try { conn.send(msg, null); fail("Should throw an exception when authentication falis."); } catch (final MongoDbAuthenticationException good) { // Good. } try { conn.send(msg, null); } catch (final MongoDbAuthenticationException good) { // Good. Ask once. Keep failing. } verify(mockConnection); // Setup for the auth retry. reset(mockConnection); myAuthReply.reset(); myAuthReply.addInteger("ok", 1); // Nonce. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myNonceRequest.build())), cb(myNonceReply)); expectLastCall(); // Auth. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myAuthRequest.build())), cb(myAuthReply)); expectLastCall(); // Message. mockConnection.send(msg, null); expectLastCall(); mockConnection.close(); expectLastCall(); replay(mockConnection); // Wait for the retry interval to expire. sleep(AuthenticatingConnection.RETRY_INTERVAL_MS + AuthenticatingConnection.RETRY_INTERVAL_MS); // Note that normally the auth would be delayed but with the EasyMock // callbacks the authentication completes on this thread. try { conn.send(msg, null); fail("Should throw an exception when authentication fails."); } catch (final MongoDbAuthenticationException good) { // Good. } try { conn.send(msg, null); } catch (final MongoDbAuthenticationException good) { // Good. fail("Should not throw an exception when authentication retry succeeds."); } IOUtils.close(conn); verify(mockConnection); } /** * Test method for {@link AuthenticatingConnection#send} . * * @throws IOException * On a failure setting up the mocks for the test. */ @Test public void testAuthenticateFailsWithRetryAndCredentialRemoved() throws IOException { myAuthReply.reset(); myAuthReply.addInteger("ok", 0); final Message msg = new Delete(TEST_DB, "collection", EMPTY_DOC, true); final Connection mockConnection = createMock(Connection.class); // Nonce. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myNonceRequest.build())), cb(myNonceReply)); expectLastCall(); // Auth. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myAuthRequest.build())), cb(myAuthReply)); expectLastCall(); replay(mockConnection); final AuthenticatingConnection conn = new AuthenticatingConnection( mockConnection, myConfig); try { conn.send(msg, null); fail("Should throw an exception when authentication falis."); } catch (final MongoDbAuthenticationException good) { // Good. } try { conn.send(msg, null); } catch (final MongoDbAuthenticationException good) { // Good. Ask once. Keep failing. } verify(mockConnection); // Setup for the auth retry. reset(mockConnection); // Remove the credentials. final List<Credential> noCredentials = Collections.emptyList(); myConfig.setCredentials(noCredentials); // Message. mockConnection.send(msg, null); expectLastCall(); mockConnection.close(); expectLastCall(); replay(mockConnection); // Wait for the retry interval to expire. sleep(AuthenticatingConnection.RETRY_INTERVAL_MS + AuthenticatingConnection.RETRY_INTERVAL_MS); // Note that normally the auth would be delayed but with the EasyMock // callbacks the authentication completes on this thread. try { conn.send(msg, null); fail("Should throw an exception when authentication fails."); } catch (final MongoDbAuthenticationException good) { // Good. } try { conn.send(msg, null); } catch (final MongoDbAuthenticationException good) { // Good. fail("Should not throw an exception when authentication credentials are removed."); } IOUtils.close(conn); verify(mockConnection); } /** * Test method for {@link AuthenticatingConnection#send} . * * @throws IOException * On a failure setting up the mocks for the test. */ @Test public void testAuthenticateFailsWithRetryExternal() throws IOException { myConfig.addCredential(Credential.builder().userName("allanbank") .password("super_secret_password".toCharArray()) .database(AuthenticatingConnection.EXTERNAL_DB_NAME) .authenticationType(Credential.MONGODB_CR).build()); final Message msg = new Delete(TEST_DB, "collection", EMPTY_DOC, true); final Connection mockConnection = createMock(Connection.class); // Nonce. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myNonceRequest.build())), cb(myNonceReply)); expectLastCall(); // Auth. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myAuthRequest.build())), cb(myAuthReply)); expectLastCall(); // Nonce - external mockConnection.send(eq(new Command( AuthenticatingConnection.EXTERNAL_DB_NAME, Command.COMMAND_COLLECTION, myNonceRequest.build())), cb(myNonceReply)); expectLastCall(); // Auth - external myAuthReply.reset(); myAuthReply.addInteger("ok", 0); mockConnection.send(eq(new Command( AuthenticatingConnection.EXTERNAL_DB_NAME, Command.COMMAND_COLLECTION, myAuthRequest.build())), cb(myAuthReply)); expectLastCall(); // Message. mockConnection.send(msg, null); expectLastCall(); replay(mockConnection); final AuthenticatingConnection conn = new AuthenticatingConnection( mockConnection, myConfig); try { conn.send(msg, null); } catch (final MongoDbAuthenticationException good) { fail("Should not fail when the authentication succeeds on the database."); } verify(mockConnection); // Setup for the auth retry. reset(mockConnection); myAuthReply.reset(); myAuthReply.addInteger("ok", 1); // Nonce. mockConnection.send(eq(new Command( AuthenticatingConnection.EXTERNAL_DB_NAME, Command.COMMAND_COLLECTION, myNonceRequest.build())), cb(myNonceReply)); expectLastCall(); // Auth - external myAuthReply.reset(); myAuthReply.addInteger("ok", 1); mockConnection.send(eq(new Command( AuthenticatingConnection.EXTERNAL_DB_NAME, Command.COMMAND_COLLECTION, myAuthRequest.build())), cb(myAuthReply)); expectLastCall(); // Message. mockConnection.send(msg, null); expectLastCall(); mockConnection.close(); expectLastCall(); replay(mockConnection); // Wait for the retry interval to expire. sleep(AuthenticatingConnection.RETRY_INTERVAL_MS + AuthenticatingConnection.RETRY_INTERVAL_MS); // Note that normally the auth would be delayed but with the EasyMock // callbacks the authentication completes on this thread. try { conn.send(msg, null); } catch (final MongoDbAuthenticationException good) { fail("Should not fail when the authentication succeeds on the database."); } IOUtils.close(conn); verify(mockConnection); } /** * Test method for {@link AuthenticatingConnection#send} . * * @throws IOException * On a failure setting up the mocks for the test. */ @Test public void testAuthenticateFailsWithRetryFails() throws IOException { myAuthReply.reset(); myAuthReply.addInteger("ok", 0); final Message msg = new Delete(TEST_DB, "collection", EMPTY_DOC, true); final Connection mockConnection = createMock(Connection.class); // Nonce. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myNonceRequest.build())), cb(myNonceReply)); expectLastCall(); // Auth. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myAuthRequest.build())), cb(myAuthReply)); expectLastCall(); replay(mockConnection); final AuthenticatingConnection conn = new AuthenticatingConnection( mockConnection, myConfig); try { conn.send(msg, null); fail("Should throw an exception when authentication falis."); } catch (final MongoDbAuthenticationException good) { // Good. } try { conn.send(msg, null); } catch (final MongoDbAuthenticationException good) { // Good. Ask once. Keep failing. } verify(mockConnection); // Setup for the auth retry. reset(mockConnection); // Nonce. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myNonceRequest.build())), cb(myNonceReply)); expectLastCall(); // Auth. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myAuthRequest.build())), cb(myAuthReply)); expectLastCall(); mockConnection.close(); expectLastCall(); replay(mockConnection); // Wait for the retry interval to expire. sleep(AuthenticatingConnection.RETRY_INTERVAL_MS + AuthenticatingConnection.RETRY_INTERVAL_MS); // Note that normally the auth would be delayed but with the EasyMock // callbacks the authentication completes on this thread. try { conn.send(msg, null); fail("Should throw an exception when authentication fails."); } catch (final MongoDbAuthenticationException good) { // Good. } try { conn.send(msg, null); fail("Should throw an exception when authentication fails."); } catch (final MongoDbAuthenticationException good) { // Good. Ask once. Keep failing. } IOUtils.close(conn); verify(mockConnection); } /** * Test method for {@link AuthenticatingConnection#send} . * * @throws IOException * On a failure setting up the mocks for the test. */ @Test public void testAuthenticateReplyException() throws IOException { final Message msg = new Delete(TEST_DB, "collection", EMPTY_DOC, true); final MongoDbException injected = new MongoDbException("Injected"); final Connection mockConnection = createMock(Connection.class); // Nonce. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myNonceRequest.build())), cb(myNonceReply)); expectLastCall(); // Auth. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myAuthRequest.build())), cb(injected)); expectLastCall(); mockConnection.close(); expectLastCall(); replay(mockConnection); final AuthenticatingConnection conn = new AuthenticatingConnection( mockConnection, myConfig); try { conn.send(msg, null); fail("Should throw an exception when authentication falis."); } catch (final MongoDbException good) { // Good. assertSame(injected, good.getCause().getCause().getCause()); } // And again. try { conn.send(msg, null); fail("Should throw an exception when authentication falis."); } catch (final MongoDbException good) { // Good. assertSame(injected, good.getCause().getCause().getCause()); } IOUtils.close(conn); verify(mockConnection); } /** * Test method for {@link AuthenticatingConnection#send} . * * @throws IOException * On a failure setting up the mocks for the test. */ @Test public void testAuthenticateRequestFails() throws IOException { final Message msg = new Delete(TEST_DB, "collection", EMPTY_DOC, true); final MongoDbException injected = new MongoDbException("Injected"); final Connection mockConnection = createMock(Connection.class); // Nonce. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myNonceRequest.build())), cb(myNonceReply)); expectLastCall(); // Auth. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myAuthRequest.build())), anyObject(ReplyCallback.class)); expectLastCall().andThrow(injected); // Just a log message (now). mockConnection.close(); expectLastCall(); replay(mockConnection); final AuthenticatingConnection conn = new AuthenticatingConnection( mockConnection, myConfig); try { conn.send(msg, null); fail("Should throw an exception when authentication fails."); } catch (final MongoDbException good) { // Good. // Our error should be in there somewhere. Throwable thrown = good; while (thrown != null) { if (injected == thrown) { break; } thrown = thrown.getCause(); } assertSame(injected, thrown); } // And again. try { conn.send(msg, null); fail("Should throw an exception when authentication falis."); } catch (final MongoDbException good) { // Good. // Our error should be in there somewhere. Throwable thrown = good; while (thrown != null) { if (injected == thrown) { break; } thrown = thrown.getCause(); } assertSame(injected, thrown); } IOUtils.close(conn); verify(mockConnection); } /** * Test method for {@link AuthenticatingConnection#send} . * * @throws IOException * On a failure setting up the mocks for the test. */ @Test public void testAuthWithMultipleCredentials() throws IOException { myConfig.addCredential(Credential.builder().userName("allanbank") .password("super_secret_password".toCharArray()) .database(TEST_DB + '1') .authenticationType(Credential.MONGODB_CR).build()); final Delete msg = new Delete(TEST_DB, "collection", EMPTY_DOC, true); final Connection mockConnection = createMock(Connection.class); // Nonce. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myNonceRequest.build())), cb(myNonceReply)); expectLastCall(); // Auth. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myAuthRequest.build())), cb(myAuthReply)); expectLastCall(); // Nonce. mockConnection.send(eq(new Command(TEST_DB + '1', Command.COMMAND_COLLECTION, myNonceRequest.build())), cb(myNonceReply)); expectLastCall(); // Auth. mockConnection.send(eq(new Command(TEST_DB + '1', Command.COMMAND_COLLECTION, myAuthRequest.build())), cb(myAuthReply)); expectLastCall(); // Message. mockConnection.send(msg, null); expectLastCall(); mockConnection.close(); expectLastCall(); replay(mockConnection); final AuthenticatingConnection conn = new AuthenticatingConnection( mockConnection, myConfig); conn.send(msg, null); IOUtils.close(conn); verify(mockConnection); } /** * Test method for {@link AuthenticatingConnection#send} . * * @throws IOException * On a failure setting up the mocks for the test. */ @Test public void testAuthWithMultipleCredentialsFailures() throws IOException { myConfig.addCredential(Credential.builder().userName("allanbank") .password("super_secret_password".toCharArray()) .database(TEST_DB + '1') .authenticationType(Credential.MONGODB_CR).build()); final Delete msg = new Delete(TEST_DB, "collection", EMPTY_DOC, true); final Connection mockConnection = createMock(Connection.class); // Nonce. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myNonceRequest.build())), cb(myNonceReply)); expectLastCall(); // Auth -- Failure mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myAuthRequest.build())), cb(start(myAuthReply).remove("ok"))); expectLastCall(); // Nonce. mockConnection.send(eq(new Command(TEST_DB + '1', Command.COMMAND_COLLECTION, myNonceRequest.build())), cb(myNonceReply)); expectLastCall(); // Auth -- Failure 2 mockConnection.send(eq(new Command(TEST_DB + '1', Command.COMMAND_COLLECTION, myAuthRequest.build())), cb(start(myAuthReply).remove("ok").add("ok", 0))); expectLastCall(); mockConnection.close(); expectLastCall(); replay(mockConnection); final AuthenticatingConnection conn = new AuthenticatingConnection( mockConnection, myConfig); try { conn.send(msg, null); fail("Authentication should have failed."); } catch (final MongoDbAuthenticationException good) { // Good. } finally { IOUtils.close(conn); } verify(mockConnection); } /** * Test method for {@link AuthenticatingConnection#send} . * * @throws IOException * On a failure setting up the mocks for the test. */ @Test public void testNoAuthenticateDoc() throws IOException { final Message msg = new Delete(TEST_DB, "collection", EMPTY_DOC, true); final Connection mockConnection = createMock(Connection.class); // Nonce. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myNonceRequest.build())), cb(myNonceReply)); expectLastCall(); // Auth. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myAuthRequest.build())), cb()); expectLastCall(); mockConnection.close(); expectLastCall(); replay(mockConnection); final AuthenticatingConnection conn = new AuthenticatingConnection( mockConnection, myConfig); try { conn.send(msg, null); fail("Should throw an exception when authentication falis."); } catch (final MongoDbAuthenticationException good) { // Good. } IOUtils.close(conn); verify(mockConnection); } /** * Test method for {@link AuthenticatingConnection#send} . * * @throws IOException * On a failure setting up the mocks for the test. */ @Test public void testNoAuthenticateOkDoc() throws IOException { myAuthReply.reset(); myAuthReply.addInteger("not_ok", 0); final Message msg = new Delete(TEST_DB, "collection", EMPTY_DOC, true); final Connection mockConnection = createMock(Connection.class); // Nonce. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myNonceRequest.build())), cb(myNonceReply)); expectLastCall(); // Auth. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myAuthRequest.build())), cb(myAuthReply)); expectLastCall(); mockConnection.close(); expectLastCall(); replay(mockConnection); final AuthenticatingConnection conn = new AuthenticatingConnection( mockConnection, myConfig); try { conn.send(msg, null); fail("Should throw an exception when authentication falis."); } catch (final MongoDbAuthenticationException good) { // Good. } IOUtils.close(conn); verify(mockConnection); } /** * Test method for {@link AuthenticatingConnection#send} . * * @throws IOException * On a failure setting up the mocks for the test. */ @Test public void testNonceFails() throws IOException { final MongoDbException injected = new MongoDbException("Injected"); final Connection mockConnection = createMock(Connection.class); // Nonce. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myNonceRequest.build())), cb()); expectLastCall().andThrow(injected); replay(mockConnection); try { final AuthenticatingConnection conn = new AuthenticatingConnection( mockConnection, myConfig); fail("Should throw an exception when nonce fails."); conn.close(); } catch (final MongoDbException good) { // Good. assertSame(injected, good); } verify(mockConnection); } /** * Test that the old and new password hash values match. * * @throws NoSuchAlgorithmException * On a failure. */ @Test @Deprecated public void testPasswordHash() throws NoSuchAlgorithmException { final MongoClientConfiguration config = new MongoClientConfiguration(); config.authenticate("allanbank", "super_secret_password"); final Credential credential = Credential.builder() .userName("allanbank") .password("super_secret_password".toCharArray()) .database(TEST_DB).authenticationType(Credential.MONGODB_CR) .build(); assertEquals(config.getPasswordHash(), new MongoDbAuthenticator().passwordHash(credential)); } /** * Test method for {@link AuthenticatingConnection#send} . * * @throws IOException * On a failure setting up the mocks for the test. */ @Test public void testSendAdminMessageArrayAsNonAdmin() throws IOException { myConfig.setCredentials(Arrays.asList(Credential.builder() .userName("allanbank") .password("super_secret_password".toCharArray()) .database("foo").authenticationType(Credential.MONGODB_CR) .build())); final Delete msg = new Delete(MongoClientConfiguration.ADMIN_DB_NAME, "collection", EMPTY_DOC, true); final Connection mockConnection = createMock(Connection.class); // Nonce. mockConnection.send(eq(new Command("foo", Command.COMMAND_COLLECTION, myNonceRequest.build())), cb(myNonceReply)); expectLastCall(); // Auth. mockConnection.send(eq(new Command("foo", Command.COMMAND_COLLECTION, myAuthRequest.build())), cb(myAuthReply)); expectLastCall(); // Message. mockConnection.send(msg, null); expectLastCall(); mockConnection.close(); expectLastCall(); replay(mockConnection); final AuthenticatingConnection conn = new AuthenticatingConnection( mockConnection, myConfig); conn.send(msg, null); IOUtils.close(conn); verify(mockConnection); } /** * Test method for * {@link AuthenticatingConnection#send(Message, ReplyCallback)} . * * @throws IOException * On a failure setting up the mocks for the test. */ @Test public void testSendCallbackOfReplyMessageArray() throws IOException { final ReplyCallback reply = new FutureReplyCallback(); final Delete msg = new Delete(TEST_DB, "collection", EMPTY_DOC, true); final Connection mockConnection = createMock(Connection.class); // Nonce. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myNonceRequest.build())), cb(myNonceReply)); expectLastCall(); // Auth. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myAuthRequest.build())), cb(myAuthReply)); expectLastCall(); // Message. mockConnection.send(msg, reply); expectLastCall(); mockConnection.close(); expectLastCall(); replay(mockConnection); final AuthenticatingConnection conn = new AuthenticatingConnection( mockConnection, myConfig); conn.send(msg, reply); IOUtils.close(conn); verify(mockConnection); } /** * Test method for {@link AuthenticatingConnection#send} . * * @throws IOException * On a failure setting up the mocks for the test. */ @Test public void testSendMessage2() throws IOException { final Delete msg = new Delete(TEST_DB, "collection", EMPTY_DOC, true); final GetLastError msg2 = new GetLastError(TEST_DB, Durability.ACK); final Connection mockConnection = createMock(Connection.class); // Nonce. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myNonceRequest.build())), cb(myNonceReply)); expectLastCall(); // Auth. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myAuthRequest.build())), cb(myAuthReply)); expectLastCall(); // Message. mockConnection.send(msg, msg2, null); expectLastCall(); mockConnection.close(); expectLastCall(); replay(mockConnection); final AuthenticatingConnection conn = new AuthenticatingConnection( mockConnection, myConfig); conn.send(msg, msg2, null); IOUtils.close(conn); verify(mockConnection); } /** * Test method for {@link AuthenticatingConnection#send} . * * @throws IOException * On a failure setting up the mocks for the test. */ @Test public void testSendMessageArray() throws IOException { final Delete msg = new Delete(TEST_DB, "collection", EMPTY_DOC, true); final Connection mockConnection = createMock(Connection.class); // Nonce. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myNonceRequest.build())), cb(myNonceReply)); expectLastCall(); // Auth. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myAuthRequest.build())), cb(myAuthReply)); expectLastCall(); // Message. mockConnection.send(msg, null); expectLastCall(); mockConnection.close(); expectLastCall(); replay(mockConnection); final AuthenticatingConnection conn = new AuthenticatingConnection( mockConnection, myConfig); conn.send(msg, null); IOUtils.close(conn); verify(mockConnection); } /** * Test method for {@link AuthenticatingConnection#send} . * * @throws IOException * On a failure setting up the mocks for the test. */ @Test public void testSendMessageArrayAsAdmin() throws IOException { myConfig.setCredentials(Arrays.asList(Credential.builder() .userName("allanbank") .password("super_secret_password".toCharArray()) .authenticationType(Credential.MONGODB_CR).build())); final Delete msg = new Delete(TEST_DB, "collection", EMPTY_DOC, true); final Connection mockConnection = createMock(Connection.class); // Nonce. mockConnection.send(eq(new Command("admin", Command.COMMAND_COLLECTION, myNonceRequest.build())), cb(myNonceReply)); expectLastCall(); // Auth. mockConnection.send(eq(new Command("admin", Command.COMMAND_COLLECTION, myAuthRequest.build())), cb(myAuthReply)); expectLastCall(); // Message. mockConnection.send(msg, null); expectLastCall(); mockConnection.close(); expectLastCall(); replay(mockConnection); final AuthenticatingConnection conn = new AuthenticatingConnection( mockConnection, myConfig); conn.send(msg, null); IOUtils.close(conn); verify(mockConnection); } /** * Test method for {@link AuthenticatingConnection#send} . * * @throws IOException * On a failure setting up the mocks for the test. */ @Test public void testSendOnlyAuthenticateOnce() throws IOException { final Message msg = new Delete(TEST_DB, "collection", EMPTY_DOC, true); final Connection mockConnection = createMock(Connection.class); // Nonce. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myNonceRequest.build())), cb(myNonceReply)); expectLastCall(); // Auth. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myAuthRequest.build())), cb(myAuthReply)); expectLastCall(); // Message. mockConnection.send(msg, null); expectLastCall(); // Message, again. mockConnection.send(msg, null); expectLastCall(); mockConnection.close(); expectLastCall(); replay(mockConnection); final AuthenticatingConnection conn = new AuthenticatingConnection( mockConnection, myConfig); conn.send(msg, null); conn.send(msg, null); IOUtils.close(conn); verify(mockConnection); } /** * Test method for {@link AuthenticatingConnection#toString()}. * * @throws IOException * On a failure setting up the mocks for the test. */ @Test public void testToString() throws IOException { final Connection mockConnection = createMock(Connection.class); // Nonce. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myNonceRequest.build())), cb(myNonceReply)); expectLastCall(); // Auth. mockConnection.send(eq(new Command(TEST_DB, Command.COMMAND_COLLECTION, myAuthRequest.build())), cb(myAuthReply)); expectLastCall(); mockConnection.close(); expectLastCall(); replay(mockConnection); final AuthenticatingConnection conn = new AuthenticatingConnection( mockConnection, myConfig); assertEquals( "Auth(EasyMock for interface com.allanbank.mongodb.client.connection.Connection)", conn.toString()); IOUtils.close(conn); verify(mockConnection); } /** * Pauses for the specified amount of time. * * @param timeMs * The time to sleep in milliseconds. */ private void sleep(final long timeMs) { try { Thread.sleep(timeMs); } catch (final InterruptedException e) { // Ignore } } }
package com.smbarne.lazyflickr; import com.actionbarsherlock.app.SherlockListActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.view.MenuItem.OnActionExpandListener; import android.os.Bundle; import android.preference.PreferenceManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.view.View; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.LinearLayout; import android.widget.AdapterView.OnItemClickListener; import android.widget.EditText; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import android.view.KeyEvent; /** * The MainActivity of LazyFlickr. */ public class MainActivity extends SherlockListActivity { LazyListViewAdapter LazyListAdapter; DataLoader mDataLoader; ImageLoader mImageLoader; MenuItem mRefreshItem; MenuItem mSearchItem; String mTagString = ""; LinearLayout mIntroSearch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize the XML data loader and cache instance mDataLoader = DataLoader.getInstance(); mDataLoader.Init(getApplicationContext()); // Initialize the Image loader and cache instance mImageLoader = ImageLoader.getInstance(); mImageLoader.init(getApplicationContext()); LazyListAdapter = new LazyListViewAdapter(this, mImageLoader); setListAdapter(LazyListAdapter); getListView().setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { LaunchPagerActivity(position); } }); SetupInitialScreen(); SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(this.getApplicationContext()); String mTagString = sp.getString("tagString", ""); if (!mTagString.equals("")) RefreshData(); } /** * Initialize the UI for the intro screen if the user has not searched * before or if they have recently cleared the cache. * */ private void SetupInitialScreen() { mIntroSearch = (LinearLayout) findViewById(R.id.emptySearchView); EditText searchText = (EditText) findViewById(R.id.emptySearchEditText); searchText.setOnEditorActionListener(new SearchHandler()); } /** * Check our state, typically from onResume, to see if our mTagString is * still viable. * */ private void checkCacheState() { SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(this.getApplicationContext()); String mTagString = sp.getString("tagString", ""); if (mTagString.equals("")) { if (LazyListAdapter != null) LazyListAdapter.clearData(); mIntroSearch.setVisibility(View.VISIBLE); getListView().getEmptyView().setVisibility(View.GONE); getSupportActionBar().setTitle(R.string.app_name); } else { getSupportActionBar().setTitle(mTagString); mIntroSearch.setVisibility(View.INVISIBLE); if (LazyListAdapter.getCount() == 0) getListView().getEmptyView().setVisibility(View.VISIBLE); } } @Override protected void onResume() { super.onResume(); checkCacheState(); } /** * Launch the gallery ViewPager activity centered at the position provided. * * @param position * Integer position of the image to center the gallery on. */ public void LaunchPagerActivity(int position) { String[] tags = { mTagString }; Intent intent = new Intent(this, PagerActivity.class); intent.putExtra("tags", tags); intent.putExtra("Position", position); startActivity(intent); } /** * Called from the intro screen and functions as a tag search kickoff. * * @param view */ public void onEmptySearchDone(View view) { EditText et = (EditText) findViewById(R.id.emptySearchEditText); ProcessSearchText(et.getText().toString()); } /** * Convert a user input search string into a comma separated tag string. * Store the string in the common preferences manager and handle the UI * transition to having a tag query setup. * * Calls RefreshData() after it is done processing. * * @param text */ public void ProcessSearchText(String text) { // Hide the keyboard, but be sure to null check getCurrentFocus due to the full screen landscape keyboard InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); View v = this.getCurrentFocus(); if (v != null) imm.hideSoftInputFromWindow(v.getWindowToken(), 0); if (!text.equals("")) { mTagString = text.replaceAll("\\s+", ","); SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(this.getApplicationContext()); sp.edit().putString("tagString", mTagString).commit(); getSupportActionBar().setTitle(mTagString); LinearLayout ll = (LinearLayout) findViewById(R.id.emptySearchView); ll.setVisibility(View.INVISIBLE); getListView().getEmptyView().setVisibility(View.VISIBLE); RefreshData(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. MenuInflater inflater = getSupportMenuInflater(); inflater.inflate(R.menu.activity_main, (Menu) menu); mRefreshItem = menu.findItem(R.id.refresh); mSearchItem = menu.findItem(R.id.menu_tag_search); mSearchItem.setActionView(R.layout.collapsible_edittext); final EditText searchText = (EditText) mSearchItem.getActionView() .findViewById(R.id.collapsible_edittext_item); // Hide Keyboard when the user defocuses from the ActionBar tag search searchText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } } }); // Respond to the search keyboard input for the ActionBar tag search searchText.setOnEditorActionListener(new SearchHandler()); // Focus on the EditText box in the ActionBar after it has been expanded // and show the keyboard mSearchItem.setOnActionExpandListener(new OnActionExpandListener() { @Override public boolean onMenuItemActionCollapse(MenuItem item) { return true; // Return true to collapse action view } @Override public boolean onMenuItemActionExpand(MenuItem item) { searchText.post(new Runnable() { @Override public void run() { searchText.requestFocus(); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(searchText, InputMethodManager.SHOW_IMPLICIT); } }); return true; // Return true to expand action view } }); return super.onCreateOptionsMenu(menu); } public void onRefreshMenuClick(final MenuItem item) { RefreshData(); } public void onSettingsMenuClick(final MenuItem item) { Intent intent = new Intent(this, PreferencesActivity.class); startActivity(intent); } /** * Reload feed data from Flickr. */ public void RefreshData() { String[] tags = { mTagString }; mDataLoader.LoadFeed(tags, LazyListAdapter, null, mRefreshItem, false); } /** * A class to handle responding to the search or done keys from a virtual * keyboard. * */ class SearchHandler implements OnEditorActionListener { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) { if (mSearchItem != null) mSearchItem.collapseActionView(); ProcessSearchText(v.getText().toString()); return true; } return false; } } }
/** * 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.aurora.scheduler.filter; import java.util.NoSuchElementException; import java.util.Optional; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableMultiset; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multiset; import org.apache.aurora.common.collections.Pair; import org.apache.aurora.common.testing.easymock.EasyMockTest; import org.apache.aurora.gen.AssignedTask; import org.apache.aurora.gen.Attribute; import org.apache.aurora.gen.HostAttributes; import org.apache.aurora.gen.ScheduledTask; import org.apache.aurora.scheduler.storage.AttributeStore; import org.apache.aurora.scheduler.storage.entities.IHostAttributes; import org.apache.aurora.scheduler.storage.entities.IScheduledTask; import org.easymock.IExpectationSetters; import org.junit.Before; import org.junit.Test; import static org.easymock.EasyMock.expect; import static org.junit.Assert.assertEquals; public class AttributeAggregateTest extends EasyMockTest { private AttributeStore attributeStore; @Before public void setUp() throws Exception { attributeStore = createMock(AttributeStore.class); } @Test public void testNoTasks() { control.replay(); AttributeAggregate aggregate = aggregate(); assertEquals(ImmutableMultiset.<Pair<String, String>>of(), aggregate.getAggregates()); assertAggregate(aggregate, "none", "alsoNone", 0); } @Test(expected = NoSuchElementException.class) public void testAttributesMissing() { expect(attributeStore.getHostAttributes("a")).andReturn(Optional.empty()); control.replay(); aggregate(task("1", "a")).getAggregates(); } @Test(expected = NullPointerException.class) public void testTaskWithNoHost() { control.replay(); aggregate(task("1", null)).getAggregates(); } @Test public void testNoAttributes() { expectGetAttributes("hostA"); control.replay(); assertEquals( ImmutableMultiset.<Pair<String, String>>of(), aggregate(task("1", "hostA")).getAggregates()); } @Test public void testAggregate() { expectGetAttributes( "a1", attribute("host", "a1"), attribute("rack", "a"), attribute("pdu", "p1")); expectGetAttributes( "b1", attribute("host", "b1"), attribute("rack", "b"), attribute("pdu", "p1", "p2")) .times(2); expectGetAttributes( "b2", attribute("host", "b2"), attribute("rack", "b"), attribute("pdu", "p1", "p2")); expectGetAttributes( "c1", attribute("host", "c1"), attribute("rack", "c"), attribute("pdu", "p2"), attribute("ssd", "true")); control.replay(); Multiset<Pair<String, String>> expected = ImmutableMultiset.<Pair<String, String>>builder() .add(Pair.of("rack", "a")) .addCopies(Pair.of("rack", "b"), 3) .add(Pair.of("rack", "c")) .add(Pair.of("host", "a1")) .addCopies(Pair.of("host", "b1"), 2) .add(Pair.of("host", "b2")) .add(Pair.of("host", "c1")) .addCopies(Pair.of("pdu", "p1"), 4) .addCopies(Pair.of("pdu", "p2"), 4) .add(Pair.of("ssd", "true")) .build(); AttributeAggregate aggregate = aggregate( task("1", "a1"), task("2", "b1"), task("3", "b1"), task("4", "b2"), task("5", "c1")); assertEquals(expected, aggregate.getAggregates()); for (Multiset.Entry<Pair<String, String>> entry : expected.entrySet()) { Pair<String, String> element = entry.getElement(); assertAggregate(aggregate, element.getFirst(), element.getSecond(), entry.getCount()); } assertAggregate(aggregate, "host", "c2", 0L); assertAggregate(aggregate, "hostc", "2", 0L); } @Test public void testUpdateAttributeAggregate() { expectGetAttributes( "a1", attribute("host", "a1"), attribute("rack", "a"), attribute("pdu", "p1")); control.replay(); Multiset<Pair<String, String>> expected = ImmutableMultiset.<Pair<String, String>>builder() .add(Pair.of("rack", "a")) .add(Pair.of("host", "a1")) .add(Pair.of("pdu", "p1")) .build(); AttributeAggregate aggregate = aggregate(task("1", "a1")); assertEquals(expected, aggregate.getAggregates()); aggregate.updateAttributeAggregate(IHostAttributes.build(new HostAttributes() .setHost("a2") .setAttributes(ImmutableSet.of(attribute("host", "a2"), attribute("rack", "b"))))); expected = ImmutableMultiset.<Pair<String, String>>builder() .addAll(expected) .add(Pair.of("rack", "b")) .add(Pair.of("host", "a2")) .build(); assertEquals(expected, aggregate.getAggregates()); } private AttributeAggregate aggregate(IScheduledTask... activeTasks) { return AttributeAggregate.create( Suppliers.ofInstance(ImmutableSet.copyOf(activeTasks)), attributeStore); } private IExpectationSetters<?> expectGetAttributes(String host, Attribute... attributes) { return expect(attributeStore.getHostAttributes(host)).andReturn(Optional.of( IHostAttributes.build(new HostAttributes() .setHost(host) .setAttributes(ImmutableSet.copyOf(attributes))))); } private void assertAggregate( AttributeAggregate aggregate, String name, String value, long expected) { assertEquals(expected, aggregate.getNumTasksWithAttribute(name, value)); } private static IScheduledTask task(String id, String host) { return IScheduledTask.build(new ScheduledTask().setAssignedTask( new AssignedTask() .setTaskId(id) .setSlaveHost(host))); } private Attribute attribute(String name, String... values) { return new Attribute() .setName(name) .setValues(ImmutableSet.copyOf(values)); } }
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * 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.wso2.carbon.identity.governance.listener; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.Spy; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.event.IdentityEventException; import org.wso2.carbon.identity.event.event.Event; import org.wso2.carbon.identity.event.services.IdentityEventService; import org.wso2.carbon.identity.governance.internal.IdentityMgtServiceDataHolder; import org.wso2.carbon.user.api.Permission; import org.wso2.carbon.user.api.RealmConfiguration; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.core.UserCoreConstants; import org.wso2.carbon.user.core.UserStoreManager; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.tenant.TenantManager; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.mockito.Matchers.any; import static org.mockito.Mockito.when; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.spy; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; /** * Test class for IdentityMgtEventListener. */ public class IdentityMgtEventListenerTest { private int SAMPLE_TENANT_ID = 3456; private String SAMPLE_TENANT_DOMAIN = "abc.com"; @Mock UserStoreManager userStoreManager; @Mock RealmConfiguration realmConfiguration; @Mock TenantManager tenantManager; @Mock RealmService realmService; @Mock IdentityEventService identityEventService; IdentityMgtServiceDataHolder instance; @InjectMocks @Spy IdentityMgtEventListener identityMgtEventListener; @BeforeTest public void setUp() throws Exception { instance = IdentityMgtServiceDataHolder.getInstance(); identityEventService = Mockito.mock(IdentityEventService.class); instance.setIdentityEventService(identityEventService); realmService = Mockito.mock(RealmService.class); instance.setRealmService(realmService); identityMgtEventListener = new IdentityMgtEventListener(); mockHandleEvent(); } @Test public void testGetExecutionOrderId() { int orderId = identityMgtEventListener.getExecutionOrderId(); assertEquals(orderId, 95, "OrderId is not equal to IdentityCoreConstants.EVENT_LISTENER_ORDER_ID"); IdentityMgtEventListener testIdentityMgtEventListener = spy(IdentityMgtEventListener.class); Mockito.doReturn(55).when(testIdentityMgtEventListener).getOrderId(); orderId = testIdentityMgtEventListener.getExecutionOrderId(); assertEquals(orderId, 55, "OrderId is not equal to IdentityCoreConstants.EVENT_LISTENER_ORDER_ID"); } @DataProvider(name = "authenticatedDataHandler") public Object[][] getAuthenticatedData() { return new Object[][]{ {"admin", new String("admin")}, {"admin", null}, {null, new String("admin")}, {null, null} }; } @Test(expectedExceptions = UserStoreException.class, dataProvider = "authenticatedDataHandler") public void testDoPreAuthenticate(String username, Object pwd) throws Exception { assertTrue(identityMgtEventListener.doPreAuthenticate(username, pwd, userStoreManager), "Do pre authenticate flow is failed."); doThrow(IdentityEventException.class).when(identityEventService).handleEvent(any(Event.class)); identityMgtEventListener.doPreAuthenticate(username, pwd, userStoreManager); } @DataProvider(name = "postAuthenticateHandler") public Object[][] getPostAuthenticateData() { return new Object[][]{ {"admin", true}, {"admin", false}, {null, true}, {null, false} }; } @Test(dataProvider = "postAuthenticateHandler") public void testDoPostAuthenticate(String userName, boolean authenticated) throws Exception { IdentityTenantUtil identityTenantUtil = new IdentityTenantUtil(); identityTenantUtil.setRealmService(realmService); when(realmService.getBootstrapRealmConfiguration()).thenReturn(realmConfiguration); assertTrue(identityMgtEventListener.doPostAuthenticate(userName, authenticated, userStoreManager), "Do post authenticate flow is failed."); } @DataProvider(name = "setUserClaimValueHandler") public Object[][] getUserClaimData() { Map<String, String> claimSet1 = new HashMap<>(); claimSet1.put("http://wso2.org/claims/email", "example1@wso2.com"); claimSet1.put("http://wso2.org/claims/username", "john"); claimSet1.put("http://wso2.org/claims/identity/accountLocked", "true"); claimSet1.put("http://wso2.org/claims/identity/preferredChannel","EMAIL"); Map<String, String> claimSet2 = new HashMap<>(); claimSet2.put("http://wso2.org/claims/identity/oidc", "oidc"); claimSet2.put("http://wso2.org/claims/email", "example@wso2.com"); claimSet2.put("http://wso2.org/claims/identity/accountLocked", "false"); claimSet2.put("http://wso2.org/claims/identity/preferredChannel","EMAIL"); return new Object[][]{ {"admin", claimSet1, "myProfile"}, {"user", claimSet2, "admin"} }; } @Test(dataProvider = "setUserClaimValueHandler") public void testDoPreSetUserClaimValues(String userName, Map<String, String> claims, String profileName) throws Exception { mockHandleEvent(); assertTrue(identityMgtEventListener.doPreSetUserClaimValues(userName, claims, profileName, userStoreManager), "Do pre set claim values failed."); } @Test(dataProvider = "setUserClaimValueHandler") public void testDoPostSetUserClaimValues(String userName, Map<String, String> claims, String profileName) throws Exception { assertTrue(identityMgtEventListener.doPostSetUserClaimValues(userName, claims, profileName, userStoreManager), "Do post set claim values failed."); } @DataProvider(name = "addUserDataHandler") public Object[][] addUserGetData() { String[] roleList = {"admin1", "admin2"}; Map<String, String> claimSet1 = new HashMap<>(); claimSet1.put("http://wso2.org/claims/email", "example@wso2.com"); claimSet1.put("http://wso2.org/claims/username", "john"); claimSet1.put("http://wso2.org/claims/identity/accountLocked", "true"); claimSet1.put("http://wso2.org/claims/identity/preferredChannel","EMAIL"); Map<String, String> claimSet2 = new HashMap<>(); claimSet2.put("http://wso2.org/claims/identity/oidc", "oidc"); claimSet2.put("http://wso2.org/claims/email", "john@wso2.com"); claimSet2.put("http://wso2.org/claims/identity/accountLocked", "false"); claimSet1.put("http://wso2.org/claims/identity/preferredChannel","EMAIL"); return new Object[][]{ {"admin", new String("admin"), roleList, claimSet1, "muProfile"}, {"admin", new String("admin"), roleList, claimSet2, "muProfile"} }; } @Test(dataProvider = "addUserDataHandler") public void testDoPreAddUser(String userName, Object pwd, String[] roleList, Map<String, String> claims, String profileName) throws Exception { assertTrue(identityMgtEventListener.doPreAddUser(userName, pwd, roleList, claims, profileName, userStoreManager), "Do pre add user failed."); } @Test(dataProvider = "addUserDataHandler") public void testDoPostAddUser(String userName, Object pwd, String[] roleList, Map<String, String> claims, String profileName) throws Exception { assertTrue(identityMgtEventListener.doPostAddUser(userName, pwd, roleList, claims, profileName, userStoreManager), "Do post add user failed."); } @DataProvider(name = "credentialHandler") public Object[][] getCredentialData() { return new Object[][]{ {"admin", new String("admin"), new String("user1")}, {"user", null, new String("user2")} }; } @Test(dataProvider = "credentialHandler") public void testDoPreUpdateCredential(String username, Object oldPwd, Object newPwd) throws Exception { mockHandleEvent(); assertTrue(identityMgtEventListener.doPreUpdateCredential(username, oldPwd, newPwd, userStoreManager), "Do pre update credential failed."); } @Test(dataProvider = "credentialHandler") public void testDoPostUpdateCredential(String username, Object oldPwd, Object newPwd) throws Exception { assertTrue(identityMgtEventListener.doPostUpdateCredential(username, newPwd, userStoreManager), "Do post update credential failed."); } @Test(dataProvider = "credentialHandler") public void testDoPreUpdateCredentialByAdmin(String username, Object oldPwd, Object newPwd) throws Exception { mockHandleEvent(); assertTrue(identityMgtEventListener.doPreUpdateCredentialByAdmin(username, newPwd, userStoreManager), "Do pre update credential by admin failed."); } @Test(dataProvider = "credentialHandler") public void testDoPostUpdateCredentialByAdmin(String username, Object oldPwd, Object newPwd) throws Exception { assertTrue(identityMgtEventListener.doPostUpdateCredentialByAdmin(username, newPwd, userStoreManager), "Do post update credential by admin failed."); } @Test(dataProvider = "authenticatedDataHandler") public void testDoPreDeleteUser(String username, Object pwd) throws Exception { mockHandleEvent(); assertTrue(identityMgtEventListener.doPreDeleteUser(username, userStoreManager), "Do pre update delete user failed."); } @Test(dataProvider = "authenticatedDataHandler") public void testDoPostDeleteUser(String username, Object pwd) throws Exception { assertTrue(identityMgtEventListener.doPostDeleteUser(username, userStoreManager), "Do post delete user failed."); } @Test(dataProvider = "setClaimHandler") public void testDoPreSetUserClaimValue(String userName, String claimURI, String claimValue, String profileName) throws Exception { mockHandleEvent(); assertTrue(identityMgtEventListener.doPreSetUserClaimValue(userName, claimURI, claimValue, profileName, userStoreManager), "Do post delete user failed."); } @Test(dataProvider = "authenticatedDataHandler") public void testDoPostSetUserClaimValue(String username, Object pwd) throws Exception { assertTrue(identityMgtEventListener.doPostSetUserClaimValue(username, userStoreManager), "Do post set user claim value failed."); } @DataProvider(name = "deleteClaimHandler") public Object[][] getDeleteClaimData() { String[] claims1 = {"http://wso2.org/claims/email", "http://wso2.org/claims/username"}; String[] claims2 = {"http://wso2.org/claims/birthday", "http://wso2.org/claims/address"}; return new Object[][]{ {"admin", claims1, "muProfile"}, {"admin", claims2, "muProfile"} }; } @Test(dataProvider = "deleteClaimHandler") public void testDoPreDeleteUserClaimValues(String userName, String[] claims, String profileName) throws Exception { mockHandleEvent(); assertTrue(identityMgtEventListener.doPreDeleteUserClaimValues(userName, claims, profileName, userStoreManager), "Do pre delete user claim values failed."); } @Test(dataProvider = "authenticatedDataHandler") public void testDoPostDeleteUserClaimValues(String userName, Object pwd) throws Exception { assertTrue(identityMgtEventListener.doPostDeleteUserClaimValues(userName, userStoreManager), "Do post delete user claim values failed."); } @DataProvider(name = "setClaimHandler") public Object[][] hetClaimData() { return new Object[][]{ {"admin", "http://wso2.org/claims/email", "example1@wso2.com", "muProfile"}, {"admin", "http://wso2.org/claims/username", "example", "muProfile"} }; } @Test(dataProvider = "setClaimHandler") public void testDoPreDeleteUserClaimValue(String userName, String claimURI, String claimValue, String profileName) throws Exception { mockHandleEvent(); assertTrue(identityMgtEventListener.doPreDeleteUserClaimValue(userName, claimURI, profileName, userStoreManager), "Do pre delete user claim value failed."); } @Test(dataProvider = "authenticatedDataHandler") public void testDoPostDeleteUserClaimValue(String userName, Object pwd) throws Exception { assertTrue(identityMgtEventListener.doPostDeleteUserClaimValue(userName, userStoreManager), "Do post delete user claim value failed."); } @DataProvider(name = "roleHandler") public Object[][] getRoleData() { String[] userList1 = {"user1", "user2"}; String[] userList2 = {"user3", "user4"}; return new Object[][]{ {"admin", userList1}, {"admin", userList2} }; } @Test(dataProvider = "roleHandler") public void testDoPreAddRole(String userName, String[] roleList) throws Exception { Permission permission1 = new Permission("resourceId1", "read"); Permission permission2 = new Permission("resourceId2", "write"); Permission[] permissions = {permission1, permission2, null}; assertTrue(identityMgtEventListener.doPreAddRole(userName, roleList, permissions, userStoreManager), "Do pre add role failed."); } @Test(dataProvider = "roleHandler") public void testDoPostAddRole(String userName, String[] roleList) throws Exception { Permission permission1 = new Permission("resourceId1", "read"); Permission permission2 = new Permission("resourceId2", "write"); Permission[] permissions = {permission1, permission2, null}; assertTrue(identityMgtEventListener.doPostAddRole(userName, roleList, permissions, userStoreManager), "Do pre add role failed."); } @Test(dataProvider = "authenticatedDataHandler") public void testDoPreDeleteRole(String roleName, Object pwd) throws Exception { mockHandleEvent(); assertTrue(identityMgtEventListener.doPreDeleteRole(roleName, userStoreManager), "Do pre add role failed."); } @Test(dataProvider = "authenticatedDataHandler") public void testDoPostDeleteRole(String roleName, Object pwd) throws Exception { assertTrue(identityMgtEventListener.doPostDeleteRole(roleName, userStoreManager), "Do pre add role failed."); } @DataProvider(name = "updateRoleHandler") public Object[][] getUpdateRoleData() { return new String[][]{ {"user1", "User1"}, {"user2", "user3"} }; } @Test(dataProvider = "updateRoleHandler") public void testDoPreUpdateRoleName(String roleName, String newRoleName) throws Exception { mockHandleEvent(); assertTrue(identityMgtEventListener.doPreUpdateRoleName(roleName, newRoleName, userStoreManager), "Do pre update role failed."); } @Test(dataProvider = "updateRoleHandler") public void testDoPostUpdateRoleName(String roleName, String newRoleName) throws Exception { assertTrue(identityMgtEventListener.doPostUpdateRoleName(roleName, newRoleName, userStoreManager), "Do post update role failed."); } @DataProvider(name = "updateRoleListHandler") public Object[][] getData10() { String[] deletedUsers1 = {"user1", "user2"}; String[] deletedUsers2 = {"user3", "user4"}; String[] newUsers1 = {"puser1", "puser2"}; String[] newUsers2 = {"puser3", "puser4"}; return new Object[][]{ {"role1", deletedUsers1, newUsers1}, {"role2", deletedUsers2, newUsers2} }; } @Test(dataProvider = "updateRoleListHandler") public void testDoPreUpdateUserListOfRole(String roleName, String[] deletedUsers, String[] newUsers) throws Exception { mockHandleEvent(); assertTrue(identityMgtEventListener.doPreUpdateUserListOfRole(roleName, deletedUsers, newUsers, userStoreManager), "Do pre update roles failed."); } @Test(dataProvider = "updateRoleListHandler") public void testDoPostUpdateUserListOfRole(String roleName, String[] deletedUsers, String[] newUsers) throws Exception { mockHandleEvent(); assertTrue(identityMgtEventListener.doPostUpdateUserListOfRole(roleName, deletedUsers, newUsers, userStoreManager), "Do post update roles failed."); } @Test(dataProvider = "updateRoleListHandler") public void testDoPreUpdateRoleListOfUser(String roleName, String[] deletedUsers, String[] newUsers) throws Exception { assertTrue(identityMgtEventListener.doPreUpdateRoleListOfUser(roleName, deletedUsers, newUsers, userStoreManager), "Do pre update role list of user failed."); } @Test(dataProvider = "updateRoleListHandler") public void testDoPostUpdateRoleListOfUser(String roleName, String[] deletedUsers, String[] newUsers) throws Exception { assertTrue(identityMgtEventListener.doPostUpdateRoleListOfUser(roleName, deletedUsers, newUsers, userStoreManager), "Do post update role list of user failed."); } @DataProvider(name = "postuserClaimHandler") public Object[][] getPostClaimData() { List<String> listClaimValues1 = new ArrayList<>(); listClaimValues1.add("example1@wso2.com"); listClaimValues1.add("example2@wso2.com"); List<String> listClaimValues2 = new ArrayList<>(); listClaimValues2.add("role1"); listClaimValues2.add("role2"); return new Object[][]{ {"user1", "http://wso2.org/claims/email", listClaimValues1, "myProfile"}, {"user2", "http://wso2.org/claims/roles", listClaimValues2, "myProfile"} }; } @Test(dataProvider = "postuserClaimHandler") public void testDoPostGetUserClaimValue(String userName, String claim, List<String> values, String profileName) throws Exception { mockHandleEvent(); assertTrue(identityMgtEventListener.doPostGetUserClaimValue(userName, claim, values, profileName, userStoreManager), "Do post get user claim value failed."); } @DataProvider(name = "postGetClaimvaluesHandler") public Object[][] getPostClaimValues() { String[] claimList1 = {"http://wso2.org/claims/email", "http://wso2.org/claims/username", "http://wso2.org/claims/identity/accountLocked"}; String[] claimList2 = {"http://wso2.org/claims/identity/oidc", "http://wso2.org/claims/email", "http://wso2.org/claims/identity/accountLocked"}; Map<String, String> claimSet1 = new HashMap<>(); claimSet1.put("http://wso2.org/claims/email", "example1@wso2.com"); claimSet1.put("http://wso2.org/claims/username", "john"); claimSet1.put("http://wso2.org/claims/identity/accountLocked", "true"); Map<String, String> claimSet2 = new HashMap<>(); claimSet2.put("http://wso2.org/claims/identity/oidc", "oidc"); claimSet2.put("http://wso2.org/claims/email", "example@wso2.com"); claimSet2.put("http://wso2.org/claims/identity/accountLocked", "false"); return new Object[][]{ {"user1", claimList1, "myProfile", claimSet1}, {"user2", claimList2, "myProfile", claimSet2} }; } @Test(dataProvider = "postGetClaimvaluesHandler") public void testDoPostGetUserClaimValues(String userName, String[] claims, String profileName, Map<String, String> claimMap) throws Exception { mockHandleEvent(); assertTrue(identityMgtEventListener.doPostGetUserClaimValues(userName, claims, profileName, claimMap, userStoreManager), "Do post get user claim value failed."); } private void mockHandleEvent() throws Exception { identityMgtEventListener = spy(IdentityMgtEventListener.class); userStoreManager = Mockito.mock(UserStoreManager.class); realmConfiguration = Mockito.mock(RealmConfiguration.class); tenantManager = Mockito.mock(TenantManager.class); when(realmService.getTenantManager()).thenReturn(tenantManager); when(tenantManager.getDomain(SAMPLE_TENANT_ID)).thenReturn(SAMPLE_TENANT_DOMAIN); TestUtils.startTenantFlow(SAMPLE_TENANT_DOMAIN); when(userStoreManager.getTenantId()).thenReturn(SAMPLE_TENANT_ID); when(userStoreManager.getRealmConfiguration()).thenReturn(realmConfiguration); when(realmConfiguration.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME)).thenReturn("PRIMARY"); Map<String, Object> properties = new HashMap<>(); Event identityMgtEvent = new Event("sampleEvent", properties); doNothing().when(identityEventService).handleEvent(any(Event.class)); identityEventService.handleEvent(identityMgtEvent); } }
/* * Copyright (c) 2011-2013, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * 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 boofcv.alg.transform.wavelet.impl; import boofcv.misc.AutoTypeImage; import boofcv.misc.CodeGeneratorBase; import java.io.FileNotFoundException; /** * @author Peter Abeles */ public class GenerateImplWaveletTransformInner extends CodeGeneratorBase { String className = "ImplWaveletTransformInner"; AutoTypeImage imageIn; AutoTypeImage imageOut; String genName; String sumType; String bitWise; String outputCast; public GenerateImplWaveletTransformInner() throws FileNotFoundException { setOutputFile(className); } @Override public void generate() throws FileNotFoundException { printPreamble(); printFuncs(AutoTypeImage.F32, AutoTypeImage.F32); printFuncs(AutoTypeImage.S32, AutoTypeImage.S32); out.print("\n" + "}\n"); } private void printPreamble() { out.print("import boofcv.alg.transform.wavelet.UtilWavelet;\n" + "import boofcv.struct.image.*;\n" + "import boofcv.struct.wavelet.WlCoef_F32;\n" + "import boofcv.struct.wavelet.WlCoef_I32;\n" + "\n" + "\n" + "/**\n" + " * <p>\n" + " * Standard algorithm for forward and inverse wavelet transform which has been optimized to only\n" + " * process the inner portion of the image by excluding the border.\n" + " * </p>\n" + " *\n" + " * <p>\n" + " * DO NOT MODIFY: This class was automatically generated by {@link GenerateImplWaveletTransformInner}\n" + " * </p>\n" + " *\n" + " * @author Peter Abeles\n" + " */\n" + "@SuppressWarnings({\"ForLoopReplaceableByForEach\"})\n" + "public class ImplWaveletTransformInner {\n\n"); } private void printFuncs( AutoTypeImage imageIn , AutoTypeImage imageOut ) { this.imageIn = imageIn; this.imageOut = imageOut; if( imageIn.isInteger() ) genName = "I32"; else genName = "F"+imageIn.getNumBits(); sumType = imageIn.getSumType(); bitWise = imageIn.getBitWise(); if( sumType.compareTo(imageOut.getDataType()) == 0 ) { outputCast = ""; } else { outputCast = "("+imageOut.getDataType()+")"; } printHorizontal(); printVertical(); printHorizontalInverse(); printVerticalInverse(); } private void printHorizontal() { out.print("\tpublic static void horizontal( WlCoef_"+genName+" coefficients , "+imageIn.getSingleBandName()+" input , "+imageOut.getSingleBandName()+" output )\n" + "\t{\n" + "\t\tfinal int offsetA = coefficients.offsetScaling;\n" + "\t\tfinal int offsetB = coefficients.offsetWavelet;\n" + "\t\tfinal "+sumType+"[] alpha = coefficients.scaling;\n" + "\t\tfinal "+sumType+"[] beta = coefficients.wavelet;\n" + "\n" + "\t\tfinal "+imageIn.getDataType()+" dataIn[] = input.data;\n" + "\t\tfinal "+imageOut.getDataType()+" dataOut[] = output.data;\n" + "\n" + "\t\tfinal int width = output.width;\n" + "\t\tfinal int height = input.height;\n" + "\t\tfinal int widthD2 = width/2;\n" + "\t\tfinal int startX = UtilWavelet.borderForwardLower(coefficients);\n" + "\t\tfinal int endOffsetX = input.width - UtilWavelet.borderForwardUpper(coefficients,input.width) - startX;\n" + "\n" + "\t\tfor( int y = 0; y < height; y++ ) {\n" + "\n" + "\t\t\tint indexIn = input.startIndex + input.stride*y + startX;\n" + "\t\t\tint indexOut = output.startIndex + output.stride*y + startX/2;\n" + "\n" + "\t\t\tint end = indexIn + endOffsetX;\n" + "\n" + "\t\t\tfor( ; indexIn < end; indexIn += 2 ) {\n" + "\n" + "\t\t\t\t"+sumType+" scale = 0;\n" + "\t\t\t\tint index = indexIn+offsetA;\n" + "\t\t\t\tfor( int i = 0; i < alpha.length; i++ ) {\n" + "\t\t\t\t\tscale += (dataIn[index++]"+bitWise+")*alpha[i];\n" + "\t\t\t\t}\n" + "\n" + "\t\t\t\t"+sumType+" wavelet = 0;\n" + "\t\t\t\tindex = indexIn+offsetB;\n" + "\t\t\t\tfor( int i = 0; i < beta.length; i++ ) {\n" + "\t\t\t\t\twavelet += (dataIn[index++]"+bitWise+")*beta[i];\n" + "\t\t\t\t}\n" + "\n"); if( imageIn.isInteger() ) { out.print("\t\t\t\tscale = 2*scale/coefficients.denominatorScaling;\n" + "\t\t\t\twavelet = 2*wavelet/coefficients.denominatorWavelet;\n\n"); } out.print("\t\t\t\tdataOut[ indexOut+widthD2] = "+outputCast+"wavelet;\n" + "\t\t\t\tdataOut[ indexOut++ ] = "+outputCast+"scale;\n" + "\t\t\t}\n" + "\t\t}\n" + "\t}\n\n"); } private void printVertical() { out.print("\tpublic static void vertical( WlCoef_"+genName+" coefficients , "+imageIn.getSingleBandName()+" input , "+imageOut.getSingleBandName()+" output )\n" + "\t{\n" + "\t\tfinal int offsetA = coefficients.offsetScaling*input.stride;\n" + "\t\tfinal int offsetB = coefficients.offsetWavelet*input.stride;\n" + "\t\tfinal "+sumType+"[] alpha = coefficients.scaling;\n" + "\t\tfinal "+sumType+"[] beta = coefficients.wavelet;\n" + "\n" + "\t\tfinal "+imageIn.getDataType()+" dataIn[] = input.data;\n" + "\t\tfinal "+imageOut.getDataType()+" dataOut[] = output.data;\n" + "\n" + "\t\tfinal int width = input.width;\n" + "\t\tfinal int height = output.height;\n" + "\t\tfinal int heightD2 = (height/2)*output.stride;\n" + "\t\tfinal int startY = UtilWavelet.borderForwardLower(coefficients);\n" + "\t\tfinal int endY = input.height - UtilWavelet.borderForwardUpper(coefficients,input.width);\n" + "\n" + "\t\tfor( int y = startY; y < endY; y += 2 ) {\n" + "\n" + "\t\t\tint indexIn = input.startIndex + input.stride*y;\n" + "\t\t\tint indexOut = output.startIndex + output.stride*(y/2);\n" + "\n" + "\t\t\tfor( int x = 0; x < width; x++, indexIn++) {\n" + "\n" + "\t\t\t\t"+sumType+" scale = 0;\n" + "\t\t\t\tint index = indexIn + offsetA;\n" + "\t\t\t\tfor( int i = 0; i < alpha.length; i++ ) {\n" + "\t\t\t\t\tscale += (dataIn[index]"+bitWise+")*alpha[i];\n" + "\t\t\t\t\tindex += input.stride;\n" + "\t\t\t\t}\n" + "\n" + "\t\t\t\t"+sumType+" wavelet = 0;\n" + "\t\t\t\tindex = indexIn + offsetB;\n" + "\t\t\t\tfor( int i = 0; i < beta.length; i++ ) {\n" + "\t\t\t\t\twavelet += (dataIn[index]"+bitWise+")*beta[i];\n" + "\t\t\t\t\tindex += input.stride;\n" + "\t\t\t\t}\n" + "\n"); if( imageIn.isInteger() ) { out.print("\t\t\t\tscale = 2*scale/coefficients.denominatorScaling;\n" + "\t\t\t\twavelet = 2*wavelet/coefficients.denominatorWavelet;\n\n"); } out.print("\t\t\t\tdataOut[indexOut+heightD2] = "+outputCast+"wavelet;\n" + "\t\t\t\tdataOut[indexOut++] = "+outputCast+"scale;\n" + "\n" + "\t\t\t}\n" + "\t\t}\n" + "\t}\n\n"); } private void printHorizontalInverse() { out.print("\tpublic static void horizontalInverse( WlCoef_"+genName+" coefficients , "+imageIn.getSingleBandName()+" input , "+imageOut.getSingleBandName()+" output )\n" + "\t{\n" + "\t\tfinal int offsetA = coefficients.offsetScaling;\n" + "\t\tfinal int offsetB = coefficients.offsetWavelet;\n" + "\t\tfinal "+sumType+"[] alpha = coefficients.scaling;\n" + "\t\tfinal "+sumType+"[] beta = coefficients.wavelet;\n" + "\n" + "\t\t"+sumType+" []trends = new "+sumType+"[ output.width ];\n" + "\t\t"+sumType+" []details = new "+sumType+"[ output.width ];\n" + "\n" + "\t\tfinal int width = input.width;\n" + "\t\tfinal int height = output.height;\n" + "\t\tfinal int widthD2 = width/2;\n" + "\t\tfinal int lowerBorder = UtilWavelet.borderForwardLower(coefficients);\n" + "\t\tfinal int upperBorder = output.width - UtilWavelet.borderForwardUpper(coefficients,output.width);" + "\n"); if( imageIn.isInteger() ) { out.print("\t\tfinal int e = coefficients.denominatorScaling*2;\n" + "\t\tfinal int f = coefficients.denominatorWavelet*2;\n" + "\t\tfinal int ef = e*f;\n" + "\t\tfinal int ef2 = ef/2;\n" + "\n"); } out.print("\t\tfor( int y = 0; y < height; y++ ) {\n" + "\n" + "\t\t\t// initialize details and trends arrays\n" + "\t\t\tint indexSrc = input.startIndex + y*input.stride+lowerBorder/2;\n" + "\t\t\tfor( int x = lowerBorder; x < upperBorder; x += 2 , indexSrc++ ) {\n" + "\t\t\t\t"+sumType+" a = input.data[ indexSrc ] "+bitWise+";\n" + "\t\t\t\t"+sumType+" d = input.data[ indexSrc + widthD2 ] "+bitWise+";\n" + "\n" + "\t\t\t\t// add the trend\n" + "\t\t\t\tfor( int i = 0; i < 2; i++ )\n" + "\t\t\t\t\ttrends[i+x+offsetA] = a*alpha[i];\n" + "\n" + "\t\t\t\t// add the detail signal\n" + "\t\t\t\tfor( int i = 0; i < 2; i++ )\n" + "\t\t\t\t\tdetails[i+x+offsetB] = d*beta[i];\n" + "\t\t\t}\n" + "\n" + "\t\t\tfor( int i = upperBorder+offsetA; i < upperBorder; i++ )\n" + "\t\t\t\ttrends[i] = 0;\n" + "\t\t\tfor( int i = upperBorder+offsetB; i < upperBorder; i++ )\n" + "\t\t\t\tdetails[i] = 0;\n"+ "\n"+ "\t\t\t// perform the normal inverse transform\n" + "\t\t\tindexSrc = input.startIndex + y*input.stride+lowerBorder/2;\n" + "\t\t\tfor( int x = lowerBorder; x < upperBorder; x += 2 , indexSrc++ ) {\n" + "\t\t\t\t"+sumType+" a = input.data[ indexSrc ] "+bitWise+";\n" + "\t\t\t\t"+sumType+" d = input.data[ indexSrc + widthD2 ] "+bitWise+";\n" + "\n" + "\t\t\t\t// add the trend\n" + "\t\t\t\tfor( int i = 2; i < alpha.length; i++ ) {\n" + "\t\t\t\t\ttrends[i+x+offsetA] += a*alpha[i];\n" + "\t\t\t\t}\n" + "\n" + "\t\t\t\t// add the detail signal\n" + "\t\t\t\tfor( int i = 2; i < beta.length; i++ ) {\n" + "\t\t\t\t\tdetails[i+x+offsetB] += d*beta[i];\n" + "\t\t\t\t}\n" + "\t\t\t}\n" + "\n" + "\t\t\tint indexDst = output.startIndex + y*output.stride + lowerBorder;\n" + "\t\t\tfor( int x = lowerBorder; x < upperBorder; x++ ) {\n"); if( imageIn.isInteger() ) { out.print("\t\t\t\toutput.data[ indexDst++ ] = "+outputCast+"UtilWavelet.round(trends[x]*f + details[x]*e , ef2,ef);\n" ); } else { out.print("\t\t\t\toutput.data[ indexDst++ ] = "+outputCast+"(trends[x] + details[x]);\n" ); } out.print("\t\t\t}\n" + "\t\t}\n" + "\t}\n\n"); } private void printVerticalInverse() { out.print("\tpublic static void verticalInverse( WlCoef_"+genName+" coefficients , "+imageIn.getSingleBandName()+" input , "+imageOut.getSingleBandName()+" output )\n" + "\t{\n" + "\t\tfinal int offsetA = coefficients.offsetScaling;\n" + "\t\tfinal int offsetB = coefficients.offsetWavelet;\n" + "\t\tfinal "+sumType+"[] alpha = coefficients.scaling;\n" + "\t\tfinal "+sumType+"[] beta = coefficients.wavelet;\n" + "\n" + "\t\t"+sumType+" []trends = new "+sumType+"[ output.height ];\n" + "\t\t"+sumType+" []details = new "+sumType+"[ output.height ];\n" + "\n" + "\t\tfinal int width = output.width;\n" + "\t\tfinal int height = input.height;\n" + "\t\tfinal int heightD2 = (height/2)*input.stride;\n" + "\t\tfinal int lowerBorder = UtilWavelet.borderForwardLower(coefficients);\n" + "\t\tfinal int upperBorder = output.height - UtilWavelet.borderForwardUpper(coefficients,output.height);" + "\n"); if( imageIn.isInteger() ) { out.print("\t\tfinal int e = coefficients.denominatorScaling*2;\n" + "\t\tfinal int f = coefficients.denominatorWavelet*2;\n" + "\t\tfinal int ef = e*f;\n" + "\t\tfinal int ef2 = ef/2;\n" + "\n"); } out.print("\t\tfor( int x = 0; x < width; x++) {\n" + "\n" + "\t\t\tint indexSrc = input.startIndex + (lowerBorder/2)*input.stride + x;\n" + "\t\t\tfor( int y = lowerBorder; y < upperBorder; y += 2 , indexSrc += input.stride ) {\n" + "\t\t\t\t"+sumType+" a = input.data[ indexSrc ] "+bitWise+";\n" + "\t\t\t\t"+sumType+" d = input.data[ indexSrc + heightD2 ] "+bitWise+";\n" + "\n" + "\t\t\t\t// add the trend\n" + "\t\t\t\tfor( int i = 0; i < 2; i++ )\n" + "\t\t\t\t\ttrends[i+y+offsetA] = a*alpha[i];\n" + "\n" + "\t\t\t\t// add the detail signal\n" + "\t\t\t\tfor( int i = 0; i < 2; i++ )\n" + "\t\t\t\t\tdetails[i+y+offsetB] = d*beta[i];\n" + "\t\t\t}\n" + "\n" + "\t\t\tfor( int i = upperBorder+offsetA; i < upperBorder; i++ )\n" + "\t\t\t\ttrends[i] = 0;\n" + "\t\t\tfor( int i = upperBorder+offsetB; i < upperBorder; i++ )\n" + "\t\t\t\tdetails[i] = 0;\n"+ "\n"+ "\t\t\t// perform the normal inverse transform\n" + "\t\t\tindexSrc = input.startIndex + (lowerBorder/2)*input.stride + x;\n" + "\n" + "\t\t\tfor( int y = lowerBorder; y < upperBorder; y += 2 , indexSrc += input.stride ) {\n" + "\t\t\t\t"+sumType+" a = input.data[indexSrc] "+bitWise+";\n" + "\t\t\t\t"+sumType+" d = input.data[indexSrc+heightD2] "+bitWise+";\n" + "\n" + "\t\t\t\t// add the 'average' signal\n" + "\t\t\t\tfor( int i = 2; i < alpha.length; i++ ) {\n" + "\t\t\t\t\ttrends[y+offsetA+i] += a*alpha[i];\n" + "\t\t\t\t}\n" + "\n" + "\t\t\t\t// add the detail signal\n" + "\t\t\t\tfor( int i = 2; i < beta.length; i++ ) {\n" + "\t\t\t\t\tdetails[y+offsetB+i] += d*beta[i];\n" + "\t\t\t\t}\n" + "\t\t\t}\n" + "\n" + "\t\t\tint indexDst = output.startIndex + x + lowerBorder*output.stride;\n" + "\t\t\tfor( int y = lowerBorder; y < upperBorder; y++ , indexDst += output.stride ) {\n"); if( imageIn.isInteger() ) { out.print("\t\t\t\toutput.data[ indexDst ] = "+outputCast+"UtilWavelet.round(trends[y]*f + details[y]*e , ef2 , ef);\n" ); } else { out.print("\t\t\t\toutput.data[ indexDst ] = "+outputCast+"(trends[y] + details[y]);\n" ); } out.print("\t\t\t}\n" + "\t\t}\n" + "\t}\n\n"); } public static void main( String args[] ) throws FileNotFoundException { GenerateImplWaveletTransformInner app = new GenerateImplWaveletTransformInner(); app.generate(); } }
package org.swellrt.beta.model.wave; import java.util.ArrayList; import java.util.function.Consumer; import org.swellrt.beta.common.SException; import org.swellrt.beta.model.SEvent; import org.swellrt.beta.model.SMutationHandler; import org.swellrt.beta.model.SList; import org.swellrt.beta.model.SMap; import org.swellrt.beta.model.SPrimitive; import org.swellrt.beta.model.wave.mutable.SWaveList; import org.swellrt.beta.model.wave.mutable.SWaveMap; import org.swellrt.beta.model.wave.mutable.SWaveNode; public class SWaveListTest extends SWaveNodeAbstractTest { @SuppressWarnings("rawtypes") public void testAddOperation() throws SException { SList localList = SList.create(); localList.add("hello world"); localList.add(12345); localList.add(false); SMap localMap = SMap.create(); localMap.put("key0", "value0"); localMap.put("key1", "value1"); localList.add(localMap); object.put("list", localList); SWaveList remoteList = (SWaveList) object.pick("list"); assertNotNull(remoteList); assertEquals(4, remoteList.size()); assertEquals("hello world", SPrimitive.asString(remoteList.pick(0))); assertEquals(12345, SPrimitive.asInt(remoteList.pick(1)).intValue()); assertEquals(false, SPrimitive.asBoolean(remoteList.pick(2)).booleanValue()); assertTrue(remoteList.pick(3) instanceof SMap); SWaveMap remoteMap = (SWaveMap) remoteList.pick(3); assertEquals("value0", remoteMap.get("key0")); assertEquals("value1", remoteMap.get("key1")); assertEquals(3, remoteList.indexOf(remoteMap)); remoteList.values().forEach(new Consumer<SWaveNode>() { int counter = 0; @Override public void accept(SWaveNode t) { switch(counter++) { case 0: assertEquals("hello world", SPrimitive.asString(t)); break; case 1: assertEquals(12345, (int) SPrimitive.asInt(t)); break; case 2: assertEquals(false, (boolean) SPrimitive.asBoolean(t)); break; case 3: assertTrue(t instanceof SMap); break; } } }); } @SuppressWarnings("rawtypes") public void testRemoveOperation() throws SException { SList localList = SList.create(); localList.add("hello world"); localList.add(12345); localList.add(false); SMap localMap = SMap.create(); localMap.put("key0", "value0"); localMap.put("key1", "value1"); localList.add(localMap); object.put("list", localList); SList remoteList = (SList) object.pick("list"); assertEquals(4, remoteList.size()); // Remove first remoteList.remove(0); assertEquals(3, remoteList.size()); assertEquals(12345, SPrimitive.asInt(remoteList.pick(0)).intValue()); // Remove last remoteList.remove(2); assertEquals(2, remoteList.size()); assertEquals(12345, SPrimitive.asInt(remoteList.pick(0)).intValue()); assertEquals(false, SPrimitive.asBoolean(remoteList.pick(1)).booleanValue()); } @SuppressWarnings("rawtypes") public void testClearOperation() throws SException { SList localList = SList.create(); localList.add("hello world"); localList.add(12345); localList.add(false); SMap localMap = SMap.create(); localMap.put("key0", "value0"); localMap.put("key1", "value1"); localList.add(localMap); object.put("list", localList); SList remoteList = (SList) object.pick("list"); remoteList.clear(); assertEquals(0, remoteList.size()); assertTrue(remoteList.isEmpty()); } @SuppressWarnings("rawtypes") public void testEvents() throws SException, InterruptedException { SList localList = SList.create(); localList.add("hello world"); localList.add(12345); localList.add(false); SMap localMap = SMap.create(); localMap.put("key0", "value0"); localMap.put("key1", "value1"); localList.add(localMap); object.put("list", localList); SWaveList remoteList = (SWaveList) object.pick("list"); final ArrayList<SEvent> recvEvents = new ArrayList<SEvent>(); SMutationHandler eventHandler = new SMutationHandler() { @Override public boolean exec(SEvent e) { recvEvents.add(e); synchronized (this) { if (recvEvents.size() == 4) notifyAll(); } return false; } }; remoteList.addListener(eventHandler, null); localMap = SMap.create(); localMap.put("key0", "value0"); localMap.put("key1", "value1"); remoteList.add(localMap); remoteList.remove(1).remove(1); remoteList.add("some words"); synchronized (eventHandler) { eventHandler.wait(1000); } assertEquals(4, remoteList.size()); assertEquals(4, recvEvents.size()); assertEquals(SEvent.ADDED_VALUE, recvEvents.get(0).getType()); assertTrue(recvEvents.get(0).getTarget() instanceof SList); assertTrue(recvEvents.get(0).getValue() instanceof SMap); assertEquals(SEvent.REMOVED_VALUE, recvEvents.get(1).getType()); assertTrue(recvEvents.get(1).getTarget() instanceof SList); assertEquals(12345, (int) recvEvents.get(1).getValue()); assertEquals(SEvent.REMOVED_VALUE, recvEvents.get(2).getType()); assertTrue(recvEvents.get(2).getTarget() instanceof SList); assertEquals(false, (boolean) recvEvents.get(2).getValue()); assertEquals(SEvent.ADDED_VALUE, recvEvents.get(3).getType()); assertTrue(recvEvents.get(3).getTarget() instanceof SList); assertEquals("some words", (String) recvEvents.get(3).getValue()); } @SuppressWarnings("rawtypes") public void testListWithNestedMap() throws SException { SList localList = SList.create(); localList.add("hello world"); localList.add(12345); localList.add(false); SMap localMap = SMap.create(); localMap.put("key0", "value0"); localMap.put("key1", "value1"); localList.add(localMap); object.put("list", localList); SWaveList remoteList = (SWaveList) object.pick("list"); SWaveMap remoteMap = (SWaveMap) remoteList.pick(3); remoteMap.put("key0", 1000); assertEquals(new Integer(1000), SPrimitive.asInt(remoteMap.pick("key0"))); SPrimitive intNode = (SPrimitive) remoteList.pick(1); assertEquals(1, remoteList.indexOf(intNode)); } }
/* * Copyright 2022 ThoughtWorks, Inc. * * 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.thoughtworks.go.helper; import com.thoughtworks.go.config.CaseInsensitiveString; import com.thoughtworks.go.config.materials.*; import com.thoughtworks.go.config.materials.dependency.DependencyMaterialConfig; import com.thoughtworks.go.config.materials.git.GitMaterialConfig; import com.thoughtworks.go.config.materials.mercurial.HgMaterialConfig; import com.thoughtworks.go.config.materials.perforce.P4MaterialConfig; import com.thoughtworks.go.config.materials.svn.SvnMaterialConfig; import com.thoughtworks.go.config.materials.tfs.TfsMaterialConfig; import com.thoughtworks.go.domain.config.Configuration; import com.thoughtworks.go.domain.config.ConfigurationKey; import com.thoughtworks.go.domain.config.ConfigurationProperty; import com.thoughtworks.go.domain.config.ConfigurationValue; import com.thoughtworks.go.domain.packagerepository.*; import com.thoughtworks.go.domain.scm.SCM; import com.thoughtworks.go.domain.scm.SCMMother; import com.thoughtworks.go.security.GoCipher; import com.thoughtworks.go.util.command.HgUrlArgument; import com.thoughtworks.go.util.command.UrlArgument; import static com.thoughtworks.go.util.DataStructureUtils.m; public class MaterialConfigsMother { public static GitMaterialConfig git() { return new GitMaterialConfig(); } public static GitMaterialConfig git(String url) { GitMaterialConfig gitMaterialConfig = git(); gitMaterialConfig.setUrl(url); return gitMaterialConfig; } public static GitMaterialConfig git(String url, String branch) { GitMaterialConfig gitMaterialConfig = git(url); gitMaterialConfig.setBranch(branch); return gitMaterialConfig; } public static GitMaterialConfig git(String url, boolean shallowClone) { GitMaterialConfig gitMaterialConfig = git(url); gitMaterialConfig.setShallowClone(shallowClone); return gitMaterialConfig; } public static GitMaterialConfig git(String url, String branch, boolean shallowClone) { GitMaterialConfig gitMaterialConfig = git(url, branch); gitMaterialConfig.setShallowClone(shallowClone); return gitMaterialConfig; } public static GitMaterialConfig git(UrlArgument url, String userName, String password, String branch, String submoduleFolder, boolean autoUpdate, Filter filter, boolean invertFilter, String folder, CaseInsensitiveString name, Boolean shallowClone) { return git(url.originalArgument(), userName, password, branch, submoduleFolder, autoUpdate, filter, invertFilter, folder, name, shallowClone); } public static GitMaterialConfig git(String url, String userName, String password, String branch, String submoduleFolder, boolean autoUpdate, Filter filter, boolean invertFilter, String folder, CaseInsensitiveString name, Boolean shallowClone) { GitMaterialConfig gitMaterialConfig = git(url, branch, shallowClone); gitMaterialConfig.setUserName(userName); gitMaterialConfig.setPassword(password); gitMaterialConfig.setSubmoduleFolder(submoduleFolder); gitMaterialConfig.setAutoUpdate(autoUpdate); gitMaterialConfig.setFilter(filter); gitMaterialConfig.setInvertFilter(invertFilter); gitMaterialConfig.setFolder(folder); gitMaterialConfig.setName(name); return gitMaterialConfig; } public static HgMaterialConfig hg() { return new HgMaterialConfig(); } public static HgMaterialConfig hg(String url, String folder) { HgMaterialConfig config = hg(); config.setUrl(url); config.setFolder(folder); return config; } public static HgMaterialConfig hg(HgUrlArgument url, String userName, String password, String branch, boolean autoUpdate, Filter filter, boolean invertFilter, String folder, CaseInsensitiveString name) { return hg(url.originalArgument(), userName, password, branch, autoUpdate, filter, invertFilter, folder, name); } public static HgMaterialConfig hg(String url, String userName, String password, String branch, boolean autoUpdate, Filter filter, boolean invertFilter, String folder, CaseInsensitiveString name) { HgMaterialConfig config = hg(url, folder); config.setUserName(userName); config.setPassword(password); config.setBranchAttribute(branch); config.setAutoUpdate(autoUpdate); config.setFilter(filter); config.setInvertFilter(invertFilter); config.setName(name); return config; } public static SvnMaterialConfig svn() { return new SvnMaterialConfig(); } public static SvnMaterialConfig svn(String url, boolean checkExternals) { return svn(url, null, null, checkExternals); } public static SvnMaterialConfig svn(String url, String userName, String password, boolean checkExternals) { return svn(url, userName, password, checkExternals, new GoCipher()); } public static SvnMaterialConfig svn(String url, String userName, String password, boolean checkExternals, String folder) { SvnMaterialConfig svnMaterialConfig = svn(url, userName, password, checkExternals); svnMaterialConfig.setFolder(folder); return svnMaterialConfig; } //there is no need to mock GoCipher as it already using test provider public static SvnMaterialConfig svn(String url, String userName, String password, boolean checkExternals, GoCipher goCipher) { SvnMaterialConfig svnMaterialConfig = svn(); svnMaterialConfig.setUrl(url); svnMaterialConfig.setUserName(userName); svnMaterialConfig.setPassword(password); svnMaterialConfig.setCheckExternals(checkExternals); return svnMaterialConfig; } //there is no need to mock GoCipher as it already using test provider public static SvnMaterialConfig svn(UrlArgument url, String userName, String password, boolean checkExternals, GoCipher goCipher, boolean autoUpdate, Filter filter, boolean invertFilter, String folder, CaseInsensitiveString name) { SvnMaterialConfig svnMaterialConfig = svn(); svnMaterialConfig.setUrl(url.originalArgument()); svnMaterialConfig.setUserName(userName); svnMaterialConfig.setPassword(password); svnMaterialConfig.setCheckExternals(checkExternals); svnMaterialConfig.setAutoUpdate(autoUpdate); svnMaterialConfig.setFilter(filter); svnMaterialConfig.setInvertFilter(invertFilter); svnMaterialConfig.setFolder(folder); svnMaterialConfig.setName(name); return svnMaterialConfig; } public static TfsMaterialConfig tfs() { return new TfsMaterialConfig(); } public static TfsMaterialConfig tfs(GoCipher goCipher, String url, String userName, String domain, String projectPath) { return tfs(goCipher, new UrlArgument(url), userName, domain, null, projectPath); } public static TfsMaterialConfig tfs(String url) { return tfs(new GoCipher(), new UrlArgument(url), null, null, "password"); } public static TfsMaterialConfig tfs(UrlArgument urlArgument, String password, String encryptedPassword, GoCipher goCipher) { TfsMaterialConfig tfsMaterialConfig = tfs(goCipher, urlArgument, null, null, password); tfsMaterialConfig.setEncryptedPassword(encryptedPassword); return tfsMaterialConfig; } public static TfsMaterialConfig tfs(GoCipher goCipher, UrlArgument url, String userName, String domain, String projectPath) { return tfs(goCipher, url.originalArgument(), userName, domain, projectPath); } //avoid using GoCipher: there is no need to mock GoCipher as it already using test provider public static TfsMaterialConfig tfs(GoCipher goCipher, UrlArgument url, String userName, String domain, String password, String projectPath) { return tfs(url, userName, domain, password, projectPath, goCipher, true, null, false, null, null); } public static TfsMaterialConfig tfs(UrlArgument url, String userName, String domain, String password, String projectPath, GoCipher goCipher, boolean autoUpdate, Filter filter, boolean invertFilter, String folder, CaseInsensitiveString name) { TfsMaterialConfig tfsMaterialConfig = new TfsMaterialConfig(); tfsMaterialConfig.setUrl(url == null ? null : url.originalArgument()); tfsMaterialConfig.setUserName(userName); tfsMaterialConfig.setDomain(domain); tfsMaterialConfig.setPassword(password); tfsMaterialConfig.setProjectPath(projectPath); tfsMaterialConfig.setAutoUpdate(autoUpdate); tfsMaterialConfig.setFilter(filter); tfsMaterialConfig.setInvertFilter(invertFilter); tfsMaterialConfig.setFolder(folder); tfsMaterialConfig.setName(name); return tfsMaterialConfig; } public static P4MaterialConfig p4() { return new P4MaterialConfig(); } public static P4MaterialConfig p4(String serverAndPort, String view, GoCipher goCipher) { P4MaterialConfig p4MaterialConfig = p4(); p4MaterialConfig.setUrl(serverAndPort); p4MaterialConfig.setView(view); return p4MaterialConfig; } public static P4MaterialConfig p4(String serverAndPort, String view) { return p4(serverAndPort, view, new GoCipher()); } public static P4MaterialConfig p4(String url, String view, String userName) { P4MaterialConfig p4MaterialConfig = p4(url, view); p4MaterialConfig.setUserName(userName); return p4MaterialConfig; } public static P4MaterialConfig p4(String serverAndPort, String password, String encryptedPassword, GoCipher goCipher) { P4MaterialConfig p4MaterialConfig = p4(); p4MaterialConfig.setUrl(serverAndPort); p4MaterialConfig.setPassword(password); p4MaterialConfig.setEncryptedPassword(encryptedPassword); return p4MaterialConfig; } public static P4MaterialConfig p4(String serverAndPort, String userName, String password, Boolean useTickets, String viewStr, GoCipher goCipher, CaseInsensitiveString name, boolean autoUpdate, Filter filter, boolean invertFilter, String folder) { P4MaterialConfig p4MaterialConfig = p4(); p4MaterialConfig.setUrl(serverAndPort); p4MaterialConfig.setUserName(userName); p4MaterialConfig.setPassword(password); p4MaterialConfig.setUseTickets(useTickets); p4MaterialConfig.setView(viewStr); p4MaterialConfig.setAutoUpdate(autoUpdate); p4MaterialConfig.setFilter(filter); p4MaterialConfig.setInvertFilter(invertFilter); p4MaterialConfig.setFolder(folder); p4MaterialConfig.setName(name); return p4MaterialConfig; } public static MaterialConfigs defaultMaterialConfigs() { return defaultSvnMaterialConfigsWithUrl("http://some/svn/url"); } public static MaterialConfigs defaultSvnMaterialConfigsWithUrl(String svnUrl) { return new MaterialConfigs(svnMaterialConfig(svnUrl, "svnDir", null, null, false, null)); } public static MaterialConfigs multipleMaterialConfigs() { MaterialConfigs materialConfigs = new MaterialConfigs(); materialConfigs.add(svnMaterialConfig("http://svnurl", null)); materialConfigs.add(hgMaterialConfig("http://hgurl", "hgdir")); materialConfigs.add(dependencyMaterialConfig("cruise", "dev")); return materialConfigs; } public static PackageMaterialConfig packageMaterialConfig() { return packageMaterialConfig("repo-name", "package-name"); } public static PackageMaterialConfig packageMaterialConfig(String repoName, String packageName) { PackageMaterialConfig material = new PackageMaterialConfig("p-id"); PackageRepository repository = PackageRepositoryMother.create("repo-id", repoName, "pluginid", "version", new Configuration(ConfigurationPropertyMother.create("k1", false, "repo-v1"), ConfigurationPropertyMother.create("k2", false, "repo-v2"))); PackageDefinition packageDefinition = PackageDefinitionMother.create("p-id", packageName, new Configuration(ConfigurationPropertyMother.create("k3", false, "package-v1")), repository); material.setPackageDefinition(packageDefinition); repository.getPackages().add(packageDefinition); return material; } public static PluggableSCMMaterialConfig pluggableSCMMaterialConfig() { Filter filter = new Filter(new IgnoredFiles("**/*.html"), new IgnoredFiles("**/foobar/")); return pluggableSCMMaterialConfig("scm-id", "des-folder", filter); } public static PluggableSCMMaterialConfig pluggableSCMMaterialConfigWithConfigProperties(String... properties) { SCM scmConfig = SCMMother.create("scm-id"); Configuration configuration = new Configuration(); for (String property : properties) { ConfigurationProperty configurationProperty = new ConfigurationProperty(new ConfigurationKey(property), new ConfigurationValue(property + "-value")); configuration.add(configurationProperty); } scmConfig.setConfiguration(configuration); return new PluggableSCMMaterialConfig(null, scmConfig, "des-folder", null, false); } public static PluggableSCMMaterialConfig pluggableSCMMaterialConfig(String scmId, String... properties) { return new PluggableSCMMaterialConfig(null, SCMMother.create(scmId, properties), "des-folder", null, false); } public static PluggableSCMMaterialConfig pluggableSCMMaterialConfig(String scmId, String destinationFolder, Filter filter) { return new PluggableSCMMaterialConfig(null, SCMMother.create(scmId), destinationFolder, filter, false); } public static DependencyMaterialConfig dependencyMaterialConfig(String pipelineName, String stageName) { return new DependencyMaterialConfig(new CaseInsensitiveString(pipelineName), new CaseInsensitiveString(stageName)); } public static DependencyMaterialConfig dependencyMaterialConfig() { return new DependencyMaterialConfig(new CaseInsensitiveString("pipeline-name"), new CaseInsensitiveString("stage-name"), true); } public static HgMaterialConfig hgMaterialConfigFull() { Filter filter = new Filter(new IgnoredFiles("**/*.html"), new IgnoredFiles("**/foobar/")); return hg(new HgUrlArgument("http://user:pass@domain/path##branch"), null, null, null, true, filter, false, "dest-folder", new CaseInsensitiveString("hg-material")); } public static HgMaterialConfig hgMaterialConfigFull(String url) { Filter filter = new Filter(new IgnoredFiles("**/*.html"), new IgnoredFiles("**/foobar/")); return hg(new HgUrlArgument(url), null, null, null, true, filter, false, "dest-folder", new CaseInsensitiveString("hg-material")); } public static HgMaterialConfig hgMaterialConfig() { return hgMaterialConfig("hg-url"); } public static HgMaterialConfig hgMaterialConfig(String url) { return hgMaterialConfig(url, null); } public static HgMaterialConfig hgMaterialConfig(String url, String folder) { return hg(url, folder); } public static GitMaterialConfig gitMaterialConfig(String url, String submoduleFolder, String branch, boolean shallowClone) { GitMaterialConfig gitMaterialConfig = git(url, branch); gitMaterialConfig.setShallowClone(shallowClone); gitMaterialConfig.setSubmoduleFolder(submoduleFolder); return gitMaterialConfig; } public static GitMaterialConfig gitMaterialConfig() { Filter filter = new Filter(new IgnoredFiles("**/*.html"), new IgnoredFiles("**/foobar/")); return git(new UrlArgument("http://user:password@funk.com/blank"), null, null, "branch", "sub_module_folder", false, filter, false, "destination", new CaseInsensitiveString("AwesomeGitMaterial"), true); } public static GitMaterialConfig gitMaterialConfig(String url) { return git(url); } public static P4MaterialConfig p4MaterialConfig() { return p4MaterialConfig("serverAndPort", null, null, "view", false); } public static P4MaterialConfig p4MaterialConfigFull() { Filter filter = new Filter(new IgnoredFiles("**/*.html"), new IgnoredFiles("**/foobar/")); P4MaterialConfig config = p4MaterialConfig("host:9876", "user", "password", "view", true); config.setFolder("dest-folder"); config.setFilter(filter); config.setName(new CaseInsensitiveString("p4-material")); return config; } public static P4MaterialConfig p4MaterialConfig(String serverAndPort, String userName, String password, String view, boolean useTickets) { final P4MaterialConfig material = p4(serverAndPort, view); material.setConfigAttributes(m(P4MaterialConfig.USERNAME, userName, P4MaterialConfig.AUTO_UPDATE, "true")); material.setPassword(password); material.setUseTickets(useTickets); return material; } public static SvnMaterialConfig svnMaterialConfig() { return svnMaterialConfig("url", "svnDir"); } public static SvnMaterialConfig svnMaterialConfig(String svnUrl, String folder, CaseInsensitiveString name) { SvnMaterialConfig svnMaterialConfig = svnMaterialConfig(svnUrl, folder); svnMaterialConfig.setName(name); return svnMaterialConfig; } public static SvnMaterialConfig svnMaterialConfig(String svnUrl, String folder) { return svnMaterialConfig(svnUrl, folder, false); } public static SvnMaterialConfig svnMaterialConfig(String svnUrl, String folder, boolean autoUpdate) { SvnMaterialConfig materialConfig = svn(new UrlArgument(svnUrl), "user", "pass", true, new GoCipher(), autoUpdate, new Filter(new IgnoredFiles("*.doc")), false, folder, new CaseInsensitiveString("svn-material")); materialConfig.setPassword("pass"); return materialConfig; } public static SvnMaterialConfig svnMaterialConfig(String svnUrl, String folder, String userName, String password, boolean checkExternals, String filterPattern) { SvnMaterialConfig svnMaterial = svn(svnUrl, userName, password, checkExternals, folder); if (filterPattern != null) svnMaterial.setFilter(new Filter(new IgnoredFiles(filterPattern))); String name = svnUrl.replaceAll("/", "_"); name = name.replaceAll(":", "_"); svnMaterial.setName(new CaseInsensitiveString(name)); return svnMaterial; } public static HgMaterialConfig filteredHgMaterialConfig(String pattern) { HgMaterialConfig materialConfig = hgMaterialConfig(); materialConfig.setFilter(new Filter(new IgnoredFiles(pattern))); return materialConfig; } public static MaterialConfigs mockMaterialConfigs(String url) { return new MaterialConfigs(svn(url, null, null, false)); } public static TfsMaterialConfig tfsMaterialConfig() { Filter filter = new Filter(new IgnoredFiles("**/*.html"), new IgnoredFiles("**/foobar/")); TfsMaterialConfig tfsMaterialConfig = tfs(new GoCipher(), new UrlArgument("http://10.4.4.101:8080/tfs/Sample"), "loser", "some_domain", "passwd", "walk_this_path"); tfsMaterialConfig.setFilter(filter); tfsMaterialConfig.setName(new CaseInsensitiveString("tfs-material")); tfsMaterialConfig.setFolder("dest-folder"); return tfsMaterialConfig; } public static GitMaterialConfig git(String url, String username, String password) { GitMaterialConfig gitMaterialConfig = git(url); gitMaterialConfig.setUserName(username); gitMaterialConfig.setPassword(password); return gitMaterialConfig; } public static HgMaterialConfig hg(String url, String username, String password) { HgMaterialConfig materialConfig = hg(url, null); materialConfig.setUserName(username); materialConfig.setPassword(password); return materialConfig; } }
/* * Copyright (c) 2016, Groupon, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of GROUPON nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.groupon.lex.metrics.history.v2.list; import com.groupon.lex.metrics.MetricName; import com.groupon.lex.metrics.MetricValue; import com.groupon.lex.metrics.SimpleGroupPath; import com.groupon.lex.metrics.history.v2.Compression; import com.groupon.lex.metrics.history.v2.DictionaryForWrite; import static com.groupon.lex.metrics.history.v2.list.ReadOnlyState.calculateDictionary; import static com.groupon.lex.metrics.history.v2.list.ReadOnlyState.calculateTimeSeries; import static com.groupon.lex.metrics.history.v2.list.ReadOnlyState.readAllTSDataHeaders; import static com.groupon.lex.metrics.history.v2.list.ReadOnlyState.readTSDataHeader; import com.groupon.lex.metrics.history.v2.tables.DictionaryDelta; import com.groupon.lex.metrics.history.v2.xdr.FromXdr; import com.groupon.lex.metrics.history.v2.xdr.ToXdr; import static com.groupon.lex.metrics.history.v2.xdr.Util.ALL_HDR_CRC_LEN; import com.groupon.lex.metrics.history.v2.xdr.header_flags; import com.groupon.lex.metrics.history.v2.xdr.record; import com.groupon.lex.metrics.history.v2.xdr.record_array; import com.groupon.lex.metrics.history.v2.xdr.record_metric; import com.groupon.lex.metrics.history.v2.xdr.record_metrics; import com.groupon.lex.metrics.history.v2.xdr.record_tags; import com.groupon.lex.metrics.history.v2.xdr.tsdata; import com.groupon.lex.metrics.history.v2.xdr.tsfile_header; import com.groupon.lex.metrics.history.xdr.Const; import com.groupon.lex.metrics.history.xdr.support.FilePos; import com.groupon.lex.metrics.history.xdr.support.reader.FileChannelSegmentReader; import com.groupon.lex.metrics.history.xdr.support.reader.SegmentReader; import com.groupon.lex.metrics.history.xdr.support.writer.AbstractSegmentWriter.Writer; import com.groupon.lex.metrics.history.xdr.support.writer.Crc32AppendingFileWriter; import com.groupon.lex.metrics.history.xdr.support.writer.FileChannelWriter; import com.groupon.lex.metrics.history.xdr.support.writer.SizeVerifyingWriter; import com.groupon.lex.metrics.history.xdr.support.writer.XdrEncodingFileWriter; import com.groupon.lex.metrics.lib.GCCloseable; import com.groupon.lex.metrics.lib.sequence.ForwardSequence; import com.groupon.lex.metrics.lib.sequence.ObjectSequence; import com.groupon.lex.metrics.timeseries.TimeSeriesCollection; import com.groupon.lex.metrics.timeseries.TimeSeriesValue; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.Collection; import static java.util.Collections.singletonList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.Function; import java.util.function.Supplier; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.Stream; import lombok.AccessLevel; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import org.acplt.oncrpc.OncRpcException; import org.joda.time.DateTime; /** * * @author ariane */ public final class ReadWriteState implements State { private static final Logger LOG = Logger.getLogger(ReadWriteState.class.getName()); private final ReadWriteLock guard = new ReentrantReadWriteLock(true); // Protects internal data structures. private final List<SegmentReader<TimeSeriesCollection>> tsdata; @Getter(AccessLevel.PRIVATE) private SegmentReader<DictionaryDelta> dictionary; @Getter private final GCCloseable<FileChannel> file; private final List<SegmentReader<ReadonlyTSDataHeader>> tsdataHeaders; private DictionaryForWrite writerDictionary; private tsfile_header hdr; private final Compression compression; public ReadWriteState(GCCloseable<FileChannel> file, tsfile_header hdr) throws IOException, OncRpcException { this.file = file; this.hdr = hdr; this.compression = Compression.fromFlags(this.hdr.flags); tsdataHeaders = readAllTSDataHeaders(file, FromXdr.filePos(hdr.fdt)); dictionary = calculateDictionary(file, compression, tsdataHeaders) .cache(); tsdata = calculateTimeSeries(file, compression, tsdataHeaders, SegmentReader.ofSupplier(this::getDictionary).flatMap(x -> x)); writerDictionary = new DictionaryForWrite(dictionary.decode()); } private <T> T doReadLocked(Supplier<T> fn) { Lock lock = guard.readLock(); lock.lock(); try { return fn.get(); } finally { lock.unlock(); } } public boolean isSorted() { return doReadLocked(() -> (hdr.flags & header_flags.SORTED) == header_flags.SORTED); } public boolean isDistinct() { return doReadLocked(() -> (hdr.flags & header_flags.DISTINCT) == header_flags.DISTINCT); } @Override public DateTime getBegin() { return doReadLocked(() -> FromXdr.timestamp(hdr.first)); } @Override public DateTime getEnd() { return doReadLocked(() -> FromXdr.timestamp(hdr.last)); } @Override public ObjectSequence<SegmentReader<TimeSeriesCollection>> sequence() { return doReadLocked(() -> { boolean sorted = (hdr.flags & header_flags.SORTED) == header_flags.SORTED; boolean distinct = (hdr.flags & header_flags.DISTINCT) == header_flags.DISTINCT; return new ForwardSequence(0, tsdata.size()) .map(tsdata::get, sorted, true, distinct); }); } @Override public void add(TimeSeriesCollection tsc) { try { addRecords(singletonList(tsc)); } catch (IOException | OncRpcException ex) { throw new RuntimeException("unable to add records", ex); } } @Override public void addAll(Collection<? extends TimeSeriesCollection> tsc) { try { addRecords(tsc); } catch (IOException | OncRpcException ex) { throw new RuntimeException("unable to add records", ex); } } private synchronized void addRecords(Collection<? extends TimeSeriesCollection> tscList) throws IOException, OncRpcException { LOG.log(Level.FINER, "adding {0} records", tscList.size()); if (tscList.isEmpty()) return; long recordOffset; final DictionaryForWrite newWriterDict; FilePos lastRecord; { final Lock lock = guard.readLock(); lock.lock(); try { recordOffset = hdr.file_size; lastRecord = FromXdr.filePos(hdr.fdt); newWriterDict = writerDictionary.clone(); newWriterDict.reset(); } finally { lock.unlock(); } } LOG.log(Level.FINER, "newWriterDict initialized (strOffset={0}, pathOffset={1}, tagsOffset={2})", new Object[]{ newWriterDict.getStringTable().getOffset(), newWriterDict.getPathTable().getOffset(), newWriterDict.getTagsTable().getOffset()}); final ByteBuffer useBuffer = (compression != Compression.NONE ? ByteBuffer.allocate(65536) : ByteBuffer.allocateDirect(65536)); if (lastRecord.getOffset() == 0) lastRecord = null; // Empty file. final List<FilePos> headers = new ArrayList<>(tscList.size()); final List<EncodedTscHeaderForWrite> writeHeaders; try (FileChannelWriter fd = new FileChannelWriter(this.file.get(), recordOffset)) { { final Writer writer = new Writer(fd, compression, useBuffer, false); /* Write the contents of each collection. */ writeHeaders = new ArrayList<>(tscList.size()); for (TimeSeriesCollection tsc : tscList) writeHeaders.add(writeTSC(writer, tsc, newWriterDict)); /* First header owns reference to dictionary delta. */ if (!newWriterDict.isEmpty()) writeHeaders.get(0).setNewWriterDict(Optional.of(writer.write(newWriterDict.encode()))); } /* Write the headers. */ for (EncodedTscHeaderForWrite header : writeHeaders) { header.setPreviousTscHeader(Optional.ofNullable(lastRecord)); lastRecord = header.write(fd, useBuffer); headers.add(lastRecord); } recordOffset = fd.getOffset(); // New file end. } /* Prepare new dictionary for installation. */ final DictionaryDelta newDictionary; if (newWriterDict.isEmpty()) { newDictionary = null; LOG.log(Level.FINER, "not installing new dictionary: delta is empty"); } else { newDictionary = newWriterDict.asDictionaryDelta(); writerDictionary = newWriterDict; LOG.log(Level.FINER, "installing new dictionary"); } /* * Prepare updated file header. */ final tsfile_header hdr = updateHeaderData(writeHeaders); /* * Update shared datastructures. */ final Lock lock = guard.writeLock(); lock.lock(); try { /* * Write the header. * * Up to this point, we could abandon the write and the file_end mark * would pretend nothing was written. */ hdr.file_size = recordOffset; hdr.fdt = ToXdr.filePos(lastRecord); writeHeader(hdr, useBuffer); this.hdr = hdr; /* * Update all data structures. */ final List<SegmentReader<ReadonlyTSDataHeader>> newTsdataHeaders = headers.stream() .map(offset -> readTSDataHeader(file, offset)) .collect(Collectors.toList()); tsdataHeaders.addAll(newTsdataHeaders); if (newDictionary != null) { dictionary = calculateDictionary(file, compression, tsdataHeaders) .cache(newDictionary); } tsdata.addAll(newTsdataHeaders.stream() .map(roHdr -> { return roHdr .map(tsdHeader -> { final SegmentReader<DictionaryDelta> dictSegment = SegmentReader.ofSupplier(this::getDictionary) .flatMap(Function.identity()); final SegmentReader<record_array> recordsSegment = tsdHeader.recordsDecoder(file, compression); final TimeSeriesCollection newTsc = new ListTSC(tsdHeader.getTimestamp(), recordsSegment, dictSegment, new FileChannelSegmentReader.Factory(file, compression)); return newTsc; }) .share(); }) .collect(Collectors.toList())); } finally { lock.unlock(); } } /** * Update all flags/metadata in header for update. */ private tsfile_header updateHeaderData(List<EncodedTscHeaderForWrite> headers) { // Make copy of header and work on that. final tsfile_header hdr = doReadLocked(() -> { tsfile_header copy = new tsfile_header(); copy.first = this.hdr.first; copy.last = this.hdr.last; copy.file_size = this.hdr.file_size; copy.flags = this.hdr.flags; copy.reserved = this.hdr.reserved; copy.fdt = this.hdr.fdt; return copy; }); if (isDistinct()) { boolean distinct = true; Stream<DateTime> tsStream = headers.stream().map(EncodedTscHeaderForWrite::getTimestamp); if (!headers.get(0).getTimestamp().isAfter(getEnd())) { try { tsStream = Stream.concat(tsStream, sequence() .reverse() .map(segment -> { try { return segment.decode().getTimestamp(); } catch (IOException | OncRpcException ex) { throw new RuntimeException("unable to decode", ex); } }, true, true, true) .stream()); } catch (Exception ex) { LOG.log(Level.WARNING, "read error during new record write", ex); distinct = false; } if (distinct) { distinct = tsStream .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .values() .stream() .allMatch(count -> count == 1); } if (!distinct) hdr.flags &= ~header_flags.DISTINCT; } } if (!tsdataHeaders.isEmpty() && !headers.get(0).getTimestamp().isAfter(FromXdr.timestamp(hdr.last))) hdr.flags &= ~header_flags.SORTED; if (tsdataHeaders.isEmpty() || headers.get(0).getTimestamp().isBefore(FromXdr.timestamp(hdr.first))) hdr.first = ToXdr.timestamp(headers.get(0).getTimestamp()); if (tsdataHeaders.isEmpty() || headers.get(headers.size() - 1).getTimestamp().isAfter(FromXdr.timestamp(hdr.last))) hdr.last = ToXdr.timestamp(headers.get(headers.size() - 1).getTimestamp()); return hdr; } /** * Write current header to file. */ private void writeHeader(tsfile_header hdr, ByteBuffer useBuffer) throws OncRpcException, IOException { try (XdrEncodingFileWriter writer = new XdrEncodingFileWriter(new Crc32AppendingFileWriter(new SizeVerifyingWriter(new FileChannelWriter(file.get(), 0), ALL_HDR_CRC_LEN), 4), useBuffer)) { Const.writeMimeHeader(writer); hdr.xdrEncode(writer); } } private SegmentReader<TimeSeriesCollection> loadAtIndex(int index) { return doReadLocked(() -> tsdata.get(index)); } private static EncodedTscHeaderForWrite writeTSC(Writer writer, TimeSeriesCollection tsc, DictionaryForWrite dict) throws IOException, OncRpcException { final List<record> recordList = new ArrayList<>(); for (SimpleGroupPath path : tsc.getGroupPaths(x -> true)) { record r = new record(); r.path_ref = dict.getPathTable().getOrCreate(path.getPath()); r.tags = writeTSCTags(writer, path, tsc, dict); recordList.add(r); } record_array ra = new record_array(recordList.toArray(new record[0])); final FilePos pos = writer.write(ra); return new EncodedTscHeaderForWrite(tsc.getTimestamp(), pos, dict); } private static record_tags[] writeTSCTags(Writer writer, SimpleGroupPath path, TimeSeriesCollection tsc, DictionaryForWrite dict) throws IOException, OncRpcException { final List<record_tags> recordList = new ArrayList<>(); for (TimeSeriesValue tsv : tsc.getTSValue(path).stream().collect(Collectors.toList())) { record_tags rt = new record_tags(); rt.tag_ref = dict.getTagsTable().getOrCreate(tsv.getTags()); rt.pos = ToXdr.filePos(writeMetrics(writer, tsv.getMetrics(), dict)); recordList.add(rt); } return recordList.toArray(new record_tags[0]); } private static FilePos writeMetrics(Writer writer, Map<MetricName, MetricValue> metrics, DictionaryForWrite dict) throws IOException, OncRpcException { record_metrics rma = new record_metrics(metrics.entrySet().stream() .map(metricEntry -> { record_metric rm = new record_metric(); rm.path_ref = dict.getPathTable().getOrCreate(metricEntry.getKey().getPath()); rm.v = ToXdr.metricValue(metricEntry.getValue(), dict.getStringTable()::getOrCreate); return rm; }) .toArray(record_metric[]::new)); return writer.write(rma); } private static class EncodedTscHeaderForWrite { @Getter @Setter private Optional<FilePos> previousTscHeader = Optional.empty(); @Getter @Setter private Optional<FilePos> newWriterDict = Optional.empty(); @Getter private final DateTime timestamp; private final FilePos encodedTsc; public EncodedTscHeaderForWrite(@NonNull DateTime ts, @NonNull FilePos encodedTsc, @NonNull DictionaryForWrite dict) { timestamp = ts; this.encodedTsc = encodedTsc; } public FilePos write(FileChannelWriter fd, ByteBuffer useBuffer) throws IOException, OncRpcException { final tsdata tscHdr = new tsdata(); tscHdr.reserved = 0; tscHdr.dict = newWriterDict.map(ToXdr::filePos).orElse(null); tscHdr.previous = previousTscHeader.map(ToXdr::filePos).orElse(null); tscHdr.ts = ToXdr.timestamp(timestamp); tscHdr.records = ToXdr.filePos(encodedTsc); FilePos pos = new Writer(fd, Compression.NONE, useBuffer, false).write(tscHdr); LOG.log(Level.FINEST, "tsdata header written at {0}", pos); return pos; } } }
/* * Copyright 2020 The Android Open Source Project * * 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 androidx.camera.video.internal; import android.media.MediaCodec; import android.media.MediaCodecInfo; import android.media.MediaCodecList; import android.media.MediaFormat; import android.os.Build; import android.text.TextUtils; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.camera.core.Logger; import androidx.camera.video.internal.compat.Api28Impl; import androidx.camera.video.internal.compat.Api31Impl; import androidx.core.util.Preconditions; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.concurrent.TimeUnit; /** * Utility class for debugging. */ @RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java public final class DebugUtils { private static final String TAG = "DebugUtils"; private static final String CODEC_CAPS_PREFIX = "[CodecCaps] "; private static final String VIDEO_CAPS_PREFIX = "[VideoCaps] "; private static final String AUDIO_CAPS_PREFIX = "[AudioCaps] "; private static final String ENCODER_CAPS_PREFIX = "[EncoderCaps] "; private DebugUtils() {} /** * Returns a formatted string according to the input time, the format is * "hours:minutes:seconds.milliseconds". * * @param time input time in microseconds. * @return the formatted string. */ @NonNull public static String readableUs(long time) { return readableMs(TimeUnit.MICROSECONDS.toMillis(time)); } /** * Returns a formatted string according to the input time, the format is * "hours:minutes:seconds.milliseconds". * * @param time input time in milliseconds. * @return the formatted string. */ @NonNull public static String readableMs(long time) { return formatInterval(time); } /** * Returns a formatted string according to the input {@link MediaCodec.BufferInfo}. * * @param bufferInfo the {@link MediaCodec.BufferInfo}. * @return the formatted string. */ @NonNull @SuppressWarnings("ObjectToString") public static String readableBufferInfo(@NonNull MediaCodec.BufferInfo bufferInfo) { StringBuilder sb = new StringBuilder(); sb.append("Dump BufferInfo: " + bufferInfo.toString() + "\n"); sb.append("\toffset: " + bufferInfo.offset + "\n"); sb.append("\tsize: " + bufferInfo.size + "\n"); { sb.append("\tflag: " + bufferInfo.flags); List<String> flagList = new ArrayList<>(); if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) { flagList.add("EOS"); } if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) { flagList.add("CODEC_CONFIG"); } if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_KEY_FRAME) != 0) { flagList.add("KEY_FRAME"); } if ((bufferInfo.flags & MediaCodec.BUFFER_FLAG_PARTIAL_FRAME) != 0) { flagList.add("PARTIAL_FRAME"); } if (!flagList.isEmpty()) { sb.append(" (").append(TextUtils.join(" | ", flagList)).append(")"); } sb.append("\n"); } sb.append("\tpresentationTime: " + bufferInfo.presentationTimeUs + " (" + readableUs(bufferInfo.presentationTimeUs) + ")\n"); return sb.toString(); } private static String formatInterval(long millis) { final long hr = TimeUnit.MILLISECONDS.toHours(millis); final long min = TimeUnit.MILLISECONDS.toMinutes(millis - TimeUnit.HOURS.toMillis(hr)); final long sec = TimeUnit.MILLISECONDS.toSeconds( millis - TimeUnit.HOURS.toMillis(hr) - TimeUnit.MINUTES.toMillis(min)); final long ms = millis - TimeUnit.HOURS.toMillis(hr) - TimeUnit.MINUTES.toMillis(min) - TimeUnit.SECONDS.toMillis(sec); return String.format(Locale.US, "%02d:%02d:%02d.%03d", hr, min, sec, ms); } /** * Dumps {@link MediaCodecInfo} of input {@link MediaCodecList} and support for input * {@link MediaFormat}. */ public static void dumpMediaCodecListForFormat(@NonNull MediaCodecList mediaCodecList, @NonNull MediaFormat mediaFormat) { Logger.d(TAG, "[Start] Dump MediaCodecList for mediaFormat " + mediaFormat); String mime = mediaFormat.getString(MediaFormat.KEY_MIME); for (MediaCodecInfo mediaCodecInfo : mediaCodecList.getCodecInfos()) { if (!mediaCodecInfo.isEncoder()) { continue; } try { Preconditions.checkArgument(mime != null); MediaCodecInfo.CodecCapabilities caps = mediaCodecInfo.getCapabilitiesForType(mime); Preconditions.checkArgument(caps != null); Logger.d(TAG, "[Start] [" + mediaCodecInfo.getName() + "]"); dumpCodecCapabilities(caps, mediaFormat); Logger.d(TAG, "[End] [" + mediaCodecInfo.getName() + "]"); } catch (IllegalArgumentException e) { Logger.w(TAG, "[" + mediaCodecInfo.getName() + "] does not support mime " + mime); } } Logger.d(TAG, "[End] Dump MediaCodecList"); } private static void dumpCodecCapabilities(@NonNull MediaCodecInfo.CodecCapabilities caps, @NonNull MediaFormat mediaFormat) { Logger.d(TAG, CODEC_CAPS_PREFIX + "isFormatSupported = " + caps.isFormatSupported(mediaFormat)); Logger.d(TAG, CODEC_CAPS_PREFIX + "getDefaultFormat = " + caps.getDefaultFormat()); if (caps.profileLevels != null) { StringBuilder stringBuilder = new StringBuilder("["); List<String> profileLevelsStr = new ArrayList<>(); for (MediaCodecInfo.CodecProfileLevel profileLevel : caps.profileLevels) { profileLevelsStr.add(toString(profileLevel)); } stringBuilder.append(TextUtils.join(", ", profileLevelsStr)).append("]"); Logger.d(TAG, CODEC_CAPS_PREFIX + "profileLevels = " + stringBuilder); } if (caps.colorFormats != null) { Logger.d(TAG, CODEC_CAPS_PREFIX + "colorFormats = " + Arrays.toString(caps.colorFormats)); } MediaCodecInfo.VideoCapabilities videoCaps = caps.getVideoCapabilities(); if (videoCaps != null) { dumpVideoCapabilities(videoCaps, mediaFormat); } MediaCodecInfo.AudioCapabilities audioCaps = caps.getAudioCapabilities(); if (audioCaps != null) { dumpAudioCapabilities(audioCaps, mediaFormat); } MediaCodecInfo.EncoderCapabilities encoderCaps = caps.getEncoderCapabilities(); if (encoderCaps != null) { dumpEncoderCapabilities(encoderCaps, mediaFormat); } } private static void dumpVideoCapabilities(@NonNull MediaCodecInfo.VideoCapabilities caps, @NonNull MediaFormat mediaFormat) { // Bitrate Logger.d(TAG, VIDEO_CAPS_PREFIX + "getBitrateRange = " + caps.getBitrateRange()); // Size Logger.d(TAG, VIDEO_CAPS_PREFIX + "getSupportedWidths = " + caps.getSupportedWidths() + ", getWidthAlignment = " + caps.getWidthAlignment()); Logger.d(TAG, VIDEO_CAPS_PREFIX + "getSupportedHeights = " + caps.getSupportedHeights() + ", getHeightAlignment = " + caps.getHeightAlignment()); boolean hasSize = true; int width; int height; try { width = mediaFormat.getInteger(MediaFormat.KEY_WIDTH); height = mediaFormat.getInteger(MediaFormat.KEY_HEIGHT); Preconditions.checkArgument(width > 0 && height > 0); } catch (NullPointerException | IllegalArgumentException e) { Logger.w(TAG, VIDEO_CAPS_PREFIX + "mediaFormat does not contain valid width and height"); width = height = 0; hasSize = false; } if (hasSize) { try { Logger.d(TAG, VIDEO_CAPS_PREFIX + "getSupportedHeightsFor " + width + " = " + caps.getSupportedHeightsFor(width)); } catch (IllegalArgumentException e) { Logger.w(TAG, VIDEO_CAPS_PREFIX + "could not getSupportedHeightsFor " + width, e); } try { Logger.d(TAG, VIDEO_CAPS_PREFIX + "getSupportedWidthsFor " + height + " = " + caps.getSupportedWidthsFor(height)); } catch (IllegalArgumentException e) { Logger.w(TAG, VIDEO_CAPS_PREFIX + "could not getSupportedWidthsFor " + height, e); } Logger.d(TAG, VIDEO_CAPS_PREFIX + "isSizeSupported for " + width + "x" + height + " = " + caps.isSizeSupported(width, height)); } // Frame rate Logger.d(TAG, VIDEO_CAPS_PREFIX + "getSupportedFrameRates = " + caps.getSupportedFrameRates()); int frameRate; try { frameRate = mediaFormat.getInteger(MediaFormat.KEY_FRAME_RATE); Preconditions.checkArgument(frameRate > 0); } catch (NullPointerException | IllegalArgumentException e) { Logger.w(TAG, VIDEO_CAPS_PREFIX + "mediaFormat does not contain frame rate"); frameRate = 0; } if (hasSize) { Logger.d(TAG, VIDEO_CAPS_PREFIX + "getSupportedFrameRatesFor " + width + "x" + height + " = " + caps.getSupportedFrameRatesFor(width, height)); } if (hasSize && frameRate > 0) { Logger.d(TAG, VIDEO_CAPS_PREFIX + "areSizeAndRateSupported for " + width + "x" + height + ", " + frameRate + " = " + caps.areSizeAndRateSupported(width, height, frameRate)); } } private static void dumpAudioCapabilities(@NonNull MediaCodecInfo.AudioCapabilities caps, @NonNull MediaFormat mediaFormat) { // Bitrate Logger.d(TAG, AUDIO_CAPS_PREFIX + "getBitrateRange = " + caps.getBitrateRange()); // Channel count Logger.d(TAG, AUDIO_CAPS_PREFIX + "getMaxInputChannelCount = " + caps.getMaxInputChannelCount()); if (Build.VERSION.SDK_INT >= 31) { Logger.d(TAG, AUDIO_CAPS_PREFIX + "getMinInputChannelCount = " + Api31Impl.getMinInputChannelCount(caps)); Logger.d(TAG, AUDIO_CAPS_PREFIX + "getInputChannelCountRanges = " + Arrays.toString(Api31Impl.getInputChannelCountRanges(caps))); } // Sample rate Logger.d(TAG, AUDIO_CAPS_PREFIX + "getSupportedSampleRateRanges = " + Arrays.toString(caps.getSupportedSampleRateRanges())); Logger.d(TAG, AUDIO_CAPS_PREFIX + "getSupportedSampleRates = " + Arrays.toString(caps.getSupportedSampleRates())); try { int sampleRate = mediaFormat.getInteger(MediaFormat.KEY_SAMPLE_RATE); Logger.d(TAG, AUDIO_CAPS_PREFIX + "isSampleRateSupported for " + sampleRate + " = " + caps.isSampleRateSupported(sampleRate)); } catch (NullPointerException | IllegalArgumentException e) { Logger.w(TAG, AUDIO_CAPS_PREFIX + "mediaFormat does not contain sample rate"); } } private static void dumpEncoderCapabilities(@NonNull MediaCodecInfo.EncoderCapabilities caps, @NonNull MediaFormat mediaFormat) { Logger.d(TAG, ENCODER_CAPS_PREFIX + "getComplexityRange = " + caps.getComplexityRange()); if (Build.VERSION.SDK_INT >= 28) { Logger.d(TAG, ENCODER_CAPS_PREFIX + "getQualityRange = " + Api28Impl.getQualityRange(caps)); } int bitrateMode; try { bitrateMode = mediaFormat.getInteger(MediaFormat.KEY_BITRATE_MODE); Logger.d(TAG, ENCODER_CAPS_PREFIX + "isBitrateModeSupported = " + caps.isBitrateModeSupported(bitrateMode)); } catch (NullPointerException | IllegalArgumentException e) { Logger.w(TAG, ENCODER_CAPS_PREFIX + "mediaFormat does not contain bitrate mode"); } } @NonNull private static String toString(@Nullable MediaCodecInfo.CodecProfileLevel codecProfileLevel) { if (codecProfileLevel == null) { return "null"; } return String.format("{level=%d, profile=%d}", codecProfileLevel.level, codecProfileLevel.profile); } }
// ======================================================================== // Copyright 2007 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // 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.mortbay.cometd; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.GenericServlet; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.cometd.Bayeux; import org.cometd.DataFilter; import org.cometd.Message; import org.mortbay.cometd.filter.JSONDataFilter; import org.mortbay.log.Log; import org.mortbay.util.ajax.JSON; /** * Cometd Filter Servlet implementing the {@link AbstractBayeux} protocol. * * The Servlet can be initialized with a json file mapping channels to * {@link DataFilter} definitions. The servlet init parameter "filters" should * point to a webapplication resource containing a JSON array of filter * definitions. For example: * * <pre> * [ * { * &quot;channels&quot;: &quot;/**&quot;, * &quot;class&quot; : &quot;org.mortbay.cometd.filter.NoMarkupFilter&quot;, * &quot;init&quot; : {} * } * ] * </pre> * * The following init parameters can be used to configure the servlet: * <dl> * <dt>timeout</dt> * <dd>The server side poll timeout in milliseconds (default 250000). This is * how long the server will hold a reconnect request before responding.</dd> * * <dt>interval</dt> * <dd>The client side poll timeout in milliseconds (default 0). How long a * client will wait between reconnects</dd> * * <dt>maxInterval</dt> * <dd>The max client side poll timeout in milliseconds (default 30000). A * client will be removed if a connection is not received in this time. * * <dt>maxLazyLatency</dt> * <dd>The max time in ms(default 0) that a client with lazy messages will wait before * sending a response. If 0, then the client will wait until the next timeout or * non-lazy message. * * <dt>multiFrameInterval</dt> * <dd>the client side poll timeout if multiple connections are detected from * the same browser (default 1500).</dd> * * <dt>JSONCommented</dt> * <dd>If "true" then the server will accept JSON wrapped in a comment and will * generate JSON wrapped in a comment. This is a defence against Ajax Hijacking. * </dd> * * <dt>filters</dt> * <dd>the location of a JSON file describing {@link DataFilter} instances to be * installed</dd> * * <dt>requestAvailable</dt> * <dd>If true, the current request is made available via the * {@link AbstractBayeux#getCurrentRequest()} method</dd> * * <dt>loglevel</dt> * <dd>0=none, 1=info, 2=debug</dd> * * <dt>refsThreshold</dt> * <dd>The number of message refs at which the a single message response will be * cached instead of being generated for every client delivered to. Done to * optimize a single message being sent to multiple clients.</dd> * </dl> * * @author gregw * @author aabeling: added JSONP transport * * @see {@link AbstractBayeux} * @see {@link ChannelId} */ public abstract class AbstractCometdServlet extends GenericServlet { public static final String CLIENT_ATTR="org.mortbay.cometd.client"; public static final String TRANSPORT_ATTR="org.mortbay.cometd.transport"; public static final String MESSAGE_PARAM="message"; public static final String TUNNEL_INIT_PARAM="tunnelInit"; public static final String HTTP_CLIENT_ID="BAYEUX_HTTP_CLIENT"; public final static String BROWSER_ID="BAYEUX_BROWSER"; protected AbstractBayeux _bayeux; public final static int __DEFAULT_REFS_THRESHOLD=0; protected int _refsThreshold=__DEFAULT_REFS_THRESHOLD; public AbstractBayeux getBayeux() { return _bayeux; } protected abstract AbstractBayeux newBayeux(); @Override public void init() throws ServletException { synchronized(AbstractCometdServlet.class) { _bayeux=(AbstractBayeux)getServletContext().getAttribute(Bayeux.ATTRIBUTE); if (_bayeux == null) { _bayeux=newBayeux(); } } synchronized(_bayeux) { boolean was_initialized=_bayeux.isInitialized(); _bayeux.initialize(getServletContext()); if (!was_initialized) { String filters=getInitParameter("filters"); if (filters != null) { try { InputStream is=getServletContext().getResourceAsStream(filters); if (is == null) throw new FileNotFoundException(filters); Object[] objects=(Object[])JSON.parse(new InputStreamReader(getServletContext().getResourceAsStream(filters),"utf-8")); for (int i=0; objects != null && i < objects.length; i++) { Map<?,?> filter_def=(Map<?,?>)objects[i]; String fc=(String)filter_def.get("class"); if (fc != null) Log.warn(filters + " file uses deprecated \"class\" name. Use \"filter\" instead"); else fc=(String)filter_def.get("filter"); Class<?> c=Thread.currentThread().getContextClassLoader().loadClass(fc); DataFilter filter=(DataFilter)c.newInstance(); if (filter instanceof JSONDataFilter) ((JSONDataFilter)filter).init(filter_def.get("init")); _bayeux.getChannel((String)filter_def.get("channels"),true).addDataFilter(filter); } } catch(Exception e) { getServletContext().log("Could not parse: " + filters,e); throw new ServletException(e); } } String timeout=getInitParameter("timeout"); if (timeout != null) _bayeux.setTimeout(Long.parseLong(timeout)); String maxInterval=getInitParameter("maxInterval"); if (maxInterval != null) _bayeux.setMaxInterval(Long.parseLong(maxInterval)); String commentedJSON=getInitParameter("JSONCommented"); _bayeux.setJSONCommented(commentedJSON != null && Boolean.parseBoolean(commentedJSON)); String l=getInitParameter("logLevel"); if (l != null && l.length() > 0) _bayeux.setLogLevel(Integer.parseInt(l)); String interval=getInitParameter("interval"); if (interval != null) _bayeux.setInterval(Long.parseLong(interval)); String maxLazy=getInitParameter("maxLazyLatency"); if (maxLazy != null) _bayeux.setMaxLazyLatency(Integer.parseInt(maxLazy)); String mfInterval=getInitParameter("multiFrameInterval"); if (mfInterval != null) _bayeux.setMultiFrameInterval(Integer.parseInt(mfInterval)); String requestAvailable=getInitParameter("requestAvailable"); _bayeux.setRequestAvailable(requestAvailable != null && Boolean.parseBoolean(requestAvailable)); String async=getInitParameter("asyncDeliver"); if (async != null) getServletContext().log("asyncDeliver no longer supported"); String refsThreshold=getInitParameter("refsThreshold"); if (refsThreshold != null) _refsThreshold=Integer.parseInt(refsThreshold); _bayeux.generateAdvice(); if (_bayeux.isLogInfo()) { getServletContext().log("timeout=" + timeout); getServletContext().log("interval=" + interval); getServletContext().log("maxInterval=" + maxInterval); getServletContext().log("multiFrameInterval=" + mfInterval); getServletContext().log("filters=" + filters); getServletContext().log("refsThreshold=" + refsThreshold); } } } getServletContext().setAttribute(Bayeux.ATTRIBUTE,_bayeux); } protected abstract void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException; @Override public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException { HttpServletRequest request=(HttpServletRequest)req; HttpServletResponse response=(HttpServletResponse)resp; if (_bayeux.isRequestAvailable()) _bayeux.setCurrentRequest(request); try { service(request,response); } finally { if (_bayeux.isRequestAvailable()) _bayeux.setCurrentRequest(null); } } protected String findBrowserId(HttpServletRequest request) { Cookie[] cookies=request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (BROWSER_ID.equals(cookie.getName())) return cookie.getValue(); } } return null; } protected String setBrowserId(HttpServletRequest request, HttpServletResponse response) { String browser_id=Long.toHexString(request.getRemotePort()) + Long.toString(_bayeux.getRandom(),36) + Long.toString(System.currentTimeMillis(),36) + Long.toString(request.getRemotePort(),36); Cookie cookie=new Cookie(BROWSER_ID,browser_id); cookie.setPath("/"); cookie.setMaxAge(-1); response.addCookie(cookie); return browser_id; } private static Message[] __EMPTY_BATCH=new Message[0]; protected Message[] getMessages(HttpServletRequest request) throws IOException { String fodder=null; try { // Get message batches either as JSON body or as message parameters if (request.getContentType() != null && !request.getContentType().startsWith("application/x-www-form-urlencoded")) { return _bayeux.parse(request.getReader()); } String[] batches=request.getParameterValues(MESSAGE_PARAM); if (batches == null || batches.length == 0) return __EMPTY_BATCH; if (batches.length == 0) { fodder=batches[0]; return _bayeux.parse(fodder); } List<Message> messages=new ArrayList<Message>(); for (int i=0; i < batches.length; i++) { if (batches[i] == null) continue; fodder=batches[i]; _bayeux.parseTo(fodder,messages); } return messages.toArray(new Message[messages.size()]); } catch(IOException e) { throw e; } catch(Exception e) { throw new Error(fodder,e); } } }
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.auditmanager.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/UpdateAssessmentFramework" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class UpdateAssessmentFrameworkRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The unique identifier for the framework. * </p> */ private String frameworkId; /** * <p> * The name of the framework to be updated. * </p> */ private String name; /** * <p> * The description of the updated framework. * </p> */ private String description; /** * <p> * The compliance type that the new custom framework supports, such as CIS or HIPAA. * </p> */ private String complianceType; /** * <p> * The control sets that are associated with the framework. * </p> */ private java.util.List<UpdateAssessmentFrameworkControlSet> controlSets; /** * <p> * The unique identifier for the framework. * </p> * * @param frameworkId * The unique identifier for the framework. */ public void setFrameworkId(String frameworkId) { this.frameworkId = frameworkId; } /** * <p> * The unique identifier for the framework. * </p> * * @return The unique identifier for the framework. */ public String getFrameworkId() { return this.frameworkId; } /** * <p> * The unique identifier for the framework. * </p> * * @param frameworkId * The unique identifier for the framework. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateAssessmentFrameworkRequest withFrameworkId(String frameworkId) { setFrameworkId(frameworkId); return this; } /** * <p> * The name of the framework to be updated. * </p> * * @param name * The name of the framework to be updated. */ public void setName(String name) { this.name = name; } /** * <p> * The name of the framework to be updated. * </p> * * @return The name of the framework to be updated. */ public String getName() { return this.name; } /** * <p> * The name of the framework to be updated. * </p> * * @param name * The name of the framework to be updated. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateAssessmentFrameworkRequest withName(String name) { setName(name); return this; } /** * <p> * The description of the updated framework. * </p> * * @param description * The description of the updated framework. */ public void setDescription(String description) { this.description = description; } /** * <p> * The description of the updated framework. * </p> * * @return The description of the updated framework. */ public String getDescription() { return this.description; } /** * <p> * The description of the updated framework. * </p> * * @param description * The description of the updated framework. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateAssessmentFrameworkRequest withDescription(String description) { setDescription(description); return this; } /** * <p> * The compliance type that the new custom framework supports, such as CIS or HIPAA. * </p> * * @param complianceType * The compliance type that the new custom framework supports, such as CIS or HIPAA. */ public void setComplianceType(String complianceType) { this.complianceType = complianceType; } /** * <p> * The compliance type that the new custom framework supports, such as CIS or HIPAA. * </p> * * @return The compliance type that the new custom framework supports, such as CIS or HIPAA. */ public String getComplianceType() { return this.complianceType; } /** * <p> * The compliance type that the new custom framework supports, such as CIS or HIPAA. * </p> * * @param complianceType * The compliance type that the new custom framework supports, such as CIS or HIPAA. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateAssessmentFrameworkRequest withComplianceType(String complianceType) { setComplianceType(complianceType); return this; } /** * <p> * The control sets that are associated with the framework. * </p> * * @return The control sets that are associated with the framework. */ public java.util.List<UpdateAssessmentFrameworkControlSet> getControlSets() { return controlSets; } /** * <p> * The control sets that are associated with the framework. * </p> * * @param controlSets * The control sets that are associated with the framework. */ public void setControlSets(java.util.Collection<UpdateAssessmentFrameworkControlSet> controlSets) { if (controlSets == null) { this.controlSets = null; return; } this.controlSets = new java.util.ArrayList<UpdateAssessmentFrameworkControlSet>(controlSets); } /** * <p> * The control sets that are associated with the framework. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setControlSets(java.util.Collection)} or {@link #withControlSets(java.util.Collection)} if you want to * override the existing values. * </p> * * @param controlSets * The control sets that are associated with the framework. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateAssessmentFrameworkRequest withControlSets(UpdateAssessmentFrameworkControlSet... controlSets) { if (this.controlSets == null) { setControlSets(new java.util.ArrayList<UpdateAssessmentFrameworkControlSet>(controlSets.length)); } for (UpdateAssessmentFrameworkControlSet ele : controlSets) { this.controlSets.add(ele); } return this; } /** * <p> * The control sets that are associated with the framework. * </p> * * @param controlSets * The control sets that are associated with the framework. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateAssessmentFrameworkRequest withControlSets(java.util.Collection<UpdateAssessmentFrameworkControlSet> controlSets) { setControlSets(controlSets); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getFrameworkId() != null) sb.append("FrameworkId: ").append(getFrameworkId()).append(","); if (getName() != null) sb.append("Name: ").append(getName()).append(","); if (getDescription() != null) sb.append("Description: ").append(getDescription()).append(","); if (getComplianceType() != null) sb.append("ComplianceType: ").append(getComplianceType()).append(","); if (getControlSets() != null) sb.append("ControlSets: ").append(getControlSets()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof UpdateAssessmentFrameworkRequest == false) return false; UpdateAssessmentFrameworkRequest other = (UpdateAssessmentFrameworkRequest) obj; if (other.getFrameworkId() == null ^ this.getFrameworkId() == null) return false; if (other.getFrameworkId() != null && other.getFrameworkId().equals(this.getFrameworkId()) == false) return false; if (other.getName() == null ^ this.getName() == null) return false; if (other.getName() != null && other.getName().equals(this.getName()) == false) return false; if (other.getDescription() == null ^ this.getDescription() == null) return false; if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false) return false; if (other.getComplianceType() == null ^ this.getComplianceType() == null) return false; if (other.getComplianceType() != null && other.getComplianceType().equals(this.getComplianceType()) == false) return false; if (other.getControlSets() == null ^ this.getControlSets() == null) return false; if (other.getControlSets() != null && other.getControlSets().equals(this.getControlSets()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getFrameworkId() == null) ? 0 : getFrameworkId().hashCode()); hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode()); hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode()); hashCode = prime * hashCode + ((getComplianceType() == null) ? 0 : getComplianceType().hashCode()); hashCode = prime * hashCode + ((getControlSets() == null) ? 0 : getControlSets().hashCode()); return hashCode; } @Override public UpdateAssessmentFrameworkRequest clone() { return (UpdateAssessmentFrameworkRequest) super.clone(); } }
// Copyright 2014 The Bazel Authors. All rights reserved. // // 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.devtools.build.lib.syntax; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable; import com.google.devtools.build.lib.events.Event; import com.google.devtools.build.lib.events.EventHandler; import com.google.devtools.build.lib.events.Location; import com.google.devtools.build.lib.profiler.Profiler; import com.google.devtools.build.lib.profiler.ProfilerTask; import com.google.devtools.build.lib.util.Pair; import com.google.devtools.build.lib.vfs.PathFragment; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Stack; /** * A tokenizer for the BUILD language. * <p> * See: <a href="https://docs.python.org/2/reference/lexical_analysis.html"/> * for some details. * <p> * Since BUILD files are small, we just tokenize the entire file a-priori * instead of interleaving scanning with parsing. */ public final class Lexer { // Characters that can come immediately prior to an '=' character to generate // a different token private static final ImmutableMap<Character, TokenKind> EQUAL_TOKENS = ImmutableMap.<Character, TokenKind>builder() .put('=', TokenKind.EQUALS_EQUALS) .put('!', TokenKind.NOT_EQUALS) .put('>', TokenKind.GREATER_EQUALS) .put('<', TokenKind.LESS_EQUALS) .put('+', TokenKind.PLUS_EQUALS) .put('-', TokenKind.MINUS_EQUALS) .put('*', TokenKind.STAR_EQUALS) .put('/', TokenKind.SLASH_EQUALS) .put('%', TokenKind.PERCENT_EQUALS) .build(); private final EventHandler eventHandler; // Input buffer and position private final char[] buffer; private int pos; /** * The part of the location information that is common to all LexerLocation * instances created by this Lexer. Factored into a separate object so that * many Locations instances can share the same information as compactly as * possible, without closing over a Lexer instance. */ private static class LocationInfo { final LineNumberTable lineNumberTable; final PathFragment filename; LocationInfo(PathFragment filename, LineNumberTable lineNumberTable) { this.filename = filename; this.lineNumberTable = lineNumberTable; } } private final LocationInfo locationInfo; // The stack of enclosing indentation levels; always contains '0' at the // bottom. private final Stack<Integer> indentStack = new Stack<>(); private final List<Token> tokens; // The number of unclosed open-parens ("(", '{', '[') at the current point in // the stream. Whitespace is handled differently when this is nonzero. private int openParenStackDepth = 0; private boolean containsErrors; /** * Constructs a lexer which tokenizes the contents of the specified InputBuffer. Any errors during * lexing are reported on "handler". */ public Lexer( ParserInputSource input, EventHandler eventHandler, LineNumberTable lineNumberTable) { this.buffer = input.getContent(); // Empirical measurements show roughly 1 token per 8 characters in buffer. this.tokens = Lists.newArrayListWithExpectedSize(buffer.length / 8); this.pos = 0; this.eventHandler = eventHandler; this.locationInfo = new LocationInfo(input.getPath(), lineNumberTable); indentStack.push(0); long startTime = Profiler.nanoTimeMaybe(); tokenize(); Profiler.instance().logSimpleTask(startTime, ProfilerTask.SKYLARK_LEXER, getFilename()); } public Lexer(ParserInputSource input, EventHandler eventHandler) { this(input, eventHandler, LineNumberTable.create(input.getContent(), input.getPath())); } /** * Returns the filename from which the lexer's input came. Returns an empty value if the input * came from a string. */ public PathFragment getFilename() { return locationInfo.filename != null ? locationInfo.filename : PathFragment.EMPTY_FRAGMENT; } /** * Returns true if there were errors during scanning of this input file or * string. The Lexer may attempt to recover from errors, but clients should * not rely on the results of scanning if this flag is set. */ public boolean containsErrors() { return containsErrors; } /** * Returns the (mutable) list of tokens generated by the Lexer. */ public List<Token> getTokens() { return tokens; } private void popParen() { if (openParenStackDepth == 0) { error("indentation error"); } else { openParenStackDepth--; } } private void error(String message) { error(message, pos - 1, pos - 1); } private void error(String message, int start, int end) { this.containsErrors = true; eventHandler.handle(Event.error(createLocation(start, end), message)); } Location createLocation(int start, int end) { return new LexerLocation(locationInfo, start, end); } // Don't use an inner class as we don't want to close over the Lexer, only // the LocationInfo. @Immutable private static final class LexerLocation extends Location { private final LineNumberTable lineNumberTable; LexerLocation(LocationInfo locationInfo, int start, int end) { super(start, end); this.lineNumberTable = locationInfo.lineNumberTable; } @Override public PathFragment getPath() { PathFragment path = lineNumberTable.getPath(getStartOffset()); return path; } @Override public LineAndColumn getStartLineAndColumn() { return lineNumberTable.getLineAndColumn(getStartOffset()); } @Override public LineAndColumn getEndLineAndColumn() { return lineNumberTable.getLineAndColumn(getEndOffset()); } @Override public int hashCode() { return Objects.hash(lineNumberTable, internalHashCode()); } @Override public boolean equals(Object other) { if (other == null || !other.getClass().equals(getClass())) { return false; } LexerLocation that = (LexerLocation) other; return internalEquals(that) && Objects.equals(this.lineNumberTable, that.lineNumberTable); } } /** invariant: symbol positions are half-open intervals. */ private void addToken(Token s) { tokens.add(s); } /** * Parses an end-of-line sequence, handling statement indentation correctly. * * <p>UNIX newlines are assumed (LF). Carriage returns are always ignored. * * <p>ON ENTRY: 'pos' is the index of the char after '\n'. * ON EXIT: 'pos' is the index of the next non-space char after '\n'. */ private void newline() { if (openParenStackDepth > 0) { newlineInsideExpression(); // in an expression: ignore space } else { newlineOutsideExpression(); // generate NEWLINE/INDENT/OUTDENT tokens } } private void newlineInsideExpression() { while (pos < buffer.length) { switch (buffer[pos]) { case ' ': case '\t': case '\r': pos++; break; default: return; } } } private void newlineOutsideExpression() { if (pos > 1) { // skip over newline at start of file addToken(new Token(TokenKind.NEWLINE, pos - 1, pos)); } // we're in a stmt: suck up space at beginning of next line int indentLen = 0; while (pos < buffer.length) { char c = buffer[pos]; if (c == ' ') { indentLen++; pos++; } else if (c == '\r') { pos++; } else if (c == '\t') { indentLen += 8 - indentLen % 8; pos++; } else if (c == '\n') { // entirely blank line: discard indentLen = 0; pos++; } else if (c == '#') { // line containing only indented comment int oldPos = pos; while (pos < buffer.length && c != '\n') { c = buffer[pos++]; } addToken(new Token(TokenKind.COMMENT, oldPos, pos - 1, bufferSlice(oldPos, pos - 1))); indentLen = 0; } else { // printing character break; } } if (pos == buffer.length) { indentLen = 0; } // trailing space on last line int peekedIndent = indentStack.peek(); if (peekedIndent < indentLen) { // push a level indentStack.push(indentLen); addToken(new Token(TokenKind.INDENT, pos - 1, pos)); } else if (peekedIndent > indentLen) { // pop one or more levels while (peekedIndent > indentLen) { indentStack.pop(); addToken(new Token(TokenKind.OUTDENT, pos - 1, pos)); peekedIndent = indentStack.peek(); } if (peekedIndent < indentLen) { error("indentation error"); } } } /** * Returns true if current position is in the middle of a triple quote * delimiter (3 x quot), and advances 'pos' by two if so. */ private boolean skipTripleQuote(char quot) { if (lookaheadIs(0, quot) && lookaheadIs(1, quot)) { pos += 2; return true; } else { return false; } } /** * Scans a string literal delimited by 'quot', containing escape sequences. * * <p>ON ENTRY: 'pos' is 1 + the index of the first delimiter * ON EXIT: 'pos' is 1 + the index of the last delimiter. * * @return the string-literal token. */ private Token escapedStringLiteral(char quot, boolean isRaw) { boolean inTriplequote = skipTripleQuote(quot); int oldPos = pos - 1; // more expensive second choice that expands escaped into a buffer StringBuilder literal = new StringBuilder(); while (pos < buffer.length) { char c = buffer[pos]; pos++; switch (c) { case '\n': if (inTriplequote) { literal.append(c); break; } else { error("unterminated string literal at eol", oldPos, pos); newline(); return new Token(TokenKind.STRING, oldPos, pos, literal.toString()); } case '\\': if (pos == buffer.length) { error("unterminated string literal at eof", oldPos, pos); return new Token(TokenKind.STRING, oldPos, pos, literal.toString()); } if (isRaw) { // Insert \ and the following character. // As in Python, it means that a raw string can never end with a single \. literal.append('\\'); if (lookaheadIs(0, '\r') && lookaheadIs(1, '\n')) { literal.append("\n"); pos += 2; } else if (buffer[pos] == '\r' || buffer[pos] == '\n') { literal.append("\n"); pos += 1; } else { literal.append(buffer[pos]); pos += 1; } break; } c = buffer[pos]; pos++; switch (c) { case '\r': if (lookaheadIs(0, '\n')) { pos += 1; break; } else { break; } case '\n': // ignore end of line character break; case 'n': literal.append('\n'); break; case 'r': literal.append('\r'); break; case 't': literal.append('\t'); break; case '\\': literal.append('\\'); break; case '\'': literal.append('\''); break; case '"': literal.append('"'); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': { // octal escape int octal = c - '0'; if (pos < buffer.length) { c = buffer[pos]; if (c >= '0' && c <= '7') { pos++; octal = (octal << 3) | (c - '0'); if (pos < buffer.length) { c = buffer[pos]; if (c >= '0' && c <= '7') { pos++; octal = (octal << 3) | (c - '0'); } } } } literal.append((char) (octal & 0xff)); break; } case 'a': case 'b': case 'f': case 'N': case 'u': case 'U': case 'v': case 'x': // exists in Python but not implemented in Blaze => error error("escape sequence not implemented: \\" + c, oldPos, pos); break; default: // unknown char escape => "\literal" literal.append('\\'); literal.append(c); break; } break; case '\'': case '"': if (c != quot || (inTriplequote && !skipTripleQuote(quot))) { // Non-matching quote, treat it like a regular char. literal.append(c); } else { // Matching close-delimiter, all done. return new Token(TokenKind.STRING, oldPos, pos, literal.toString()); } break; default: literal.append(c); break; } } error("unterminated string literal at eof", oldPos, pos); return new Token(TokenKind.STRING, oldPos, pos, literal.toString()); } /** * Scans a string literal delimited by 'quot'. * * <ul> * <li> ON ENTRY: 'pos' is 1 + the index of the first delimiter * <li> ON EXIT: 'pos' is 1 + the index of the last delimiter. * </ul> * * @param isRaw if true, do not escape the string. * @return the string-literal token. */ private Token stringLiteral(char quot, boolean isRaw) { int oldPos = pos - 1; // Don't even attempt to parse triple-quotes here. if (skipTripleQuote(quot)) { pos -= 2; return escapedStringLiteral(quot, isRaw); } // first quick optimistic scan for a simple non-escaped string while (pos < buffer.length) { char c = buffer[pos++]; switch (c) { case '\n': error("unterminated string literal at eol", oldPos, pos); Token t = new Token(TokenKind.STRING, oldPos, pos, bufferSlice(oldPos + 1, pos - 1)); newline(); return t; case '\\': if (isRaw) { if (lookaheadIs(0, '\r') && lookaheadIs(1, '\n')) { // There was a CRLF after the newline. No shortcut possible, since it needs to be // transformed into a single LF. pos = oldPos + 1; return escapedStringLiteral(quot, true); } else { pos++; break; } } // oops, hit an escape, need to start over & build a new string buffer pos = oldPos + 1; return escapedStringLiteral(quot, false); case '\'': case '"': if (c == quot) { // close-quote, all done. return new Token(TokenKind.STRING, oldPos, pos, bufferSlice(oldPos + 1, pos - 1)); } break; default: // fall out } } // If the current position is beyond the end of the file, need to move it backwards // Possible if the file ends with `r"\` (unterminated raw string literal with a backslash) if (pos > buffer.length) { pos = buffer.length; } error("unterminated string literal at eof", oldPos, pos); return new Token(TokenKind.STRING, oldPos, pos, bufferSlice(oldPos + 1, pos)); } private static final Map<String, TokenKind> keywordMap = new HashMap<>(); static { keywordMap.put("and", TokenKind.AND); keywordMap.put("as", TokenKind.AS); keywordMap.put("assert", TokenKind.ASSERT); keywordMap.put("break", TokenKind.BREAK); keywordMap.put("class", TokenKind.CLASS); keywordMap.put("continue", TokenKind.CONTINUE); keywordMap.put("def", TokenKind.DEF); keywordMap.put("del", TokenKind.DEL); keywordMap.put("elif", TokenKind.ELIF); keywordMap.put("else", TokenKind.ELSE); keywordMap.put("except", TokenKind.EXCEPT); keywordMap.put("finally", TokenKind.FINALLY); keywordMap.put("for", TokenKind.FOR); keywordMap.put("from", TokenKind.FROM); keywordMap.put("global", TokenKind.GLOBAL); keywordMap.put("if", TokenKind.IF); keywordMap.put("import", TokenKind.IMPORT); keywordMap.put("in", TokenKind.IN); keywordMap.put("is", TokenKind.IS); keywordMap.put("lambda", TokenKind.LAMBDA); keywordMap.put("nonlocal", TokenKind.NONLOCAL); keywordMap.put("not", TokenKind.NOT); keywordMap.put("or", TokenKind.OR); keywordMap.put("pass", TokenKind.PASS); keywordMap.put("raise", TokenKind.RAISE); keywordMap.put("return", TokenKind.RETURN); keywordMap.put("try", TokenKind.TRY); keywordMap.put("while", TokenKind.WHILE); keywordMap.put("with", TokenKind.WITH); keywordMap.put("yield", TokenKind.YIELD); } /** * Scans an identifier or keyword. * * <p>ON ENTRY: 'pos' is 1 + the index of the first char in the identifier. * ON EXIT: 'pos' is 1 + the index of the last char in the identifier. * * @return the identifier or keyword token. */ private Token identifierOrKeyword() { int oldPos = pos - 1; String id = scanIdentifier(); TokenKind kind = keywordMap.get(id); return (kind == null) ? new Token(TokenKind.IDENTIFIER, oldPos, pos, id) : new Token(kind, oldPos, pos, null); } private String scanIdentifier() { int oldPos = pos - 1; while (pos < buffer.length) { switch (buffer[pos]) { case '_': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': pos++; break; default: return bufferSlice(oldPos, pos); } } return bufferSlice(oldPos, pos); } private String scanInteger() { int oldPos = pos - 1; while (pos < buffer.length) { char c = buffer[pos]; switch (c) { case 'X': case 'x': case 'a': case 'A': case 'b': case 'B': case 'c': case 'C': case 'd': case 'D': case 'e': case 'E': case 'f': case 'F': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': pos++; break; default: return bufferSlice(oldPos, pos); } } // TODO(bazel-team): (2009) to do roundtripping when we evaluate the integer // constants, we must save the actual text of the tokens, not just their // integer value. return bufferSlice(oldPos, pos); } /** * Scans an integer literal. * * <p>ON ENTRY: 'pos' is 1 + the index of the first char in the literal. * ON EXIT: 'pos' is 1 + the index of the last char in the literal. * * @return the integer token. */ private Token integer() { int oldPos = pos - 1; String literal = scanInteger(); final String substring; final int radix; if (literal.startsWith("0x") || literal.startsWith("0X")) { radix = 16; substring = literal.substring(2); } else if (literal.startsWith("0") && literal.length() > 1) { radix = 8; substring = literal.substring(1); } else { radix = 10; substring = literal; } int value = 0; try { value = Integer.parseInt(substring, radix); } catch (NumberFormatException e) { error("invalid base-" + radix + " integer constant: " + literal); } return new Token(TokenKind.INT, oldPos, pos, value); } /** * Tokenizes a two-char operator. * @return true if it tokenized an operator */ private boolean tokenizeTwoChars() { if (pos + 2 >= buffer.length) { return false; } char c1 = buffer[pos]; char c2 = buffer[pos + 1]; TokenKind tok = null; if (c2 == '=') { tok = EQUAL_TOKENS.get(c1); } else if (c2 == '*' && c1 == '*') { tok = TokenKind.STAR_STAR; } if (tok == null) { return false; } else { addToken(new Token(tok, pos, pos + 2)); return true; } } /** Test if the character at pos+p is c. */ private boolean lookaheadIs(int p, char c) { return pos + p < buffer.length && buffer[pos + p] == c; } /** * Performs tokenization of the character buffer of file contents provided to * the constructor. */ private void tokenize() { while (pos < buffer.length) { if (tokenizeTwoChars()) { pos += 2; continue; } char c = buffer[pos]; pos++; switch (c) { case '{': { addToken(new Token(TokenKind.LBRACE, pos - 1, pos)); openParenStackDepth++; break; } case '}': { addToken(new Token(TokenKind.RBRACE, pos - 1, pos)); popParen(); break; } case '(': { addToken(new Token(TokenKind.LPAREN, pos - 1, pos)); openParenStackDepth++; break; } case ')': { addToken(new Token(TokenKind.RPAREN, pos - 1, pos)); popParen(); break; } case '[': { addToken(new Token(TokenKind.LBRACKET, pos - 1, pos)); openParenStackDepth++; break; } case ']': { addToken(new Token(TokenKind.RBRACKET, pos - 1, pos)); popParen(); break; } case '>': { addToken(new Token(TokenKind.GREATER, pos - 1, pos)); break; } case '<': { addToken(new Token(TokenKind.LESS, pos - 1, pos)); break; } case ':': { addToken(new Token(TokenKind.COLON, pos - 1, pos)); break; } case ',': { addToken(new Token(TokenKind.COMMA, pos - 1, pos)); break; } case '+': { addToken(new Token(TokenKind.PLUS, pos - 1, pos)); break; } case '-': { addToken(new Token(TokenKind.MINUS, pos - 1, pos)); break; } case '|': { addToken(new Token(TokenKind.PIPE, pos - 1, pos)); break; } case '=': { addToken(new Token(TokenKind.EQUALS, pos - 1, pos)); break; } case '%': { addToken(new Token(TokenKind.PERCENT, pos - 1, pos)); break; } case '/': { if (lookaheadIs(0, '/') && lookaheadIs(1, '=')) { addToken(new Token(TokenKind.SLASH_SLASH_EQUALS, pos - 1, pos + 2)); pos += 2; } else if (lookaheadIs(0, '/')) { addToken(new Token(TokenKind.SLASH_SLASH, pos - 1, pos + 1)); pos += 1; } else { // /= is handled by tokenizeTwoChars. addToken(new Token(TokenKind.SLASH, pos - 1, pos)); } break; } case ';': { addToken(new Token(TokenKind.SEMI, pos - 1, pos)); break; } case '.': { addToken(new Token(TokenKind.DOT, pos - 1, pos)); break; } case '*': { addToken(new Token(TokenKind.STAR, pos - 1, pos)); break; } case ' ': case '\t': case '\r': { /* ignore */ break; } case '\\': { // Backslash character is valid only at the end of a line (or in a string) if (lookaheadIs(0, '\n')) { pos += 1; // skip the end of line character } else if (lookaheadIs(0, '\r') && lookaheadIs(1, '\n')) { pos += 2; // skip the CRLF at the end of line } else { addToken(new Token(TokenKind.ILLEGAL, pos - 1, pos, Character.toString(c))); } break; } case '\n': { newline(); break; } case '#': { int oldPos = pos - 1; while (pos < buffer.length) { c = buffer[pos]; if (c == '\n') { break; } else { pos++; } } addToken(new Token(TokenKind.COMMENT, oldPos, pos, bufferSlice(oldPos, pos))); break; } case '\'': case '\"': { addToken(stringLiteral(c, false)); break; } default: { // detect raw strings, e.g. r"str" if (c == 'r' && pos < buffer.length && (buffer[pos] == '\'' || buffer[pos] == '\"')) { c = buffer[pos]; pos++; addToken(stringLiteral(c, true)); break; } if (Character.isDigit(c)) { addToken(integer()); } else if (Character.isJavaIdentifierStart(c) && c != '$') { addToken(identifierOrKeyword()); } else { error("invalid character: '" + c + "'"); } break; } // default } // switch } // while if (indentStack.size() > 1) { // top of stack is always zero addToken(new Token(TokenKind.NEWLINE, pos - 1, pos)); while (indentStack.size() > 1) { indentStack.pop(); addToken(new Token(TokenKind.OUTDENT, pos - 1, pos)); } } // Like Python, always end with a NEWLINE token, even if no '\n' in input: if (tokens.isEmpty() || Iterables.getLast(tokens).kind != TokenKind.NEWLINE) { addToken(new Token(TokenKind.NEWLINE, pos - 1, pos)); } addToken(new Token(TokenKind.EOF, pos, pos)); } /** * Returns the string at the current line, minus the new line. * * @param line the line from which to retrieve the String, 1-based * @return the text of the line */ public String stringAtLine(int line) { Pair<Integer, Integer> offsets = locationInfo.lineNumberTable.getOffsetsForLine(line); return bufferSlice(offsets.first, offsets.second); } /** * Returns parts of the source buffer based on offsets * * @param start the beginning offset for the slice * @param end the offset immediately following the slice * @return the text at offset start with length end - start */ private String bufferSlice(int start, int end) { return new String(this.buffer, start, end - start); } }
/** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 1999-2015, QOS.ch. All rights reserved. * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation * * or (per the licensee's choosing) * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ package ch.qos.logback.core; import static ch.qos.logback.core.CoreConstants.CODES_URL; import java.io.IOException; import java.io.OutputStream; import java.util.concurrent.locks.ReentrantLock; import ch.qos.logback.core.encoder.Encoder; import ch.qos.logback.core.encoder.LayoutWrappingEncoder; import ch.qos.logback.core.spi.DeferredProcessingAware; import ch.qos.logback.core.status.ErrorStatus; /** * OutputStreamAppender appends events to a {@link OutputStream}. This class * provides basic services that other appenders build upon. * * For more information about this appender, please refer to the online manual * at http://logback.qos.ch/manual/appenders.html#OutputStreamAppender * * @author Ceki G&uuml;lc&uuml; */ public class OutputStreamAppender<E> extends UnsynchronizedAppenderBase<E> { /** * It is the encoder which is ultimately responsible for writing the event to * an {@link OutputStream}. */ protected Encoder<E> encoder; /** * All synchronization in this class is done via the lock object. */ protected final ReentrantLock lock = new ReentrantLock(true); /** * This is the {@link OutputStream outputStream} where output will be written. */ private OutputStream outputStream; /** * The underlying output stream used by this appender. * * @return */ public OutputStream getOutputStream() { return outputStream; } /** * Checks that requires parameters are set and if everything is in order, * activates this appender. */ public void start() { int errors = 0; if (this.encoder == null) { addStatus(new ErrorStatus("No encoder set for the appender named \"" + name + "\".", this)); errors++; } if (this.outputStream == null) { addStatus(new ErrorStatus( "No output stream set for the appender named \"" + name + "\".", this)); errors++; } // only error free appenders should be activated if (errors == 0) { super.start(); } } public void setLayout(Layout<E> layout) { addWarn("This appender no longer admits a layout as a sub-component, set an encoder instead."); addWarn("To ensure compatibility, wrapping your layout in LayoutWrappingEncoder."); addWarn("See also "+CODES_URL+"#layoutInsteadOfEncoder for details"); LayoutWrappingEncoder<E> lwe = new LayoutWrappingEncoder<E>(); lwe.setLayout(layout); lwe.setContext(context); this.encoder = lwe; } @Override protected void append(E eventObject) { if (!isStarted()) { return; } subAppend(eventObject); } /** * Stop this appender instance. The underlying stream or writer is also * closed. * * <p> * Stopped appenders cannot be reused. */ public void stop() { lock.lock(); try { closeOutputStream(); super.stop(); } finally { lock.unlock(); } } /** * Close the underlying {@link OutputStream}. */ protected void closeOutputStream() { if (this.outputStream != null) { try { // before closing we have to output out layout's footer encoderClose(); this.outputStream.close(); this.outputStream = null; } catch (IOException e) { addStatus(new ErrorStatus( "Could not close output stream for OutputStreamAppender.", this, e)); } } } void encoderInit() { if (encoder != null && this.outputStream != null) { try { encoder.init(outputStream); } catch (IOException ioe) { this.started = false; addStatus(new ErrorStatus( "Failed to initialize encoder for appender named [" + name + "].", this, ioe)); } } } void encoderClose() { if (encoder != null && this.outputStream != null) { try { encoder.close(); } catch (IOException ioe) { this.started = false; addStatus(new ErrorStatus("Failed to write footer for appender named [" + name + "].", this, ioe)); } } } /** * <p> * Sets the @link OutputStream} where the log output will go. The specified * <code>OutputStream</code> must be opened by the user and be writable. The * <code>OutputStream</code> will be closed when the appender instance is * closed. * * @param outputStream * An already opened OutputStream. */ public void setOutputStream(OutputStream outputStream) { lock.lock(); try { // close any previously opened output stream closeOutputStream(); this.outputStream = outputStream; if (encoder == null) { addWarn("Encoder has not been set. Cannot invoke its init method."); return; } encoderInit(); } finally { lock.unlock(); } } protected void writeOut(E event) throws IOException { this.encoder.doEncode(event); } /** * Actual writing occurs here. * <p> * Most subclasses of <code>WriterAppender</code> will need to override this * method. * * @since 0.9.0 */ protected void subAppend(E event) { if (!isStarted()) { return; } try { // this step avoids LBCLASSIC-139 if (event instanceof DeferredProcessingAware) { ((DeferredProcessingAware) event).prepareForDeferredProcessing(); } // the synchronization prevents the OutputStream from being closed while we // are writing. It also prevents multiple threads from entering the same // converter. Converters assume that they are in a synchronized block. lock.lock(); try { writeOut(event); } finally { lock.unlock(); } } catch (IOException ioe) { // as soon as an exception occurs, move to non-started state // and add a single ErrorStatus to the SM. this.started = false; addStatus(new ErrorStatus("IO failure in appender", this, ioe)); } } public Encoder<E> getEncoder() { return encoder; } public void setEncoder(Encoder<E> encoder) { this.encoder = encoder; } }
/* * Copyright 2015 Paul Sidnell * * 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.psidnell.omnifocus.model; import java.util.LinkedList; import java.util.List; import org.psidnell.omnifocus.expr.ExprAttribute; import org.psidnell.omnifocus.sqlite.SQLiteProperty; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonPropertyOrder; /** * @author psidnell * * Represents an OmniFocus Context. * */ @JsonPropertyOrder(alphabetic=true) public class Context extends NodeImpl implements ContextHierarchyNode{ public static final String TYPE = "Context"; private List<Task> tasks = new LinkedList<>(); private List<Context> contexts = new LinkedList<>(); private String parentContextId; private Context parent; private boolean active = true; private boolean allowsNextAction = true; @Deprecated // Should use NodeFactory public Context() { } @Deprecated // Should use NodeFactory public Context(String name) { this.name = name; } @ExprAttribute(help = "number of tasks.") @JsonIgnore public int getTaskCount() { return tasks.size(); } @ExprAttribute(help = "number of uncompleted tasks.") @JsonIgnore public int getUncompletedTaskCount() { int count = 0; for (Task child : tasks) { if (!child.isCompleted()) { count++; } } return count; } @ExprAttribute(help = "the sub tasks.") public List<Task> getTasks() { return tasks; } public void setTasks(List<Task> tasks) { this.tasks = tasks; } @ExprAttribute(help = "number of contexts.") @JsonIgnore public int getContextCount() { return contexts.size(); } public List<Context> getContexts() { return contexts; } public void setContexts(List<Context> contexts) { this.contexts = contexts; } @SQLiteProperty(name = "parent") public String getParentContextId() { return parentContextId; } public void setParentContextId(String parentContextId) { this.parentContextId = parentContextId; } @Override @JsonIgnore @ExprAttribute(help = "the items type: '" + TYPE + "'.") public String getType() { return TYPE; } @JsonIgnore @Override public Context getContextModeParent() { return parent; } @Override public void setContextModeParent(Context parent) { this.parent = parent; } @SQLiteProperty(name="active") public boolean isActiveFlag() { return active; } public void setActiveFlag(boolean active) { this.active = active; } @ExprAttribute(help = "true if context is active.") public boolean isActive() { return active && allowsNextAction; } public void setActive(boolean dummy) { // To keep jackson happy } @ExprAttribute(help = "true if context is on hold.") public boolean isOnHold () { return active && !allowsNextAction; } public void setOnHold (boolean dummy) { // Keep Jackson happy } @ExprAttribute(help = "true if context is dropped.") public boolean isDropped () { // Unlike the other statuses dropped does cascade if (!active) { return true; } if (parent != null) { return parent.isDropped(); } return false; } public void setDropped (boolean dummy) { // Keep Jackson happy } @SQLiteProperty public boolean getAllowsNextAction() { return allowsNextAction; } public void setAllowsNextAction(boolean allowsNextAction) { this.allowsNextAction = allowsNextAction; } @Override @JsonIgnore public List<ContextHierarchyNode> getContextPath() { return getContextPath(parent); } public void add(Context child) { Context oldParent = child.getContextModeParent(); if (oldParent != null) { oldParent.getContexts().remove(child); } contexts.add(child); child.setContextModeParent(this); } public void add(Task child) { Context oldParent = child.getContextModeParent(); if (oldParent != null) { oldParent.getTasks().remove(child); } tasks.add(child); child.setContextModeParent(this); } @Override public void cascadeMarked() { setMarked(true); tasks.stream().forEach((t) -> t.setMarked(true)); contexts.stream().forEach((c) -> c.cascadeMarked()); } }
/** * 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.codehaus.groovy.runtime.metaclass; import groovy.lang.*; import org.codehaus.groovy.classgen.Verifier; import org.codehaus.groovy.reflection.*; import org.codehaus.groovy.runtime.*; import org.codehaus.groovy.runtime.m12n.ExtensionModule; import org.codehaus.groovy.runtime.m12n.ExtensionModuleRegistry; import org.codehaus.groovy.runtime.m12n.ExtensionModuleScanner; import org.codehaus.groovy.vmplugin.VMPluginFactory; import org.codehaus.groovy.util.FastArray; import org.codehaus.groovy.util.ManagedLinkedList; import org.codehaus.groovy.util.ReferenceBundle; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.*; /** * A registry of MetaClass instances which caches introspection & * reflection information and allows methods to be dynamically added to * existing classes at runtime * * @author <a href="mailto:james@coredevelopers.net">James Strachan</a> * @author John Wilson * @author <a href="mailto:blackdrag@gmx.org">Jochen Theodorou</a> * @author Graeme Rocher * @author Alex Tkachman * */ public class MetaClassRegistryImpl implements MetaClassRegistry{ /** * @deprecated Use {@link ExtensionModuleScanner#MODULE_META_INF_FILE instead} */ public static final String MODULE_META_INF_FILE = "META-INF/services/org.codehaus.groovy.runtime.ExtensionModule"; private final boolean useAccessible; private final FastArray instanceMethods = new FastArray(); private final FastArray staticMethods = new FastArray(); private final LinkedList<MetaClassRegistryChangeEventListener> changeListenerList = new LinkedList<MetaClassRegistryChangeEventListener>(); private final LinkedList<MetaClassRegistryChangeEventListener> nonRemoveableChangeListenerList = new LinkedList<MetaClassRegistryChangeEventListener>(); private final ManagedLinkedList metaClassInfo = new ManagedLinkedList<MetaClass>(ReferenceBundle.getWeakBundle()); private final ExtensionModuleRegistry moduleRegistry = new ExtensionModuleRegistry(); public static final int LOAD_DEFAULT = 0; public static final int DONT_LOAD_DEFAULT = 1; private static MetaClassRegistry instanceInclude; private static MetaClassRegistry instanceExclude; public MetaClassRegistryImpl() { this(LOAD_DEFAULT, true); } public MetaClassRegistryImpl(int loadDefault) { this(loadDefault, true); } /** * @param useAccessible defines whether or not the {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} * method will be called to enable access to all methods when using reflection */ public MetaClassRegistryImpl(boolean useAccessible) { this(LOAD_DEFAULT, useAccessible); } public MetaClassRegistryImpl(final int loadDefault, final boolean useAccessible) { this.useAccessible = useAccessible; if (loadDefault == LOAD_DEFAULT) { final Map<CachedClass, List<MetaMethod>> map = new HashMap<CachedClass, List<MetaMethod>>(); // let's register the default methods registerMethods(null, true, true, map); final Class[] additionals = DefaultGroovyMethods.additionals; for (int i = 0; i != additionals.length; ++i) { createMetaMethodFromClass(map, additionals[i]); } Class[] pluginDGMs = VMPluginFactory.getPlugin().getPluginDefaultGroovyMethods(); for (Class plugin : pluginDGMs) { registerMethods(plugin, false, true, map); } registerMethods(DefaultGroovyStaticMethods.class, false, false, map); Class[] staticPluginDGMs = VMPluginFactory.getPlugin().getPluginStaticGroovyMethods(); for (Class plugin : staticPluginDGMs) { registerMethods(plugin, false, false, map); } ExtensionModuleScanner scanner = new ExtensionModuleScanner(new DefaultModuleListener(map), this.getClass().getClassLoader()); scanner.scanClasspathModules(); refreshMopMethods(map); } installMetaClassCreationHandle(); final MetaClass emcMetaClass = metaClassCreationHandle.create(ExpandoMetaClass.class, this); emcMetaClass.initialize(); ClassInfo.getClassInfo(ExpandoMetaClass.class).setStrongMetaClass(emcMetaClass); addNonRemovableMetaClassRegistryChangeEventListener(new MetaClassRegistryChangeEventListener(){ public void updateConstantMetaClass(MetaClassRegistryChangeEvent cmcu) { synchronized (metaClassInfo) { metaClassInfo.add(cmcu.getNewMetaClass()); DefaultMetaClassInfo.getNewConstantMetaClassVersioning(); Class c = cmcu.getClassToUpdate(); DefaultMetaClassInfo.setPrimitiveMeta(c, cmcu.getNewMetaClass()==null); Field sdyn; try { sdyn = c.getDeclaredField(Verifier.STATIC_METACLASS_BOOL); sdyn.setBoolean(null, cmcu.getNewMetaClass()!=null); } catch (Throwable e) { //DO NOTHING } } } }); } private void refreshMopMethods(final Map<CachedClass, List<MetaMethod>> map) { for (Map.Entry<CachedClass, List<MetaMethod>> e : map.entrySet()) { CachedClass cls = e.getKey(); cls.setNewMopMethods(e.getValue()); } } public void registerExtensionModuleFromProperties(final Properties properties, final ClassLoader classLoader, final Map<CachedClass, List<MetaMethod>> map) { ExtensionModuleScanner scanner = new ExtensionModuleScanner(new DefaultModuleListener(map), classLoader); scanner.scanExtensionModuleFromProperties(properties); } public ExtensionModuleRegistry getModuleRegistry() { return moduleRegistry; } /** * Looks for a class called 'groovy.runtime.metaclass.CustomMetaClassCreationHandle' and if it exists uses it as the MetaClassCreationHandle * otherwise uses the default * * @see groovy.lang.MetaClassRegistry.MetaClassCreationHandle */ private void installMetaClassCreationHandle() { try { final Class customMetaClassHandle = Class.forName("groovy.runtime.metaclass.CustomMetaClassCreationHandle"); final Constructor customMetaClassHandleConstructor = customMetaClassHandle.getConstructor(new Class[]{}); this.metaClassCreationHandle = (MetaClassCreationHandle)customMetaClassHandleConstructor.newInstance(); } catch (final ClassNotFoundException e) { this.metaClassCreationHandle = new MetaClassCreationHandle(); } catch (final Exception e) { throw new GroovyRuntimeException("Could not instantiate custom Metaclass creation handle: "+ e, e); } } private void registerMethods(final Class theClass, final boolean useMethodWrapper, final boolean useInstanceMethods, Map<CachedClass, List<MetaMethod>> map) { if (useMethodWrapper) { // Here we instantiate objects representing MetaMethods for DGM methods. // Calls for such meta methods done without reflection, so more effectively. try { List<GeneratedMetaMethod.DgmMethodRecord> records = GeneratedMetaMethod.DgmMethodRecord.loadDgmInfo(); for (GeneratedMetaMethod.DgmMethodRecord record : records) { Class[] newParams = new Class[record.parameters.length - 1]; System.arraycopy(record.parameters, 1, newParams, 0, record.parameters.length-1); MetaMethod method = new GeneratedMetaMethod.Proxy( record.className, record.methodName, ReflectionCache.getCachedClass(record.parameters[0]), record.returnType, newParams ); final CachedClass declClass = method.getDeclaringClass(); List<MetaMethod> arr = map.get(declClass); if (arr == null) { arr = new ArrayList<MetaMethod>(4); map.put(declClass, arr); } arr.add(method); instanceMethods.add(method); } } catch (Throwable e) { e.printStackTrace(); // we print the error, but we don't stop with an exception here // since it is more comfortable this way for development } } else { CachedMethod[] methods = ReflectionCache.getCachedClass(theClass).getMethods(); for (CachedMethod method : methods) { final int mod = method.getModifiers(); if (Modifier.isStatic(mod) && Modifier.isPublic(mod) && method.getCachedMethod().getAnnotation(Deprecated.class) == null) { CachedClass[] paramTypes = method.getParameterTypes(); if (paramTypes.length > 0) { List<MetaMethod> arr = map.get(paramTypes[0]); if (arr == null) { arr = new ArrayList<MetaMethod>(4); map.put(paramTypes[0], arr); } if (useInstanceMethods) { final NewInstanceMetaMethod metaMethod = new NewInstanceMetaMethod(method); arr.add(metaMethod); instanceMethods.add(metaMethod); } else { final NewStaticMetaMethod metaMethod = new NewStaticMetaMethod(method); arr.add(metaMethod); staticMethods.add(metaMethod); } } } } } } private void createMetaMethodFromClass(Map<CachedClass, List<MetaMethod>> map, Class aClass) { try { MetaMethod method = (MetaMethod) aClass.newInstance(); final CachedClass declClass = method.getDeclaringClass(); List<MetaMethod> arr = map.get(declClass); if (arr == null) { arr = new ArrayList<MetaMethod>(4); map.put(declClass, arr); } arr.add(method); instanceMethods.add(method); } catch (InstantiationException e) { /* ignore */ } catch (IllegalAccessException e) { /* ignore */ } } public final MetaClass getMetaClass(Class theClass) { return ClassInfo.getClassInfo(theClass).getMetaClass(); } public MetaClass getMetaClass(Object obj) { return ClassInfo.getClassInfo(obj.getClass()).getMetaClass(obj); } /** * if oldMc is null, newMc will replace whatever meta class was used before. * if oldMc is not null, then newMc will be used only if he stored mc is * the same as oldMc */ private void setMetaClass(Class theClass, MetaClass oldMc, MetaClass newMc) { final ClassInfo info = ClassInfo.getClassInfo(theClass); MetaClass mc = null; info.lock(); try { mc = info.getStrongMetaClass(); info.setStrongMetaClass(newMc); } finally { info.unlock(); } if ((oldMc == null && mc != newMc) || (oldMc != null && mc != newMc && mc != oldMc)) { fireConstantMetaClassUpdate(null, theClass, mc, newMc); } } public void removeMetaClass(Class theClass) { setMetaClass(theClass, null, null); } /** * Registers a new MetaClass in the registry to customize the type * * @param theClass * @param theMetaClass */ public void setMetaClass(Class theClass, MetaClass theMetaClass) { setMetaClass(theClass,null,theMetaClass); } public void setMetaClass(Object obj, MetaClass theMetaClass) { Class theClass = obj.getClass (); final ClassInfo info = ClassInfo.getClassInfo(theClass); MetaClass oldMC = null; info.lock(); try { oldMC = info.getPerInstanceMetaClass(obj); info.setPerInstanceMetaClass(obj, theMetaClass); } finally { info.unlock(); } fireConstantMetaClassUpdate(obj, theClass, oldMC, theMetaClass); } public boolean useAccessible() { return useAccessible; } // the following is experimental code, not intended for stable use yet private volatile MetaClassCreationHandle metaClassCreationHandle = new MetaClassCreationHandle(); /** * Gets a handle internally used to create MetaClass implementations * WARNING: experimental code, likely to change soon * @return the handle */ public MetaClassCreationHandle getMetaClassCreationHandler() { return metaClassCreationHandle; } /** * Sets a handle internally used to create MetaClass implementations. * When replacing the handle with a custom version, you should * reuse the old handle to keep custom logic and to use the * default logic as fall back. * WARNING: experimental code, likely to change soon * @param handle the handle */ public void setMetaClassCreationHandle(MetaClassCreationHandle handle) { if(handle == null) throw new IllegalArgumentException("Cannot set MetaClassCreationHandle to null value!"); ClassInfo.clearModifiedExpandos(); handle.setDisableCustomMetaClassLookup(metaClassCreationHandle.isDisableCustomMetaClassLookup()); metaClassCreationHandle = handle; } /** * Adds a listener for constant meta classes. * @param listener the listener */ public void addMetaClassRegistryChangeEventListener(MetaClassRegistryChangeEventListener listener) { synchronized (changeListenerList) { changeListenerList.add(listener); } } /** * Adds a listener for constant meta classes. This listener cannot be removed! * @param listener the listener */ public void addNonRemovableMetaClassRegistryChangeEventListener(MetaClassRegistryChangeEventListener listener) { synchronized (changeListenerList) { nonRemoveableChangeListenerList.add(listener); } } /** * Removes a constant meta class listener. * @param listener the listener */ public void removeMetaClassRegistryChangeEventListener(MetaClassRegistryChangeEventListener listener) { synchronized (changeListenerList) { changeListenerList.remove(listener); } } /** * Causes the execution of all registered listeners. This method is used mostly * internal to kick of the listener notification. It can also be used by subclasses * to achieve the same. * * @param obj object instance if the MetaClass change is on a per-instance metaclass (or null if global) * @param c the class * @param oldMC the old MetaClass * @param newMc the new MetaClass */ protected void fireConstantMetaClassUpdate(Object obj, Class c, final MetaClass oldMC, MetaClass newMc) { MetaClassRegistryChangeEventListener[] listener = getMetaClassRegistryChangeEventListeners(); MetaClassRegistryChangeEvent cmcu = new MetaClassRegistryChangeEvent(this, obj, c, oldMC, newMc); for (int i = 0; i<listener.length; i++) { listener[i].updateConstantMetaClass(cmcu); } } /** * Gets an array of of all registered ConstantMetaClassListener instances. */ public MetaClassRegistryChangeEventListener[] getMetaClassRegistryChangeEventListeners() { synchronized (changeListenerList) { ArrayList<MetaClassRegistryChangeEventListener> ret = new ArrayList(changeListenerList.size()+nonRemoveableChangeListenerList.size()); ret.addAll(nonRemoveableChangeListenerList); ret.addAll(changeListenerList); return (MetaClassRegistryChangeEventListener[]) ret.toArray(new MetaClassRegistryChangeEventListener[ret.size()]); } } /** * Singleton of MetaClassRegistry. * * @param includeExtension * @return the registry */ public static MetaClassRegistry getInstance(int includeExtension) { if (includeExtension != DONT_LOAD_DEFAULT) { if (instanceInclude == null) { instanceInclude = new MetaClassRegistryImpl(); } return instanceInclude; } else { if (instanceExclude == null) { instanceExclude = new MetaClassRegistryImpl(DONT_LOAD_DEFAULT); } return instanceExclude; } } public FastArray getInstanceMethods() { return instanceMethods; } public FastArray getStaticMethods() { return staticMethods; } /** * Returns an iterator to iterate over all constant meta classes. * This iterator can be seen as making a snapshot of the current state * of the registry. The snapshot will include all meta classes that has * been used unless they are already collected. Collected meta classes * will be skipped automatically, so you can expect that each element * of the iteration is not null. Calling this method is thread safe, the * usage of the iterator is not. * * @return the iterator. */ public Iterator iterator() { final MetaClass[] refs; synchronized (metaClassInfo) { refs = (MetaClass[]) metaClassInfo.toArray(new MetaClass[0]); } return new Iterator() { // index in the ref array private int index = 0; // the current meta class private MetaClass currentMeta; // used to ensure that hasNext has been called private boolean hasNextCalled = false; // the cached hasNext call value private boolean hasNext = false; public boolean hasNext() { if (hasNextCalled) return hasNext; hasNextCalled = true; if(index < refs.length) { hasNext = true; currentMeta = refs[index]; index++; } else { hasNext = false; } return hasNext; } private void ensureNext() { // we ensure that hasNext has been called before // next is called hasNext(); hasNextCalled = false; } public Object next() { ensureNext(); return currentMeta; } public void remove() { ensureNext(); setMetaClass(currentMeta.getTheClass(), currentMeta, null); currentMeta = null; } }; } private class DefaultModuleListener implements ExtensionModuleScanner.ExtensionModuleListener { private final Map<CachedClass, List<MetaMethod>> map; public DefaultModuleListener(final Map<CachedClass, List<MetaMethod>> map) { this.map = map; } public void onModule(final ExtensionModule module) { if (moduleRegistry.hasModule(module.getName())) { ExtensionModule loadedModule = moduleRegistry.getModule(module.getName()); if (loadedModule.getVersion().equals(module.getVersion())) { // already registered return; } else { throw new GroovyRuntimeException("Conflicting module versions. Module ["+module.getName()+" is loaded in version "+ loadedModule.getVersion()+" and you are trying to load version "+module.getVersion()); } } moduleRegistry.addModule(module); // register MetaMethods List<MetaMethod> metaMethods = module.getMetaMethods(); for (MetaMethod metaMethod : metaMethods) { CachedClass cachedClass = metaMethod.getDeclaringClass(); List<MetaMethod> methods = map.get(cachedClass); if (methods==null) { methods = new ArrayList<MetaMethod>(4); map.put(cachedClass, methods); } methods.add(metaMethod); if (metaMethod.isStatic()) { staticMethods.add(metaMethod); } else { instanceMethods.add(metaMethod); } } } } }
/* * 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.jmeterplugins.protocol.http.control.gui; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import kg.apc.jmeter.JMeterPluginsUtils; import org.apache.jmeter.control.gui.LogicControllerGui; import org.apache.jmeter.gui.JMeterGUIComponent; import org.apache.jmeter.gui.UnsharedComponent; import org.apache.jmeter.gui.util.HorizontalPanel; import org.apache.jmeter.gui.util.MenuFactory; import org.apache.jmeter.testelement.TestElement; import org.apache.jmeter.util.JMeterUtils; import org.apache.jorphan.logging.LoggingManager; import org.apache.log.Logger; import org.jmeterplugins.protocol.http.control.HttpSimpleTableControl; public class HttpSimpleTableControlGui extends LogicControllerGui implements JMeterGUIComponent, ActionListener, UnsharedComponent { private static final long serialVersionUID = 240L; private static final Logger log = LoggingManager.getLoggerForClass(); public static final String WIKIPAGE = "HttpSimpleTableServer"; private JTextField portField; private JTextField datasetDirectoryField; private JCheckBox timestampChkBox; private JButton stop, start; private static final String ACTION_STOP = "stop"; private static final String ACTION_START = "start"; private HttpSimpleTableControl simpleTableController; public HttpSimpleTableControlGui() { super(); log.debug("Creating HttpSimpleTableControlGui"); init(); } @Override public TestElement createTestElement() { simpleTableController = new HttpSimpleTableControl(); log.debug("creating/configuring model = " + simpleTableController); modifyTestElement(simpleTableController); return simpleTableController; } /** * Modifies a given TestElement to mirror the data in the gui components. * * @see org.apache.jmeter.gui.JMeterGUIComponent#modifyTestElement(TestElement) */ @Override public void modifyTestElement(TestElement el) { configureTestElement(el); if (el instanceof HttpSimpleTableControl) { simpleTableController = (HttpSimpleTableControl) el; if (portField.getText().isEmpty()) { simpleTableController .setPort(HttpSimpleTableControl.DEFAULT_PORT_S); } else { simpleTableController.setPort(portField.getText()); } if (datasetDirectoryField.getText().isEmpty()) { simpleTableController .setDataDir(HttpSimpleTableControl.DEFAULT_DATA_DIR); } else { simpleTableController.setDataDir(datasetDirectoryField .getText()); } simpleTableController.setTimestamp(timestampChkBox.isSelected()); } } public String getLabelResource() { return this.getClass().getSimpleName(); } @Override public String getStaticLabel() { return JMeterPluginsUtils.prefixLabel("HTTP Simple Table Server"); } @Override public Collection<String> getMenuCategories() { return Arrays.asList(new String[] { MenuFactory.NON_TEST_ELEMENTS }); } @Override public void configure(TestElement element) { log.debug("Configuring gui with " + element); super.configure(element); simpleTableController = (HttpSimpleTableControl) element; portField.setText(simpleTableController.getPortString()); datasetDirectoryField.setText(simpleTableController.getDataDir()); timestampChkBox.setSelected(simpleTableController.getTimestamp()); repaint(); } @Override public void actionPerformed(ActionEvent action) { String command = action.getActionCommand(); Exception except = null; if (command.equals(ACTION_STOP)) { simpleTableController.stopHttpSimpleTable(); stop.setEnabled(false); start.setEnabled(true); } else if (command.equals(ACTION_START)) { modifyTestElement(simpleTableController); try { simpleTableController.startHttpSimpleTable(); } catch (IOException e) { e.printStackTrace(); except = e; } if (null == except) { start.setEnabled(false); stop.setEnabled(true); } } } private void init() { setLayout(new BorderLayout(0, 5)); setBorder(makeBorder()); add(JMeterPluginsUtils.addHelpLinkToPanel(makeTitlePanel(), WIKIPAGE), BorderLayout.NORTH); JPanel mainPanel = new JPanel(new BorderLayout()); Box myBox = Box.createVerticalBox(); myBox.add(createPortPanel()); mainPanel.add(myBox, BorderLayout.NORTH); mainPanel.add(createControls(), BorderLayout.CENTER); add(mainPanel, BorderLayout.CENTER); } private JPanel createControls() { start = new JButton(JMeterUtils.getResString("start")); start.addActionListener(this); start.setActionCommand(ACTION_START); start.setEnabled(true); stop = new JButton(JMeterUtils.getResString("stop")); stop.addActionListener(this); stop.setActionCommand(ACTION_STOP); stop.setEnabled(false); JPanel panel = new JPanel(); panel.add(start); panel.add(stop); return panel; } private JPanel createPortPanel() { portField = new JTextField(HttpSimpleTableControl.DEFAULT_PORT_S, 8); portField.setName(HttpSimpleTableControl.PORT); JLabel label = new JLabel(JMeterUtils.getResString("port")); label.setLabelFor(portField); datasetDirectoryField = new JTextField( HttpSimpleTableControl.DEFAULT_DATA_DIR, 8); datasetDirectoryField.setName(HttpSimpleTableControl.DATA_DIR); JLabel ddLabel = new JLabel("Dataset directory:"); ddLabel.setLabelFor(datasetDirectoryField); timestampChkBox = new JCheckBox(); timestampChkBox.setSelected(HttpSimpleTableControl.DEFAULT_TIMESTAMP); timestampChkBox.setName(HttpSimpleTableControl.TIMESTAMP); JLabel tsLabel = new JLabel("Timestamp:"); tsLabel.setLabelFor(timestampChkBox); HorizontalPanel panel = new HorizontalPanel(); panel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), "Settings")); panel.add(label); panel.add(portField); panel.add(ddLabel); panel.add(datasetDirectoryField); panel.add(tsLabel); panel.add(timestampChkBox); panel.add(Box.createHorizontalStrut(10)); return panel; } @Override public void clearGui() { super.clearGui(); portField.setText(HttpSimpleTableControl.DEFAULT_PORT_S); datasetDirectoryField.setText(HttpSimpleTableControl.DEFAULT_DATA_DIR); timestampChkBox.setSelected(HttpSimpleTableControl.DEFAULT_TIMESTAMP); } }
/* * 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 aria.apache.commons.net.util; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A class that performs some subnet calculations given a network address and a subnet mask. * * @see "http://www.faqs.org/rfcs/rfc1519.html" * @since 2.0 */ public class SubnetUtils { private static final String IP_ADDRESS = "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})"; private static final String SLASH_FORMAT = IP_ADDRESS + "/(\\d{1,3})"; private static final Pattern addressPattern = Pattern.compile(IP_ADDRESS); private static final Pattern cidrPattern = Pattern.compile(SLASH_FORMAT); private static final int NBITS = 32; private int netmask = 0; private int address = 0; private int network = 0; private int broadcast = 0; /** Whether the broadcast/network address are included in host count */ private boolean inclusiveHostCount = false; /** * Constructor that takes a CIDR-notation string, e.g. "192.168.0.1/16" * * @param cidrNotation A CIDR-notation string, e.g. "192.168.0.1/16" * @throws IllegalArgumentException if the parameter is invalid, * i.e. does not match n.n.n.n/m where n=1-3 decimal digits, m = 1-3 decimal digits in range 1-32 */ public SubnetUtils(String cidrNotation) { calculate(cidrNotation); } /** * Constructor that takes a dotted decimal address and a dotted decimal mask. * * @param address An IP address, e.g. "192.168.0.1" * @param mask A dotted decimal netmask e.g. "255.255.0.0" * @throws IllegalArgumentException if the address or mask is invalid, * i.e. does not match n.n.n.n where n=1-3 decimal digits and the mask is not all zeros */ public SubnetUtils(String address, String mask) { calculate(toCidrNotation(address, mask)); } /** * Returns <code>true</code> if the return value of {@link SubnetInfo#getAddressCount()} * includes the network and broadcast addresses. * * @return true if the hostcount includes the network and broadcast addresses * @since 2.2 */ public boolean isInclusiveHostCount() { return inclusiveHostCount; } /** * Set to <code>true</code> if you want the return value of {@link SubnetInfo#getAddressCount()} * to include the network and broadcast addresses. * * @param inclusiveHostCount true if network and broadcast addresses are to be included * @since 2.2 */ public void setInclusiveHostCount(boolean inclusiveHostCount) { this.inclusiveHostCount = inclusiveHostCount; } /** * Convenience container for subnet summary information. */ public final class SubnetInfo { /* Mask to convert unsigned int to a long (i.e. keep 32 bits) */ private static final long UNSIGNED_INT_MASK = 0x0FFFFFFFFL; private SubnetInfo() { } private int netmask() { return netmask; } private int network() { return network; } private int address() { return address; } private int broadcast() { return broadcast; } // long versions of the values (as unsigned int) which are more suitable for range checking private long networkLong() { return network & UNSIGNED_INT_MASK; } private long broadcastLong() { return broadcast & UNSIGNED_INT_MASK; } private int low() { return (isInclusiveHostCount() ? network() : broadcastLong() - networkLong() > 1 ? network() + 1 : 0); } private int high() { return (isInclusiveHostCount() ? broadcast() : broadcastLong() - networkLong() > 1 ? broadcast() - 1 : 0); } /** * Returns true if the parameter <code>address</code> is in the * range of usable endpoint addresses for this subnet. This excludes the * network and broadcast adresses. * * @param address A dot-delimited IPv4 address, e.g. "192.168.0.1" * @return True if in range, false otherwise */ public boolean isInRange(String address) { return isInRange(toInteger(address)); } /** * @param address the address to check * @return true if it is in range * @since 3.4 (made public) */ public boolean isInRange(int address) { long addLong = address & UNSIGNED_INT_MASK; long lowLong = low() & UNSIGNED_INT_MASK; long highLong = high() & UNSIGNED_INT_MASK; return addLong >= lowLong && addLong <= highLong; } public String getBroadcastAddress() { return format(toArray(broadcast())); } public String getNetworkAddress() { return format(toArray(network())); } public String getNetmask() { return format(toArray(netmask())); } public String getAddress() { return format(toArray(address())); } /** * Return the low address as a dotted IP address. * Will be zero for CIDR/31 and CIDR/32 if the inclusive flag is false. * * @return the IP address in dotted format, may be "0.0.0.0" if there is no valid address */ public String getLowAddress() { return format(toArray(low())); } /** * Return the high address as a dotted IP address. * Will be zero for CIDR/31 and CIDR/32 if the inclusive flag is false. * * @return the IP address in dotted format, may be "0.0.0.0" if there is no valid address */ public String getHighAddress() { return format(toArray(high())); } /** * Get the count of available addresses. * Will be zero for CIDR/31 and CIDR/32 if the inclusive flag is false. * * @return the count of addresses, may be zero. * @throws RuntimeException if the correct count is greater than {@code Integer.MAX_VALUE} * @deprecated (3.4) use {@link #getAddressCountLong()} instead */ @Deprecated public int getAddressCount() { long countLong = getAddressCountLong(); if (countLong > Integer.MAX_VALUE) { throw new RuntimeException("Count is larger than an integer: " + countLong); } // N.B. cannot be negative return (int) countLong; } /** * Get the count of available addresses. * Will be zero for CIDR/31 and CIDR/32 if the inclusive flag is false. * * @return the count of addresses, may be zero. * @since 3.4 */ public long getAddressCountLong() { long b = broadcastLong(); long n = networkLong(); long count = b - n + (isInclusiveHostCount() ? 1 : -1); return count < 0 ? 0 : count; } public int asInteger(String address) { return toInteger(address); } public String getCidrSignature() { return toCidrNotation(format(toArray(address())), format(toArray(netmask()))); } public String[] getAllAddresses() { int ct = getAddressCount(); String[] addresses = new String[ct]; if (ct == 0) { return addresses; } for (int add = low(), j = 0; add <= high(); ++add, ++j) { addresses[j] = format(toArray(add)); } return addresses; } /** * {@inheritDoc} * * @since 2.2 */ @Override public String toString() { final StringBuilder buf = new StringBuilder(); buf.append("CIDR Signature:\t[") .append(getCidrSignature()) .append("]") .append(" Netmask: [") .append(getNetmask()) .append("]\n") .append("Network:\t[") .append(getNetworkAddress()) .append("]\n") .append("Broadcast:\t[") .append(getBroadcastAddress()) .append("]\n") .append("First Address:\t[") .append(getLowAddress()) .append("]\n") .append("Last Address:\t[") .append(getHighAddress()) .append("]\n") .append("# Addresses:\t[") .append(getAddressCount()) .append("]\n"); return buf.toString(); } } /** * Return a {@link SubnetInfo} instance that contains subnet-specific statistics * * @return new instance */ public final SubnetInfo getInfo() { return new SubnetInfo(); } /* * Initialize the internal fields from the supplied CIDR mask */ private void calculate(String mask) { Matcher matcher = cidrPattern.matcher(mask); if (matcher.matches()) { address = matchAddress(matcher); /* Create a binary netmask from the number of bits specification /x */ int cidrPart = rangeCheck(Integer.parseInt(matcher.group(5)), 0, NBITS); for (int j = 0; j < cidrPart; ++j) { netmask |= (1 << 31 - j); } /* Calculate base network address */ network = (address & netmask); /* Calculate broadcast address */ broadcast = network | ~(netmask); } else { throw new IllegalArgumentException("Could not parse [" + mask + "]"); } } /* * Convert a dotted decimal format address to a packed integer format */ private int toInteger(String address) { Matcher matcher = addressPattern.matcher(address); if (matcher.matches()) { return matchAddress(matcher); } else { throw new IllegalArgumentException("Could not parse [" + address + "]"); } } /* * Convenience method to extract the components of a dotted decimal address and * pack into an integer using a regex match */ private int matchAddress(Matcher matcher) { int addr = 0; for (int i = 1; i <= 4; ++i) { int n = (rangeCheck(Integer.parseInt(matcher.group(i)), 0, 255)); addr |= ((n & 0xff) << 8 * (4 - i)); } return addr; } /* * Convert a packed integer address into a 4-element array */ private int[] toArray(int val) { int ret[] = new int[4]; for (int j = 3; j >= 0; --j) { ret[j] |= ((val >>> 8 * (3 - j)) & (0xff)); } return ret; } /* * Convert a 4-element array into dotted decimal format */ private String format(int[] octets) { StringBuilder str = new StringBuilder(); for (int i = 0; i < octets.length; ++i) { str.append(octets[i]); if (i != octets.length - 1) { str.append("."); } } return str.toString(); } /* * Convenience function to check integer boundaries. * Checks if a value x is in the range [begin,end]. * Returns x if it is in range, throws an exception otherwise. */ private int rangeCheck(int value, int begin, int end) { if (value >= begin && value <= end) { // (begin,end] return value; } throw new IllegalArgumentException( "Value [" + value + "] not in range [" + begin + "," + end + "]"); } /* * Count the number of 1-bits in a 32-bit integer using a divide-and-conquer strategy * see Hacker's Delight section 5.1 */ int pop(int x) { x = x - ((x >>> 1) & 0x55555555); x = (x & 0x33333333) + ((x >>> 2) & 0x33333333); x = (x + (x >>> 4)) & 0x0F0F0F0F; x = x + (x >>> 8); x = x + (x >>> 16); return x & 0x0000003F; } /* Convert two dotted decimal addresses to a single xxx.xxx.xxx.xxx/yy format * by counting the 1-bit population in the mask address. (It may be better to count * NBITS-#trailing zeroes for this case) */ private String toCidrNotation(String addr, String mask) { return addr + "/" + pop(toInteger(mask)); } }
/* * 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.ambari.server.state; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlElements; import org.apache.commons.collections.CollectionUtils; /** * Represents stack component dependency information. */ public class DependencyInfo { /** * The name of the component which is the dependency. * Specified in the form serviceName/componentName. */ private String name; /** * The scope of the dependency. Either "cluster" or "host". */ private String scope; /** * Service name of the dependency. */ private String serviceName; /** * Component name of the dependency. */ private String componentName; /** * Auto-deployment information for the dependency. * If auto-deployment is enabled for the dependency, the dependency is * automatically deployed if it is not specified in the provided topology. */ @XmlElement(name="auto-deploy") private AutoDeployInfo m_autoDeploy; /** * Conditions for Component dependency to other components. */ private List<DependencyConditionInfo> dependencyConditions = new ArrayList<>(); /** * Setter for name property. * * @param name the name of the component which is the dependency * in the form serviceName/componentName */ public void setName(String name) { if (! name.contains("/")) { throw new IllegalArgumentException("Invalid dependency name specified in stack. " + "Expected form is: serviceName/componentName"); } this.name = name; int idx = name.indexOf('/'); serviceName = name.substring(0, idx); componentName = name.substring(idx + 1); } /** * Getter for name property. * * @return the name of the component which is the dependency * in the form serviceName/componentName */ public String getName() { return name; } /** * Setter for scope property. * * @param scope the scope of the dependency. Either "cluster" or "host". */ public void setScope(String scope) { this.scope = scope; } /** * Getter for scope property. * * @return either "cluster" or "host". */ public String getScope() { return scope; } /** * Setter for auto-deploy property. * * @param autoDeploy auto-deploy information */ public void setAutoDeploy(AutoDeployInfo autoDeploy) { m_autoDeploy = autoDeploy; } /** * Getter for the auto-deploy property. * * @return auto-deploy information */ public AutoDeployInfo getAutoDeploy() { return m_autoDeploy; } /** * Get the component name of the dependency. * * @return dependency component name */ public String getComponentName() { return componentName; } /** * Get the service name associated with the dependency component. * * @return associated service name */ public String getServiceName() { return serviceName; } /** * Get the dependencyConditions list * * @return dependencyConditions */ @XmlElementWrapper(name="conditions") @XmlElements(@XmlElement(name="condition")) public List<DependencyConditionInfo> getDependencyConditions() { return dependencyConditions; } /** * Set dependencyConditions * * @param dependencyConditions */ public void setDependencyConditions(List<DependencyConditionInfo> dependencyConditions) { this.dependencyConditions = dependencyConditions; } /** * Confirms if dependency have any condition or not * @return true if dependencies are based on a condition */ public boolean hasDependencyConditions(){ return !CollectionUtils.isEmpty(dependencyConditions); } @Override public String toString() { return "DependencyInfo[name=" + getName() + ", scope=" + getScope() + ", auto-deploy=" + m_autoDeploy.isEnabled() + "]"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DependencyInfo that = (DependencyInfo) o; if (componentName != null ? !componentName.equals(that.componentName) : that.componentName != null) return false; if (m_autoDeploy != null ? !m_autoDeploy.equals(that.m_autoDeploy) : that.m_autoDeploy != null) return false; if (name != null ? !name.equals(that.name) : that.name != null) return false; if (scope != null ? !scope.equals(that.scope) : that.scope != null) return false; if (serviceName != null ? !serviceName.equals(that.serviceName) : that.serviceName != null) return false; return true; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + (scope != null ? scope.hashCode() : 0); result = 31 * result + (serviceName != null ? serviceName.hashCode() : 0); result = 31 * result + (componentName != null ? componentName.hashCode() : 0); result = 31 * result + (m_autoDeploy != null ? m_autoDeploy.hashCode() : 0); return result; } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.action.bench; import org.apache.lucene.util.PriorityQueue; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.Client; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.Loggers; import com.google.common.collect.UnmodifiableIterator; import java.util.*; import java.util.concurrent.*; /** * Handles execution, listing, and aborting of benchmarks */ public class BenchmarkExecutor { private static final ESLogger logger = Loggers.getLogger(BenchmarkExecutor.class); private final Client client; private String nodeName; private final ClusterService clusterService; private volatile ImmutableOpenMap<String, BenchmarkState> activeBenchmarks = ImmutableOpenMap.of(); private final Object lock = new Object(); public BenchmarkExecutor(Client client, ClusterService clusterService) { this.client = client; this.clusterService = clusterService; } private static class BenchmarkState { final String id; final StoppableSemaphore semaphore; final BenchmarkResponse response; BenchmarkState(BenchmarkRequest request, BenchmarkResponse response, StoppableSemaphore semaphore) { this.id = request.benchmarkName(); this.response = response; this.semaphore = semaphore; } } /** * Aborts a benchmark with the given id * * @param benchmarkName The benchmark to abort * @return Abort response */ public AbortBenchmarkNodeResponse abortBenchmark(String benchmarkName) { BenchmarkState state = activeBenchmarks.get(benchmarkName); if (state == null) { throw new BenchmarkMissingException("Benchmark [" + benchmarkName + "] not found on [" + nodeName() + "]"); } state.semaphore.stop(); activeBenchmarks = ImmutableOpenMap.builder(activeBenchmarks).fRemove(benchmarkName).build(); logger.debug("Aborted benchmark [{}] on [{}]", benchmarkName, nodeName()); return new AbortBenchmarkNodeResponse(benchmarkName, nodeName()); } /** * Reports status of all active benchmarks * * @return Benchmark status response */ public BenchmarkStatusNodeResponse benchmarkStatus() { BenchmarkStatusNodeResponse response = new BenchmarkStatusNodeResponse(); final ImmutableOpenMap<String, BenchmarkState> activeBenchmarks = this.activeBenchmarks; UnmodifiableIterator<String> iter = activeBenchmarks.keysIt(); while (iter.hasNext()) { String id = iter.next(); BenchmarkState state = activeBenchmarks.get(id); response.addBenchResponse(state.response); } logger.debug("Reporting [{}] active benchmarks on [{}]", response.activeBenchmarks(), nodeName()); return response; } /** * Submits a search benchmark for execution * * @param request A benchmark request * @return Summary response of executed benchmark * @throws ElasticsearchException */ public BenchmarkResponse benchmark(BenchmarkRequest request) throws ElasticsearchException { final StoppableSemaphore semaphore = new StoppableSemaphore(1); final Map<String, CompetitionResult> competitionResults = new HashMap<String, CompetitionResult>(); final BenchmarkResponse benchmarkResponse = new BenchmarkResponse(request.benchmarkName(), competitionResults); synchronized (lock) { if (activeBenchmarks.containsKey(request.benchmarkName())) { throw new ElasticsearchException("Benchmark [" + request.benchmarkName() + "] is already running on [" + nodeName() + "]"); } activeBenchmarks = ImmutableOpenMap.builder(activeBenchmarks).fPut( request.benchmarkName(), new BenchmarkState(request, benchmarkResponse, semaphore)).build(); } try { for (BenchmarkCompetitor competitor : request.competitors()) { final BenchmarkSettings settings = competitor.settings(); final int iterations = settings.iterations(); logger.debug("Executing [iterations: {}] [multiplier: {}] for [{}] on [{}]", iterations, settings.multiplier(), request.benchmarkName(), nodeName()); final List<CompetitionIteration> competitionIterations = new ArrayList<>(iterations); final CompetitionResult competitionResult = new CompetitionResult(competitor.name(), settings.concurrency(), settings.multiplier(), request.percentiles()); final CompetitionNodeResult competitionNodeResult = new CompetitionNodeResult(competitor.name(), nodeName(), iterations, competitionIterations); competitionResult.addCompetitionNodeResult(competitionNodeResult); benchmarkResponse.competitionResults.put(competitor.name(), competitionResult); final List<SearchRequest> searchRequests = competitor.settings().searchRequests(); if (settings.warmup()) { final long beforeWarmup = System.nanoTime(); final List<String> warmUpErrors = warmUp(competitor, searchRequests, semaphore); final long afterWarmup = System.nanoTime(); competitionNodeResult.warmUpTime(TimeUnit.MILLISECONDS.convert(afterWarmup - beforeWarmup, TimeUnit.NANOSECONDS)); if (!warmUpErrors.isEmpty()) { throw new BenchmarkExecutionException("Failed to execute warmup phase", warmUpErrors); } } final int numMeasurements = settings.multiplier() * searchRequests.size(); final long[] timeBuckets = new long[numMeasurements]; final long[] docBuckets = new long[numMeasurements]; for (int i = 0; i < iterations; i++) { if (settings.allowCacheClearing() && settings.clearCaches() != null) { try { client.admin().indices().clearCache(settings.clearCaches()).get(); } catch (ExecutionException e) { throw new BenchmarkExecutionException("Failed to clear caches", e); } } // Run the iteration CompetitionIteration ci = runIteration(competitor, searchRequests, timeBuckets, docBuckets, semaphore); ci.percentiles(request.percentiles()); competitionIterations.add(ci); competitionNodeResult.incrementCompletedIterations(); } competitionNodeResult.totalExecutedQueries(settings.multiplier() * searchRequests.size() * iterations); } benchmarkResponse.state(BenchmarkResponse.State.COMPLETE); } catch (BenchmarkExecutionException e) { benchmarkResponse.state(BenchmarkResponse.State.FAILED); benchmarkResponse.errors(e.errorMessages().toArray(new String[e.errorMessages().size()])); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); benchmarkResponse.state(BenchmarkResponse.State.ABORTED); } catch (Throwable ex) { logger.debug("Unexpected exception during benchmark", ex); benchmarkResponse.state(BenchmarkResponse.State.FAILED); benchmarkResponse.errors(ex.getMessage()); } finally { synchronized (lock) { semaphore.stop(); activeBenchmarks = ImmutableOpenMap.builder(activeBenchmarks).fRemove(request.benchmarkName()).build(); } } return benchmarkResponse; } private List<String> warmUp(BenchmarkCompetitor competitor, List<SearchRequest> searchRequests, StoppableSemaphore stoppableSemaphore) throws InterruptedException { final StoppableSemaphore semaphore = stoppableSemaphore.reset(competitor.settings().concurrency()); final CountDownLatch totalCount = new CountDownLatch(searchRequests.size()); final CopyOnWriteArrayList<String> errorMessages = new CopyOnWriteArrayList<>(); for (SearchRequest searchRequest : searchRequests) { semaphore.acquire(); client.search(searchRequest, new BoundsManagingActionListener<SearchResponse>(semaphore, totalCount, errorMessages) { } ); } totalCount.await(); return errorMessages; } private CompetitionIteration runIteration(BenchmarkCompetitor competitor, List<SearchRequest> searchRequests, final long[] timeBuckets, final long[] docBuckets, StoppableSemaphore stoppableSemaphore) throws InterruptedException { assert timeBuckets.length == competitor.settings().multiplier() * searchRequests.size(); assert docBuckets.length == competitor.settings().multiplier() * searchRequests.size(); final StoppableSemaphore semaphore = stoppableSemaphore.reset(competitor.settings().concurrency()); Arrays.fill(timeBuckets, -1); // wipe CPU cache ;) Arrays.fill(docBuckets, -1); // wipe CPU cache ;) int id = 0; final CountDownLatch totalCount = new CountDownLatch(timeBuckets.length); final CopyOnWriteArrayList<String> errorMessages = new CopyOnWriteArrayList<>(); final long beforeRun = System.nanoTime(); for (int i = 0; i < competitor.settings().multiplier(); i++) { for (SearchRequest searchRequest : searchRequests) { StatisticCollectionActionListener statsListener = new StatisticCollectionActionListener(semaphore, timeBuckets, docBuckets, id++, totalCount, errorMessages); semaphore.acquire(); client.search(searchRequest, statsListener); } } totalCount.await(); assert id == timeBuckets.length; final long afterRun = System.nanoTime(); if (!errorMessages.isEmpty()) { throw new BenchmarkExecutionException("Too many execution failures", errorMessages); } final long totalTime = TimeUnit.MILLISECONDS.convert(afterRun - beforeRun, TimeUnit.NANOSECONDS); CompetitionIterationData iterationData = new CompetitionIterationData(timeBuckets); long sumDocs = new CompetitionIterationData(docBuckets).sum(); // Don't track slowest request if there is only one request as that is redundant CompetitionIteration.SlowRequest[] topN = null; if ((competitor.settings().numSlowest() > 0) && (searchRequests.size() > 1)) { topN = getTopN(timeBuckets, searchRequests, competitor.settings().multiplier(), competitor.settings().numSlowest()); } CompetitionIteration round = new CompetitionIteration(topN, totalTime, timeBuckets.length, sumDocs, iterationData); return round; } private CompetitionIteration.SlowRequest[] getTopN(long[] buckets, List<SearchRequest> requests, int multiplier, int topN) { final int numRequests = requests.size(); // collect the top N final PriorityQueue<IndexAndTime> topNQueue = new PriorityQueue<IndexAndTime>(topN) { @Override protected boolean lessThan(IndexAndTime a, IndexAndTime b) { return a.avgTime < b.avgTime; } }; assert multiplier > 0; for (int i = 0; i < numRequests; i++) { long sum = 0; long max = Long.MIN_VALUE; for (int j = 0; j < multiplier; j++) { final int base = (numRequests * j); sum += buckets[i + base]; max = Math.max(buckets[i + base], max); } final long avg = sum / multiplier; if (topNQueue.size() < topN) { topNQueue.add(new IndexAndTime(i, max, avg)); } else if (topNQueue.top().avgTime < max) { topNQueue.top().update(i, max, avg); topNQueue.updateTop(); } } final CompetitionIteration.SlowRequest[] slowRequests = new CompetitionIteration.SlowRequest[topNQueue.size()]; int i = topNQueue.size() - 1; while (topNQueue.size() > 0) { IndexAndTime pop = topNQueue.pop(); CompetitionIteration.SlowRequest slow = new CompetitionIteration.SlowRequest(pop.avgTime, pop.maxTime, requests.get(pop.index)); slowRequests[i--] = slow; } return slowRequests; } private static class IndexAndTime { int index; long maxTime; long avgTime; public IndexAndTime(int index, long maxTime, long avgTime) { this.index = index; this.maxTime = maxTime; this.avgTime = avgTime; } public void update(int index, long maxTime, long avgTime) { this.index = index; this.maxTime = maxTime; this.avgTime = avgTime; } } private static abstract class BoundsManagingActionListener<Response> implements ActionListener<Response> { private final StoppableSemaphore semaphore; private final CountDownLatch latch; private final CopyOnWriteArrayList<String> errorMessages; public BoundsManagingActionListener(StoppableSemaphore semaphore, CountDownLatch latch, CopyOnWriteArrayList<String> errorMessages) { this.semaphore = semaphore; this.latch = latch; this.errorMessages = errorMessages; } private void manage() { try { semaphore.release(); } finally { latch.countDown(); } } public void onResponse(Response response) { manage(); } public void onFailure(Throwable e) { manage(); if (errorMessages.size() < 5) { logger.error("Failed to execute benchmark [{}]", e.getMessage(), e); e = ExceptionsHelper.unwrapCause(e); errorMessages.add(e.getLocalizedMessage()); } } } private static class StatisticCollectionActionListener extends BoundsManagingActionListener<SearchResponse> { private final long[] timeBuckets; private final int bucketId; private final long[] docBuckets; public StatisticCollectionActionListener(StoppableSemaphore semaphore, long[] timeBuckets, long[] docs, int bucketId, CountDownLatch totalCount, CopyOnWriteArrayList<String> errorMessages) { super(semaphore, totalCount, errorMessages); this.bucketId = bucketId; this.timeBuckets = timeBuckets; this.docBuckets = docs; } @Override public void onResponse(SearchResponse searchResponse) { super.onResponse(searchResponse); timeBuckets[bucketId] = searchResponse.getTookInMillis(); if (searchResponse.getHits() != null) { docBuckets[bucketId] = searchResponse.getHits().getTotalHits(); } } @Override public void onFailure(Throwable e) { timeBuckets[bucketId] = -1; docBuckets[bucketId] = -1; super.onFailure(e); } } private final static class StoppableSemaphore { private Semaphore semaphore; private volatile boolean stopped = false; public StoppableSemaphore(int concurrency) { semaphore = new Semaphore(concurrency); } public StoppableSemaphore reset(int concurrency) { semaphore = new Semaphore(concurrency); return this; } public void acquire() throws InterruptedException { if (stopped) { throw new InterruptedException("Benchmark Interrupted"); } semaphore.acquire(); } public void release() { semaphore.release(); } public void stop() { stopped = true; } } private String nodeName() { if (nodeName == null) { nodeName = clusterService.localNode().name(); } return nodeName; } private final boolean assertBuckets(long[] buckets) { for (int i = 0; i < buckets.length; i++) { assert buckets[i] >= 0 : "Bucket value was negative: " + buckets[i] + " bucket id: " + i; } return true; } }
/* 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 com.unarin.cordova.beacon; import android.Manifest; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.content.pm.PackageManager; import android.os.AsyncTask; import android.os.Build; import android.os.Handler; import android.os.RemoteException; import android.util.Log; import org.altbeacon.beacon.Beacon; import org.altbeacon.beacon.BeaconConsumer; import org.altbeacon.beacon.BeaconManager; import org.altbeacon.beacon.BeaconParser; import org.altbeacon.beacon.BeaconTransmitter; import android.bluetooth.le.AdvertiseCallback; import android.bluetooth.le.AdvertiseSettings; import org.altbeacon.beacon.BleNotAvailableException; import org.altbeacon.beacon.Identifier; import org.altbeacon.beacon.MonitorNotifier; import org.altbeacon.beacon.RangeNotifier; import org.altbeacon.beacon.Region; import org.altbeacon.beacon.service.RunningAverageRssiFilter; import org.altbeacon.beacon.service.ArmaRssiFilter; import org.altbeacon.beacon.service.RangedBeacon; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.apache.cordova.PluginResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.InvalidKeyException; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public class LocationManager extends CordovaPlugin implements BeaconConsumer { public static final String TAG = "com.unarin.beacon"; private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1; private static final String FOREGROUND_BETWEEN_SCAN_PERIOD_NAME = "com.unarin.cordova.beacon.android.altbeacon.ForegroundBetweenScanPeriod"; private static final String FOREGROUND_SCAN_PERIOD_NAME = "com.unarin.cordova.beacon.android.altbeacon.ForegroundScanPeriod"; private static final int DEFAULT_FOREGROUND_BETWEEN_SCAN_PERIOD = 0; private static final String SAMPLE_EXPIRATION_MILLISECOND = "com.unarin.cordova.beacon.android.altbeacon.SampleExpirationMilliseconds"; private static final int DEFAULT_SAMPLE_EXPIRATION_MILLISECOND = 20000; private static final String ENABLE_ARMA_FILTER_NAME = "com.unarin.cordova.beacon.android.altbeacon.EnableArmaFilter"; private static final boolean DEFAULT_ENABLE_ARMA_FILTER = false; private static final String REQUEST_BT_PERMISSION_NAME = "com.unarin.cordova.beacon.android.altbeacon.RequestBtPermission"; private static final boolean DEFAULT_REQUEST_BT_PERMISSION = true; private static final int DEFAULT_FOREGROUND_SCAN_PERIOD = 1100; private static int CDV_LOCATION_MANAGER_DOM_DELEGATE_TIMEOUT = 30; private static final int BUILD_VERSION_CODES_M = 23; private BeaconTransmitter beaconTransmitter; private BeaconManager iBeaconManager; private BlockingQueue<Runnable> queue; private PausableThreadPoolExecutor threadPoolExecutor; private boolean debugEnabled = true; private IBeaconServiceNotifier beaconServiceNotifier; //listener for changes in state for system Bluetooth service private BroadcastReceiver broadcastReceiver; private BluetoothAdapter bluetoothAdapter; /** * Constructor. */ public LocationManager() { } /** * Sets the context of the Command. This can then be used to do things like * get file paths associated with the Activity. * * @param cordova The context of the main Activity. * @param webView The CordovaWebView Cordova is running in. */ public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); final Activity cordovaActivity = cordova.getActivity(); final int foregroundBetweenScanPeriod = this.preferences.getInteger( FOREGROUND_BETWEEN_SCAN_PERIOD_NAME, DEFAULT_FOREGROUND_BETWEEN_SCAN_PERIOD); final int foregroundScanPeriod = this.preferences.getInteger( FOREGROUND_SCAN_PERIOD_NAME, DEFAULT_FOREGROUND_SCAN_PERIOD); Log.i(TAG, "Determined config value FOREGROUND_SCAN_PERIOD: " + String.valueOf(foregroundScanPeriod)); iBeaconManager = BeaconManager.getInstanceForApplication(cordovaActivity); iBeaconManager.setForegroundBetweenScanPeriod(foregroundBetweenScanPeriod); iBeaconManager.setForegroundScanPeriod(foregroundScanPeriod); final int sampleExpirationMilliseconds = this.preferences.getInteger( SAMPLE_EXPIRATION_MILLISECOND, DEFAULT_SAMPLE_EXPIRATION_MILLISECOND); Log.i(TAG, "Determined config value SAMPLE_EXPIRATION_MILLISECOND: " + String.valueOf(sampleExpirationMilliseconds)); final boolean enableArmaFilter = this.preferences.getBoolean( ENABLE_ARMA_FILTER_NAME, DEFAULT_ENABLE_ARMA_FILTER); if(enableArmaFilter){ iBeaconManager.setRssiFilterImplClass(ArmaRssiFilter.class); } else{ iBeaconManager.setRssiFilterImplClass(RunningAverageRssiFilter.class); RunningAverageRssiFilter.setSampleExpirationMilliseconds(sampleExpirationMilliseconds); } RangedBeacon.setSampleExpirationMilliseconds(sampleExpirationMilliseconds); initBluetoothListener(); initEventQueue(); pauseEventPropagationToDom(); // Before the DOM is loaded we'll just keep collecting the events and fire them later. initLocationManager(); debugEnabled = true; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { initBluetoothAdapter(); } //TODO AddObserver when page loaded final boolean requestPermission = this.preferences.getBoolean( REQUEST_BT_PERMISSION_NAME, DEFAULT_REQUEST_BT_PERMISSION); if(requestPermission) tryToRequestMarshmallowLocationPermission(); } /** * The final call you receive before your activity is destroyed. */ @Override public void onDestroy() { iBeaconManager.unbind(this); if (broadcastReceiver != null) { cordova.getActivity().unregisterReceiver(broadcastReceiver); broadcastReceiver = null; } super.onDestroy(); } //////////////// PLUGIN ENTRY POINT ///////////////////////////// /** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArray of arguments for the plugin. * @param callbackContext The callback id used when calling back into JavaScript. * @return True if the action was valid, false if not. */ public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if (action.equals("onDomDelegateReady")) { onDomDelegateReady(callbackContext); } else if (action.equals("disableDebugNotifications")) { disableDebugNotifications(callbackContext); } else if (action.equals("enableDebugNotifications")) { enableDebugNotifications(callbackContext); } else if (action.equals("disableDebugLogs")) { disableDebugLogs(callbackContext); } else if (action.equals("enableDebugLogs")) { enableDebugLogs(callbackContext); } else if (action.equals("appendToDeviceLog")) { appendToDeviceLog(args.optString(0), callbackContext); } else if (action.equals("startMonitoringForRegion")) { startMonitoringForRegion(args.optJSONObject(0), callbackContext); } else if (action.equals("stopMonitoringForRegion")) { stopMonitoringForRegion(args.optJSONObject(0), callbackContext); } else if (action.equals("startRangingBeaconsInRegion")) { startRangingBeaconsInRegion(args.optJSONObject(0), callbackContext); } else if (action.equals("stopRangingBeaconsInRegion")) { stopRangingBeaconsInRegion(args.optJSONObject(0), callbackContext); } else if (action.equals("isRangingAvailable")) { isRangingAvailable(callbackContext); } else if (action.equals("getAuthorizationStatus")) { getAuthorizationStatus(callbackContext); } else if (action.equals("requestWhenInUseAuthorization")) { requestWhenInUseAuthorization(callbackContext); } else if (action.equals("requestAlwaysAuthorization")) { requestAlwaysAuthorization(callbackContext); } else if (action.equals("getMonitoredRegions")) { getMonitoredRegions(callbackContext); } else if (action.equals("getRangedRegions")) { getRangedRegions(callbackContext); } else if (action.equals("requestStateForRegion")) { requestStateForRegion(args.optJSONObject(0), callbackContext); } else if (action.equals("registerDelegateCallbackId")) { registerDelegateCallbackId(args.optJSONObject(0), callbackContext); } else if (action.equals("isMonitoringAvailableForClass")) { isMonitoringAvailableForClass(args.optJSONObject(0), callbackContext); } else if (action.equals("isAdvertisingAvailable")) { isAdvertisingAvailable(callbackContext); } else if (action.equals("isAdvertising")) { isAdvertising(callbackContext); } else if (action.equals("startAdvertising")) { startAdvertising(args, callbackContext); } else if (action.equals("stopAdvertising")) { stopAdvertising(callbackContext); } else if (action.equals("isBluetoothEnabled")) { isBluetoothEnabled(callbackContext); } else if (action.equals("enableBluetooth")) { enableBluetooth(callbackContext); } else if (action.equals("disableBluetooth")) { disableBluetooth(callbackContext); } else { return false; } return true; } ///////////////// SETUP AND VALIDATION ///////////////////////////////// private void initLocationManager() { iBeaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24")); iBeaconManager.bind(this); } private BeaconTransmitter createOrGetBeaconTransmitter() { if (this.beaconTransmitter == null) { final BeaconParser beaconParser = new BeaconParser() .setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"); this.beaconTransmitter = new BeaconTransmitter(getApplicationContext(), beaconParser); } return this.beaconTransmitter; } @TargetApi(BUILD_VERSION_CODES_M) private void tryToRequestMarshmallowLocationPermission() { if (Build.VERSION.SDK_INT < BUILD_VERSION_CODES_M) { Log.i(TAG, "tryToRequestMarshmallowLocationPermission() skipping because API code is " + "below criteria: " + String.valueOf(Build.VERSION.SDK_INT)); return; } final Activity activity = cordova.getActivity(); final Method checkSelfPermissionMethod = getCheckSelfPermissionMethod(); if (checkSelfPermissionMethod == null) { Log.e(TAG, "Could not obtain the method Activity.checkSelfPermission method. Will " + "not check for ACCESS_COARSE_LOCATION even though we seem to be on a " + "supported version of Android."); return; } try { final Integer permissionCheckResult = (Integer) checkSelfPermissionMethod.invoke( activity, Manifest.permission.ACCESS_COARSE_LOCATION); Log.i(TAG, "Permission check result for ACCESS_COARSE_LOCATION: " + String.valueOf(permissionCheckResult)); if (permissionCheckResult == PackageManager.PERMISSION_GRANTED) { Log.i(TAG, "Permission for ACCESS_COARSE_LOCATION has already been granted."); return; } final Method requestPermissionsMethod = getRequestPermissionsMethod(); if (requestPermissionsMethod == null) { Log.e(TAG, "Could not obtain the method Activity.requestPermissions. Will " + "not ask for ACCESS_COARSE_LOCATION even though we seem to be on a " + "supported version of Android."); return; } final AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle("This app needs location access"); builder.setMessage("Please grant location access so this app can detect beacons."); builder.setPositiveButton(android.R.string.ok, null); builder.setOnDismissListener(new DialogInterface.OnDismissListener() { @SuppressLint("NewApi") @Override public void onDismiss(final DialogInterface dialog) { try { requestPermissionsMethod.invoke(activity, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION ); } catch (IllegalAccessException e) { Log.e(TAG, "IllegalAccessException while requesting permission for " + "ACCESS_COARSE_LOCATION:", e); } catch (InvocationTargetException e) { Log.e(TAG, "InvocationTargetException while requesting permission for " + "ACCESS_COARSE_LOCATION:", e); } } }); builder.show(); } catch (final IllegalAccessException e) { Log.w(TAG, "IllegalAccessException while checking for ACCESS_COARSE_LOCATION:", e); } catch (final InvocationTargetException e) { Log.w(TAG, "InvocationTargetException while checking for ACCESS_COARSE_LOCATION:", e); } } private Method getCheckSelfPermissionMethod() { try { return Activity.class.getMethod("checkSelfPermission", String.class); } catch (Exception e) { return null; } } private Method getRequestPermissionsMethod() { try { final Class[] parameterTypes = {String[].class, int.class}; return Activity.class.getMethod("requestPermissions", parameterTypes); } catch (Exception e) { return null; } } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) private void initBluetoothAdapter() { Activity activity = cordova.getActivity(); BluetoothManager bluetoothManager = (BluetoothManager) activity.getSystemService(Context.BLUETOOTH_SERVICE); bluetoothAdapter = bluetoothManager.getAdapter(); } private void pauseEventPropagationToDom() { checkEventQueue(); threadPoolExecutor.pause(); } private void resumeEventPropagationToDom() { checkEventQueue(); threadPoolExecutor.resume(); } private void initBluetoothListener() { //check access if (!hasBlueToothPermission()) { debugWarn("Cannot listen to Bluetooth service when BLUETOOTH permission is not added"); return; } //check device support try { iBeaconManager.checkAvailability(); } catch (BleNotAvailableException e) { //if device does not support iBeacons this error is thrown debugWarn("Cannot listen to Bluetooth service: " + e.getMessage()); return; } catch (Exception e) { debugWarn("Unexpected exception checking for Bluetooth service: " + e.getMessage()); return; } if (broadcastReceiver != null) { debugWarn("Already listening to Bluetooth service, not adding again"); return; } broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); // Only listen for Bluetooth server changes if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) { final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); final int oldState = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, BluetoothAdapter.ERROR); debugLog("Bluetooth Service state changed from " + getStateDescription(oldState) + " to " + getStateDescription(state)); switch (state) { case BluetoothAdapter.ERROR: beaconServiceNotifier.didChangeAuthorizationStatus("AuthorizationStatusNotDetermined"); break; case BluetoothAdapter.STATE_OFF: case BluetoothAdapter.STATE_TURNING_OFF: if (oldState == BluetoothAdapter.STATE_ON) beaconServiceNotifier.didChangeAuthorizationStatus("AuthorizationStatusDenied"); break; case BluetoothAdapter.STATE_ON: beaconServiceNotifier.didChangeAuthorizationStatus("AuthorizationStatusAuthorized"); break; case BluetoothAdapter.STATE_TURNING_ON: break; } } } private String getStateDescription(int state) { switch (state) { case BluetoothAdapter.ERROR: return "ERROR"; case BluetoothAdapter.STATE_OFF: return "STATE_OFF"; case BluetoothAdapter.STATE_TURNING_OFF: return "STATE_TURNING_OFF"; case BluetoothAdapter.STATE_ON: return "STATE_ON"; case BluetoothAdapter.STATE_TURNING_ON: return "STATE_TURNING_ON"; } return "ERROR" + state; } }; // Register for broadcasts on BluetoothAdapter state change IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); cordova.getActivity().registerReceiver(broadcastReceiver, filter); } private void initEventQueue() { //queue is limited to one thread at a time queue = new LinkedBlockingQueue<Runnable>(); threadPoolExecutor = new PausableThreadPoolExecutor(queue); //Add a timeout check new Handler().postDelayed(new Runnable() { @Override public void run() { checkIfDomSignaldDelegateReady(); } }, CDV_LOCATION_MANAGER_DOM_DELEGATE_TIMEOUT * 1000); } private void checkEventQueue() { if (threadPoolExecutor != null && queue != null) return; debugWarn("WARNING event queue should not be null."); queue = new LinkedBlockingQueue<Runnable>(); threadPoolExecutor = new PausableThreadPoolExecutor(queue); } private void checkIfDomSignaldDelegateReady() { if (threadPoolExecutor != null && !threadPoolExecutor.isPaused()) return; String warning = "WARNING did not receive delegate ready callback from DOM after " + CDV_LOCATION_MANAGER_DOM_DELEGATE_TIMEOUT + " seconds!"; debugWarn(warning); webView.sendJavascript("console.warn('" + warning + "')"); } ///////// CALLBACKS //////////////////////////// private void createMonitorCallbacks(final CallbackContext callbackContext) { //Monitor callbacks iBeaconManager.setMonitorNotifier(new MonitorNotifier() { @Override public void didEnterRegion(Region region) { debugLog("didEnterRegion INSIDE for " + region.getUniqueId()); dispatchMonitorState("didEnterRegion", MonitorNotifier.INSIDE, region, callbackContext); } @Override public void didExitRegion(Region region) { debugLog("didExitRegion OUTSIDE for " + region.getUniqueId()); dispatchMonitorState("didExitRegion", MonitorNotifier.OUTSIDE, region, callbackContext); } @Override public void didDetermineStateForRegion(int state, Region region) { debugLog("didDetermineStateForRegion '" + nameOfRegionState(state) + "' for region: " + region.getUniqueId()); dispatchMonitorState("didDetermineStateForRegion", state, region, callbackContext); } // Send state to JS callback until told to stop private void dispatchMonitorState(final String eventType, final int state, final Region region, final CallbackContext callbackContext) { threadPoolExecutor.execute(new Runnable() { public void run() { try { JSONObject data = new JSONObject(); data.put("eventType", eventType); data.put("region", mapOfRegion(region)); if (eventType.equals("didDetermineStateForRegion")) { String stateName = nameOfRegionState(state); data.put("state", stateName); } //send and keep reference to callback PluginResult result = new PluginResult(PluginResult.Status.OK, data); result.setKeepCallback(true); callbackContext.sendPluginResult(result); } catch (Exception e) { Log.e(TAG, "'monitoringDidFailForRegion' exception " + e.getCause()); beaconServiceNotifier.monitoringDidFailForRegion(region, e); } } }); } }); } private void createRangingCallbacks(final CallbackContext callbackContext) { iBeaconManager.setRangeNotifier(new RangeNotifier() { @Override public void didRangeBeaconsInRegion(final Collection<Beacon> iBeacons, final Region region) { threadPoolExecutor.execute(new Runnable() { public void run() { try { JSONObject data = new JSONObject(); JSONArray beaconData = new JSONArray(); for (Beacon beacon : iBeacons) { beaconData.put(mapOfBeacon(beacon)); } data.put("eventType", "didRangeBeaconsInRegion"); data.put("region", mapOfRegion(region)); data.put("beacons", beaconData); debugLog("didRangeBeacons: " + data.toString()); //send and keep reference to callback PluginResult result = new PluginResult(PluginResult.Status.OK, data); result.setKeepCallback(true); callbackContext.sendPluginResult(result); } catch (Exception e) { Log.e(TAG, "'rangingBeaconsDidFailForRegion' exception " + e.getCause()); beaconServiceNotifier.rangingBeaconsDidFailForRegion(region, e); } } }); } }); } private void createManagerCallbacks(final CallbackContext callbackContext) { beaconServiceNotifier = new IBeaconServiceNotifier() { @Override public void rangingBeaconsDidFailForRegion(final Region region, final Exception exception) { threadPoolExecutor.execute(new Runnable() { public void run() { sendFailEvent("rangingBeaconsDidFailForRegion", region, exception, callbackContext); } }); } @Override public void monitoringDidFailForRegion(final Region region, final Exception exception) { threadPoolExecutor.execute(new Runnable() { public void run() { sendFailEvent("monitoringDidFailForRegionWithError", region, exception, callbackContext); } }); } @Override public void didStartMonitoringForRegion(final Region region) { threadPoolExecutor.execute(new Runnable() { public void run() { try { JSONObject data = new JSONObject(); data.put("eventType", "didStartMonitoringForRegion"); data.put("region", mapOfRegion(region)); debugLog("didStartMonitoringForRegion: " + data.toString()); //send and keep reference to callback PluginResult result = new PluginResult(PluginResult.Status.OK, data); result.setKeepCallback(true); callbackContext.sendPluginResult(result); } catch (Exception e) { Log.e(TAG, "'startMonitoringForRegion' exception " + e.getCause()); monitoringDidFailForRegion(region, e); } } }); } @Override public void didChangeAuthorizationStatus(final String status) { threadPoolExecutor.execute(new Runnable() { public void run() { try { JSONObject data = new JSONObject(); data.put("eventType", "didChangeAuthorizationStatus"); data.put("authorizationStatus", status); debugLog("didChangeAuthorizationStatus: " + data.toString()); //send and keep reference to callback PluginResult result = new PluginResult(PluginResult.Status.OK, data); result.setKeepCallback(true); callbackContext.sendPluginResult(result); } catch (Exception e) { callbackContext.error("didChangeAuthorizationStatus error: " + e.getMessage()); } } }); } private void sendFailEvent(String eventType, Region region, Exception exception, final CallbackContext callbackContext) { try { JSONObject data = new JSONObject(); data.put("eventType", eventType);//not perfect mapping, but it's very unlikely to happen here data.put("region", mapOfRegion(region)); data.put("error", exception.getMessage()); PluginResult result = new PluginResult(PluginResult.Status.OK, data); result.setKeepCallback(true); callbackContext.sendPluginResult(result); } catch (Exception e) { //still failing, so kill all further event dispatch Log.e(TAG, eventType + " error " + e.getMessage()); callbackContext.error(eventType + " error " + e.getMessage()); } } }; } //-------------------------------------------------------------------------- // PLUGIN METHODS //-------------------------------------------------------------------------- /* * onDomDelegateReady: * * Discussion: * Called from the DOM by the LocationManager Javascript object when it's delegate has been set. * This is to notify the native layer that it can start sending queued up events, like didEnterRegion, * didDetermineState, etc. * * Without this mechanism, the messages would get lost in background mode, because the native layer * has no way of knowing when the consumer Javascript code will actually set it's delegate on the * LocationManager of the DOM. */ private void onDomDelegateReady(CallbackContext callbackContext) { _handleCallSafely(callbackContext, new ILocationManagerCommand() { @Override public PluginResult run() { resumeEventPropagationToDom(); return new PluginResult(PluginResult.Status.OK); } }); } private void isBluetoothEnabled(CallbackContext callbackContext) { _handleCallSafely(callbackContext, new ILocationManagerCommand() { @Override public PluginResult run() { try { //Check the Bluetooth service is running boolean available = bluetoothAdapter != null && bluetoothAdapter.isEnabled(); return new PluginResult(PluginResult.Status.OK, available); } catch (Exception e) { debugWarn("'isBluetoothEnabled' exception " + e.getMessage()); return new PluginResult(PluginResult.Status.ERROR, e.getMessage()); } } }); } private void enableBluetooth(CallbackContext callbackContext) { _handleCallSafely(callbackContext, new ILocationManagerCommand() { @Override public PluginResult run() { try { bluetoothAdapter.enable(); PluginResult result = new PluginResult(PluginResult.Status.OK); result.setKeepCallback(true); return result; } catch (Exception e) { Log.e(TAG, "'enableBluetooth' service error: " + e.getCause()); return new PluginResult(PluginResult.Status.ERROR, e.getMessage()); } } }); } private void disableBluetooth(CallbackContext callbackContext) { _handleCallSafely(callbackContext, new ILocationManagerCommand() { @Override public PluginResult run() { try { bluetoothAdapter.disable(); PluginResult result = new PluginResult(PluginResult.Status.OK); result.setKeepCallback(true); return result; } catch (Exception e) { Log.e(TAG, "'disableBluetooth' service error: " + e.getCause()); return new PluginResult(PluginResult.Status.ERROR, e.getMessage()); } } }); } private void disableDebugNotifications(CallbackContext callbackContext) { _handleCallSafely(callbackContext, new ILocationManagerCommand() { @Override public PluginResult run() { debugEnabled = false; BeaconManager.setDebug(false); //android.bluetooth.BluetoothAdapter.DBG = false; return new PluginResult(PluginResult.Status.OK); } }); } private void enableDebugNotifications(CallbackContext callbackContext) { _handleCallSafely(callbackContext, new ILocationManagerCommand() { @Override public PluginResult run() { debugEnabled = true; //android.bluetooth.BluetoothAdapter.DBG = true; BeaconManager.setDebug(true); return new PluginResult(PluginResult.Status.OK); } }); } private void disableDebugLogs(CallbackContext callbackContext) { _handleCallSafely(callbackContext, new ILocationManagerCommand() { @Override public PluginResult run() { debugEnabled = false; BeaconManager.setDebug(false); //android.bluetooth.BluetoothAdapter.DBG = false; return new PluginResult(PluginResult.Status.OK); } }); } private void enableDebugLogs(CallbackContext callbackContext) { _handleCallSafely(callbackContext, new ILocationManagerCommand() { @Override public PluginResult run() { debugEnabled = true; //android.bluetooth.BluetoothAdapter.DBG = true; BeaconManager.setDebug(true); return new PluginResult(PluginResult.Status.OK); } }); } private void appendToDeviceLog(final String message, CallbackContext callbackContext) { _handleCallSafely(callbackContext, new ILocationManagerCommand() { @Override public PluginResult run() { if (message != null && !message.isEmpty()) { debugLog("[DOM] " + message); return new PluginResult(PluginResult.Status.OK, message); } else { return new PluginResult(PluginResult.Status.ERROR, "Log message not provided"); } } }); } private void startMonitoringForRegion(final JSONObject arguments, final CallbackContext callbackContext) { _handleCallSafely(callbackContext, new ILocationManagerCommand() { @Override public PluginResult run() { Region region = null; try { region = parseRegion(arguments); iBeaconManager.startMonitoringBeaconsInRegion(region); PluginResult result = new PluginResult(PluginResult.Status.OK); result.setKeepCallback(true); beaconServiceNotifier.didStartMonitoringForRegion(region); return result; } catch (RemoteException e) { Log.e(TAG, "'startMonitoringForRegion' service error: " + e.getCause()); beaconServiceNotifier.monitoringDidFailForRegion(region, e); return new PluginResult(PluginResult.Status.ERROR, e.getMessage()); } catch (Exception e) { Log.e(TAG, "'startMonitoringForRegion' exception " + e.getCause()); beaconServiceNotifier.monitoringDidFailForRegion(region, e); return new PluginResult(PluginResult.Status.ERROR, e.getMessage()); } } }); } private void stopMonitoringForRegion(final JSONObject arguments, final CallbackContext callbackContext) { _handleCallSafely(callbackContext, new ILocationManagerCommand() { @Override public PluginResult run() { try { Region region = parseRegion(arguments); iBeaconManager.stopMonitoringBeaconsInRegion(region); PluginResult result = new PluginResult(PluginResult.Status.OK); result.setKeepCallback(true); return result; } catch (RemoteException e) { Log.e(TAG, "'stopMonitoringForRegion' service error: " + e.getCause()); return new PluginResult(PluginResult.Status.ERROR, e.getMessage()); } catch (Exception e) { Log.e(TAG, "'stopMonitoringForRegion' exception " + e.getCause()); return new PluginResult(PluginResult.Status.ERROR, e.getMessage()); } } }); } private void startRangingBeaconsInRegion(final JSONObject arguments, final CallbackContext callbackContext) { _handleCallSafely(callbackContext, new ILocationManagerCommand() { @Override public PluginResult run() { try { Region region = parseRegion(arguments); iBeaconManager.startRangingBeaconsInRegion(region); PluginResult result = new PluginResult(PluginResult.Status.OK); result.setKeepCallback(true); return result; } catch (RemoteException e) { Log.e(TAG, "'startRangingBeaconsInRegion' service error: " + e.getCause()); return new PluginResult(PluginResult.Status.ERROR, e.getMessage()); } catch (Exception e) { Log.e(TAG, "'startRangingBeaconsInRegion' exception " + e.getCause()); return new PluginResult(PluginResult.Status.ERROR, e.getMessage()); } } }); } private void stopRangingBeaconsInRegion(final JSONObject arguments, CallbackContext callbackContext) { _handleCallSafely(callbackContext, new ILocationManagerCommand() { @Override public PluginResult run() { try { Region region = parseRegion(arguments); iBeaconManager.stopRangingBeaconsInRegion(region); PluginResult result = new PluginResult(PluginResult.Status.OK); result.setKeepCallback(true); return result; } catch (RemoteException e) { Log.e(TAG, "'stopRangingBeaconsInRegion' service error: " + e.getCause()); return new PluginResult(PluginResult.Status.ERROR, e.getMessage()); } catch (Exception e) { Log.e(TAG, "'stopRangingBeaconsInRegion' exception " + e.getCause()); return new PluginResult(PluginResult.Status.ERROR, e.getMessage()); } } }); } private void getAuthorizationStatus(CallbackContext callbackContext) { _handleCallSafely(callbackContext, new ILocationManagerCommand() { @Override public PluginResult run() { try { //Check app has the necessary permissions if (!hasBlueToothPermission()) { return new PluginResult(PluginResult.Status.ERROR, "Application does not BLUETOOTH or BLUETOOTH_ADMIN permissions"); } //Check the Bluetooth service is running String authStatus = iBeaconManager.checkAvailability() ? "AuthorizationStatusAuthorized" : "AuthorizationStatusDenied"; JSONObject result = new JSONObject(); result.put("authorizationStatus", authStatus); return new PluginResult(PluginResult.Status.OK, result); } catch (BleNotAvailableException e) { //if device does not support iBeacons and error is thrown debugLog("'getAuthorizationStatus' Device not supported: " + e.getMessage()); return new PluginResult(PluginResult.Status.ERROR, e.getMessage()); } catch (Exception e) { debugWarn("'getAuthorizationStatus' exception " + e.getMessage()); return new PluginResult(PluginResult.Status.ERROR, e.getMessage()); } } }); } private void requestWhenInUseAuthorization(CallbackContext callbackContext) { _handleCallSafely(callbackContext, new ILocationManagerCommand() { @Override public PluginResult run() { return new PluginResult(PluginResult.Status.OK); } }); } private void requestAlwaysAuthorization(CallbackContext callbackContext) { _handleCallSafely(callbackContext, new ILocationManagerCommand() { @Override public PluginResult run() { return new PluginResult(PluginResult.Status.OK); } }); } private void getMonitoredRegions(CallbackContext callbackContext) { _handleCallSafely(callbackContext, new ILocationManagerCommand() { @Override public PluginResult run() { try { Collection<Region> regions = iBeaconManager.getMonitoredRegions(); JSONArray regionArray = new JSONArray(); for (Region region : regions) { regionArray.put(mapOfRegion(region)); } return new PluginResult(PluginResult.Status.OK, regionArray); } catch (JSONException e) { debugWarn("'getMonitoredRegions' exception: " + e.getMessage()); return new PluginResult(PluginResult.Status.ERROR, e.getMessage()); } } }); } private void getRangedRegions(CallbackContext callbackContext) { _handleCallSafely(callbackContext, new ILocationManagerCommand() { @Override public PluginResult run() { try { Collection<Region> regions = iBeaconManager.getRangedRegions(); JSONArray regionArray = new JSONArray(); for (Region region : regions) { regionArray.put(mapOfRegion(region)); } return new PluginResult(PluginResult.Status.OK, regionArray); } catch (JSONException e) { debugWarn("'getRangedRegions' exception: " + e.getMessage()); return new PluginResult(PluginResult.Status.ERROR, e.getMessage()); } } }); } //NOT IMPLEMENTED: Manually request monitoring scan for region. //This might not even be needed for Android as it should happen no matter what private void requestStateForRegion(final JSONObject arguments, CallbackContext callbackContext) { _handleCallSafely(callbackContext, new ILocationManagerCommand() { @Override public PluginResult run() { //not supported on Android PluginResult result = new PluginResult(PluginResult.Status.ERROR, "Manual request for monitoring update is not supported on Android"); result.setKeepCallback(true); return result; } }); } private void isRangingAvailable(CallbackContext callbackContext) { _handleCallSafely(callbackContext, new ILocationManagerCommand() { @Override public PluginResult run() { try { //Check the Bluetooth service is running boolean available = iBeaconManager.checkAvailability(); return new PluginResult(PluginResult.Status.OK, available); } catch (BleNotAvailableException e) { //if device does not support iBeacons and error is thrown debugLog("'isRangingAvailable' Device not supported: " + e.getMessage()); return new PluginResult(PluginResult.Status.ERROR, e.getMessage()); } catch (Exception e) { debugWarn("'isRangingAvailable' exception " + e.getMessage()); return new PluginResult(PluginResult.Status.ERROR, e.getMessage()); } } }); } private void registerDelegateCallbackId(JSONObject arguments, final CallbackContext callbackContext) { _handleCallSafely(callbackContext, new ILocationManagerCommand() { @Override public PluginResult run() { debugLog("Registering delegate callback ID: " + callbackContext.getCallbackId()); //delegateCallbackId = callbackContext.getCallbackId(); createMonitorCallbacks(callbackContext); createRangingCallbacks(callbackContext); createManagerCallbacks(callbackContext); PluginResult result = new PluginResult(PluginResult.Status.OK); result.setKeepCallback(true); return result; } }); } /* * Checks if the region is supported, both for type and content */ private void isMonitoringAvailableForClass(final JSONObject arguments, final CallbackContext callbackContext) { _handleCallSafely(callbackContext, new ILocationManagerCommand() { @Override public PluginResult run() { boolean isValid = true; try { parseRegion(arguments); } catch (Exception e) { //will fail is the region is circular or some expected structure is missing isValid = false; } PluginResult result = new PluginResult(PluginResult.Status.OK, isValid); result.setKeepCallback(true); return result; } }); } private void isAdvertisingAvailable(CallbackContext callbackContext) { _handleCallSafely(callbackContext, new ILocationManagerCommand() { @Override public PluginResult run() { //not supported at Android yet (see Android L) if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // only for ANDROID >= 5.0 PluginResult result = new PluginResult(PluginResult.Status.OK, true); result.setKeepCallback(true); return result; }else{ PluginResult result = new PluginResult(PluginResult.Status.OK, false); result.setKeepCallback(true); return result; } } }); } private void isAdvertising(CallbackContext callbackContext) { _handleCallSafely(callbackContext, new ILocationManagerCommand() { @Override public PluginResult run() { //not supported on Android PluginResult result = new PluginResult(PluginResult.Status.OK, false); result.setKeepCallback(true); return result; } }); } private void startAdvertising(final JSONArray args, CallbackContext callbackContext) throws JSONException { debugLog("Advertisement start START BEACON "); debugLog(args.toString(4)); /* Advertisement start START BEACON [ { "identifier": "beaconAsMesh", "uuid": "e80300fe-ff4b-0c37-5149-d9f394b5ca39", "major": 0, "minor": 30463, "notifyEntryStateOnDisplay": true, "typeName": "BeaconRegion" }, 7 ] */ JSONObject arguments = args.optJSONObject(0); // get first object String identifier = arguments.getString("identifier"); //For Android, uuid can be null when scanning for all beacons (I think) final String uuid = arguments.has("uuid") && !arguments.isNull("uuid") ? arguments.getString("uuid") : null; final String major = arguments.has("major") && !arguments.isNull("major") ? arguments.getString("major") : null; final String minor = arguments.has("minor") && !arguments.isNull("minor") ? arguments.getString("minor") : null; // optinal second member in JSONArray is just a number final int measuredPower = args.length() > 1 ? args.getInt(1) : -55; if (major == null && minor != null) throw new UnsupportedOperationException("Unsupported combination of 'major' and 'minor' parameters."); _handleCallSafely(callbackContext, new ILocationManagerCommand() { @Override public PluginResult run() { debugLog("Advertisement start STEP Beacon.Builder "); Beacon beacon = new Beacon.Builder() .setId1(uuid) // UUID for beacon .setId2(major) // Major for beacon .setId3(minor) // Minor for beacon .setManufacturer(0x004C) // Radius Networks.0x0118 Change this for other beacon layouts//0x004C for iPhone .setTxPower(measuredPower) // Power in dB .setDataFields(Arrays.asList(new Long[] {0l})) // Remove this for beacon layouts without d: fields .build(); debugLog("[DEBUG] Beacon.Builder: "+beacon); /* Beacon beacon = new Beacon.Builder() .setId1("00000000-2016-0000-0000-000000000000") // UUID for beacon .setId2("5") // Major for beacon .setId3("2000") // Minor for beacon .setManufacturer(0x004C) // Radius Networks.0x0118 Change this for other beacon layouts//0x004C for iPhone .setTxPower(-56) // Power in dB .setDataFields(Arrays.asList(new Long[] {0l})) // Remove this for beacon layouts without d: fields .build(); */ debugLog("Advertisement start STEP BeaconParser "); debugLog("Advertisement start STEP BeaconTransmitter "); final BeaconTransmitter beaconTransmitter = LocationManager.this.createOrGetBeaconTransmitter(); debugLog("[DEBUG] BeaconTransmitter: "+beaconTransmitter); beaconTransmitter.startAdvertising(beacon, new AdvertiseCallback() { @Override public void onStartFailure(int errorCode) { debugWarn("Advertisement start failed with code: "+errorCode); } @Override public void onStartSuccess(AdvertiseSettings settingsInEffect) { debugWarn("startAdvertising start succeeded."); } }); final PluginResult result = new PluginResult(PluginResult.Status.OK, false); result.setKeepCallback(true); return result; } }); } private void stopAdvertising(CallbackContext callbackContext) { _handleCallSafely(callbackContext, new ILocationManagerCommand() { @Override public PluginResult run() { debugInfo("LocationManager::stopAdvertising::STOPPING..."); final BeaconTransmitter beaconTransmitter = LocationManager.this.createOrGetBeaconTransmitter(); beaconTransmitter.stopAdvertising(); debugInfo("LocationManager::stopAdvertising::DONE"); //not supported on Android PluginResult result = new PluginResult(PluginResult.Status.OK, "iBeacon Advertising stopped."); result.setKeepCallback(true); return result; } }); } /////////// SERIALISATION ///////////////////// private Region parseRegion(JSONObject json) throws JSONException, InvalidKeyException, UnsupportedOperationException { if (!json.has("typeName")) throw new InvalidKeyException("'typeName' is missing, cannot parse Region."); if (!json.has("identifier")) throw new InvalidKeyException("'identifier' is missing, cannot parse Region."); String typeName = json.getString("typeName"); if (typeName.equals("BeaconRegion")) { return parseBeaconRegion(json); } else if (typeName.equals("CircularRegion")) { return parseCircularRegion(json); } else { throw new UnsupportedOperationException("Unsupported region type"); } } /* NOT SUPPORTED, a possible enhancement later */ private Region parseCircularRegion(JSONObject json) throws JSONException, InvalidKeyException, UnsupportedOperationException { if (!json.has("latitude")) throw new InvalidKeyException("'latitude' is missing, cannot parse CircularRegion."); if (!json.has("longitude")) throw new InvalidKeyException("'longitude' is missing, cannot parse CircularRegion."); if (!json.has("radius")) throw new InvalidKeyException("'radius' is missing, cannot parse CircularRegion."); /*String identifier = json.getString("identifier"); double latitude = json.getDouble("latitude"); double longitude = json.getDouble("longitude"); double radius = json.getDouble("radius"); */ throw new UnsupportedOperationException("Circular regions are not supported at present"); } private Region parseBeaconRegion(JSONObject json) throws JSONException, UnsupportedOperationException { String identifier = json.getString("identifier"); //For Android, uuid can be null when scanning for all beacons (I think) String uuid = json.has("uuid") && !json.isNull("uuid") ? json.getString("uuid") : null; String major = json.has("major") && !json.isNull("major") ? json.getString("major") : null; String minor = json.has("minor") && !json.isNull("minor") ? json.getString("minor") : null; if (major == null && minor != null) throw new UnsupportedOperationException("Unsupported combination of 'major' and 'minor' parameters."); Identifier id1 = uuid != null ? Identifier.parse(uuid) : null; Identifier id2 = major != null ? Identifier.parse(major) : null; Identifier id3 = minor != null ? Identifier.parse(minor) : null; return new Region(identifier, id1, id2, id3); } private String nameOfRegionState(int state) { switch (state) { case MonitorNotifier.INSIDE: return "CLRegionStateInside"; case MonitorNotifier.OUTSIDE: return "CLRegionStateOutside"; /*case MonitorNotifier.UNKNOWN: return "CLRegionStateUnknown";*/ default: return "ErrorUnknownCLRegionStateObjectReceived"; } } private JSONObject mapOfRegion(Region region) throws JSONException { //NOTE: NOT SUPPORTING CIRCULAR REGIONS return mapOfBeaconRegion(region); } private JSONObject mapOfBeaconRegion(Region region) throws JSONException { JSONObject dict = new JSONObject(); // identifier if (region.getUniqueId() != null) { dict.put("identifier", region.getUniqueId()); } dict.put("uuid", region.getId1()); if (region.getId2() != null) { dict.put("major", region.getId2()); } if (region.getId3() != null) { dict.put("minor", region.getId3()); } dict.put("typeName", "BeaconRegion"); return dict; } /* NOT SUPPORTED */ /*private JSONObject mapOfCircularRegion(Region region) throws JSONException { JSONObject dict = new JSONObject(); // identifier if (region.getUniqueId() != null) { dict.put("identifier", region.getUniqueId()); } //NOT SUPPORTING CIRCULAR REGIONS //dict.put("radius", region.getRadius()); //JSONObject coordinates = new JSONObject(); //coordinates.put("latitude", 0.0d); //coordinates.put("longitude", 0.0d); //dict.put("center", coordinates); //dict.put("typeName", "CircularRegion"); return dict; }*/ private JSONObject mapOfBeacon(Beacon region) throws JSONException { JSONObject dict = new JSONObject(); //beacon id dict.put("uuid", region.getId1()); dict.put("major", region.getId2()); dict.put("minor", region.getId3()); // proximity dict.put("proximity", nameOfProximity(region.getDistance())); // signal strength and transmission power dict.put("rssi", region.getRssi()); dict.put("tx", region.getTxPower()); // accuracy = rough distance estimate limited to two decimal places (in metres) // NO NOT ASSUME THIS IS ACCURATE - it is effected by radio interference and obstacles dict.put("accuracy", Math.round(region.getDistance() * 100.0) / 100.0); return dict; } private String nameOfProximity(double accuracy) { if (accuracy < 0) { return "ProximityUnknown"; // is this correct? does proximity only show unknown when accuracy is negative? I have seen cases where it returns unknown when // accuracy is -1; } if (accuracy < 0.5) { return "ProximityImmediate"; } // forums say 3.0 is the near/far threshold, but it looks to be based on experience that this is 4.0 if (accuracy <= 4.0) { return "ProximityNear"; } // if it is > 4.0 meters, call it far return "ProximityFar"; } private boolean hasBlueToothPermission() { Context context = cordova.getActivity(); int access = context.checkCallingOrSelfPermission(Manifest.permission.BLUETOOTH); int adminAccess = context.checkCallingOrSelfPermission(Manifest.permission.BLUETOOTH_ADMIN); return (access == PackageManager.PERMISSION_GRANTED) && (adminAccess == PackageManager.PERMISSION_GRANTED); } //////// Async Task Handling //////////////////////////////// private void _handleCallSafely(CallbackContext callbackContext, final ILocationManagerCommand task) { _handleCallSafely(callbackContext, task, true); } private void _handleCallSafely(final CallbackContext callbackContext, final ILocationManagerCommand task, boolean runInBackground) { if (runInBackground) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(final Void... params) { try { _sendResultOfCommand(callbackContext, task.run()); } catch (Exception ex) { _handleExceptionOfCommand(callbackContext, ex); } return null; } }.execute(); } else { try { _sendResultOfCommand(callbackContext, task.run()); } catch (Exception ex) { _handleExceptionOfCommand(callbackContext, ex); } } } private void _handleExceptionOfCommand(CallbackContext callbackContext, Exception exception) { Log.e(TAG, "Uncaught exception: " + exception.getMessage()); final StackTraceElement[] stackTrace = exception.getStackTrace(); final String stackTraceElementsAsString = Arrays.toString(stackTrace); Log.e(TAG, "Stack trace: " + stackTraceElementsAsString); // When calling without a callback from the client side the command can be null. if (callbackContext == null) { return; } callbackContext.error(exception.getMessage()); } private void _sendResultOfCommand(CallbackContext callbackContext, PluginResult pluginResult) { //debugLog("Send result: " + pluginResult.getMessage()); if (pluginResult.getStatus() != PluginResult.Status.OK.ordinal()) debugWarn("WARNING: " + PluginResult.StatusMessages[pluginResult.getStatus()]); // When calling without a callback from the client side the command can be null. if (callbackContext == null) { return; } callbackContext.sendPluginResult(pluginResult); } private void debugInfo(String message) { if (debugEnabled) { Log.i(TAG, message); } } private void debugLog(String message) { if (debugEnabled) { Log.d(TAG, message); } } private void debugWarn(String message) { if (debugEnabled) { Log.w(TAG, message); } } //////// IBeaconConsumer implementation ///////////////////// @Override public void onBeaconServiceConnect() { debugLog("Connected to IBeacon service"); } @Override public Context getApplicationContext() { return cordova.getActivity(); } @Override public void unbindService(ServiceConnection connection) { debugLog("Unbind from IBeacon service"); cordova.getActivity().unbindService(connection); } @Override public boolean bindService(Intent intent, ServiceConnection connection, int mode) { debugLog("Bind to IBeacon service"); return cordova.getActivity().bindService(intent, connection, mode); } }
package extend.common.wangtiansoft; import java.io.UnsupportedEncodingException; public class Base64 { /** * Chunk size per RFC 2045 section 6.8. * * <p>The {@value} character limit does not count the trailing CRLF, but counts * all other characters, including any equal signs.</p> * * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a> */ static final int CHUNK_SIZE = 76; /** * Chunk separator per RFC 2045 section 2.1. * * @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 2.1</a> */ static final byte[] CHUNK_SEPARATOR = "\r\n".getBytes(); /** * The base length. */ static final int BASELENGTH = 255; /** * Lookup length. */ static final int LOOKUPLENGTH = 64; /** * Used to calculate the number of bits in a byte. */ static final int EIGHTBIT = 8; /** * Used when encoding something which has fewer than 24 bits. */ static final int SIXTEENBIT = 16; /** * Used to determine how many bits data contains. */ static final int TWENTYFOURBITGROUP = 24; /** * Used to get the number of Quadruples. */ static final int FOURBYTE = 4; /** * Used to test the sign of a byte. */ static final int SIGN = -128; /** * Byte used to pad output. */ static final byte PAD = (byte) '='; // Create arrays to hold the base64 characters and a // lookup for base64 chars private static byte[] base64Alphabet = new byte[BASELENGTH]; private static byte[] lookUpBase64Alphabet = new byte[LOOKUPLENGTH]; // Populating the lookup and character arrays static { for (int i = 0; i < BASELENGTH; i++) { base64Alphabet[i] = (byte) -1; } for (int i = 'Z'; i >= 'A'; i--) { base64Alphabet[i] = (byte) (i - 'A'); } for (int i = 'z'; i >= 'a'; i--) { base64Alphabet[i] = (byte) (i - 'a' + 26); } for (int i = '9'; i >= '0'; i--) { base64Alphabet[i] = (byte) (i - '0' + 52); } base64Alphabet['+'] = 62; base64Alphabet['/'] = 63; for (int i = 0; i <= 25; i++) { lookUpBase64Alphabet[i] = (byte) ('A' + i); } for (int i = 26, j = 0; i <= 51; i++, j++) { lookUpBase64Alphabet[i] = (byte) ('a' + j); } for (int i = 52, j = 0; i <= 61; i++, j++) { lookUpBase64Alphabet[i] = (byte) ('0' + j); } lookUpBase64Alphabet[62] = (byte) '+'; lookUpBase64Alphabet[63] = (byte) '/'; } private static boolean isBase64(byte octect) { if (octect == PAD) { return true; } else if (base64Alphabet[octect] == -1) { return false; } else { return true; } } /** * Tests a given byte array to see if it contains * only valid characters within the Base64 alphabet. * * @param arrayOctect byte array to test * @return true if all bytes are valid characters in the Base64 * alphabet or if the byte array is empty; false, otherwise */ public static boolean isArrayByteBase64(byte[] arrayOctect) { arrayOctect = discardWhitespace(arrayOctect); int length = arrayOctect.length; if (length == 0) { // shouldn't a 0 length array be valid base64 data? // return false; return true; } for (int i = 0; i < length; i++) { if (!isBase64(arrayOctect[i])) { return false; } } return true; } /** * Encodes binary data using the base64 algorithm but * does not chunk the output. * * @param binaryData binary data to encode * @return Base64 characters */ public static byte[] encodeBase64(byte[] binaryData) { return encodeBase64(binaryData, false); } /** * Encodes binary data using the base64 algorithm and chunks * the encoded output into 76 character blocks * * @param binaryData binary data to encode * @return Base64 characters chunked in 76 character blocks */ public static byte[] encodeBase64Chunked(byte[] binaryData) { return encodeBase64(binaryData, true); } /** * Decodes a byte[] containing containing * characters in the Base64 alphabet. * * @param pArray A byte array containing Base64 character data * @return a byte array containing binary data */ public static byte[] decode(byte[] pArray) { return decodeBase64(pArray); } /** * Encodes binary data using the base64 algorithm, optionally * chunking the output into 76 character blocks. * * @param binaryData Array containing binary data to encode. * @param isChunked if isChunked is true this encoder will chunk * the base64 output into 76 character blocks * @return Base64-encoded data. */ public static byte[] encodeBase64(byte[] binaryData, boolean isChunked) { int lengthDataBits = binaryData.length * EIGHTBIT; int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; byte encodedData[] = null; int encodedDataLength = 0; int nbrChunks = 0; if (fewerThan24bits != 0) { //data not divisible by 24 bit encodedDataLength = (numberTriplets + 1) * 4; } else { // 16 or 8 bit encodedDataLength = numberTriplets * 4; } // If the output is to be "chunked" into 76 character sections, // for compliance with RFC 2045 MIME, then it is important to // allow for extra length to account for the separator(s) if (isChunked) { nbrChunks = (CHUNK_SEPARATOR.length == 0 ? 0 : (int) Math.ceil((float) encodedDataLength / CHUNK_SIZE)); encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length; } encodedData = new byte[encodedDataLength]; byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; int encodedIndex = 0; int dataIndex = 0; int i = 0; int nextSeparatorIndex = CHUNK_SIZE; int chunksSoFar = 0; //log.debug("number of triplets = " + numberTriplets); for (i = 0; i < numberTriplets; i++) { dataIndex = i * 3; b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; b3 = binaryData[dataIndex + 2]; //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3); l = (byte) (b2 & 0x0f); k = (byte) (b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; //log.debug( "val2 = " + val2 ); //log.debug( "k4 = " + (k<<4) ); //log.debug( "vak = " + (val2 | (k<<4)) ); encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[(l << 2) | val3]; encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f]; encodedIndex += 4; // If we are chunking, let's put a chunk separator down. if (isChunked) { // this assumes that CHUNK_SIZE % 4 == 0 if (encodedIndex == nextSeparatorIndex) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedIndex, CHUNK_SEPARATOR.length); chunksSoFar++; nextSeparatorIndex = (CHUNK_SIZE * (chunksSoFar + 1)) + (chunksSoFar * CHUNK_SEPARATOR.length); encodedIndex += CHUNK_SEPARATOR.length; } } } // form integral number of 6-bit groups dataIndex = i * 3; if (fewerThan24bits == EIGHTBIT) { b1 = binaryData[dataIndex]; k = (byte) (b1 & 0x03); //log.debug("b1=" + b1); //log.debug("b1<<2 = " + (b1>>2) ); byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4]; encodedData[encodedIndex + 2] = PAD; encodedData[encodedIndex + 3] = PAD; } else if (fewerThan24bits == SIXTEENBIT) { b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; l = (byte) (b2 & 0x0f); k = (byte) (b1 & 0x03); byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | (k << 4)]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2]; encodedData[encodedIndex + 3] = PAD; } if (isChunked) { // we also add a separator to the end of the final chunk. if (chunksSoFar < nbrChunks) { System.arraycopy( CHUNK_SEPARATOR, 0, encodedData, encodedDataLength - CHUNK_SEPARATOR.length, CHUNK_SEPARATOR.length); } } return encodedData; } /** * Decodes Base64 data into octects * * @param base64Data Byte array containing Base64 data * @return Array containing decoded data. */ public static byte[] decodeBase64(byte[] base64Data) { // RFC 2045 requires that we discard ALL non-Base64 characters base64Data = discardNonBase64(base64Data); // handle the edge case, so we don't have to worry about it later if (base64Data.length == 0) { return new byte[0]; } int numberQuadruple = base64Data.length / FOURBYTE; byte decodedData[] = null; byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0; // Throw away anything not in base64Data int encodedIndex = 0; int dataIndex = 0; { // this sizes the output array properly - rlw int lastData = base64Data.length; // ignore the '=' padding while (base64Data[lastData - 1] == PAD) { if (--lastData == 0) { return new byte[0]; } } decodedData = new byte[lastData - numberQuadruple]; } for (int i = 0; i < numberQuadruple; i++) { dataIndex = i * 4; marker0 = base64Data[dataIndex + 2]; marker1 = base64Data[dataIndex + 3]; b1 = base64Alphabet[base64Data[dataIndex]]; b2 = base64Alphabet[base64Data[dataIndex + 1]]; if (marker0 != PAD && marker1 != PAD) { //No PAD e.g 3cQl b3 = base64Alphabet[marker0]; b4 = base64Alphabet[marker1]; decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4); } else if (marker0 == PAD) { //Two PAD e.g. 3c[Pad][Pad] decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); } else if (marker1 == PAD) { //One PAD e.g. 3cQ[Pad] b3 = base64Alphabet[marker0]; decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); decodedData[encodedIndex + 1] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); } encodedIndex += 3; } return decodedData; } /** * Discards any whitespace from a base-64 encoded block. * * @param data The base-64 encoded data to discard the whitespace * from. * @return The data, less whitespace (see RFC 2045). */ static byte[] discardWhitespace(byte[] data) { byte groomedData[] = new byte[data.length]; int bytesCopied = 0; for (int i = 0; i < data.length; i++) { switch (data[i]) { case (byte) ' ' : case (byte) '\n' : case (byte) '\r' : case (byte) '\t' : break; default: groomedData[bytesCopied++] = data[i]; } } byte packedData[] = new byte[bytesCopied]; System.arraycopy(groomedData, 0, packedData, 0, bytesCopied); return packedData; } /** * Discards any characters outside of the base64 alphabet, per * the requirements on page 25 of RFC 2045 - "Any characters * outside of the base64 alphabet are to be ignored in base64 * encoded data." * * @param data The base-64 encoded data to groom * @return The data, less non-base64 characters (see RFC 2045). */ static byte[] discardNonBase64(byte[] data) { byte groomedData[] = new byte[data.length]; int bytesCopied = 0; for (int i = 0; i < data.length; i++) { if (isBase64(data[i])) { groomedData[bytesCopied++] = data[i]; } } byte packedData[] = new byte[bytesCopied]; System.arraycopy(groomedData, 0, packedData, 0, bytesCopied); return packedData; } /** * Encodes a byte[] containing binary data, into a byte[] containing * characters in the Base64 alphabet. * * @param pArray a byte array containing binary data * @return A byte array containing only Base64 character data */ public static byte[] encode(byte[] pArray) { return encodeBase64(pArray, false); } public static String encode(String str) throws UnsupportedEncodingException { String baseStr = new String(encode(str.getBytes("UTF-8"))); String tempStr = Digest.digest(str).toUpperCase(); String result = tempStr+baseStr; return new String(encode(result.getBytes("UTF-8"))); } public static String decode(String cryptoStr) throws UnsupportedEncodingException { if(cryptoStr.length()<40) return ""; try { String tempStr = new String(decode(cryptoStr.getBytes("UTF-8"))); String result = tempStr.substring(40, tempStr.length()); return new String(decode(result.getBytes("UTF-8"))); } catch(java.lang.ArrayIndexOutOfBoundsException ex) { return ""; } } /** * Decodes Base64 data into octects * * @param encoded string containing Base64 data * @return Array containind decoded data. */ public static byte[] decode2(String encoded) { if (encoded == null) { return null; } char[] base64Data = encoded.toCharArray(); // remove white spaces int len = removeWhiteSpace(base64Data); if (len % FOURBYTE != 0) { return null;//should be divisible by four } int numberQuadruple = (len / FOURBYTE); if (numberQuadruple == 0) { return new byte[0]; } byte decodedData[] = null; byte b1 = 0, b2 = 0, b3 = 0, b4 = 0; char d1 = 0, d2 = 0, d3 = 0, d4 = 0; int i = 0; int encodedIndex = 0; int dataIndex = 0; decodedData = new byte[(numberQuadruple) * 3]; for (; i < numberQuadruple - 1; i++) { if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++])) || !isData((d3 = base64Data[dataIndex++])) || !isData((d4 = base64Data[dataIndex++]))) { return null; }//if found "no data" just return null b1 = base64Alphabet[d1]; b2 = base64Alphabet[d2]; b3 = base64Alphabet[d3]; b4 = base64Alphabet[d4]; decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4); decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); decodedData[encodedIndex++] = (byte) (b3 << 6 | b4); } if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))) { return null;//if found "no data" just return null } b1 = base64Alphabet[d1]; b2 = base64Alphabet[d2]; d3 = base64Data[dataIndex++]; d4 = base64Data[dataIndex++]; if (!isData((d3)) || !isData((d4))) {//Check if they are PAD characters if (isPad(d3) && isPad(d4)) { if ((b2 & 0xf) != 0)//last 4 bits should be zero { return null; } byte[] tmp = new byte[i * 3 + 1]; System.arraycopy(decodedData, 0, tmp, 0, i * 3); tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); return tmp; } else if (!isPad(d3) && isPad(d4)) { b3 = base64Alphabet[d3]; if ((b3 & 0x3) != 0)//last 2 bits should be zero { return null; } byte[] tmp = new byte[i * 3 + 2]; System.arraycopy(decodedData, 0, tmp, 0, i * 3); tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4); tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); return tmp; } else { return null; } } else { //No PAD e.g 3cQl b3 = base64Alphabet[d3]; b4 = base64Alphabet[d4]; decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4); decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); decodedData[encodedIndex++] = (byte) (b3 << 6 | b4); } return decodedData; } private static boolean isWhiteSpace(char octect) { return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9); } private static boolean isData(char octect) { return (octect < BASELENGTH && base64Alphabet[octect] != -1); } private static boolean isPad(char octect) { return (octect == PAD); } /** * remove WhiteSpace from MIME containing encoded Base64 data. * * @param data the byte array of base64 data (with WS) * @return the new length */ private static int removeWhiteSpace(char[] data) { if (data == null) { return 0; } // count characters that's not whitespace int newSize = 0; int len = data.length; for (int i = 0; i < len; i++) { if (!isWhiteSpace(data[i])) { data[newSize++] = data[i]; } } return newSize; } }
/* * Copyright 2011 Google Inc. All Rights Reserved. * * 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.android.apps.authenticator; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import com.google.android.apps.authenticator.testability.DependencyInjector; import com.google.android.apps.authenticator.testability.StartActivityListener; import com.google.android.apps.authenticator.BuildConfig; import android.app.Activity; import android.app.Instrumentation; import android.content.Context; import android.content.Intent; import android.graphics.Point; import android.os.Build; import android.os.Looper; import android.os.SystemClock; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceScreen; import android.test.InstrumentationTestCase; import android.test.TouchUtils; import android.test.ViewAsserts; import android.view.Gravity; import android.view.View; import android.view.ViewParent; import android.widget.EditText; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.Spinner; import junit.framework.Assert; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * A class that offers various utility methods for writing tests. * * @author sarvar@google.com (Sarvar Patel) */ public class TestUtilities { public static final String APP_PACKAGE_NAME = BuildConfig.APPLICATION_ID; /** * Timeout (milliseconds) when waiting for the results of a UI action performed by the code * under test. */ public static final int UI_ACTION_EFFECT_TIMEOUT_MILLIS = 5000; private TestUtilities() { } public static void clickView(Instrumentation instr, final View view) { instr.runOnMainSync(new Runnable() { @Override public void run() { view.performClick(); } }); // this shouldn't be needed but without it or sleep, there isn't time for view refresh, etc. instr.waitForIdleSync(); } public static void longClickView(Instrumentation instr, final View view) { instr.runOnMainSync(new Runnable() { @Override public void run() { view.performLongClick(); } }); instr.waitForIdleSync(); } /** * Selects the item at the requested position in the Spinner. * * @return the selected item as string. */ public static String selectSpinnerItem( Instrumentation instr, final Spinner spinner, final int position) { instr.runOnMainSync(new Runnable() { @Override public void run() { spinner.setSelection(position); } }); instr.waitForIdleSync(); return spinner.getSelectedItem().toString(); } /** * Sets the text of the provided {@link EditText} widget on the UI thread. * * @return the resulting text of the widget. */ public static String setText(Instrumentation instr, final EditText editText, final String text) { instr.runOnMainSync(new Runnable() { @Override public void run() { editText.setText(text); } }); instr.waitForIdleSync(); return editText.getText().toString(); } /* * Sends a string to a EditText box. * * @return the resulting string read from the editText - this should equal text. */ public static String enterText( Instrumentation instr, final EditText editText, final String text) { instr.runOnMainSync(new Runnable() { @Override public void run() { editText.requestFocus(); } }); // TODO(sarvar): decide on using touch mode and how to do it consistently. e.g., // the above could be replaced by "TouchUtils.tapView(this, editText);" instr.sendStringSync(text); return editText.getText().toString(); } /** * Taps the specified preference displayed by the provided Activity. */ public static void tapPreference(InstrumentationTestCase instrumentationTestCase, PreferenceActivity activity, Preference preference) { // IMPLEMENTATION NOTE: There's no obvious way to find out which View corresponds to the // preference because the Preference list in the adapter is flattened, whereas the View // hierarchy in the ListView is not. // Thus, we go for the Reflection-based invocation of Preference.performClick() which is as // close to the invocation stack of a normal tap as it gets. // Only perform the click if the preference is in the adapter to catch cases where the // preference is not part of the PreferenceActivity for some reason. ListView listView = activity.getListView(); ListAdapter listAdapter = listView.getAdapter(); for (int i = 0, len = listAdapter.getCount(); i < len; i++) { if (listAdapter.getItem(i) == preference) { invokePreferencePerformClickOnMainThread( instrumentationTestCase.getInstrumentation(), preference, activity.getPreferenceScreen()); return; } } throw new IllegalArgumentException("Preference " + preference + " not in list"); } private static void invokePreferencePerformClickOnMainThread( Instrumentation instrumentation, final Preference preference, final PreferenceScreen preferenceScreen) { if (Thread.currentThread() == Looper.getMainLooper().getThread()) { invokePreferencePerformClick(preference, preferenceScreen); } else { FutureTask<Void> task = new FutureTask<Void>(new Runnable() { @Override public void run() { invokePreferencePerformClick(preference, preferenceScreen); } }, null); instrumentation.runOnMainSync(task); try { task.get(); } catch (Exception e) { throw new RuntimeException("Failed to click on preference on main thread", e); } } } private static void invokePreferencePerformClick( Preference preference, PreferenceScreen preferenceScreen) { try { Method performClickMethod = Preference.class.getDeclaredMethod("performClick", PreferenceScreen.class); performClickMethod.setAccessible(true); performClickMethod.invoke(preference, preferenceScreen); } catch (NoSuchMethodException e) { throw new RuntimeException("Preference.performClickMethod method not found", e); } catch (InvocationTargetException e) { throw new RuntimeException("Preference.performClickMethod failed", e); } catch (IllegalAccessException e) { throw new RuntimeException("Failed to access Preference.performClickMethod", e); } } /** * Waits until the window which contains the provided view has focus. */ public static void waitForWindowFocus(View view) throws InterruptedException, TimeoutException { long deadline = SystemClock.uptimeMillis() + UI_ACTION_EFFECT_TIMEOUT_MILLIS; while (!view.hasWindowFocus()) { long millisTillDeadline = deadline - SystemClock.uptimeMillis(); if (millisTillDeadline < 0) { throw new TimeoutException("Timed out while waiting for window focus"); } Thread.sleep(50); } } /** * Waits until the {@link Activity} is finishing. */ public static void waitForActivityFinishing(Activity activity) throws InterruptedException, TimeoutException { long deadline = SystemClock.uptimeMillis() + UI_ACTION_EFFECT_TIMEOUT_MILLIS; while (!activity.isFinishing()) { long millisTillDeadline = deadline - SystemClock.uptimeMillis(); if (millisTillDeadline < 0) { throw new TimeoutException("Timed out while waiting for activity to start finishing"); } Thread.sleep(50); } } /** * Invokes the {@link Activity}'s {@code onBackPressed()} on the UI thread and blocks (with * a timeout) the calling thread until the invocation completes. If the calling thread is the UI * thread, the {@code finish} is invoked directly and without a timeout. */ public static void invokeActivityOnBackPressedOnUiThread(final Activity activity) throws InterruptedException, TimeoutException { FutureTask<Void> finishTask = new FutureTask<Void>(new Runnable() { @Override public void run() { activity.onBackPressed(); } }, null); activity.runOnUiThread(finishTask); try { finishTask.get(UI_ACTION_EFFECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); } catch (ExecutionException e) { throw new RuntimeException("Activity.onBackPressed() failed", e); } } /** * Invokes the {@link Activity}'s {@code finish()} on the UI thread and blocks (with * a timeout) the calling thread until the invocation completes. If the calling thread is the UI * thread, the {@code finish} is invoked directly and without a timeout. */ public static void invokeFinishActivityOnUiThread(final Activity activity) throws InterruptedException, TimeoutException { FutureTask<Void> finishTask = new FutureTask<Void>(new Runnable() { @Override public void run() { activity.finish(); } }, null); activity.runOnUiThread(finishTask); try { finishTask.get(UI_ACTION_EFFECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); } catch (ExecutionException e) { throw new RuntimeException("Activity.finish() failed", e); } } private static boolean isViewAndAllItsParentsVisible(View view) { if (view.getVisibility() != View.VISIBLE) { return false; } ViewParent parent = view.getParent(); if (!(parent instanceof View)) { // This View is the root of the View hierarche, and it's visible (checked above) return true; } // This View itself is actually visible only all of its parents are visible. return isViewAndAllItsParentsVisible((View) parent); } private static boolean isViewOrAnyParentVisibilityGone(View view) { if (view.getVisibility() == View.GONE) { return true; } ViewParent parent = view.getParent(); if (!(parent instanceof View)) { // This View is the root of the View hierarchy, and its visibility is not GONE (checked above) return false; } // This View itself is actually visible only all of its parents are visible. return isViewOrAnyParentVisibilityGone((View) parent); } /** * Asserts that the provided {@link View} and all its parents are visible. */ public static void assertViewAndAllItsParentsVisible(View view) { Assert.assertTrue(isViewAndAllItsParentsVisible(view)); } /** * Asserts that the provided {@link View} and all its parents are visible. */ public static void assertViewOrAnyParentVisibilityGone(View view) { Assert.assertTrue(isViewOrAnyParentVisibilityGone(view)); } /** * Asserts that the provided {@link View} is on the screen and is visible (which means its parent * and the parent of its parent and so forth are visible too). */ public static void assertViewVisibleOnScreen(View view) { ViewAsserts.assertOnScreen(view.getRootView(), view); assertViewAndAllItsParentsVisible(view); } /** * Opens the options menu of the provided {@link Activity} and invokes the menu item with the * provided ID. * * Note: This method cannot be invoked on the main thread. */ public static void openOptionsMenuAndInvokeItem( Instrumentation instrumentation, final Activity activity, final int itemId) { if (!instrumentation.invokeMenuActionSync(activity, itemId, 0)) { throw new RuntimeException("Failed to invoke options menu item ID " + itemId); } instrumentation.waitForIdleSync(); } /** * Opens the context menu for the provided {@link View} and invokes the menu item with the * provided ID. * * Note: This method cannot be invoked on the main thread. */ public static void openContextMenuAndInvokeItem( Instrumentation instrumentation, final Activity activity, final View view, final int itemId) { // IMPLEMENTATION NOTE: Instrumentation.invokeContextMenuAction would've been much simpler, but // it doesn't work on ICS because its KEY_UP event times out. FutureTask<Boolean> task = new FutureTask<Boolean>(new Callable<Boolean>() { @Override public Boolean call() { // Use performLongClick instead of showContextMenu to exercise more of the code path that // is invoked when the user normally opens a context menu. view.performLongClick(); return activity.getWindow().performContextMenuIdentifierAction(itemId, 0); } }); instrumentation.runOnMainSync(task); try { if (!task.get()) { throw new RuntimeException("Failed to invoke context menu item with ID " + itemId); } } catch (Exception e) { throw new RuntimeException("Failed to open context menu and select a menu item", e); } instrumentation.waitForIdleSync(); } /** * Asserts that the provided {@link Activity} displayed a dialog with the provided ID at some * point in the past. Note that this does not necessarily mean that the dialog is still being * displayed. * * <p> * <b>Note:</b> this method resets the "was displayed" state of the dialog. This means that a * consecutive invocation of this method for the same dialog ID will fail unless the dialog * was displayed again prior to the invocation of this method. */ public static void assertDialogWasDisplayed(Activity activity, int dialogId) { // IMPLEMENTATION NOTE: This code below relies on the fact that, if a dialog with the ID was // every displayed, then dismissDialog will succeed, whereas if the dialog with the ID has // never been shown, then dismissDialog throws an IllegalArgumentException. try { activity.dismissDialog(dialogId); // Reset the "was displayed" state activity.removeDialog(dialogId); } catch (IllegalArgumentException e) { Assert.fail("No dialog with ID " + dialogId + " was ever displayed"); } } /** * Taps the positive button of a currently displayed dialog. This method assumes that a button * of the dialog is currently selected. * * @see #tapDialogNegativeButton(InstrumentationTestCase) */ public static void tapDialogNegativeButton(InstrumentationTestCase testCase) { // The order of the buttons is reversed from ICS onwards if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { testCase.sendKeys("DPAD_RIGHT DPAD_CENTER"); } else { testCase.sendKeys("DPAD_LEFT DPAD_CENTER"); } } /** * Taps the negative button of a currently displayed dialog. This method assumes that a button * of the dialog is currently selected. * * @see #tapDialogNegativeButton(InstrumentationTestCase) */ public static void tapDialogPositiveButton(InstrumentationTestCase testCase) { // The order of the buttons is reversed from ICS onwards if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { testCase.sendKeys("DPAD_LEFT DPAD_CENTER"); } else { testCase.sendKeys("DPAD_RIGHT DPAD_CENTER"); } } /** * Taps the negative button of a currently displayed 3 button dialog. This method assumes * that a button of the dialog is currently selected. */ public static void tapNegativeButtonIn3ButtonDialog(InstrumentationTestCase testCase) { // The order of the buttons is reversed from ICS onwards if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { testCase.sendKeys("DPAD_RIGHT DPAD_RIGHT DPAD_CENTER"); } else { testCase.sendKeys("DPAD_LEFT DPAD_LEFT DPAD_CENTER"); } } /** * Taps the neutral button of a currently displayed 3 button dialog. This method assumes * that a button of the dialog is currently selected. */ public static void tapNeutralButtonIn3ButtonDialog(InstrumentationTestCase testCase) { // The order of the buttons is reversed from ICS onwards if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { testCase.sendKeys("DPAD_RIGHT DPAD_CENTER"); } else { testCase.sendKeys("DPAD_RIGHT DPAD_CENTER"); } } /** * Taps the positive button of a currently displayed 3 button dialog. This method assumes * that a button of the dialog is currently selected. */ public static void tapPositiveButtonIn3ButtonDialog(InstrumentationTestCase testCase) { // The order of the buttons is reversed from ICS onwards if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { testCase.sendKeys("DPAD_LEFT DPAD_LEFT DPAD_CENTER"); } else { testCase.sendKeys("DPAD_RIGHT DPAD_RIGHT DPAD_CENTER"); } } /** * Configures the {@link DependencyInjector} with a {@link StartActivityListener} that prevents * activity launches. */ public static void withLaunchPreventingStartActivityListenerInDependencyResolver() { StartActivityListener mockListener = Mockito.mock(StartActivityListener.class); doReturn(true).when(mockListener).onStartActivityInvoked( Mockito.<Context>anyObject(), Mockito.<Intent>anyObject()); DependencyInjector.setStartActivityListener(mockListener); } /** * Verifies (with a timeout of {@link #UI_ACTION_EFFECT_TIMEOUT_MILLIS}) that an activity launch * has been attempted and returns the {@link Intent} with which the attempt occurred. * * <p><b>NOTE: This method assumes that the {@link DependencyInjector} was configured * using {@link #withLaunchPreventingStartActivityListenerInDependencyResolver()}.</b> */ public static Intent verifyWithTimeoutThatStartActivityAttemptedExactlyOnce() { StartActivityListener mockListener = DependencyInjector.getStartActivityListener(); ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); verify(mockListener, timeout(UI_ACTION_EFFECT_TIMEOUT_MILLIS)) .onStartActivityInvoked(Mockito.<Context>anyObject(), intentCaptor.capture()); return intentCaptor.getValue(); } public static void assertLessThanOrEquals(long expected, long actual) { if (actual > expected) { Assert.fail(actual + " > " + expected); } } /* * Returns the x and y coordinates of center of view in pixels. */ public static Point getCenterOfViewOnScreen( InstrumentationTestCase instr, View view) { int[] location = new int[2]; view.getLocationOnScreen(location); int width = view.getWidth(); int height = view.getHeight(); final int center_x = location[0] + width / 2; final int center_y = location[1] + height / 2; return new Point(center_x, center_y); } /* * returns the pixel value at the right side end of the view. */ public static int getRightXofViewOnScreen(View view) { int[] location = new int[2]; view.getLocationOnScreen(location); int width = view.getWidth(); return location[0] + width; } /* * returns the pixel value at the left side end of the view. */ public static int getLeftXofViewOnScreen(View view) { int[] location = new int[2]; view.getLocationOnScreen(location); return location[0]; } /* * Drags from the center of the view to the toX value. * This methods exists in TouchUtil, however, it has a bug which causes it to work * while dragging on the left side, but not on the right side, hence, we * had to recreate it here. */ public static int dragViewToX(InstrumentationTestCase test, View v, int gravity, int toX) { if (gravity != Gravity.CENTER) { throw new IllegalArgumentException("Can only handle Gravity.CENTER."); } Point point = getCenterOfViewOnScreen(test, v); final int fromX = point.x; final int fromY = point.y; int deltaX = Math.abs(fromX - toX); TouchUtils.drag(test, fromX, toX, fromY, fromY, deltaX); return deltaX; } }
/* * Copyright 2010, Mysema Ltd * * 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.querydsl.codegen.utils; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.Stack; import java.util.function.Function; import com.querydsl.codegen.utils.model.Parameter; import com.querydsl.codegen.utils.model.Type; /** * JavaWriter is the default implementation of the CodeWriter interface * * @author tiwe * */ public final class JavaWriter extends AbstractCodeWriter<JavaWriter> { private static final String EXTENDS = " extends "; private static final String IMPLEMENTS = " implements "; private static final String IMPORT = "import "; private static final String IMPORT_STATIC = "import static "; private static final String PACKAGE = "package "; private static final String PRIVATE = "private "; private static final String PRIVATE_FINAL = "private final "; private static final String PRIVATE_STATIC_FINAL = "private static final "; private static final String PROTECTED = "protected "; private static final String PROTECTED_FINAL = "protected final "; private static final String PUBLIC = "public "; private static final String PUBLIC_CLASS = "public class "; private static final String PUBLIC_FINAL = "public final "; private static final String PUBLIC_INTERFACE = "public interface "; private static final String PUBLIC_STATIC = "public static "; private static final String PUBLIC_STATIC_FINAL = "public static final "; private final Set<String> classes = new HashSet<String>(); private final Set<String> packages = new HashSet<String>(); private final Stack<Type> types = new Stack<Type>(); public JavaWriter(Appendable appendable) { super(appendable, 4); this.packages.add("java.lang"); } @Override public JavaWriter annotation(Annotation annotation) throws IOException { beginLine().append("@").appendType(annotation.annotationType()); Method[] methods = annotation.annotationType().getDeclaredMethods(); if (methods.length == 1 && methods[0].getName().equals("value")) { try { Object value = methods[0].invoke(annotation); append("("); annotationConstant(value); append(")"); } catch (IllegalArgumentException e) { throw new CodegenException(e); } catch (IllegalAccessException e) { throw new CodegenException(e); } catch (InvocationTargetException e) { throw new CodegenException(e); } } else { boolean first = true; for (Method method : methods) { try { Object value = method.invoke(annotation); if (value == null || value.equals(method.getDefaultValue())) { continue; } else if (value.getClass().isArray() && Arrays.equals((Object[]) value, (Object[]) method.getDefaultValue())) { continue; } else if (!first) { append(Symbols.COMMA); } else { append("("); } append(method.getName()).append("="); annotationConstant(value); } catch (IllegalArgumentException e) { throw new CodegenException(e); } catch (IllegalAccessException e) { throw new CodegenException(e); } catch (InvocationTargetException e) { throw new CodegenException(e); } first = false; } if (!first) { append(")"); } } return nl(); } @Override public JavaWriter annotation(Class<? extends Annotation> annotation) throws IOException { return beginLine().append("@").appendType(annotation).nl(); } @SuppressWarnings("unchecked") private void annotationConstant(Object value) throws IOException { if (value.getClass().isArray()) { append("{"); boolean first = true; for (Object o : (Object[]) value) { if (!first) { append(", "); } annotationConstant(o); first = false; } append("}"); } else if (value instanceof Class) { appendType((Class) value).append(".class"); } else if (value instanceof Number || value instanceof Boolean) { append(value.toString()); } else if (value instanceof Enum) { Enum<?> enumValue = (Enum<?>) value; if (classes.contains(enumValue.getClass().getName()) || packages.contains(enumValue.getClass().getPackage().getName())) { append(enumValue.name()); } else { append(enumValue.getDeclaringClass().getName()).append(Symbols.DOT).append(enumValue.name()); } } else if (value instanceof String) { String escaped = StringUtils.escapeJava(value.toString()); append(Symbols.QUOTE).append(escaped.replace("\\/", "/")).append(Symbols.QUOTE); } else { throw new IllegalArgumentException("Unsupported annotation value : " + value); } } private JavaWriter appendType(Class<?> type) throws IOException { if (classes.contains(type.getName()) || packages.contains(type.getPackage().getName())) { append(type.getSimpleName()); } else { append(type.getName()); } return this; } @Override public JavaWriter beginClass(Type type) throws IOException { return beginClass(type, null); } @Override public JavaWriter beginClass(Type type, Type superClass, Type... interfaces) throws IOException { packages.add(type.getPackageName()); beginLine(PUBLIC_CLASS, type.getGenericName(false, packages, classes)); if (superClass != null) { append(EXTENDS).append(superClass.getGenericName(false, packages, classes)); } if (interfaces.length > 0) { append(IMPLEMENTS); for (int i = 0; i < interfaces.length; i++) { if (i > 0) { append(Symbols.COMMA); } append(interfaces[i].getGenericName(false, packages, classes)); } } append(" {").nl().nl(); goIn(); types.push(type); return this; } @Override public <T> JavaWriter beginConstructor(Collection<T> parameters, Function<T, Parameter> transformer) throws IOException { types.push(types.peek()); beginLine(PUBLIC, types.peek().getSimpleName()).params(parameters, transformer) .append(" {").nl(); return goIn(); } @Override public JavaWriter beginConstructor(Parameter... parameters) throws IOException { types.push(types.peek()); beginLine(PUBLIC, types.peek().getSimpleName()).params(parameters).append(" {").nl(); return goIn(); } @Override public JavaWriter beginInterface(Type type, Type... interfaces) throws IOException { packages.add(type.getPackageName()); beginLine(PUBLIC_INTERFACE, type.getGenericName(false, packages, classes)); if (interfaces.length > 0) { append(EXTENDS); for (int i = 0; i < interfaces.length; i++) { if (i > 0) { append(Symbols.COMMA); } append(interfaces[i].getGenericName(false, packages, classes)); } } append(" {").nl().nl(); goIn(); types.push(type); return this; } private JavaWriter beginMethod(String modifiers, Type returnType, String methodName, Parameter... args) throws IOException { types.push(types.peek()); beginLine( modifiers, returnType.getGenericName(true, packages, classes), Symbols.SPACE, methodName) .params(args).append(" {").nl(); return goIn(); } @Override public <T> JavaWriter beginPublicMethod(Type returnType, String methodName, Collection<T> parameters, Function<T, Parameter> transformer) throws IOException { return beginMethod(PUBLIC, returnType, methodName, transform(parameters, transformer)); } @Override public JavaWriter beginPublicMethod(Type returnType, String methodName, Parameter... args) throws IOException { return beginMethod(PUBLIC, returnType, methodName, args); } @Override public <T> JavaWriter beginStaticMethod(Type returnType, String methodName, Collection<T> parameters, Function<T, Parameter> transformer) throws IOException { return beginMethod(PUBLIC_STATIC, returnType, methodName, transform(parameters, transformer)); } @Override public JavaWriter beginStaticMethod(Type returnType, String methodName, Parameter... args) throws IOException { return beginMethod(PUBLIC_STATIC, returnType, methodName, args); } @Override public JavaWriter end() throws IOException { types.pop(); goOut(); return line("}").nl(); } @Override public JavaWriter field(Type type, String name) throws IOException { return line(type.getGenericName(true, packages, classes), Symbols.SPACE, name, Symbols.SEMICOLON).nl(); } private JavaWriter field(String modifier, Type type, String name) throws IOException { return line( modifier, type.getGenericName(true, packages, classes), Symbols.SPACE, name, Symbols.SEMICOLON) .nl(); } private JavaWriter field(String modifier, Type type, String name, String value) throws IOException { return line( modifier, type.getGenericName(true, packages, classes), Symbols.SPACE, name, Symbols.ASSIGN , value, Symbols.SEMICOLON).nl(); } @Override public String getClassConstant(String className) { return className + ".class"; } @Override public String getGenericName(boolean asArgType, Type type) { return type.getGenericName(asArgType, packages, classes); } @Override public String getRawName(Type type) { return type.getRawName(packages, classes); } @Override public JavaWriter imports(Class<?>... imports) throws IOException { for (Class<?> cl : imports) { classes.add(cl.getName()); line(IMPORT, cl.getName(), Symbols.SEMICOLON); } nl(); return this; } @Override public JavaWriter imports(Package... imports) throws IOException { for (Package p : imports) { packages.add(p.getName()); line(IMPORT, p.getName(), ".*;"); } nl(); return this; } @Override public JavaWriter importClasses(String... imports) throws IOException { for (String cl : imports) { classes.add(cl); line(IMPORT, cl, Symbols.SEMICOLON); } nl(); return this; } @Override public JavaWriter importPackages(String... imports) throws IOException { for (String p : imports) { packages.add(p); line(IMPORT, p, ".*;"); } nl(); return this; } @Override public JavaWriter javadoc(String... lines) throws IOException { line("/**"); for (String line : lines) { line(" * ", line); } return line(" */"); } @Override public JavaWriter packageDecl(String packageName) throws IOException { packages.add(packageName); return line(PACKAGE, packageName, Symbols.SEMICOLON).nl(); } private <T> JavaWriter params(Collection<T> parameters, Function<T, Parameter> transformer) throws IOException { append("("); boolean first = true; for (T param : parameters) { if (!first) { append(Symbols.COMMA); } param(transformer.apply(param)); first = false; } append(")"); return this; } private JavaWriter params(Parameter... params) throws IOException { append("("); for (int i = 0; i < params.length; i++) { if (i > 0) { append(Symbols.COMMA); } param(params[i]); } append(")"); return this; } private JavaWriter param(Parameter parameter) throws IOException { append(parameter.getType().getGenericName(true, packages, classes)); append(" "); append(parameter.getName()); return this; } @Override public JavaWriter privateField(Type type, String name) throws IOException { return field(PRIVATE, type, name); } @Override public JavaWriter privateFinal(Type type, String name) throws IOException { return field(PRIVATE_FINAL, type, name); } @Override public JavaWriter privateFinal(Type type, String name, String value) throws IOException { return field(PRIVATE_FINAL, type, name, value); } @Override public JavaWriter privateStaticFinal(Type type, String name, String value) throws IOException { return field(PRIVATE_STATIC_FINAL, type, name, value); } @Override public JavaWriter protectedField(Type type, String name) throws IOException { return field(PROTECTED, type, name); } @Override public JavaWriter protectedFinal(Type type, String name) throws IOException { return field(PROTECTED_FINAL, type, name); } @Override public JavaWriter protectedFinal(Type type, String name, String value) throws IOException { return field(PROTECTED_FINAL, type, name, value); } @Override public JavaWriter publicField(Type type, String name) throws IOException { return field(PUBLIC, type, name); } @Override public JavaWriter publicField(Type type, String name, String value) throws IOException { return field(PUBLIC, type, name, value); } @Override public JavaWriter publicFinal(Type type, String name) throws IOException { return field(PUBLIC_FINAL, type, name); } @Override public JavaWriter publicFinal(Type type, String name, String value) throws IOException { return field(PUBLIC_FINAL, type, name, value); } @Override public JavaWriter publicStaticFinal(Type type, String name, String value) throws IOException { return field(PUBLIC_STATIC_FINAL, type, name, value); } @Override public JavaWriter staticimports(Class<?>... imports) throws IOException { for (Class<?> cl : imports) { line(IMPORT_STATIC, cl.getName(), ".*;"); } return this; } @Override public JavaWriter suppressWarnings(String type) throws IOException { return line("@SuppressWarnings(\"", type, "\")"); } @Override public CodeWriter suppressWarnings(String... types) throws IOException { return annotation(new MultiSuppressWarnings(types)); } private <T> Parameter[] transform(Collection<T> parameters, Function<T, Parameter> transformer) { Parameter[] rv = new Parameter[parameters.size()]; int i = 0; for (T value : parameters) { rv[i++] = transformer.apply(value); } return rv; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package menuPrePartita; import dominio.eccezioni.NumeroBotException; import dominio.eccezioni.DifficoltaBotException; import dominio.eccezioni.FichesInizialiException; import dominio.classi_dati.DifficoltaBot; import dominio.gui.Sfondo; import java.awt.Dimension; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JTextField; import moduli.PartitaOfflineGui; public class MenuPrePartitaGui extends JFrame{ private Sfondo sfondo; private JButton bot1, bot2, bot3, bot4; private ImageIcon dado1, dado1x, dado2, dado2x, dado3, dado3x, dado4, dado4x; private JButton diffFacile, diffMedia, diffDifficile, gioca; private JButton indietro; private ImageIcon facile1, facile2, medio1, medio2, difficile1, difficile2; private JTextField fiches; private String fiches_iniziali_inserite; private int numero_bot, fiches_iniziali; private DifficoltaBot difficolta_bot; public MenuPrePartitaGui() { setTitle("Impostazioni partita offline"); setPreferredSize(new Dimension(1000, 800)); setMinimumSize(new Dimension(1000, 800)); pack(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setResizable(false); setLocationRelativeTo(null); getContentPane().setLayout(null); inizializzaGUI(); } private void inizializzaGUI() { sfondo = new Sfondo("dominio/immagini/sfondoPreOffline.jpg", 1000, 800); sfondo.setBounds(0, 0, 1000, 800); add(sfondo); facile1 = caricaImmagine("dominio/immagini/facile.png"); facile2 = caricaImmagine("dominio/immagini/facile2.png"); medio1 = caricaImmagine("dominio/immagini/medio.png"); medio2 = caricaImmagine("dominio/immagini/medio2.png"); difficile1 = caricaImmagine("dominio/immagini/difficile.png"); difficile2 = caricaImmagine("dominio/immagini/difficile2.png"); dado1 = caricaImmagine("dominio/immagini/dado1.png"); dado1x = caricaImmagine("dominio/immagini/dado1X.png"); dado2 = caricaImmagine("dominio/immagini/dado2.png"); dado2x = caricaImmagine("dominio/immagini/dado2X.png"); dado3 = caricaImmagine("dominio/immagini/dado3.png"); dado3x = caricaImmagine("dominio/immagini/dado3X.png"); dado4 = caricaImmagine("dominio/immagini/dado4.png"); dado4x = caricaImmagine("dominio/immagini/dado4X.png"); bot1 = new JButton(dado1); bot2 = new JButton(dado2); bot3 = new JButton(dado3); bot4 = new JButton(dado4); diffFacile = new JButton(facile1); diffMedia = new JButton(medio1); diffDifficile = new JButton(difficile1); indietro = new JButton(caricaImmagine("dominio/immagini/indietro.png")); gioca = new JButton(caricaImmagine("dominio/immagini/gioca!.png")); fiches = new JTextField(); bot1.setBounds(250, 215, 54, 54); bot2.setBounds(400, 215, 54, 54); bot3.setBounds(550, 215, 54, 54); bot4.setBounds(700, 215, 54, 54); diffFacile.setBounds(250, 350, 200, 80); diffMedia.setBounds(500, 350, 200, 80); diffDifficile.setBounds(750, 350, 200, 80); indietro.setBounds(100, 680, 200, 80); gioca.setBounds(700, 680, 200, 80); fiches.setBounds(375, 500, 200, 80); fiches.setFont(new Font("fiches", 1, 35)); bot1.setOpaque(false); bot1.setContentAreaFilled(false); bot1.setBorderPainted(false); bot2.setOpaque(false); bot2.setContentAreaFilled(false); bot2.setBorderPainted(false); bot3.setOpaque(false); bot3.setContentAreaFilled(false); bot3.setBorderPainted(false); bot4.setOpaque(false); bot4.setContentAreaFilled(false); bot4.setBorderPainted(false); bot1.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { bot1.setIcon(dado1x); bot2.setIcon(dado2); bot3.setIcon(dado3); bot4.setIcon(dado4); bot1.repaint(); bot2.repaint(); bot3.repaint(); bot4.repaint(); numero_bot = 1; }; }); bot2.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { bot1.setIcon(dado1); bot2.setIcon(dado2x); bot3.setIcon(dado3); bot4.setIcon(dado4); bot1.repaint(); bot2.repaint(); bot3.repaint(); bot4.repaint(); numero_bot = 2; }; }); bot3.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { bot1.setIcon(dado1); bot2.setIcon(dado2); bot3.setIcon(dado3x); bot4.setIcon(dado4); bot1.repaint(); bot2.repaint(); bot3.repaint(); bot4.repaint(); numero_bot = 3; }; }); bot4.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { bot1.setIcon(dado1); bot2.setIcon(dado2); bot3.setIcon(dado3); bot4.setIcon(dado4x); bot1.repaint(); bot2.repaint(); bot3.repaint(); bot4.repaint(); numero_bot = 4; }; }); diffFacile.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { diffFacile.setIcon(facile2); diffMedia.setIcon(medio1); diffDifficile.setIcon(difficile1); diffFacile.repaint(); diffMedia.repaint(); diffDifficile.repaint(); difficolta_bot = DifficoltaBot.Facile; }; }); diffMedia.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { diffMedia.setIcon(medio2); diffFacile.setIcon(facile1); diffDifficile.setIcon(difficile1); diffFacile.repaint(); diffMedia.repaint(); diffDifficile.repaint(); difficolta_bot = DifficoltaBot.Medio; }; }); diffDifficile.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { diffDifficile.setIcon(difficile2); diffFacile.setIcon(facile1); diffMedia.setIcon(medio1); diffFacile.repaint(); diffMedia.repaint(); diffDifficile.repaint(); difficolta_bot = DifficoltaBot.Difficile; }; }); gioca.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { fiches_iniziali_inserite = fiches.getText(); try { NuovaPartita(); } catch (FichesInizialiException ex) { JOptionPane.showMessageDialog(null, "Errore: Il numero di fiches iniziali dev'essere un numero compreso tra 1 e 100000000.", "Errore", JOptionPane.ERROR_MESSAGE); } catch (NumeroBotException ex) { JOptionPane.showMessageDialog(null, "Errore: Selezionare il numero di bot.", "Errore", JOptionPane.ERROR_MESSAGE); } catch (DifficoltaBotException ex) { JOptionPane.showMessageDialog(null, "Errore: Selezionare la difficolta dei bot.", "Errore", JOptionPane.ERROR_MESSAGE); } }; }); sfondo.add(bot1); sfondo.add(bot2); sfondo.add(bot3); sfondo.add(bot4); sfondo.add(diffFacile); sfondo.add(diffMedia); sfondo.add(diffDifficile); sfondo.add(indietro); sfondo.add(gioca); sfondo.add(fiches); } private ImageIcon caricaImmagine(String nome){ ClassLoader loader = getClass().getClassLoader(); URL percorso = loader.getResource(nome); return new ImageIcon(percorso); } private void NuovaPartita() throws NumeroBotException, FichesInizialiException, DifficoltaBotException{ checkFichesIniziali(); checkNumeroBot(); checkDifficoltaBot(); this.setVisible(false); new PartitaOfflineGui(numero_bot, difficolta_bot, fiches_iniziali, this); } private void checkFichesIniziali() throws FichesInizialiException{ try{ fiches_iniziali = Integer.valueOf(fiches_iniziali_inserite); if(fiches_iniziali < 1 || fiches_iniziali > 100000000){ throw new FichesInizialiException(); } }catch(NumberFormatException e){ throw new FichesInizialiException(); } } private void checkNumeroBot() throws NumeroBotException { if(numero_bot == 0){ throw new NumeroBotException(); } } private void checkDifficoltaBot() throws DifficoltaBotException { if(difficolta_bot == null){ throw new DifficoltaBotException(); } } /** * aggiunge un action listener * @param l */ public void addIndietroActionListener(ActionListener l){ indietro.addActionListener(l); } }
/* * Copyright 2013-2017 consulo.io * * 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 consulo.wm.impl; import com.intellij.ide.UiActivity; import com.intellij.ide.UiActivityMonitor; import com.intellij.ide.impl.ContentManagerWatcher; import com.intellij.openapi.actionSystem.ActionGroup; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.wm.ToolWindowAnchor; import com.intellij.openapi.wm.ToolWindowContentUiType; import com.intellij.openapi.wm.ToolWindowFactory; import com.intellij.openapi.wm.ToolWindowType; import com.intellij.openapi.wm.ex.ToolWindowEx; import com.intellij.ui.content.Content; import com.intellij.ui.content.ContentManager; import com.intellij.ui.content.impl.ContentImpl; import consulo.localize.LocalizeValue; import consulo.logging.Logger; import consulo.ui.UIAccess; import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.ToolWindowInternalDecorator; import consulo.ui.image.Image; import consulo.ui.Rectangle2D; import kava.beans.PropertyChangeListener; import kava.beans.PropertyChangeSupport; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * @author VISTALL * @since 14-Oct-17 * <p> * Extracted part independent part from IDEA ToolWindowImpl (named DesktopToolWindowImpl) */ public abstract class ToolWindowBase implements ToolWindowEx { private static final Logger LOG = Logger.getInstance(ToolWindowBase.class); protected final ToolWindowManagerBase myToolWindowManager; protected ContentManager myContentManager; private final PropertyChangeSupport myChangeSupport; private final String myId; private LocalizeValue myDisplayName; protected boolean myAvailable; private ToolWindowInternalDecorator myDecorator; private boolean myHideOnEmptyContent = false; private boolean myPlaceholderMode; private ToolWindowFactory myContentFactory; private Image myIcon; private boolean myUseLastFocused = true; @RequiredUIAccess protected ToolWindowBase(final ToolWindowManagerBase toolWindowManager, String id, LocalizeValue displayName, boolean canCloseContent, @Nullable Object component, boolean available) { myToolWindowManager = toolWindowManager; myChangeSupport = new PropertyChangeSupport(this); myId = id; myDisplayName = displayName; myAvailable = available; init(canCloseContent, component); } @RequiredUIAccess protected abstract void init(boolean canCloseContent, @Nullable Object component); @Nonnull @Override public LocalizeValue getDisplayName() { return myDisplayName; } @Override public void setDisplayName(@Nonnull LocalizeValue displayName) { myDisplayName = displayName; } @Override public final void addPropertyChangeListener(final PropertyChangeListener l) { myChangeSupport.addPropertyChangeListener(l); } @Override public final void removePropertyChangeListener(final PropertyChangeListener l) { myChangeSupport.removePropertyChangeListener(l); } @RequiredUIAccess @Override public final void activate(final Runnable runnable) { activate(runnable, true); } @RequiredUIAccess @Override public void activate(@Nullable final Runnable runnable, final boolean autoFocusContents) { activate(runnable, autoFocusContents, true); } @RequiredUIAccess @Override public void activate(@Nullable final Runnable runnable, boolean autoFocusContents, boolean forced) { UIAccess.assertIsUIThread(); final UiActivity activity = new UiActivity.Focus("toolWindow:" + myId); UiActivityMonitor.getInstance().addActivity(myToolWindowManager.getProject(), activity, ModalityState.NON_MODAL); myToolWindowManager.activateToolWindow(myId, forced, autoFocusContents); myToolWindowManager.invokeLater(() -> { if (runnable != null) { runnable.run(); } UiActivityMonitor.getInstance().removeActivity(myToolWindowManager.getProject(), activity); }); } @RequiredUIAccess @Override public final boolean isActive() { UIAccess.assertIsUIThread(); if (myToolWindowManager.isEditorComponentActive()) return false; return myToolWindowManager.isToolWindowActive(myId) || myDecorator != null && myDecorator.isFocused(); } @RequiredUIAccess @Override public final void show(final Runnable runnable) { UIAccess.assertIsUIThread(); myToolWindowManager.showToolWindow(myId); if (runnable != null) { myToolWindowManager.invokeLater(runnable); } } @RequiredUIAccess @Override public final void hide(@Nullable final Runnable runnable) { UIAccess.assertIsUIThread(); myToolWindowManager.hideToolWindow(myId, false); if (runnable != null) { myToolWindowManager.invokeLater(runnable); } } @Override public final boolean isVisible() { return myToolWindowManager.isToolWindowRegistered(myId) && myToolWindowManager.isToolWindowVisible(myId); } @Override public final ToolWindowAnchor getAnchor() { return myToolWindowManager.getToolWindowAnchor(myId); } @RequiredUIAccess @Override public final void setAnchor(@Nonnull final ToolWindowAnchor anchor, @Nullable final Runnable runnable) { UIAccess.assertIsUIThread(); myToolWindowManager.setToolWindowAnchor(myId, anchor); if (runnable != null) { myToolWindowManager.invokeLater(runnable); } } @RequiredUIAccess @Override public boolean isSplitMode() { UIAccess.assertIsUIThread(); return myToolWindowManager.isSplitMode(myId); } @RequiredUIAccess @Override public void setContentUiType(@Nonnull ToolWindowContentUiType type, @Nullable Runnable runnable) { UIAccess.assertIsUIThread(); myToolWindowManager.setContentUiType(myId, type); if (runnable != null) { myToolWindowManager.invokeLater(runnable); } } @Override public void setDefaultContentUiType(@Nonnull ToolWindowContentUiType type) { myToolWindowManager.setDefaultContentUiType(this, type); } @RequiredUIAccess @Nonnull @Override public ToolWindowContentUiType getContentUiType() { UIAccess.assertIsUIThread(); return myToolWindowManager.getContentUiType(myId); } @RequiredUIAccess @Override public void setSplitMode(final boolean isSideTool, @Nullable final Runnable runnable) { UIAccess.assertIsUIThread(); myToolWindowManager.setSideTool(myId, isSideTool); if (runnable != null) { myToolWindowManager.invokeLater(runnable); } } @RequiredUIAccess @Override public final void setAutoHide(final boolean state) { UIAccess.assertIsUIThread(); myToolWindowManager.setToolWindowAutoHide(myId, state); } @RequiredUIAccess @Override public final boolean isAutoHide() { UIAccess.assertIsUIThread(); return myToolWindowManager.isToolWindowAutoHide(myId); } @Nonnull @Override public final ToolWindowType getType() { return myToolWindowManager.getToolWindowType(myId); } @RequiredUIAccess @Override public final void setType(@Nonnull final ToolWindowType type, @Nullable final Runnable runnable) { UIAccess.assertIsUIThread(); myToolWindowManager.setToolWindowType(myId, type); if (runnable != null) { myToolWindowManager.invokeLater(runnable); } } @RequiredUIAccess @Override public final ToolWindowType getInternalType() { UIAccess.assertIsUIThread(); return myToolWindowManager.getToolWindowInternalType(myId); } @Override public ToolWindowInternalDecorator getDecorator() { return myDecorator; } @Override public void setAdditionalGearActions(ActionGroup additionalGearActions) { getDecorator().setAdditionalGearActions(additionalGearActions); } @Override public void setTitleActions(@Nonnull AnAction... actions) { getDecorator().setTitleActions(actions); } @Override public void setTabActions(@Nonnull AnAction... actions) { getDecorator().setTabActions(actions); } @RequiredUIAccess @Override public final void setAvailable(final boolean available, final Runnable runnable) { UIAccess.assertIsUIThread(); final Boolean oldAvailable = myAvailable ? Boolean.TRUE : Boolean.FALSE; myAvailable = available; myChangeSupport.firePropertyChange(PROP_AVAILABLE, oldAvailable, myAvailable ? Boolean.TRUE : Boolean.FALSE); if (runnable != null) { myToolWindowManager.invokeLater(runnable); } } @Override public void installWatcher(@Nonnull ContentManager contentManager) { new ContentManagerWatcher(this, contentManager); } /** * @return <code>true</code> if the component passed into constructor is not instance of * <code>ContentManager</code> class. Otherwise it delegates the functionality to the * passed content manager. */ @Override public boolean isAvailable() { return myAvailable; } @Nonnull @Override public ContentManager getContentManager() { ensureContentInitialized(); return myContentManager; } @Nullable @Override public ContentManager getContentManagerIfCreated() { return myContentManager; } @Override @Nonnull public final String getId() { return myId; } @RequiredUIAccess @Override public final String getTitle() { UIAccess.assertIsUIThread(); return getSelectedContent().getDisplayName(); } @RequiredUIAccess @Override public final void setTitle(String title) { UIAccess.assertIsUIThread(); String oldTitle = getTitle(); getSelectedContent().setDisplayName(title); myChangeSupport.firePropertyChange(PROP_TITLE, oldTitle, title); } private Content getSelectedContent() { final Content selected = getContentManager().getSelectedContent(); return selected != null ? selected : EMPTY_CONTENT; } public void setDecorator(final ToolWindowInternalDecorator decorator) { myDecorator = decorator; } public void fireActivated() { if (myDecorator != null) { myDecorator.fireActivated(); } } public void fireHidden() { if (myDecorator != null) { myDecorator.fireHidden(); } } public void fireHiddenSide() { if (myDecorator != null) { myDecorator.fireHiddenSide(); } } public ToolWindowManagerBase getToolWindowManager() { return myToolWindowManager; } @Nullable public ActionGroup getPopupGroup() { return myDecorator != null ? myDecorator.createPopupGroup() : null; } @Override public void setDefaultState(@Nullable final ToolWindowAnchor anchor, @Nullable final ToolWindowType type, @Nullable final Rectangle2D floatingBounds) { myToolWindowManager.setDefaultState(this, anchor, type, floatingBounds); } @Override public void setToHideOnEmptyContent(final boolean hideOnEmpty) { myHideOnEmptyContent = hideOnEmpty; } @Override public boolean isToHideOnEmptyContent() { return myHideOnEmptyContent; } @Override public void setShowStripeButton(boolean show) { myToolWindowManager.setShowStripeButton(myId, show); } @Override public boolean isShowStripeButton() { return myToolWindowManager.isShowStripeButton(myId); } @Override public boolean isDisposed() { return myContentManager.isDisposed(); } public boolean isPlaceholderMode() { return myPlaceholderMode; } public void setPlaceholderMode(final boolean placeholderMode) { myPlaceholderMode = placeholderMode; } public void setContentFactory(ToolWindowFactory contentFactory) { myContentFactory = contentFactory; contentFactory.init(this); } public void ensureContentInitialized() { if (myContentFactory != null) { ToolWindowFactory contentFactory = myContentFactory; // clear it first to avoid SOE myContentFactory = null; if (!myToolWindowManager.isUnified()) { myContentManager.removeAllContents(false); contentFactory.createToolWindowContent(myToolWindowManager.getProject(), this); } else { if (contentFactory.isUnified()) { myContentManager.removeAllContents(false); contentFactory.createToolWindowContent(myToolWindowManager.getProject(), this); } else { myContentFactory = null; // nothing // FIXME just leave initialize label } } } } @Override public void setUseLastFocusedOnActivation(boolean focus) { myUseLastFocused = focus; } @Override public boolean isUseLastFocusedOnActivation() { return myUseLastFocused; } @RequiredUIAccess @Override public void setIcon(@Nullable Image icon) { UIAccess.assertIsUIThread(); Object oldIcon = myIcon; myIcon = icon; myChangeSupport.firePropertyChange(PROP_ICON, oldIcon, icon); } @RequiredUIAccess @Nullable @Override public Image getIcon() { UIAccess.assertIsUIThread(); return myIcon; } // TODO [VISTALL] AWT & Swing dependency // region AWT & Swing dependency private static final Content EMPTY_CONTENT = new ContentImpl(new javax.swing.JLabel(), "", false); // endregion }
/* * Copyright (C) 2008 The Android Open Source Project * * 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 android.graphics.cts; import com.android.cts.stub.R; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.Rect; import android.graphics.Bitmap.CompressFormat; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory.Options; import android.os.ParcelFileDescriptor; import android.test.InstrumentationTestCase; import android.util.DisplayMetrics; import android.util.TypedValue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileDescriptor; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class BitmapFactoryTest extends InstrumentationTestCase { private Resources mRes; // opt for non-null private BitmapFactory.Options mOpt1; // opt for null private BitmapFactory.Options mOpt2; // height and width of start.jpg private static final int START_HEIGHT = 31; private static final int START_WIDTH = 31; private int mDefaultDensity; private int mTargetDensity; // The test images, including baseline JPEG, a PNG, a GIF, a BMP AND a WEBP. private static int[] RES_IDS = new int[] { R.drawable.baseline_jpeg, R.drawable.png_test, R.drawable.gif_test, R.drawable.bmp_test, R.drawable.webp_test }; private static String[] NAMES_TEMP_FILES = new String[] { "baseline_temp.jpg", "png_temp.png", "gif_temp.gif", "bmp_temp.bmp", "webp_temp.webp" }; // The width and height of the above image. private static int WIDTHS[] = new int[] { 1280, 640, 320, 320, 640 }; private static int HEIGHTS[] = new int[] { 960, 480, 240, 240, 480 }; // Configurations for BitmapFactory.Options private static Config[] COLOR_CONFIGS = new Config[] {Config.ARGB_8888, Config.RGB_565, Config.ARGB_4444}; private static int[] COLOR_TOLS = new int[] {16, 49, 576}; private static int[] RAW_COLORS = new int[] { // raw data from R.drawable.premul_data Color.argb(255, 0, 0, 0), Color.argb(128, 255, 0, 0), Color.argb(128, 25, 26, 27), Color.argb(2, 255, 254, 253), }; private static int[] DEPREMUL_COLORS = new int[] { // data from R.drawable.premul_data, after premultiplied store + un-premultiplied load Color.argb(255, 0, 0, 0), Color.argb(128, 255, 0, 0), Color.argb(128, 26, 26, 28), Color.argb(2, 255, 255, 255), }; @Override protected void setUp() throws Exception { super.setUp(); mRes = getInstrumentation().getTargetContext().getResources(); mDefaultDensity = DisplayMetrics.DENSITY_DEFAULT; mTargetDensity = mRes.getDisplayMetrics().densityDpi; mOpt1 = new BitmapFactory.Options(); mOpt1.inScaled = false; mOpt2 = new BitmapFactory.Options(); mOpt2.inScaled = false; mOpt2.inJustDecodeBounds = true; } public void testConstructor() { // new the BitmapFactory instance new BitmapFactory(); } public void testDecodeResource1() { Bitmap b = BitmapFactory.decodeResource(mRes, R.drawable.start, mOpt1); assertNotNull(b); // Test the bitmap size assertEquals(START_HEIGHT, b.getHeight()); assertEquals(START_WIDTH, b.getWidth()); // Test if no bitmap assertNull(BitmapFactory.decodeResource(mRes, R.drawable.start, mOpt2)); } public void testDecodeResource2() { Bitmap b = BitmapFactory.decodeResource(mRes, R.drawable.start); assertNotNull(b); // Test the bitmap size assertEquals(START_HEIGHT * mTargetDensity / mDefaultDensity, b.getHeight(), 1.1); assertEquals(START_WIDTH * mTargetDensity / mDefaultDensity, b.getWidth(), 1.1); } public void testDecodeResourceStream() { InputStream is = obtainInputStream(); Rect r = new Rect(1, 1, 1, 1); TypedValue value = new TypedValue(); Bitmap b = BitmapFactory.decodeResourceStream(mRes, value, is, r, mOpt1); assertNotNull(b); // Test the bitmap size assertEquals(START_HEIGHT, b.getHeight()); assertEquals(START_WIDTH, b.getWidth()); } public void testDecodeByteArray1() { byte[] array = obtainArray(); Bitmap b = BitmapFactory.decodeByteArray(array, 0, array.length, mOpt1); assertNotNull(b); // Test the bitmap size assertEquals(START_HEIGHT, b.getHeight()); assertEquals(START_WIDTH, b.getWidth()); // Test if no bitmap assertNull(BitmapFactory.decodeByteArray(array, 0, array.length, mOpt2)); } public void testDecodeByteArray2() { byte[] array = obtainArray(); Bitmap b = BitmapFactory.decodeByteArray(array, 0, array.length); assertNotNull(b); // Test the bitmap size assertEquals(START_HEIGHT, b.getHeight()); assertEquals(START_WIDTH, b.getWidth()); } public void testDecodeStream1() { InputStream is = obtainInputStream(); Rect r = new Rect(1, 1, 1, 1); Bitmap b = BitmapFactory.decodeStream(is, r, mOpt1); assertNotNull(b); // Test the bitmap size assertEquals(START_HEIGHT, b.getHeight()); assertEquals(START_WIDTH, b.getWidth()); // Test if no bitmap assertNull(BitmapFactory.decodeStream(is, r, mOpt2)); } public void testDecodeStream2() { InputStream is = obtainInputStream(); Bitmap b = BitmapFactory.decodeStream(is); assertNotNull(b); // Test the bitmap size assertEquals(START_HEIGHT, b.getHeight()); assertEquals(START_WIDTH, b.getWidth()); } public void testDecodeStream3() throws IOException { for (int i = 0; i < RES_IDS.length; ++i) { InputStream is = obtainInputStream(RES_IDS[i]); Bitmap b = BitmapFactory.decodeStream(is); assertNotNull(b); // Test the bitmap size assertEquals(WIDTHS[i], b.getWidth()); assertEquals(HEIGHTS[i], b.getHeight()); } } public void testDecodeStream4() throws IOException { BitmapFactory.Options options = new BitmapFactory.Options(); for (int k = 0; k < COLOR_CONFIGS.length; ++k) { options.inPreferredConfig = COLOR_CONFIGS[k]; // Decode the PNG & WebP test images. The WebP test image has been encoded from PNG test // image and should have same similar (within some error-tolerance) Bitmap data. InputStream iStreamPng = obtainInputStream(R.drawable.png_test); Bitmap bPng = BitmapFactory.decodeStream(iStreamPng, null, options); assertNotNull(bPng); assertEquals(bPng.getConfig(), COLOR_CONFIGS[k]); InputStream iStreamWebp1 = obtainInputStream(R.drawable.webp_test); Bitmap bWebp1 = BitmapFactory.decodeStream(iStreamWebp1, null, options); assertNotNull(bWebp1); compareBitmaps(bPng, bWebp1, COLOR_TOLS[k], true); // Compress the PNG image to WebP format (Quality=90) and decode it back. // This will test end-to-end WebP encoding and decoding. ByteArrayOutputStream oStreamWebp = new ByteArrayOutputStream(); assertTrue(bPng.compress(CompressFormat.WEBP, 90, oStreamWebp)); InputStream iStreamWebp2 = new ByteArrayInputStream(oStreamWebp.toByteArray()); Bitmap bWebp2 = BitmapFactory.decodeStream(iStreamWebp2, null, options); assertNotNull(bWebp2); compareBitmaps(bPng, bWebp2, COLOR_TOLS[k], true); } } public void testDecodeFileDescriptor1() throws IOException { ParcelFileDescriptor pfd = obtainParcelDescriptor(obtainPath()); FileDescriptor input = pfd.getFileDescriptor(); Rect r = new Rect(1, 1, 1, 1); Bitmap b = BitmapFactory.decodeFileDescriptor(input, r, mOpt1); assertNotNull(b); // Test the bitmap size assertEquals(START_HEIGHT, b.getHeight()); assertEquals(START_WIDTH, b.getWidth()); // Test if no bitmap assertNull(BitmapFactory.decodeFileDescriptor(input, r, mOpt2)); } public void testDecodeFileDescriptor2() throws IOException { ParcelFileDescriptor pfd = obtainParcelDescriptor(obtainPath()); FileDescriptor input = pfd.getFileDescriptor(); Bitmap b = BitmapFactory.decodeFileDescriptor(input); assertNotNull(b); // Test the bitmap size assertEquals(START_HEIGHT, b.getHeight()); assertEquals(START_WIDTH, b.getWidth()); } public void testDecodeFile1() throws IOException { Bitmap b = BitmapFactory.decodeFile(obtainPath(), mOpt1); assertNotNull(b); // Test the bitmap size assertEquals(START_HEIGHT, b.getHeight()); assertEquals(START_WIDTH, b.getWidth()); // Test if no bitmap assertNull(BitmapFactory.decodeFile(obtainPath(), mOpt2)); } public void testDecodeFile2() throws IOException { Bitmap b = BitmapFactory.decodeFile(obtainPath()); assertNotNull(b); // Test the bitmap size assertEquals(START_HEIGHT, b.getHeight()); assertEquals(START_WIDTH, b.getWidth()); } public void testDecodeReuseBasic() throws IOException { BitmapFactory.Options options = new BitmapFactory.Options(); options.inMutable = true; options.inSampleSize = 0; // treated as 1 options.inScaled = false; Bitmap start = BitmapFactory.decodeResource(mRes, R.drawable.start, options); int originalSize = start.getByteCount(); assertEquals(originalSize, start.getAllocationByteCount()); options.inBitmap = start; options.inMutable = false; // will be overridden by non-null inBitmap options.inSampleSize = -42; // treated as 1 Bitmap pass = BitmapFactory.decodeResource(mRes, R.drawable.pass, options); assertEquals(originalSize, pass.getByteCount()); assertEquals(originalSize, pass.getAllocationByteCount()); assertSame(start, pass); assertTrue(pass.isMutable()); } public void testDecodeReuseFormats() throws IOException { // reuse should support all image formats for (int i = 0; i < RES_IDS.length; ++i) { Bitmap reuseBuffer = Bitmap.createBitmap(1000000, 1, Bitmap.Config.ALPHA_8); BitmapFactory.Options options = new BitmapFactory.Options(); options.inBitmap = reuseBuffer; options.inSampleSize = 4; options.inScaled = false; Bitmap decoded = BitmapFactory.decodeResource(mRes, RES_IDS[i], options); assertSame(reuseBuffer, decoded); } } public void testDecodeReuseFailure() throws IOException { BitmapFactory.Options options = new BitmapFactory.Options(); options.inMutable = true; options.inScaled = false; options.inSampleSize = 4; Bitmap reduced = BitmapFactory.decodeResource(mRes, R.drawable.robot, options); options.inBitmap = reduced; options.inSampleSize = 1; try { Bitmap original = BitmapFactory.decodeResource(mRes, R.drawable.robot, options); fail("should throw exception due to lack of space"); } catch (IllegalArgumentException e) { } } public void testDecodeReuseScaling() throws IOException { BitmapFactory.Options options = new BitmapFactory.Options(); options.inMutable = true; options.inScaled = false; Bitmap original = BitmapFactory.decodeResource(mRes, R.drawable.robot, options); int originalSize = original.getByteCount(); assertEquals(originalSize, original.getAllocationByteCount()); options.inBitmap = original; options.inSampleSize = 4; Bitmap reduced = BitmapFactory.decodeResource(mRes, R.drawable.robot, options); assertSame(original, reduced); assertEquals(originalSize, reduced.getAllocationByteCount()); assertEquals(originalSize, reduced.getByteCount() * 16); } public void testDecodeReuseDoubleScaling() throws IOException { BitmapFactory.Options options = new BitmapFactory.Options(); options.inMutable = true; options.inScaled = false; options.inSampleSize = 1; Bitmap original = BitmapFactory.decodeResource(mRes, R.drawable.robot, options); int originalSize = original.getByteCount(); // Verify that inSampleSize and density scaling both work with reuse concurrently options.inBitmap = original; options.inScaled = true; options.inSampleSize = 2; options.inDensity = 2; options.inTargetDensity = 4; Bitmap doubleScaled = BitmapFactory.decodeResource(mRes, R.drawable.robot, options); assertSame(original, doubleScaled); assertEquals(4, doubleScaled.getDensity()); assertEquals(originalSize, doubleScaled.getByteCount()); } public void testDecodeReuseEquivalentScaling() throws IOException { BitmapFactory.Options options = new BitmapFactory.Options(); options.inMutable = true; options.inScaled = true; options.inDensity = 4; options.inTargetDensity = 2; Bitmap densityReduced = BitmapFactory.decodeResource(mRes, R.drawable.robot, options); assertEquals(2, densityReduced.getDensity()); options.inBitmap = densityReduced; options.inDensity = 0; options.inScaled = false; options.inSampleSize = 2; Bitmap scaleReduced = BitmapFactory.decodeResource(mRes, R.drawable.robot, options); // verify that density isn't incorrectly carried over during bitmap reuse assertFalse(densityReduced.getDensity() == 2); assertFalse(densityReduced.getDensity() == 0); assertSame(densityReduced, scaleReduced); } public void testDecodePremultipliedDefault() throws IOException { Bitmap simplePremul = BitmapFactory.decodeResource(mRes, R.drawable.premul_data); assertTrue(simplePremul.isPremultiplied()); } public void testDecodePremultipliedData() throws IOException { BitmapFactory.Options options = new BitmapFactory.Options(); options.inScaled = false; Bitmap premul = BitmapFactory.decodeResource(mRes, R.drawable.premul_data, options); options.inPremultiplied = false; Bitmap unpremul = BitmapFactory.decodeResource(mRes, R.drawable.premul_data, options); assertEquals(premul.getConfig(), Bitmap.Config.ARGB_8888); assertEquals(unpremul.getConfig(), Bitmap.Config.ARGB_8888); assertTrue(premul.getHeight() == 1 && unpremul.getHeight() == 1); assertTrue(premul.getWidth() == unpremul.getWidth() && DEPREMUL_COLORS.length == RAW_COLORS.length && premul.getWidth() == DEPREMUL_COLORS.length); // verify pixel data - unpremul should have raw values, premul will have rounding errors for (int i = 0; i < premul.getWidth(); i++) { assertEquals(premul.getPixel(i, 0), DEPREMUL_COLORS[i]); assertEquals(unpremul.getPixel(i, 0), RAW_COLORS[i]); } } private byte[] obtainArray() { ByteArrayOutputStream stm = new ByteArrayOutputStream(); Options opt = new BitmapFactory.Options(); opt.inScaled = false; Bitmap bitmap = BitmapFactory.decodeResource(mRes, R.drawable.start, opt); bitmap.compress(Bitmap.CompressFormat.JPEG, 0, stm); return(stm.toByteArray()); } private InputStream obtainInputStream() { return mRes.openRawResource(R.drawable.start); } private InputStream obtainInputStream(int resId) { return mRes.openRawResource(resId); } private ParcelFileDescriptor obtainParcelDescriptor(String path) throws IOException { File file = new File(path); return(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)); } private String obtainPath() throws IOException { File dir = getInstrumentation().getTargetContext().getFilesDir(); dir.mkdirs(); File file = new File(dir, "test.jpg"); if (!file.createNewFile()) { if (!file.exists()) { fail("Failed to create new File!"); } } InputStream is = obtainInputStream(); FileOutputStream fOutput = new FileOutputStream(file); byte[] dataBuffer = new byte[1024]; int readLength = 0; while ((readLength = is.read(dataBuffer)) != -1) { fOutput.write(dataBuffer, 0, readLength); } is.close(); fOutput.close(); return (file.getPath()); } // Compare expected to actual to see if their diff is less then mseMargin. // lessThanMargin is to indicate whether we expect the mean square error // to be "less than" or "no less than". private void compareBitmaps(Bitmap expected, Bitmap actual, int mseMargin, boolean lessThanMargin) { final int width = expected.getWidth(); final int height = expected.getHeight(); assertEquals("mismatching widths", width, actual.getWidth()); assertEquals("mismatching heights", height, actual.getHeight()); assertEquals("mismatching configs", expected.getConfig(), actual.getConfig()); double mse = 0; int[] expectedColors = new int [width * height]; int[] actualColors = new int [width * height]; expected.getPixels(expectedColors, 0, width, 0, 0, width, height); actual.getPixels(actualColors, 0, width, 0, 0, width, height); for (int row = 0; row < height; ++row) { for (int col = 0; col < width; ++col) { int idx = row * width + col; mse += distance(expectedColors[idx], actualColors[idx]); } } mse /= width * height; if (lessThanMargin) { assertTrue("MSE too large for normal case: " + mse, mse <= mseMargin); } else { assertFalse("MSE too small for abnormal case: " + mse, mse <= mseMargin); } } private double distance(int expect, int actual) { final int r = Color.red(actual) - Color.red(expect); final int g = Color.green(actual) - Color.green(expect); final int b = Color.blue(actual) - Color.blue(expect); return r * r + g * g + b * b; } }
/* * Copyright 2020 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.gradle.process.internal; import org.gradle.api.file.ConfigurableFileCollection; import org.gradle.api.file.FileCollection; import org.gradle.api.internal.file.FileCollectionFactory; import org.gradle.api.jvm.ModularitySpec; import org.gradle.api.model.ObjectFactory; import org.gradle.api.provider.Property; import org.gradle.internal.deprecation.DeprecationLogger; import org.gradle.internal.file.PathToFileResolver; import org.gradle.internal.jvm.DefaultModularitySpec; import org.gradle.process.CommandLineArgumentProvider; import org.gradle.process.JavaExecSpec; import javax.annotation.Nullable; import javax.inject.Inject; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import static org.gradle.process.internal.DefaultExecSpec.copyBaseExecSpecTo; public class DefaultJavaExecSpec extends DefaultJavaForkOptions implements JavaExecSpec, ProcessArgumentsSpec.HasExecutable { private boolean ignoreExitValue; private final ProcessStreamsSpec streamsSpec = new ProcessStreamsSpec(); private final ProcessArgumentsSpec argumentsSpec = new ProcessArgumentsSpec(this); private final Property<String> mainClass; private final Property<String> mainModule; private final ModularitySpec modularity; private final FileCollectionFactory fileCollectionFactory; private ConfigurableFileCollection classpath; @Inject public DefaultJavaExecSpec( ObjectFactory objectFactory, PathToFileResolver resolver, FileCollectionFactory fileCollectionFactory ) { super(resolver, fileCollectionFactory, objectFactory.newInstance(DefaultJavaDebugOptions.class)); this.mainClass = objectFactory.property(String.class); this.mainModule = objectFactory.property(String.class); this.modularity = objectFactory.newInstance(DefaultModularitySpec.class); this.fileCollectionFactory = fileCollectionFactory; this.classpath = fileCollectionFactory.configurableFiles("classpath"); } public void copyTo(JavaExecSpec targetSpec) { // JavaExecSpec targetSpec.setArgs(getArgs()); targetSpec.getArgumentProviders().addAll(getArgumentProviders()); targetSpec.getMainClass().set(getMainClass()); targetSpec.getMainModule().set(getMainModule()); targetSpec.getModularity().getInferModulePath().set(getModularity().getInferModulePath()); targetSpec.classpath(getClasspath()); // BaseExecSpec copyBaseExecSpecTo(this, targetSpec); // Java fork options super.copyTo(targetSpec); } @Override public List<String> getCommandLine() { return argumentsSpec.getCommandLine(); } @Override public JavaExecSpec args(Object... args) { argumentsSpec.args(args); return this; } @Override public JavaExecSpec args(Iterable<?> args) { argumentsSpec.args(args); return this; } @Override public JavaExecSpec setArgs(@Nullable List<String> arguments) { argumentsSpec.setArgs(arguments); return this; } @Override public JavaExecSpec setArgs(@Nullable Iterable<?> arguments) { argumentsSpec.setArgs(arguments); return this; } @Nullable @Override public List<String> getArgs() { return argumentsSpec.getArgs(); } @Override public List<CommandLineArgumentProvider> getArgumentProviders() { return argumentsSpec.getArgumentProviders(); } @Override public JavaExecSpec classpath(Object... paths) { this.classpath.from(paths); return this; } @Override public FileCollection getClasspath() { return classpath; } @Override public JavaExecSpec setClasspath(FileCollection classpath) { this.classpath = fileCollectionFactory.configurableFiles("classpath"); this.classpath.setFrom(classpath); return this; } @Override public boolean isIgnoreExitValue() { return ignoreExitValue; } @Override public JavaExecSpec setIgnoreExitValue(boolean ignoreExitValue) { this.ignoreExitValue = ignoreExitValue; return this; } @Override public InputStream getStandardInput() { return streamsSpec.getStandardInput(); } @Override public JavaExecSpec setStandardInput(InputStream standardInput) { streamsSpec.setStandardInput(standardInput); return this; } @Override public OutputStream getStandardOutput() { return streamsSpec.getStandardOutput(); } @Override public JavaExecSpec setStandardOutput(OutputStream standardOutput) { streamsSpec.setStandardOutput(standardOutput); return this; } @Override public OutputStream getErrorOutput() { return streamsSpec.getErrorOutput(); } @Override public JavaExecSpec setErrorOutput(OutputStream errorOutput) { streamsSpec.setErrorOutput(errorOutput); return this; } @Override public Property<String> getMainClass() { return mainClass; } @Nullable @Override @Deprecated public String getMain() { DeprecationLogger.deprecateMethod(JavaExecSpec.class, "getMain()") .withAdvice("Please use the mainClass property instead.") .willBeRemovedInGradle8() .withUpgradeGuideSection(7, "java_exec_properties") .nagUser(); return mainClass.getOrNull(); } @Override @Deprecated public JavaExecSpec setMain(@Nullable String main) { DeprecationLogger.deprecateMethod(JavaExecSpec.class, "setMain(String)") .withAdvice("Please use the mainClass property instead.") .willBeRemovedInGradle8() .withUpgradeGuideSection(7, "java_exec_properties") .nagUser(); mainClass.set(main); return this; } @Override public Property<String> getMainModule() { return mainModule; } @Override public ModularitySpec getModularity() { return modularity; } }
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.iotthingsgraph.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * An object that contains summary information about a system instance. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotthingsgraph-2018-09-06/SystemInstanceSummary" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class SystemInstanceSummary implements Serializable, Cloneable, StructuredPojo { /** * <p> * The ID of the system instance. * </p> */ private String id; /** * <p> * The ARN of the system instance. * </p> */ private String arn; /** * <p> * The status of the system instance. * </p> */ private String status; /** * <p> * The target of the system instance. * </p> */ private String target; /** * <p> * The ID of the Greengrass group where the system instance is deployed. * </p> */ private String greengrassGroupName; /** * <p> * The date when the system instance was created. * </p> */ private java.util.Date createdAt; /** * <p> * The date and time when the system instance was last updated. * </p> */ private java.util.Date updatedAt; /** * <p> * The ID of the Greengrass group where the system instance is deployed. * </p> */ private String greengrassGroupId; /** * <p> * The version of the Greengrass group where the system instance is deployed. * </p> */ private String greengrassGroupVersionId; /** * <p> * The ID of the system instance. * </p> * * @param id * The ID of the system instance. */ public void setId(String id) { this.id = id; } /** * <p> * The ID of the system instance. * </p> * * @return The ID of the system instance. */ public String getId() { return this.id; } /** * <p> * The ID of the system instance. * </p> * * @param id * The ID of the system instance. * @return Returns a reference to this object so that method calls can be chained together. */ public SystemInstanceSummary withId(String id) { setId(id); return this; } /** * <p> * The ARN of the system instance. * </p> * * @param arn * The ARN of the system instance. */ public void setArn(String arn) { this.arn = arn; } /** * <p> * The ARN of the system instance. * </p> * * @return The ARN of the system instance. */ public String getArn() { return this.arn; } /** * <p> * The ARN of the system instance. * </p> * * @param arn * The ARN of the system instance. * @return Returns a reference to this object so that method calls can be chained together. */ public SystemInstanceSummary withArn(String arn) { setArn(arn); return this; } /** * <p> * The status of the system instance. * </p> * * @param status * The status of the system instance. * @see SystemInstanceDeploymentStatus */ public void setStatus(String status) { this.status = status; } /** * <p> * The status of the system instance. * </p> * * @return The status of the system instance. * @see SystemInstanceDeploymentStatus */ public String getStatus() { return this.status; } /** * <p> * The status of the system instance. * </p> * * @param status * The status of the system instance. * @return Returns a reference to this object so that method calls can be chained together. * @see SystemInstanceDeploymentStatus */ public SystemInstanceSummary withStatus(String status) { setStatus(status); return this; } /** * <p> * The status of the system instance. * </p> * * @param status * The status of the system instance. * @return Returns a reference to this object so that method calls can be chained together. * @see SystemInstanceDeploymentStatus */ public SystemInstanceSummary withStatus(SystemInstanceDeploymentStatus status) { this.status = status.toString(); return this; } /** * <p> * The target of the system instance. * </p> * * @param target * The target of the system instance. * @see DeploymentTarget */ public void setTarget(String target) { this.target = target; } /** * <p> * The target of the system instance. * </p> * * @return The target of the system instance. * @see DeploymentTarget */ public String getTarget() { return this.target; } /** * <p> * The target of the system instance. * </p> * * @param target * The target of the system instance. * @return Returns a reference to this object so that method calls can be chained together. * @see DeploymentTarget */ public SystemInstanceSummary withTarget(String target) { setTarget(target); return this; } /** * <p> * The target of the system instance. * </p> * * @param target * The target of the system instance. * @return Returns a reference to this object so that method calls can be chained together. * @see DeploymentTarget */ public SystemInstanceSummary withTarget(DeploymentTarget target) { this.target = target.toString(); return this; } /** * <p> * The ID of the Greengrass group where the system instance is deployed. * </p> * * @param greengrassGroupName * The ID of the Greengrass group where the system instance is deployed. */ public void setGreengrassGroupName(String greengrassGroupName) { this.greengrassGroupName = greengrassGroupName; } /** * <p> * The ID of the Greengrass group where the system instance is deployed. * </p> * * @return The ID of the Greengrass group where the system instance is deployed. */ public String getGreengrassGroupName() { return this.greengrassGroupName; } /** * <p> * The ID of the Greengrass group where the system instance is deployed. * </p> * * @param greengrassGroupName * The ID of the Greengrass group where the system instance is deployed. * @return Returns a reference to this object so that method calls can be chained together. */ public SystemInstanceSummary withGreengrassGroupName(String greengrassGroupName) { setGreengrassGroupName(greengrassGroupName); return this; } /** * <p> * The date when the system instance was created. * </p> * * @param createdAt * The date when the system instance was created. */ public void setCreatedAt(java.util.Date createdAt) { this.createdAt = createdAt; } /** * <p> * The date when the system instance was created. * </p> * * @return The date when the system instance was created. */ public java.util.Date getCreatedAt() { return this.createdAt; } /** * <p> * The date when the system instance was created. * </p> * * @param createdAt * The date when the system instance was created. * @return Returns a reference to this object so that method calls can be chained together. */ public SystemInstanceSummary withCreatedAt(java.util.Date createdAt) { setCreatedAt(createdAt); return this; } /** * <p> * The date and time when the system instance was last updated. * </p> * * @param updatedAt * The date and time when the system instance was last updated. */ public void setUpdatedAt(java.util.Date updatedAt) { this.updatedAt = updatedAt; } /** * <p> * The date and time when the system instance was last updated. * </p> * * @return The date and time when the system instance was last updated. */ public java.util.Date getUpdatedAt() { return this.updatedAt; } /** * <p> * The date and time when the system instance was last updated. * </p> * * @param updatedAt * The date and time when the system instance was last updated. * @return Returns a reference to this object so that method calls can be chained together. */ public SystemInstanceSummary withUpdatedAt(java.util.Date updatedAt) { setUpdatedAt(updatedAt); return this; } /** * <p> * The ID of the Greengrass group where the system instance is deployed. * </p> * * @param greengrassGroupId * The ID of the Greengrass group where the system instance is deployed. */ public void setGreengrassGroupId(String greengrassGroupId) { this.greengrassGroupId = greengrassGroupId; } /** * <p> * The ID of the Greengrass group where the system instance is deployed. * </p> * * @return The ID of the Greengrass group where the system instance is deployed. */ public String getGreengrassGroupId() { return this.greengrassGroupId; } /** * <p> * The ID of the Greengrass group where the system instance is deployed. * </p> * * @param greengrassGroupId * The ID of the Greengrass group where the system instance is deployed. * @return Returns a reference to this object so that method calls can be chained together. */ public SystemInstanceSummary withGreengrassGroupId(String greengrassGroupId) { setGreengrassGroupId(greengrassGroupId); return this; } /** * <p> * The version of the Greengrass group where the system instance is deployed. * </p> * * @param greengrassGroupVersionId * The version of the Greengrass group where the system instance is deployed. */ public void setGreengrassGroupVersionId(String greengrassGroupVersionId) { this.greengrassGroupVersionId = greengrassGroupVersionId; } /** * <p> * The version of the Greengrass group where the system instance is deployed. * </p> * * @return The version of the Greengrass group where the system instance is deployed. */ public String getGreengrassGroupVersionId() { return this.greengrassGroupVersionId; } /** * <p> * The version of the Greengrass group where the system instance is deployed. * </p> * * @param greengrassGroupVersionId * The version of the Greengrass group where the system instance is deployed. * @return Returns a reference to this object so that method calls can be chained together. */ public SystemInstanceSummary withGreengrassGroupVersionId(String greengrassGroupVersionId) { setGreengrassGroupVersionId(greengrassGroupVersionId); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getId() != null) sb.append("Id: ").append(getId()).append(","); if (getArn() != null) sb.append("Arn: ").append(getArn()).append(","); if (getStatus() != null) sb.append("Status: ").append(getStatus()).append(","); if (getTarget() != null) sb.append("Target: ").append(getTarget()).append(","); if (getGreengrassGroupName() != null) sb.append("GreengrassGroupName: ").append(getGreengrassGroupName()).append(","); if (getCreatedAt() != null) sb.append("CreatedAt: ").append(getCreatedAt()).append(","); if (getUpdatedAt() != null) sb.append("UpdatedAt: ").append(getUpdatedAt()).append(","); if (getGreengrassGroupId() != null) sb.append("GreengrassGroupId: ").append(getGreengrassGroupId()).append(","); if (getGreengrassGroupVersionId() != null) sb.append("GreengrassGroupVersionId: ").append(getGreengrassGroupVersionId()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof SystemInstanceSummary == false) return false; SystemInstanceSummary other = (SystemInstanceSummary) obj; if (other.getId() == null ^ this.getId() == null) return false; if (other.getId() != null && other.getId().equals(this.getId()) == false) return false; if (other.getArn() == null ^ this.getArn() == null) return false; if (other.getArn() != null && other.getArn().equals(this.getArn()) == false) return false; if (other.getStatus() == null ^ this.getStatus() == null) return false; if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false) return false; if (other.getTarget() == null ^ this.getTarget() == null) return false; if (other.getTarget() != null && other.getTarget().equals(this.getTarget()) == false) return false; if (other.getGreengrassGroupName() == null ^ this.getGreengrassGroupName() == null) return false; if (other.getGreengrassGroupName() != null && other.getGreengrassGroupName().equals(this.getGreengrassGroupName()) == false) return false; if (other.getCreatedAt() == null ^ this.getCreatedAt() == null) return false; if (other.getCreatedAt() != null && other.getCreatedAt().equals(this.getCreatedAt()) == false) return false; if (other.getUpdatedAt() == null ^ this.getUpdatedAt() == null) return false; if (other.getUpdatedAt() != null && other.getUpdatedAt().equals(this.getUpdatedAt()) == false) return false; if (other.getGreengrassGroupId() == null ^ this.getGreengrassGroupId() == null) return false; if (other.getGreengrassGroupId() != null && other.getGreengrassGroupId().equals(this.getGreengrassGroupId()) == false) return false; if (other.getGreengrassGroupVersionId() == null ^ this.getGreengrassGroupVersionId() == null) return false; if (other.getGreengrassGroupVersionId() != null && other.getGreengrassGroupVersionId().equals(this.getGreengrassGroupVersionId()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getId() == null) ? 0 : getId().hashCode()); hashCode = prime * hashCode + ((getArn() == null) ? 0 : getArn().hashCode()); hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode()); hashCode = prime * hashCode + ((getTarget() == null) ? 0 : getTarget().hashCode()); hashCode = prime * hashCode + ((getGreengrassGroupName() == null) ? 0 : getGreengrassGroupName().hashCode()); hashCode = prime * hashCode + ((getCreatedAt() == null) ? 0 : getCreatedAt().hashCode()); hashCode = prime * hashCode + ((getUpdatedAt() == null) ? 0 : getUpdatedAt().hashCode()); hashCode = prime * hashCode + ((getGreengrassGroupId() == null) ? 0 : getGreengrassGroupId().hashCode()); hashCode = prime * hashCode + ((getGreengrassGroupVersionId() == null) ? 0 : getGreengrassGroupVersionId().hashCode()); return hashCode; } @Override public SystemInstanceSummary clone() { try { return (SystemInstanceSummary) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.iotthingsgraph.model.transform.SystemInstanceSummaryMarshaller.getInstance().marshall(this, protocolMarshaller); } }
/* * Copyright 2000-2017 JetBrains s.r.o. * * 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.intellij.xdebugger.impl.ui.tree.nodes; import com.intellij.icons.AllIcons; import com.intellij.openapi.application.ApplicationManager; import com.intellij.util.ThreeState; import com.intellij.xdebugger.Obsolescent; import com.intellij.xdebugger.XExpression; import com.intellij.xdebugger.evaluation.XDebuggerEvaluator; import com.intellij.xdebugger.evaluation.XInstanceEvaluator; import com.intellij.xdebugger.frame.*; import com.intellij.xdebugger.frame.presentation.XErrorValuePresentation; import com.intellij.xdebugger.frame.presentation.XValuePresentation; import com.intellij.xdebugger.impl.ui.XDebuggerUIConstants; import com.intellij.xdebugger.impl.ui.tree.XDebuggerTree; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.concurrency.Promise; /** * @author nik */ public class WatchNodeImpl extends XValueNodeImpl implements WatchNode { private final XExpression myExpression; public WatchNodeImpl(@NotNull XDebuggerTree tree, @NotNull WatchesRootNode parent, @NotNull XExpression expression, @Nullable XStackFrame stackFrame) { super(tree, parent, expression.getExpression(), new XWatchValue(expression, tree, stackFrame)); myExpression = expression; } @Override @NotNull public XExpression getExpression() { return myExpression; } @NotNull @Override public XValue getValueContainer() { XValue container = super.getValueContainer(); XValue value = ((XWatchValue)container).myValue; return value != null ? value : container; } void computePresentationIfNeeded() { if (getValuePresentation() == null) { getValueContainer().computePresentation(this, XValuePlace.TREE); } } private static class XWatchValue extends XNamedValue { private final XExpression myExpression; private final XDebuggerTree myTree; private final XStackFrame myStackFrame; private volatile XValue myValue; public XWatchValue(XExpression expression, XDebuggerTree tree, XStackFrame stackFrame) { super(expression.getExpression()); myExpression = expression; myTree = tree; myStackFrame = stackFrame; } @Override public void computeChildren(@NotNull XCompositeNode node) { if (myValue != null) { myValue.computeChildren(node); } } @Override public void computePresentation(@NotNull XValueNode node, @NotNull XValuePlace place) { if (myStackFrame != null) { if (myTree.isShowing() || ApplicationManager.getApplication().isUnitTestMode()) { XDebuggerEvaluator evaluator = myStackFrame.getEvaluator(); if (evaluator != null) { evaluator.evaluate(myExpression, new MyEvaluationCallback(node, place), myStackFrame.getSourcePosition()); return; } } else { return; // do not set anything if view is not visible, otherwise the code in computePresentationIfNeeded() will not work } } node.setPresentation(AllIcons.Debugger.Watch, EMPTY_PRESENTATION, false); } private class MyEvaluationCallback extends XEvaluationCallbackBase implements Obsolescent { @NotNull private final XValueNode myNode; @NotNull private final XValuePlace myPlace; public MyEvaluationCallback(@NotNull XValueNode node, @NotNull XValuePlace place) { myNode = node; myPlace = place; } @Override public boolean isObsolete() { return myNode.isObsolete(); } @Override public void evaluated(@NotNull XValue result) { myValue = result; result.computePresentation(myNode, myPlace); } @Override public void errorOccurred(@NotNull String errorMessage) { myNode.setPresentation(XDebuggerUIConstants.ERROR_MESSAGE_ICON, new XErrorValuePresentation(errorMessage), false); } } private static final XValuePresentation EMPTY_PRESENTATION = new XValuePresentation() { @NotNull @Override public String getSeparator() { return ""; } @Override public void renderValue(@NotNull XValueTextRenderer renderer) { } }; @Override @Nullable public String getEvaluationExpression() { return myValue != null ? myValue.getEvaluationExpression() : null; } @Override @NotNull public Promise<XExpression> calculateEvaluationExpression() { return Promise.resolve(myExpression); } @Override @Nullable public XInstanceEvaluator getInstanceEvaluator() { return myValue != null ? myValue.getInstanceEvaluator() : null; } @Override @Nullable public XValueModifier getModifier() { return myValue != null ? myValue.getModifier() : null; } @Override public void computeSourcePosition(@NotNull XNavigatable navigatable) { if (myValue != null) { myValue.computeSourcePosition(navigatable); } } @Override @NotNull public ThreeState computeInlineDebuggerData(@NotNull XInlineDebuggerDataCallback callback) { return ThreeState.NO; } @Override public boolean canNavigateToSource() { return myValue != null && myValue.canNavigateToSource(); } @Override public boolean canNavigateToTypeSource() { return myValue != null && myValue.canNavigateToTypeSource(); } @Override public void computeTypeSourcePosition(@NotNull XNavigatable navigatable) { if (myValue != null) { myValue.computeTypeSourcePosition(navigatable); } } @Override @Nullable public XReferrersProvider getReferrersProvider() { return myValue != null ? myValue.getReferrersProvider() : null; } } }
/* 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.flowable.rest.service.api.history; import java.util.Date; import java.util.List; import org.flowable.rest.api.PaginateRequest; import org.flowable.rest.service.api.engine.variable.QueryVariable; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; /** * @author Tijs Rademakers */ public class HistoricProcessInstanceQueryRequest extends PaginateRequest { private String processInstanceId; private List<String> processInstanceIds; private String processBusinessKey; private String processDefinitionId; private String processDefinitionKey; private String superProcessInstanceId; private Boolean excludeSubprocesses; private Boolean finished; private String involvedUser; private Date finishedAfter; private Date finishedBefore; private Date startedAfter; private Date startedBefore; private String startedBy; private Boolean includeProcessVariables; private List<QueryVariable> variables; private String tenantId; private String tenantIdLike; private Boolean withoutTenantId; public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public List<String> getProcessInstanceIds() { return processInstanceIds; } public void setProcessInstanceIds(List<String> processInstanceIds) { this.processInstanceIds = processInstanceIds; } public String getProcessBusinessKey() { return processBusinessKey; } public void setProcessBusinessKey(String processBusinessKey) { this.processBusinessKey = processBusinessKey; } public String getProcessDefinitionId() { return processDefinitionId; } public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public void setProcessDefinitionKey(String processDefinitionKey) { this.processDefinitionKey = processDefinitionKey; } public String getSuperProcessInstanceId() { return superProcessInstanceId; } public void setSuperProcessInstanceId(String superProcessInstanceId) { this.superProcessInstanceId = superProcessInstanceId; } public Boolean getExcludeSubprocesses() { return excludeSubprocesses; } public void setExcludeSubprocesses(Boolean excludeSubprocesses) { this.excludeSubprocesses = excludeSubprocesses; } public Boolean getFinished() { return finished; } public void setFinished(Boolean finished) { this.finished = finished; } public String getInvolvedUser() { return involvedUser; } public void setInvolvedUser(String involvedUser) { this.involvedUser = involvedUser; } public Date getFinishedAfter() { return finishedAfter; } public void setFinishedAfter(Date finishedAfter) { this.finishedAfter = finishedAfter; } public Date getFinishedBefore() { return finishedBefore; } public void setFinishedBefore(Date finishedBefore) { this.finishedBefore = finishedBefore; } public Date getStartedAfter() { return startedAfter; } public void setStartedAfter(Date startedAfter) { this.startedAfter = startedAfter; } public Date getStartedBefore() { return startedBefore; } public void setStartedBefore(Date startedBefore) { this.startedBefore = startedBefore; } public String getStartedBy() { return startedBy; } public void setStartedBy(String startedBy) { this.startedBy = startedBy; } public Boolean getIncludeProcessVariables() { return includeProcessVariables; } public void setIncludeProcessVariables(Boolean includeProcessVariables) { this.includeProcessVariables = includeProcessVariables; } @JsonTypeInfo(use = Id.CLASS, defaultImpl = QueryVariable.class) public List<QueryVariable> getVariables() { return variables; } public void setVariables(List<QueryVariable> variables) { this.variables = variables; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantIdLike() { return tenantIdLike; } public void setTenantIdLike(String tenantIdLike) { this.tenantIdLike = tenantIdLike; } public Boolean getWithoutTenantId() { return withoutTenantId; } public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } }
package xw.cn.daoexample.ui; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.CompoundButton; import android.widget.SeekBar; import android.widget.Spinner; import android.widget.Switch; import java.util.ArrayList; import java.util.List; import xw.cn.daoexample.R; import xw.cn.daoexample.view.progressview.AnimationState; import xw.cn.daoexample.view.progressview.AnimationStateChangedListener; import xw.cn.daoexample.view.progressview.CircleProgressView; import xw.cn.daoexample.view.progressview.TextMode; import xw.cn.daoexample.view.progressview.UnitPosition; public class MainActivity extends AppCompatActivity { /** * The log tag. */ private final static String TAG = "MainActivity"; CircleProgressView mCircleView; Switch mSwitchSpin; Switch mSwitchShowUnit; SeekBar mSeekBar; SeekBar mSeekBarSpinnerLength; Boolean mShowUnit = true; Spinner mSpinner; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.progress_act); mCircleView = (CircleProgressView) findViewById(R.id.circleView); mCircleView.setOnProgressChangedListener(new CircleProgressView.OnProgressChangedListener() { @Override public void onProgressChanged(float value) { Log.d(TAG, "Progress Changed: " + value); } }); //value setting // mCircleView.setMaxValue(100); // mCircleView.setValue(0); // mCircleView.setValueAnimated(24); //growing/rotating counter-clockwise // mCircleView.setDirection(Direction.CCW) // //show unit // mCircleView.setUnit("%"); // mCircleView.setUnitVisible(mShowUnit); // // //text sizes // mCircleView.setTextSize(50); // text size set, auto text size off // mCircleView.setUnitSize(40); // if i set the text size i also have to set the unit size // mCircleView.setAutoTextSize(true); // enable auto text size, previous values are overwritten // //if you want the calculated text sizes to be bigger/smaller you can do so via // mCircleView.setUnitScale(0.9f); // mCircleView.setTextScale(0.9f); // //// //custom typeface //// Typeface font = Typeface.createFromAsset(getAssets(), "fonts/ANDROID_ROBOT.ttf"); //// mCircleView.setTextTypeface(font); //// mCircleView.setUnitTextTypeface(font); // // // //color // //you can use a gradient // mCircleView.setBarColor(getResources().getColor(R.color.primary), getResources().getColor(R.color.accent)); // // //colors of text and unit can be set via // mCircleView.setTextColor(Color.RED); // mCircleView.setTextColor(Color.BLUE); // //or to use the same color as in the gradient // mCircleView.setTextColorAuto(true); //previous set values are ignored // // //text mode // mCircleView.setText("Text"); //shows the given text in the circle view // mCircleView.setTextMode(TextMode.TEXT); // Set text mode to text to show text // // //in the following text modes, the text is ignored // mCircleView.setTextMode(TextMode.VALUE); // Shows the current value // mCircleView.setTextMode(TextMode.PERCENT); // Shows current percent of the current value from the max value //spinning // mCircleView.spin(); // start spinning // mCircleView.stopSpinning(); // stops spinning. Spinner gets shorter until it disappears. // mCircleView.setValueAnimated(24); // stops spinning. Spinner spins until on top. Then fills to set value. //animation callbacks //this example shows how to show a loading text if it is in spinning mode, and the current percent value otherwise. mCircleView.setShowTextWhileSpinning(true); // Show/hide text in spinning mode mCircleView.setText("Loading..."); mCircleView.setOnAnimationStateChangedListener( new AnimationStateChangedListener() { @Override public void onAnimationStateChanged(AnimationState _animationState) { switch (_animationState) { case IDLE: case ANIMATING: case START_ANIMATING_AFTER_SPINNING: mCircleView.setTextMode(TextMode.PERCENT); // show percent if not spinning mCircleView.setUnitVisible(mShowUnit); break; case SPINNING: mCircleView.setTextMode(TextMode.TEXT); // show text while spinning mCircleView.setUnitVisible(false); case END_SPINNING: break; case END_SPINNING_START_ANIMATING: break; } } } ); // region setup other ui elements //Setup Switch mSwitchSpin = (Switch) findViewById(R.id.switch1); mSwitchSpin.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { mCircleView.spin(); } else { mCircleView.stopSpinning(); } } } ); mSwitchShowUnit = (Switch) findViewById(R.id.switch2); mSwitchShowUnit.setChecked(mShowUnit); mSwitchShowUnit.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mCircleView.setUnitVisible(isChecked); mShowUnit = isChecked; } } ); //Setup SeekBar mSeekBar = (SeekBar) findViewById(R.id.seekBar); mSeekBar.setMax(100); mSeekBar.setOnSeekBarChangeListener( new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { mCircleView.setValueAnimated(seekBar.getProgress(), 1500); mSwitchSpin.setChecked(false); } } ); mSeekBarSpinnerLength = (SeekBar) findViewById(R.id.seekBar2); mSeekBarSpinnerLength.setMax(360); mSeekBarSpinnerLength.setOnSeekBarChangeListener( new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { mCircleView.setSpinningBarLength(seekBar.getProgress()); } }); mSpinner = (Spinner) findViewById(R.id.spinner); List<String> list = new ArrayList<String>(); list.add("Left Top"); list.add("Left Bottom"); list.add("Right Top"); list.add("Right Bottom"); list.add("Top"); list.add("Bottom"); ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list); mSpinner.setAdapter(dataAdapter); mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { switch (position) { case 0: mCircleView.setUnitPosition(UnitPosition.LEFT_TOP); break; case 1: mCircleView.setUnitPosition(UnitPosition.LEFT_BOTTOM); break; case 2: mCircleView.setUnitPosition(UnitPosition.RIGHT_TOP); break; case 3: mCircleView.setUnitPosition(UnitPosition.RIGHT_BOTTOM); break; case 4: mCircleView.setUnitPosition(UnitPosition.TOP); break; case 5: mCircleView.setUnitPosition(UnitPosition.BOTTOM); break; } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); mSpinner.setSelection(2); //endregion // new LongOperation().execute(); } @Override protected void onStart() { super.onStart(); } private class LongOperation extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { mCircleView.setValue(0); mCircleView.spin(); } }); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void aVoid) { mCircleView.setValueAnimated(42); } } }
/** * 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.hadoop.hive.ql.optimizer.calcite.stats; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedMap; import org.apache.calcite.linq4j.Linq4j; import org.apache.calcite.linq4j.Ord; import org.apache.calcite.linq4j.function.Predicate1; import org.apache.calcite.plan.RelOptPredicateList; import org.apache.calcite.plan.RelOptUtil; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.core.Aggregate; import org.apache.calcite.rel.core.Join; import org.apache.calcite.rel.core.JoinRelType; import org.apache.calcite.rel.core.Project; import org.apache.calcite.rel.core.SemiJoin; import org.apache.calcite.rel.core.Union; import org.apache.calcite.rel.metadata.ReflectiveRelMetadataProvider; import org.apache.calcite.rel.metadata.RelMdPredicates; import org.apache.calcite.rel.metadata.RelMetadataProvider; import org.apache.calcite.rel.metadata.RelMetadataQuery; import org.apache.calcite.rex.RexBuilder; import org.apache.calcite.rex.RexCall; import org.apache.calcite.rex.RexInputRef; import org.apache.calcite.rex.RexLiteral; import org.apache.calcite.rex.RexNode; import org.apache.calcite.rex.RexPermuteInputsShuttle; import org.apache.calcite.rex.RexUtil; import org.apache.calcite.rex.RexVisitorImpl; import org.apache.calcite.sql.SqlKind; import org.apache.calcite.sql.fun.SqlStdOperatorTable; import org.apache.calcite.util.BitSets; import org.apache.calcite.util.BuiltInMethod; import org.apache.calcite.util.ImmutableBitSet; import org.apache.calcite.util.mapping.Mapping; import org.apache.calcite.util.mapping.MappingType; import org.apache.calcite.util.mapping.Mappings; import org.apache.hadoop.hive.ql.optimizer.calcite.HiveCalciteUtil; import com.google.common.base.Function; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.collect.Maps; //TODO: Move this to calcite public class HiveRelMdPredicates extends RelMdPredicates { public static final RelMetadataProvider SOURCE = ReflectiveRelMetadataProvider.reflectiveSource( BuiltInMethod.PREDICATES.method, new HiveRelMdPredicates()); private static final List<RexNode> EMPTY_LIST = ImmutableList.of(); /** * Infers predicates for a project. * * <ol> * <li>create a mapping from input to projection. Map only positions that * directly reference an input column. * <li>Expressions that only contain above columns are retained in the * Project's pullExpressions list. * <li>For e.g. expression 'a + e = 9' below will not be pulled up because 'e' * is not in the projection list. * * <pre> * childPullUpExprs: {a &gt; 7, b + c &lt; 10, a + e = 9} * projectionExprs: {a, b, c, e / 2} * projectionPullupExprs: {a &gt; 7, b + c &lt; 10} * </pre> * * </ol> */ @Override public RelOptPredicateList getPredicates(Project project, RelMetadataQuery mq) { RelNode child = project.getInput(); final RexBuilder rexBuilder = project.getCluster().getRexBuilder(); RelOptPredicateList childInfo = mq.getPulledUpPredicates(child); List<RexNode> projectPullUpPredicates = new ArrayList<RexNode>(); HashMultimap<Integer, Integer> inpIndxToOutIndxMap = HashMultimap.create(); ImmutableBitSet.Builder columnsMappedBuilder = ImmutableBitSet.builder(); Mapping m = Mappings.create(MappingType.PARTIAL_FUNCTION, child.getRowType().getFieldCount(), project.getRowType().getFieldCount()); for (Ord<RexNode> o : Ord.zip(project.getProjects())) { if (o.e instanceof RexInputRef) { int sIdx = ((RexInputRef) o.e).getIndex(); m.set(sIdx, o.i); inpIndxToOutIndxMap.put(sIdx, o.i); columnsMappedBuilder.set(sIdx); } } // Go over childPullUpPredicates. If a predicate only contains columns in // 'columnsMapped' construct a new predicate based on mapping. final ImmutableBitSet columnsMapped = columnsMappedBuilder.build(); for (RexNode r : childInfo.pulledUpPredicates) { ImmutableBitSet rCols = RelOptUtil.InputFinder.bits(r); if (columnsMapped.contains(rCols)) { r = r.accept(new RexPermuteInputsShuttle(m, child)); projectPullUpPredicates.add(r); } } // Project can also generate constants. We need to include them. for (Ord<RexNode> expr : Ord.zip(project.getProjects())) { if (RexLiteral.isNullLiteral(expr.e)) { projectPullUpPredicates.add(rexBuilder.makeCall(SqlStdOperatorTable.IS_NULL, rexBuilder.makeInputRef(project, expr.i))); } else if (expr.e instanceof RexLiteral) { final RexLiteral literal = (RexLiteral) expr.e; projectPullUpPredicates.add(rexBuilder.makeCall(SqlStdOperatorTable.EQUALS, rexBuilder.makeInputRef(project, expr.i), literal)); } else if (expr.e instanceof RexCall && HiveCalciteUtil.isDeterministicFuncOnLiterals(expr.e)) { //TODO: Move this to calcite projectPullUpPredicates.add(rexBuilder.makeCall(SqlStdOperatorTable.EQUALS, rexBuilder.makeInputRef(project, expr.i), expr.e)); } } return RelOptPredicateList.of(projectPullUpPredicates); } /** Infers predicates for a {@link org.apache.calcite.rel.core.Join}. */ @Override public RelOptPredicateList getPredicates(Join join, RelMetadataQuery mq) { RexBuilder rB = join.getCluster().getRexBuilder(); RelNode left = join.getInput(0); RelNode right = join.getInput(1); final RelOptPredicateList leftInfo = mq.getPulledUpPredicates(left); final RelOptPredicateList rightInfo = mq.getPulledUpPredicates(right); JoinConditionBasedPredicateInference jI = new JoinConditionBasedPredicateInference(join, RexUtil.composeConjunction(rB, leftInfo.pulledUpPredicates, false), RexUtil.composeConjunction(rB, rightInfo.pulledUpPredicates, false)); return jI.inferPredicates(false); } /** * Infers predicates for an Aggregate. * * <p>Pulls up predicates that only contains references to columns in the * GroupSet. For e.g. * * <pre> * inputPullUpExprs : { a &gt; 7, b + c &lt; 10, a + e = 9} * groupSet : { a, b} * pulledUpExprs : { a &gt; 7} * </pre> */ @Override public RelOptPredicateList getPredicates(Aggregate agg, RelMetadataQuery mq) { final RelNode input = agg.getInput(); final RelOptPredicateList inputInfo = mq.getPulledUpPredicates(input); final List<RexNode> aggPullUpPredicates = new ArrayList<>(); ImmutableBitSet groupKeys = agg.getGroupSet(); Mapping m = Mappings.create(MappingType.PARTIAL_FUNCTION, input.getRowType().getFieldCount(), agg.getRowType().getFieldCount()); int i = 0; for (int j : groupKeys) { m.set(j, i++); } for (RexNode r : inputInfo.pulledUpPredicates) { ImmutableBitSet rCols = RelOptUtil.InputFinder.bits(r); if (!rCols.isEmpty() && groupKeys.contains(rCols)) { r = r.accept(new RexPermuteInputsShuttle(m, input)); aggPullUpPredicates.add(r); } } return RelOptPredicateList.of(aggPullUpPredicates); } /** * Infers predicates for a Union. */ @Override public RelOptPredicateList getPredicates(Union union, RelMetadataQuery mq) { RexBuilder rB = union.getCluster().getRexBuilder(); Map<String, RexNode> finalPreds = new HashMap<>(); List<RexNode> finalResidualPreds = new ArrayList<>(); for (int i = 0; i < union.getInputs().size(); i++) { RelNode input = union.getInputs().get(i); RelOptPredicateList info = mq.getPulledUpPredicates(input); if (info.pulledUpPredicates.isEmpty()) { return RelOptPredicateList.EMPTY; } Map<String, RexNode> preds = new HashMap<>(); List<RexNode> residualPreds = new ArrayList<>(); for (RexNode pred : info.pulledUpPredicates) { final String predString = pred.toString(); if (i == 0) { preds.put(predString, pred); continue; } if (finalPreds.containsKey(predString)) { preds.put(predString, pred); } else { residualPreds.add(pred); } } // Add new residual preds finalResidualPreds.add(RexUtil.composeConjunction(rB, residualPreds, false)); // Add those that are not part of the final set to residual for (Entry<String, RexNode> e : finalPreds.entrySet()) { if (!preds.containsKey(e.getKey())) { // This node was in previous union inputs, but it is not in this one for (int j = 0; j < i; j++) { finalResidualPreds.set(j, RexUtil.composeConjunction(rB, Lists.newArrayList( finalResidualPreds.get(j), e.getValue()), false)); } } } // Final preds finalPreds = preds; } List<RexNode> preds = new ArrayList<>(finalPreds.values()); RexNode disjPred = RexUtil.composeDisjunction(rB, finalResidualPreds, false); if (!disjPred.isAlwaysTrue()) { preds.add(disjPred); } return RelOptPredicateList.of(preds); } /** * Utility to infer predicates from one side of the join that apply on the * other side. * * <p>Contract is:<ul> * * <li>initialize with a {@link org.apache.calcite.rel.core.Join} and * optional predicates applicable on its left and right subtrees. * * <li>you can * then ask it for equivalentPredicate(s) given a predicate. * * </ul> * * <p>So for: * <ol> * <li>'<code>R1(x) join R2(y) on x = y</code>' a call for * equivalentPredicates on '<code>x &gt; 7</code>' will return ' * <code>[y &gt; 7]</code>' * <li>'<code>R1(x) join R2(y) on x = y join R3(z) on y = z</code>' a call for * equivalentPredicates on the second join '<code>x &gt; 7</code>' will return * </ol> */ static class JoinConditionBasedPredicateInference { final Join joinRel; final boolean isSemiJoin; final int nSysFields; final int nFieldsLeft; final int nFieldsRight; final ImmutableBitSet leftFieldsBitSet; final ImmutableBitSet rightFieldsBitSet; final ImmutableBitSet allFieldsBitSet; SortedMap<Integer, BitSet> equivalence; final Map<String, ImmutableBitSet> exprFields; final Set<String> allExprsDigests; final Set<String> equalityPredicates; final RexNode leftChildPredicates; final RexNode rightChildPredicates; public JoinConditionBasedPredicateInference(Join joinRel, RexNode lPreds, RexNode rPreds) { this(joinRel, joinRel instanceof SemiJoin, lPreds, rPreds); } private JoinConditionBasedPredicateInference(Join joinRel, boolean isSemiJoin, RexNode lPreds, RexNode rPreds) { super(); this.joinRel = joinRel; this.isSemiJoin = isSemiJoin; nFieldsLeft = joinRel.getLeft().getRowType().getFieldList().size(); nFieldsRight = joinRel.getRight().getRowType().getFieldList().size(); nSysFields = joinRel.getSystemFieldList().size(); leftFieldsBitSet = ImmutableBitSet.range(nSysFields, nSysFields + nFieldsLeft); rightFieldsBitSet = ImmutableBitSet.range(nSysFields + nFieldsLeft, nSysFields + nFieldsLeft + nFieldsRight); allFieldsBitSet = ImmutableBitSet.range(0, nSysFields + nFieldsLeft + nFieldsRight); exprFields = Maps.newHashMap(); allExprsDigests = new HashSet<>(); if (lPreds == null) { leftChildPredicates = null; } else { Mappings.TargetMapping leftMapping = Mappings.createShiftMapping( nSysFields + nFieldsLeft, nSysFields, 0, nFieldsLeft); leftChildPredicates = lPreds.accept( new RexPermuteInputsShuttle(leftMapping, joinRel.getInput(0))); for (RexNode r : RelOptUtil.conjunctions(leftChildPredicates)) { exprFields.put(r.toString(), RelOptUtil.InputFinder.bits(r)); allExprsDigests.add(r.toString()); } } if (rPreds == null) { rightChildPredicates = null; } else { Mappings.TargetMapping rightMapping = Mappings.createShiftMapping( nSysFields + nFieldsLeft + nFieldsRight, nSysFields + nFieldsLeft, 0, nFieldsRight); rightChildPredicates = rPreds.accept( new RexPermuteInputsShuttle(rightMapping, joinRel.getInput(1))); for (RexNode r : RelOptUtil.conjunctions(rightChildPredicates)) { exprFields.put(r.toString(), RelOptUtil.InputFinder.bits(r)); allExprsDigests.add(r.toString()); } } equivalence = Maps.newTreeMap(); equalityPredicates = new HashSet<>(); for (int i = 0; i < nSysFields + nFieldsLeft + nFieldsRight; i++) { equivalence.put(i, BitSets.of(i)); } // Only process equivalences found in the join conditions. Processing // Equivalences from the left or right side infer predicates that are // already present in the Tree below the join. RexBuilder rexBuilder = joinRel.getCluster().getRexBuilder(); List<RexNode> exprs = RelOptUtil.conjunctions( compose(rexBuilder, ImmutableList.of(joinRel.getCondition()))); final EquivalenceFinder eF = new EquivalenceFinder(); new ArrayList<>( Lists.transform(exprs, new Function<RexNode, Void>() { public Void apply(RexNode input) { return input.accept(eF); } })); equivalence = BitSets.closure(equivalence); } /** * The PullUp Strategy is sound but not complete. * <ol> * <li>We only pullUp inferred predicates for now. Pulling up existing * predicates causes an explosion of duplicates. The existing predicates are * pushed back down as new predicates. Once we have rules to eliminate * duplicate Filter conditions, we should pullUp all predicates. * <li>For Left Outer: we infer new predicates from the left and set them as * applicable on the Right side. No predicates are pulledUp. * <li>Right Outer Joins are handled in an analogous manner. * <li>For Full Outer Joins no predicates are pulledUp or inferred. * </ol> */ public RelOptPredicateList inferPredicates( boolean includeEqualityInference) { final List<RexNode> inferredPredicates = new ArrayList<>(); final List<RexNode> nonFieldsPredicates = new ArrayList<>(); final Set<String> allExprsDigests = new HashSet<>(this.allExprsDigests); final JoinRelType joinType = joinRel.getJoinType(); final List<RexNode> leftPreds = ImmutableList.copyOf(RelOptUtil.conjunctions(leftChildPredicates)); final List<RexNode> rightPreds = ImmutableList.copyOf(RelOptUtil.conjunctions(rightChildPredicates)); switch (joinType) { case INNER: case LEFT: infer(leftPreds, allExprsDigests, inferredPredicates, nonFieldsPredicates, includeEqualityInference, joinType == JoinRelType.LEFT ? rightFieldsBitSet : allFieldsBitSet); break; } switch (joinType) { case INNER: case RIGHT: infer(rightPreds, allExprsDigests, inferredPredicates, nonFieldsPredicates, includeEqualityInference, joinType == JoinRelType.RIGHT ? leftFieldsBitSet : allFieldsBitSet); break; } Mappings.TargetMapping rightMapping = Mappings.createShiftMapping( nSysFields + nFieldsLeft + nFieldsRight, 0, nSysFields + nFieldsLeft, nFieldsRight); final RexPermuteInputsShuttle rightPermute = new RexPermuteInputsShuttle(rightMapping, joinRel); Mappings.TargetMapping leftMapping = Mappings.createShiftMapping( nSysFields + nFieldsLeft, 0, nSysFields, nFieldsLeft); final RexPermuteInputsShuttle leftPermute = new RexPermuteInputsShuttle(leftMapping, joinRel); final List<RexNode> leftInferredPredicates = new ArrayList<>(); final List<RexNode> rightInferredPredicates = new ArrayList<>(); for (RexNode iP : inferredPredicates) { ImmutableBitSet iPBitSet = RelOptUtil.InputFinder.bits(iP); if (leftFieldsBitSet.contains(iPBitSet)) { leftInferredPredicates.add(iP.accept(leftPermute)); } else if (rightFieldsBitSet.contains(iPBitSet)) { rightInferredPredicates.add(iP.accept(rightPermute)); } } if (joinType == JoinRelType.INNER && !nonFieldsPredicates.isEmpty()) { // Predicates without field references can be pushed to both inputs final Set<String> leftPredsSet = new HashSet<String>( Lists.transform(leftPreds, HiveCalciteUtil.REX_STR_FN)); final Set<String> rightPredsSet = new HashSet<String>( Lists.transform(rightPreds, HiveCalciteUtil.REX_STR_FN)); for (RexNode iP : nonFieldsPredicates) { if (!leftPredsSet.contains(iP.toString())) { leftInferredPredicates.add(iP); } if (!rightPredsSet.contains(iP.toString())) { rightInferredPredicates.add(iP); } } } switch (joinType) { case INNER: Iterable<RexNode> pulledUpPredicates; if (isSemiJoin) { pulledUpPredicates = Iterables.concat(leftPreds, leftInferredPredicates); } else { pulledUpPredicates = Iterables.concat(leftPreds, rightPreds, RelOptUtil.conjunctions(joinRel.getCondition()), inferredPredicates); } return RelOptPredicateList.of( pulledUpPredicates, leftInferredPredicates, rightInferredPredicates); case LEFT: return RelOptPredicateList.of( leftPreds, EMPTY_LIST, rightInferredPredicates); case RIGHT: return RelOptPredicateList.of( rightPreds, leftInferredPredicates, EMPTY_LIST); default: assert inferredPredicates.size() == 0; return RelOptPredicateList.EMPTY; } } public RexNode left() { return leftChildPredicates; } public RexNode right() { return rightChildPredicates; } private void infer(List<RexNode> predicates, Set<String> allExprsDigests, List<RexNode> inferedPredicates, List<RexNode> nonFieldsPredicates, boolean includeEqualityInference, ImmutableBitSet inferringFields) { for (RexNode r : predicates) { if (!includeEqualityInference && equalityPredicates.contains(r.toString())) { continue; } Iterable<Mapping> ms = mappings(r); if (ms.iterator().hasNext()) { for (Mapping m : ms) { RexNode tr = r.accept( new RexPermuteInputsShuttle(m, joinRel.getInput(0), joinRel.getInput(1))); if (inferringFields.contains(RelOptUtil.InputFinder.bits(tr)) && !allExprsDigests.contains(tr.toString()) && !isAlwaysTrue(tr)) { inferedPredicates.add(tr); allExprsDigests.add(tr.toString()); } } } else { if (!isAlwaysTrue(r)) { nonFieldsPredicates.add(r); } } } } Iterable<Mapping> mappings(final RexNode predicate) { return new Iterable<Mapping>() { public Iterator<Mapping> iterator() { ImmutableBitSet fields = exprFields.get(predicate.toString()); if (fields.cardinality() == 0) { return Iterators.emptyIterator(); } return new ExprsItr(fields); } }; } private void equivalent(int p1, int p2) { BitSet b = equivalence.get(p1); b.set(p2); b = equivalence.get(p2); b.set(p1); } RexNode compose(RexBuilder rexBuilder, Iterable<RexNode> exprs) { exprs = Linq4j.asEnumerable(exprs).where(new Predicate1<RexNode>() { public boolean apply(RexNode expr) { return expr != null; } }); return RexUtil.composeConjunction(rexBuilder, exprs, false); } /** * Find expressions of the form 'col_x = col_y'. */ class EquivalenceFinder extends RexVisitorImpl<Void> { protected EquivalenceFinder() { super(true); } @Override public Void visitCall(RexCall call) { if (call.getOperator().getKind() == SqlKind.EQUALS) { int lPos = pos(call.getOperands().get(0)); int rPos = pos(call.getOperands().get(1)); if (lPos != -1 && rPos != -1) { JoinConditionBasedPredicateInference.this.equivalent(lPos, rPos); JoinConditionBasedPredicateInference.this.equalityPredicates .add(call.toString()); } } return null; } } /** * Given an expression returns all the possible substitutions. * * <p>For example, for an expression 'a + b + c' and the following * equivalences: <pre> * a : {a, b} * b : {a, b} * c : {c, e} * </pre> * * <p>The following Mappings will be returned: * <pre> * {a &rarr; a, b &rarr; a, c &rarr; c} * {a &rarr; a, b &rarr; a, c &rarr; e} * {a &rarr; a, b &rarr; b, c &rarr; c} * {a &rarr; a, b &rarr; b, c &rarr; e} * {a &rarr; b, b &rarr; a, c &rarr; c} * {a &rarr; b, b &rarr; a, c &rarr; e} * {a &rarr; b, b &rarr; b, c &rarr; c} * {a &rarr; b, b &rarr; b, c &rarr; e} * </pre> * * <p>which imply the following inferences: * <pre> * a + a + c * a + a + e * a + b + c * a + b + e * b + a + c * b + a + e * b + b + c * b + b + e * </pre> */ class ExprsItr implements Iterator<Mapping> { final int[] columns; final BitSet[] columnSets; final int[] iterationIdx; Mapping nextMapping; boolean firstCall; ExprsItr(ImmutableBitSet fields) { nextMapping = null; columns = new int[fields.cardinality()]; columnSets = new BitSet[fields.cardinality()]; iterationIdx = new int[fields.cardinality()]; for (int j = 0, i = fields.nextSetBit(0); i >= 0; i = fields .nextSetBit(i + 1), j++) { columns[j] = i; columnSets[j] = equivalence.get(i); iterationIdx[j] = 0; } firstCall = true; } public boolean hasNext() { if (firstCall) { initializeMapping(); firstCall = false; } else { computeNextMapping(iterationIdx.length - 1); } return nextMapping != null; } public Mapping next() { return nextMapping; } public void remove() { throw new UnsupportedOperationException(); } private void computeNextMapping(int level) { int t = columnSets[level].nextSetBit(iterationIdx[level]); if (t < 0) { if (level == 0) { nextMapping = null; } else { iterationIdx[level] = 0; computeNextMapping(level - 1); } } else { nextMapping.set(columns[level], t); iterationIdx[level] = t + 1; } } private void initializeMapping() { nextMapping = Mappings.create(MappingType.PARTIAL_FUNCTION, nSysFields + nFieldsLeft + nFieldsRight, nSysFields + nFieldsLeft + nFieldsRight); for (int i = 0; i < columnSets.length; i++) { BitSet c = columnSets[i]; int t = c.nextSetBit(iterationIdx[i]); if (t < 0) { nextMapping = null; return; } nextMapping.set(columns[i], t); iterationIdx[i] = t + 1; } } } private int pos(RexNode expr) { if (expr instanceof RexInputRef) { return ((RexInputRef) expr).getIndex(); } return -1; } private boolean isAlwaysTrue(RexNode predicate) { if (predicate instanceof RexCall) { RexCall c = (RexCall) predicate; if (c.getOperator().getKind() == SqlKind.EQUALS) { int lPos = pos(c.getOperands().get(0)); int rPos = pos(c.getOperands().get(1)); return lPos != -1 && lPos == rPos; } } return predicate.isAlwaysTrue(); } } }
/**************************************************************** * Licensed to the AOS Community (AOS) under one or more * * contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The AOS 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. * ****************************************************************/ /* * @(#)Joins.java 1.32 10/03/23 * * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * -Redistribution of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Oracle or the names of contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or intended * for use in the design, construction, operation or maintenance of any * nuclear facility. */ /* * @(#)Joins.java 1.32 10/03/23 */ package java2d.demos.Lines; import static java.awt.Color.*; import java.awt.*; import java.awt.event.*; import java.awt.geom.AffineTransform; import java.awt.geom.GeneralPath; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.*; import java2d.ControlsSurface; import java2d.CustomControls; /** * BasicStroke join types and width sizes illustrated. Control for * rendering a shape returned from BasicStroke.createStrokedShape(Shape). */ public class Joins extends ControlsSurface implements ChangeListener { protected int joinType = BasicStroke.JOIN_MITER; protected float bswidth = 20.0f; protected JSlider slider; protected JLabel label; public Joins() { setBackground(WHITE); slider = new JSlider(JSlider.VERTICAL, 0, 100, (int)(bswidth*2)); slider.setPreferredSize(new Dimension(15, 100)); slider.addChangeListener(this); setControls(new Component[] { new DemoControls(this), slider }); setConstraints(new String[] { BorderLayout.NORTH, BorderLayout.WEST}); } public void stateChanged(ChangeEvent e) { // when using these sliders use double buffering, which means // ignoring when DemoSurface.imageType = 'On Screen' if (getImageType() <= 1) { setImageType(2); } bswidth = (float) slider.getValue() / 2.0f; label.setText(" Width = " + String.valueOf(bswidth)); label.repaint(); repaint(); } public void render(int w, int h, Graphics2D g2) { BasicStroke bs = new BasicStroke(bswidth, BasicStroke.CAP_BUTT, joinType); GeneralPath p = new GeneralPath(); p.moveTo(- w / 4.0f, - h / 12.0f); p.lineTo(+ w / 4.0f, - h / 12.0f); p.lineTo(- w / 6.0f, + h / 4.0f); p.lineTo(+ 0.0f, - h / 4.0f); p.lineTo(+ w / 6.0f, + h / 4.0f); p.closePath(); p.closePath(); g2.translate(w/2, h/2); g2.setColor(BLACK); g2.draw(bs.createStrokedShape(p)); } public static void main(String s[]) { createDemoFrame(new Joins()); } class DemoControls extends CustomControls implements ActionListener { Joins demo; int joinType[] = { BasicStroke.JOIN_MITER, BasicStroke.JOIN_ROUND, BasicStroke.JOIN_BEVEL }; String joinName[] = { "Mitered Join", "Rounded Join", "Beveled Join" }; JMenu menu; JMenuItem menuitem[] = new JMenuItem[joinType.length]; JoinIcon icons[] = new JoinIcon[joinType.length]; JToolBar toolbar; public DemoControls(Joins demo) { super(demo.name); setBorder(new CompoundBorder(getBorder(), new EmptyBorder(2, 2, 2, 2))); this.demo = demo; setLayout(new BorderLayout()); label = new JLabel(" Width = " + String.valueOf(demo.bswidth)); Font font = new Font("serif", Font.BOLD, 14); label.setFont(font); add("West", label); JMenuBar menubar = new JMenuBar(); add("East", menubar); menu = (JMenu) menubar.add(new JMenu(joinName[0])); menu.setFont(font = new Font("serif", Font.PLAIN, 10)); for (int i = 0; i < joinType.length; i++) { icons[i]= new JoinIcon(joinType[i]); menuitem[i] = menu.add(new JMenuItem(joinName[i])); menuitem[i].setFont(font); menuitem[i].setIcon(icons[i]); menuitem[i].addActionListener(this); } menu.setIcon(icons[0]); } public void actionPerformed(ActionEvent e) { for (int i = 0; i < joinType.length; i++) { if (e.getSource().equals(menuitem[i])) { demo.joinType = joinType[i]; menu.setIcon(icons[i]); menu.setText(joinName[i]); break; } } demo.repaint(); } public Dimension getPreferredSize() { return new Dimension(200,37); } public void run() { try { thread.sleep(999); } catch (Exception e) { return; } Thread me = Thread.currentThread(); while (thread == me) { for (int i = 0; i < menuitem.length; i++) { menuitem[i].doClick(); for (int k = 10; k < 60; k+=2) { demo.slider.setValue(k); try { thread.sleep(100); } catch (InterruptedException e) { return; } } try { thread.sleep(999); } catch (InterruptedException e) { return; } } } thread = null; } class JoinIcon implements Icon { int joinType; public JoinIcon(int joinType) { this.joinType = joinType; } public void paintIcon(Component c, Graphics g, int x, int y) { ((Graphics2D) g).setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); BasicStroke bs = new BasicStroke(8.0f, BasicStroke.CAP_BUTT, joinType); ((Graphics2D) g).setStroke(bs); GeneralPath p = new GeneralPath(); p.moveTo(0, 3); p.lineTo(getIconWidth()-2, getIconHeight()/2); p.lineTo(0,getIconHeight()); ((Graphics2D) g).draw(p); } public int getIconWidth() { return 20; } public int getIconHeight() { return 20; } } // End JoinIcon class } // End DemoControls class } // End Joins class
/* * Copyright 2014 The Netty Project * * The Netty Project 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 io.netty.handler.ssl; import java.security.KeyStore; import java.security.Provider; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSessionContext; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import java.io.File; import java.security.PrivateKey; import java.security.cert.X509Certificate; /** * A client-side {@link SslContext} which uses JDK's SSL/TLS implementation. * * @deprecated Use {@link SslContextBuilder} to create {@link JdkSslContext} instances and only * use {@link JdkSslContext} in your code. */ @Deprecated public final class JdkSslClientContext extends JdkSslContext { /** * Creates a new instance. * * @deprecated use {@link SslContextBuilder} */ @Deprecated public JdkSslClientContext() throws SSLException { this(null, null); } /** * Creates a new instance. * * @param certChainFile an X.509 certificate chain file in PEM format. * {@code null} to use the system default * @deprecated use {@link SslContextBuilder} */ @Deprecated public JdkSslClientContext(File certChainFile) throws SSLException { this(certChainFile, null); } /** * Creates a new instance. * * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s * that verifies the certificates sent from servers. * {@code null} to use the default. * @deprecated use {@link SslContextBuilder} */ @Deprecated public JdkSslClientContext(TrustManagerFactory trustManagerFactory) throws SSLException { this(null, trustManagerFactory); } /** * Creates a new instance. * * @param certChainFile an X.509 certificate chain file in PEM format. * {@code null} to use the system default * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s * that verifies the certificates sent from servers. * {@code null} to use the default. * @deprecated use {@link SslContextBuilder} */ @Deprecated public JdkSslClientContext(File certChainFile, TrustManagerFactory trustManagerFactory) throws SSLException { this(certChainFile, trustManagerFactory, null, IdentityCipherSuiteFilter.INSTANCE, JdkDefaultApplicationProtocolNegotiator.INSTANCE, 0, 0); } /** * Creates a new instance. * * @param certChainFile an X.509 certificate chain file in PEM format. * {@code null} to use the system default * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s * that verifies the certificates sent from servers. * {@code null} to use the default. * @param ciphers the cipher suites to enable, in the order of preference. * {@code null} to use the default cipher suites. * @param nextProtocols the application layer protocols to accept, in the order of preference. * {@code null} to disable TLS NPN/ALPN extension. * @param sessionCacheSize the size of the cache used for storing SSL session objects. * {@code 0} to use the default value. * @param sessionTimeout the timeout for the cached SSL session objects, in seconds. * {@code 0} to use the default value. * @deprecated use {@link SslContextBuilder} */ @Deprecated public JdkSslClientContext( File certChainFile, TrustManagerFactory trustManagerFactory, Iterable<String> ciphers, Iterable<String> nextProtocols, long sessionCacheSize, long sessionTimeout) throws SSLException { this(certChainFile, trustManagerFactory, ciphers, IdentityCipherSuiteFilter.INSTANCE, toNegotiator(toApplicationProtocolConfig(nextProtocols), false), sessionCacheSize, sessionTimeout); } /** * Creates a new instance. * * @param certChainFile an X.509 certificate chain file in PEM format. * {@code null} to use the system default * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s * that verifies the certificates sent from servers. * {@code null} to use the default. * @param ciphers the cipher suites to enable, in the order of preference. * {@code null} to use the default cipher suites. * @param cipherFilter a filter to apply over the supplied list of ciphers * @param apn Provides a means to configure parameters related to application protocol negotiation. * @param sessionCacheSize the size of the cache used for storing SSL session objects. * {@code 0} to use the default value. * @param sessionTimeout the timeout for the cached SSL session objects, in seconds. * {@code 0} to use the default value. * @deprecated use {@link SslContextBuilder} */ @Deprecated public JdkSslClientContext( File certChainFile, TrustManagerFactory trustManagerFactory, Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn, long sessionCacheSize, long sessionTimeout) throws SSLException { this(certChainFile, trustManagerFactory, ciphers, cipherFilter, toNegotiator(apn, false), sessionCacheSize, sessionTimeout); } /** * Creates a new instance. * * @param certChainFile an X.509 certificate chain file in PEM format. * {@code null} to use the system default * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s * that verifies the certificates sent from servers. * {@code null} to use the default. * @param ciphers the cipher suites to enable, in the order of preference. * {@code null} to use the default cipher suites. * @param cipherFilter a filter to apply over the supplied list of ciphers * @param apn Application Protocol Negotiator object. * @param sessionCacheSize the size of the cache used for storing SSL session objects. * {@code 0} to use the default value. * @param sessionTimeout the timeout for the cached SSL session objects, in seconds. * {@code 0} to use the default value. * @deprecated use {@link SslContextBuilder} */ @Deprecated public JdkSslClientContext( File certChainFile, TrustManagerFactory trustManagerFactory, Iterable<String> ciphers, CipherSuiteFilter cipherFilter, JdkApplicationProtocolNegotiator apn, long sessionCacheSize, long sessionTimeout) throws SSLException { this(null, certChainFile, trustManagerFactory, ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout); } JdkSslClientContext(Provider provider, File trustCertCollectionFile, TrustManagerFactory trustManagerFactory, Iterable<String> ciphers, CipherSuiteFilter cipherFilter, JdkApplicationProtocolNegotiator apn, long sessionCacheSize, long sessionTimeout) throws SSLException { super(newSSLContext(provider, toX509CertificatesInternal(trustCertCollectionFile), trustManagerFactory, null, null, null, null, sessionCacheSize, sessionTimeout, KeyStore.getDefaultType()), true, ciphers, cipherFilter, apn, ClientAuth.NONE, null, false); } /** * Creates a new instance. * @param trustCertCollectionFile an X.509 certificate collection file in PEM format. * {@code null} to use the system default * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s * that verifies the certificates sent from servers. * {@code null} to use the default or the results of parsing * {@code trustCertCollectionFile} * @param keyCertChainFile an X.509 certificate chain file in PEM format. * This provides the public key for mutual authentication. * {@code null} to use the system default * @param keyFile a PKCS#8 private key file in PEM format. * This provides the private key for mutual authentication. * {@code null} for no mutual authentication. * @param keyPassword the password of the {@code keyFile}. * {@code null} if it's not password-protected. * Ignored if {@code keyFile} is {@code null}. * @param keyManagerFactory the {@link KeyManagerFactory} that provides the {@link KeyManager}s * that is used to encrypt data being sent to servers. * {@code null} to use the default or the results of parsing * {@code keyCertChainFile} and {@code keyFile}. * @param ciphers the cipher suites to enable, in the order of preference. * {@code null} to use the default cipher suites. * @param cipherFilter a filter to apply over the supplied list of ciphers * @param apn Provides a means to configure parameters related to application protocol negotiation. * @param sessionCacheSize the size of the cache used for storing SSL session objects. * {@code 0} to use the default value. * @param sessionTimeout the timeout for the cached SSL session objects, in seconds. * {@code 0} to use the default value. * @deprecated use {@link SslContextBuilder} */ @Deprecated public JdkSslClientContext(File trustCertCollectionFile, TrustManagerFactory trustManagerFactory, File keyCertChainFile, File keyFile, String keyPassword, KeyManagerFactory keyManagerFactory, Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn, long sessionCacheSize, long sessionTimeout) throws SSLException { this(trustCertCollectionFile, trustManagerFactory, keyCertChainFile, keyFile, keyPassword, keyManagerFactory, ciphers, cipherFilter, toNegotiator(apn, false), sessionCacheSize, sessionTimeout); } /** * Creates a new instance. * @param trustCertCollectionFile an X.509 certificate collection file in PEM format. * {@code null} to use the system default * @param trustManagerFactory the {@link TrustManagerFactory} that provides the {@link TrustManager}s * that verifies the certificates sent from servers. * {@code null} to use the default or the results of parsing * {@code trustCertCollectionFile} * @param keyCertChainFile an X.509 certificate chain file in PEM format. * This provides the public key for mutual authentication. * {@code null} to use the system default * @param keyFile a PKCS#8 private key file in PEM format. * This provides the private key for mutual authentication. * {@code null} for no mutual authentication. * @param keyPassword the password of the {@code keyFile}. * {@code null} if it's not password-protected. * Ignored if {@code keyFile} is {@code null}. * @param keyManagerFactory the {@link KeyManagerFactory} that provides the {@link KeyManager}s * that is used to encrypt data being sent to servers. * {@code null} to use the default or the results of parsing * {@code keyCertChainFile} and {@code keyFile}. * @param ciphers the cipher suites to enable, in the order of preference. * {@code null} to use the default cipher suites. * @param cipherFilter a filter to apply over the supplied list of ciphers * @param apn Application Protocol Negotiator object. * @param sessionCacheSize the size of the cache used for storing SSL session objects. * {@code 0} to use the default value. * @param sessionTimeout the timeout for the cached SSL session objects, in seconds. * {@code 0} to use the default value. * @deprecated use {@link SslContextBuilder} */ @Deprecated public JdkSslClientContext(File trustCertCollectionFile, TrustManagerFactory trustManagerFactory, File keyCertChainFile, File keyFile, String keyPassword, KeyManagerFactory keyManagerFactory, Iterable<String> ciphers, CipherSuiteFilter cipherFilter, JdkApplicationProtocolNegotiator apn, long sessionCacheSize, long sessionTimeout) throws SSLException { super(newSSLContext(null, toX509CertificatesInternal( trustCertCollectionFile), trustManagerFactory, toX509CertificatesInternal(keyCertChainFile), toPrivateKeyInternal(keyFile, keyPassword), keyPassword, keyManagerFactory, sessionCacheSize, sessionTimeout, KeyStore.getDefaultType()), true, ciphers, cipherFilter, apn, ClientAuth.NONE, null, false); } JdkSslClientContext(Provider sslContextProvider, X509Certificate[] trustCertCollection, TrustManagerFactory trustManagerFactory, X509Certificate[] keyCertChain, PrivateKey key, String keyPassword, KeyManagerFactory keyManagerFactory, Iterable<String> ciphers, CipherSuiteFilter cipherFilter, ApplicationProtocolConfig apn, String[] protocols, long sessionCacheSize, long sessionTimeout, String keyStoreType) throws SSLException { super(newSSLContext(sslContextProvider, trustCertCollection, trustManagerFactory, keyCertChain, key, keyPassword, keyManagerFactory, sessionCacheSize, sessionTimeout, keyStoreType), true, ciphers, cipherFilter, toNegotiator(apn, false), ClientAuth.NONE, protocols, false); } private static SSLContext newSSLContext(Provider sslContextProvider, X509Certificate[] trustCertCollection, TrustManagerFactory trustManagerFactory, X509Certificate[] keyCertChain, PrivateKey key, String keyPassword, KeyManagerFactory keyManagerFactory, long sessionCacheSize, long sessionTimeout, String keyStore) throws SSLException { try { if (trustCertCollection != null) { trustManagerFactory = buildTrustManagerFactory(trustCertCollection, trustManagerFactory, keyStore); } if (keyCertChain != null) { keyManagerFactory = buildKeyManagerFactory(keyCertChain, key, keyPassword, keyManagerFactory, null); } SSLContext ctx = sslContextProvider == null ? SSLContext.getInstance(PROTOCOL) : SSLContext.getInstance(PROTOCOL, sslContextProvider); ctx.init(keyManagerFactory == null ? null : keyManagerFactory.getKeyManagers(), trustManagerFactory == null ? null : trustManagerFactory.getTrustManagers(), null); SSLSessionContext sessCtx = ctx.getClientSessionContext(); if (sessionCacheSize > 0) { sessCtx.setSessionCacheSize((int) Math.min(sessionCacheSize, Integer.MAX_VALUE)); } if (sessionTimeout > 0) { sessCtx.setSessionTimeout((int) Math.min(sessionTimeout, Integer.MAX_VALUE)); } return ctx; } catch (Exception e) { if (e instanceof SSLException) { throw (SSLException) e; } throw new SSLException("failed to initialize the client-side SSL context", e); } } }
/*! * Copyright 2010 - 2013 Pentaho Corporation. All rights reserved. * * 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.pentaho.mongo; import java.util.HashMap; import java.util.Map; import javax.security.auth.Subject; import javax.security.auth.login.AppConfigurationEntry; import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag; import javax.security.auth.login.Configuration; import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; import com.sun.security.auth.module.Krb5LoginModule; /** * A collection of utilities for working with Kerberos. * * Note: This specifically does not support IBM VMs and must be modified to do * so: 1) LoginModule name differs, 2) Configuration defaults differ for ticket * cache, keytab, and others. * * @author Jordan Ganoff <jganoff@pentaho.com> */ public class KerberosUtil { /** * The application name to use when creating login contexts. */ private static final String KERBEROS_APP_NAME = "pentaho"; /** * The environment property to set to enable JAAS debugging for the * LoginConfiguration created by this utility. */ private static final String PENTAHO_JAAS_DEBUG = "PENTAHO_JAAS_DEBUG"; /** * Base properties to be inherited by all other LOGIN_CONFIG* configuration * maps. */ private static final Map<String, String> LOGIN_CONFIG_BASE; static { LOGIN_CONFIG_BASE = new HashMap<String, String>(); // Enable JAAS debug if PENTAHO_JAAS_DEBUG is set if (Boolean.parseBoolean(System.getenv(PENTAHO_JAAS_DEBUG))) { LOGIN_CONFIG_BASE.put("debug", Boolean.TRUE.toString()); } } /** * Login Configuration options for KERBEROS_USER mode. */ private static final Map<String, String> LOGIN_CONFIG_OPTS_KERBEROS_USER; static { LOGIN_CONFIG_OPTS_KERBEROS_USER = new HashMap<String, String>(LOGIN_CONFIG_BASE); // Never prompt for passwords LOGIN_CONFIG_OPTS_KERBEROS_USER.put("doNotPrompt", Boolean.TRUE.toString()); LOGIN_CONFIG_OPTS_KERBEROS_USER.put("useTicketCache", Boolean.TRUE.toString()); // Attempt to renew tickets LOGIN_CONFIG_OPTS_KERBEROS_USER.put("renewTGT", Boolean.TRUE.toString()); // Set the ticket cache if it was defined externally String ticketCache = System.getenv("KRB5CCNAME"); if (ticketCache != null) { LOGIN_CONFIG_OPTS_KERBEROS_USER.put("ticketCache", ticketCache); } } /** * Login Configuration options for KERBEROS_KEYTAB mode. */ private static final Map<String, String> LOGIN_CONFIG_OPTS_KERBEROS_KEYTAB; static { LOGIN_CONFIG_OPTS_KERBEROS_KEYTAB = new HashMap<String, String>(LOGIN_CONFIG_BASE); // Never prompt for passwords LOGIN_CONFIG_OPTS_KERBEROS_KEYTAB.put("doNotPrompt", Boolean.TRUE.toString()); // Use a keytab file LOGIN_CONFIG_OPTS_KERBEROS_KEYTAB.put("useKeyTab", Boolean.TRUE.toString()); LOGIN_CONFIG_OPTS_KERBEROS_KEYTAB.put("storeKey", Boolean.TRUE.toString()); // Refresh KRB5 config before logging in LOGIN_CONFIG_OPTS_KERBEROS_KEYTAB.put("refreshKrb5Config", Boolean.TRUE.toString()); } /** * The Login Configuration entry to use for authenticating with Kerberos. */ private static final AppConfigurationEntry CONFIG_ENTRY_PENTAHO_KERBEROS_USER = new AppConfigurationEntry( Krb5LoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, LOGIN_CONFIG_OPTS_KERBEROS_USER); /** * Static configuration to use when KERBEROS_USER mode is enabled. */ private static final AppConfigurationEntry[] CONFIG_ENTRIES_KERBEROS_USER = new AppConfigurationEntry[] { CONFIG_ENTRY_PENTAHO_KERBEROS_USER }; /** * A Login Configuration that is pre-configured based on our static * configuration. */ private static class PentahoLoginConfiguration extends Configuration { private AppConfigurationEntry[] entries; public PentahoLoginConfiguration(AppConfigurationEntry[] entries) { if (entries == null) { throw new NullPointerException("AppConfigurationEntry[] is required"); } this.entries = entries; } @Override public AppConfigurationEntry[] getAppConfigurationEntry(String ignored) { return entries; } } /** * Defines the types of Kerberos authentication modes we support. */ public static enum JaasAuthenticationMode { /** * User has pre-authenticated with Kerberos (likely via kinit) and has * launched this process within that authenticated environment. */ KERBEROS_USER, /** * A keytab file must be used to authenticate. */ KERBEROS_KEYTAB, /** * A default authentication mode to bypass our static configuration. This is * to be used with an externally configured JAAS Configuration file. */ EXTERNAL; }; /** * Log in as the provided principal. If a keytab file is specified in the * environment property "PENTAHO_JAAS_KEYTAB_FILE", it will be used during * authentication. * * @see #loginAs(String, String) loginAs(principal, * env("PENTAHO_KEYTAB_FILE")) */ public static LoginContext loginAs(String principal) throws LoginException { return loginAs(JaasAuthenticationMode.KERBEROS_USER, principal, null); } /** * Log in as the provided principal. This assumes the user has already * authenticated with kerberos and a TGT exists in the cache. * * @param principal * Principal to login in as. * @param keytabFile * @return The context for the logged in principal. * @throws LoginException * Error encountered while logging in. */ public static LoginContext loginAs(JaasAuthenticationMode authMode, String principal, String keytabFile) throws LoginException { LoginContext lc; Subject subject; switch (authMode) { case EXTERNAL: // Use the default JAAS configuration by only supplying the app name lc = new LoginContext(KERBEROS_APP_NAME); case KERBEROS_USER: subject = new Subject(); lc = new LoginContext(KERBEROS_APP_NAME, subject, null, new PentahoLoginConfiguration(CONFIG_ENTRIES_KERBEROS_USER)); break; case KERBEROS_KEYTAB: lc = createLoginContextWithKeytab(principal, keytabFile); break; default: throw new IllegalArgumentException("Unsupported authentication mode: " + authMode); } // Perform the login lc.login(); return lc; } /** * Creates a {@link LoginContext} configured to authenticate with the provided * credentials. * * @param principal * Principal to authenticate as. * @param keytabFile * Keytab file with credentials to authenticate as the given * principal. * @return A login context configured to authenticate as the provided * principal via a keytab. * @throws LoginException * Error creating login context. */ private static LoginContext createLoginContextWithKeytab(String principal, String keytabFile) throws LoginException { if (keytabFile == null) { throw new IllegalArgumentException("A keytab file is required to authenticate with Kerberos via keytab"); } // Extend the default keytab config properties and set the necessary // overrides for this invocation Map<String, String> keytabConfig = new HashMap<String, String>(LOGIN_CONFIG_OPTS_KERBEROS_KEYTAB); keytabConfig.put("keyTab", keytabFile); keytabConfig.put("principal", principal); // Create the configuration and from them, a new login context AppConfigurationEntry config = new AppConfigurationEntry(Krb5LoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, keytabConfig); AppConfigurationEntry[] configEntries = new AppConfigurationEntry[] { config }; Subject subject = new Subject(); return new LoginContext(KERBEROS_APP_NAME, subject, null, new PentahoLoginConfiguration(configEntries)); } }
/* * Copyright 2020 Google LLC * * 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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/bigquery/datatransfer/v1/transfer.proto package com.google.cloud.bigquery.datatransfer.v1; /** * * * <pre> * Represents data transfer run state. * </pre> * * Protobuf enum {@code google.cloud.bigquery.datatransfer.v1.TransferState} */ public enum TransferState implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * State placeholder (0). * </pre> * * <code>TRANSFER_STATE_UNSPECIFIED = 0;</code> */ TRANSFER_STATE_UNSPECIFIED(0), /** * * * <pre> * Data transfer is scheduled and is waiting to be picked up by * data transfer backend (2). * </pre> * * <code>PENDING = 2;</code> */ PENDING(2), /** * * * <pre> * Data transfer is in progress (3). * </pre> * * <code>RUNNING = 3;</code> */ RUNNING(3), /** * * * <pre> * Data transfer completed successfully (4). * </pre> * * <code>SUCCEEDED = 4;</code> */ SUCCEEDED(4), /** * * * <pre> * Data transfer failed (5). * </pre> * * <code>FAILED = 5;</code> */ FAILED(5), /** * * * <pre> * Data transfer is cancelled (6). * </pre> * * <code>CANCELLED = 6;</code> */ CANCELLED(6), UNRECOGNIZED(-1), ; /** * * * <pre> * State placeholder (0). * </pre> * * <code>TRANSFER_STATE_UNSPECIFIED = 0;</code> */ public static final int TRANSFER_STATE_UNSPECIFIED_VALUE = 0; /** * * * <pre> * Data transfer is scheduled and is waiting to be picked up by * data transfer backend (2). * </pre> * * <code>PENDING = 2;</code> */ public static final int PENDING_VALUE = 2; /** * * * <pre> * Data transfer is in progress (3). * </pre> * * <code>RUNNING = 3;</code> */ public static final int RUNNING_VALUE = 3; /** * * * <pre> * Data transfer completed successfully (4). * </pre> * * <code>SUCCEEDED = 4;</code> */ public static final int SUCCEEDED_VALUE = 4; /** * * * <pre> * Data transfer failed (5). * </pre> * * <code>FAILED = 5;</code> */ public static final int FAILED_VALUE = 5; /** * * * <pre> * Data transfer is cancelled (6). * </pre> * * <code>CANCELLED = 6;</code> */ public static final int CANCELLED_VALUE = 6; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static TransferState valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. */ public static TransferState forNumber(int value) { switch (value) { case 0: return TRANSFER_STATE_UNSPECIFIED; case 2: return PENDING; case 3: return RUNNING; case 4: return SUCCEEDED; case 5: return FAILED; case 6: return CANCELLED; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<TransferState> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<TransferState> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<TransferState>() { public TransferState findValueByNumber(int number) { return TransferState.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.google.cloud.bigquery.datatransfer.v1.TransferProto.getDescriptor() .getEnumTypes() .get(1); } private static final TransferState[] VALUES = values(); public static TransferState valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private TransferState(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.cloud.bigquery.datatransfer.v1.TransferState) }
package com.github.dockerjava.jaxrs; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; import com.github.dockerjava.api.command.AttachContainerCmd; import com.github.dockerjava.api.command.AuthCmd; import com.github.dockerjava.api.command.BuildImageCmd; import com.github.dockerjava.api.command.CommitCmd; import com.github.dockerjava.api.command.ConnectToNetworkCmd; import com.github.dockerjava.api.command.ContainerDiffCmd; import com.github.dockerjava.api.command.CopyArchiveFromContainerCmd; import com.github.dockerjava.api.command.CopyArchiveToContainerCmd; import com.github.dockerjava.api.command.CopyFileFromContainerCmd; import com.github.dockerjava.api.command.CreateContainerCmd; import com.github.dockerjava.api.command.CreateImageCmd; import com.github.dockerjava.api.command.CreateNetworkCmd; import com.github.dockerjava.api.command.CreateServiceCmd; import com.github.dockerjava.api.command.CreateVolumeCmd; import com.github.dockerjava.api.command.DisconnectFromNetworkCmd; import com.github.dockerjava.api.command.DockerCmdExecFactory; import com.github.dockerjava.api.command.EventsCmd; import com.github.dockerjava.api.command.ExecCreateCmd; import com.github.dockerjava.api.command.ExecStartCmd; import com.github.dockerjava.api.command.InfoCmd; import com.github.dockerjava.api.command.InitializeSwarmCmd; import com.github.dockerjava.api.command.InspectContainerCmd; import com.github.dockerjava.api.command.InspectExecCmd; import com.github.dockerjava.api.command.InspectImageCmd; import com.github.dockerjava.api.command.InspectNetworkCmd; import com.github.dockerjava.api.command.InspectServiceCmd; import com.github.dockerjava.api.command.InspectSwarmCmd; import com.github.dockerjava.api.command.InspectSwarmNodeCmd; import com.github.dockerjava.api.command.InspectVolumeCmd; import com.github.dockerjava.api.command.JoinSwarmCmd; import com.github.dockerjava.api.command.KillContainerCmd; import com.github.dockerjava.api.command.LeaveSwarmCmd; import com.github.dockerjava.api.command.ListContainersCmd; import com.github.dockerjava.api.command.ListImagesCmd; import com.github.dockerjava.api.command.ListNetworksCmd; import com.github.dockerjava.api.command.ListServicesCmd; import com.github.dockerjava.api.command.ListSwarmNodesCmd; import com.github.dockerjava.api.command.ListVolumesCmd; import com.github.dockerjava.api.command.LoadImageCmd; import com.github.dockerjava.api.command.LogContainerCmd; import com.github.dockerjava.api.command.PauseContainerCmd; import com.github.dockerjava.api.command.PingCmd; import com.github.dockerjava.api.command.PullImageCmd; import com.github.dockerjava.api.command.PushImageCmd; import com.github.dockerjava.api.command.RemoveContainerCmd; import com.github.dockerjava.api.command.RemoveImageCmd; import com.github.dockerjava.api.command.RemoveNetworkCmd; import com.github.dockerjava.api.command.RemoveServiceCmd; import com.github.dockerjava.api.command.RemoveSwarmNodeCmd; import com.github.dockerjava.api.command.RemoveVolumeCmd; import com.github.dockerjava.api.command.RenameContainerCmd; import com.github.dockerjava.api.command.RestartContainerCmd; import com.github.dockerjava.api.command.SaveImageCmd; import com.github.dockerjava.api.command.SearchImagesCmd; import com.github.dockerjava.api.command.StartContainerCmd; import com.github.dockerjava.api.command.StatsCmd; import com.github.dockerjava.api.command.StopContainerCmd; import com.github.dockerjava.api.command.TagImageCmd; import com.github.dockerjava.api.command.TopContainerCmd; import com.github.dockerjava.api.command.UnpauseContainerCmd; import com.github.dockerjava.api.command.UpdateContainerCmd; import com.github.dockerjava.api.command.UpdateServiceCmd; import com.github.dockerjava.api.command.UpdateSwarmCmd; import com.github.dockerjava.api.command.UpdateSwarmNodeCmd; import com.github.dockerjava.api.command.VersionCmd; import com.github.dockerjava.api.command.WaitContainerCmd; import com.github.dockerjava.api.exception.DockerClientException; import com.github.dockerjava.core.DockerClientConfig; import com.github.dockerjava.core.SSLConfig; import com.github.dockerjava.jaxrs.filter.JsonClientFilter; import com.github.dockerjava.jaxrs.filter.ResponseStatusExceptionFilter; import com.github.dockerjava.jaxrs.filter.SelectiveLoggingFilter; import org.apache.http.client.config.RequestConfig; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.glassfish.jersey.CommonProperties; import org.glassfish.jersey.apache.connector.ApacheClientProperties; import org.glassfish.jersey.apache.connector.ApacheConnectorProvider; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.SSLContext; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.ClientRequestFilter; import javax.ws.rs.client.ClientResponseFilter; import javax.ws.rs.client.WebTarget; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.ProxySelector; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.concurrent.TimeUnit; import static com.google.common.base.Preconditions.checkNotNull; //import org.glassfish.jersey.apache.connector.ApacheConnectorProvider; // see https://github.com/docker-java/docker-java/issues/196 public class JerseyDockerCmdExecFactory implements DockerCmdExecFactory { private static final Logger LOGGER = LoggerFactory.getLogger(JerseyDockerCmdExecFactory.class.getName()); private Client client; private WebTarget baseResource; private Integer readTimeout = null; private Integer connectTimeout = null; private Integer maxTotalConnections = null; private Integer maxPerRouteConnections = null; private Integer connectionRequestTimeout = null; private ClientRequestFilter[] clientRequestFilters = null; private ClientResponseFilter[] clientResponseFilters = null; private DockerClientConfig dockerClientConfig; private PoolingHttpClientConnectionManager connManager = null; @Override public void init(DockerClientConfig dockerClientConfig) { checkNotNull(dockerClientConfig, "config was not specified"); this.dockerClientConfig = dockerClientConfig; ClientConfig clientConfig = new ClientConfig(); clientConfig.connectorProvider(new ApacheConnectorProvider()); clientConfig.property(CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true); clientConfig.register(ResponseStatusExceptionFilter.class); clientConfig.register(JsonClientFilter.class); clientConfig.register(JacksonJsonProvider.class); RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); clientConfig.register(new JacksonJsonProvider(objectMapper)); // logging may disabled via log level clientConfig.register(new SelectiveLoggingFilter(LOGGER, true)); if (readTimeout != null) { requestConfigBuilder.setSocketTimeout(readTimeout); clientConfig.property(ClientProperties.READ_TIMEOUT, readTimeout); } if (connectTimeout != null) { requestConfigBuilder.setConnectTimeout(connectTimeout); clientConfig.property(ClientProperties.CONNECT_TIMEOUT, connectTimeout); } if (clientResponseFilters != null) { for (ClientResponseFilter clientResponseFilter : clientResponseFilters) { if (clientResponseFilter != null) { clientConfig.register(clientResponseFilter); } } } if (clientRequestFilters != null) { for (ClientRequestFilter clientRequestFilter : clientRequestFilters) { if (clientRequestFilter != null) { clientConfig.register(clientRequestFilter); } } } URI originalUri = dockerClientConfig.getDockerHost(); String protocol = null; SSLContext sslContext = null; try { final SSLConfig sslConfig = dockerClientConfig.getSSLConfig(); if (sslConfig != null) { sslContext = sslConfig.getSSLContext(); } } catch (Exception ex) { throw new DockerClientException("Error in SSL Configuration", ex); } if (sslContext != null) { protocol = "https"; } else { protocol = "http"; } if (!originalUri.getScheme().equals("unix")) { try { originalUri = new URI(originalUri.toString().replaceFirst("tcp", protocol)); } catch (URISyntaxException e) { throw new RuntimeException(e); } configureProxy(clientConfig, originalUri, protocol); } connManager = new PoolingHttpClientConnectionManager(getSchemeRegistry( originalUri, sslContext)) { @Override public void close() { super.shutdown(); } @Override public void shutdown() { // Disable shutdown of the pool. This will be done later, when this factory is closed // This is a workaround for finalize method on jerseys ClientRuntime which // closes the client and shuts down the connection pool when it is garbage collected } }; if (maxTotalConnections != null) { connManager.setMaxTotal(maxTotalConnections); } if (maxPerRouteConnections != null) { connManager.setDefaultMaxPerRoute(maxPerRouteConnections); } clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, connManager); // Configure connection pool timeout if (connectionRequestTimeout != null) { requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeout); } clientConfig.property(ApacheClientProperties.REQUEST_CONFIG, requestConfigBuilder.build()); ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(clientConfig); if (sslContext != null) { clientBuilder.sslContext(sslContext); } client = clientBuilder.build(); baseResource = client.target(sanitizeUrl(originalUri).toString()).path(dockerClientConfig.getApiVersion().asWebPathPart()); } private URI sanitizeUrl(URI originalUri) { if (originalUri.getScheme().equals("unix")) { return UnixConnectionSocketFactory.sanitizeUri(originalUri); } return originalUri; } private void configureProxy(ClientConfig clientConfig, URI originalUri, String protocol) { List<Proxy> proxies = ProxySelector.getDefault().select(originalUri); for (Proxy proxy : proxies) { InetSocketAddress address = (InetSocketAddress) proxy.address(); if (address != null) { String hostname = address.getHostName(); int port = address.getPort(); clientConfig.property(ClientProperties.PROXY_URI, "http://" + hostname + ":" + port); String httpProxyUser = System.getProperty(protocol + ".proxyUser"); if (httpProxyUser != null) { clientConfig.property(ClientProperties.PROXY_USERNAME, httpProxyUser); String httpProxyPassword = System.getProperty(protocol + ".proxyPassword"); if (httpProxyPassword != null) { clientConfig.property(ClientProperties.PROXY_PASSWORD, httpProxyPassword); } } } } } private org.apache.http.config.Registry<ConnectionSocketFactory> getSchemeRegistry(final URI originalUri, SSLContext sslContext) { RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create(); registryBuilder.register("http", PlainConnectionSocketFactory.getSocketFactory()); if (sslContext != null) { registryBuilder.register("https", new SSLConnectionSocketFactory(sslContext)); } registryBuilder.register("unix", new UnixConnectionSocketFactory(originalUri)); return registryBuilder.build(); } protected WebTarget getBaseResource() { checkNotNull(baseResource, "Factory not initialized, baseResource not set. You probably forgot to call init()!"); return baseResource; } protected DockerClientConfig getDockerClientConfig() { checkNotNull(dockerClientConfig, "Factor not initialized, dockerClientConfig not set. You probably forgot to call init()!"); return dockerClientConfig; } @Override public AuthCmd.Exec createAuthCmdExec() { return new AuthCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public InfoCmd.Exec createInfoCmdExec() { return new InfoCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public PingCmd.Exec createPingCmdExec() { return new PingCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public VersionCmd.Exec createVersionCmdExec() { return new VersionCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public PullImageCmd.Exec createPullImageCmdExec() { return new PullImageCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public PushImageCmd.Exec createPushImageCmdExec() { return new PushImageCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public SaveImageCmd.Exec createSaveImageCmdExec() { return new SaveImageCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public CreateImageCmd.Exec createCreateImageCmdExec() { return new CreateImageCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public LoadImageCmd.Exec createLoadImageCmdExec() { return new LoadImageCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public SearchImagesCmd.Exec createSearchImagesCmdExec() { return new SearchImagesCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public RemoveImageCmd.Exec createRemoveImageCmdExec() { return new RemoveImageCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public ListImagesCmd.Exec createListImagesCmdExec() { return new ListImagesCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public InspectImageCmd.Exec createInspectImageCmdExec() { return new InspectImageCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public ListContainersCmd.Exec createListContainersCmdExec() { return new ListContainersCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public CreateContainerCmd.Exec createCreateContainerCmdExec() { return new CreateContainerCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public StartContainerCmd.Exec createStartContainerCmdExec() { return new StartContainerCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public InspectContainerCmd.Exec createInspectContainerCmdExec() { return new InspectContainerCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public ExecCreateCmd.Exec createExecCmdExec() { return new ExecCreateCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public RemoveContainerCmd.Exec createRemoveContainerCmdExec() { return new RemoveContainerCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public WaitContainerCmd.Exec createWaitContainerCmdExec() { return new WaitContainerCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public AttachContainerCmd.Exec createAttachContainerCmdExec() { return new AttachContainerCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public ExecStartCmd.Exec createExecStartCmdExec() { return new ExecStartCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public InspectExecCmd.Exec createInspectExecCmdExec() { return new InspectExecCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public LogContainerCmd.Exec createLogContainerCmdExec() { return new LogContainerCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public CopyArchiveFromContainerCmd.Exec createCopyArchiveFromContainerCmdExec() { return new CopyArchiveFromContainerCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public CopyFileFromContainerCmd.Exec createCopyFileFromContainerCmdExec() { return new CopyFileFromContainerCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public CopyArchiveToContainerCmd.Exec createCopyArchiveToContainerCmdExec() { return new CopyArchiveToContainerCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public StopContainerCmd.Exec createStopContainerCmdExec() { return new StopContainerCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public ContainerDiffCmd.Exec createContainerDiffCmdExec() { return new ContainerDiffCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public KillContainerCmd.Exec createKillContainerCmdExec() { return new KillContainerCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public UpdateContainerCmd.Exec createUpdateContainerCmdExec() { return new UpdateContainerCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public RenameContainerCmd.Exec createRenameContainerCmdExec() { return new RenameContainerCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public RestartContainerCmd.Exec createRestartContainerCmdExec() { return new RestartContainerCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public CommitCmd.Exec createCommitCmdExec() { return new CommitCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public BuildImageCmd.Exec createBuildImageCmdExec() { return new BuildImageCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public TopContainerCmd.Exec createTopContainerCmdExec() { return new TopContainerCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public TagImageCmd.Exec createTagImageCmdExec() { return new TagImageCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public PauseContainerCmd.Exec createPauseContainerCmdExec() { return new PauseContainerCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public UnpauseContainerCmd.Exec createUnpauseContainerCmdExec() { return new UnpauseContainerCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public EventsCmd.Exec createEventsCmdExec() { return new EventsCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public StatsCmd.Exec createStatsCmdExec() { return new StatsCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public CreateVolumeCmd.Exec createCreateVolumeCmdExec() { return new CreateVolumeCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public InspectVolumeCmd.Exec createInspectVolumeCmdExec() { return new InspectVolumeCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public RemoveVolumeCmd.Exec createRemoveVolumeCmdExec() { return new RemoveVolumeCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public ListVolumesCmd.Exec createListVolumesCmdExec() { return new ListVolumesCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public ListNetworksCmd.Exec createListNetworksCmdExec() { return new ListNetworksCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public InspectNetworkCmd.Exec createInspectNetworkCmdExec() { return new InspectNetworkCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public CreateNetworkCmd.Exec createCreateNetworkCmdExec() { return new CreateNetworkCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public RemoveNetworkCmd.Exec createRemoveNetworkCmdExec() { return new RemoveNetworkCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public ConnectToNetworkCmd.Exec createConnectToNetworkCmdExec() { return new ConnectToNetworkCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public DisconnectFromNetworkCmd.Exec createDisconnectFromNetworkCmdExec() { return new DisconnectFromNetworkCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public InitializeSwarmCmd.Exec createInitializeSwarmCmdExec() { return new InitializeSwarmCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public InspectSwarmCmd.Exec createInspectSwarmCmdExec() { return new InspectSwarmCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public JoinSwarmCmd.Exec createJoinSwarmCmdExec() { return new JoinSwarmCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public LeaveSwarmCmd.Exec createLeaveSwarmCmdExec() { return new LeaveSwarmCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public UpdateSwarmCmd.Exec createUpdateSwarmCmdExec() { return new UpdateSwarmCmdExec(getBaseResource(), getDockerClientConfig()); } // service @Override public ListServicesCmd.Exec createListServicesCmdExec() { return new ListServicesCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public CreateServiceCmd.Exec createCreateServiceCmdExec() { return new CreateServiceCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public InspectServiceCmd.Exec createInspectServiceCmdExec() { return new InspectServiceCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public UpdateServiceCmd.Exec createUpdateServiceCmdExec() { return new UpdateServiceCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public RemoveServiceCmd.Exec createRemoveServiceCmdExec() { return new RemoveServiceCmdExec(getBaseResource(), getDockerClientConfig()); } //node @Override public ListSwarmNodesCmd.Exec listSwarmNodeCmdExec() { return new ListSwarmNodesCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public InspectSwarmNodeCmd.Exec inspectSwarmNodeCmdExec() { return new InspectSwarmNodeCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public RemoveSwarmNodeCmd.Exec removeSwarmNodeCmdExec() { return new RemoveSwarmNodeCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public UpdateSwarmNodeCmd.Exec updateSwarmNodeCmdExec() { return new UpdateSwarmNodeCmdExec(getBaseResource(), getDockerClientConfig()); } @Override public void close() throws IOException { checkNotNull(client, "Factory not initialized. You probably forgot to call init()!"); client.close(); connManager.close(); } public JerseyDockerCmdExecFactory withReadTimeout(Integer readTimeout) { this.readTimeout = readTimeout; return this; } public JerseyDockerCmdExecFactory withConnectTimeout(Integer connectTimeout) { this.connectTimeout = connectTimeout; return this; } public JerseyDockerCmdExecFactory withMaxTotalConnections(Integer maxTotalConnections) { this.maxTotalConnections = maxTotalConnections; return this; } public JerseyDockerCmdExecFactory withMaxPerRouteConnections(Integer maxPerRouteConnections) { this.maxPerRouteConnections = maxPerRouteConnections; return this; } public JerseyDockerCmdExecFactory withConnectionRequestTimeout(Integer connectionRequestTimeout) { this.connectionRequestTimeout = connectionRequestTimeout; return this; } public JerseyDockerCmdExecFactory withClientResponseFilters(ClientResponseFilter... clientResponseFilter) { this.clientResponseFilters = clientResponseFilter; return this; } public JerseyDockerCmdExecFactory withClientRequestFilters(ClientRequestFilter... clientRequestFilters) { this.clientRequestFilters = clientRequestFilters; return this; } /** * release connections from the pool * * @param idleSeconds idle seconds, longer than the configured value will be evicted */ public void releaseConnection(long idleSeconds) { this.connManager.closeExpiredConnections(); this.connManager.closeIdleConnections(idleSeconds, TimeUnit.SECONDS); } }
/* * Copyright 2021 ThoughtWorks, Inc. * * 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.thoughtworks.go.plugin.access.artifact; import com.thoughtworks.go.config.ArtifactStore; import com.thoughtworks.go.domain.ArtifactPlan; import com.thoughtworks.go.domain.config.Configuration; import com.thoughtworks.go.plugin.access.DefaultPluginInteractionCallback; import com.thoughtworks.go.plugin.access.ExtensionsRegistry; import com.thoughtworks.go.plugin.access.PluginRequestHelper; import com.thoughtworks.go.plugin.access.artifact.model.PublishArtifactResponse; import com.thoughtworks.go.plugin.access.artifact.models.FetchArtifactEnvironmentVariable; import com.thoughtworks.go.plugin.access.common.AbstractExtension; import com.thoughtworks.go.plugin.access.common.settings.PluginSettingsJsonMessageHandler; import com.thoughtworks.go.plugin.access.common.settings.PluginSettingsJsonMessageHandler1_0; import com.thoughtworks.go.plugin.api.response.validation.ValidationResult; import com.thoughtworks.go.plugin.domain.common.PluginConfiguration; import com.thoughtworks.go.plugin.infra.PluginManager; import com.thoughtworks.go.util.command.EnvironmentVariableContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.thoughtworks.go.plugin.access.artifact.ArtifactExtensionConstants.*; import static com.thoughtworks.go.plugin.domain.common.PluginConstants.ARTIFACT_EXTENSION; @Component public class ArtifactExtension extends AbstractExtension { private final HashMap<String, ArtifactMessageConverter> messageHandlerMap = new HashMap<>(); @Autowired protected ArtifactExtension(PluginManager pluginManager, ExtensionsRegistry extensionsRegistry) { super(pluginManager, extensionsRegistry, new PluginRequestHelper(pluginManager, SUPPORTED_VERSIONS, ARTIFACT_EXTENSION), ARTIFACT_EXTENSION); addHandler(V1, new ArtifactMessageConverterV1(), new PluginSettingsJsonMessageHandler1_0()); addHandler(V2, new ArtifactMessageConverterV2(), new PluginSettingsJsonMessageHandler1_0()); } private void addHandler(String version, ArtifactMessageConverter extensionHandler, PluginSettingsJsonMessageHandler pluginSettingsJsonMessageHandler) { messageHandlerMap.put(version, extensionHandler); registerHandler(version, pluginSettingsJsonMessageHandler); } public com.thoughtworks.go.plugin.domain.artifact.Capabilities getCapabilities(String pluginId) { return pluginRequestHelper.submitRequest(pluginId, REQUEST_GET_CAPABILITIES, new DefaultPluginInteractionCallback<com.thoughtworks.go.plugin.domain.artifact.Capabilities>() { @Override public com.thoughtworks.go.plugin.domain.artifact.Capabilities onSuccess(String responseBody, Map<String, String> responseHeaders, String resolvedExtensionVersion) { return getMessageHandler(resolvedExtensionVersion).getCapabilitiesFromResponseBody(responseBody); } }); } public List<PluginConfiguration> getArtifactStoreMetadata(String pluginId) { return pluginRequestHelper.submitRequest(pluginId, REQUEST_STORE_CONFIG_METADATA, new DefaultPluginInteractionCallback<List<PluginConfiguration>>() { @Override public List<PluginConfiguration> onSuccess(String responseBody, Map<String, String> responseHeaders, String resolvedExtensionVersion) { return getMessageHandler(resolvedExtensionVersion).getMetadataResponseFromBody(responseBody); } }); } public String getArtifactStoreView(String pluginId) { return pluginRequestHelper.submitRequest(pluginId, REQUEST_STORE_CONFIG_VIEW, new DefaultPluginInteractionCallback<String>() { @Override public String onSuccess(String responseBody, Map<String, String> responseHeaders, String resolvedExtensionVersion) { return getMessageHandler(resolvedExtensionVersion).getViewFromResponseBody(responseBody, "Artifact store view"); } }); } public ValidationResult validateArtifactStoreConfig(final String pluginId, final Map<String, String> configuration) { return pluginRequestHelper.submitRequest(pluginId, REQUEST_STORE_CONFIG_VALIDATE, new DefaultPluginInteractionCallback<ValidationResult>() { @Override public String requestBody(String resolvedExtensionVersion) { return getMessageHandler(resolvedExtensionVersion).validateConfigurationRequestBody(configuration); } @Override public ValidationResult onSuccess(String responseBody, Map<String, String> responseHeaders, String resolvedExtensionVersion) { return getMessageHandler(resolvedExtensionVersion).getConfigurationValidationResultFromResponseBody(responseBody); } }); } public List<PluginConfiguration> getPublishArtifactMetadata(String pluginId) { return pluginRequestHelper.submitRequest(pluginId, REQUEST_PUBLISH_ARTIFACT_METADATA, new DefaultPluginInteractionCallback<List<PluginConfiguration>>() { @Override public List<PluginConfiguration> onSuccess(String responseBody, Map<String, String> responseHeaders, String resolvedExtensionVersion) { return getMessageHandler(resolvedExtensionVersion).getMetadataResponseFromBody(responseBody); } }); } public String getPublishArtifactView(String pluginId) { return pluginRequestHelper.submitRequest(pluginId, REQUEST_PUBLISH_ARTIFACT_VIEW, new DefaultPluginInteractionCallback<String>() { @Override public String onSuccess(String responseBody, Map<String, String> responseHeaders, String resolvedExtensionVersion) { return getMessageHandler(resolvedExtensionVersion).getViewFromResponseBody(responseBody, "Publish artifact view"); } }); } public ValidationResult validatePluggableArtifactConfig(final String pluginId, final Map<String, String> configuration) { return pluginRequestHelper.submitRequest(pluginId, REQUEST_PUBLISH_ARTIFACT_VALIDATE, new DefaultPluginInteractionCallback<ValidationResult>() { @Override public String requestBody(String resolvedExtensionVersion) { return getMessageHandler(resolvedExtensionVersion).validateConfigurationRequestBody(configuration); } @Override public ValidationResult onSuccess(String responseBody, Map<String, String> responseHeaders, String resolvedExtensionVersion) { return getMessageHandler(resolvedExtensionVersion).getConfigurationValidationResultFromResponseBody(responseBody); } }); } public PublishArtifactResponse publishArtifact(String pluginId, ArtifactPlan artifactPlan, ArtifactStore artifactStore, String agentWorkingDirectory, EnvironmentVariableContext environmentVariableContext) { return pluginRequestHelper.submitRequest(pluginId, REQUEST_PUBLISH_ARTIFACT, new DefaultPluginInteractionCallback<PublishArtifactResponse>() { @Override public String requestBody(String resolvedExtensionVersion) { return getMessageHandler(resolvedExtensionVersion).publishArtifactMessage(artifactPlan, artifactStore, agentWorkingDirectory, environmentVariableContext.getProperties()); } @Override public PublishArtifactResponse onSuccess(String responseBody, Map<String, String> responseHeaders, String resolvedExtensionVersion) { return getMessageHandler(resolvedExtensionVersion).publishArtifactResponse(responseBody); } }); } public List<PluginConfiguration> getFetchArtifactMetadata(String pluginId) { return pluginRequestHelper.submitRequest(pluginId, REQUEST_FETCH_ARTIFACT_METADATA, new DefaultPluginInteractionCallback<List<PluginConfiguration>>() { @Override public List<PluginConfiguration> onSuccess(String responseBody, Map<String, String> responseHeaders, String resolvedExtensionVersion) { return getMessageHandler(resolvedExtensionVersion).getMetadataResponseFromBody(responseBody); } }); } public String getFetchArtifactView(String pluginId) { return pluginRequestHelper.submitRequest(pluginId, REQUEST_FETCH_ARTIFACT_VIEW, new DefaultPluginInteractionCallback<String>() { @Override public String onSuccess(String responseBody, Map<String, String> responseHeaders, String resolvedExtensionVersion) { return getMessageHandler(resolvedExtensionVersion).getViewFromResponseBody(responseBody, "Fetch artifact view"); } }); } public ValidationResult validateFetchArtifactConfig(final String pluginId, final Map<String, String> configuration) { return pluginRequestHelper.submitRequest(pluginId, REQUEST_FETCH_ARTIFACT_VALIDATE, new DefaultPluginInteractionCallback<ValidationResult>() { @Override public String requestBody(String resolvedExtensionVersion) { return getMessageHandler(resolvedExtensionVersion).validateConfigurationRequestBody(configuration); } @Override public ValidationResult onSuccess(String responseBody, Map<String, String> responseHeaders, String resolvedExtensionVersion) { return getMessageHandler(resolvedExtensionVersion).getConfigurationValidationResultFromResponseBody(responseBody); } }); } com.thoughtworks.go.plugin.domain.common.Image getIcon(String pluginId) { return pluginRequestHelper.submitRequest(pluginId, REQUEST_GET_PLUGIN_ICON, new DefaultPluginInteractionCallback<com.thoughtworks.go.plugin.domain.common.Image>() { @Override public com.thoughtworks.go.plugin.domain.common.Image onSuccess(String responseBody, Map<String, String> responseHeaders, String resolvedExtensionVersion) { return getMessageHandler(resolvedExtensionVersion).getImageResponseFromBody(responseBody); } }); } protected ArtifactMessageConverter getMessageHandler(String version) { return messageHandlerMap.get(version); } @Override public List<String> goSupportedVersions() { return SUPPORTED_VERSIONS; } public List<FetchArtifactEnvironmentVariable> fetchArtifact(String pluginId, ArtifactStore artifactStore, Configuration configuration, Map<String, Object> metadata, String agentWorkingDirectory) { return pluginRequestHelper.submitRequest(pluginId, REQUEST_FETCH_ARTIFACT, new DefaultPluginInteractionCallback<List<FetchArtifactEnvironmentVariable>>() { @Override public String requestBody(String resolvedExtensionVersion) { return getMessageHandler(resolvedExtensionVersion).fetchArtifactMessage(artifactStore, configuration, metadata, agentWorkingDirectory); } @Override public List<FetchArtifactEnvironmentVariable> onSuccess(String responseBody, Map<String, String> responseHeaders, String resolvedExtensionVersion) { return getMessageHandler(resolvedExtensionVersion).getFetchArtifactEnvironmentVariablesFromResponseBody(responseBody); } }); } }
package domain.util; import com.musicocracy.fpgk.domain.util.CircularQueue; import org.junit.Test; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; public class CircularQueueTests { @Test(expected = IllegalArgumentException.class) public void CircularQueue_constructor_zero_exception() { CircularQueue<String> cq = new CircularQueue<>(0); } @Test(expected = IllegalArgumentException.class) public void CircularQueue_constructor_negative_exception() { CircularQueue<String> cq = new CircularQueue<>(-1); } @Test public void CircularQueue_enqueue_sizeIncrements() { CircularQueue<String> cq = new CircularQueue<>(5); cq.enqueue("A"); assertEquals(1, cq.size()); } @Test public void CircularQueue_enqueue_queueSizeOne() { CircularQueue<String> cq = new CircularQueue<>(1); cq.enqueue("A"); assertEquals(1, cq.size()); } @Test public void CircularQueue_enqueue_whenFull_SizeSame() { CircularQueue<String> cq = new CircularQueue<>(5); for (int i = 0; i < 6; i++) { cq.enqueue("A"); } assertEquals(5, cq.size()); } @Test public void CircularQueue_enqueue_justBeforeFull_SizeSame() { CircularQueue<String> cq = new CircularQueue<>(5); for (int i = 0; i < 4; i++) { cq.enqueue("A"); } assertEquals(4, cq.size()); } @Test public void CircularQueue_enqueue_simple_dequeue() { CircularQueue<String> cq = new CircularQueue<>(5); cq.enqueue("A"); String returnedString = cq.dequeue(); assertEquals("A", returnedString); } @Test public void CircularQueue_enqueue_dequeue_queueSizeOne() { CircularQueue<String> cq = new CircularQueue<>(1); cq.enqueue("A"); assertEquals("A", cq.dequeue()); } @Test public void CircularQueue_enqueue_enqueue_dequeue_queueSizeOne() { CircularQueue<String> cq = new CircularQueue<>(1); cq.enqueue("A"); cq.enqueue("B"); assertEquals("B", cq.dequeue()); } @Test public void CircularQueue_enqueuePastMax_dequeueAll_sizeDoesNotChange() { String[] inputStrings = new String[]{"A", "B", "C", "D", "E", "F"}; int queueSize = 5; CircularQueue<String> cq = new CircularQueue<>(queueSize); for (String inputString : inputStrings) { cq.enqueue(inputString); } for (int i = 0; i < queueSize; i++) { cq.dequeue(); } assertEquals(5, cq.size()); } @Test public void CircularQueue_enqueuePastMax_dequeueAll() { String[] inputStrings = new String[]{"A", "B", "C", "D", "E", "F"}; String[] expectedStrings = new String[]{"B", "C", "D", "E", "F"}; int queueSize = 5; CircularQueue<String> cq = new CircularQueue<>(queueSize); for (String inputString : inputStrings) { cq.enqueue(inputString); } for (int i = 0; i < queueSize; i++) { assertEquals(expectedStrings[i], cq.dequeue()); } } @Test public void CircularQueue_enqueuePastMax_dequeuePastAll() { String[] inputStrings = new String[]{"A", "B", "C", "D", "E", "F"}; String[] expectedStrings = new String[]{"B", "C", "D", "E", "F", "B", "C"}; int queueSize = 5; CircularQueue<String> cq = new CircularQueue<>(queueSize); for (String inputString : inputStrings) { cq.enqueue(inputString); } for (int i = 0; i < 7; i++) { assertEquals(expectedStrings[i], cq.dequeue()); } } @Test public void CircularQueue_enqueuePartial_dequeueAll_enqueuePartial_checkDequeue() { String[] inputStrings = new String[]{"A", "B", "C"}; int queueSize = 5; CircularQueue<String> cq = new CircularQueue<>(queueSize); for (String inputString : inputStrings) { cq.enqueue(inputString); } for (String ignored : inputStrings) { cq.dequeue(); } cq.enqueue("D"); assertEquals("A", cq.dequeue()); } @Test public void CircularQueue_enqueuePastMax_dequeueAll_enqueuePartial_dequeAll_sizeIsMax() { int queueSize = 5; CircularQueue<String> cq = new CircularQueue<>(queueSize); for (int i = 0; i < 6; i++) { cq.enqueue("A"); } for (int i = 0; i < 5; i++) { cq.dequeue(); } cq.enqueue("B"); cq.enqueue("C"); cq.dequeue(); cq.dequeue(); assertEquals(queueSize, cq.size()); } @Test public void CircularQueue_enqueuePastMax_dequeueAll_enqueuePartial_dequeAll_correctData() { CircularQueue<String> cq = new CircularQueue<>(5); for (int i = 0; i < 6; i++) { cq.enqueue("A"); } for (int i = 0; i < 5; i++) { cq.dequeue(); } String[] inputStrings = new String[]{"B", "C", "D"}; String[] expectedStrings = new String[]{"A", "A", "B"}; for (String inputString : inputStrings) { cq.enqueue(inputString); } for (String expectedString : expectedStrings) { assertEquals(expectedString, cq.dequeue()); } } @Test(expected = IllegalStateException.class) public void CircularQueue_dequeueWhenEmpty_IllegalArguementException() { CircularQueue<String> cq = new CircularQueue<>(5); cq.dequeue(); } @Test public void CircularQueue_contains_empty_false() { CircularQueue<String> cq = new CircularQueue<>(5); assertFalse(cq.contains("A")); } @Test public void CircularQueue_contains_oneEnqueue_true() { CircularQueue<String> cq = new CircularQueue<>(5); cq.enqueue("A"); assertTrue(cq.contains("A")); } @Test public void CircularQueue_contains_enqueueWrapAroundOverwrite_false() { CircularQueue<String> cq = new CircularQueue<>(5); String[] inputStrings = new String[]{"A", "B", "C", "D", "E", "F"}; for (String inputString : inputStrings) { cq.enqueue(inputString); } assertFalse(cq.contains("A")); } @Test public void CircularQueue_containsAllButOverwritten_enqueueWrapAroundOverwrite_true() { CircularQueue<String> cq = new CircularQueue<>(5); String[] inputStrings = new String[]{"A", "B", "C", "D", "E", "F"}; for (String inputString : inputStrings) { cq.enqueue(inputString); } for (int i = 1; i < inputStrings.length; i++) { assertTrue(cq.contains(inputStrings[i])); } } }
package ca.campbell.networkcheckstatus; import android.app.Activity; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.NetworkInfo.State; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; /* * This app is intended to be an example of checking network connectivity. * It does not do any network access, though this is the normal next step. * * When using networking it is important to verify that you have an active * connected network connection before doing any network activity. * * Since it checks connectivity but does no network access it does not need * to be done in an AsyncTask. Any network access (data over the network) * must be done in a background thread. * * Permissions required in AndroidMainifest.xml: * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"> * </uses-permission> */ public class MainActivity extends Activity { private final static String TAG = "NETCHK"; private TextView tv2, tv3; private boolean networkIsUp = false; NetworkInfo networkInfo; ConnectivityManager connMgr; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv2 = (TextView) findViewById(R.id.tv2); tv3 = (TextView) findViewById(R.id.tv3); } public void checkStatusButton(View view) { checkStatus(); } /* * checkStatus() using an instance of ConnectivityManager via the * Connectivity Service which is an Android Service. Checks if network is * live, sets networkIsUp depending on network state. * * Connectivity Manager Class * * gives access to the state of network connectivity. Can be used to notify * apps when connectivity changes * * -monitor network connections (wi-fi, GPRS, UMTs, etc * * -send broadcast intents when connectivity changes * * -trys to failover to another net when connectivity lost * * -api for network state connectivity * * ConnectivityManager.getActiveNetworkInfo() * * returns details about the current active default network (NetworkInfo) * null if no default network ALWAYS check isConnected() before initiating * network traffic * * requires perm: android.permission.ACCESS_NETWORK_STATE * * NetworkInfo class * * gives access information about the status of a network interface * connection */ public void checkStatus() { connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); // getActiveNetworkInfo() each time as the network may swap as the // device moves if (connMgr != null ) { networkInfo = connMgr.getActiveNetworkInfo(); // ALWAYS check isConnected() before initiating network traffic if (networkInfo != null && networkInfo.isConnectedOrConnecting()) { tv2.setText("Network is connected or connecting"); networkIsUp = true; } else { tv2.setText("No network connectivity"); networkIsUp = false; } } else { tv2.setText("No network manager service"); networkIsUp = false; } } // checkStatus() public void checkEverything(View view) { String message = null; State state = null; checkStatus(); if (networkIsUp) { state = networkInfo.getState(); } if (state == null) { tv2.setText("Unable to get state info"); } else { switch (networkInfo.getState()) { case CONNECTED: message = "Connected"; break; case CONNECTING: message = "Connecting"; break; case DISCONNECTED: message = "Disconnected"; break; case DISCONNECTING: message = "Disconnecting"; break; case SUSPENDED: message = "Suspened"; break; case UNKNOWN: message = "Unknown"; break; default: message = "No valid State found"; break; } tv2.setText("State: "+message); } } // checkEverything() public void checkEverythingDetailed(View view) { String message = null; State state = null; checkStatus(); if (networkIsUp) { state = networkInfo.getState(); } if (state == null) { tv2.setText("Unable to get state info"); } else { switch (networkInfo.getDetailedState()) { case IDLE: message = "Idle"; break; case CONNECTED: message = "Connected"; break; case CONNECTING: message = "Connecting"; break; case SCANNING: message = "Scanning: searching for an access point"; break; case DISCONNECTED: message = "Disconnected"; break; case DISCONNECTING: message = "Connected"; break; case AUTHENTICATING: message = "Authenticating"; break; case BLOCKED: message = "Block"; break; case OBTAINING_IPADDR: message = "awaiting DHCP response"; break; case FAILED: message = "Failed"; break; case VERIFYING_POOR_LINK: message = "Link has poor connectivity"; break; default: message = "No valid State found"; break; } // Ex types WIFI, Bluetooth, Mobile... String typeName = networkInfo.getTypeName(); message = message + "\n Network Type " + typeName; if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { // subtype applies only to type mobile // see TelephonyManager class for enum of types String subtypeName = networkInfo.getSubtypeName(); message = message + "\n Network Subtype: " + subtypeName; } String extraInfo = networkInfo.getExtraInfo(); message = message + "\n Extra Info " + extraInfo; tv2.setText("Detailed State: \n " + message); } tv3.setText("Available \n " + getAvailablilty()); } // checkEverythingDetailed() private String getAvailablilty() { boolean wifiConn, mobileConn; NetworkInfo netInfo; // get an instance of ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); // check if wifi is available netInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (netInfo != null) { wifiConn = netInfo.isAvailable(); } else { wifiConn = false; } // check if mobile is available netInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (netInfo != null) { mobileConn = netInfo.isAvailable(); } else { mobileConn = false; } return "Wifi available: " + wifiConn + "\n Mobile available: " + mobileConn; } }
/* JCavernApplet.java Title: JCavern And Glen Author: Bill Walker Description: */ package jcavern.ui; import jcavern.*; import jcavern.thing.*; import java.awt.*; import java.applet.Applet; import java.awt.event.*; import java.util.*; /** * WorldView displays a view of a world centered around a player's location. * * @author Bill Walker * @version $Id$ */ public class WorldView extends JCavernView { /** * Radius of the world view, in Locations */ public static final int kWorldViewRadius = 4; /** * Preferred size of images */ public static final int kPreferredImageSize = 32; /** * Number of pixels between board pictures. */ private static final int kSpacing = 5 * kPreferredImageSize / 4; /** * The World being viewed by this View. */ private World mModel; /** * The list of events received from the model for this turn */ private Vector mEvents; /** * The location of the most interesting thing in the World, usually the player. */ private Location mLocationOfInterest; private Hashtable mBackgroundColors; /** * A Thread to animate the world view. */ private WorldViewUpdateThread mThread; /** * An animation thread class. */ private class WorldViewUpdateThread extends Thread { /** * Should the thread continue running. */ private boolean mKeepRunning = true; /** * Asks the thread to stop running. */ public void pleaseStop() { mKeepRunning = false; } /** * The main animation routine. */ public void run() { while (mKeepRunning) { try { sleep(5000); System.out.println("WorldView animation thread"); } catch (InterruptedException ie) { //System.out.println("Interrupted " + ie); } } } } /** * Creates a new WorldView for the given World. * * @param inApplet a non-null Applet used to retrieve images * @param inWorld a non-null World being viewed. * @param inLocationOfInterest a Location of interest, or <CODE>null</CODE> if none. */ public WorldView(JCavernApplet inApplet, World inWorld, Location inLocationOfInterest) { super(inApplet); if (inWorld == null) { throw new IllegalArgumentException("can't create WorldView with null World!"); } mModel = inWorld; mEvents = new Vector(); if (inLocationOfInterest != null) { mLocationOfInterest = mModel.enforceMinimumInset(inLocationOfInterest, kWorldViewRadius); } setBackground(Color.black); setForeground(JCavernApplet.CavernOrange); mBackgroundColors = new Hashtable(); for (int xIndex = 0; xIndex < mModel.getBounds().width; xIndex++) { for (int yIndex = 0; yIndex < mModel.getBounds().height; yIndex++) { Location aLocation = new Location(xIndex, yIndex); mBackgroundColors.put(aLocation, randomPaleOrange(xIndex, yIndex)); } } mThread = new WorldViewUpdateThread(); mThread.start(); } /** * Stops the animation thread from running. */ public void stopThread() { mThread.pleaseStop(); } /** * Retrieves a WorldEvent for a particular location. * These are events that happened at the location (especially the deaths of combatants). * * @param aLocation a non-null Location * @return a non-null WorldEvent */ private WorldEvent getEventForLocation(Location aLocation) { Enumeration theEvents = mEvents.elements(); while (theEvents.hasMoreElements()) { WorldEvent anEvent = (WorldEvent) theEvents.nextElement(); if (anEvent.getLocation() != null && anEvent.getLocation().equals(aLocation)) { return anEvent; } } return null; } /** * Receives update notification that the World being viewed has changed. * * @param a the object that sent the update * @param b information about the update. */ public void update(Observable a, Object b) { // System.out.println("WorldView.update(" + a + ", " + b + ")"); WorldEvent anEvent = (WorldEvent) b; switch (anEvent.getEventCode()) { case WorldEvent.TURN_START: mEvents = new Vector(); break; case WorldContentsEvent.PLACED: case WorldContentsEvent.MOVED: case WorldContentsEvent.REMOVED: case CombatEvent.ATTACKED_MISSED: case CombatEvent.ATTACKED_HIT: case CombatEvent.ATTACKED_KILLED: case WorldContentsEvent.REVEALED: case WorldEvent.RANGED_ATTACK: mEvents.addElement(anEvent); break; case WorldEvent.TURN_STOP: if (mEvents.size() > 0) { repaint(); } else { System.out.println("WorldView.update() received TURN_END, did not repaint"); } break; } } /** * Paints a board image centered around the given coordinates. * * @param inApplet a non-null Applet used to retrieve images * @param g a non-null Graphics object with which to paint * @param plotX x coordinate relative to the corner of the world view * @param plotY y coordinate relative to the corner of the world view * @param imageName name of the image * @exception JCavernInternalError could not paint */ public static void paintCenteredImage(JCavernApplet inApplet, Graphics g, int plotX, int plotY, String imageName) throws JCavernInternalError { Image theImage = inApplet.getBoardImage(imageName); paintCenteredImage(g, theImage, plotX, plotY); } /** * Paints a board image centered around the given coordinates. * * @param g a non-null Graphics object with which to paint * @param inImage a non-null Image * @param plotX x coordinate relative to the corner of the world view * @param plotY y coordinate relative to the corner of the world view * @exception JCavernInternalError could not paint */ public static void paintCenteredImage(Graphics g, Image inImage, int plotX, int plotY) throws JCavernInternalError { g.drawImage(inImage, plotX - WorldView.kPreferredImageSize / 2, plotY - WorldView.kPreferredImageSize / 2, WorldView.kPreferredImageSize, WorldView.kPreferredImageSize, null); } /** * Paints some text centered around the given coordinates. * * @param g a non-null Graphics object with which to paint * @param plotX x coordinate relative to the corner of the world view * @param plotY y coordinate relative to the corner of the world view * @param inLavel the non-null String to be painted * @exception JCavernInternalError could not paint */ public static void paintCenteredText(Graphics g, int plotX, int plotY, String inLabel) throws JCavernInternalError { int textWidth = g.getFontMetrics().stringWidth(inLabel); int textHeight = g.getFontMetrics().getHeight(); System.out.println("textWidth " + textWidth + " textHeight " + textHeight); g.drawString(inLabel, plotX - textWidth / 2, plotY - textHeight / 2); } /** * Paints a representation of a given Location at the given screen coordinates. * If the given Location is out of bounds, do nothing. * If the given Location is empty, see if there's an event for that location; if so, paint the event. * If the given Location contains a Thing, invoke that Thing's paint method * * @param g a non-null Graphics object * @param inLocation a non-null Location to paint * @param plotX horizontal screen coordinate relative to corner of this WorldView * @param plotY vertical screen coordinate relative to corner of this WorldView * @exception JCavernInternalError problem retrieving contents of this Location */ public void paintLocation(Graphics g, Location inLocation, int plotX, int plotY) throws JCavernInternalError { if (mModel.inBounds(inLocation)) { if (! mModel.isEmpty(inLocation)) { Thing theThing; try { theThing = mModel.getThing(inLocation); } catch(EmptyLocationException ele) { throw new JCavernInternalError("model says not empty, but throws EmptyLocationException"); } catch(IllegalLocationException ele) { throw new JCavernInternalError("model says not in bounds, but throws IllegalLocationException"); } theThing.getGraphicalThingView().paint(getApplet(), g, plotX, plotY); } else { WorldEvent anEvent = getEventForLocation(inLocation); paintEvent(g, anEvent, plotX, plotY); } } // end if mModel.isEmpty } /** * Paints a representation of a given Event at the given screen coordinates. * * @param g a non-null Graphics object * @param anEvent a non-null WorldEvent to paint * @param plotX horizontal screen coordinate relative to corner of this WorldView * @param plotY vertical screen coordinate relative to corner of this WorldView * @exception JCavernInternalError problem painting a board image */ public void paintEvent(Graphics g, WorldEvent anEvent, int plotX, int plotY) throws JCavernInternalError { if (anEvent != null) { switch (anEvent.getEventCode()) { case CombatEvent.ATTACKED_KILLED: paintCenteredImage(getApplet(), g, plotX, plotY, "splat"); break; case WorldContentsEvent.REMOVED: paintCenteredImage(getApplet(), g, plotX, plotY, "open-chest"); break; case CombatEvent.RANGED_ATTACK: //paintCenteredText(g, plotX, plotY, "*"); paintCenteredImage(getApplet(), g, plotX, plotY, "empty"); break; default: //paintCenteredImage(getApplet(), g, plotX, plotY, "empty"); break; } } //else //{ // paintCenteredImage(getApplet(), g, plotX, plotY, "empty"); //} } /** * Converts from World coordinates to WorldView coordinates. * Used in WorldView paint routines. * @see jcavern.World#getBounds() * * @param ordinal a World coordinate * @return a WorldView coordinate. */ private int scaled(double ordinal) { return (int) (kSpacing / 2 + (ordinal * kSpacing)); } /** * Draw a grid of dots on the World view to * help convey the idea of motion. * * @param g a non-null Graphics object * @param theLocation the location to focus on. */ private void paintBorder(Graphics g, Location theLocation) { int topBorder = scaled(-0.5); int bottomBorder = scaled(2 * kWorldViewRadius + 0.5); g.setColor(JCavernApplet.CavernOrangeDim); // draw axes at the perimeter of the display if (theLocation.getY() < 4) g.drawLine(topBorder, topBorder, bottomBorder, topBorder); if (theLocation.getY() > (mModel.getBounds().height - 5)) g.drawLine(topBorder, bottomBorder, bottomBorder, bottomBorder); if (theLocation.getX() < 4) g.drawLine(topBorder, topBorder, topBorder, bottomBorder); if (theLocation.getX() > (mModel.getBounds().width - 5)) g.drawLine(bottomBorder, topBorder, bottomBorder, bottomBorder); // draw tick marks on those axes. Major ticks every third unit. for (int yIndex = -kWorldViewRadius; yIndex <= kWorldViewRadius; yIndex++) { int worldY = yIndex + theLocation.getY(); int plotY = scaled(yIndex + kWorldViewRadius); boolean isYEdge = Math.abs(worldY - mModel.getBounds().height) <= kWorldViewRadius || worldY < kWorldViewRadius; for (int xIndex = -kWorldViewRadius; xIndex <= kWorldViewRadius; xIndex++) { int worldX = xIndex + theLocation.getX(); int plotX = scaled(xIndex + kWorldViewRadius); boolean isXEdge = Math.abs(worldX - mModel.getBounds().width) <= kWorldViewRadius || worldX < kWorldViewRadius; //if ((worldX % 3 == 0) && (worldY % 3 == 0)) //{ // g.fillRect(plotX - 3, plotY - 3, 6, 6); //} g.setColor((Color) mBackgroundColors.get(new Location(worldX, worldY))); g.fillRect(plotX - kSpacing / 2, plotY - kSpacing / 2, kSpacing, kSpacing); } } } private Color randomPaleOrange(int worldX, int worldY) { //double scale = (worldX % 5) / 16.0 + (worldY % 7) / 24.0; double scale = 0.1 + Math.random() * 0.1; double red = 1.0 * scale; double green = 0.2 * scale; double blue = 0 * scale; return new Color((float) red, (float) green, (float) blue); } /** * Returns the preferred radius for this view. */ public int getPreferredRadius() { return (4 + 2 * kWorldViewRadius) * kPreferredImageSize; } /** * Paints a view of the world, centered around the player's current location. * * @param g a non-null Graphics object with which to paint */ public void paint(Graphics g) { Player thePlayer; try { thePlayer = mModel.getPlayer(); mLocationOfInterest = mModel.enforceMinimumInset(mModel.getLocation(thePlayer), kWorldViewRadius); } catch (JCavernInternalError jcie) { System.out.println("Can't find player, using " + mLocationOfInterest); } paintBorder(g, mLocationOfInterest); try { for (int yIndex = -kWorldViewRadius; yIndex <= kWorldViewRadius; yIndex++) { int worldY = yIndex + mLocationOfInterest.getY(); int plotY = scaled(yIndex + kWorldViewRadius); for (int xIndex = -kWorldViewRadius; xIndex <= kWorldViewRadius; xIndex++) { int worldX = xIndex + mLocationOfInterest.getX(); int plotX = scaled(xIndex + kWorldViewRadius); Location aLocation = new Location(worldX, worldY); paintLocation(g, aLocation, plotX, plotY); } } } catch (JCavernInternalError jcie) { System.out.println("Can't paint world view, " + jcie); } } }
/* * Copyright(c) DBFlute TestCo.,TestLtd. All Rights Reserved. */ package org.docksidestage.derby.dbflute.cbean.cq.bs; import java.util.*; import org.dbflute.cbean.*; import org.dbflute.cbean.chelper.*; import org.dbflute.cbean.ckey.*; import org.dbflute.cbean.coption.*; import org.dbflute.cbean.cvalue.ConditionValue; import org.dbflute.cbean.ordering.*; import org.dbflute.cbean.scoping.*; import org.dbflute.cbean.sqlclause.SqlClause; import org.dbflute.dbmeta.DBMetaProvider; import org.docksidestage.derby.dbflute.allcommon.*; import org.docksidestage.derby.dbflute.cbean.*; import org.docksidestage.derby.dbflute.cbean.cq.*; /** * The abstract condition-query of REGION. * @author DBFlute(AutoGenerator) */ public abstract class AbstractBsRegionCQ extends AbstractConditionQuery { // =================================================================================== // Constructor // =========== public AbstractBsRegionCQ(ConditionQuery referrerQuery, SqlClause sqlClause, String aliasName, int nestLevel) { super(referrerQuery, sqlClause, aliasName, nestLevel); } // =================================================================================== // DB Meta // ======= @Override protected DBMetaProvider xgetDBMetaProvider() { return DBMetaInstanceHandler.getProvider(); } public String asTableDbName() { return "REGION"; } // =================================================================================== // Query // ===== /** * Equal(=). And NullIgnored, OnlyOnceRegistered. <br> * REGION_ID: {PK, NotNull, INTEGER(10), classification=Region} * @param regionId The value of regionId as equal. (basically NotNull: error as default, or no condition as option) */ protected void setRegionId_Equal(Integer regionId) { doSetRegionId_Equal(regionId); } /** * Equal(=). As Region. And NullIgnored, OnlyOnceRegistered. <br> * REGION_ID: {PK, NotNull, INTEGER(10), classification=Region} <br> * mainly region of member address * @param cdef The instance of classification definition (as ENUM type). (basically NotNull: error as default, or no condition as option) */ public void setRegionId_Equal_AsRegion(CDef.Region cdef) { doSetRegionId_Equal(cTNum(cdef != null ? cdef.code() : null, Integer.class)); } /** * Equal(=). As America (1). And NullIgnored, OnlyOnceRegistered. <br> * AMERICA: AMERICA */ public void setRegionId_Equal_America() { setRegionId_Equal_AsRegion(CDef.Region.America); } /** * Equal(=). As Canada (2). And NullIgnored, OnlyOnceRegistered. <br> * CANADA: CANADA */ public void setRegionId_Equal_Canada() { setRegionId_Equal_AsRegion(CDef.Region.Canada); } /** * Equal(=). As China (3). And NullIgnored, OnlyOnceRegistered. <br> * CHINA: CHINA */ public void setRegionId_Equal_China() { setRegionId_Equal_AsRegion(CDef.Region.China); } /** * Equal(=). As Chiba (4). And NullIgnored, OnlyOnceRegistered. <br> * CHIBA: CHIBA */ public void setRegionId_Equal_Chiba() { setRegionId_Equal_AsRegion(CDef.Region.Chiba); } protected void doSetRegionId_Equal(Integer regionId) { regRegionId(CK_EQ, regionId); } /** * NotEqual(&lt;&gt;). And NullIgnored, OnlyOnceRegistered. <br> * REGION_ID: {PK, NotNull, INTEGER(10), classification=Region} * @param regionId The value of regionId as notEqual. (basically NotNull: error as default, or no condition as option) */ protected void setRegionId_NotEqual(Integer regionId) { doSetRegionId_NotEqual(regionId); } /** * NotEqual(&lt;&gt;). As Region. And NullIgnored, OnlyOnceRegistered. <br> * REGION_ID: {PK, NotNull, INTEGER(10), classification=Region} <br> * mainly region of member address * @param cdef The instance of classification definition (as ENUM type). (basically NotNull: error as default, or no condition as option) */ public void setRegionId_NotEqual_AsRegion(CDef.Region cdef) { doSetRegionId_NotEqual(cTNum(cdef != null ? cdef.code() : null, Integer.class)); } /** * NotEqual(&lt;&gt;). As America (1). And NullIgnored, OnlyOnceRegistered. <br> * AMERICA: AMERICA */ public void setRegionId_NotEqual_America() { setRegionId_NotEqual_AsRegion(CDef.Region.America); } /** * NotEqual(&lt;&gt;). As Canada (2). And NullIgnored, OnlyOnceRegistered. <br> * CANADA: CANADA */ public void setRegionId_NotEqual_Canada() { setRegionId_NotEqual_AsRegion(CDef.Region.Canada); } /** * NotEqual(&lt;&gt;). As China (3). And NullIgnored, OnlyOnceRegistered. <br> * CHINA: CHINA */ public void setRegionId_NotEqual_China() { setRegionId_NotEqual_AsRegion(CDef.Region.China); } /** * NotEqual(&lt;&gt;). As Chiba (4). And NullIgnored, OnlyOnceRegistered. <br> * CHIBA: CHIBA */ public void setRegionId_NotEqual_Chiba() { setRegionId_NotEqual_AsRegion(CDef.Region.Chiba); } protected void doSetRegionId_NotEqual(Integer regionId) { regRegionId(CK_NES, regionId); } /** * InScope {in (1, 2)}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br> * REGION_ID: {PK, NotNull, INTEGER(10), classification=Region} * @param regionIdList The collection of regionId as inScope. (basically NotNull, NotEmpty: error as default, or no condition as option) */ protected void setRegionId_InScope(Collection<Integer> regionIdList) { doSetRegionId_InScope(regionIdList); } /** * InScope {in (1, 2)}. As Region. And NullIgnored, NullElementIgnored, SeveralRegistered. <br> * REGION_ID: {PK, NotNull, INTEGER(10), classification=Region} <br> * mainly region of member address * @param cdefList The list of classification definition (as ENUM type). (basically NotNull, NotEmpty: error as default, or no condition as option) */ public void setRegionId_InScope_AsRegion(Collection<CDef.Region> cdefList) { doSetRegionId_InScope(cTNumL(cdefList, Integer.class)); } protected void doSetRegionId_InScope(Collection<Integer> regionIdList) { regINS(CK_INS, cTL(regionIdList), xgetCValueRegionId(), "REGION_ID"); } /** * NotInScope {not in (1, 2)}. And NullIgnored, NullElementIgnored, SeveralRegistered. <br> * REGION_ID: {PK, NotNull, INTEGER(10), classification=Region} * @param regionIdList The collection of regionId as notInScope. (basically NotNull, NotEmpty: error as default, or no condition as option) */ protected void setRegionId_NotInScope(Collection<Integer> regionIdList) { doSetRegionId_NotInScope(regionIdList); } /** * NotInScope {not in (1, 2)}. As Region. And NullIgnored, NullElementIgnored, SeveralRegistered. <br> * REGION_ID: {PK, NotNull, INTEGER(10), classification=Region} <br> * mainly region of member address * @param cdefList The list of classification definition (as ENUM type). (basically NotNull, NotEmpty: error as default, or no condition as option) */ public void setRegionId_NotInScope_AsRegion(Collection<CDef.Region> cdefList) { doSetRegionId_NotInScope(cTNumL(cdefList, Integer.class)); } protected void doSetRegionId_NotInScope(Collection<Integer> regionIdList) { regINS(CK_NINS, cTL(regionIdList), xgetCValueRegionId(), "REGION_ID"); } /** * Set up ExistsReferrer (correlated sub-query). <br> * {exists (select REGION_ID from MEMBER_ADDRESS where ...)} <br> * MEMBER_ADDRESS by REGION_ID, named 'memberAddressAsOne'. * <pre> * cb.query().<span style="color: #CC4747">existsMemberAddress</span>(addressCB <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * addressCB.query().set... * }); * </pre> * @param subCBLambda The callback for sub-query of MemberAddressList for 'exists'. (NotNull) */ public void existsMemberAddress(SubQuery<MemberAddressCB> subCBLambda) { assertObjectNotNull("subCBLambda", subCBLambda); MemberAddressCB cb = new MemberAddressCB(); cb.xsetupForExistsReferrer(this); lockCall(() -> subCBLambda.query(cb)); String pp = keepRegionId_ExistsReferrer_MemberAddressList(cb.query()); registerExistsReferrer(cb.query(), "REGION_ID", "REGION_ID", pp, "memberAddressList"); } public abstract String keepRegionId_ExistsReferrer_MemberAddressList(MemberAddressCQ sq); /** * Set up NotExistsReferrer (correlated sub-query). <br> * {not exists (select REGION_ID from MEMBER_ADDRESS where ...)} <br> * MEMBER_ADDRESS by REGION_ID, named 'memberAddressAsOne'. * <pre> * cb.query().<span style="color: #CC4747">notExistsMemberAddress</span>(addressCB <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * addressCB.query().set... * }); * </pre> * @param subCBLambda The callback for sub-query of RegionId_NotExistsReferrer_MemberAddressList for 'not exists'. (NotNull) */ public void notExistsMemberAddress(SubQuery<MemberAddressCB> subCBLambda) { assertObjectNotNull("subCBLambda", subCBLambda); MemberAddressCB cb = new MemberAddressCB(); cb.xsetupForExistsReferrer(this); lockCall(() -> subCBLambda.query(cb)); String pp = keepRegionId_NotExistsReferrer_MemberAddressList(cb.query()); registerNotExistsReferrer(cb.query(), "REGION_ID", "REGION_ID", pp, "memberAddressList"); } public abstract String keepRegionId_NotExistsReferrer_MemberAddressList(MemberAddressCQ sq); public void xsderiveMemberAddressList(String fn, SubQuery<MemberAddressCB> sq, String al, DerivedReferrerOption op) { assertObjectNotNull("subQuery", sq); MemberAddressCB cb = new MemberAddressCB(); cb.xsetupForDerivedReferrer(this); lockCall(() -> sq.query(cb)); String pp = keepRegionId_SpecifyDerivedReferrer_MemberAddressList(cb.query()); registerSpecifyDerivedReferrer(fn, cb.query(), "REGION_ID", "REGION_ID", pp, "memberAddressList", al, op); } public abstract String keepRegionId_SpecifyDerivedReferrer_MemberAddressList(MemberAddressCQ sq); /** * Prepare for (Query)DerivedReferrer (correlated sub-query). <br> * {FOO &lt;= (select max(BAR) from MEMBER_ADDRESS where ...)} <br> * MEMBER_ADDRESS by REGION_ID, named 'memberAddressAsOne'. * <pre> * cb.query().<span style="color: #CC4747">derivedMemberAddress()</span>.<span style="color: #CC4747">max</span>(addressCB <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * addressCB.specify().<span style="color: #CC4747">columnFoo...</span> <span style="color: #3F7E5E">// derived column by function</span> * addressCB.query().setBar... <span style="color: #3F7E5E">// referrer condition</span> * }).<span style="color: #CC4747">greaterEqual</span>(123); <span style="color: #3F7E5E">// condition to derived column</span> * </pre> * @return The object to set up a function for referrer table. (NotNull) */ public HpQDRFunction<MemberAddressCB> derivedMemberAddress() { return xcreateQDRFunctionMemberAddressList(); } protected HpQDRFunction<MemberAddressCB> xcreateQDRFunctionMemberAddressList() { return xcQDRFunc((fn, sq, rd, vl, op) -> xqderiveMemberAddressList(fn, sq, rd, vl, op)); } public void xqderiveMemberAddressList(String fn, SubQuery<MemberAddressCB> sq, String rd, Object vl, DerivedReferrerOption op) { assertObjectNotNull("subQuery", sq); MemberAddressCB cb = new MemberAddressCB(); cb.xsetupForDerivedReferrer(this); lockCall(() -> sq.query(cb)); String sqpp = keepRegionId_QueryDerivedReferrer_MemberAddressList(cb.query()); String prpp = keepRegionId_QueryDerivedReferrer_MemberAddressListParameter(vl); registerQueryDerivedReferrer(fn, cb.query(), "REGION_ID", "REGION_ID", sqpp, "memberAddressList", rd, vl, prpp, op); } public abstract String keepRegionId_QueryDerivedReferrer_MemberAddressList(MemberAddressCQ sq); public abstract String keepRegionId_QueryDerivedReferrer_MemberAddressListParameter(Object vl); /** * IsNull {is null}. And OnlyOnceRegistered. <br> * REGION_ID: {PK, NotNull, INTEGER(10), classification=Region} */ public void setRegionId_IsNull() { regRegionId(CK_ISN, DOBJ); } /** * IsNotNull {is not null}. And OnlyOnceRegistered. <br> * REGION_ID: {PK, NotNull, INTEGER(10), classification=Region} */ public void setRegionId_IsNotNull() { regRegionId(CK_ISNN, DOBJ); } protected void regRegionId(ConditionKey ky, Object vl) { regQ(ky, vl, xgetCValueRegionId(), "REGION_ID"); } protected abstract ConditionValue xgetCValueRegionId(); /** * Equal(=). And NullOrEmptyIgnored, OnlyOnceRegistered. <br> * REGION_NAME: {NotNull, VARCHAR(50)} * @param regionName The value of regionName as equal. (basically NotNull, NotEmpty: error as default, or no condition as option) */ public void setRegionName_Equal(String regionName) { doSetRegionName_Equal(fRES(regionName)); } protected void doSetRegionName_Equal(String regionName) { regRegionName(CK_EQ, regionName); } /** * NotEqual(&lt;&gt;). And NullOrEmptyIgnored, OnlyOnceRegistered. <br> * REGION_NAME: {NotNull, VARCHAR(50)} * @param regionName The value of regionName as notEqual. (basically NotNull, NotEmpty: error as default, or no condition as option) */ public void setRegionName_NotEqual(String regionName) { doSetRegionName_NotEqual(fRES(regionName)); } protected void doSetRegionName_NotEqual(String regionName) { regRegionName(CK_NES, regionName); } /** * InScope {in ('a', 'b')}. And NullOrEmptyIgnored, NullOrEmptyElementIgnored, SeveralRegistered. <br> * REGION_NAME: {NotNull, VARCHAR(50)} * @param regionNameList The collection of regionName as inScope. (basically NotNull, NotEmpty: error as default, or no condition as option) */ public void setRegionName_InScope(Collection<String> regionNameList) { doSetRegionName_InScope(regionNameList); } protected void doSetRegionName_InScope(Collection<String> regionNameList) { regINS(CK_INS, cTL(regionNameList), xgetCValueRegionName(), "REGION_NAME"); } /** * NotInScope {not in ('a', 'b')}. And NullOrEmptyIgnored, NullOrEmptyElementIgnored, SeveralRegistered. <br> * REGION_NAME: {NotNull, VARCHAR(50)} * @param regionNameList The collection of regionName as notInScope. (basically NotNull, NotEmpty: error as default, or no condition as option) */ public void setRegionName_NotInScope(Collection<String> regionNameList) { doSetRegionName_NotInScope(regionNameList); } protected void doSetRegionName_NotInScope(Collection<String> regionNameList) { regINS(CK_NINS, cTL(regionNameList), xgetCValueRegionName(), "REGION_NAME"); } /** * LikeSearch with various options. (versatile) {like '%xxx%' escape ...}. And NullOrEmptyIgnored, SeveralRegistered. <br> * REGION_NAME: {NotNull, VARCHAR(50)} <br> * <pre>e.g. setRegionName_LikeSearch("xxx", op <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> op.<span style="color: #CC4747">likeContain()</span>);</pre> * @param regionName The value of regionName as likeSearch. (basically NotNull, NotEmpty: error as default, or no condition as option) * @param opLambda The callback for option of like-search. (NotNull) */ public void setRegionName_LikeSearch(String regionName, ConditionOptionCall<LikeSearchOption> opLambda) { setRegionName_LikeSearch(regionName, xcLSOP(opLambda)); } /** * LikeSearch with various options. (versatile) {like '%xxx%' escape ...}. And NullOrEmptyIgnored, SeveralRegistered. <br> * REGION_NAME: {NotNull, VARCHAR(50)} <br> * <pre>e.g. setRegionName_LikeSearch("xxx", new <span style="color: #CC4747">LikeSearchOption</span>().likeContain());</pre> * @param regionName The value of regionName as likeSearch. (basically NotNull, NotEmpty: error as default, or no condition as option) * @param likeSearchOption The option of like-search. (NotNull) */ protected void setRegionName_LikeSearch(String regionName, LikeSearchOption likeSearchOption) { regLSQ(CK_LS, fRES(regionName), xgetCValueRegionName(), "REGION_NAME", likeSearchOption); } /** * NotLikeSearch with various options. (versatile) {not like 'xxx%' escape ...} <br> * And NullOrEmptyIgnored, SeveralRegistered. <br> * REGION_NAME: {NotNull, VARCHAR(50)} * @param regionName The value of regionName as notLikeSearch. (basically NotNull, NotEmpty: error as default, or no condition as option) * @param opLambda The callback for option of like-search. (NotNull) */ public void setRegionName_NotLikeSearch(String regionName, ConditionOptionCall<LikeSearchOption> opLambda) { setRegionName_NotLikeSearch(regionName, xcLSOP(opLambda)); } /** * NotLikeSearch with various options. (versatile) {not like 'xxx%' escape ...} <br> * And NullOrEmptyIgnored, SeveralRegistered. <br> * REGION_NAME: {NotNull, VARCHAR(50)} * @param regionName The value of regionName as notLikeSearch. (basically NotNull, NotEmpty: error as default, or no condition as option) * @param likeSearchOption The option of not-like-search. (NotNull) */ protected void setRegionName_NotLikeSearch(String regionName, LikeSearchOption likeSearchOption) { regLSQ(CK_NLS, fRES(regionName), xgetCValueRegionName(), "REGION_NAME", likeSearchOption); } protected void regRegionName(ConditionKey ky, Object vl) { regQ(ky, vl, xgetCValueRegionName(), "REGION_NAME"); } protected abstract ConditionValue xgetCValueRegionName(); // =================================================================================== // ScalarCondition // =============== /** * Prepare ScalarCondition as equal. <br> * {where FOO = (select max(BAR) from ...)} * <pre> * cb.query().scalar_Equal().<span style="color: #CC4747">avg</span>(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">purchaseCB</span>.specify().<span style="color: #CC4747">columnPurchasePrice</span>(); <span style="color: #3F7E5E">// *Point!</span> * <span style="color: #553000">purchaseCB</span>.query().setPaymentCompleteFlg_Equal_True(); * }); * </pre> * @return The object to set up a function. (NotNull) */ public HpSLCFunction<RegionCB> scalar_Equal() { return xcreateSLCFunction(CK_EQ, RegionCB.class); } /** * Prepare ScalarCondition as equal. <br> * {where FOO &lt;&gt; (select max(BAR) from ...)} * <pre> * cb.query().scalar_Equal().<span style="color: #CC4747">avg</span>(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">purchaseCB</span>.specify().<span style="color: #CC4747">columnPurchasePrice</span>(); <span style="color: #3F7E5E">// *Point!</span> * <span style="color: #553000">purchaseCB</span>.query().setPaymentCompleteFlg_Equal_True(); * }); * </pre> * @return The object to set up a function. (NotNull) */ public HpSLCFunction<RegionCB> scalar_NotEqual() { return xcreateSLCFunction(CK_NES, RegionCB.class); } /** * Prepare ScalarCondition as greaterThan. <br> * {where FOO &gt; (select max(BAR) from ...)} * <pre> * cb.query().scalar_Equal().<span style="color: #CC4747">avg</span>(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">purchaseCB</span>.specify().<span style="color: #CC4747">columnPurchasePrice</span>(); <span style="color: #3F7E5E">// *Point!</span> * <span style="color: #553000">purchaseCB</span>.query().setPaymentCompleteFlg_Equal_True(); * }); * </pre> * @return The object to set up a function. (NotNull) */ public HpSLCFunction<RegionCB> scalar_GreaterThan() { return xcreateSLCFunction(CK_GT, RegionCB.class); } /** * Prepare ScalarCondition as lessThan. <br> * {where FOO &lt; (select max(BAR) from ...)} * <pre> * cb.query().scalar_Equal().<span style="color: #CC4747">avg</span>(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">purchaseCB</span>.specify().<span style="color: #CC4747">columnPurchasePrice</span>(); <span style="color: #3F7E5E">// *Point!</span> * <span style="color: #553000">purchaseCB</span>.query().setPaymentCompleteFlg_Equal_True(); * }); * </pre> * @return The object to set up a function. (NotNull) */ public HpSLCFunction<RegionCB> scalar_LessThan() { return xcreateSLCFunction(CK_LT, RegionCB.class); } /** * Prepare ScalarCondition as greaterEqual. <br> * {where FOO &gt;= (select max(BAR) from ...)} * <pre> * cb.query().scalar_Equal().<span style="color: #CC4747">avg</span>(<span style="color: #553000">purchaseCB</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">purchaseCB</span>.specify().<span style="color: #CC4747">columnPurchasePrice</span>(); <span style="color: #3F7E5E">// *Point!</span> * <span style="color: #553000">purchaseCB</span>.query().setPaymentCompleteFlg_Equal_True(); * }); * </pre> * @return The object to set up a function. (NotNull) */ public HpSLCFunction<RegionCB> scalar_GreaterEqual() { return xcreateSLCFunction(CK_GE, RegionCB.class); } /** * Prepare ScalarCondition as lessEqual. <br> * {where FOO &lt;= (select max(BAR) from ...)} * <pre> * cb.query().<span style="color: #CC4747">scalar_LessEqual()</span>.max(new SubQuery&lt;RegionCB&gt;() { * public void query(RegionCB subCB) { * subCB.specify().setFoo... <span style="color: #3F7E5E">// derived column for function</span> * subCB.query().setBar... * } * }); * </pre> * @return The object to set up a function. (NotNull) */ public HpSLCFunction<RegionCB> scalar_LessEqual() { return xcreateSLCFunction(CK_LE, RegionCB.class); } @SuppressWarnings("unchecked") protected <CB extends ConditionBean> void xscalarCondition(String fn, SubQuery<CB> sq, String rd, HpSLCCustomized<CB> cs, ScalarConditionOption op) { assertObjectNotNull("subQuery", sq); RegionCB cb = xcreateScalarConditionCB(); sq.query((CB)cb); String pp = keepScalarCondition(cb.query()); // for saving query-value cs.setPartitionByCBean((CB)xcreateScalarConditionPartitionByCB()); // for using partition-by registerScalarCondition(fn, cb.query(), pp, rd, cs, op); } public abstract String keepScalarCondition(RegionCQ sq); protected RegionCB xcreateScalarConditionCB() { RegionCB cb = newMyCB(); cb.xsetupForScalarCondition(this); return cb; } protected RegionCB xcreateScalarConditionPartitionByCB() { RegionCB cb = newMyCB(); cb.xsetupForScalarConditionPartitionBy(this); return cb; } // =================================================================================== // MyselfDerived // ============= public void xsmyselfDerive(String fn, SubQuery<RegionCB> sq, String al, DerivedReferrerOption op) { assertObjectNotNull("subQuery", sq); RegionCB cb = new RegionCB(); cb.xsetupForDerivedReferrer(this); lockCall(() -> sq.query(cb)); String pp = keepSpecifyMyselfDerived(cb.query()); String pk = "REGION_ID"; registerSpecifyMyselfDerived(fn, cb.query(), pk, pk, pp, "myselfDerived", al, op); } public abstract String keepSpecifyMyselfDerived(RegionCQ sq); /** * Prepare for (Query)MyselfDerived (correlated sub-query). * @return The object to set up a function for myself table. (NotNull) */ public HpQDRFunction<RegionCB> myselfDerived() { return xcreateQDRFunctionMyselfDerived(RegionCB.class); } @SuppressWarnings("unchecked") protected <CB extends ConditionBean> void xqderiveMyselfDerived(String fn, SubQuery<CB> sq, String rd, Object vl, DerivedReferrerOption op) { assertObjectNotNull("subQuery", sq); RegionCB cb = new RegionCB(); cb.xsetupForDerivedReferrer(this); sq.query((CB)cb); String pk = "REGION_ID"; String sqpp = keepQueryMyselfDerived(cb.query()); // for saving query-value. String prpp = keepQueryMyselfDerivedParameter(vl); registerQueryMyselfDerived(fn, cb.query(), pk, pk, sqpp, "myselfDerived", rd, vl, prpp, op); } public abstract String keepQueryMyselfDerived(RegionCQ sq); public abstract String keepQueryMyselfDerivedParameter(Object vl); // =================================================================================== // MyselfExists // ============ /** * Prepare for MyselfExists (correlated sub-query). * @param subCBLambda The implementation of sub-query. (NotNull) */ public void myselfExists(SubQuery<RegionCB> subCBLambda) { assertObjectNotNull("subCBLambda", subCBLambda); RegionCB cb = new RegionCB(); cb.xsetupForMyselfExists(this); lockCall(() -> subCBLambda.query(cb)); String pp = keepMyselfExists(cb.query()); registerMyselfExists(cb.query(), pp); } public abstract String keepMyselfExists(RegionCQ sq); // =================================================================================== // Manual Order // ============ /** * Order along manual ordering information. * <pre> * cb.query().addOrderBy_Birthdate_Asc().<span style="color: #CC4747">withManualOrder</span>(<span style="color: #553000">op</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">op</span>.<span style="color: #CC4747">when_GreaterEqual</span>(priorityDate); <span style="color: #3F7E5E">// e.g. 2000/01/01</span> * }); * <span style="color: #3F7E5E">// order by </span> * <span style="color: #3F7E5E">// case</span> * <span style="color: #3F7E5E">// when BIRTHDATE &gt;= '2000/01/01' then 0</span> * <span style="color: #3F7E5E">// else 1</span> * <span style="color: #3F7E5E">// end asc, ...</span> * * cb.query().addOrderBy_MemberStatusCode_Asc().<span style="color: #CC4747">withManualOrder</span>(<span style="color: #553000">op</span> <span style="color: #90226C; font-weight: bold"><span style="font-size: 120%">-</span>&gt;</span> { * <span style="color: #553000">op</span>.<span style="color: #CC4747">when_Equal</span>(CDef.MemberStatus.Withdrawal); * <span style="color: #553000">op</span>.<span style="color: #CC4747">when_Equal</span>(CDef.MemberStatus.Formalized); * <span style="color: #553000">op</span>.<span style="color: #CC4747">when_Equal</span>(CDef.MemberStatus.Provisional); * }); * <span style="color: #3F7E5E">// order by </span> * <span style="color: #3F7E5E">// case</span> * <span style="color: #3F7E5E">// when MEMBER_STATUS_CODE = 'WDL' then 0</span> * <span style="color: #3F7E5E">// when MEMBER_STATUS_CODE = 'FML' then 1</span> * <span style="color: #3F7E5E">// when MEMBER_STATUS_CODE = 'PRV' then 2</span> * <span style="color: #3F7E5E">// else 3</span> * <span style="color: #3F7E5E">// end asc, ...</span> * </pre> * <p>This function with Union is unsupported!</p> * <p>The order values are bound (treated as bind parameter).</p> * @param opLambda The callback for option of manual-order containing order values. (NotNull) */ public void withManualOrder(ManualOrderOptionCall opLambda) { // is user public! xdoWithManualOrder(cMOO(opLambda)); } // =================================================================================== // Small Adjustment // ================ // =================================================================================== // Very Internal // ============= protected RegionCB newMyCB() { return new RegionCB(); } // very internal (for suppressing warn about 'Not Use Import') protected String xabUDT() { return Date.class.getName(); } protected String xabCQ() { return RegionCQ.class.getName(); } protected String xabLSO() { return LikeSearchOption.class.getName(); } protected String xabSLCS() { return HpSLCSetupper.class.getName(); } protected String xabSCP() { return SubQuery.class.getName(); } }